mprintf.c 30 KB

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