printf.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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.8 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. /* Allow leading '+' - bb_strtoull() by itself does not allow it,
  90. * and probably shouldn't (other callers might require purely numeric
  91. * inputs to be allowed.
  92. */
  93. if (arg[0] == '+')
  94. arg++;
  95. *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
  96. /* both coreutils 6.10 and bash 3.2:
  97. * $ printf '%x\n' -2
  98. * fffffffffffffffe
  99. * Mimic that:
  100. */
  101. if (errno) {
  102. *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
  103. }
  104. }
  105. static void FAST_FUNC conv_strtoll(const char *arg, void *result)
  106. {
  107. if (arg[0] == '+')
  108. arg++;
  109. *(long long*)result = bb_strtoll(arg, NULL, 0);
  110. }
  111. static void FAST_FUNC conv_strtod(const char *arg, void *result)
  112. {
  113. char *end;
  114. /* Well, this one allows leading whitespace... so what? */
  115. /* What I like much less is that "-" accepted too! :( */
  116. *(double*)result = strtod(arg, &end);
  117. if (end[0]) {
  118. errno = ERANGE;
  119. *(double*)result = 0;
  120. }
  121. }
  122. /* Callers should check errno to detect errors */
  123. static unsigned long long my_xstrtoull(const char *arg)
  124. {
  125. unsigned long long result;
  126. if (multiconvert(arg, &result, conv_strtoull))
  127. result = 0;
  128. return result;
  129. }
  130. static long long my_xstrtoll(const char *arg)
  131. {
  132. long long result;
  133. if (multiconvert(arg, &result, conv_strtoll))
  134. result = 0;
  135. return result;
  136. }
  137. static double my_xstrtod(const char *arg)
  138. {
  139. double result;
  140. multiconvert(arg, &result, conv_strtod);
  141. return result;
  142. }
  143. /* Handles %b; return 1 if output is to be short-circuited by \c */
  144. static int print_esc_string(const char *str)
  145. {
  146. char c;
  147. while ((c = *str) != '\0') {
  148. str++;
  149. if (c == '\\') {
  150. /* %b also accepts 4-digit octals of the form \0### */
  151. if (*str == '0') {
  152. if ((unsigned char)(str[1] - '0') < 8) {
  153. /* 2nd char is 0..7: skip leading '0' */
  154. str++;
  155. }
  156. }
  157. else if (*str == 'c') {
  158. return 1;
  159. }
  160. {
  161. /* optimization: don't force arg to be on-stack,
  162. * use another variable for that. */
  163. const char *z = str;
  164. c = bb_process_escape_sequence(&z);
  165. str = z;
  166. }
  167. }
  168. putchar(c);
  169. }
  170. return 0;
  171. }
  172. static void print_direc(char *format, unsigned fmt_length,
  173. int field_width, int precision,
  174. const char *argument)
  175. {
  176. long long llv;
  177. double dv;
  178. char saved;
  179. char *have_prec, *have_width;
  180. saved = format[fmt_length];
  181. format[fmt_length] = '\0';
  182. have_prec = strstr(format, ".*");
  183. have_width = strchr(format, '*');
  184. if (have_width - 1 == have_prec)
  185. have_width = NULL;
  186. /* multiconvert sets errno = 0, but %s needs it cleared */
  187. errno = 0;
  188. switch (format[fmt_length - 1]) {
  189. case 'c':
  190. printf(format, *argument);
  191. break;
  192. case 'd':
  193. case 'i':
  194. llv = my_xstrtoll(skip_whitespace(argument));
  195. print_long:
  196. if (!have_width) {
  197. if (!have_prec)
  198. printf(format, llv);
  199. else
  200. printf(format, precision, llv);
  201. } else {
  202. if (!have_prec)
  203. printf(format, field_width, llv);
  204. else
  205. printf(format, field_width, precision, llv);
  206. }
  207. break;
  208. case 'o':
  209. case 'u':
  210. case 'x':
  211. case 'X':
  212. llv = my_xstrtoull(skip_whitespace(argument));
  213. /* cheat: unsigned long and long have same width, so... */
  214. goto print_long;
  215. case 's':
  216. /* Are char* and long long the same? */
  217. if (sizeof(argument) == sizeof(llv)) {
  218. llv = (long long)(ptrdiff_t)argument;
  219. goto print_long;
  220. } else {
  221. /* Hope compiler will optimize it out by moving call
  222. * instruction after the ifs... */
  223. if (!have_width) {
  224. if (!have_prec)
  225. printf(format, argument, /*unused:*/ argument, argument);
  226. else
  227. printf(format, precision, argument, /*unused:*/ argument);
  228. } else {
  229. if (!have_prec)
  230. printf(format, field_width, argument, /*unused:*/ argument);
  231. else
  232. printf(format, field_width, precision, argument);
  233. }
  234. break;
  235. }
  236. case 'f':
  237. case 'e':
  238. case 'E':
  239. case 'g':
  240. case 'G':
  241. dv = my_xstrtod(argument);
  242. if (!have_width) {
  243. if (!have_prec)
  244. printf(format, dv);
  245. else
  246. printf(format, precision, dv);
  247. } else {
  248. if (!have_prec)
  249. printf(format, field_width, dv);
  250. else
  251. printf(format, field_width, precision, dv);
  252. }
  253. break;
  254. } /* switch */
  255. format[fmt_length] = saved;
  256. }
  257. /* Handle params for "%*.*f". Negative numbers are ok (compat). */
  258. static int get_width_prec(const char *str)
  259. {
  260. int v = bb_strtoi(str, NULL, 10);
  261. if (errno) {
  262. bb_error_msg("invalid number '%s'", str);
  263. v = 0;
  264. }
  265. return v;
  266. }
  267. /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
  268. Return advanced ARGV. */
  269. static char **print_formatted(char *f, char **argv, int *conv_err)
  270. {
  271. char *direc_start; /* Start of % directive. */
  272. unsigned direc_length; /* Length of % directive. */
  273. int field_width; /* Arg to first '*' */
  274. int precision; /* Arg to second '*' */
  275. char **saved_argv = argv;
  276. for (; *f; ++f) {
  277. switch (*f) {
  278. case '%':
  279. direc_start = f++;
  280. direc_length = 1;
  281. field_width = precision = 0;
  282. if (*f == '%') {
  283. bb_putchar('%');
  284. break;
  285. }
  286. if (*f == 'b') {
  287. if (*argv) {
  288. if (print_esc_string(*argv))
  289. return saved_argv; /* causes main() to exit */
  290. ++argv;
  291. }
  292. break;
  293. }
  294. if (*f && strchr("-+ #", *f)) {
  295. ++f;
  296. ++direc_length;
  297. }
  298. if (*f == '*') {
  299. ++f;
  300. ++direc_length;
  301. if (*argv)
  302. field_width = get_width_prec(*argv++);
  303. } else {
  304. while (isdigit(*f)) {
  305. ++f;
  306. ++direc_length;
  307. }
  308. }
  309. if (*f == '.') {
  310. ++f;
  311. ++direc_length;
  312. if (*f == '*') {
  313. ++f;
  314. ++direc_length;
  315. if (*argv)
  316. precision = get_width_prec(*argv++);
  317. } else {
  318. while (isdigit(*f)) {
  319. ++f;
  320. ++direc_length;
  321. }
  322. }
  323. }
  324. /* Remove "lLhz" size modifiers, repeatedly.
  325. * bash does not like "%lld", but coreutils
  326. * happily takes even "%Llllhhzhhzd"!
  327. * We are permissive like coreutils */
  328. while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
  329. overlapping_strcpy(f, f + 1);
  330. }
  331. /* Add "ll" if integer modifier, then print */
  332. {
  333. static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
  334. char *p = strchr(format_chars, *f);
  335. /* needed - try "printf %" without it */
  336. if (p == NULL || *f == '\0') {
  337. bb_error_msg("%s: invalid format", direc_start);
  338. /* causes main() to exit with error */
  339. return saved_argv - 1;
  340. }
  341. ++direc_length;
  342. if (p - format_chars <= 5) {
  343. /* it is one of "diouxX" */
  344. p = xmalloc(direc_length + 3);
  345. memcpy(p, direc_start, direc_length);
  346. p[direc_length + 1] = p[direc_length - 1];
  347. p[direc_length - 1] = 'l';
  348. p[direc_length] = 'l';
  349. //bb_error_msg("<%s>", p);
  350. direc_length += 2;
  351. direc_start = p;
  352. } else {
  353. p = NULL;
  354. }
  355. if (*argv) {
  356. print_direc(direc_start, direc_length, field_width,
  357. precision, *argv++);
  358. } else {
  359. print_direc(direc_start, direc_length, field_width,
  360. precision, "");
  361. }
  362. *conv_err |= errno;
  363. free(p);
  364. }
  365. break;
  366. case '\\':
  367. if (*++f == 'c') {
  368. return saved_argv; /* causes main() to exit */
  369. }
  370. bb_putchar(bb_process_escape_sequence((const char **)&f));
  371. f--;
  372. break;
  373. default:
  374. putchar(*f);
  375. }
  376. }
  377. return argv;
  378. }
  379. int printf_main(int argc UNUSED_PARAM, char **argv)
  380. {
  381. int conv_err;
  382. char *format;
  383. char **argv2;
  384. /* We must check that stdout is not closed.
  385. * The reason for this is highly non-obvious.
  386. * printf_main is used from shell.
  387. * Shell must correctly handle 'printf "%s" foo'
  388. * if stdout is closed. With stdio, output gets shoveled into
  389. * stdout buffer, and even fflush cannot clear it out. It seems that
  390. * even if libc receives EBADF on write attempts, it feels determined
  391. * to output data no matter what. So it will try later,
  392. * and possibly will clobber future output. Not good. */
  393. // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
  394. if (fcntl(1, F_GETFL) == -1)
  395. return 1; /* match coreutils 6.10 (sans error msg to stderr) */
  396. //if (dup2(1, 1) != 1) - old way
  397. // return 1;
  398. /* bash builtin errors out on "printf '-%s-\n' foo",
  399. * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
  400. * We will mimic coreutils. */
  401. if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
  402. argv++;
  403. if (!argv[1]) {
  404. if (ENABLE_ASH_PRINTF
  405. && applet_name[0] != 'p'
  406. ) {
  407. bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
  408. return 2; /* bash compat */
  409. }
  410. bb_show_usage();
  411. }
  412. format = argv[1];
  413. argv2 = argv + 2;
  414. conv_err = 0;
  415. do {
  416. argv = argv2;
  417. argv2 = print_formatted(format, argv, &conv_err);
  418. } while (argv2 > argv && *argv2);
  419. /* coreutils compat (bash doesn't do this):
  420. if (*argv)
  421. fprintf(stderr, "excess args ignored");
  422. */
  423. return (argv2 < argv) /* if true, print_formatted errored out */
  424. || conv_err; /* print_formatted saw invalid number */
  425. }