3
0

printf.c 10 KB

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