mprintf.c 30 KB

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