mprintf.c 30 KB

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