mprintf.c 32 KB

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