printf.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 GPL v2 or later, see file LICENSE in this tarball for details.
  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("%s: invalid number", 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(char *str)
  108. {
  109. while (*str) {
  110. if (*str == '\\') {
  111. str++;
  112. bb_putchar(bb_process_escape_sequence((const char **)&str));
  113. } else {
  114. bb_putchar(*str);
  115. str++;
  116. }
  117. }
  118. }
  119. static void print_direc(char *format, unsigned fmt_length,
  120. int field_width, int precision,
  121. const char *argument)
  122. {
  123. long long llv;
  124. double dv;
  125. char saved;
  126. char *have_prec, *have_width;
  127. saved = format[fmt_length];
  128. format[fmt_length] = '\0';
  129. have_prec = strstr(format, ".*");
  130. have_width = strchr(format, '*');
  131. if (have_width - 1 == have_prec)
  132. have_width = NULL;
  133. errno = 0;
  134. switch (format[fmt_length - 1]) {
  135. case 'c':
  136. printf(format, *argument);
  137. break;
  138. case 'd':
  139. case 'i':
  140. llv = my_xstrtoll(argument);
  141. print_long:
  142. if (!have_width) {
  143. if (!have_prec)
  144. printf(format, llv);
  145. else
  146. printf(format, precision, llv);
  147. } else {
  148. if (!have_prec)
  149. printf(format, field_width, llv);
  150. else
  151. printf(format, field_width, precision, llv);
  152. }
  153. break;
  154. case 'o':
  155. case 'u':
  156. case 'x':
  157. case 'X':
  158. llv = my_xstrtoull(argument);
  159. /* cheat: unsigned long and long have same width, so... */
  160. goto print_long;
  161. case 's':
  162. /* Are char* and long long the same? */
  163. if (sizeof(argument) == sizeof(llv)) {
  164. llv = (long long)(ptrdiff_t)argument;
  165. goto print_long;
  166. } else {
  167. /* Hope compiler will optimize it out by moving call
  168. * instruction after the ifs... */
  169. if (!have_width) {
  170. if (!have_prec)
  171. printf(format, argument, /*unused:*/ argument, argument);
  172. else
  173. printf(format, precision, argument, /*unused:*/ argument);
  174. } else {
  175. if (!have_prec)
  176. printf(format, field_width, argument, /*unused:*/ argument);
  177. else
  178. printf(format, field_width, precision, argument);
  179. }
  180. break;
  181. }
  182. case 'f':
  183. case 'e':
  184. case 'E':
  185. case 'g':
  186. case 'G':
  187. dv = my_xstrtod(argument);
  188. if (!have_width) {
  189. if (!have_prec)
  190. printf(format, dv);
  191. else
  192. printf(format, precision, dv);
  193. } else {
  194. if (!have_prec)
  195. printf(format, field_width, dv);
  196. else
  197. printf(format, field_width, precision, dv);
  198. }
  199. break;
  200. } /* switch */
  201. format[fmt_length] = saved;
  202. }
  203. /* Handle params for "%*.*f". Negative numbers are ok (compat). */
  204. static int get_width_prec(const char *str)
  205. {
  206. int v = bb_strtoi(str, NULL, 10);
  207. if (errno) {
  208. bb_error_msg("%s: invalid number", str);
  209. v = 0;
  210. }
  211. return v;
  212. }
  213. /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
  214. Return advanced ARGV. */
  215. static char **print_formatted(char *f, char **argv, int *conv_err)
  216. {
  217. char *direc_start; /* Start of % directive. */
  218. unsigned direc_length; /* Length of % directive. */
  219. int field_width; /* Arg to first '*' */
  220. int precision; /* Arg to second '*' */
  221. char **saved_argv = argv;
  222. for (; *f; ++f) {
  223. switch (*f) {
  224. case '%':
  225. direc_start = f++;
  226. direc_length = 1;
  227. field_width = precision = 0;
  228. if (*f == '%') {
  229. bb_putchar('%');
  230. break;
  231. }
  232. if (*f == 'b') {
  233. if (*argv) {
  234. print_esc_string(*argv);
  235. ++argv;
  236. }
  237. break;
  238. }
  239. if (strchr("-+ #", *f)) {
  240. ++f;
  241. ++direc_length;
  242. }
  243. if (*f == '*') {
  244. ++f;
  245. ++direc_length;
  246. if (*argv)
  247. field_width = get_width_prec(*argv++);
  248. } else {
  249. while (isdigit(*f)) {
  250. ++f;
  251. ++direc_length;
  252. }
  253. }
  254. if (*f == '.') {
  255. ++f;
  256. ++direc_length;
  257. if (*f == '*') {
  258. ++f;
  259. ++direc_length;
  260. if (*argv)
  261. precision = get_width_prec(*argv++);
  262. } else {
  263. while (isdigit(*f)) {
  264. ++f;
  265. ++direc_length;
  266. }
  267. }
  268. }
  269. /* Remove "lLhz" size modifiers, repeatedly.
  270. * bash does not like "%lld", but coreutils
  271. * happily takes even "%Llllhhzhhzd"!
  272. * We are permissive like coreutils */
  273. while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
  274. overlapping_strcpy(f, f + 1);
  275. }
  276. /* Add "ll" if integer modifier, then print */
  277. {
  278. static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
  279. char *p = strchr(format_chars, *f);
  280. /* needed - try "printf %" without it */
  281. if (p == NULL) {
  282. bb_error_msg("%s: invalid format", direc_start);
  283. /* causes main() to exit with error */
  284. return saved_argv - 1;
  285. }
  286. ++direc_length;
  287. if (p - format_chars <= 5) {
  288. /* it is one of "diouxX" */
  289. p = xmalloc(direc_length + 3);
  290. memcpy(p, direc_start, direc_length);
  291. p[direc_length + 1] = p[direc_length - 1];
  292. p[direc_length - 1] = 'l';
  293. p[direc_length] = 'l';
  294. //bb_error_msg("<%s>", p);
  295. direc_length += 2;
  296. direc_start = p;
  297. } else {
  298. p = NULL;
  299. }
  300. if (*argv) {
  301. print_direc(direc_start, direc_length, field_width,
  302. precision, *argv++);
  303. } else {
  304. print_direc(direc_start, direc_length, field_width,
  305. precision, "");
  306. }
  307. *conv_err |= errno;
  308. free(p);
  309. }
  310. break;
  311. case '\\':
  312. if (*++f == 'c') {
  313. return saved_argv; /* causes main() to exit */
  314. }
  315. bb_putchar(bb_process_escape_sequence((const char **)&f));
  316. f--;
  317. break;
  318. default:
  319. bb_putchar(*f);
  320. }
  321. }
  322. return argv;
  323. }
  324. int printf_main(int argc UNUSED_PARAM, char **argv)
  325. {
  326. int conv_err;
  327. char *format;
  328. char **argv2;
  329. /* We must check that stdout is not closed.
  330. * The reason for this is highly non-obvious.
  331. * printf_main is used from shell.
  332. * Shell must correctly handle 'printf "%s" foo'
  333. * if stdout is closed. With stdio, output gets shoveled into
  334. * stdout buffer, and even fflush cannot clear it out. It seems that
  335. * even if libc receives EBADF on write attempts, it feels determined
  336. * to output data no matter what. So it will try later,
  337. * and possibly will clobber future output. Not good. */
  338. // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
  339. if (fcntl(1, F_GETFL) == -1)
  340. return 1; /* match coreutils 6.10 (sans error msg to stderr) */
  341. //if (dup2(1, 1) != 1) - old way
  342. // return 1;
  343. /* bash builtin errors out on "printf '-%s-\n' foo",
  344. * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
  345. * We will mimic coreutils. */
  346. if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
  347. argv++;
  348. if (!argv[1]) {
  349. if (ENABLE_ASH_BUILTIN_PRINTF
  350. && applet_name[0] != 'p'
  351. ) {
  352. bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
  353. return 2; /* bash compat */
  354. }
  355. bb_show_usage();
  356. }
  357. format = argv[1];
  358. argv2 = argv + 2;
  359. conv_err = 0;
  360. do {
  361. argv = argv2;
  362. argv2 = print_formatted(format, argv, &conv_err);
  363. } while (argv2 > argv && *argv2);
  364. /* coreutils compat (bash doesn't do this):
  365. if (*argv)
  366. fprintf(stderr, "excess args ignored");
  367. */
  368. return (argv2 < argv) /* if true, print_formatted errored out */
  369. || conv_err; /* print_formatted saw invalid number */
  370. }