2
0

mprintf.c 29 KB

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