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
51 //kbuild:lib-$(CONFIG_ASH_PRINTF) += printf.o
52 //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
54 //usage:#define printf_trivial_usage
55 //usage: "FORMAT [ARG]..."
56 //usage:#define printf_full_usage "\n\n"
57 //usage: "Format and print ARG(s) according to FORMAT (a-la C printf)"
59 //usage:#define printf_example_usage
60 //usage: "$ printf \"Val=%d\\n\" 5\n"
65 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
67 * bash: printf: XXX: invalid number
68 * printf: XXX: expected a numeric value
69 * bash: printf: 123XXX: invalid number
70 * printf: 123XXX: value not completely converted
71 * but then they use 0 (or partially converted numeric prefix) as a value
72 * and continue. They exit with 1 in this case.
73 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
74 * Both print error message and assume 0 if %*.*f width/precision is "bad"
75 * (but negative numbers are not "bad").
76 * Both accept negative numbers for %u specifier.
78 * We try to be compatible.
81 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
83 static int multiconvert(const char *arg, void *result, converter convert)
85 if (*arg == '"' || *arg == '\'') {
86 arg = utoa((unsigned char)arg[1]);
91 bb_error_msg("invalid number '%s'", arg);
97 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
99 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
100 /* both coreutils 6.10 and bash 3.2:
106 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
109 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
111 *(long long*)result = bb_strtoll(arg, NULL, 0);
113 static void FAST_FUNC conv_strtod(const char *arg, void *result)
116 /* Well, this one allows leading whitespace... so what? */
117 /* What I like much less is that "-" accepted too! :( */
118 *(double*)result = strtod(arg, &end);
121 *(double*)result = 0;
125 /* Callers should check errno to detect errors */
126 static unsigned long long my_xstrtoull(const char *arg)
128 unsigned long long result;
129 if (multiconvert(arg, &result, conv_strtoull))
133 static long long my_xstrtoll(const char *arg)
136 if (multiconvert(arg, &result, conv_strtoll))
140 static double my_xstrtod(const char *arg)
143 multiconvert(arg, &result, conv_strtod);
147 /* Handles %b; return 1 if output is to be short-circuited by \c */
148 static int print_esc_string(const char *str)
151 while ((c = *str) != '\0') {
154 /* %b also accepts 4-digit octals of the form \0### */
156 if ((unsigned char)(str[1] - '0') < 8) {
157 /* 2nd char is 0..7: skip leading '0' */
161 else if (*str == 'c') {
165 /* optimization: don't force arg to be on-stack,
166 * use another variable for that. */
168 c = bb_process_escape_sequence(&z);
178 static void print_direc(char *format, unsigned fmt_length,
179 int field_width, int precision,
180 const char *argument)
185 char *have_prec, *have_width;
187 saved = format[fmt_length];
188 format[fmt_length] = '\0';
190 have_prec = strstr(format, ".*");
191 have_width = strchr(format, '*');
192 if (have_width - 1 == have_prec)
197 switch (format[fmt_length - 1]) {
199 printf(format, *argument);
203 llv = my_xstrtoll(argument);
209 printf(format, precision, llv);
212 printf(format, field_width, llv);
214 printf(format, field_width, precision, llv);
221 llv = my_xstrtoull(argument);
222 /* cheat: unsigned long and long have same width, so... */
225 /* Are char* and long long the same? */
226 if (sizeof(argument) == sizeof(llv)) {
227 llv = (long long)(ptrdiff_t)argument;
230 /* Hope compiler will optimize it out by moving call
231 * instruction after the ifs... */
234 printf(format, argument, /*unused:*/ argument, argument);
236 printf(format, precision, argument, /*unused:*/ argument);
239 printf(format, field_width, argument, /*unused:*/ argument);
241 printf(format, field_width, precision, argument);
250 dv = my_xstrtod(argument);
255 printf(format, precision, dv);
258 printf(format, field_width, dv);
260 printf(format, field_width, precision, dv);
265 format[fmt_length] = saved;
268 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
269 static int get_width_prec(const char *str)
271 int v = bb_strtoi(str, NULL, 10);
273 bb_error_msg("invalid number '%s'", str);
279 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
280 Return advanced ARGV. */
281 static char **print_formatted(char *f, char **argv, int *conv_err)
283 char *direc_start; /* Start of % directive. */
284 unsigned direc_length; /* Length of % directive. */
285 int field_width; /* Arg to first '*' */
286 int precision; /* Arg to second '*' */
287 char **saved_argv = argv;
294 field_width = precision = 0;
301 if (print_esc_string(*argv))
302 return saved_argv; /* causes main() to exit */
307 if (*f && strchr("-+ #", *f)) {
315 field_width = get_width_prec(*argv++);
317 while (isdigit(*f)) {
329 precision = get_width_prec(*argv++);
331 while (isdigit(*f)) {
338 /* Remove "lLhz" size modifiers, repeatedly.
339 * bash does not like "%lld", but coreutils
340 * happily takes even "%Llllhhzhhzd"!
341 * We are permissive like coreutils */
342 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
343 overlapping_strcpy(f, f + 1);
345 /* Add "ll" if integer modifier, then print */
347 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
348 char *p = strchr(format_chars, *f);
349 /* needed - try "printf %" without it */
350 if (p == NULL || *f == '\0') {
351 bb_error_msg("%s: invalid format", direc_start);
352 /* causes main() to exit with error */
353 return saved_argv - 1;
356 if (p - format_chars <= 5) {
357 /* it is one of "diouxX" */
358 p = xmalloc(direc_length + 3);
359 memcpy(p, direc_start, direc_length);
360 p[direc_length + 1] = p[direc_length - 1];
361 p[direc_length - 1] = 'l';
362 p[direc_length] = 'l';
363 //bb_error_msg("<%s>", p);
370 print_direc(direc_start, direc_length, field_width,
373 print_direc(direc_start, direc_length, field_width,
382 return saved_argv; /* causes main() to exit */
384 bb_putchar(bb_process_escape_sequence((const char **)&f));
395 int printf_main(int argc UNUSED_PARAM, char **argv)
401 /* We must check that stdout is not closed.
402 * The reason for this is highly non-obvious.
403 * printf_main is used from shell.
404 * Shell must correctly handle 'printf "%s" foo'
405 * if stdout is closed. With stdio, output gets shoveled into
406 * stdout buffer, and even fflush cannot clear it out. It seems that
407 * even if libc receives EBADF on write attempts, it feels determined
408 * to output data no matter what. So it will try later,
409 * and possibly will clobber future output. Not good. */
410 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
411 if (fcntl(1, F_GETFL) == -1)
412 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
413 //if (dup2(1, 1) != 1) - old way
416 /* bash builtin errors out on "printf '-%s-\n' foo",
417 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
418 * We will mimic coreutils. */
419 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
422 if (ENABLE_ASH_PRINTF
423 && applet_name[0] != 'p'
425 bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
426 return 2; /* bash compat */
437 argv2 = print_formatted(format, argv, &conv_err);
438 } while (argv2 > argv && *argv2);
440 /* coreutils compat (bash doesn't do this):
442 fprintf(stderr, "excess args ignored");
445 return (argv2 < argv) /* if true, print_formatted errored out */
446 || conv_err; /* print_formatted saw invalid number */