mprintf.c 30 KB

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