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 //usage:#define printf_trivial_usage
42 //usage: "FORMAT [ARGUMENT]..."
43 //usage:#define printf_full_usage "\n\n"
44 //usage: "Format and print ARGUMENT(s) according to FORMAT,\n"
45 //usage: "where FORMAT controls the output exactly as in C printf"
47 //usage:#define printf_example_usage
48 //usage: "$ printf \"Val=%d\\n\" 5\n"
53 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
55 * bash: printf: XXX: invalid number
56 * printf: XXX: expected a numeric value
57 * bash: printf: 123XXX: invalid number
58 * printf: 123XXX: value not completely converted
59 * but then they use 0 (or partially converted numeric prefix) as a value
60 * and continue. They exit with 1 in this case.
61 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
62 * Both print error message and assume 0 if %*.*f width/precision is "bad"
63 * (but negative numbers are not "bad").
64 * Both accept negative numbers for %u specifier.
66 * We try to be compatible.
69 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
71 static int multiconvert(const char *arg, void *result, converter convert)
73 if (*arg == '"' || *arg == '\'') {
74 arg = utoa((unsigned char)arg[1]);
79 bb_error_msg("invalid number '%s'", arg);
85 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
87 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
88 /* both coreutils 6.10 and bash 3.2:
94 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
97 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
99 *(long long*)result = bb_strtoll(arg, NULL, 0);
101 static void FAST_FUNC conv_strtod(const char *arg, void *result)
104 /* Well, this one allows leading whitespace... so what? */
105 /* What I like much less is that "-" accepted too! :( */
106 *(double*)result = strtod(arg, &end);
109 *(double*)result = 0;
113 /* Callers should check errno to detect errors */
114 static unsigned long long my_xstrtoull(const char *arg)
116 unsigned long long result;
117 if (multiconvert(arg, &result, conv_strtoull))
121 static long long my_xstrtoll(const char *arg)
124 if (multiconvert(arg, &result, conv_strtoll))
128 static double my_xstrtod(const char *arg)
131 multiconvert(arg, &result, conv_strtod);
135 static void print_esc_string(const char *str)
138 while ((c = *str) != '\0') {
141 c = bb_process_escape_sequence(&str);
146 static void print_direc(char *format, unsigned fmt_length,
147 int field_width, int precision,
148 const char *argument)
153 char *have_prec, *have_width;
155 saved = format[fmt_length];
156 format[fmt_length] = '\0';
158 have_prec = strstr(format, ".*");
159 have_width = strchr(format, '*');
160 if (have_width - 1 == have_prec)
165 switch (format[fmt_length - 1]) {
167 printf(format, *argument);
171 llv = my_xstrtoll(argument);
177 printf(format, precision, llv);
180 printf(format, field_width, llv);
182 printf(format, field_width, precision, llv);
189 llv = my_xstrtoull(argument);
190 /* cheat: unsigned long and long have same width, so... */
193 /* Are char* and long long the same? */
194 if (sizeof(argument) == sizeof(llv)) {
195 llv = (long long)(ptrdiff_t)argument;
198 /* Hope compiler will optimize it out by moving call
199 * instruction after the ifs... */
202 printf(format, argument, /*unused:*/ argument, argument);
204 printf(format, precision, argument, /*unused:*/ argument);
207 printf(format, field_width, argument, /*unused:*/ argument);
209 printf(format, field_width, precision, argument);
218 dv = my_xstrtod(argument);
223 printf(format, precision, dv);
226 printf(format, field_width, dv);
228 printf(format, field_width, precision, dv);
233 format[fmt_length] = saved;
236 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
237 static int get_width_prec(const char *str)
239 int v = bb_strtoi(str, NULL, 10);
241 bb_error_msg("invalid number '%s'", str);
247 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
248 Return advanced ARGV. */
249 static char **print_formatted(char *f, char **argv, int *conv_err)
251 char *direc_start; /* Start of % directive. */
252 unsigned direc_length; /* Length of % directive. */
253 int field_width; /* Arg to first '*' */
254 int precision; /* Arg to second '*' */
255 char **saved_argv = argv;
262 field_width = precision = 0;
269 print_esc_string(*argv);
274 if (strchr("-+ #", *f)) {
282 field_width = get_width_prec(*argv++);
284 while (isdigit(*f)) {
296 precision = get_width_prec(*argv++);
298 while (isdigit(*f)) {
305 /* Remove "lLhz" size modifiers, repeatedly.
306 * bash does not like "%lld", but coreutils
307 * happily takes even "%Llllhhzhhzd"!
308 * We are permissive like coreutils */
309 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
310 overlapping_strcpy(f, f + 1);
312 /* Add "ll" if integer modifier, then print */
314 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
315 char *p = strchr(format_chars, *f);
316 /* needed - try "printf %" without it */
318 bb_error_msg("%s: invalid format", direc_start);
319 /* causes main() to exit with error */
320 return saved_argv - 1;
323 if (p - format_chars <= 5) {
324 /* it is one of "diouxX" */
325 p = xmalloc(direc_length + 3);
326 memcpy(p, direc_start, direc_length);
327 p[direc_length + 1] = p[direc_length - 1];
328 p[direc_length - 1] = 'l';
329 p[direc_length] = 'l';
330 //bb_error_msg("<%s>", p);
337 print_direc(direc_start, direc_length, field_width,
340 print_direc(direc_start, direc_length, field_width,
349 return saved_argv; /* causes main() to exit */
351 bb_putchar(bb_process_escape_sequence((const char **)&f));
362 int printf_main(int argc UNUSED_PARAM, char **argv)
368 /* We must check that stdout is not closed.
369 * The reason for this is highly non-obvious.
370 * printf_main is used from shell.
371 * Shell must correctly handle 'printf "%s" foo'
372 * if stdout is closed. With stdio, output gets shoveled into
373 * stdout buffer, and even fflush cannot clear it out. It seems that
374 * even if libc receives EBADF on write attempts, it feels determined
375 * to output data no matter what. So it will try later,
376 * and possibly will clobber future output. Not good. */
377 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
378 if (fcntl(1, F_GETFL) == -1)
379 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
380 //if (dup2(1, 1) != 1) - old way
383 /* bash builtin errors out on "printf '-%s-\n' foo",
384 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
385 * We will mimic coreutils. */
386 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
389 if (ENABLE_ASH_BUILTIN_PRINTF
390 && applet_name[0] != 'p'
392 bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
393 return 2; /* bash compat */
404 argv2 = print_formatted(format, argv, &conv_err);
405 } while (argv2 > argv && *argv2);
407 /* coreutils compat (bash doesn't do this):
409 fprintf(stderr, "excess args ignored");
412 return (argv2 < argv) /* if true, print_formatted errored out */
413 || conv_err; /* print_formatted saw invalid number */