mprintf.c 30 KB

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