mprintf.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. * 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. if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) ==
  284. (FLAGS_PREC | FLAGS_PRECPARAM))
  285. /* it is not permitted to use both kinds of precision for the same
  286. argument */
  287. return 1;
  288. break;
  289. case 'h':
  290. flags |= FLAGS_SHORT;
  291. break;
  292. #if defined(MP_HAVE_INT_EXTENSIONS)
  293. case 'I':
  294. #if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
  295. flags |= FLAGS_LONGLONG;
  296. #else
  297. flags |= FLAGS_LONG;
  298. #endif
  299. break;
  300. #endif
  301. case 'l':
  302. if(flags & FLAGS_LONG)
  303. flags |= FLAGS_LONGLONG;
  304. else
  305. flags |= FLAGS_LONG;
  306. break;
  307. case 'L':
  308. flags |= FLAGS_LONGDOUBLE;
  309. break;
  310. case 'q':
  311. flags |= FLAGS_LONGLONG;
  312. break;
  313. case 'z':
  314. /* the code below generates a warning if -Wunreachable-code is
  315. used */
  316. #if (SIZEOF_SIZE_T > SIZEOF_LONG)
  317. flags |= FLAGS_LONGLONG;
  318. #else
  319. flags |= FLAGS_LONG;
  320. #endif
  321. break;
  322. case 'O':
  323. #if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
  324. flags |= FLAGS_LONGLONG;
  325. #else
  326. flags |= FLAGS_LONG;
  327. #endif
  328. break;
  329. case '0':
  330. if(!(flags & FLAGS_LEFT))
  331. flags |= FLAGS_PAD_NIL;
  332. /* FALLTHROUGH */
  333. case '1': case '2': case '3': case '4':
  334. case '5': case '6': case '7': case '8': case '9':
  335. flags |= FLAGS_WIDTH;
  336. width = strtol(fmt-1, &fmt, 10);
  337. break;
  338. case '*': /* Special case */
  339. flags |= FLAGS_WIDTHPARAM;
  340. param_num++;
  341. i = dprintf_DollarString(fmt, &fmt);
  342. if(i)
  343. width = i;
  344. else
  345. width = param_num;
  346. if(width > max_param)
  347. max_param = width;
  348. break;
  349. case '\0':
  350. fmt--;
  351. default:
  352. break;
  353. }
  354. } /* switch */
  355. /* Handle the specifier */
  356. i = this_param - 1;
  357. if((i < 0) || (i >= MAX_PARAMETERS))
  358. /* out of allowed range */
  359. return 1;
  360. switch (*fmt) {
  361. case 'S':
  362. flags |= FLAGS_ALT;
  363. /* FALLTHROUGH */
  364. case 's':
  365. vto[i].type = FORMAT_STRING;
  366. break;
  367. case 'n':
  368. vto[i].type = FORMAT_INTPTR;
  369. break;
  370. case 'p':
  371. vto[i].type = FORMAT_PTR;
  372. break;
  373. case 'd': case 'i':
  374. vto[i].type = FORMAT_INT;
  375. break;
  376. case 'u':
  377. vto[i].type = FORMAT_INT;
  378. flags |= FLAGS_UNSIGNED;
  379. break;
  380. case 'o':
  381. vto[i].type = FORMAT_INT;
  382. flags |= FLAGS_OCTAL;
  383. break;
  384. case 'x':
  385. vto[i].type = FORMAT_INT;
  386. flags |= FLAGS_HEX|FLAGS_UNSIGNED;
  387. break;
  388. case 'X':
  389. vto[i].type = FORMAT_INT;
  390. flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
  391. break;
  392. case 'c':
  393. vto[i].type = FORMAT_INT;
  394. flags |= FLAGS_CHAR;
  395. break;
  396. case 'f':
  397. vto[i].type = FORMAT_DOUBLE;
  398. break;
  399. case 'e':
  400. vto[i].type = FORMAT_DOUBLE;
  401. flags |= FLAGS_FLOATE;
  402. break;
  403. case 'E':
  404. vto[i].type = FORMAT_DOUBLE;
  405. flags |= FLAGS_FLOATE|FLAGS_UPPER;
  406. break;
  407. case 'g':
  408. vto[i].type = FORMAT_DOUBLE;
  409. flags |= FLAGS_FLOATG;
  410. break;
  411. case 'G':
  412. vto[i].type = FORMAT_DOUBLE;
  413. flags |= FLAGS_FLOATG|FLAGS_UPPER;
  414. break;
  415. default:
  416. vto[i].type = FORMAT_UNKNOWN;
  417. break;
  418. } /* switch */
  419. vto[i].flags = flags;
  420. vto[i].width = width;
  421. vto[i].precision = precision;
  422. if(flags & FLAGS_WIDTHPARAM) {
  423. /* we have the width specified from a parameter, so we make that
  424. parameter's info setup properly */
  425. long k = width - 1;
  426. if((k < 0) || (k >= MAX_PARAMETERS))
  427. /* out of allowed range */
  428. return 1;
  429. vto[i].width = k;
  430. vto[k].type = FORMAT_WIDTH;
  431. vto[k].flags = FLAGS_NEW;
  432. /* can't use width or precision of width! */
  433. vto[k].width = 0;
  434. vto[k].precision = 0;
  435. }
  436. if(flags & FLAGS_PRECPARAM) {
  437. /* we have the precision specified from a parameter, so we make that
  438. parameter's info setup properly */
  439. long k = precision - 1;
  440. if((k < 0) || (k >= MAX_PARAMETERS))
  441. /* out of allowed range */
  442. return 1;
  443. vto[i].precision = k;
  444. vto[k].type = FORMAT_WIDTH;
  445. vto[k].flags = FLAGS_NEW;
  446. /* can't use width or precision of width! */
  447. vto[k].width = 0;
  448. vto[k].precision = 0;
  449. }
  450. *endpos++ = fmt + ((*fmt == '\0') ? 0 : 1); /* end of this sequence */
  451. }
  452. }
  453. /* Read the arg list parameters into our data list */
  454. for(i = 0; i<max_param; i++) {
  455. /* Width/precision arguments must be read before the main argument
  456. they are attached to */
  457. if(vto[i].flags & FLAGS_WIDTHPARAM) {
  458. vto[vto[i].width].data.num.as_signed =
  459. (mp_intmax_t)va_arg(arglist, int);
  460. }
  461. if(vto[i].flags & FLAGS_PRECPARAM) {
  462. vto[vto[i].precision].data.num.as_signed =
  463. (mp_intmax_t)va_arg(arglist, int);
  464. }
  465. switch(vto[i].type) {
  466. case FORMAT_STRING:
  467. vto[i].data.str = va_arg(arglist, char *);
  468. break;
  469. case FORMAT_INTPTR:
  470. case FORMAT_UNKNOWN:
  471. case FORMAT_PTR:
  472. vto[i].data.ptr = va_arg(arglist, void *);
  473. break;
  474. case FORMAT_INT:
  475. #ifdef HAVE_LONG_LONG_TYPE
  476. if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
  477. vto[i].data.num.as_unsigned =
  478. (mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
  479. else if(vto[i].flags & FLAGS_LONGLONG)
  480. vto[i].data.num.as_signed =
  481. (mp_intmax_t)va_arg(arglist, mp_intmax_t);
  482. else
  483. #endif
  484. {
  485. if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
  486. vto[i].data.num.as_unsigned =
  487. (mp_uintmax_t)va_arg(arglist, unsigned long);
  488. else if(vto[i].flags & FLAGS_LONG)
  489. vto[i].data.num.as_signed =
  490. (mp_intmax_t)va_arg(arglist, long);
  491. else if(vto[i].flags & FLAGS_UNSIGNED)
  492. vto[i].data.num.as_unsigned =
  493. (mp_uintmax_t)va_arg(arglist, unsigned int);
  494. else
  495. vto[i].data.num.as_signed =
  496. (mp_intmax_t)va_arg(arglist, int);
  497. }
  498. break;
  499. case FORMAT_DOUBLE:
  500. vto[i].data.dnum = va_arg(arglist, double);
  501. break;
  502. case FORMAT_WIDTH:
  503. /* Argument has been read. Silently convert it into an integer
  504. * for later use
  505. */
  506. vto[i].type = FORMAT_INT;
  507. break;
  508. default:
  509. break;
  510. }
  511. }
  512. return 0;
  513. }
  514. static int dprintf_formatf(
  515. void *data, /* untouched by format(), just sent to the stream() function in
  516. the second argument */
  517. /* function pointer called for each output character */
  518. int (*stream)(int, FILE *),
  519. const char *format, /* %-formatted string */
  520. va_list ap_save) /* list of parameters */
  521. {
  522. /* Base-36 digits for numbers. */
  523. const char *digits = lower_digits;
  524. /* Pointer into the format string. */
  525. char *f;
  526. /* Number of characters written. */
  527. int done = 0;
  528. long param; /* current parameter to read */
  529. long param_num = 0; /* parameter counter */
  530. struct va_stack vto[MAX_PARAMETERS];
  531. char *endpos[MAX_PARAMETERS];
  532. char **end;
  533. char work[BUFFSIZE];
  534. struct va_stack *p;
  535. /* 'workend' points to the final buffer byte position, but with an extra
  536. byte as margin to avoid the (false?) warning Coverity gives us
  537. otherwise */
  538. char *workend = &work[sizeof(work) - 2];
  539. /* Do the actual %-code parsing */
  540. if(dprintf_Pass1(format, vto, endpos, ap_save))
  541. return 0;
  542. end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
  543. created for us */
  544. f = (char *)format;
  545. while(*f != '\0') {
  546. /* Format spec modifiers. */
  547. int is_alt;
  548. /* Width of a field. */
  549. long width;
  550. /* Precision of a field. */
  551. long prec;
  552. /* Decimal integer is negative. */
  553. int is_neg;
  554. /* Base of a number to be written. */
  555. unsigned long base;
  556. /* Integral values to be written. */
  557. mp_uintmax_t num;
  558. /* Used to convert negative in positive. */
  559. mp_intmax_t signed_num;
  560. char *w;
  561. if(*f != '%') {
  562. /* This isn't a format spec, so write everything out until the next one
  563. OR end of string is reached. */
  564. do {
  565. OUTCHAR(*f);
  566. } while(*++f && ('%' != *f));
  567. continue;
  568. }
  569. ++f;
  570. /* Check for "%%". Note that although the ANSI standard lists
  571. '%' as a conversion specifier, it says "The complete format
  572. specification shall be `%%'," so we can avoid all the width
  573. and precision processing. */
  574. if(*f == '%') {
  575. ++f;
  576. OUTCHAR('%');
  577. continue;
  578. }
  579. /* If this is a positional parameter, the position must follow immediately
  580. after the %, thus create a %<num>$ sequence */
  581. param = dprintf_DollarString(f, &f);
  582. if(!param)
  583. param = param_num;
  584. else
  585. --param;
  586. param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
  587. third %s will pick the 3rd argument */
  588. p = &vto[param];
  589. /* pick up the specified width */
  590. if(p->flags & FLAGS_WIDTHPARAM) {
  591. width = (long)vto[p->width].data.num.as_signed;
  592. param_num++; /* since the width is extracted from a parameter, we
  593. must skip that to get to the next one properly */
  594. if(width < 0) {
  595. /* "A negative field width is taken as a '-' flag followed by a
  596. positive field width." */
  597. width = -width;
  598. p->flags |= FLAGS_LEFT;
  599. p->flags &= ~FLAGS_PAD_NIL;
  600. }
  601. }
  602. else
  603. width = p->width;
  604. /* pick up the specified precision */
  605. if(p->flags & FLAGS_PRECPARAM) {
  606. prec = (long)vto[p->precision].data.num.as_signed;
  607. param_num++; /* since the precision is extracted from a parameter, we
  608. must skip that to get to the next one properly */
  609. if(prec < 0)
  610. /* "A negative precision is taken as if the precision were
  611. omitted." */
  612. prec = -1;
  613. }
  614. else if(p->flags & FLAGS_PREC)
  615. prec = p->precision;
  616. else
  617. prec = -1;
  618. is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
  619. switch(p->type) {
  620. case FORMAT_INT:
  621. num = p->data.num.as_unsigned;
  622. if(p->flags & FLAGS_CHAR) {
  623. /* Character. */
  624. if(!(p->flags & FLAGS_LEFT))
  625. while(--width > 0)
  626. OUTCHAR(' ');
  627. OUTCHAR((char) num);
  628. if(p->flags & FLAGS_LEFT)
  629. while(--width > 0)
  630. OUTCHAR(' ');
  631. break;
  632. }
  633. if(p->flags & FLAGS_OCTAL) {
  634. /* Octal unsigned integer. */
  635. base = 8;
  636. goto unsigned_number;
  637. }
  638. else if(p->flags & FLAGS_HEX) {
  639. /* Hexadecimal unsigned integer. */
  640. digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
  641. base = 16;
  642. goto unsigned_number;
  643. }
  644. else if(p->flags & FLAGS_UNSIGNED) {
  645. /* Decimal unsigned integer. */
  646. base = 10;
  647. goto unsigned_number;
  648. }
  649. /* Decimal integer. */
  650. base = 10;
  651. is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
  652. if(is_neg) {
  653. /* signed_num might fail to hold absolute negative minimum by 1 */
  654. signed_num = p->data.num.as_signed + (mp_intmax_t)1;
  655. signed_num = -signed_num;
  656. num = (mp_uintmax_t)signed_num;
  657. num += (mp_uintmax_t)1;
  658. }
  659. goto number;
  660. unsigned_number:
  661. /* Unsigned number of base BASE. */
  662. is_neg = 0;
  663. number:
  664. /* Number of base BASE. */
  665. /* Supply a default precision if none was given. */
  666. if(prec == -1)
  667. prec = 1;
  668. /* Put the number in WORK. */
  669. w = workend;
  670. while(num > 0) {
  671. *w-- = digits[num % base];
  672. num /= base;
  673. }
  674. width -= (long)(workend - w);
  675. prec -= (long)(workend - w);
  676. if(is_alt && base == 8 && prec <= 0) {
  677. *w-- = '0';
  678. --width;
  679. }
  680. if(prec > 0) {
  681. width -= prec;
  682. while(prec-- > 0 && w >= work)
  683. *w-- = '0';
  684. }
  685. if(is_alt && base == 16)
  686. width -= 2;
  687. if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
  688. --width;
  689. if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
  690. while(width-- > 0)
  691. OUTCHAR(' ');
  692. if(is_neg)
  693. OUTCHAR('-');
  694. else if(p->flags & FLAGS_SHOWSIGN)
  695. OUTCHAR('+');
  696. else if(p->flags & FLAGS_SPACE)
  697. OUTCHAR(' ');
  698. if(is_alt && base == 16) {
  699. OUTCHAR('0');
  700. if(p->flags & FLAGS_UPPER)
  701. OUTCHAR('X');
  702. else
  703. OUTCHAR('x');
  704. }
  705. if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
  706. while(width-- > 0)
  707. OUTCHAR('0');
  708. /* Write the number. */
  709. while(++w <= workend) {
  710. OUTCHAR(*w);
  711. }
  712. if(p->flags & FLAGS_LEFT)
  713. while(width-- > 0)
  714. OUTCHAR(' ');
  715. break;
  716. case FORMAT_STRING:
  717. /* String. */
  718. {
  719. static const char null[] = "(nil)";
  720. const char *str;
  721. size_t len;
  722. str = (char *) p->data.str;
  723. if(!str) {
  724. /* Write null[] if there's space. */
  725. if(prec == -1 || prec >= (long) sizeof(null) - 1) {
  726. str = null;
  727. len = sizeof(null) - 1;
  728. /* Disable quotes around (nil) */
  729. p->flags &= (~FLAGS_ALT);
  730. }
  731. else {
  732. str = "";
  733. len = 0;
  734. }
  735. }
  736. else if(prec != -1)
  737. len = (size_t)prec;
  738. else if(*str == '\0')
  739. len = 0;
  740. else
  741. len = strlen(str);
  742. width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
  743. if(p->flags & FLAGS_ALT)
  744. OUTCHAR('"');
  745. if(!(p->flags&FLAGS_LEFT))
  746. while(width-- > 0)
  747. OUTCHAR(' ');
  748. for(; len && *str; len--)
  749. OUTCHAR(*str++);
  750. if(p->flags&FLAGS_LEFT)
  751. while(width-- > 0)
  752. OUTCHAR(' ');
  753. if(p->flags & FLAGS_ALT)
  754. OUTCHAR('"');
  755. }
  756. break;
  757. case FORMAT_PTR:
  758. /* Generic pointer. */
  759. {
  760. void *ptr;
  761. ptr = (void *) p->data.ptr;
  762. if(ptr) {
  763. /* If the pointer is not NULL, write it as a %#x spec. */
  764. base = 16;
  765. digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
  766. is_alt = 1;
  767. num = (size_t) ptr;
  768. is_neg = 0;
  769. goto number;
  770. }
  771. else {
  772. /* Write "(nil)" for a nil pointer. */
  773. static const char strnil[] = "(nil)";
  774. const char *point;
  775. width -= (long)(sizeof(strnil) - 1);
  776. if(p->flags & FLAGS_LEFT)
  777. while(width-- > 0)
  778. OUTCHAR(' ');
  779. for(point = strnil; *point != '\0'; ++point)
  780. OUTCHAR(*point);
  781. if(!(p->flags & FLAGS_LEFT))
  782. while(width-- > 0)
  783. OUTCHAR(' ');
  784. }
  785. }
  786. break;
  787. case FORMAT_DOUBLE:
  788. {
  789. char formatbuf[32]="%";
  790. char *fptr = &formatbuf[1];
  791. size_t left = sizeof(formatbuf)-strlen(formatbuf);
  792. int len;
  793. width = -1;
  794. if(p->flags & FLAGS_WIDTH)
  795. width = p->width;
  796. else if(p->flags & FLAGS_WIDTHPARAM)
  797. width = (long)vto[p->width].data.num.as_signed;
  798. prec = -1;
  799. if(p->flags & FLAGS_PREC)
  800. prec = p->precision;
  801. else if(p->flags & FLAGS_PRECPARAM)
  802. prec = (long)vto[p->precision].data.num.as_signed;
  803. if(p->flags & FLAGS_LEFT)
  804. *fptr++ = '-';
  805. if(p->flags & FLAGS_SHOWSIGN)
  806. *fptr++ = '+';
  807. if(p->flags & FLAGS_SPACE)
  808. *fptr++ = ' ';
  809. if(p->flags & FLAGS_ALT)
  810. *fptr++ = '#';
  811. *fptr = 0;
  812. if(width >= 0) {
  813. if(width >= (long)sizeof(work))
  814. width = sizeof(work)-1;
  815. /* RECURSIVE USAGE */
  816. len = curl_msnprintf(fptr, left, "%ld", width);
  817. fptr += len;
  818. left -= len;
  819. }
  820. if(prec >= 0) {
  821. /* for each digit in the integer part, we can have one less
  822. precision */
  823. size_t maxprec = sizeof(work) - 2;
  824. double val = p->data.dnum;
  825. if(width > 0 && prec <= width)
  826. maxprec -= width;
  827. while(val >= 10.0) {
  828. val /= 10;
  829. maxprec--;
  830. }
  831. if(prec > (long)maxprec)
  832. prec = (long)maxprec-1;
  833. if(prec < 0)
  834. prec = 0;
  835. /* RECURSIVE USAGE */
  836. len = curl_msnprintf(fptr, left, ".%ld", prec);
  837. fptr += len;
  838. }
  839. if(p->flags & FLAGS_LONG)
  840. *fptr++ = 'l';
  841. if(p->flags & FLAGS_FLOATE)
  842. *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
  843. else if(p->flags & FLAGS_FLOATG)
  844. *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
  845. else
  846. *fptr++ = 'f';
  847. *fptr = 0; /* and a final null-termination */
  848. #ifdef __clang__
  849. #pragma clang diagnostic push
  850. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  851. #endif
  852. /* NOTE NOTE NOTE!! Not all sprintf implementations return number of
  853. output characters */
  854. #ifdef HAVE_SNPRINTF
  855. (snprintf)(work, sizeof(work), formatbuf, p->data.dnum);
  856. #else
  857. (sprintf)(work, formatbuf, p->data.dnum);
  858. #endif
  859. #ifdef __clang__
  860. #pragma clang diagnostic pop
  861. #endif
  862. DEBUGASSERT(strlen(work) <= sizeof(work));
  863. for(fptr = work; *fptr; fptr++)
  864. OUTCHAR(*fptr);
  865. }
  866. break;
  867. case FORMAT_INTPTR:
  868. /* Answer the count of characters written. */
  869. #ifdef HAVE_LONG_LONG_TYPE
  870. if(p->flags & FLAGS_LONGLONG)
  871. *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
  872. else
  873. #endif
  874. if(p->flags & FLAGS_LONG)
  875. *(long *) p->data.ptr = (long)done;
  876. else if(!(p->flags & FLAGS_SHORT))
  877. *(int *) p->data.ptr = (int)done;
  878. else
  879. *(short *) p->data.ptr = (short)done;
  880. break;
  881. default:
  882. break;
  883. }
  884. f = *end++; /* goto end of %-code */
  885. }
  886. return done;
  887. }
  888. /* fputc() look-alike */
  889. static int addbyter(int output, FILE *data)
  890. {
  891. struct nsprintf *infop = (struct nsprintf *)data;
  892. unsigned char outc = (unsigned char)output;
  893. if(infop->length < infop->max) {
  894. /* only do this if we haven't reached max length yet */
  895. infop->buffer[0] = outc; /* store */
  896. infop->buffer++; /* increase pointer */
  897. infop->length++; /* we are now one byte larger */
  898. return outc; /* fputc() returns like this on success */
  899. }
  900. return -1;
  901. }
  902. int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
  903. va_list ap_save)
  904. {
  905. int retcode;
  906. struct nsprintf info;
  907. info.buffer = buffer;
  908. info.length = 0;
  909. info.max = maxlength;
  910. retcode = dprintf_formatf(&info, addbyter, format, ap_save);
  911. if(info.max) {
  912. /* we terminate this with a zero byte */
  913. if(info.max == info.length) {
  914. /* we're at maximum, scrap the last letter */
  915. info.buffer[-1] = 0;
  916. DEBUGASSERT(retcode);
  917. retcode--; /* don't count the nul byte */
  918. }
  919. else
  920. info.buffer[0] = 0;
  921. }
  922. return retcode;
  923. }
  924. int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
  925. {
  926. int retcode;
  927. va_list ap_save; /* argument pointer */
  928. va_start(ap_save, format);
  929. retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
  930. va_end(ap_save);
  931. return retcode;
  932. }
  933. /* fputc() look-alike */
  934. static int alloc_addbyter(int output, FILE *data)
  935. {
  936. struct asprintf *infop = (struct asprintf *)data;
  937. unsigned char outc = (unsigned char)output;
  938. if(Curl_dyn_addn(infop->b, &outc, 1)) {
  939. infop->fail = 1;
  940. return -1; /* fail */
  941. }
  942. return outc; /* fputc() returns like this on success */
  943. }
  944. extern int Curl_dyn_vprintf(struct dynbuf *dyn,
  945. const char *format, va_list ap_save);
  946. /* appends the formatted string, returns 0 on success, 1 on error */
  947. int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save)
  948. {
  949. struct asprintf info;
  950. info.b = dyn;
  951. info.fail = 0;
  952. (void)dprintf_formatf(&info, alloc_addbyter, format, ap_save);
  953. if(info.fail) {
  954. Curl_dyn_free(info.b);
  955. return 1;
  956. }
  957. return 0;
  958. }
  959. char *curl_mvaprintf(const char *format, va_list ap_save)
  960. {
  961. struct asprintf info;
  962. struct dynbuf dyn;
  963. info.b = &dyn;
  964. Curl_dyn_init(info.b, DYN_APRINTF);
  965. info.fail = 0;
  966. (void)dprintf_formatf(&info, alloc_addbyter, format, ap_save);
  967. if(info.fail) {
  968. Curl_dyn_free(info.b);
  969. return NULL;
  970. }
  971. if(Curl_dyn_len(info.b))
  972. return Curl_dyn_ptr(info.b);
  973. return strdup("");
  974. }
  975. char *curl_maprintf(const char *format, ...)
  976. {
  977. va_list ap_save;
  978. char *s;
  979. va_start(ap_save, format);
  980. s = curl_mvaprintf(format, ap_save);
  981. va_end(ap_save);
  982. return s;
  983. }
  984. static int storebuffer(int output, FILE *data)
  985. {
  986. char **buffer = (char **)data;
  987. unsigned char outc = (unsigned char)output;
  988. **buffer = outc;
  989. (*buffer)++;
  990. return outc; /* act like fputc() ! */
  991. }
  992. int curl_msprintf(char *buffer, const char *format, ...)
  993. {
  994. va_list ap_save; /* argument pointer */
  995. int retcode;
  996. va_start(ap_save, format);
  997. retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
  998. va_end(ap_save);
  999. *buffer = 0; /* we terminate this with a zero byte */
  1000. return retcode;
  1001. }
  1002. int curl_mprintf(const char *format, ...)
  1003. {
  1004. int retcode;
  1005. va_list ap_save; /* argument pointer */
  1006. va_start(ap_save, format);
  1007. retcode = dprintf_formatf(stdout, fputc, format, ap_save);
  1008. va_end(ap_save);
  1009. return retcode;
  1010. }
  1011. int curl_mfprintf(FILE *whereto, const char *format, ...)
  1012. {
  1013. int retcode;
  1014. va_list ap_save; /* argument pointer */
  1015. va_start(ap_save, format);
  1016. retcode = dprintf_formatf(whereto, fputc, format, ap_save);
  1017. va_end(ap_save);
  1018. return retcode;
  1019. }
  1020. int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
  1021. {
  1022. int retcode;
  1023. retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
  1024. *buffer = 0; /* we terminate this with a zero byte */
  1025. return retcode;
  1026. }
  1027. int curl_mvprintf(const char *format, va_list ap_save)
  1028. {
  1029. return dprintf_formatf(stdout, fputc, format, ap_save);
  1030. }
  1031. int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
  1032. {
  1033. return dprintf_formatf(whereto, fputc, format, ap_save);
  1034. }