cbprintf_complete.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. /*
  2. * Copyright (c) 1997-2010, 2012-2015 Wind River Systems, Inc.
  3. * Copyright (c) 2020 Nordic Semiconductor ASA
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. */
  7. #include <ctype.h>
  8. #include <errno.h>
  9. #include <inttypes.h>
  10. #include <limits.h>
  11. #include <stdarg.h>
  12. #include <stdbool.h>
  13. #include <stddef.h>
  14. #include <stdint.h>
  15. #include <string.h>
  16. #include <toolchain.h>
  17. #include <sys/types.h>
  18. #include <sys/util.h>
  19. #include <sys/cbprintf.h>
  20. /* newlib doesn't declare this function unless __POSIX_VISIBLE >= 200809. No
  21. * idea how to make that happen, so lets put it right here.
  22. */
  23. size_t strnlen(const char *s, size_t maxlen);
  24. /* Provide typedefs used for signed and unsigned integral types
  25. * capable of holding all convertable integral values.
  26. */
  27. #ifdef CONFIG_CBPRINTF_FULL_INTEGRAL
  28. typedef intmax_t sint_value_type;
  29. typedef uintmax_t uint_value_type;
  30. #else
  31. typedef int32_t sint_value_type;
  32. typedef uint32_t uint_value_type;
  33. #endif
  34. /* The maximum buffer size required is for octal formatting: one character for
  35. * every 3 bits. Neither EOS nor alternate forms are required.
  36. */
  37. #define CONVERTED_INT_BUFLEN ((CHAR_BIT * sizeof(uint_value_type) + 2) / 3)
  38. /* The float code may extract up to 16 digits, plus a prefix, a
  39. * leading 0, a dot, and an exponent in the form e+xxx for a total of
  40. * 24. Add a trailing NULL so the buffer length required is 25.
  41. */
  42. #define CONVERTED_FP_BUFLEN 25U
  43. #ifdef CONFIG_CBPRINTF_FP_SUPPORT
  44. #define CONVERTED_BUFLEN MAX(CONVERTED_INT_BUFLEN, CONVERTED_FP_BUFLEN)
  45. #else
  46. #define CONVERTED_BUFLEN CONVERTED_INT_BUFLEN
  47. #endif
  48. /* The allowed types of length modifier. */
  49. enum length_mod_enum {
  50. LENGTH_NONE, /* int */
  51. LENGTH_HH, /* char */
  52. LENGTH_H, /* short */
  53. LENGTH_L, /* long */
  54. LENGTH_LL, /* long long */
  55. LENGTH_J, /* intmax */
  56. LENGTH_Z, /* size_t */
  57. LENGTH_T, /* ptrdiff_t */
  58. LENGTH_UPPER_L, /* long double */
  59. };
  60. /* Categories of conversion specifiers. */
  61. enum specifier_cat_enum {
  62. /* unrecognized */
  63. SPECIFIER_INVALID,
  64. /* d, i */
  65. SPECIFIER_SINT,
  66. /* c, o, u, x, X */
  67. SPECIFIER_UINT,
  68. /* n, p, s */
  69. SPECIFIER_PTR,
  70. /* a, A, e, E, f, F, g, G */
  71. SPECIFIER_FP,
  72. };
  73. #define CHAR_IS_SIGNED (CHAR_MIN != 0)
  74. #if CHAR_IS_SIGNED
  75. #define CASE_SINT_CHAR case 'c':
  76. #define CASE_UINT_CHAR
  77. #else
  78. #define CASE_SINT_CHAR
  79. #define CASE_UINT_CHAR case 'c':
  80. #endif
  81. /* We need two pieces of information about wchar_t:
  82. * * WCHAR_IS_SIGNED: whether it's signed or unsigned;
  83. * * WINT_TYPE: the type to use when extracting it from va_args
  84. *
  85. * The former can be determined from the value of WCHAR_MIN if it's defined.
  86. * It's not for minimal libc, so treat it as whatever char is.
  87. *
  88. * The latter should be wint_t, but minimal libc doesn't provide it. We can
  89. * substitute wchar_t as long as that type does not undergo default integral
  90. * promotion as an argument. But it does for at least one toolchain (xtensa),
  91. * and where it does we need to use the promoted type in va_arg() to avoid
  92. * build errors, otherwise we can use the base type. We can tell that
  93. * integral promotion occurs if WCHAR_MAX is strictly less than INT_MAX.
  94. */
  95. #ifndef WCHAR_MIN
  96. #define WCHAR_IS_SIGNED CHAR_IS_SIGNED
  97. #if WCHAR_IS_SIGNED
  98. #define WINT_TYPE int
  99. #else /* wchar signed */
  100. #define WINT_TYPE unsigned int
  101. #endif /* wchar signed */
  102. #else /* WCHAR_MIN defined */
  103. #define WCHAR_IS_SIGNED ((WCHAR_MIN - 0) != 0)
  104. #if WCHAR_MAX < INT_MAX
  105. /* Signed or unsigned, it'll be int */
  106. #define WINT_TYPE int
  107. #else /* wchar rank vs int */
  108. #define WINT_TYPE wchar_t
  109. #endif /* wchar rank vs int */
  110. #endif /* WCHAR_MIN defined */
  111. /* Case label to identify conversions for signed integral values. The
  112. * corresponding argument_value tag is sint and category is
  113. * SPECIFIER_SINT.
  114. */
  115. #define SINT_CONV_CASES \
  116. 'd': \
  117. CASE_SINT_CHAR \
  118. case 'i'
  119. /* Case label to identify conversions for signed integral arguments.
  120. * The corresponding argument_value tag is uint and category is
  121. * SPECIFIER_UINT.
  122. */
  123. #define UINT_CONV_CASES \
  124. 'o': \
  125. CASE_UINT_CHAR \
  126. case 'u': \
  127. case 'x': \
  128. case 'X'
  129. /* Case label to identify conversions for floating point arguments.
  130. * The corresponding argument_value tag is either dbl or ldbl,
  131. * depending on length modifier, and the category is SPECIFIER_FP.
  132. */
  133. #define FP_CONV_CASES \
  134. 'a': \
  135. case 'A': \
  136. case 'e': \
  137. case 'E': \
  138. case 'f': \
  139. case 'F': \
  140. case 'g': \
  141. case 'G'
  142. /* Case label to identify conversions for pointer arguments. The
  143. * corresponding argument_value tag is ptr and the category is
  144. * SPECIFIER_PTR.
  145. */
  146. #define PTR_CONV_CASES \
  147. 'n': \
  148. case 'p': \
  149. case 's'
  150. /* Storage for an argument value. */
  151. union argument_value {
  152. /* For SINT conversions */
  153. sint_value_type sint;
  154. /* For UINT conversions */
  155. uint_value_type uint;
  156. /* For FP conversions without L length */
  157. double dbl;
  158. /* For FP conversions with L length */
  159. long double ldbl;
  160. /* For PTR conversions */
  161. void *ptr;
  162. };
  163. /* Structure capturing all attributes of a conversion
  164. * specification.
  165. *
  166. * Initial values come from the specification, but are updated during
  167. * the conversion.
  168. */
  169. struct conversion {
  170. /** Indicates flags are inconsistent */
  171. bool invalid: 1;
  172. /** Indicates flags are valid but not supported */
  173. bool unsupported: 1;
  174. /** Left-justify value in width */
  175. bool flag_dash: 1;
  176. /** Explicit sign */
  177. bool flag_plus: 1;
  178. /** Space for non-negative sign */
  179. bool flag_space: 1;
  180. /** Alternative form */
  181. bool flag_hash: 1;
  182. /** Pad with leading zeroes */
  183. bool flag_zero: 1;
  184. /** Width field present */
  185. bool width_present: 1;
  186. /** Width value from int argument
  187. *
  188. * width_value is set to the absolute value of the argument.
  189. * If the argument is negative flag_dash is also set.
  190. */
  191. bool width_star: 1;
  192. /** Precision field present */
  193. bool prec_present: 1;
  194. /** Precision from int argument
  195. *
  196. * prec_value is set to the value of a non-negative argument.
  197. * If the argument is negative prec_present is cleared.
  198. */
  199. bool prec_star: 1;
  200. /** Length modifier (value from length_mod_enum) */
  201. unsigned int length_mod: 4;
  202. /** Indicates an a or A conversion specifier.
  203. *
  204. * This affects how precision is handled.
  205. */
  206. bool specifier_a: 1;
  207. /** Conversion specifier category (value from specifier_cat_enum) */
  208. unsigned int specifier_cat: 3;
  209. /** If set alternate form requires 0 before octal. */
  210. bool altform_0: 1;
  211. /** If set alternate form requires 0x before hex. */
  212. bool altform_0c: 1;
  213. /** Set when pad0_value zeroes are to be to be inserted after
  214. * the decimal point in a floating point conversion.
  215. */
  216. bool pad_postdp: 1;
  217. /** Set for floating point values that have a non-zero
  218. * pad0_prefix or pad0_pre_exp.
  219. */
  220. bool pad_fp: 1;
  221. /** Conversion specifier character */
  222. unsigned char specifier;
  223. union {
  224. /** Width value from specification.
  225. *
  226. * Valid until conversion begins.
  227. */
  228. int width_value;
  229. /** Number of extra zeroes to be inserted around a
  230. * formatted value:
  231. *
  232. * * before a formatted integer value due to precision
  233. * and flag_zero; or
  234. * * before a floating point mantissa decimal point
  235. * due to precision; or
  236. * * after a floating point mantissa decimal point due
  237. * to precision.
  238. *
  239. * For example for zero-padded hexadecimal integers
  240. * this would insert where the angle brackets are in:
  241. * 0x<>hhhh.
  242. *
  243. * For floating point numbers this would insert at
  244. * either <1> or <2> depending on #pad_postdp:
  245. * VVV<1>.<2>FFFFeEEE
  246. *
  247. * Valid after conversion begins.
  248. */
  249. int pad0_value;
  250. };
  251. union {
  252. /** Precision from specification.
  253. *
  254. * Valid until conversion begins.
  255. */
  256. int prec_value;
  257. /** Number of extra zeros to be inserted after a decimal
  258. * point due to precision.
  259. *
  260. * Inserts at <> in: VVVV.FFFF<>eEE
  261. *
  262. * Valid after conversion begins.
  263. */
  264. int pad0_pre_exp;
  265. };
  266. };
  267. /** Get a size represented as a sequence of decimal digits.
  268. *
  269. * @param[inout] str where to read from. Updated to point to the first
  270. * unconsumed character. There must be at least one non-digit character in
  271. * the referenced text.
  272. *
  273. * @return the decoded integer value.
  274. */
  275. static size_t extract_decimal(const char **str)
  276. {
  277. const char *sp = *str;
  278. size_t val = 0;
  279. while (isdigit((int)(unsigned char)*sp)) {
  280. val = 10U * val + *sp++ - '0';
  281. }
  282. *str = sp;
  283. return val;
  284. }
  285. /** Extract C99 conversion specification flags.
  286. *
  287. * @param conv pointer to the conversion being defined.
  288. *
  289. * @param sp pointer to the first character after the % of a conversion
  290. * specifier.
  291. *
  292. * @return a pointer the first character that follows the flags.
  293. */
  294. static inline const char *extract_flags(struct conversion *conv,
  295. const char *sp)
  296. {
  297. bool loop = true;
  298. do {
  299. switch (*sp) {
  300. case '-':
  301. conv->flag_dash = true;
  302. break;
  303. case '+':
  304. conv->flag_plus = true;
  305. break;
  306. case ' ':
  307. conv->flag_space = true;
  308. break;
  309. case '#':
  310. conv->flag_hash = true;
  311. break;
  312. case '0':
  313. conv->flag_zero = true;
  314. break;
  315. default:
  316. loop = false;
  317. }
  318. if (loop) {
  319. ++sp;
  320. }
  321. } while (loop);
  322. /* zero && dash => !zero */
  323. if (conv->flag_zero && conv->flag_dash) {
  324. conv->flag_zero = false;
  325. }
  326. /* space && plus => !plus, handled in emitter code */
  327. return sp;
  328. }
  329. /** Extract a C99 conversion specification width.
  330. *
  331. * @param conv pointer to the conversion being defined.
  332. *
  333. * @param sp pointer to the first character after the flags element of a
  334. * conversion specification.
  335. *
  336. * @return a pointer the first character that follows the width.
  337. */
  338. static inline const char *extract_width(struct conversion *conv,
  339. const char *sp)
  340. {
  341. conv->width_present = true;
  342. if (*sp == '*') {
  343. conv->width_star = true;
  344. return ++sp;
  345. }
  346. const char *wp = sp;
  347. size_t width = extract_decimal(&sp);
  348. if (sp != wp) {
  349. conv->width_present = true;
  350. conv->width_value = width;
  351. conv->unsupported |= ((conv->width_value < 0)
  352. || (width != (size_t)conv->width_value));
  353. }
  354. return sp;
  355. }
  356. /** Extract a C99 conversion specification precision.
  357. *
  358. * @param conv pointer to the conversion being defined.
  359. *
  360. * @param sp pointer to the first character after the width element of a
  361. * conversion specification.
  362. *
  363. * @return a pointer the first character that follows the precision.
  364. */
  365. static inline const char *extract_prec(struct conversion *conv,
  366. const char *sp)
  367. {
  368. conv->prec_present = (*sp == '.');
  369. if (!conv->prec_present) {
  370. return sp;
  371. }
  372. ++sp;
  373. if (*sp == '*') {
  374. conv->prec_star = true;
  375. return ++sp;
  376. }
  377. size_t prec = extract_decimal(&sp);
  378. conv->prec_value = prec;
  379. conv->unsupported |= ((conv->prec_value < 0)
  380. || (prec != (size_t)conv->prec_value));
  381. return sp;
  382. }
  383. /** Extract a C99 conversion specification length.
  384. *
  385. * @param conv pointer to the conversion being defined.
  386. *
  387. * @param sp pointer to the first character after the precision element of a
  388. * conversion specification.
  389. *
  390. * @return a pointer the first character that follows the precision.
  391. */
  392. static inline const char *extract_length(struct conversion *conv,
  393. const char *sp)
  394. {
  395. switch (*sp) {
  396. case 'h':
  397. if (*++sp == 'h') {
  398. conv->length_mod = LENGTH_HH;
  399. ++sp;
  400. } else {
  401. conv->length_mod = LENGTH_H;
  402. }
  403. break;
  404. case 'l':
  405. if (*++sp == 'l') {
  406. conv->length_mod = LENGTH_LL;
  407. ++sp;
  408. } else {
  409. conv->length_mod = LENGTH_L;
  410. }
  411. break;
  412. case 'j':
  413. conv->length_mod = LENGTH_J;
  414. ++sp;
  415. break;
  416. case 'z':
  417. conv->length_mod = LENGTH_Z;
  418. ++sp;
  419. break;
  420. case 't':
  421. conv->length_mod = LENGTH_T;
  422. ++sp;
  423. break;
  424. case 'L':
  425. conv->length_mod = LENGTH_UPPER_L;
  426. ++sp;
  427. /* We recognize and consume these, but can't format
  428. * them.
  429. */
  430. conv->unsupported = true;
  431. break;
  432. default:
  433. conv->length_mod = LENGTH_NONE;
  434. break;
  435. }
  436. return sp;
  437. }
  438. /* Extract a C99 conversion specifier.
  439. *
  440. * This is the character that identifies the representation of the converted
  441. * value.
  442. *
  443. * @param conv pointer to the conversion being defined.
  444. *
  445. * @param sp pointer to the first character after the length element of a
  446. * conversion specification.
  447. *
  448. * @return a pointer the first character that follows the specifier.
  449. */
  450. static inline const char *extract_specifier(struct conversion *conv,
  451. const char *sp)
  452. {
  453. bool unsupported = false;
  454. conv->specifier = *sp++;
  455. switch (conv->specifier) {
  456. case SINT_CONV_CASES:
  457. conv->specifier_cat = SPECIFIER_SINT;
  458. goto int_conv;
  459. case UINT_CONV_CASES:
  460. conv->specifier_cat = SPECIFIER_UINT;
  461. int_conv:
  462. /* L length specifier not acceptable */
  463. if (conv->length_mod == LENGTH_UPPER_L) {
  464. conv->invalid = true;
  465. }
  466. /* For c LENGTH_NONE and LENGTH_L would be ok,
  467. * but we don't support formatting wide characters.
  468. */
  469. if (conv->specifier == 'c') {
  470. unsupported = (conv->length_mod != LENGTH_NONE);
  471. } else if (!IS_ENABLED(CONFIG_CBPRINTF_FULL_INTEGRAL)) {
  472. /* Disable conversion that might produce truncated
  473. * results with buffers sized for 32 bits.
  474. */
  475. switch (conv->length_mod) {
  476. case LENGTH_L:
  477. unsupported = sizeof(long) > 4;
  478. break;
  479. case LENGTH_LL:
  480. unsupported = sizeof(long long) > 4;
  481. break;
  482. case LENGTH_J:
  483. unsupported = sizeof(uintmax_t) > 4;
  484. break;
  485. case LENGTH_Z:
  486. unsupported = sizeof(size_t) > 4;
  487. break;
  488. case LENGTH_T:
  489. unsupported = sizeof(ptrdiff_t) > 4;
  490. break;
  491. default:
  492. /* Add an empty default with break, this is a defensive
  493. * programming. Static analysis tool won't raise a violation
  494. * if default is empty, but has that comment.
  495. */
  496. break;
  497. }
  498. } else {
  499. ;
  500. }
  501. break;
  502. case FP_CONV_CASES:
  503. conv->specifier_cat = SPECIFIER_FP;
  504. /* Don't support if disabled */
  505. if (!IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)) {
  506. unsupported = true;
  507. break;
  508. }
  509. /* When FP enabled %a support is still conditional. */
  510. conv->specifier_a = (conv->specifier == 'a')
  511. || (conv->specifier == 'A');
  512. if (conv->specifier_a
  513. && !IS_ENABLED(CONFIG_CBPRINTF_FP_A_SUPPORT)) {
  514. unsupported = true;
  515. break;
  516. }
  517. /* The l specifier has no effect. Otherwise length
  518. * modifiers other than L are invalid.
  519. */
  520. if (conv->length_mod == LENGTH_L) {
  521. conv->length_mod = LENGTH_NONE;
  522. } else if ((conv->length_mod != LENGTH_NONE)
  523. && (conv->length_mod != LENGTH_UPPER_L)) {
  524. conv->invalid = true;
  525. } else {
  526. ;
  527. }
  528. break;
  529. /* PTR cases are distinct */
  530. case 'n':
  531. conv->specifier_cat = SPECIFIER_PTR;
  532. /* Anything except L */
  533. if (conv->length_mod == LENGTH_UPPER_L) {
  534. unsupported = true;
  535. }
  536. break;
  537. case 's':
  538. case 'p':
  539. conv->specifier_cat = SPECIFIER_PTR;
  540. /* p: only LENGTH_NONE
  541. *
  542. * s: LENGTH_NONE or LENGTH_L but wide
  543. * characters not supported.
  544. */
  545. if (conv->length_mod != LENGTH_NONE) {
  546. unsupported = true;
  547. }
  548. break;
  549. default:
  550. conv->invalid = true;
  551. break;
  552. }
  553. conv->unsupported |= unsupported;
  554. return sp;
  555. }
  556. /* Extract the complete C99 conversion specification.
  557. *
  558. * @param conv pointer to the conversion being defined.
  559. *
  560. * @param sp pointer to the % that introduces a conversion specification.
  561. *
  562. * @return pointer to the first character that follows the specification.
  563. */
  564. static inline const char *extract_conversion(struct conversion *conv,
  565. const char *sp)
  566. {
  567. *conv = (struct conversion) {
  568. .invalid = false,
  569. };
  570. /* Skip over the opening %. If the conversion specifier is %,
  571. * that's the only thing that should be there, so
  572. * fast-exit.
  573. */
  574. ++sp;
  575. if (*sp == '%') {
  576. conv->specifier = *sp++;
  577. return sp;
  578. }
  579. sp = extract_flags(conv, sp);
  580. sp = extract_width(conv, sp);
  581. sp = extract_prec(conv, sp);
  582. sp = extract_length(conv, sp);
  583. sp = extract_specifier(conv, sp);
  584. return sp;
  585. }
  586. #ifdef CONFIG_64BIT
  587. static void _ldiv5(uint64_t *v)
  588. {
  589. /* The compiler can optimize this on its own on 64-bit architectures */
  590. *v /= 5U;
  591. }
  592. #else /* CONFIG_64BIT */
  593. /*
  594. * Tiny integer divide-by-five routine. The full 64 bit division
  595. * implementations in libgcc are very large on some architectures, and
  596. * currently nothing in Zephyr pulls it into the link. So it makes
  597. * sense to define this much smaller special case here to avoid
  598. * including it just for printf.
  599. *
  600. * It works by multiplying v by the reciprocal of 5 i.e.:
  601. *
  602. * result = v * ((1 << 64) / 5) / (1 << 64)
  603. *
  604. * This produces a 128-bit result, but we drop the bottom 64 bits which
  605. * accounts for the division by (1 << 64). The product is kept to 64 bits
  606. * by summing partial multiplications and shifting right by 32 which on
  607. * most 32-bit architectures means only a register drop.
  608. *
  609. * Here the multiplier is: (1 << 64) / 5 = 0x3333333333333333
  610. * i.e. a 62 bits value. To compensate for the reduced precision, we
  611. * add an initial bias of 1 to v. This conveniently allows for keeping
  612. * the multiplier in a single 32-bit register given its pattern.
  613. * Enlarging the multiplier to 64 bits would also work but carry handling
  614. * on the summing of partial mults would be necessary, and a final right
  615. * shift would be needed, requiring more instructions.
  616. */
  617. static void _ldiv5(uint64_t *v)
  618. {
  619. uint32_t v_lo = *v;
  620. uint32_t v_hi = *v >> 32;
  621. uint32_t m = 0x33333333;
  622. uint64_t result;
  623. /*
  624. * Force the multiplier constant into a register and make it
  625. * opaque to the compiler, otherwise gcc tries to be too smart
  626. * for its own good with a large expansion of adds and shifts.
  627. */
  628. __asm__ ("" : "+r" (m));
  629. /*
  630. * Apply a bias of 1 to v. We can't add it to v as this would overflow
  631. * it when at max range. Factor it out with the multiplier upfront.
  632. */
  633. result = ((uint64_t)m << 32) | m;
  634. /* The actual multiplication. */
  635. result += (uint64_t)v_lo * m;
  636. result >>= 32;
  637. result += (uint64_t)v_lo * m;
  638. result += (uint64_t)v_hi * m;
  639. result >>= 32;
  640. result += (uint64_t)v_hi * m;
  641. *v = result;
  642. }
  643. #endif /* CONFIG_64BIT */
  644. /* Division by 10 */
  645. static void _ldiv10(uint64_t *v)
  646. {
  647. *v >>= 1;
  648. _ldiv5(v);
  649. }
  650. /* Extract the next decimal character in the converted representation of a
  651. * fractional component.
  652. */
  653. static char _get_digit(uint64_t *fr, int *digit_count)
  654. {
  655. char rval;
  656. if (*digit_count > 0) {
  657. --*digit_count;
  658. *fr *= 10U;
  659. rval = ((*fr >> 60) & 0xF) + '0';
  660. *fr &= (BIT64(60) - 1U);
  661. } else {
  662. rval = '0';
  663. }
  664. return rval;
  665. }
  666. static inline size_t conversion_radix(char specifier)
  667. {
  668. switch (specifier) {
  669. default:
  670. case 'd':
  671. case 'i':
  672. case 'u':
  673. return 10;
  674. case 'o':
  675. return 8;
  676. case 'p':
  677. case 'x':
  678. case 'X':
  679. return 16;
  680. }
  681. }
  682. /* Writes the given value into the buffer in the specified base.
  683. *
  684. * Precision is applied *ONLY* within the space allowed.
  685. *
  686. * Alternate form value is applied to o, x, and X conversions.
  687. *
  688. * The buffer is filled backwards, so the input bpe is the end of the
  689. * generated representation. The returned pointer is to the first
  690. * character of the representation.
  691. */
  692. static char *encode_uint(uint_value_type value,
  693. struct conversion *conv,
  694. char *bps,
  695. const char *bpe)
  696. {
  697. bool upcase = isupper((int)conv->specifier);
  698. const unsigned int radix = conversion_radix(conv->specifier);
  699. char *bp = bps + (bpe - bps);
  700. do {
  701. unsigned int lsv = (unsigned int)(value % radix);
  702. *--bp = (lsv <= 9) ? ('0' + lsv)
  703. : upcase ? ('A' + lsv - 10) : ('a' + lsv - 10);
  704. value /= radix;
  705. } while ((value != 0) && (bps < bp));
  706. /* Record required alternate forms. This can be determined
  707. * from the radix without re-checking specifier.
  708. */
  709. if (conv->flag_hash) {
  710. if (radix == 8) {
  711. conv->altform_0 = true;
  712. } else if (radix == 16) {
  713. conv->altform_0c = true;
  714. } else {
  715. ;
  716. }
  717. }
  718. return bp;
  719. }
  720. /* Number of bits in the fractional part of an IEEE 754-2008 double
  721. * precision float.
  722. */
  723. #define FRACTION_BITS 52
  724. /* Number of hex "digits" in the fractional part of an IEEE 754-2008
  725. * double precision float.
  726. */
  727. #define FRACTION_HEX ceiling_fraction(FRACTION_BITS, 4)
  728. /* Number of bits in the exponent of an IEEE 754-2008 double precision
  729. * float.
  730. */
  731. #define EXPONENT_BITS 11
  732. /* Mask for the sign (negative) bit of an IEEE 754-2008 double precision
  733. * float.
  734. */
  735. #define SIGN_MASK BIT64(63)
  736. /* Mask for the high-bit of a uint64_t representation of a fractional
  737. * value.
  738. */
  739. #define BIT_63 BIT64(63)
  740. /* Convert the IEEE 754-2008 double to text format.
  741. *
  742. * @param value the 64-bit floating point value.
  743. *
  744. * @param conv details about how the conversion is to proceed. Some fields
  745. * are adjusted based on the value being converted.
  746. *
  747. * @param precision the precision for the conversion (generally digits past
  748. * the decimal point).
  749. *
  750. * @param bps pointer to the first character in a buffer that will hold the
  751. * converted value.
  752. *
  753. * @param bpe On entry this points to the end of the buffer reserved to hold
  754. * the converted value. On exit it is updated to point just past the
  755. * converted value.
  756. *
  757. * return a pointer to the start of the converted value. This may not be @p
  758. * bps but will be consistent with the exit value of *bpe.
  759. */
  760. static char *encode_float(double value,
  761. struct conversion *conv,
  762. int precision,
  763. char *sign,
  764. char *bps,
  765. const char **bpe)
  766. {
  767. union {
  768. uint64_t u64;
  769. double dbl;
  770. } u = {
  771. .dbl = value,
  772. };
  773. bool prune_zero = false;
  774. char *buf = bps;
  775. /* Prepend the sign: '-' if negative, flags control
  776. * non-negative behavior.
  777. */
  778. if ((u.u64 & SIGN_MASK) != 0U) {
  779. *sign = '-';
  780. } else if (conv->flag_plus) {
  781. *sign = '+';
  782. } else if (conv->flag_space) {
  783. *sign = ' ';
  784. } else {
  785. ;
  786. }
  787. /* Extract the non-negative offset exponent and fraction. Record
  788. * whether the value is subnormal.
  789. */
  790. char c = conv->specifier;
  791. int expo = (u.u64 >> FRACTION_BITS) & BIT_MASK(EXPONENT_BITS);
  792. uint64_t fract = u.u64 & BIT64_MASK(FRACTION_BITS);
  793. bool is_subnormal = (expo == 0) && (fract != 0);
  794. /* Exponent of all-ones signals infinity or NaN, which are
  795. * text constants regardless of specifier.
  796. */
  797. if (expo == BIT_MASK(EXPONENT_BITS)) {
  798. if (fract == 0) {
  799. if (isupper((int)c)) {
  800. *buf++ = 'I';
  801. *buf++ = 'N';
  802. *buf++ = 'F';
  803. } else {
  804. *buf++ = 'i';
  805. *buf++ = 'n';
  806. *buf++ = 'f';
  807. }
  808. } else {
  809. if (isupper((int)c)) {
  810. *buf++ = 'N';
  811. *buf++ = 'A';
  812. *buf++ = 'N';
  813. } else {
  814. *buf++ = 'n';
  815. *buf++ = 'a';
  816. *buf++ = 'n';
  817. }
  818. }
  819. /* No zero-padding with text values */
  820. conv->flag_zero = false;
  821. *bpe = buf;
  822. return bps;
  823. }
  824. /* The case of an F specifier is no longer relevant. */
  825. if (c == 'F') {
  826. c = 'f';
  827. }
  828. /* Handle converting to the hex representation. */
  829. if (IS_ENABLED(CONFIG_CBPRINTF_FP_A_SUPPORT)
  830. && (IS_ENABLED(CONFIG_CBPRINTF_FP_ALWAYS_A)
  831. || conv->specifier_a)) {
  832. *buf++ = '0';
  833. *buf++ = 'x';
  834. /* Remove the offset from the exponent, and store the
  835. * non-fractional value. Subnormals require increasing the
  836. * exponent as first bit isn't the implicit bit.
  837. */
  838. expo -= 1023;
  839. if (is_subnormal) {
  840. *buf++ = '0';
  841. ++expo;
  842. } else {
  843. *buf++ = '1';
  844. }
  845. /* If we didn't get precision from a %a specification then we
  846. * treat it as from a %a specification with no precision: full
  847. * range, zero-pruning enabled.
  848. *
  849. * Otherwise we have to cap the precision of the generated
  850. * fraction, or possibly round it.
  851. */
  852. if (!(conv->specifier_a && conv->prec_present)) {
  853. precision = FRACTION_HEX;
  854. prune_zero = true;
  855. } else if (precision > FRACTION_HEX) {
  856. conv->pad0_pre_exp = precision - FRACTION_HEX;
  857. conv->pad_fp = true;
  858. precision = FRACTION_HEX;
  859. } else if ((fract != 0)
  860. && (precision < FRACTION_HEX)) {
  861. size_t pos = 4 * (FRACTION_HEX - precision) - 1;
  862. uint64_t mask = BIT64(pos);
  863. /* Round only if the bit that would round is
  864. * set.
  865. */
  866. if (fract & mask) {
  867. fract += mask;
  868. }
  869. }
  870. /* Record whether we must retain the decimal point even if we
  871. * can prune zeros.
  872. */
  873. bool require_dp = ((fract != 0) || conv->flag_hash);
  874. if (require_dp || (precision != 0)) {
  875. *buf++ = '.';
  876. }
  877. /* Get the fractional value as a hexadecimal string, using x
  878. * for a and X for A.
  879. */
  880. struct conversion aconv = {
  881. .specifier = isupper((int)c) ? 'X' : 'x',
  882. };
  883. const char *spe = *bpe;
  884. char *sp = bps + (spe - bps);
  885. if (fract != 0) {
  886. sp = encode_uint(fract, &aconv, buf, spe);
  887. }
  888. /* Pad out to full range since this is below the decimal
  889. * point.
  890. */
  891. while ((spe - sp) < FRACTION_HEX) {
  892. *--sp = '0';
  893. }
  894. /* Append the leading sigificant "digits". */
  895. while ((sp < spe) && (precision > 0)) {
  896. *buf++ = *sp++;
  897. --precision;
  898. }
  899. if (prune_zero) {
  900. while (*--buf == '0') {
  901. ;
  902. }
  903. if ((*buf != '.') || require_dp) {
  904. ++buf;
  905. }
  906. }
  907. *buf++ = 'p';
  908. if (expo >= 0) {
  909. *buf++ = '+';
  910. } else {
  911. *buf++ = '-';
  912. expo = -expo;
  913. }
  914. aconv.specifier = 'i';
  915. sp = encode_uint(expo, &aconv, buf, spe);
  916. while (sp < spe) {
  917. *buf++ = *sp++;
  918. }
  919. *bpe = buf;
  920. return bps;
  921. }
  922. /* Remainder of code operates on a 64-bit fraction, so shift up (and
  923. * discard garbage from the exponent where the implicit 1 would be
  924. * stored).
  925. */
  926. fract <<= EXPONENT_BITS;
  927. fract &= ~SIGN_MASK;
  928. /* Non-zero values need normalization. */
  929. if ((expo | fract) != 0) {
  930. if (is_subnormal) {
  931. /* Fraction is subnormal. Normalize it and correct
  932. * the exponent.
  933. */
  934. while (((fract <<= 1) & BIT_63) == 0) {
  935. expo--;
  936. }
  937. }
  938. /* Adjust the offset exponent to be signed rather than offset,
  939. * and set the implicit 1 bit in the (shifted) 53-bit
  940. * fraction.
  941. */
  942. expo -= (1023 - 1); /* +1 since .1 vs 1. */
  943. fract |= BIT_63;
  944. }
  945. /*
  946. * Let's consider:
  947. *
  948. * value = fract * 2^expo * 10^decexp
  949. *
  950. * Initially decexp = 0. The goal is to bring exp between
  951. * 0 and -2 as the magnitude of a fractional decimal digit is 3 bits.
  952. */
  953. int decexp = 0;
  954. while (expo < -2) {
  955. /*
  956. * Make roon to allow a multiplication by 5 without overflow.
  957. * We test only the top part for faster code.
  958. */
  959. do {
  960. fract >>= 1;
  961. expo++;
  962. } while ((uint32_t)(fract >> 32) >= (UINT32_MAX / 5U));
  963. /* Perform fract * 5 * 2 / 10 */
  964. fract *= 5U;
  965. expo++;
  966. decexp--;
  967. }
  968. while (expo > 0) {
  969. /*
  970. * Perform fract / 5 / 2 * 10.
  971. * The +2 is there to do round the result of the division
  972. * by 5 not to lose too much precision in extreme cases.
  973. */
  974. fract += 2;
  975. _ldiv5(&fract);
  976. expo--;
  977. decexp++;
  978. /* Bring back our fractional number to full scale */
  979. do {
  980. fract <<= 1;
  981. expo--;
  982. } while (!(fract & BIT_63));
  983. }
  984. /*
  985. * The binary fractional point is located somewhere above bit 63.
  986. * Move it between bits 59 and 60 to give 4 bits of room to the
  987. * integer part.
  988. */
  989. fract >>= (4 - expo);
  990. if ((c == 'g') || (c == 'G')) {
  991. /* Use the specified precision and exponent to select the
  992. * representation and correct the precision and zero-pruning
  993. * in accordance with the ISO C rule.
  994. */
  995. if (decexp < (-4 + 1) || decexp > precision) {
  996. c += 'e' - 'g'; /* e or E */
  997. if (precision > 0) {
  998. precision--;
  999. }
  1000. } else {
  1001. c = 'f';
  1002. precision -= decexp;
  1003. }
  1004. if (!conv->flag_hash && (precision > 0)) {
  1005. prune_zero = true;
  1006. }
  1007. }
  1008. int decimals;
  1009. if (c == 'f') {
  1010. decimals = precision + decexp;
  1011. if (decimals < 0) {
  1012. decimals = 0;
  1013. }
  1014. } else {
  1015. decimals = precision + 1;
  1016. }
  1017. int digit_count = 16;
  1018. if (decimals > 16) {
  1019. decimals = 16;
  1020. }
  1021. /* Round the value to the last digit being printed. */
  1022. uint64_t round = BIT64(59); /* 0.5 */
  1023. while (decimals--) {
  1024. _ldiv10(&round);
  1025. }
  1026. fract += round;
  1027. /* Make sure rounding didn't make fract >= 1.0 */
  1028. if (fract >= BIT64(60)) {
  1029. _ldiv10(&fract);
  1030. decexp++;
  1031. }
  1032. if (c == 'f') {
  1033. if (decexp > 0) {
  1034. /* Emit the digits above the decimal point. */
  1035. while (decexp > 0 && digit_count > 0) {
  1036. *buf++ = _get_digit(&fract, &digit_count);
  1037. decexp--;
  1038. }
  1039. conv->pad0_value = decexp;
  1040. decexp = 0;
  1041. } else {
  1042. *buf++ = '0';
  1043. }
  1044. /* Emit the decimal point only if required by the alternative
  1045. * format, or if more digits are to follow.
  1046. */
  1047. if (conv->flag_hash || (precision > 0)) {
  1048. *buf++ = '.';
  1049. }
  1050. if (decexp < 0 && precision > 0) {
  1051. conv->pad0_value = -decexp;
  1052. if (conv->pad0_value > precision) {
  1053. conv->pad0_value = precision;
  1054. }
  1055. precision -= conv->pad0_value;
  1056. conv->pad_postdp = (conv->pad0_value > 0);
  1057. }
  1058. } else { /* e or E */
  1059. /* Emit the one digit before the decimal. If it's not zero,
  1060. * this is significant so reduce the base-10 exponent.
  1061. */
  1062. *buf = _get_digit(&fract, &digit_count);
  1063. if (*buf++ != '0') {
  1064. decexp--;
  1065. }
  1066. /* Emit the decimal point only if required by the alternative
  1067. * format, or if more digits are to follow.
  1068. */
  1069. if (conv->flag_hash || (precision > 0)) {
  1070. *buf++ = '.';
  1071. }
  1072. }
  1073. while (precision > 0 && digit_count > 0) {
  1074. *buf++ = _get_digit(&fract, &digit_count);
  1075. precision--;
  1076. }
  1077. conv->pad0_pre_exp = precision;
  1078. if (prune_zero) {
  1079. conv->pad0_pre_exp = 0;
  1080. while (*--buf == '0') {
  1081. ;
  1082. }
  1083. if (*buf != '.') {
  1084. buf++;
  1085. }
  1086. }
  1087. /* Emit the explicit exponent, if format requires it. */
  1088. if ((c == 'e') || (c == 'E')) {
  1089. *buf++ = c;
  1090. if (decexp < 0) {
  1091. decexp = -decexp;
  1092. *buf++ = '-';
  1093. } else {
  1094. *buf++ = '+';
  1095. }
  1096. /* At most 3 digits to the decimal. Spit them out. */
  1097. if (decexp >= 100) {
  1098. *buf++ = (decexp / 100) + '0';
  1099. decexp %= 100;
  1100. }
  1101. *buf++ = (decexp / 10) + '0';
  1102. *buf++ = (decexp % 10) + '0';
  1103. }
  1104. /* Cache whether there's padding required */
  1105. conv->pad_fp = (conv->pad0_value > 0)
  1106. || (conv->pad0_pre_exp > 0);
  1107. /* Set the end of the encoded sequence, and return its start. Also
  1108. * store EOS as a non-digit/non-decimal value so we don't have to
  1109. * check against bpe when iterating in multiple places.
  1110. */
  1111. *bpe = buf;
  1112. *buf = 0;
  1113. return bps;
  1114. }
  1115. /* Store a count into the pointer provided in a %n specifier.
  1116. *
  1117. * @param conv the specifier that indicates the size of the value into which
  1118. * the count will be stored.
  1119. *
  1120. * @param dp where the count should be stored.
  1121. *
  1122. * @param count the count to be stored.
  1123. */
  1124. static inline void store_count(const struct conversion *conv,
  1125. void *dp,
  1126. int count)
  1127. {
  1128. switch ((enum length_mod_enum)conv->length_mod) {
  1129. case LENGTH_NONE:
  1130. *(int *)dp = count;
  1131. break;
  1132. case LENGTH_HH:
  1133. *(signed char *)dp = (signed char)count;
  1134. break;
  1135. case LENGTH_H:
  1136. *(short *)dp = (short)count;
  1137. break;
  1138. case LENGTH_L:
  1139. *(long *)dp = (long)count;
  1140. break;
  1141. case LENGTH_LL:
  1142. *(long long *)dp = (long long)count;
  1143. break;
  1144. case LENGTH_J:
  1145. *(intmax_t *)dp = (intmax_t)count;
  1146. break;
  1147. case LENGTH_Z:
  1148. *(size_t *)dp = (size_t)count;
  1149. break;
  1150. case LENGTH_T:
  1151. *(ptrdiff_t *)dp = (ptrdiff_t)count;
  1152. break;
  1153. default:
  1154. /* Add an empty default with break, this is a defensive programming.
  1155. * Static analysis tool won't raise a violation if default is empty,
  1156. * but has that comment.
  1157. */
  1158. break;
  1159. }
  1160. }
  1161. /* Outline function to emit all characters in [sp, ep). */
  1162. static int outs(cbprintf_cb out,
  1163. void *ctx,
  1164. const char *sp,
  1165. const char *ep)
  1166. {
  1167. size_t count = 0;
  1168. while ((sp < ep) || ((ep == NULL) && *sp)) {
  1169. int rc = out((int)*sp++, ctx);
  1170. if (rc < 0) {
  1171. return rc;
  1172. }
  1173. ++count;
  1174. }
  1175. return (int)count;
  1176. }
  1177. int cbvprintf(cbprintf_cb out, void *ctx, const char *fp, va_list ap)
  1178. {
  1179. char buf[CONVERTED_BUFLEN];
  1180. size_t count = 0;
  1181. sint_value_type sint;
  1182. /* Output character, returning EOF if output failed, otherwise
  1183. * updating count.
  1184. *
  1185. * NB: c is evaluated exactly once: side-effects are OK
  1186. */
  1187. #define OUTC(c) do { \
  1188. int rc = (*out)((int)(c), ctx); \
  1189. \
  1190. if (rc < 0) { \
  1191. return rc; \
  1192. } \
  1193. ++count; \
  1194. } while (false)
  1195. /* Output sequence of characters, returning a negative error if output
  1196. * failed.
  1197. */
  1198. #define OUTS(_sp, _ep) do { \
  1199. int rc = outs(out, ctx, _sp, _ep); \
  1200. \
  1201. if (rc < 0) { \
  1202. return rc; \
  1203. } \
  1204. count += rc; \
  1205. } while (false)
  1206. while (*fp != 0) {
  1207. if (*fp != '%') {
  1208. OUTC(*fp++);
  1209. continue;
  1210. }
  1211. /* Force union into RAM with conversion state to
  1212. * mitigate LLVM code generation bug.
  1213. */
  1214. struct {
  1215. union argument_value value;
  1216. struct conversion conv;
  1217. } state = {
  1218. .value = {
  1219. .uint = 0,
  1220. },
  1221. };
  1222. struct conversion *const conv = &state.conv;
  1223. union argument_value *const value = &state.value;
  1224. const char *sp = fp;
  1225. int width = -1;
  1226. int precision = -1;
  1227. const char *bps = NULL;
  1228. const char *bpe = buf + sizeof(buf);
  1229. char sign = 0;
  1230. fp = extract_conversion(conv, sp);
  1231. /* If dynamic width is specified, process it,
  1232. * otherwise set width if present.
  1233. */
  1234. if (conv->width_star) {
  1235. width = va_arg(ap, int);
  1236. if (width < 0) {
  1237. conv->flag_dash = true;
  1238. width = -width;
  1239. }
  1240. } else if (conv->width_present) {
  1241. width = conv->width_value;
  1242. } else {
  1243. ;
  1244. }
  1245. /* If dynamic precision is specified, process it, otherwise
  1246. * set precision if present. For floating point where
  1247. * precision is not present use 6.
  1248. */
  1249. if (conv->prec_star) {
  1250. int arg = va_arg(ap, int);
  1251. if (arg < 0) {
  1252. conv->prec_present = false;
  1253. } else {
  1254. precision = arg;
  1255. }
  1256. } else if (conv->prec_present) {
  1257. precision = conv->prec_value;
  1258. } else {
  1259. ;
  1260. }
  1261. /* Reuse width and precision memory in conv for value
  1262. * padding counts.
  1263. */
  1264. conv->pad0_value = 0;
  1265. conv->pad0_pre_exp = 0;
  1266. /* FP conversion requires knowing the precision. */
  1267. if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)
  1268. && (conv->specifier_cat == SPECIFIER_FP)
  1269. && !conv->prec_present) {
  1270. if (conv->specifier_a) {
  1271. precision = FRACTION_HEX;
  1272. } else {
  1273. precision = 6;
  1274. }
  1275. }
  1276. /* Get the value to be converted from the args.
  1277. *
  1278. * This can't be extracted to a helper function because
  1279. * passing a pointer to va_list doesn't work on x86_64. See
  1280. * https://stackoverflow.com/a/8048892.
  1281. */
  1282. enum specifier_cat_enum specifier_cat
  1283. = (enum specifier_cat_enum)conv->specifier_cat;
  1284. enum length_mod_enum length_mod
  1285. = (enum length_mod_enum)conv->length_mod;
  1286. /* Extract the value based on the argument category and length.
  1287. *
  1288. * Note that the length modifier doesn't affect the value of a
  1289. * pointer argument.
  1290. */
  1291. if (specifier_cat == SPECIFIER_SINT) {
  1292. switch (length_mod) {
  1293. default:
  1294. case LENGTH_NONE:
  1295. case LENGTH_HH:
  1296. case LENGTH_H:
  1297. value->sint = va_arg(ap, int);
  1298. break;
  1299. case LENGTH_L:
  1300. if (WCHAR_IS_SIGNED
  1301. && (conv->specifier == 'c')) {
  1302. value->sint = (wchar_t)va_arg(ap,
  1303. WINT_TYPE);
  1304. } else {
  1305. value->sint = va_arg(ap, long);
  1306. }
  1307. break;
  1308. case LENGTH_LL:
  1309. value->sint =
  1310. (sint_value_type)va_arg(ap, long long);
  1311. break;
  1312. case LENGTH_J:
  1313. value->sint =
  1314. (sint_value_type)va_arg(ap, intmax_t);
  1315. break;
  1316. case LENGTH_Z: /* size_t */
  1317. case LENGTH_T: /* ptrdiff_t */
  1318. /* Though ssize_t is the signed equivalent of
  1319. * size_t for POSIX, there is no uptrdiff_t.
  1320. * Assume that size_t and ptrdiff_t are the
  1321. * unsigned and signed equivalents of each
  1322. * other. This can be checked in a platform
  1323. * test.
  1324. */
  1325. value->sint =
  1326. (sint_value_type)va_arg(ap, ptrdiff_t);
  1327. break;
  1328. }
  1329. if (length_mod == LENGTH_HH) {
  1330. value->sint = (char)value->sint;
  1331. } else if (length_mod == LENGTH_H) {
  1332. value->sint = (short)value->sint;
  1333. }
  1334. } else if (specifier_cat == SPECIFIER_UINT) {
  1335. switch (length_mod) {
  1336. default:
  1337. case LENGTH_NONE:
  1338. case LENGTH_HH:
  1339. case LENGTH_H:
  1340. value->uint = va_arg(ap, unsigned int);
  1341. break;
  1342. case LENGTH_L:
  1343. if ((!WCHAR_IS_SIGNED)
  1344. && (conv->specifier == 'c')) {
  1345. value->uint = (wchar_t)va_arg(ap,
  1346. WINT_TYPE);
  1347. } else {
  1348. value->uint = va_arg(ap, unsigned long);
  1349. }
  1350. break;
  1351. case LENGTH_LL:
  1352. value->uint =
  1353. (uint_value_type)va_arg(ap,
  1354. unsigned long long);
  1355. break;
  1356. case LENGTH_J:
  1357. value->uint =
  1358. (uint_value_type)va_arg(ap,
  1359. uintmax_t);
  1360. break;
  1361. case LENGTH_Z: /* size_t */
  1362. case LENGTH_T: /* ptrdiff_t */
  1363. value->uint =
  1364. (uint_value_type)va_arg(ap, size_t);
  1365. break;
  1366. }
  1367. if (length_mod == LENGTH_HH) {
  1368. value->uint = (unsigned char)value->uint;
  1369. } else if (length_mod == LENGTH_H) {
  1370. value->uint = (unsigned short)value->uint;
  1371. }
  1372. } else if (specifier_cat == SPECIFIER_FP) {
  1373. if (length_mod == LENGTH_UPPER_L) {
  1374. value->ldbl = va_arg(ap, long double);
  1375. } else {
  1376. value->dbl = va_arg(ap, double);
  1377. }
  1378. } else if (specifier_cat == SPECIFIER_PTR) {
  1379. value->ptr = va_arg(ap, void *);
  1380. }
  1381. /* We've now consumed all arguments related to this
  1382. * specification. If the conversion is invalid, or is
  1383. * something we don't support, then output the original
  1384. * specification and move on.
  1385. */
  1386. if (conv->invalid || conv->unsupported) {
  1387. OUTS(sp, fp);
  1388. continue;
  1389. }
  1390. /* Do formatting, either into the buffer or
  1391. * referencing external data.
  1392. */
  1393. switch (conv->specifier) {
  1394. case '%':
  1395. OUTC('%');
  1396. break;
  1397. case 's': {
  1398. bps = (const char *)value->ptr;
  1399. size_t len;
  1400. if (precision >= 0) {
  1401. len = strnlen(bps, precision);
  1402. } else {
  1403. len = strlen(bps);
  1404. }
  1405. bpe = bps + len;
  1406. precision = -1;
  1407. break;
  1408. }
  1409. case 'c':
  1410. bps = buf;
  1411. buf[0] = CHAR_IS_SIGNED ? value->sint : value->uint;
  1412. bpe = buf + 1;
  1413. break;
  1414. case 'd':
  1415. case 'i':
  1416. if (conv->flag_plus) {
  1417. sign = '+';
  1418. } else if (conv->flag_space) {
  1419. sign = ' ';
  1420. }
  1421. /* sint/uint overlay in the union, and so
  1422. * can't appear in read and write operations
  1423. * in the same statement.
  1424. */
  1425. sint = value->sint;
  1426. if (sint < 0) {
  1427. sign = '-';
  1428. value->uint = (uint_value_type)-sint;
  1429. } else {
  1430. value->uint = (uint_value_type)sint;
  1431. }
  1432. __fallthrough;
  1433. case 'o':
  1434. case 'u':
  1435. case 'x':
  1436. case 'X':
  1437. bps = encode_uint(value->uint, conv, buf, bpe);
  1438. prec_int_pad0:
  1439. /* Update pad0 values based on precision and converted
  1440. * length. Note that a non-empty sign is not in the
  1441. * converted sequence, but it does not affect the
  1442. * padding size.
  1443. */
  1444. if (precision >= 0) {
  1445. size_t len = bpe - bps;
  1446. /* Zero-padding flag is ignored for integer
  1447. * conversions with precision.
  1448. */
  1449. conv->flag_zero = false;
  1450. /* Set pad0_value to satisfy precision */
  1451. if (len < (size_t)precision) {
  1452. conv->pad0_value = precision - (int)len;
  1453. }
  1454. }
  1455. break;
  1456. case 'p':
  1457. /* Implementation-defined: null is "(nil)", non-null
  1458. * has 0x prefix followed by significant address hex
  1459. * digits, no leading zeros.
  1460. */
  1461. if (value->ptr != NULL) {
  1462. bps = encode_uint((uintptr_t)value->ptr, conv,
  1463. buf, bpe);
  1464. /* Use 0x prefix */
  1465. conv->altform_0c = true;
  1466. conv->specifier = 'x';
  1467. goto prec_int_pad0;
  1468. }
  1469. bps = "(nil)";
  1470. bpe = bps + 5;
  1471. break;
  1472. case 'n':
  1473. if (IS_ENABLED(CONFIG_CBPRINTF_N_SPECIFIER)) {
  1474. store_count(conv, value->ptr, count);
  1475. }
  1476. break;
  1477. case FP_CONV_CASES:
  1478. if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)) {
  1479. bps = encode_float(value->dbl, conv, precision,
  1480. &sign, buf, &bpe);
  1481. }
  1482. break;
  1483. default:
  1484. /* Add an empty default with break, this is a defensive
  1485. * programming. Static analysis tool won't raise a violation
  1486. * if default is empty, but has that comment.
  1487. */
  1488. break;
  1489. }
  1490. /* If we don't have a converted value to emit, move
  1491. * on.
  1492. */
  1493. if (bps == NULL) {
  1494. continue;
  1495. }
  1496. /* The converted value is now stored in [bps, bpe), excluding
  1497. * any required zero padding.
  1498. *
  1499. * The unjustified output will be:
  1500. *
  1501. * * any sign character (sint-only)
  1502. * * any altform prefix
  1503. * * for FP:
  1504. * * any pre-decimal content from the converted value
  1505. * * any pad0_value padding (!postdp)
  1506. * * any decimal point in the converted value
  1507. * * any pad0_value padding (postdp)
  1508. * * any pre-exponent content from the converted value
  1509. * * any pad0_pre_exp padding
  1510. * * any exponent content from the converted value
  1511. * * for non-FP:
  1512. * * any pad0_prefix
  1513. * * the converted value
  1514. */
  1515. size_t nj_len = (bpe - bps);
  1516. int pad_len = 0;
  1517. if (sign != 0) {
  1518. nj_len += 1U;
  1519. }
  1520. if (conv->altform_0c) {
  1521. nj_len += 2U;
  1522. } else if (conv->altform_0) {
  1523. nj_len += 1U;
  1524. }
  1525. nj_len += conv->pad0_value;
  1526. if (conv->pad_fp) {
  1527. nj_len += conv->pad0_pre_exp;
  1528. }
  1529. /* If we have a width update width to hold the padding we need
  1530. * for justification. The result may be negative, which will
  1531. * result in no padding.
  1532. *
  1533. * If a non-negative padding width is present and we're doing
  1534. * right-justification, emit the padding now.
  1535. */
  1536. if (width > 0) {
  1537. width -= (int)nj_len;
  1538. if (!conv->flag_dash) {
  1539. char pad = ' ';
  1540. /* If we're zero-padding we have to emit the
  1541. * sign first.
  1542. */
  1543. if (conv->flag_zero) {
  1544. if (sign != 0) {
  1545. OUTC(sign);
  1546. sign = 0;
  1547. }
  1548. pad = '0';
  1549. }
  1550. while (width-- > 0) {
  1551. OUTC(pad);
  1552. }
  1553. }
  1554. }
  1555. /* If we have a sign that hasn't been emitted, now's the
  1556. * time....
  1557. */
  1558. if (sign != 0) {
  1559. OUTC(sign);
  1560. }
  1561. if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT) && conv->pad_fp) {
  1562. const char *cp = bps;
  1563. if (conv->specifier_a) {
  1564. /* Only padding is pre_exp */
  1565. while (*cp != 'p') {
  1566. OUTC(*cp++);
  1567. }
  1568. } else {
  1569. while (isdigit((int)*cp)) {
  1570. OUTC(*cp++);
  1571. }
  1572. pad_len = conv->pad0_value;
  1573. if (!conv->pad_postdp) {
  1574. while (pad_len-- > 0) {
  1575. OUTC('0');
  1576. }
  1577. }
  1578. if (*cp == '.') {
  1579. OUTC(*cp++);
  1580. /* Remaining padding is
  1581. * post-dp.
  1582. */
  1583. while (pad_len-- > 0) {
  1584. OUTC('0');
  1585. }
  1586. }
  1587. while (isdigit((int)*cp)) {
  1588. OUTC(*cp++);
  1589. }
  1590. }
  1591. pad_len = conv->pad0_pre_exp;
  1592. while (pad_len-- > 0) {
  1593. OUTC('0');
  1594. }
  1595. OUTS(cp, bpe);
  1596. } else {
  1597. if (conv->altform_0c | conv->altform_0) {
  1598. OUTC('0');
  1599. }
  1600. if (conv->altform_0c) {
  1601. OUTC(conv->specifier);
  1602. }
  1603. pad_len = conv->pad0_value;
  1604. while (pad_len-- > 0) {
  1605. OUTC('0');
  1606. }
  1607. OUTS(bps, bpe);
  1608. }
  1609. /* Finish left justification */
  1610. while (width > 0) {
  1611. OUTC(' ');
  1612. --width;
  1613. }
  1614. }
  1615. return count;
  1616. #undef OUTS
  1617. #undef OUTC
  1618. }