mprintf.c 30 KB

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