mprintf.c 30 KB

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