2
0

mprintf.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. type = FORMAT_INT;
  427. flags |= FLAGS_OCTAL;
  428. break;
  429. case 'x':
  430. type = FORMAT_INTU;
  431. flags |= FLAGS_HEX|FLAGS_UNSIGNED;
  432. break;
  433. case 'X':
  434. type = FORMAT_INTU;
  435. flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
  436. break;
  437. case 'c':
  438. type = FORMAT_INT;
  439. flags |= FLAGS_CHAR;
  440. break;
  441. case 'f':
  442. type = FORMAT_DOUBLE;
  443. break;
  444. case 'e':
  445. type = FORMAT_DOUBLE;
  446. flags |= FLAGS_FLOATE;
  447. break;
  448. case 'E':
  449. type = FORMAT_DOUBLE;
  450. flags |= FLAGS_FLOATE|FLAGS_UPPER;
  451. break;
  452. case 'g':
  453. type = FORMAT_DOUBLE;
  454. flags |= FLAGS_FLOATG;
  455. break;
  456. case 'G':
  457. type = FORMAT_DOUBLE;
  458. flags |= FLAGS_FLOATG|FLAGS_UPPER;
  459. break;
  460. default:
  461. /* invalid instruction, disregard and continue */
  462. continue;
  463. } /* switch */
  464. if(flags & FLAGS_WIDTHPARAM) {
  465. if(width < 0)
  466. width = param_num++;
  467. else {
  468. /* if this identifies a parameter already used, this
  469. is illegal */
  470. if(usedinput[width/8] & (1 << (width&7)))
  471. return PFMT_WIDTHARG;
  472. }
  473. if(width >= MAX_PARAMETERS)
  474. return PFMT_MANYARGS;
  475. if(width >= max_param)
  476. max_param = width;
  477. in[width].type = FORMAT_WIDTH;
  478. /* mark as used */
  479. usedinput[width/8] |= (unsigned char)(1 << (width&7));
  480. }
  481. if(flags & FLAGS_PRECPARAM) {
  482. if(precision < 0)
  483. precision = param_num++;
  484. else {
  485. /* if this identifies a parameter already used, this
  486. is illegal */
  487. if(usedinput[precision/8] & (1 << (precision&7)))
  488. return PFMT_PRECARG;
  489. }
  490. if(precision >= MAX_PARAMETERS)
  491. return PFMT_MANYARGS;
  492. if(precision >= max_param)
  493. max_param = precision;
  494. in[precision].type = FORMAT_PRECISION;
  495. usedinput[precision/8] |= (unsigned char)(1 << (precision&7));
  496. }
  497. /* Handle the specifier */
  498. if(param < 0)
  499. param = param_num++;
  500. if(param >= MAX_PARAMETERS)
  501. return PFMT_MANYARGS;
  502. if(param >= max_param)
  503. max_param = param;
  504. iptr = &in[param];
  505. iptr->type = type;
  506. /* mark this input as used */
  507. usedinput[param/8] |= (unsigned char)(1 << (param&7));
  508. fmt++;
  509. optr = &out[ocount++];
  510. if(ocount > MAX_SEGMENTS)
  511. return PFMT_MANYSEGS;
  512. optr->input = (unsigned int)param;
  513. optr->flags = flags;
  514. optr->width = width;
  515. optr->precision = precision;
  516. optr->start = start;
  517. optr->outlen = outlen;
  518. start = fmt;
  519. }
  520. else
  521. fmt++;
  522. }
  523. /* is there a trailing piece */
  524. outlen = (size_t)(fmt - start);
  525. if(outlen) {
  526. optr = &out[ocount++];
  527. if(ocount > MAX_SEGMENTS)
  528. return PFMT_MANYSEGS;
  529. optr->input = 0;
  530. optr->flags = FLAGS_SUBSTR;
  531. optr->start = start;
  532. optr->outlen = outlen;
  533. }
  534. /* Read the arg list parameters into our data list */
  535. for(i = 0; i < max_param + 1; i++) {
  536. struct va_input *iptr = &in[i];
  537. if(!(usedinput[i/8] & (1 << (i&7))))
  538. /* bad input */
  539. return PFMT_INPUTGAP;
  540. /* based on the type, read the correct argument */
  541. switch(iptr->type) {
  542. case FORMAT_STRING:
  543. iptr->val.str = va_arg(arglist, char *);
  544. break;
  545. case FORMAT_INTPTR:
  546. case FORMAT_PTR:
  547. iptr->val.ptr = va_arg(arglist, void *);
  548. break;
  549. case FORMAT_LONGLONGU:
  550. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
  551. break;
  552. case FORMAT_LONGLONG:
  553. iptr->val.nums = (mp_intmax_t)va_arg(arglist, mp_intmax_t);
  554. break;
  555. case FORMAT_LONGU:
  556. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned long);
  557. break;
  558. case FORMAT_LONG:
  559. iptr->val.nums = (mp_intmax_t)va_arg(arglist, long);
  560. break;
  561. case FORMAT_INTU:
  562. iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned int);
  563. break;
  564. case FORMAT_INT:
  565. case FORMAT_WIDTH:
  566. case FORMAT_PRECISION:
  567. iptr->val.nums = (mp_intmax_t)va_arg(arglist, int);
  568. break;
  569. case FORMAT_DOUBLE:
  570. iptr->val.dnum = va_arg(arglist, double);
  571. break;
  572. default:
  573. DEBUGASSERT(NULL); /* unexpected */
  574. break;
  575. }
  576. }
  577. *ipieces = max_param + 1;
  578. *opieces = ocount;
  579. return PFMT_OK;
  580. }
  581. /*
  582. * formatf() - the general printf function.
  583. *
  584. * It calls parsefmt() to parse the format string. It populates two arrays;
  585. * one that describes the input arguments and one that describes a number of
  586. * output segments.
  587. *
  588. * On success, the input array describes the type of all arguments and their
  589. * values.
  590. *
  591. * The function then iterates over the output segments and outputs them one
  592. * by one until done. Using the appropriate input arguments (if any).
  593. *
  594. * All output is sent to the 'stream()' callback, one byte at a time.
  595. */
  596. static int formatf(
  597. void *userp, /* untouched by format(), just sent to the stream() function in
  598. the second argument */
  599. /* function pointer called for each output character */
  600. int (*stream)(unsigned char, void *),
  601. const char *format, /* %-formatted string */
  602. va_list ap_save) /* list of parameters */
  603. {
  604. static const char nilstr[] = "(nil)";
  605. const char *digits = lower_digits; /* Base-36 digits for numbers. */
  606. int done = 0; /* number of characters written */
  607. int i;
  608. int ocount = 0; /* number of output segments */
  609. int icount = 0; /* number of input arguments */
  610. struct outsegment output[MAX_SEGMENTS];
  611. struct va_input input[MAX_PARAMETERS];
  612. char work[BUFFSIZE];
  613. /* 'workend' points to the final buffer byte position, but with an extra
  614. byte as margin to avoid the (FALSE?) warning Coverity gives us
  615. otherwise */
  616. char *workend = &work[sizeof(work) - 2];
  617. /* Parse the format string */
  618. if(parsefmt(format, output, input, &ocount, &icount, ap_save))
  619. return 0;
  620. for(i = 0; i < ocount; i++) {
  621. struct outsegment *optr = &output[i];
  622. struct va_input *iptr;
  623. bool is_alt; /* Format spec modifiers. */
  624. int width; /* Width of a field. */
  625. int prec; /* Precision of a field. */
  626. bool is_neg; /* Decimal integer is negative. */
  627. unsigned long base; /* Base of a number to be written. */
  628. mp_uintmax_t num; /* Integral values to be written. */
  629. mp_intmax_t signed_num; /* Used to convert negative in positive. */
  630. char *w;
  631. size_t outlen = optr->outlen;
  632. unsigned int flags = optr->flags;
  633. if(outlen) {
  634. char *str = optr->start;
  635. for(; outlen && *str; outlen--)
  636. OUTCHAR(*str++);
  637. if(optr->flags & FLAGS_SUBSTR)
  638. /* this is just a substring */
  639. continue;
  640. }
  641. /* pick up the specified width */
  642. if(flags & FLAGS_WIDTHPARAM) {
  643. width = (int)input[optr->width].val.nums;
  644. if(width < 0) {
  645. /* "A negative field width is taken as a '-' flag followed by a
  646. positive field width." */
  647. if(width == INT_MIN)
  648. width = INT_MAX;
  649. else
  650. width = -width;
  651. flags |= FLAGS_LEFT;
  652. flags &= ~(unsigned int)FLAGS_PAD_NIL;
  653. }
  654. }
  655. else
  656. width = optr->width;
  657. /* pick up the specified precision */
  658. if(flags & FLAGS_PRECPARAM) {
  659. prec = (int)input[optr->precision].val.nums;
  660. if(prec < 0)
  661. /* "A negative precision is taken as if the precision were
  662. omitted." */
  663. prec = -1;
  664. }
  665. else if(flags & FLAGS_PREC)
  666. prec = optr->precision;
  667. else
  668. prec = -1;
  669. is_alt = (flags & FLAGS_ALT) ? 1 : 0;
  670. iptr = &input[optr->input];
  671. switch(iptr->type) {
  672. case FORMAT_INTU:
  673. case FORMAT_LONGU:
  674. case FORMAT_LONGLONGU:
  675. flags |= FLAGS_UNSIGNED;
  676. FALLTHROUGH();
  677. case FORMAT_INT:
  678. case FORMAT_LONG:
  679. case FORMAT_LONGLONG:
  680. num = iptr->val.numu;
  681. if(flags & FLAGS_CHAR) {
  682. /* Character. */
  683. if(!(flags & FLAGS_LEFT))
  684. while(--width > 0)
  685. OUTCHAR(' ');
  686. OUTCHAR((char) num);
  687. if(flags & FLAGS_LEFT)
  688. while(--width > 0)
  689. OUTCHAR(' ');
  690. break;
  691. }
  692. if(flags & FLAGS_OCTAL) {
  693. /* Octal unsigned integer */
  694. base = 8;
  695. is_neg = FALSE;
  696. }
  697. else if(flags & FLAGS_HEX) {
  698. /* Hexadecimal unsigned integer */
  699. digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits;
  700. base = 16;
  701. is_neg = FALSE;
  702. }
  703. else if(flags & FLAGS_UNSIGNED) {
  704. /* Decimal unsigned integer */
  705. base = 10;
  706. is_neg = FALSE;
  707. }
  708. else {
  709. /* Decimal integer. */
  710. base = 10;
  711. is_neg = (iptr->val.nums < (mp_intmax_t)0);
  712. if(is_neg) {
  713. /* signed_num might fail to hold absolute negative minimum by 1 */
  714. signed_num = iptr->val.nums + (mp_intmax_t)1;
  715. signed_num = -signed_num;
  716. num = (mp_uintmax_t)signed_num;
  717. num += (mp_uintmax_t)1;
  718. }
  719. }
  720. number:
  721. /* Supply a default precision if none was given. */
  722. if(prec == -1)
  723. prec = 1;
  724. /* Put the number in WORK. */
  725. w = workend;
  726. switch(base) {
  727. case 10:
  728. while(num > 0) {
  729. *w-- = (char)('0' + (num % 10));
  730. num /= 10;
  731. }
  732. break;
  733. default:
  734. while(num > 0) {
  735. *w-- = digits[num % base];
  736. num /= base;
  737. }
  738. break;
  739. }
  740. width -= (int)(workend - w);
  741. prec -= (int)(workend - w);
  742. if(is_alt && base == 8 && prec <= 0) {
  743. *w-- = '0';
  744. --width;
  745. }
  746. if(prec > 0) {
  747. width -= prec;
  748. while(prec-- > 0 && w >= work)
  749. *w-- = '0';
  750. }
  751. if(is_alt && base == 16)
  752. width -= 2;
  753. if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
  754. --width;
  755. if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL))
  756. while(width-- > 0)
  757. OUTCHAR(' ');
  758. if(is_neg)
  759. OUTCHAR('-');
  760. else if(flags & FLAGS_SHOWSIGN)
  761. OUTCHAR('+');
  762. else if(flags & FLAGS_SPACE)
  763. OUTCHAR(' ');
  764. if(is_alt && base == 16) {
  765. OUTCHAR('0');
  766. if(flags & FLAGS_UPPER)
  767. OUTCHAR('X');
  768. else
  769. OUTCHAR('x');
  770. }
  771. if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL))
  772. while(width-- > 0)
  773. OUTCHAR('0');
  774. /* Write the number. */
  775. while(++w <= workend) {
  776. OUTCHAR(*w);
  777. }
  778. if(flags & FLAGS_LEFT)
  779. while(width-- > 0)
  780. OUTCHAR(' ');
  781. break;
  782. case FORMAT_STRING: {
  783. const char *str;
  784. size_t len;
  785. str = (char *)iptr->val.str;
  786. if(!str) {
  787. /* Write null string if there is space. */
  788. if(prec == -1 || prec >= (int) sizeof(nilstr) - 1) {
  789. str = nilstr;
  790. len = sizeof(nilstr) - 1;
  791. /* Disable quotes around (nil) */
  792. flags &= ~(unsigned int)FLAGS_ALT;
  793. }
  794. else {
  795. str = "";
  796. len = 0;
  797. }
  798. }
  799. else if(prec != -1)
  800. len = (size_t)prec;
  801. else if(*str == '\0')
  802. len = 0;
  803. else
  804. len = strlen(str);
  805. width -= (len > INT_MAX) ? INT_MAX : (int)len;
  806. if(flags & FLAGS_ALT)
  807. OUTCHAR('"');
  808. if(!(flags & FLAGS_LEFT))
  809. while(width-- > 0)
  810. OUTCHAR(' ');
  811. for(; len && *str; len--)
  812. OUTCHAR(*str++);
  813. if(flags & FLAGS_LEFT)
  814. while(width-- > 0)
  815. OUTCHAR(' ');
  816. if(flags & FLAGS_ALT)
  817. OUTCHAR('"');
  818. break;
  819. }
  820. case FORMAT_PTR:
  821. /* Generic pointer. */
  822. if(iptr->val.ptr) {
  823. /* If the pointer is not NULL, write it as a %#x spec. */
  824. base = 16;
  825. digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits;
  826. is_alt = TRUE;
  827. num = (size_t) iptr->val.ptr;
  828. is_neg = FALSE;
  829. goto number;
  830. }
  831. else {
  832. /* Write "(nil)" for a nil pointer. */
  833. const char *point;
  834. width -= (int)(sizeof(nilstr) - 1);
  835. if(flags & FLAGS_LEFT)
  836. while(width-- > 0)
  837. OUTCHAR(' ');
  838. for(point = nilstr; *point != '\0'; ++point)
  839. OUTCHAR(*point);
  840. if(!(flags & FLAGS_LEFT))
  841. while(width-- > 0)
  842. OUTCHAR(' ');
  843. }
  844. break;
  845. case FORMAT_DOUBLE: {
  846. char formatbuf[32]="%";
  847. char *fptr = &formatbuf[1];
  848. size_t left = sizeof(formatbuf)-strlen(formatbuf);
  849. int len;
  850. if(flags & FLAGS_WIDTH)
  851. width = optr->width;
  852. if(flags & FLAGS_PREC)
  853. prec = optr->precision;
  854. if(flags & FLAGS_LEFT)
  855. *fptr++ = '-';
  856. if(flags & FLAGS_SHOWSIGN)
  857. *fptr++ = '+';
  858. if(flags & FLAGS_SPACE)
  859. *fptr++ = ' ';
  860. if(flags & FLAGS_ALT)
  861. *fptr++ = '#';
  862. *fptr = 0;
  863. if(width >= 0) {
  864. size_t dlen;
  865. if(width >= (int)sizeof(work))
  866. width = sizeof(work)-1;
  867. /* RECURSIVE USAGE */
  868. dlen = (size_t)curl_msnprintf(fptr, left, "%d", width);
  869. fptr += dlen;
  870. left -= dlen;
  871. }
  872. if(prec >= 0) {
  873. /* for each digit in the integer part, we can have one less
  874. precision */
  875. size_t maxprec = sizeof(work) - 2;
  876. double val = iptr->val.dnum;
  877. if(width > 0 && prec <= width)
  878. maxprec -= (size_t)width;
  879. while(val >= 10.0) {
  880. val /= 10;
  881. maxprec--;
  882. }
  883. if(prec > (int)maxprec)
  884. prec = (int)maxprec-1;
  885. if(prec < 0)
  886. prec = 0;
  887. /* RECURSIVE USAGE */
  888. len = curl_msnprintf(fptr, left, ".%d", prec);
  889. fptr += len;
  890. }
  891. if(flags & FLAGS_LONG)
  892. *fptr++ = 'l';
  893. if(flags & FLAGS_FLOATE)
  894. *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E' : 'e');
  895. else if(flags & FLAGS_FLOATG)
  896. *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g');
  897. else
  898. *fptr++ = 'f';
  899. *fptr = 0; /* and a final null-termination */
  900. #ifdef __clang__
  901. #pragma clang diagnostic push
  902. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  903. #endif
  904. /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
  905. output characters */
  906. #ifdef HAVE_SNPRINTF
  907. (snprintf)(work, sizeof(work), formatbuf, iptr->val.dnum);
  908. #else
  909. (sprintf)(work, formatbuf, iptr->val.dnum);
  910. #endif
  911. #ifdef __clang__
  912. #pragma clang diagnostic pop
  913. #endif
  914. DEBUGASSERT(strlen(work) <= sizeof(work));
  915. for(fptr = work; *fptr; fptr++)
  916. OUTCHAR(*fptr);
  917. break;
  918. }
  919. case FORMAT_INTPTR:
  920. /* Answer the count of characters written. */
  921. #ifdef HAVE_LONG_LONG_TYPE
  922. if(flags & FLAGS_LONGLONG)
  923. *(LONG_LONG_TYPE *) iptr->val.ptr = (LONG_LONG_TYPE)done;
  924. else
  925. #endif
  926. if(flags & FLAGS_LONG)
  927. *(long *) iptr->val.ptr = (long)done;
  928. else if(!(flags & FLAGS_SHORT))
  929. *(int *) iptr->val.ptr = (int)done;
  930. else
  931. *(short *) iptr->val.ptr = (short)done;
  932. break;
  933. default:
  934. break;
  935. }
  936. }
  937. return done;
  938. }
  939. /* fputc() look-alike */
  940. static int addbyter(unsigned char outc, void *f)
  941. {
  942. struct nsprintf *infop = f;
  943. if(infop->length < infop->max) {
  944. /* only do this if we have not reached max length yet */
  945. *infop->buffer++ = (char)outc; /* store */
  946. infop->length++; /* we are now one byte larger */
  947. return 0; /* fputc() returns like this on success */
  948. }
  949. return 1;
  950. }
  951. int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
  952. va_list ap_save)
  953. {
  954. int retcode;
  955. struct nsprintf info;
  956. info.buffer = buffer;
  957. info.length = 0;
  958. info.max = maxlength;
  959. retcode = formatf(&info, addbyter, format, ap_save);
  960. if(info.max) {
  961. /* we terminate this with a zero byte */
  962. if(info.max == info.length) {
  963. /* we are at maximum, scrap the last letter */
  964. info.buffer[-1] = 0;
  965. DEBUGASSERT(retcode);
  966. retcode--; /* do not count the nul byte */
  967. }
  968. else
  969. info.buffer[0] = 0;
  970. }
  971. return retcode;
  972. }
  973. int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
  974. {
  975. int retcode;
  976. va_list ap_save; /* argument pointer */
  977. va_start(ap_save, format);
  978. retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
  979. va_end(ap_save);
  980. return retcode;
  981. }
  982. /* fputc() look-alike */
  983. static int alloc_addbyter(unsigned char outc, void *f)
  984. {
  985. struct asprintf *infop = f;
  986. CURLcode result = Curl_dyn_addn(infop->b, &outc, 1);
  987. if(result) {
  988. infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM;
  989. return 1 ; /* fail */
  990. }
  991. return 0;
  992. }
  993. /* appends the formatted string, returns MERR error code */
  994. int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save)
  995. {
  996. struct asprintf info;
  997. info.b = dyn;
  998. info.merr = MERR_OK;
  999. (void)formatf(&info, alloc_addbyter, format, ap_save);
  1000. if(info.merr) {
  1001. Curl_dyn_free(info.b);
  1002. return info.merr;
  1003. }
  1004. return 0;
  1005. }
  1006. char *curl_mvaprintf(const char *format, va_list ap_save)
  1007. {
  1008. struct asprintf info;
  1009. struct dynbuf dyn;
  1010. info.b = &dyn;
  1011. Curl_dyn_init(info.b, DYN_APRINTF);
  1012. info.merr = MERR_OK;
  1013. (void)formatf(&info, alloc_addbyter, format, ap_save);
  1014. if(info.merr) {
  1015. Curl_dyn_free(info.b);
  1016. return NULL;
  1017. }
  1018. if(Curl_dyn_len(info.b))
  1019. return Curl_dyn_ptr(info.b);
  1020. return strdup("");
  1021. }
  1022. char *curl_maprintf(const char *format, ...)
  1023. {
  1024. va_list ap_save;
  1025. char *s;
  1026. va_start(ap_save, format);
  1027. s = curl_mvaprintf(format, ap_save);
  1028. va_end(ap_save);
  1029. return s;
  1030. }
  1031. static int storebuffer(unsigned char outc, void *f)
  1032. {
  1033. char **buffer = f;
  1034. **buffer = (char)outc;
  1035. (*buffer)++;
  1036. return 0;
  1037. }
  1038. int curl_msprintf(char *buffer, const char *format, ...)
  1039. {
  1040. va_list ap_save; /* argument pointer */
  1041. int retcode;
  1042. va_start(ap_save, format);
  1043. retcode = formatf(&buffer, storebuffer, format, ap_save);
  1044. va_end(ap_save);
  1045. *buffer = 0; /* we terminate this with a zero byte */
  1046. return retcode;
  1047. }
  1048. static int fputc_wrapper(unsigned char outc, void *f)
  1049. {
  1050. int out = outc;
  1051. FILE *s = f;
  1052. int rc = fputc(out, s);
  1053. return rc == EOF;
  1054. }
  1055. int curl_mprintf(const char *format, ...)
  1056. {
  1057. int retcode;
  1058. va_list ap_save; /* argument pointer */
  1059. va_start(ap_save, format);
  1060. retcode = formatf(stdout, fputc_wrapper, format, ap_save);
  1061. va_end(ap_save);
  1062. return retcode;
  1063. }
  1064. int curl_mfprintf(FILE *whereto, const char *format, ...)
  1065. {
  1066. int retcode;
  1067. va_list ap_save; /* argument pointer */
  1068. va_start(ap_save, format);
  1069. retcode = formatf(whereto, fputc_wrapper, format, ap_save);
  1070. va_end(ap_save);
  1071. return retcode;
  1072. }
  1073. int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
  1074. {
  1075. int retcode = formatf(&buffer, storebuffer, format, ap_save);
  1076. *buffer = 0; /* we terminate this with a zero byte */
  1077. return retcode;
  1078. }
  1079. int curl_mvprintf(const char *format, va_list ap_save)
  1080. {
  1081. return formatf(stdout, fputc_wrapper, format, ap_save);
  1082. }
  1083. int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
  1084. {
  1085. return formatf(whereto, fputc_wrapper, format, ap_save);
  1086. }