mprintf.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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. return strdup("");
  959. }
  960. char *curl_mvaprintf(const char *format, va_list ap_save)
  961. {
  962. int retcode;
  963. struct asprintf info;
  964. info.buffer = NULL;
  965. info.len = 0;
  966. info.alloc = 0;
  967. info.fail = 0;
  968. retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
  969. if((-1 == retcode) || info.fail) {
  970. if(info.alloc)
  971. free(info.buffer);
  972. return NULL;
  973. }
  974. if(info.alloc) {
  975. info.buffer[info.len] = 0; /* we terminate this with a zero byte */
  976. return info.buffer;
  977. }
  978. return strdup("");
  979. }
  980. static int storebuffer(int output, FILE *data)
  981. {
  982. char **buffer = (char **)data;
  983. unsigned char outc = (unsigned char)output;
  984. **buffer = outc;
  985. (*buffer)++;
  986. return outc; /* act like fputc() ! */
  987. }
  988. int curl_msprintf(char *buffer, const char *format, ...)
  989. {
  990. va_list ap_save; /* argument pointer */
  991. int retcode;
  992. va_start(ap_save, format);
  993. retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
  994. va_end(ap_save);
  995. *buffer=0; /* we terminate this with a zero byte */
  996. return retcode;
  997. }
  998. int curl_mprintf(const char *format, ...)
  999. {
  1000. int retcode;
  1001. va_list ap_save; /* argument pointer */
  1002. va_start(ap_save, format);
  1003. retcode = dprintf_formatf(stdout, fputc, format, ap_save);
  1004. va_end(ap_save);
  1005. return retcode;
  1006. }
  1007. int curl_mfprintf(FILE *whereto, const char *format, ...)
  1008. {
  1009. int retcode;
  1010. va_list ap_save; /* argument pointer */
  1011. va_start(ap_save, format);
  1012. retcode = dprintf_formatf(whereto, fputc, format, ap_save);
  1013. va_end(ap_save);
  1014. return retcode;
  1015. }
  1016. int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
  1017. {
  1018. int retcode;
  1019. retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
  1020. *buffer=0; /* we terminate this with a zero byte */
  1021. return retcode;
  1022. }
  1023. int curl_mvprintf(const char *format, va_list ap_save)
  1024. {
  1025. return dprintf_formatf(stdout, fputc, format, ap_save);
  1026. }
  1027. int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
  1028. {
  1029. return dprintf_formatf(whereto, fputc, format, ap_save);
  1030. }