mprintf.c 30 KB

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