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 GPL v2 or later, see file LICENSE in this tarball for details.
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
43 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
45 * bash: printf: XXX: invalid number
46 * printf: XXX: expected a numeric value
47 * bash: printf: 123XXX: invalid number
48 * printf: 123XXX: value not completely converted
49 * but then they use 0 (or partially converted numeric prefix) as a value
50 * and continue. They exit with 1 in this case.
51 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
52 * Both print error message and assume 0 if %*.*f width/precision is "bad"
53 * (but negative numbers are not "bad").
54 * Both accept negative numbers for %u specifier.
56 * We try to be compatible.
59 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
61 static int multiconvert(const char *arg, void *result, converter convert)
63 if (*arg == '"' || *arg == '\'') {
64 arg = utoa((unsigned char)arg[1]);
69 bb_error_msg("%s: invalid number", arg);
75 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
77 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
78 /* both coreutils 6.10 and bash 3.2:
84 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
87 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
89 *(long long*)result = bb_strtoll(arg, NULL, 0);
91 static void FAST_FUNC conv_strtod(const char *arg, void *result)
94 /* Well, this one allows leading whitespace... so what? */
95 /* What I like much less is that "-" accepted too! :( */
96 *(double*)result = strtod(arg, &end);
103 /* Callers should check errno to detect errors */
104 static unsigned long long my_xstrtoull(const char *arg)
106 unsigned long long result;
107 if (multiconvert(arg, &result, conv_strtoull))
111 static long long my_xstrtoll(const char *arg)
114 if (multiconvert(arg, &result, conv_strtoll))
118 static double my_xstrtod(const char *arg)
121 multiconvert(arg, &result, conv_strtod);
125 static void print_esc_string(char *str)
130 bb_putchar(bb_process_escape_sequence((const char **)&str));
138 static void print_direc(char *format, unsigned fmt_length,
139 int field_width, int precision,
140 const char *argument)
145 char *have_prec, *have_width;
147 saved = format[fmt_length];
148 format[fmt_length] = '\0';
150 have_prec = strstr(format, ".*");
151 have_width = strchr(format, '*');
152 if (have_width - 1 == have_prec)
157 switch (format[fmt_length - 1]) {
159 printf(format, *argument);
163 llv = my_xstrtoll(argument);
169 printf(format, precision, llv);
172 printf(format, field_width, llv);
174 printf(format, field_width, precision, llv);
181 llv = my_xstrtoull(argument);
182 /* cheat: unsigned long and long have same width, so... */
185 /* Are char* and long long the same? */
186 if (sizeof(argument) == sizeof(llv)) {
187 llv = (long long)(ptrdiff_t)argument;
190 /* Hope compiler will optimize it out by moving call
191 * instruction after the ifs... */
194 printf(format, argument, /*unused:*/ argument, argument);
196 printf(format, precision, argument, /*unused:*/ argument);
199 printf(format, field_width, argument, /*unused:*/ argument);
201 printf(format, field_width, precision, argument);
210 dv = my_xstrtod(argument);
215 printf(format, precision, dv);
218 printf(format, field_width, dv);
220 printf(format, field_width, precision, dv);
225 format[fmt_length] = saved;
228 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
229 static int get_width_prec(const char *str)
231 int v = bb_strtoi(str, NULL, 10);
233 bb_error_msg("%s: invalid number", str);
239 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
240 Return advanced ARGV. */
241 static char **print_formatted(char *f, char **argv, int *conv_err)
243 char *direc_start; /* Start of % directive. */
244 unsigned direc_length; /* Length of % directive. */
245 int field_width; /* Arg to first '*' */
246 int precision; /* Arg to second '*' */
247 char **saved_argv = argv;
254 field_width = precision = 0;
261 print_esc_string(*argv);
266 if (strchr("-+ #", *f)) {
274 field_width = get_width_prec(*argv++);
276 while (isdigit(*f)) {
288 precision = get_width_prec(*argv++);
290 while (isdigit(*f)) {
297 /* Remove "lLhz" size modifiers, repeatedly.
298 * bash does not like "%lld", but coreutils
299 * happily takes even "%Llllhhzhhzd"!
300 * We are permissive like coreutils */
301 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
302 overlapping_strcpy(f, f + 1);
304 /* Add "ll" if integer modifier, then print */
306 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
307 char *p = strchr(format_chars, *f);
308 /* needed - try "printf %" without it */
310 bb_error_msg("%s: invalid format", direc_start);
311 /* causes main() to exit with error */
312 return saved_argv - 1;
315 if (p - format_chars <= 5) {
316 /* it is one of "diouxX" */
317 p = xmalloc(direc_length + 3);
318 memcpy(p, direc_start, direc_length);
319 p[direc_length + 1] = p[direc_length - 1];
320 p[direc_length - 1] = 'l';
321 p[direc_length] = 'l';
322 //bb_error_msg("<%s>", p);
329 print_direc(direc_start, direc_length, field_width,
332 print_direc(direc_start, direc_length, field_width,
341 return saved_argv; /* causes main() to exit */
343 bb_putchar(bb_process_escape_sequence((const char **)&f));
354 int printf_main(int argc UNUSED_PARAM, char **argv)
360 /* We must check that stdout is not closed.
361 * The reason for this is highly non-obvious.
362 * printf_main is used from shell.
363 * Shell must correctly handle 'printf "%s" foo'
364 * if stdout is closed. With stdio, output gets shoveled into
365 * stdout buffer, and even fflush cannot clear it out. It seems that
366 * even if libc receives EBADF on write attempts, it feels determined
367 * to output data no matter what. So it will try later,
368 * and possibly will clobber future output. Not good. */
369 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
370 if (fcntl(1, F_GETFL) == -1)
371 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
372 //if (dup2(1, 1) != 1) - old way
375 /* bash builtin errors out on "printf '-%s-\n' foo",
376 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
377 * We will mimic coreutils. */
378 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
381 if (ENABLE_ASH_BUILTIN_PRINTF
382 && applet_name[0] != 'p'
384 bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
385 return 2; /* bash compat */
396 argv2 = print_formatted(format, argv, &conv_err);
397 } while (argv2 > argv && *argv2);
399 /* coreutils compat (bash doesn't do this):
401 fprintf(stderr, "excess args ignored");
404 return (argv2 < argv) /* if true, print_formatted errored out */
405 || conv_err; /* print_formatted saw invalid number */