1 /* vi: set sw=4 ts=4: */
2 /* printf - format and print data
4 Copyright 1999 Dave Cinege
5 Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
7 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
26 \0ooo = octal number (ooo is 0 to 3 digits)
27 \xhhh = hexadecimal number (hhh is 1 to 3 digits)
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>
39 /* 19990508 Busy Boxed! Dave Cinege */
41 //config:config PRINTF
42 //config: bool "printf (3.3 kb)"
45 //config: printf is used to format and print specified strings.
46 //config: It's similar to 'echo' except it has more options.
48 //applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))
50 //kbuild:lib-$(CONFIG_PRINTF) += printf.o
52 //kbuild:lib-$(CONFIG_ASH_PRINTF) += printf.o
53 //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
55 //usage:#define printf_trivial_usage
56 //usage: "FORMAT [ARG]..."
57 //usage:#define printf_full_usage "\n\n"
58 //usage: "Format and print ARG(s) according to FORMAT (a-la C printf)"
60 //usage:#define printf_example_usage
61 //usage: "$ printf \"Val=%d\\n\" 5\n"
66 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
68 * bash: printf: XXX: invalid number
69 * printf: XXX: expected a numeric value
70 * bash: printf: 123XXX: invalid number
71 * printf: 123XXX: value not completely converted
72 * but then they use 0 (or partially converted numeric prefix) as a value
73 * and continue. They exit with 1 in this case.
74 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
75 * Both print error message and assume 0 if %*.*f width/precision is "bad"
76 * (but negative numbers are not "bad").
77 * Both accept negative numbers for %u specifier.
79 * We try to be compatible.
82 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
84 static int multiconvert(const char *arg, void *result, converter convert)
86 if (*arg == '"' || *arg == '\'') {
87 arg = utoa((unsigned char)arg[1]);
92 bb_error_msg("invalid number '%s'", arg);
98 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
100 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
101 /* both coreutils 6.10 and bash 3.2:
107 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
110 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
112 *(long long*)result = bb_strtoll(arg, NULL, 0);
114 static void FAST_FUNC conv_strtod(const char *arg, void *result)
117 /* Well, this one allows leading whitespace... so what? */
118 /* What I like much less is that "-" accepted too! :( */
119 *(double*)result = strtod(arg, &end);
122 *(double*)result = 0;
126 /* Callers should check errno to detect errors */
127 static unsigned long long my_xstrtoull(const char *arg)
129 unsigned long long result;
130 if (multiconvert(arg, &result, conv_strtoull))
134 static long long my_xstrtoll(const char *arg)
137 if (multiconvert(arg, &result, conv_strtoll))
141 static double my_xstrtod(const char *arg)
144 multiconvert(arg, &result, conv_strtod);
148 /* Handles %b; return 1 if output is to be short-circuited by \c */
149 static int print_esc_string(const char *str)
152 while ((c = *str) != '\0') {
155 /* %b also accepts 4-digit octals of the form \0### */
157 if ((unsigned char)(str[1] - '0') < 8) {
158 /* 2nd char is 0..7: skip leading '0' */
162 else if (*str == 'c') {
166 /* optimization: don't force arg to be on-stack,
167 * use another variable for that. */
169 c = bb_process_escape_sequence(&z);
179 static void print_direc(char *format, unsigned fmt_length,
180 int field_width, int precision,
181 const char *argument)
186 char *have_prec, *have_width;
188 saved = format[fmt_length];
189 format[fmt_length] = '\0';
191 have_prec = strstr(format, ".*");
192 have_width = strchr(format, '*');
193 if (have_width - 1 == have_prec)
198 switch (format[fmt_length - 1]) {
200 printf(format, *argument);
204 llv = my_xstrtoll(argument);
210 printf(format, precision, llv);
213 printf(format, field_width, llv);
215 printf(format, field_width, precision, llv);
222 llv = my_xstrtoull(argument);
223 /* cheat: unsigned long and long have same width, so... */
226 /* Are char* and long long the same? */
227 if (sizeof(argument) == sizeof(llv)) {
228 llv = (long long)(ptrdiff_t)argument;
231 /* Hope compiler will optimize it out by moving call
232 * instruction after the ifs... */
235 printf(format, argument, /*unused:*/ argument, argument);
237 printf(format, precision, argument, /*unused:*/ argument);
240 printf(format, field_width, argument, /*unused:*/ argument);
242 printf(format, field_width, precision, argument);
251 dv = my_xstrtod(argument);
256 printf(format, precision, dv);
259 printf(format, field_width, dv);
261 printf(format, field_width, precision, dv);
266 format[fmt_length] = saved;
269 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
270 static int get_width_prec(const char *str)
272 int v = bb_strtoi(str, NULL, 10);
274 bb_error_msg("invalid number '%s'", str);
280 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
281 Return advanced ARGV. */
282 static char **print_formatted(char *f, char **argv, int *conv_err)
284 char *direc_start; /* Start of % directive. */
285 unsigned direc_length; /* Length of % directive. */
286 int field_width; /* Arg to first '*' */
287 int precision; /* Arg to second '*' */
288 char **saved_argv = argv;
295 field_width = precision = 0;
302 if (print_esc_string(*argv))
303 return saved_argv; /* causes main() to exit */
308 if (*f && strchr("-+ #", *f)) {
316 field_width = get_width_prec(*argv++);
318 while (isdigit(*f)) {
330 precision = get_width_prec(*argv++);
332 while (isdigit(*f)) {
339 /* Remove "lLhz" size modifiers, repeatedly.
340 * bash does not like "%lld", but coreutils
341 * happily takes even "%Llllhhzhhzd"!
342 * We are permissive like coreutils */
343 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
344 overlapping_strcpy(f, f + 1);
346 /* Add "ll" if integer modifier, then print */
348 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
349 char *p = strchr(format_chars, *f);
350 /* needed - try "printf %" without it */
351 if (p == NULL || *f == '\0') {
352 bb_error_msg("%s: invalid format", direc_start);
353 /* causes main() to exit with error */
354 return saved_argv - 1;
357 if (p - format_chars <= 5) {
358 /* it is one of "diouxX" */
359 p = xmalloc(direc_length + 3);
360 memcpy(p, direc_start, direc_length);
361 p[direc_length + 1] = p[direc_length - 1];
362 p[direc_length - 1] = 'l';
363 p[direc_length] = 'l';
364 //bb_error_msg("<%s>", p);
371 print_direc(direc_start, direc_length, field_width,
374 print_direc(direc_start, direc_length, field_width,
383 return saved_argv; /* causes main() to exit */
385 bb_putchar(bb_process_escape_sequence((const char **)&f));
396 int printf_main(int argc UNUSED_PARAM, char **argv)
402 /* We must check that stdout is not closed.
403 * The reason for this is highly non-obvious.
404 * printf_main is used from shell.
405 * Shell must correctly handle 'printf "%s" foo'
406 * if stdout is closed. With stdio, output gets shoveled into
407 * stdout buffer, and even fflush cannot clear it out. It seems that
408 * even if libc receives EBADF on write attempts, it feels determined
409 * to output data no matter what. So it will try later,
410 * and possibly will clobber future output. Not good. */
411 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
412 if (fcntl(1, F_GETFL) == -1)
413 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
414 //if (dup2(1, 1) != 1) - old way
417 /* bash builtin errors out on "printf '-%s-\n' foo",
418 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
419 * We will mimic coreutils. */
420 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
423 if (ENABLE_ASH_PRINTF
424 && applet_name[0] != 'p'
426 bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
427 return 2; /* bash compat */
438 argv2 = print_formatted(format, argv, &conv_err);
439 } while (argv2 > argv && *argv2);
441 /* coreutils compat (bash doesn't do this):
443 fprintf(stderr, "excess args ignored");
446 return (argv2 < argv) /* if true, print_formatted errored out */
447 || conv_err; /* print_formatted saw invalid number */