3
0

printf.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * printf - format and print data
  4. *
  5. * Copyright 1999 Dave Cinege
  6. * Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. /* Usage: printf format [argument...]
  11. *
  12. * A front end to the printf function that lets it be used from the shell.
  13. *
  14. * Backslash escapes:
  15. *
  16. * \" = double quote
  17. * \\ = backslash
  18. * \a = alert (bell)
  19. * \b = backspace
  20. * \c = produce no further output
  21. * \f = form feed
  22. * \n = new line
  23. * \r = carriage return
  24. * \t = horizontal tab
  25. * \v = vertical tab
  26. * \0ooo = octal number (ooo is 0 to 3 digits)
  27. * \xhhh = hexadecimal number (hhh is 1 to 3 digits)
  28. *
  29. * Additional directive:
  30. *
  31. * %b = print an argument string, interpreting backslash escapes
  32. *
  33. * The 'format' argument is re-used as many times as necessary
  34. * to convert all of the given arguments.
  35. *
  36. * David MacKenzie <djm@gnu.ai.mit.edu>
  37. */
  38. /* 19990508 Busy Boxed! Dave Cinege */
  39. //config:config PRINTF
  40. //config: bool "printf (3.3 kb)"
  41. //config: default y
  42. //config: help
  43. //config: printf is used to format and print specified strings.
  44. //config: It's similar to 'echo' except it has more options.
  45. //applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))
  46. //kbuild:lib-$(CONFIG_PRINTF) += printf.o
  47. //kbuild:lib-$(CONFIG_ASH_PRINTF) += printf.o
  48. //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
  49. //usage:#define printf_trivial_usage
  50. //usage: "FORMAT [ARG]..."
  51. //usage:#define printf_full_usage "\n\n"
  52. //usage: "Format and print ARG(s) according to FORMAT (a-la C printf)"
  53. //usage:
  54. //usage:#define printf_example_usage
  55. //usage: "$ printf \"Val=%d\\n\" 5\n"
  56. //usage: "Val=5\n"
  57. #include "libbb.h"
  58. /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
  59. * They report it:
  60. * bash: printf: XXX: invalid number
  61. * printf: XXX: expected a numeric value
  62. * bash: printf: 123XXX: invalid number
  63. * printf: 123XXX: value not completely converted
  64. * but then they use 0 (or partially converted numeric prefix) as a value
  65. * and continue. They exit with 1 in this case.
  66. * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
  67. * Both print error message and assume 0 if %*.*f width/precision is "bad"
  68. * (but negative numbers are not "bad").
  69. * Both accept negative numbers for %u specifier.
  70. *
  71. * We try to be compatible.
  72. */
  73. typedef void FAST_FUNC (*converter)(const char *arg, void *result);
  74. static int multiconvert(const char *arg, void *result, converter convert)
  75. {
  76. if (*arg == '"' || *arg == '\'') {
  77. arg = utoa((unsigned char)arg[1]);
  78. }
  79. errno = 0;
  80. convert(arg, result);
  81. if (errno) {
  82. bb_error_msg("invalid number '%s'", arg);
  83. return 1;
  84. }
  85. return 0;
  86. }
  87. static void FAST_FUNC conv_strtoull(const char *arg, void *result)
  88. {
  89. *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
  90. /* both coreutils 6.10 and bash 3.2:
  91. * $ printf '%x\n' -2
  92. * fffffffffffffffe
  93. * Mimic that:
  94. */
  95. if (errno) {
  96. *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
  97. }
  98. }
  99. static void FAST_FUNC conv_strtoll(const char *arg, void *result)
  100. {
  101. *(long long*)result = bb_strtoll(arg, NULL, 0);
  102. }
  103. static void FAST_FUNC conv_strtod(const char *arg, void *result)
  104. {
  105. char *end;
  106. /* Well, this one allows leading whitespace... so what? */
  107. /* What I like much less is that "-" accepted too! :( */
  108. *(double*)result = strtod(arg, &end);
  109. if (end[0]) {
  110. errno = ERANGE;
  111. *(double*)result = 0;
  112. }
  113. }
  114. /* Callers should check errno to detect errors */
  115. static unsigned long long my_xstrtoull(const char *arg)
  116. {
  117. unsigned long long result;
  118. if (multiconvert(arg, &result, conv_strtoull))
  119. result = 0;
  120. return result;
  121. }
  122. static long long my_xstrtoll(const char *arg)
  123. {
  124. long long result;
  125. if (multiconvert(arg, &result, conv_strtoll))
  126. result = 0;
  127. return result;
  128. }
  129. static double my_xstrtod(const char *arg)
  130. {
  131. double result;
  132. multiconvert(arg, &result, conv_strtod);
  133. return result;
  134. }
  135. /* Handles %b; return 1 if output is to be short-circuited by \c */
  136. static int print_esc_string(const char *str)
  137. {
  138. char c;
  139. while ((c = *str) != '\0') {
  140. str++;
  141. if (c == '\\') {
  142. /* %b also accepts 4-digit octals of the form \0### */
  143. if (*str == '0') {
  144. if ((unsigned char)(str[1] - '0') < 8) {
  145. /* 2nd char is 0..7: skip leading '0' */
  146. str++;
  147. }
  148. }
  149. else if (*str == 'c') {
  150. return 1;
  151. }
  152. {
  153. /* optimization: don't force arg to be on-stack,
  154. * use another variable for that. */
  155. const char *z = str;
  156. c = bb_process_escape_sequence(&z);
  157. str = z;
  158. }
  159. }
  160. putchar(c);
  161. }
  162. return 0;
  163. }
  164. static void print_direc(char *format, unsigned fmt_length,
  165. int field_width, int precision,
  166. const char *argument)
  167. {
  168. long long llv;
  169. double dv;
  170. char saved;
  171. char *have_prec, *have_width;
  172. saved = format[fmt_length];
  173. format[fmt_length] = '\0';
  174. have_prec = strstr(format, ".*");
  175. have_width = strchr(format, '*');
  176. if (have_width - 1 == have_prec)
  177. have_width = NULL;
  178. errno = 0;
  179. switch (format[fmt_length - 1]) {
  180. case 'c':
  181. printf(format, *argument);
  182. break;
  183. case 'd':
  184. case 'i':
  185. llv = my_xstrtoll(argument);
  186. print_long:
  187. if (!have_width) {
  188. if (!have_prec)
  189. printf(format, llv);
  190. else
  191. printf(format, precision, llv);
  192. } else {
  193. if (!have_prec)
  194. printf(format, field_width, llv);
  195. else
  196. printf(format, field_width, precision, llv);
  197. }
  198. break;
  199. case 'o':
  200. case 'u':
  201. case 'x':
  202. case 'X':
  203. llv = my_xstrtoull(argument);
  204. /* cheat: unsigned long and long have same width, so... */
  205. goto print_long;
  206. case 's':
  207. /* Are char* and long long the same? */
  208. if (sizeof(argument) == sizeof(llv)) {
  209. llv = (long long)(ptrdiff_t)argument;
  210. goto print_long;
  211. } else {
  212. /* Hope compiler will optimize it out by moving call
  213. * instruction after the ifs... */
  214. if (!have_width) {
  215. if (!have_prec)
  216. printf(format, argument, /*unused:*/ argument, argument);
  217. else
  218. printf(format, precision, argument, /*unused:*/ argument);
  219. } else {
  220. if (!have_prec)
  221. printf(format, field_width, argument, /*unused:*/ argument);
  222. else
  223. printf(format, field_width, precision, argument);
  224. }
  225. break;
  226. }
  227. case 'f':
  228. case 'e':
  229. case 'E':
  230. case 'g':
  231. case 'G':
  232. dv = my_xstrtod(argument);
  233. if (!have_width) {
  234. if (!have_prec)
  235. printf(format, dv);
  236. else
  237. printf(format, precision, dv);
  238. } else {
  239. if (!have_prec)
  240. printf(format, field_width, dv);
  241. else
  242. printf(format, field_width, precision, dv);
  243. }
  244. break;
  245. } /* switch */
  246. format[fmt_length] = saved;
  247. }
  248. /* Handle params for "%*.*f". Negative numbers are ok (compat). */
  249. static int get_width_prec(const char *str)
  250. {
  251. int v = bb_strtoi(str, NULL, 10);
  252. if (errno) {
  253. bb_error_msg("invalid number '%s'", str);
  254. v = 0;
  255. }
  256. return v;
  257. }
  258. /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
  259. Return advanced ARGV. */
  260. static char **print_formatted(char *f, char **argv, int *conv_err)
  261. {
  262. char *direc_start; /* Start of % directive. */
  263. unsigned direc_length; /* Length of % directive. */
  264. int field_width; /* Arg to first '*' */
  265. int precision; /* Arg to second '*' */
  266. char **saved_argv = argv;
  267. for (; *f; ++f) {
  268. switch (*f) {
  269. case '%':
  270. direc_start = f++;
  271. direc_length = 1;
  272. field_width = precision = 0;
  273. if (*f == '%') {
  274. bb_putchar('%');
  275. break;
  276. }
  277. if (*f == 'b') {
  278. if (*argv) {
  279. if (print_esc_string(*argv))
  280. return saved_argv; /* causes main() to exit */
  281. ++argv;
  282. }
  283. break;
  284. }
  285. if (*f && strchr("-+ #", *f)) {
  286. ++f;
  287. ++direc_length;
  288. }
  289. if (*f == '*') {
  290. ++f;
  291. ++direc_length;
  292. if (*argv)
  293. field_width = get_width_prec(*argv++);
  294. } else {
  295. while (isdigit(*f)) {
  296. ++f;
  297. ++direc_length;
  298. }
  299. }
  300. if (*f == '.') {
  301. ++f;
  302. ++direc_length;
  303. if (*f == '*') {
  304. ++f;
  305. ++direc_length;
  306. if (*argv)
  307. precision = get_width_prec(*argv++);
  308. } else {
  309. while (isdigit(*f)) {
  310. ++f;
  311. ++direc_length;
  312. }
  313. }
  314. }
  315. /* Remove "lLhz" size modifiers, repeatedly.
  316. * bash does not like "%lld", but coreutils
  317. * happily takes even "%Llllhhzhhzd"!
  318. * We are permissive like coreutils */
  319. while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
  320. overlapping_strcpy(f, f + 1);
  321. }
  322. /* Add "ll" if integer modifier, then print */
  323. {
  324. static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
  325. char *p = strchr(format_chars, *f);
  326. /* needed - try "printf %" without it */
  327. if (p == NULL || *f == '\0') {
  328. bb_error_msg("%s: invalid format", direc_start);
  329. /* causes main() to exit with error */
  330. return saved_argv - 1;
  331. }
  332. ++direc_length;
  333. if (p - format_chars <= 5) {
  334. /* it is one of "diouxX" */
  335. p = xmalloc(direc_length + 3);
  336. memcpy(p, direc_start, direc_length);
  337. p[direc_length + 1] = p[direc_length - 1];
  338. p[direc_length - 1] = 'l';
  339. p[direc_length] = 'l';
  340. //bb_error_msg("<%s>", p);
  341. direc_length += 2;
  342. direc_start = p;
  343. } else {
  344. p = NULL;
  345. }
  346. if (*argv) {
  347. print_direc(direc_start, direc_length, field_width,
  348. precision, *argv++);
  349. } else {
  350. print_direc(direc_start, direc_length, field_width,
  351. precision, "");
  352. }
  353. *conv_err |= errno;
  354. free(p);
  355. }
  356. break;
  357. case '\\':
  358. if (*++f == 'c') {
  359. return saved_argv; /* causes main() to exit */
  360. }
  361. bb_putchar(bb_process_escape_sequence((const char **)&f));
  362. f--;
  363. break;
  364. default:
  365. putchar(*f);
  366. }
  367. }
  368. return argv;
  369. }
  370. int printf_main(int argc UNUSED_PARAM, char **argv)
  371. {
  372. int conv_err;
  373. char *format;
  374. char **argv2;
  375. /* We must check that stdout is not closed.
  376. * The reason for this is highly non-obvious.
  377. * printf_main is used from shell.
  378. * Shell must correctly handle 'printf "%s" foo'
  379. * if stdout is closed. With stdio, output gets shoveled into
  380. * stdout buffer, and even fflush cannot clear it out. It seems that
  381. * even if libc receives EBADF on write attempts, it feels determined
  382. * to output data no matter what. So it will try later,
  383. * and possibly will clobber future output. Not good. */
  384. // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
  385. if (fcntl(1, F_GETFL) == -1)
  386. return 1; /* match coreutils 6.10 (sans error msg to stderr) */
  387. //if (dup2(1, 1) != 1) - old way
  388. // return 1;
  389. /* bash builtin errors out on "printf '-%s-\n' foo",
  390. * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
  391. * We will mimic coreutils. */
  392. if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
  393. argv++;
  394. if (!argv[1]) {
  395. if (ENABLE_ASH_PRINTF
  396. && applet_name[0] != 'p'
  397. ) {
  398. bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
  399. return 2; /* bash compat */
  400. }
  401. bb_show_usage();
  402. }
  403. format = argv[1];
  404. argv2 = argv + 2;
  405. conv_err = 0;
  406. do {
  407. argv = argv2;
  408. argv2 = print_formatted(format, argv, &conv_err);
  409. } while (argv2 > argv && *argv2);
  410. /* coreutils compat (bash doesn't do this):
  411. if (*argv)
  412. fprintf(stderr, "excess args ignored");
  413. */
  414. return (argv2 < argv) /* if true, print_formatted errored out */
  415. || conv_err; /* print_formatted saw invalid number */
  416. }