mprintf.c 29 KB

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