mprintf.c 31 KB

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