1 /* vi: set sw=4 ts=4: */
3 * printf - format and print data
5 * Copyright 1999 Dave Cinege
6 * Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
8 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10 /* Usage: printf format [argument...]
12 * A front end to the printf function that lets it be used from the shell.
20 * \c = produce no further output
23 * \r = carriage return
26 * \0ooo = octal number (ooo is 0 to 3 digits)
27 * \xhhh = hexadecimal number (hhh is 1 to 3 digits)
29 * Additional directive:
31 * %b = print an argument string, interpreting backslash escapes
33 * The 'format' argument is re-used as many times as necessary
34 * to convert all of the given arguments.
36 * David MacKenzie <djm@gnu.ai.mit.edu>
38 /* 19990508 Busy Boxed! Dave Cinege */
40 //config:config PRINTF
41 //config: bool "printf (3.8 kb)"
44 //config: printf is used to format and print specified strings.
45 //config: It's similar to 'echo' except it has more options.
47 //applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))
49 //kbuild:lib-$(CONFIG_PRINTF) += printf.o
50 //kbuild:lib-$(CONFIG_ASH_PRINTF) += printf.o
51 //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
53 //usage:#define printf_trivial_usage
54 //usage: "FORMAT [ARG]..."
55 //usage:#define printf_full_usage "\n\n"
56 //usage: "Format and print ARG(s) according to FORMAT (a-la C printf)"
58 //usage:#define printf_example_usage
59 //usage: "$ printf \"Val=%d\\n\" 5\n"
64 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
66 * bash: printf: XXX: invalid number
67 * printf: XXX: expected a numeric value
68 * bash: printf: 123XXX: invalid number
69 * printf: 123XXX: value not completely converted
70 * but then they use 0 (or partially converted numeric prefix) as a value
71 * and continue. They exit with 1 in this case.
72 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
73 * Both print error message and assume 0 if %*.*f width/precision is "bad"
74 * (but negative numbers are not "bad").
75 * Both accept negative numbers for %u specifier.
77 * We try to be compatible.
80 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
82 #define WANT_HEX_ESCAPES 0
84 /* Usual "this only works for ascii compatible encodings" disclaimer. */
86 #define _tolower(X) ((X)|((char) 0x20))
88 char FAST_FUNC bb_process_escape_sequence(const char **ptr)
99 if (WANT_HEX_ESCAPES && *q == 'x') {
105 /* bash requires leading 0 in octal escapes:
106 * \02 works, \2 does not (prints \ and 2).
107 * We treat \2 as a valid octal escape sequence. */
110 unsigned d = (unsigned char)(*q) - '0';
113 d = (unsigned char)_tolower(*q) - 'a';
115 /* The above would map 'A'-'F' and 'a'-'f' to 10-15,
116 * however, some chars like '@' would map to 9 < base.
117 * Do not allow that, map invalid chars to N > base:
124 if (WANT_HEX_ESCAPES && base == 16) {
126 if (num_digits == 0) {
127 /* \x<bad_char>: return '\',
128 * leave ptr pointing to x */
142 } while (++num_digits < 3);
144 if (num_digits == 0) {
145 /* Not octal or hex escape sequence.
146 * Is it one-letter one? */
148 /* bash builtin "echo -e '\ec'" interprets \e as ESC,
149 * but coreutils "/bin/echo -e '\ec'" does not.
150 * Manpages tend to support coreutils way.
151 * Update: coreutils added support for \e on 28 Oct 2009. */
152 static const char charmap[] ALIGN1 = {
153 'a', 'b', 'e', 'f', 'n', 'r', 't', 'v', '\\', '\0',
154 '\a', '\b', 27, '\f', '\n', '\r', '\t', '\v', '\\', '\\',
156 const char *p = charmap;
162 } while (*++p != '\0');
163 /* p points to found escape char or NUL,
164 * advance it and find what it translates to.
165 * Note that \NUL and unrecognized sequence \z return '\'
166 * and leave ptr pointing to NUL or z. */
167 n = p[sizeof(charmap) / 2];
175 char* FAST_FUNC skip_whitespace(const char *s)
177 /* In POSIX/C locale (the only locale we care about: do we REALLY want
178 * to allow Unicode whitespace in, say, .conf files? nuts!)
179 * isspace is only these chars: "\t\n\v\f\r" and space.
180 * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
183 while (*s == ' ' || (unsigned char)(*s - 9) <= (13 - 9))
189 /* Like strcpy but can copy overlapping strings. */
190 void FAST_FUNC overlapping_strcpy(char *dst, const char *src)
192 /* Cheap optimization for dst == src case -
193 * better to have it here than in many callers.
196 while ((*dst = *src) != '\0') {
203 static int multiconvert(const char *arg, void *result, converter convert)
205 if (*arg == '"' || *arg == '\'') {
206 arg = utoa((unsigned char)arg[1]);
209 convert(arg, result);
211 bb_error_msg("invalid number '%s'", arg);
217 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
219 /* Allow leading '+' - bb_strtoull() by itself does not allow it,
220 * and probably shouldn't (other callers might require purely numeric
221 * inputs to be allowed.
225 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
226 /* both coreutils 6.10 and bash 3.2:
232 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
235 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
239 *(long long*)result = bb_strtoll(arg, NULL, 0);
241 static void FAST_FUNC conv_strtod(const char *arg, void *result)
244 /* Well, this one allows leading whitespace... so what? */
245 /* What I like much less is that "-" accepted too! :( */
246 *(double*)result = strtod(arg, &end);
249 *(double*)result = 0;
253 /* Callers should check errno to detect errors */
254 static unsigned long long my_xstrtoull(const char *arg)
256 unsigned long long result;
257 if (multiconvert(arg, &result, conv_strtoull))
261 static long long my_xstrtoll(const char *arg)
264 if (multiconvert(arg, &result, conv_strtoll))
268 static double my_xstrtod(const char *arg)
271 multiconvert(arg, &result, conv_strtod);
275 /* Handles %b; return 1 if output is to be short-circuited by \c */
276 static int print_esc_string(const char *str)
279 while ((c = *str) != '\0') {
282 /* %b also accepts 4-digit octals of the form \0### */
284 if ((unsigned char)(str[1] - '0') < 8) {
285 /* 2nd char is 0..7: skip leading '0' */
289 else if (*str == 'c') {
293 /* optimization: don't force arg to be on-stack,
294 * use another variable for that. */
296 c = bb_process_escape_sequence(&z);
306 static void print_direc(char *format, unsigned fmt_length,
307 int field_width, int precision,
308 const char *argument)
313 char *have_prec, *have_width;
315 saved = format[fmt_length];
316 format[fmt_length] = '\0';
318 have_prec = strstr(format, ".*");
319 have_width = strchr(format, '*');
320 if (have_width - 1 == have_prec)
323 /* multiconvert sets errno = 0, but %s needs it cleared */
326 switch (format[fmt_length - 1]) {
328 printf(format, *argument);
332 llv = my_xstrtoll(skip_whitespace(argument));
338 printf(format, precision, llv);
341 printf(format, field_width, llv);
343 printf(format, field_width, precision, llv);
350 llv = my_xstrtoull(skip_whitespace(argument));
351 /* cheat: unsigned long and long have same width, so... */
354 /* Are char* and long long the same? */
355 if (sizeof(argument) == sizeof(llv)) {
356 llv = (long long)(ptrdiff_t)argument;
359 /* Hope compiler will optimize it out by moving call
360 * instruction after the ifs... */
363 printf(format, argument, /*unused:*/ argument, argument);
365 printf(format, precision, argument, /*unused:*/ argument);
368 printf(format, field_width, argument, /*unused:*/ argument);
370 printf(format, field_width, precision, argument);
379 dv = my_xstrtod(argument);
384 printf(format, precision, dv);
387 printf(format, field_width, dv);
389 printf(format, field_width, precision, dv);
394 format[fmt_length] = saved;
397 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
398 static int get_width_prec(const char *str)
400 int v = bb_strtoi(str, NULL, 10);
402 bb_error_msg("invalid number '%s'", str);
408 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
409 Return advanced ARGV. */
410 static char **print_formatted(char *f, char **argv, int *conv_err)
412 char *direc_start; /* Start of % directive. */
413 unsigned direc_length; /* Length of % directive. */
414 int field_width; /* Arg to first '*' */
415 int precision; /* Arg to second '*' */
416 char **saved_argv = argv;
423 field_width = precision = 0;
430 if (print_esc_string(*argv))
431 return saved_argv; /* causes main() to exit */
436 if (*f && strchr("-+ #", *f)) {
444 field_width = get_width_prec(*argv++);
446 while (isdigit(*f)) {
458 precision = get_width_prec(*argv++);
460 while (isdigit(*f)) {
467 /* Remove "lLhz" size modifiers, repeatedly.
468 * bash does not like "%lld", but coreutils
469 * happily takes even "%Llllhhzhhzd"!
470 * We are permissive like coreutils */
471 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
472 overlapping_strcpy(f, f + 1);
474 /* Add "ll" if integer modifier, then print */
476 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
477 char *p = strchr(format_chars, *f);
478 /* needed - try "printf %" without it */
479 if (p == NULL || *f == '\0') {
480 bb_error_msg("%s: invalid format", direc_start);
481 /* causes main() to exit with error */
482 return saved_argv - 1;
485 if (p - format_chars <= 5) {
486 /* it is one of "diouxX" */
487 p = xmalloc(direc_length + 3);
488 memcpy(p, direc_start, direc_length);
489 p[direc_length + 1] = p[direc_length - 1];
490 p[direc_length - 1] = 'l';
491 p[direc_length] = 'l';
492 //bb_error_msg("<%s>", p);
499 print_direc(direc_start, direc_length, field_width,
502 print_direc(direc_start, direc_length, field_width,
511 return saved_argv; /* causes main() to exit */
513 bb_putchar(bb_process_escape_sequence((const char **)&f));
524 int printf_main(int argc UNUSED_PARAM, char **argv)
530 /* We must check that stdout is not closed.
531 * The reason for this is highly non-obvious.
532 * printf_main is used from shell.
533 * Shell must correctly handle 'printf "%s" foo'
534 * if stdout is closed. With stdio, output gets shoveled into
535 * stdout buffer, and even fflush cannot clear it out. It seems that
536 * even if libc receives EBADF on write attempts, it feels determined
537 * to output data no matter what. So it will try later,
538 * and possibly will clobber future output. Not good. */
539 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
540 if (fcntl(1, F_GETFL) == -1)
541 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
542 //if (dup2(1, 1) != 1) - old way
545 /* bash builtin errors out on "printf '-%s-\n' foo",
546 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
547 * We will mimic coreutils. */
548 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
551 if (ENABLE_ASH_PRINTF
552 && applet_name[0] != 'p'
554 bb_simple_error_msg("usage: printf FORMAT [ARGUMENT...]");
555 return 2; /* bash compat */
566 argv2 = print_formatted(format, argv, &conv_err);
567 } while (argv2 > argv && *argv2);
569 /* coreutils compat (bash doesn't do this):
571 fprintf(stderr, "excess args ignored");
574 return (argv2 < argv) /* if true, print_formatted errored out */
575 || conv_err; /* print_formatted saw invalid number */