mprintf.c 31 KB

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