3
0

printf.c 11 KB

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