printf.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. #include "libbb.h"
  30. /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
  31. * They report it:
  32. * bash: printf: XXX: invalid number
  33. * printf: XXX: expected a numeric value
  34. * bash: printf: 123XXX: invalid number
  35. * printf: 123XXX: value not completely converted
  36. * but then they use 0 (or partially converted numeric prefix) as a value
  37. * and continue. They exit with 1 in this case.
  38. * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
  39. * Both print error message and assume 0 if %*.*f width/precision is "bad"
  40. * (but negative numbers are not "bad").
  41. * Both accept negative numbers for %u specifier.
  42. *
  43. * We try to be compatible.
  44. */
  45. typedef void FAST_FUNC (*converter)(const char *arg, void *result);
  46. static int multiconvert(const char *arg, void *result, converter convert)
  47. {
  48. if (*arg == '"' || *arg == '\'') {
  49. arg = utoa((unsigned char)arg[1]);
  50. }
  51. errno = 0;
  52. convert(arg, result);
  53. if (errno) {
  54. bb_error_msg("invalid number '%s'", arg);
  55. return 1;
  56. }
  57. return 0;
  58. }
  59. static void FAST_FUNC conv_strtoull(const char *arg, void *result)
  60. {
  61. *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
  62. /* both coreutils 6.10 and bash 3.2:
  63. * $ printf '%x\n' -2
  64. * fffffffffffffffe
  65. * Mimic that:
  66. */
  67. if (errno) {
  68. *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
  69. }
  70. }
  71. static void FAST_FUNC conv_strtoll(const char *arg, void *result)
  72. {
  73. *(long long*)result = bb_strtoll(arg, NULL, 0);
  74. }
  75. static void FAST_FUNC conv_strtod(const char *arg, void *result)
  76. {
  77. char *end;
  78. /* Well, this one allows leading whitespace... so what? */
  79. /* What I like much less is that "-" accepted too! :( */
  80. *(double*)result = strtod(arg, &end);
  81. if (end[0]) {
  82. errno = ERANGE;
  83. *(double*)result = 0;
  84. }
  85. }
  86. /* Callers should check errno to detect errors */
  87. static unsigned long long my_xstrtoull(const char *arg)
  88. {
  89. unsigned long long result;
  90. if (multiconvert(arg, &result, conv_strtoull))
  91. result = 0;
  92. return result;
  93. }
  94. static long long my_xstrtoll(const char *arg)
  95. {
  96. long long result;
  97. if (multiconvert(arg, &result, conv_strtoll))
  98. result = 0;
  99. return result;
  100. }
  101. static double my_xstrtod(const char *arg)
  102. {
  103. double result;
  104. multiconvert(arg, &result, conv_strtod);
  105. return result;
  106. }
  107. static void print_esc_string(const char *str)
  108. {
  109. char c;
  110. while ((c = *str) != '\0') {
  111. str++;
  112. if (c == '\\')
  113. c = bb_process_escape_sequence(&str);
  114. putchar(c);
  115. }
  116. }
  117. static void print_direc(char *format, unsigned fmt_length,
  118. int field_width, int precision,
  119. const char *argument)
  120. {
  121. long long llv;
  122. double dv;
  123. char saved;
  124. char *have_prec, *have_width;
  125. saved = format[fmt_length];
  126. format[fmt_length] = '\0';
  127. have_prec = strstr(format, ".*");
  128. have_width = strchr(format, '*');
  129. if (have_width - 1 == have_prec)
  130. have_width = NULL;
  131. errno = 0;
  132. switch (format[fmt_length - 1]) {
  133. case 'c':
  134. printf(format, *argument);
  135. break;
  136. case 'd':
  137. case 'i':
  138. llv = my_xstrtoll(argument);
  139. print_long:
  140. if (!have_width) {
  141. if (!have_prec)
  142. printf(format, llv);
  143. else
  144. printf(format, precision, llv);
  145. } else {
  146. if (!have_prec)
  147. printf(format, field_width, llv);
  148. else
  149. printf(format, field_width, precision, llv);
  150. }
  151. break;
  152. case 'o':
  153. case 'u':
  154. case 'x':
  155. case 'X':
  156. llv = my_xstrtoull(argument);
  157. /* cheat: unsigned long and long have same width, so... */
  158. goto print_long;
  159. case 's':
  160. /* Are char* and long long the same? */
  161. if (sizeof(argument) == sizeof(llv)) {
  162. llv = (long long)(ptrdiff_t)argument;
  163. goto print_long;
  164. } else {
  165. /* Hope compiler will optimize it out by moving call
  166. * instruction after the ifs... */
  167. if (!have_width) {
  168. if (!have_prec)
  169. printf(format, argument, /*unused:*/ argument, argument);
  170. else
  171. printf(format, precision, argument, /*unused:*/ argument);
  172. } else {
  173. if (!have_prec)
  174. printf(format, field_width, argument, /*unused:*/ argument);
  175. else
  176. printf(format, field_width, precision, argument);
  177. }
  178. break;
  179. }
  180. case 'f':
  181. case 'e':
  182. case 'E':
  183. case 'g':
  184. case 'G':
  185. dv = my_xstrtod(argument);
  186. if (!have_width) {
  187. if (!have_prec)
  188. printf(format, dv);
  189. else
  190. printf(format, precision, dv);
  191. } else {
  192. if (!have_prec)
  193. printf(format, field_width, dv);
  194. else
  195. printf(format, field_width, precision, dv);
  196. }
  197. break;
  198. } /* switch */
  199. format[fmt_length] = saved;
  200. }
  201. /* Handle params for "%*.*f". Negative numbers are ok (compat). */
  202. static int get_width_prec(const char *str)
  203. {
  204. int v = bb_strtoi(str, NULL, 10);
  205. if (errno) {
  206. bb_error_msg("invalid number '%s'", str);
  207. v = 0;
  208. }
  209. return v;
  210. }
  211. /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
  212. Return advanced ARGV. */
  213. static char **print_formatted(char *f, char **argv, int *conv_err)
  214. {
  215. char *direc_start; /* Start of % directive. */
  216. unsigned direc_length; /* Length of % directive. */
  217. int field_width; /* Arg to first '*' */
  218. int precision; /* Arg to second '*' */
  219. char **saved_argv = argv;
  220. for (; *f; ++f) {
  221. switch (*f) {
  222. case '%':
  223. direc_start = f++;
  224. direc_length = 1;
  225. field_width = precision = 0;
  226. if (*f == '%') {
  227. bb_putchar('%');
  228. break;
  229. }
  230. if (*f == 'b') {
  231. if (*argv) {
  232. print_esc_string(*argv);
  233. ++argv;
  234. }
  235. break;
  236. }
  237. if (strchr("-+ #", *f)) {
  238. ++f;
  239. ++direc_length;
  240. }
  241. if (*f == '*') {
  242. ++f;
  243. ++direc_length;
  244. if (*argv)
  245. field_width = get_width_prec(*argv++);
  246. } else {
  247. while (isdigit(*f)) {
  248. ++f;
  249. ++direc_length;
  250. }
  251. }
  252. if (*f == '.') {
  253. ++f;
  254. ++direc_length;
  255. if (*f == '*') {
  256. ++f;
  257. ++direc_length;
  258. if (*argv)
  259. precision = get_width_prec(*argv++);
  260. } else {
  261. while (isdigit(*f)) {
  262. ++f;
  263. ++direc_length;
  264. }
  265. }
  266. }
  267. /* Remove "lLhz" size modifiers, repeatedly.
  268. * bash does not like "%lld", but coreutils
  269. * happily takes even "%Llllhhzhhzd"!
  270. * We are permissive like coreutils */
  271. while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
  272. overlapping_strcpy(f, f + 1);
  273. }
  274. /* Add "ll" if integer modifier, then print */
  275. {
  276. static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
  277. char *p = strchr(format_chars, *f);
  278. /* needed - try "printf %" without it */
  279. if (p == NULL) {
  280. bb_error_msg("%s: invalid format", direc_start);
  281. /* causes main() to exit with error */
  282. return saved_argv - 1;
  283. }
  284. ++direc_length;
  285. if (p - format_chars <= 5) {
  286. /* it is one of "diouxX" */
  287. p = xmalloc(direc_length + 3);
  288. memcpy(p, direc_start, direc_length);
  289. p[direc_length + 1] = p[direc_length - 1];
  290. p[direc_length - 1] = 'l';
  291. p[direc_length] = 'l';
  292. //bb_error_msg("<%s>", p);
  293. direc_length += 2;
  294. direc_start = p;
  295. } else {
  296. p = NULL;
  297. }
  298. if (*argv) {
  299. print_direc(direc_start, direc_length, field_width,
  300. precision, *argv++);
  301. } else {
  302. print_direc(direc_start, direc_length, field_width,
  303. precision, "");
  304. }
  305. *conv_err |= errno;
  306. free(p);
  307. }
  308. break;
  309. case '\\':
  310. if (*++f == 'c') {
  311. return saved_argv; /* causes main() to exit */
  312. }
  313. bb_putchar(bb_process_escape_sequence((const char **)&f));
  314. f--;
  315. break;
  316. default:
  317. putchar(*f);
  318. }
  319. }
  320. return argv;
  321. }
  322. int printf_main(int argc UNUSED_PARAM, char **argv)
  323. {
  324. int conv_err;
  325. char *format;
  326. char **argv2;
  327. /* We must check that stdout is not closed.
  328. * The reason for this is highly non-obvious.
  329. * printf_main is used from shell.
  330. * Shell must correctly handle 'printf "%s" foo'
  331. * if stdout is closed. With stdio, output gets shoveled into
  332. * stdout buffer, and even fflush cannot clear it out. It seems that
  333. * even if libc receives EBADF on write attempts, it feels determined
  334. * to output data no matter what. So it will try later,
  335. * and possibly will clobber future output. Not good. */
  336. // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
  337. if (fcntl(1, F_GETFL) == -1)
  338. return 1; /* match coreutils 6.10 (sans error msg to stderr) */
  339. //if (dup2(1, 1) != 1) - old way
  340. // return 1;
  341. /* bash builtin errors out on "printf '-%s-\n' foo",
  342. * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
  343. * We will mimic coreutils. */
  344. if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
  345. argv++;
  346. if (!argv[1]) {
  347. if (ENABLE_ASH_BUILTIN_PRINTF
  348. && applet_name[0] != 'p'
  349. ) {
  350. bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
  351. return 2; /* bash compat */
  352. }
  353. bb_show_usage();
  354. }
  355. format = argv[1];
  356. argv2 = argv + 2;
  357. conv_err = 0;
  358. do {
  359. argv = argv2;
  360. argv2 = print_formatted(format, argv, &conv_err);
  361. } while (argv2 > argv && *argv2);
  362. /* coreutils compat (bash doesn't do this):
  363. if (*argv)
  364. fprintf(stderr, "excess args ignored");
  365. */
  366. return (argv2 < argv) /* if true, print_formatted errored out */
  367. || conv_err; /* print_formatted saw invalid number */
  368. }