printf.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright (C) 2021 Weidmüller Interface GmbH & Co. KG
  4. * Roland Gaudig <roland.gaudig@weidmueller.com>
  5. *
  6. * Copyright 1999 Dave Cinege
  7. * Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. */
  11. /*
  12. * This file provides a shell printf like format string expansion as required
  13. * for the setexpr <name> fmt <format> <value> command.
  14. * This source file was mostly taken from the BusyBox project (www.busybox.net)
  15. * In contrast to the original sources the output is not written to stdout
  16. * anymore but into a char array, which can be used as input for the env_set()
  17. * function.
  18. */
  19. /* Usage: printf format [argument...]
  20. *
  21. * A front end to the printf function that lets it be used from the shell.
  22. *
  23. * Backslash escapes:
  24. *
  25. * \" = double quote
  26. * \\ = backslash
  27. * \a = alert (bell)
  28. * \b = backspace
  29. * \c = produce no further output
  30. * \f = form feed
  31. * \n = new line
  32. * \r = carriage return
  33. * \t = horizontal tab
  34. * \v = vertical tab
  35. * \0ooo = octal number (ooo is 0 to 3 digits)
  36. * \xhhh = hexadecimal number (hhh is 1 to 3 digits)
  37. *
  38. * Additional directive:
  39. *
  40. * %b = print an argument string, interpreting backslash escapes
  41. *
  42. * The 'format' argument is re-used as many times as necessary
  43. * to convert all of the given arguments.
  44. *
  45. * David MacKenzie <djm@gnu.ai.mit.edu>
  46. */
  47. /* 19990508 Busy Boxed! Dave Cinege */
  48. //config:config PRINTF
  49. //config: bool "printf (3.8 kb)"
  50. //config: default y
  51. //config: help
  52. //config: printf is used to format and print specified strings.
  53. //config: It's similar to 'echo' except it has more options.
  54. //applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))
  55. //kbuild:lib-$(CONFIG_PRINTF) += printf.o
  56. //kbuild:lib-$(CONFIG_ASH_PRINTF) += printf.o
  57. //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
  58. //usage:#define printf_trivial_usage
  59. //usage: "FORMAT [ARG]..."
  60. //usage:#define printf_full_usage "\n\n"
  61. //usage: "Format and print ARG(s) according to FORMAT (a-la C printf)"
  62. //usage:
  63. //usage:#define printf_example_usage
  64. //usage: "$ printf \"Val=%d\\n\" 5\n"
  65. //usage: "Val=5\n"
  66. /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
  67. * They report it:
  68. * bash: printf: XXX: invalid number
  69. * printf: XXX: expected a numeric value
  70. * bash: printf: 123XXX: invalid number
  71. * printf: 123XXX: value not completely converted
  72. * but then they use 0 (or partially converted numeric prefix) as a value
  73. * and continue. They exit with 1 in this case.
  74. * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
  75. * Both print error message and assume 0 if %*.*f width/precision is "bad"
  76. * (but negative numbers are not "bad").
  77. * Both accept negative numbers for %u specifier.
  78. *
  79. * We try to be compatible.
  80. */
  81. #include <common.h>
  82. #include <ctype.h>
  83. #include <errno.h>
  84. #include <stddef.h>
  85. #include <stdio.h>
  86. #include <stdlib.h>
  87. #define WANT_HEX_ESCAPES 0
  88. #define PRINT_CONVERSION_ERROR 1
  89. #define PRINT_TRUNCATED_ERROR 2
  90. #define PRINT_SIZE_ERROR 4
  91. struct print_inf {
  92. char *str;
  93. size_t size;
  94. size_t offset;
  95. unsigned int error;
  96. };
  97. typedef void (*converter)(const char *arg, void *result);
  98. /**
  99. * printf_str() - print formatted into char array with length checks
  100. *
  101. * This function povides a printf like function for printing into a char array
  102. * with checking the boundaries.
  103. * Unlike snprintf, all checks are performed inside this function and status
  104. * reports are stored inside the print_inf struct. That way, this function can
  105. * be used almost as drop-in replacement without needing much code changes.
  106. * Unlike snprintf errors are not reported by return value, but inside the
  107. * error member of struct print_inf. The output stored inside the struct
  108. * print_inf str member shall only be used when the error member is 0.
  109. *
  110. * @inf: Info structure for print operation
  111. * @char: format string with optional arguments
  112. */
  113. static void printf_str(struct print_inf *inf, char *format, ...)
  114. {
  115. va_list args;
  116. int i;
  117. if (!inf)
  118. return;
  119. /* Do not write anything if previous error is pending */
  120. if (inf->error)
  121. return;
  122. /* Check if end of receiving buffer is already reached */
  123. if (inf->offset >= inf->size) {
  124. inf->error |= PRINT_SIZE_ERROR;
  125. return;
  126. }
  127. size_t remaining = inf->size - inf->offset;
  128. va_start(args, format);
  129. i = vsnprintf(inf->str + inf->offset, remaining, format, args);
  130. va_end(args);
  131. if (i >= remaining)
  132. inf->error |= PRINT_TRUNCATED_ERROR;
  133. else if (i < 0)
  134. inf->error |= PRINT_CONVERSION_ERROR;
  135. else
  136. inf->offset += i;
  137. }
  138. /**
  139. * putchar_str() - Print single character into char array with length checks
  140. *
  141. * This function provices a putchar like function, which stores the output
  142. * into a char array with checking boundaries.
  143. *
  144. * @inf: Info structure for print operation
  145. * @char: Single character to be printed
  146. */
  147. static void putchar_str(struct print_inf *inf, char c)
  148. {
  149. printf_str(inf, "%c", c);
  150. }
  151. static char process_escape_sequence(const char **ptr)
  152. {
  153. const char *q;
  154. unsigned int num_digits;
  155. unsigned int n;
  156. unsigned int base;
  157. num_digits = 0;
  158. n = 0;
  159. base = 8;
  160. q = *ptr;
  161. if (WANT_HEX_ESCAPES && *q == 'x') {
  162. ++q;
  163. base = 16;
  164. ++num_digits;
  165. }
  166. /* bash requires leading 0 in octal escapes:
  167. * \02 works, \2 does not (prints \ and 2).
  168. * We treat \2 as a valid octal escape sequence.
  169. */
  170. do {
  171. unsigned int r;
  172. unsigned int d = (unsigned char)(*q) - '0';
  173. #if WANT_HEX_ESCAPES
  174. if (d >= 10) {
  175. d = (unsigned char)tolower(*q) - 'a';
  176. //d += 10;
  177. /* The above would map 'A'-'F' and 'a'-'f' to 10-15,
  178. * however, some chars like '@' would map to 9 < base.
  179. * Do not allow that, map invalid chars to N > base:
  180. */
  181. if ((int)d >= 0)
  182. d += 10;
  183. }
  184. #endif
  185. if (d >= base) {
  186. if (WANT_HEX_ESCAPES && base == 16) {
  187. --num_digits;
  188. if (num_digits == 0) {
  189. /* \x<bad_char>: return '\',
  190. * leave ptr pointing to x
  191. */
  192. return '\\';
  193. }
  194. }
  195. break;
  196. }
  197. r = n * base + d;
  198. if (r > 255)
  199. break;
  200. n = r;
  201. ++q;
  202. } while (++num_digits < 3);
  203. if (num_digits == 0) {
  204. /* Not octal or hex escape sequence.
  205. * Is it one-letter one?
  206. */
  207. /* bash builtin "echo -e '\ec'" interprets \e as ESC,
  208. * but coreutils "/bin/echo -e '\ec'" does not.
  209. * Manpages tend to support coreutils way.
  210. * Update: coreutils added support for \e on 28 Oct 2009.
  211. */
  212. static const char charmap[] = {
  213. 'a', 'b', 'e', 'f', 'n', 'r', 't', 'v', '\\', '\0',
  214. '\a', '\b', 27, '\f', '\n', '\r', '\t', '\v', '\\', '\\',
  215. };
  216. const char *p = charmap;
  217. do {
  218. if (*p == *q) {
  219. q++;
  220. break;
  221. }
  222. } while (*++p != '\0');
  223. /* p points to found escape char or NUL,
  224. * advance it and find what it translates to.
  225. * Note that \NUL and unrecognized sequence \z return '\'
  226. * and leave ptr pointing to NUL or z.
  227. */
  228. n = p[sizeof(charmap) / 2];
  229. }
  230. *ptr = q;
  231. return (char)n;
  232. }
  233. static char *skip_whitespace(const char *s)
  234. {
  235. /* In POSIX/C locale (the only locale we care about: do we REALLY want
  236. * to allow Unicode whitespace in, say, .conf files? nuts!)
  237. * isspace is only these chars: "\t\n\v\f\r" and space.
  238. * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
  239. * Use that.
  240. */
  241. while (*s == ' ' || (unsigned char)(*s - 9) <= (13 - 9))
  242. s++;
  243. return (char *)s;
  244. }
  245. /* Like strcpy but can copy overlapping strings. */
  246. static void overlapping_strcpy(char *dst, const char *src)
  247. {
  248. /* Cheap optimization for dst == src case -
  249. * better to have it here than in many callers.
  250. */
  251. if (dst != src) {
  252. while ((*dst = *src) != '\0') {
  253. dst++;
  254. src++;
  255. }
  256. }
  257. }
  258. static int multiconvert(const char *arg, void *result, converter convert)
  259. {
  260. if (*arg == '"' || *arg == '\'')
  261. sprintf((char *)arg + strlen(arg), "%u", (unsigned char)arg[1]);
  262. //errno = 0;
  263. convert(arg, result);
  264. /* Unlike their Posix counterparts, simple_strtoll and
  265. * simple_strtoull do not set errno
  266. *
  267. * if (errno) {
  268. * printf("error invalid number '%s'", arg);
  269. * return 1;
  270. * }
  271. */
  272. return 0;
  273. }
  274. static void conv_strtoull(const char *arg, void *result)
  275. {
  276. /* both coreutils 6.10 and bash 3.2:
  277. * $ printf '%x\n' -2
  278. * fffffffffffffffe
  279. * Mimic that:
  280. */
  281. if (arg[0] == '-') {
  282. *(unsigned long long *)result = simple_strtoll(arg, NULL, 16);
  283. return;
  284. }
  285. /* Allow leading '+' - simple_strtoull() by itself does not allow it,
  286. * and probably shouldn't (other callers might require purely numeric
  287. * inputs to be allowed.
  288. */
  289. if (arg[0] == '+')
  290. arg++;
  291. *(unsigned long long *)result = simple_strtoull(arg, NULL, 16);
  292. }
  293. static void conv_strtoll(const char *arg, void *result)
  294. {
  295. if (arg[0] == '+')
  296. arg++;
  297. *(long long *)result = simple_strtoll(arg, NULL, 16);
  298. }
  299. /* Callers should check errno to detect errors */
  300. static unsigned long long my_xstrtoull(const char *arg)
  301. {
  302. unsigned long long result;
  303. if (multiconvert(arg, &result, conv_strtoull))
  304. result = 0;
  305. return result;
  306. }
  307. static long long my_xstrtoll(const char *arg)
  308. {
  309. long long result;
  310. if (multiconvert(arg, &result, conv_strtoll))
  311. result = 0;
  312. return result;
  313. }
  314. /* Handles %b; return 1 if output is to be short-circuited by \c */
  315. static int print_esc_string(struct print_inf *inf, const char *str)
  316. {
  317. char c;
  318. while ((c = *str) != '\0') {
  319. str++;
  320. if (c == '\\') {
  321. /* %b also accepts 4-digit octals of the form \0### */
  322. if (*str == '0') {
  323. if ((unsigned char)(str[1] - '0') < 8) {
  324. /* 2nd char is 0..7: skip leading '0' */
  325. str++;
  326. }
  327. } else if (*str == 'c') {
  328. return 1;
  329. }
  330. {
  331. /* optimization: don't force arg to be on-stack,
  332. * use another variable for that.
  333. */
  334. const char *z = str;
  335. c = process_escape_sequence(&z);
  336. str = z;
  337. }
  338. }
  339. putchar_str(inf, c);
  340. }
  341. return 0;
  342. }
  343. static void print_direc(struct print_inf *inf, char *format, unsigned int fmt_length,
  344. int field_width, int precision,
  345. const char *argument)
  346. {
  347. long long llv;
  348. char saved;
  349. char *have_prec, *have_width;
  350. saved = format[fmt_length];
  351. format[fmt_length] = '\0';
  352. have_prec = strstr(format, ".*");
  353. have_width = strchr(format, '*');
  354. if (have_width - 1 == have_prec)
  355. have_width = NULL;
  356. /* multiconvert sets errno = 0, but %s needs it cleared */
  357. errno = 0;
  358. switch (format[fmt_length - 1]) {
  359. case 'c':
  360. printf_str(inf, format, *argument);
  361. break;
  362. case 'd':
  363. case 'i':
  364. llv = my_xstrtoll(skip_whitespace(argument));
  365. print_long:
  366. if (!have_width) {
  367. if (!have_prec)
  368. printf_str(inf, format, llv);
  369. else
  370. printf_str(inf, format, precision, llv);
  371. } else {
  372. if (!have_prec)
  373. printf_str(inf, format, field_width, llv);
  374. else
  375. printf_str(inf, format, field_width, precision, llv);
  376. }
  377. break;
  378. case 'o':
  379. case 'u':
  380. case 'x':
  381. case 'X':
  382. llv = my_xstrtoull(skip_whitespace(argument));
  383. /* cheat: unsigned long and long have same width, so... */
  384. goto print_long;
  385. case 's':
  386. /* Are char* and long long the same? */
  387. if (sizeof(argument) == sizeof(llv)) {
  388. llv = (long long)(ptrdiff_t)argument;
  389. goto print_long;
  390. } else {
  391. /* Hope compiler will optimize it out by moving call
  392. * instruction after the ifs...
  393. */
  394. if (!have_width) {
  395. if (!have_prec)
  396. printf_str(inf, format, argument,
  397. /*unused:*/ argument, argument);
  398. else
  399. printf_str(inf, format, precision,
  400. argument, /*unused:*/ argument);
  401. } else {
  402. if (!have_prec)
  403. printf_str(inf, format, field_width,
  404. argument, /*unused:*/ argument);
  405. else
  406. printf_str(inf, format, field_width,
  407. precision, argument);
  408. }
  409. break;
  410. }
  411. break;
  412. } /* switch */
  413. format[fmt_length] = saved;
  414. }
  415. /* Handle params for "%*.*f". Negative numbers are ok (compat). */
  416. static int get_width_prec(const char *str)
  417. {
  418. long v = simple_strtol(str, NULL, 10);
  419. /* Unlike its Posix counterpart, simple_strtol does not set errno
  420. *
  421. * if (errno) {
  422. * printf("error invalid number '%s'", str);
  423. * v = 0;
  424. * }
  425. */
  426. return (int)v;
  427. }
  428. /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
  429. * Return advanced ARGV.
  430. */
  431. static char **print_formatted(struct print_inf *inf, char *f, char **argv, int *conv_err)
  432. {
  433. char *direc_start; /* Start of % directive. */
  434. unsigned int direc_length; /* Length of % directive. */
  435. int field_width; /* Arg to first '*' */
  436. int precision; /* Arg to second '*' */
  437. char **saved_argv = argv;
  438. for (; *f; ++f) {
  439. switch (*f) {
  440. case '%':
  441. direc_start = f++;
  442. direc_length = 1;
  443. field_width = 0;
  444. precision = 0;
  445. if (*f == '%') {
  446. putchar_str(inf, '%');
  447. break;
  448. }
  449. if (*f == 'b') {
  450. if (*argv) {
  451. if (print_esc_string(inf, *argv))
  452. return saved_argv; /* causes main() to exit */
  453. ++argv;
  454. }
  455. break;
  456. }
  457. if (*f && strchr("-+ #", *f)) {
  458. ++f;
  459. ++direc_length;
  460. }
  461. if (*f == '*') {
  462. ++f;
  463. ++direc_length;
  464. if (*argv)
  465. field_width = get_width_prec(*argv++);
  466. } else {
  467. while (isdigit(*f)) {
  468. ++f;
  469. ++direc_length;
  470. }
  471. }
  472. if (*f == '.') {
  473. ++f;
  474. ++direc_length;
  475. if (*f == '*') {
  476. ++f;
  477. ++direc_length;
  478. if (*argv)
  479. precision = get_width_prec(*argv++);
  480. } else {
  481. while (isdigit(*f)) {
  482. ++f;
  483. ++direc_length;
  484. }
  485. }
  486. }
  487. /* Remove "lLhz" size modifiers, repeatedly.
  488. * bash does not like "%lld", but coreutils
  489. * happily takes even "%Llllhhzhhzd"!
  490. * We are permissive like coreutils
  491. */
  492. while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z')
  493. overlapping_strcpy(f, f + 1);
  494. /* Add "ll" if integer modifier, then print */
  495. {
  496. static const char format_chars[] = "diouxXcs";
  497. char *p = strchr(format_chars, *f);
  498. /* needed - try "printf %" without it */
  499. if (!p || *f == '\0') {
  500. printf("`%s': invalid format\n", direc_start);
  501. /* causes main() to exit with error */
  502. return saved_argv - 1;
  503. }
  504. ++direc_length;
  505. if (p - format_chars <= 5) {
  506. /* it is one of "diouxX" */
  507. p = malloc(direc_length + 3);
  508. if (!p) {
  509. /* exit with error */
  510. return saved_argv - 1;
  511. }
  512. memcpy(p, direc_start, direc_length);
  513. p[direc_length + 1] = p[direc_length - 1];
  514. p[direc_length - 1] = 'l';
  515. p[direc_length] = 'l';
  516. //bb_error_msg("<%s>", p);
  517. direc_length += 2;
  518. direc_start = p;
  519. } else {
  520. p = NULL;
  521. }
  522. if (*argv) {
  523. print_direc(inf, direc_start, direc_length,
  524. field_width, precision, *argv++);
  525. } else {
  526. print_direc(inf, direc_start, direc_length,
  527. field_width, precision, "");
  528. }
  529. *conv_err |= errno;
  530. free(p);
  531. }
  532. break;
  533. case '\\':
  534. if (*++f == 'c')
  535. return saved_argv; /* causes main() to exit */
  536. putchar_str(inf, process_escape_sequence((const char **)&f));
  537. f--;
  538. break;
  539. default:
  540. putchar_str(inf, *f);
  541. }
  542. }
  543. return argv;
  544. }
  545. /**
  546. * printf_setexpr() - Implements the setexpr <name> fmt <format> command
  547. *
  548. * This function implements the format string evaluation for the
  549. * setexpr <name> fmt <format> <value> command.
  550. *
  551. * @str: Output string of the evaluated expression
  552. * @size: Length of @str buffer
  553. * @argc: Number of arguments
  554. * @argv: Argument list
  555. * @return: 0 if OK, 1 on error
  556. */
  557. int printf_setexpr(char *str, size_t size, int argc, char *const *argv)
  558. {
  559. int conv_err;
  560. char *format;
  561. char **argv2;
  562. struct print_inf inf = {
  563. .str = str,
  564. .size = size,
  565. .offset = 0,
  566. .error = 0,
  567. };
  568. if (!str || !size)
  569. return 1;
  570. inf.str[0] = '\0';
  571. format = argv[0];
  572. argv2 = (char **)argv + 1;
  573. conv_err = 0;
  574. argv = argv2;
  575. /* In case any print_str call raises an error inf.error will be
  576. * set after print_formatted returns.
  577. */
  578. argv2 = print_formatted(&inf, format, (char **)argv, &conv_err);
  579. /* coreutils compat (bash doesn't do this):
  580. *if (*argv)
  581. * fprintf(stderr, "excess args ignored");
  582. */
  583. return (argv2 < argv) || /* if true, print_formatted errored out */
  584. conv_err || /* print_formatted saw invalid number */
  585. inf.error; /* print_str reported error */
  586. }