mprintf.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. */
  24. #include "curl_setup.h"
  25. #include "dynbuf.h"
  26. #include "curl_printf.h"
  27. #include "curl_memory.h"
  28. /* The last #include file should be: */
  29. #include "memdebug.h"
  30. /*
  31. * If SIZEOF_SIZE_T has not been defined, default to the size of long.
  32. */
  33. #ifdef HAVE_LONGLONG
  34. # define LONG_LONG_TYPE long long
  35. # define HAVE_LONG_LONG_TYPE
  36. #else
  37. # if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
  38. # define LONG_LONG_TYPE __int64
  39. # define HAVE_LONG_LONG_TYPE
  40. # else
  41. # undef LONG_LONG_TYPE
  42. # undef HAVE_LONG_LONG_TYPE
  43. # endif
  44. #endif
  45. /*
  46. * Max integer data types that mprintf.c is capable
  47. */
  48. #ifdef HAVE_LONG_LONG_TYPE
  49. # define mp_intmax_t LONG_LONG_TYPE
  50. # define mp_uintmax_t unsigned LONG_LONG_TYPE
  51. #else
  52. # define mp_intmax_t long
  53. # define mp_uintmax_t unsigned long
  54. #endif
  55. #define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should
  56. fit negative DBL_MAX (317 letters) */
  57. #define MAX_PARAMETERS 128 /* number of input arguments */
  58. #define MAX_SEGMENTS 128 /* number of output segments */
  59. #ifdef __AMIGA__
  60. # undef FORMAT_INT
  61. #endif
  62. /* Lower-case digits. */
  63. static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
  64. /* Upper-case digits. */
  65. static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  66. #define OUTCHAR(x) \
  67. do { \
  68. if(!stream((unsigned char)x, userp)) \
  69. done++; \
  70. else \
  71. return done; /* return on failure */ \
  72. } while(0)
  73. /* Data type to read from the arglist */
  74. typedef enum {
  75. FORMAT_STRING,
  76. FORMAT_PTR,
  77. FORMAT_INTPTR,
  78. FORMAT_INT,
  79. FORMAT_LONG,
  80. FORMAT_LONGLONG,
  81. FORMAT_INTU,
  82. FORMAT_LONGU,
  83. FORMAT_LONGLONGU,
  84. FORMAT_DOUBLE,
  85. FORMAT_LONGDOUBLE,
  86. FORMAT_WIDTH,
  87. FORMAT_PRECISION
  88. } FormatType;
  89. /* conversion and display flags */
  90. enum {
  91. FLAGS_SPACE = 1 << 0,
  92. FLAGS_SHOWSIGN = 1 << 1,
  93. FLAGS_LEFT = 1 << 2,
  94. FLAGS_ALT = 1 << 3,
  95. FLAGS_SHORT = 1 << 4,
  96. FLAGS_LONG = 1 << 5,
  97. FLAGS_LONGLONG = 1 << 6,
  98. FLAGS_LONGDOUBLE = 1 << 7,
  99. FLAGS_PAD_NIL = 1 << 8,
  100. FLAGS_UNSIGNED = 1 << 9,
  101. FLAGS_OCTAL = 1 << 10,
  102. FLAGS_HEX = 1 << 11,
  103. FLAGS_UPPER = 1 << 12,
  104. FLAGS_WIDTH = 1 << 13, /* '*' or '*<num>$' used */
  105. FLAGS_WIDTHPARAM = 1 << 14, /* width PARAMETER was specified */
  106. FLAGS_PREC = 1 << 15, /* precision was specified */
  107. FLAGS_PRECPARAM = 1 << 16, /* precision PARAMETER was specified */
  108. FLAGS_CHAR = 1 << 17, /* %c story */
  109. FLAGS_FLOATE = 1 << 18, /* %e or %E */
  110. FLAGS_FLOATG = 1 << 19, /* %g or %G */
  111. FLAGS_SUBSTR = 1 << 20 /* no input, only substring */
  112. };
  113. enum {
  114. DOLLAR_UNKNOWN,
  115. DOLLAR_NOPE,
  116. DOLLAR_USE
  117. };
  118. /*
  119. * Describes an input va_arg type and hold its value.
  120. */
  121. struct va_input {
  122. FormatType type; /* FormatType */
  123. union {
  124. char *str;
  125. void *ptr;
  126. mp_intmax_t nums; /* signed */
  127. mp_uintmax_t numu; /* unsigned */
  128. double dnum;
  129. } val;
  130. };
  131. /*
  132. * Describes an output segment.
  133. */
  134. struct outsegment {
  135. int width; /* width OR width parameter number */
  136. int precision; /* precision OR precision parameter number */
  137. unsigned int flags;
  138. unsigned int input; /* input argument array index */
  139. char *start; /* format string start to output */
  140. size_t outlen; /* number of bytes from the format string to output */
  141. };
  142. struct nsprintf {
  143. char *buffer;
  144. size_t length;
  145. size_t max;
  146. };
  147. struct asprintf {
  148. struct dynbuf *b;
  149. char merr;
  150. };
  151. /* the provided input number is 1-based but this returns the number 0-based.
  152. returns -1 if no valid number was provided.
  153. */
  154. static int dollarstring(char *input, char **end)
  155. {
  156. if(ISDIGIT(*input)) {
  157. int number = 0;
  158. do {
  159. if(number < MAX_PARAMETERS) {
  160. number *= 10;
  161. number += *input - '0';
  162. }
  163. input++;
  164. } while(ISDIGIT(*input));
  165. if(number && (number <= MAX_PARAMETERS) && ('$' == *input)) {
  166. *end = ++input;
  167. return number - 1;
  168. }
  169. }
  170. return -1;
  171. }
  172. /*
  173. * Parse the format string.
  174. *
  175. * Create two arrays. One describes the inputs, one describes the outputs.
  176. *
  177. * Returns zero on success.
  178. */
  179. #define PFMT_OK 0
  180. #define PFMT_DOLLAR 1 /* bad dollar for main param */
  181. #define PFMT_DOLLARWIDTH 2 /* bad dollar use for width */
  182. #define PFMT_DOLLARPREC 3 /* bad dollar use for precision */
  183. #define PFMT_MANYARGS 4 /* too many input arguments used */
  184. #define PFMT_PREC 5 /* precision overflow */
  185. #define PFMT_PRECMIX 6 /* bad mix of precision specifiers */
  186. #define PFMT_WIDTH 7 /* width overflow */
  187. #define PFMT_INPUTGAP 8 /* gap in arguments */
  188. #define PFMT_WIDTHARG 9 /* attempted to use same arg twice, for width */
  189. #define PFMT_PRECARG 10 /* attempted to use same arg twice, for prec */
  190. #define PFMT_MANYSEGS 11 /* maxed out output segments */
  191. static int parsefmt(const char *format,
  192. struct outsegment *out,
  193. struct va_input *in,
  194. int *opieces,
  195. int *ipieces, va_list arglist)
  196. {
  197. char *fmt = (char *)format;
  198. int param_num = 0;
  199. int param;
  200. int width;
  201. int precision;
  202. unsigned int flags;
  203. FormatType type;
  204. int max_param = -1;
  205. int i;
  206. int ocount = 0;
  207. unsigned char usedinput[MAX_PARAMETERS/8];
  208. size_t outlen = 0;
  209. struct outsegment *optr;
  210. int use_dollar = DOLLAR_UNKNOWN;
  211. char *start = fmt;
  212. /* clear, set a bit for each used input */
  213. memset(usedinput, 0, sizeof(usedinput));
  214. while(*fmt) {
  215. if(*fmt == '%') {
  216. struct va_input *iptr;
  217. bool loopit = TRUE;
  218. fmt++;
  219. outlen = (size_t)(fmt - start - 1);
  220. if(*fmt == '%') {
  221. /* this means a %% that should be output only as %. Create an output
  222. segment. */
  223. if(outlen) {
  224. optr = &out[ocount++];
  225. if(ocount > MAX_SEGMENTS)
  226. return PFMT_MANYSEGS;
  227. optr->input = 0;
  228. optr->flags = FLAGS_SUBSTR;
  229. optr->start = start;
  230. optr->outlen = outlen;
  231. }
  232. start = fmt;
  233. fmt++;
  234. continue; /* while */
  235. }
  236. flags = 0;
  237. width = precision = 0;
  238. if(use_dollar != DOLLAR_NOPE) {
  239. param = dollarstring(fmt, &fmt);
  240. if(param < 0) {
  241. if(use_dollar == DOLLAR_USE)
  242. /* illegal combo */
  243. return PFMT_DOLLAR;
  244. /* we got no positional, just get the next arg */
  245. param = -1;
  246. use_dollar = DOLLAR_NOPE;
  247. }
  248. else
  249. use_dollar = DOLLAR_USE;
  250. }
  251. else
  252. param = -1;
  253. /* Handle the flags */
  254. while(loopit) {
  255. switch(*fmt++) {
  256. case ' ':
  257. flags |= FLAGS_SPACE;
  258. break;
  259. case '+':
  260. flags |= FLAGS_SHOWSIGN;
  261. break;
  262. case '-':
  263. flags |= FLAGS_LEFT;
  264. flags &= ~(unsigned int)FLAGS_PAD_NIL;
  265. break;
  266. case '#':
  267. flags |= FLAGS_ALT;
  268. break;
  269. case '.':
  270. if('*' == *fmt) {
  271. /* The precision is picked from a specified parameter */
  272. flags |= FLAGS_PRECPARAM;
  273. fmt++;
  274. if(use_dollar == DOLLAR_USE) {
  275. precision = dollarstring(fmt, &fmt);
  276. if(precision < 0)
  277. /* illegal combo */
  278. return PFMT_DOLLARPREC;
  279. }
  280. else
  281. /* get it from the next argument */
  282. precision = -1;
  283. }
  284. else {
  285. bool is_neg = FALSE;
  286. flags |= FLAGS_PREC;
  287. precision = 0;
  288. if('-' == *fmt) {
  289. is_neg = TRUE;
  290. fmt++;
  291. }
  292. while(ISDIGIT(*fmt)) {
  293. if(precision > INT_MAX/10)
  294. return PFMT_PREC;
  295. precision *= 10;
  296. precision += *fmt - '0';
  297. fmt++;
  298. }
  299. if(is_neg)
  300. precision = -precision;
  301. }
  302. if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) ==
  303. (FLAGS_PREC | FLAGS_PRECPARAM))
  304. /* it is not permitted to use both kinds of precision for the same
  305. argument */
  306. return PFMT_PRECMIX;
  307. break;
  308. case 'h':
  309. flags |= FLAGS_SHORT;
  310. break;
  311. #if defined(_WIN32) || defined(_WIN32_WCE)
  312. case 'I':
  313. /* Non-ANSI integer extensions I32 I64 */
  314. if((fmt[0] == '3') && (fmt[1] == '2')) {
  315. flags |= FLAGS_LONG;
  316. fmt += 2;
  317. }
  318. else if((fmt[0] == '6') && (fmt[1] == '4')) {
  319. flags |= FLAGS_LONGLONG;
  320. fmt += 2;
  321. }
  322. else {
  323. #if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
  324. flags |= FLAGS_LONGLONG;
  325. #else
  326. flags |= FLAGS_LONG;
  327. #endif
  328. }
  329. break;
  330. #endif /* _WIN32 || _WIN32_WCE */
  331. case 'l':
  332. if(flags & FLAGS_LONG)
  333. flags |= FLAGS_LONGLONG;
  334. else
  335. flags |= FLAGS_LONG;
  336. break;
  337. case 'L':
  338. flags |= FLAGS_LONGDOUBLE;
  339. break;
  340. case 'q':
  341. flags |= FLAGS_LONGLONG;
  342. break;
  343. case 'z':
  344. /* the code below generates a warning if -Wunreachable-code is
  345. used */
  346. #if (SIZEOF_SIZE_T > SIZEOF_LONG)
  347. flags |= FLAGS_LONGLONG;
  348. #else
  349. flags |= FLAGS_LONG;
  350. #endif
  351. break;
  352. case 'O':
  353. #if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
  354. flags |= FLAGS_LONGLONG;
  355. #else
  356. flags |= FLAGS_LONG;
  357. #endif
  358. break;
  359. case '0':
  360. if(!(flags & FLAGS_LEFT))
  361. flags |= FLAGS_PAD_NIL;
  362. FALLTHROUGH();
  363. case '1': case '2': case '3': case '4':
  364. case '5': case '6': case '7': case '8': case '9':
  365. flags |= FLAGS_WIDTH;
  366. width = 0;
  367. fmt--;
  368. do {
  369. if(width > INT_MAX/10)
  370. return PFMT_WIDTH;
  371. width *= 10;
  372. width += *fmt - '0';
  373. fmt++;
  374. } while(ISDIGIT(*fmt));
  375. break;
  376. case '*': /* read width from argument list */
  377. flags |= FLAGS_WIDTHPARAM;
  378. if(use_dollar == DOLLAR_USE) {
  379. width = dollarstring(fmt, &fmt);
  380. if(width < 0)
  381. /* illegal combo */
  382. return PFMT_DOLLARWIDTH;
  383. }
  384. else
  385. /* pick from the next argument */
  386. width = -1;
  387. break;
  388. default:
  389. loopit = FALSE;
  390. fmt--;
  391. break;
  392. } /* switch */
  393. } /* while */
  394. switch(*fmt) {
  395. case 'S':
  396. flags |= FLAGS_ALT;
  397. FALLTHROUGH();
  398. case 's':
  399. type = FORMAT_STRING;
  400. break;
  401. case 'n':
  402. type = FORMAT_INTPTR;
  403. break;
  404. case 'p':
  405. type = FORMAT_PTR;
  406. break;
  407. case 'd':
  408. case 'i':
  409. if(flags & FLAGS_LONGLONG)
  410. type = FORMAT_LONGLONG;
  411. else if(flags & FLAGS_LONG)
  412. type = FORMAT_LONG;
  413. else
  414. type = FORMAT_INT;
  415. break;
  416. case 'u':
  417. if(flags & FLAGS_LONGLONG)
  418. type = FORMAT_LONGLONGU;
  419. else if(flags & FLAGS_LONG)
  420. type = FORMAT_LONGU;
  421. else
  422. type = FORMAT_INTU;
  423. flags |= FLAGS_UNSIGNED;
  424. break;
  425. case 'o':
  426. if(flags & FLAGS_LONGLONG)
  427. type = FORMAT_LONGLONGU;
  428. else if(flags & FLAGS_LONG)
  429. type = FORMAT_LONGU;
  430. else
  431. type = FORMAT_INTU;
  432. flags |= FLAGS_OCTAL|FLAGS_UNSIGNED;
  433. break;
  434. case 'x':
  435. if(flags & FLAGS_LONGLONG)
  436. type = FORMAT_LONGLONGU;
  437. else if(flags & FLAGS_LONG)
  438. type = FORMAT_LONGU;
  439. else
  440. type = FORMAT_INTU;
  441. flags |= FLAGS_HEX|FLAGS_UNSIGNED;
  442. break;
  443. case 'X':
  444. if(flags & FLAGS_LONGLONG)
  445. type = FORMAT_LONGLONGU;
  446. else if(flags & FLAGS_LONG)
  447. type = FORMAT_LONGU;
  448. else
  449. type = FORMAT_INTU;
  450. flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
  451. break;
  452. case 'c':
  453. type = FORMAT_INT;
  454. flags |= FLAGS_CHAR;
  455. break;
  456. case 'f':
  457. type = FORMAT_DOUBLE;
  458. break;
  459. case 'e':
  460. type = FORMAT_DOUBLE;
  461. flags |= FLAGS_FLOATE;
  462. break;
  463. case 'E':
  464. type = FORMAT_DOUBLE;
  465. flags |= FLAGS_FLOATE|FLAGS_UPPER;
  466. break;
  467. case 'g':
  468. type = FORMAT_DOUBLE;
  469. flags |= FLAGS_FLOATG;
  470. break;
  471. case 'G':
  472. type = FORMAT_DOUBLE;
  473. flags |= FLAGS_FLOATG|FLAGS_UPPER;
  474. break;
  475. default:
  476. /* invalid instruction, disregard and continue */
  477. continue;
  478. } /* switch */
  479. if(flags & FLAGS_WIDTHPARAM) {
  480. if(width < 0)
  481. width = param_num++;
  482. else {
  483. /* if this identifies a parameter already used, this
  484. is illegal */
  485. if(usedinput[width/8] & (1 << (width&7)))
  486. return PFMT_WIDTHARG;
  487. }
  488. if(width >= MAX_PARAMETERS)
  489. return PFMT_MANYARGS;
  490. if(width >= max_param)
  491. max_param = width;
  492. in[width].type = FORMAT_WIDTH;
  493. /* mark as used */
  494. usedinput[width/8] |= (unsigned char)(1 << (width&7));
  495. }
  496. if(flags & FLAGS_PRECPARAM) {
  497. if(precision < 0)
  498. precision = param_num++;
  499. else {
  500. /* if this identifies a parameter already used, this
  501. is illegal */
  502. if(usedinput[precision/8] & (1 << (precision&7)))
  503. return PFMT_PRECARG;
  504. }
  505. if(precision >= MAX_PARAMETERS)
  506. return PFMT_MANYARGS;
  507. if(precision >= max_param)
  508. max_param = precision;
  509. in[precision].type = FORMAT_PRECISION;
  510. usedinput[precision/8] |= (unsigned char)(1 << (precision&7));
  511. }
  512. /* Handle the specifier */
  513. if(param < 0)
  514. param = param_num++;
  515. if(param >= MAX_PARAMETERS)
  516. return PFMT_MANYARGS;
  517. if(param >= max_param)
  518. max_param = param;
  519. iptr = &in[param];
  520. iptr->type = type;
  521. /* mark this input as used */
  522. usedinput[param/8] |= (unsigned char)(1 << (param&7));
  523. fmt++;
  524. optr = &out[ocount++];
  525. if(ocount > MAX_SEGMENTS)
  526. return PFMT_MANYSEGS;
  527. optr->input = (unsigned int)param;
  528. optr->flags = flags;
  529. optr->width = width;
  530. optr->precision = precision;
  531. optr->start = start;
  532. optr->outlen = outlen;
  533. start = fmt;
  534. }
  535. else
  536. fmt++;
  537. }
  538. /* is there a trailing piece */
  539. outlen = (size_t)(fmt - start);
  540. if(outlen) {
  541. optr = &out[ocount++];
  542. if(ocount > MAX_SEGMENTS)
  543. return PFMT_MANYSEGS;
  544. optr->input = 0;
  545. optr->flags = FLAGS_SUBSTR;
  546. optr->start = start;
  547. optr->outlen = outlen;
  548. }
  549. /* Read the arg list parameters into our data list */
  550. for(i = 0; i < max_param + 1; i++) {
  551. struct va_input *iptr = &in[i];
  552. if(!(usedinput[i/8] & (1 << (i&7))))
  553. /* bad input */
  554. return PFMT_INPUTGAP;
  555. /* based on the type, read the correct argument */
  556. switch(iptr->type) {
  557. case FORMAT_STRING:
  558. iptr->val.str = va_arg(arglist, char *);
  559. break;
  560. case FORMAT_INTPTR:
  561. case FORMAT_PTR:
  562. iptr->val.ptr = va_arg(arglist, void *);
  563. break;
  564. case FORMAT_LONGLONGU:
  565. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
  566. break;
  567. case FORMAT_LONGLONG:
  568. iptr->val.nums = (mp_intmax_t)va_arg(arglist, mp_intmax_t);
  569. break;
  570. case FORMAT_LONGU:
  571. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned long);
  572. break;
  573. case FORMAT_LONG:
  574. iptr->val.nums = (mp_intmax_t)va_arg(arglist, long);
  575. break;
  576. case FORMAT_INTU:
  577. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned int);
  578. break;
  579. case FORMAT_INT:
  580. case FORMAT_WIDTH:
  581. case FORMAT_PRECISION:
  582. iptr->val.nums = (mp_intmax_t)va_arg(arglist, int);
  583. break;
  584. case FORMAT_DOUBLE:
  585. iptr->val.dnum = va_arg(arglist, double);
  586. break;
  587. default:
  588. DEBUGASSERT(NULL); /* unexpected */
  589. break;
  590. }
  591. }
  592. *ipieces = max_param + 1;
  593. *opieces = ocount;
  594. return PFMT_OK;
  595. }
  596. /*
  597. * formatf() - the general printf function.
  598. *
  599. * It calls parsefmt() to parse the format string. It populates two arrays;
  600. * one that describes the input arguments and one that describes a number of
  601. * output segments.
  602. *
  603. * On success, the input array describes the type of all arguments and their
  604. * values.
  605. *
  606. * The function then iterates over the output segments and outputs them one
  607. * by one until done. Using the appropriate input arguments (if any).
  608. *
  609. * All output is sent to the 'stream()' callback, one byte at a time.
  610. */
  611. static int formatf(
  612. void *userp, /* untouched by format(), just sent to the stream() function in
  613. the second argument */
  614. /* function pointer called for each output character */
  615. int (*stream)(unsigned char, void *),
  616. const char *format, /* %-formatted string */
  617. va_list ap_save) /* list of parameters */
  618. {
  619. static const char nilstr[] = "(nil)";
  620. const char *digits = lower_digits; /* Base-36 digits for numbers. */
  621. int done = 0; /* number of characters written */
  622. int i;
  623. int ocount = 0; /* number of output segments */
  624. int icount = 0; /* number of input arguments */
  625. struct outsegment output[MAX_SEGMENTS];
  626. struct va_input input[MAX_PARAMETERS];
  627. char work[BUFFSIZE];
  628. /* 'workend' points to the final buffer byte position, but with an extra
  629. byte as margin to avoid the (FALSE?) warning Coverity gives us
  630. otherwise */
  631. char *workend = &work[sizeof(work) - 2];
  632. /* Parse the format string */
  633. if(parsefmt(format, output, input, &ocount, &icount, ap_save))
  634. return 0;
  635. for(i = 0; i < ocount; i++) {
  636. struct outsegment *optr = &output[i];
  637. struct va_input *iptr;
  638. bool is_alt; /* Format spec modifiers. */
  639. int width; /* Width of a field. */
  640. int prec; /* Precision of a field. */
  641. bool is_neg; /* Decimal integer is negative. */
  642. unsigned long base; /* Base of a number to be written. */
  643. mp_uintmax_t num; /* Integral values to be written. */
  644. mp_intmax_t signed_num; /* Used to convert negative in positive. */
  645. char *w;
  646. size_t outlen = optr->outlen;
  647. unsigned int flags = optr->flags;
  648. if(outlen) {
  649. char *str = optr->start;
  650. for(; outlen && *str; outlen--)
  651. OUTCHAR(*str++);
  652. if(optr->flags & FLAGS_SUBSTR)
  653. /* this is just a substring */
  654. continue;
  655. }
  656. /* pick up the specified width */
  657. if(flags & FLAGS_WIDTHPARAM) {
  658. width = (int)input[optr->width].val.nums;
  659. if(width < 0) {
  660. /* "A negative field width is taken as a '-' flag followed by a
  661. positive field width." */
  662. if(width == INT_MIN)
  663. width = INT_MAX;
  664. else
  665. width = -width;
  666. flags |= FLAGS_LEFT;
  667. flags &= ~(unsigned int)FLAGS_PAD_NIL;
  668. }
  669. }
  670. else
  671. width = optr->width;
  672. /* pick up the specified precision */
  673. if(flags & FLAGS_PRECPARAM) {
  674. prec = (int)input[optr->precision].val.nums;
  675. if(prec < 0)
  676. /* "A negative precision is taken as if the precision were
  677. omitted." */
  678. prec = -1;
  679. }
  680. else if(flags & FLAGS_PREC)
  681. prec = optr->precision;
  682. else
  683. prec = -1;
  684. is_alt = (flags & FLAGS_ALT) ? 1 : 0;
  685. iptr = &input[optr->input];
  686. switch(iptr->type) {
  687. case FORMAT_INTU:
  688. case FORMAT_LONGU:
  689. case FORMAT_LONGLONGU:
  690. flags |= FLAGS_UNSIGNED;
  691. FALLTHROUGH();
  692. case FORMAT_INT:
  693. case FORMAT_LONG:
  694. case FORMAT_LONGLONG:
  695. num = iptr->val.numu;
  696. if(flags & FLAGS_CHAR) {
  697. /* Character. */
  698. if(!(flags & FLAGS_LEFT))
  699. while(--width > 0)
  700. OUTCHAR(' ');
  701. OUTCHAR((char) num);
  702. if(flags & FLAGS_LEFT)
  703. while(--width > 0)
  704. OUTCHAR(' ');
  705. break;
  706. }
  707. if(flags & FLAGS_OCTAL) {
  708. /* Octal unsigned integer */
  709. base = 8;
  710. is_neg = FALSE;
  711. }
  712. else if(flags & FLAGS_HEX) {
  713. /* Hexadecimal unsigned integer */
  714. digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits;
  715. base = 16;
  716. is_neg = FALSE;
  717. }
  718. else if(flags & FLAGS_UNSIGNED) {
  719. /* Decimal unsigned integer */
  720. base = 10;
  721. is_neg = FALSE;
  722. }
  723. else {
  724. /* Decimal integer. */
  725. base = 10;
  726. is_neg = (iptr->val.nums < (mp_intmax_t)0);
  727. if(is_neg) {
  728. /* signed_num might fail to hold absolute negative minimum by 1 */
  729. signed_num = iptr->val.nums + (mp_intmax_t)1;
  730. signed_num = -signed_num;
  731. num = (mp_uintmax_t)signed_num;
  732. num += (mp_uintmax_t)1;
  733. }
  734. }
  735. number:
  736. /* Supply a default precision if none was given. */
  737. if(prec == -1)
  738. prec = 1;
  739. /* Put the number in WORK. */
  740. w = workend;
  741. switch(base) {
  742. case 10:
  743. while(num > 0) {
  744. *w-- = (char)('0' + (num % 10));
  745. num /= 10;
  746. }
  747. break;
  748. default:
  749. while(num > 0) {
  750. *w-- = digits[num % base];
  751. num /= base;
  752. }
  753. break;
  754. }
  755. width -= (int)(workend - w);
  756. prec -= (int)(workend - w);
  757. if(is_alt && base == 8 && prec <= 0) {
  758. *w-- = '0';
  759. --width;
  760. }
  761. if(prec > 0) {
  762. width -= prec;
  763. while(prec-- > 0 && w >= work)
  764. *w-- = '0';
  765. }
  766. if(is_alt && base == 16)
  767. width -= 2;
  768. if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
  769. --width;
  770. if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL))
  771. while(width-- > 0)
  772. OUTCHAR(' ');
  773. if(is_neg)
  774. OUTCHAR('-');
  775. else if(flags & FLAGS_SHOWSIGN)
  776. OUTCHAR('+');
  777. else if(flags & FLAGS_SPACE)
  778. OUTCHAR(' ');
  779. if(is_alt && base == 16) {
  780. OUTCHAR('0');
  781. if(flags & FLAGS_UPPER)
  782. OUTCHAR('X');
  783. else
  784. OUTCHAR('x');
  785. }
  786. if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL))
  787. while(width-- > 0)
  788. OUTCHAR('0');
  789. /* Write the number. */
  790. while(++w <= workend) {
  791. OUTCHAR(*w);
  792. }
  793. if(flags & FLAGS_LEFT)
  794. while(width-- > 0)
  795. OUTCHAR(' ');
  796. break;
  797. case FORMAT_STRING: {
  798. const char *str;
  799. size_t len;
  800. str = (char *)iptr->val.str;
  801. if(!str) {
  802. /* Write null string if there is space. */
  803. if(prec == -1 || prec >= (int) sizeof(nilstr) - 1) {
  804. str = nilstr;
  805. len = sizeof(nilstr) - 1;
  806. /* Disable quotes around (nil) */
  807. flags &= ~(unsigned int)FLAGS_ALT;
  808. }
  809. else {
  810. str = "";
  811. len = 0;
  812. }
  813. }
  814. else if(prec != -1)
  815. len = (size_t)prec;
  816. else if(*str == '\0')
  817. len = 0;
  818. else
  819. len = strlen(str);
  820. width -= (len > INT_MAX) ? INT_MAX : (int)len;
  821. if(flags & FLAGS_ALT)
  822. OUTCHAR('"');
  823. if(!(flags & FLAGS_LEFT))
  824. while(width-- > 0)
  825. OUTCHAR(' ');
  826. for(; len && *str; len--)
  827. OUTCHAR(*str++);
  828. if(flags & FLAGS_LEFT)
  829. while(width-- > 0)
  830. OUTCHAR(' ');
  831. if(flags & FLAGS_ALT)
  832. OUTCHAR('"');
  833. break;
  834. }
  835. case FORMAT_PTR:
  836. /* Generic pointer. */
  837. if(iptr->val.ptr) {
  838. /* If the pointer is not NULL, write it as a %#x spec. */
  839. base = 16;
  840. digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits;
  841. is_alt = TRUE;
  842. num = (size_t) iptr->val.ptr;
  843. is_neg = FALSE;
  844. goto number;
  845. }
  846. else {
  847. /* Write "(nil)" for a nil pointer. */
  848. const char *point;
  849. width -= (int)(sizeof(nilstr) - 1);
  850. if(flags & FLAGS_LEFT)
  851. while(width-- > 0)
  852. OUTCHAR(' ');
  853. for(point = nilstr; *point != '\0'; ++point)
  854. OUTCHAR(*point);
  855. if(!(flags & FLAGS_LEFT))
  856. while(width-- > 0)
  857. OUTCHAR(' ');
  858. }
  859. break;
  860. case FORMAT_DOUBLE: {
  861. char formatbuf[32]="%";
  862. char *fptr = &formatbuf[1];
  863. size_t left = sizeof(formatbuf)-strlen(formatbuf);
  864. int len;
  865. if(flags & FLAGS_WIDTH)
  866. width = optr->width;
  867. if(flags & FLAGS_PREC)
  868. prec = optr->precision;
  869. if(flags & FLAGS_LEFT)
  870. *fptr++ = '-';
  871. if(flags & FLAGS_SHOWSIGN)
  872. *fptr++ = '+';
  873. if(flags & FLAGS_SPACE)
  874. *fptr++ = ' ';
  875. if(flags & FLAGS_ALT)
  876. *fptr++ = '#';
  877. *fptr = 0;
  878. if(width >= 0) {
  879. size_t dlen;
  880. if(width >= (int)sizeof(work))
  881. width = sizeof(work)-1;
  882. /* RECURSIVE USAGE */
  883. dlen = (size_t)curl_msnprintf(fptr, left, "%d", width);
  884. fptr += dlen;
  885. left -= dlen;
  886. }
  887. if(prec >= 0) {
  888. /* for each digit in the integer part, we can have one less
  889. precision */
  890. size_t maxprec = sizeof(work) - 2;
  891. double val = iptr->val.dnum;
  892. if(width > 0 && prec <= width)
  893. maxprec -= (size_t)width;
  894. while(val >= 10.0) {
  895. val /= 10;
  896. maxprec--;
  897. }
  898. if(prec > (int)maxprec)
  899. prec = (int)maxprec-1;
  900. if(prec < 0)
  901. prec = 0;
  902. /* RECURSIVE USAGE */
  903. len = curl_msnprintf(fptr, left, ".%d", prec);
  904. fptr += len;
  905. }
  906. if(flags & FLAGS_LONG)
  907. *fptr++ = 'l';
  908. if(flags & FLAGS_FLOATE)
  909. *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E' : 'e');
  910. else if(flags & FLAGS_FLOATG)
  911. *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g');
  912. else
  913. *fptr++ = 'f';
  914. *fptr = 0; /* and a final null-termination */
  915. #ifdef __clang__
  916. #pragma clang diagnostic push
  917. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  918. #endif
  919. /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
  920. output characters */
  921. #ifdef HAVE_SNPRINTF
  922. (snprintf)(work, sizeof(work), formatbuf, iptr->val.dnum);
  923. #else
  924. (sprintf)(work, formatbuf, iptr->val.dnum);
  925. #endif
  926. #ifdef __clang__
  927. #pragma clang diagnostic pop
  928. #endif
  929. DEBUGASSERT(strlen(work) <= sizeof(work));
  930. for(fptr = work; *fptr; fptr++)
  931. OUTCHAR(*fptr);
  932. break;
  933. }
  934. case FORMAT_INTPTR:
  935. /* Answer the count of characters written. */
  936. #ifdef HAVE_LONG_LONG_TYPE
  937. if(flags & FLAGS_LONGLONG)
  938. *(LONG_LONG_TYPE *) iptr->val.ptr = (LONG_LONG_TYPE)done;
  939. else
  940. #endif
  941. if(flags & FLAGS_LONG)
  942. *(long *) iptr->val.ptr = (long)done;
  943. else if(!(flags & FLAGS_SHORT))
  944. *(int *) iptr->val.ptr = (int)done;
  945. else
  946. *(short *) iptr->val.ptr = (short)done;
  947. break;
  948. default:
  949. break;
  950. }
  951. }
  952. return done;
  953. }
  954. /* fputc() look-alike */
  955. static int addbyter(unsigned char outc, void *f)
  956. {
  957. struct nsprintf *infop = f;
  958. if(infop->length < infop->max) {
  959. /* only do this if we have not reached max length yet */
  960. *infop->buffer++ = (char)outc; /* store */
  961. infop->length++; /* we are now one byte larger */
  962. return 0; /* fputc() returns like this on success */
  963. }
  964. return 1;
  965. }
  966. int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
  967. va_list ap_save)
  968. {
  969. int retcode;
  970. struct nsprintf info;
  971. info.buffer = buffer;
  972. info.length = 0;
  973. info.max = maxlength;
  974. retcode = formatf(&info, addbyter, format, ap_save);
  975. if(info.max) {
  976. /* we terminate this with a zero byte */
  977. if(info.max == info.length) {
  978. /* we are at maximum, scrap the last letter */
  979. info.buffer[-1] = 0;
  980. DEBUGASSERT(retcode);
  981. retcode--; /* do not count the nul byte */
  982. }
  983. else
  984. info.buffer[0] = 0;
  985. }
  986. return retcode;
  987. }
  988. int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
  989. {
  990. int retcode;
  991. va_list ap_save; /* argument pointer */
  992. va_start(ap_save, format);
  993. retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
  994. va_end(ap_save);
  995. return retcode;
  996. }
  997. /* fputc() look-alike */
  998. static int alloc_addbyter(unsigned char outc, void *f)
  999. {
  1000. struct asprintf *infop = f;
  1001. CURLcode result = Curl_dyn_addn(infop->b, &outc, 1);
  1002. if(result) {
  1003. infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM;
  1004. return 1 ; /* fail */
  1005. }
  1006. return 0;
  1007. }
  1008. /* appends the formatted string, returns MERR error code */
  1009. int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save)
  1010. {
  1011. struct asprintf info;
  1012. info.b = dyn;
  1013. info.merr = MERR_OK;
  1014. (void)formatf(&info, alloc_addbyter, format, ap_save);
  1015. if(info.merr) {
  1016. Curl_dyn_free(info.b);
  1017. return info.merr;
  1018. }
  1019. return 0;
  1020. }
  1021. char *curl_mvaprintf(const char *format, va_list ap_save)
  1022. {
  1023. struct asprintf info;
  1024. struct dynbuf dyn;
  1025. info.b = &dyn;
  1026. Curl_dyn_init(info.b, DYN_APRINTF);
  1027. info.merr = MERR_OK;
  1028. (void)formatf(&info, alloc_addbyter, format, ap_save);
  1029. if(info.merr) {
  1030. Curl_dyn_free(info.b);
  1031. return NULL;
  1032. }
  1033. if(Curl_dyn_len(info.b))
  1034. return Curl_dyn_ptr(info.b);
  1035. return strdup("");
  1036. }
  1037. char *curl_maprintf(const char *format, ...)
  1038. {
  1039. va_list ap_save;
  1040. char *s;
  1041. va_start(ap_save, format);
  1042. s = curl_mvaprintf(format, ap_save);
  1043. va_end(ap_save);
  1044. return s;
  1045. }
  1046. static int storebuffer(unsigned char outc, void *f)
  1047. {
  1048. char **buffer = f;
  1049. **buffer = (char)outc;
  1050. (*buffer)++;
  1051. return 0;
  1052. }
  1053. int curl_msprintf(char *buffer, const char *format, ...)
  1054. {
  1055. va_list ap_save; /* argument pointer */
  1056. int retcode;
  1057. va_start(ap_save, format);
  1058. retcode = formatf(&buffer, storebuffer, format, ap_save);
  1059. va_end(ap_save);
  1060. *buffer = 0; /* we terminate this with a zero byte */
  1061. return retcode;
  1062. }
  1063. static int fputc_wrapper(unsigned char outc, void *f)
  1064. {
  1065. int out = outc;
  1066. FILE *s = f;
  1067. int rc = fputc(out, s);
  1068. return rc == EOF;
  1069. }
  1070. int curl_mprintf(const char *format, ...)
  1071. {
  1072. int retcode;
  1073. va_list ap_save; /* argument pointer */
  1074. va_start(ap_save, format);
  1075. retcode = formatf(stdout, fputc_wrapper, format, ap_save);
  1076. va_end(ap_save);
  1077. return retcode;
  1078. }
  1079. int curl_mfprintf(FILE *whereto, const char *format, ...)
  1080. {
  1081. int retcode;
  1082. va_list ap_save; /* argument pointer */
  1083. va_start(ap_save, format);
  1084. retcode = formatf(whereto, fputc_wrapper, format, ap_save);
  1085. va_end(ap_save);
  1086. return retcode;
  1087. }
  1088. int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
  1089. {
  1090. int retcode = formatf(&buffer, storebuffer, format, ap_save);
  1091. *buffer = 0; /* we terminate this with a zero byte */
  1092. return retcode;
  1093. }
  1094. int curl_mvprintf(const char *format, va_list ap_save)
  1095. {
  1096. return formatf(stdout, fputc_wrapper, format, ap_save);
  1097. }
  1098. int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
  1099. {
  1100. return formatf(whereto, fputc_wrapper, format, ap_save);
  1101. }