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. We are not compatible here:
57 * - we do not accept -NUM for %u
58 * - exit code is 0 even if "invalid number" was seen (FIXME)
59 * See "if (errno)" checks in the code below.
62 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
64 static int multiconvert(const char *arg, void *result, converter convert)
66 if (*arg == '"' || *arg == '\'') {
67 arg = utoa((unsigned char)arg[1]);
72 bb_error_msg("%s: invalid number", arg);
78 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
80 *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
82 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
84 *(long long*)result = bb_strtoll(arg, NULL, 0);
86 static void FAST_FUNC conv_strtod(const char *arg, void *result)
89 /* Well, this one allows leading whitespace... so what? */
90 /* What I like much less is that "-" accepted too! :( */
91 *(double*)result = strtod(arg, &end);
98 /* Callers should check errno to detect errors */
99 static unsigned long long my_xstrtoull(const char *arg)
101 unsigned long long result;
102 if (multiconvert(arg, &result, conv_strtoull))
106 static long long my_xstrtoll(const char *arg)
109 if (multiconvert(arg, &result, conv_strtoll))
113 static double my_xstrtod(const char *arg)
116 multiconvert(arg, &result, conv_strtod);
120 static void print_esc_string(char *str)
125 bb_putchar(bb_process_escape_sequence((const char **)&str));
133 static void print_direc(char *format, unsigned fmt_length,
134 int field_width, int precision,
135 const char *argument)
140 char *have_prec, *have_width;
142 saved = format[fmt_length];
143 format[fmt_length] = '\0';
145 have_prec = strstr(format, ".*");
146 have_width = strchr(format, '*');
147 if (have_width - 1 == have_prec)
150 switch (format[fmt_length - 1]) {
152 printf(format, *argument);
156 llv = my_xstrtoll(argument);
158 /* if (errno) return; - see comment at the top */
163 printf(format, precision, llv);
166 printf(format, field_width, llv);
168 printf(format, field_width, precision, llv);
175 llv = my_xstrtoull(argument);
176 /* cheat: unsigned long and long have same width, so... */
179 /* Are char* and long long the same? */
180 if (sizeof(argument) == sizeof(llv)) {
181 llv = (long long)(ptrdiff_t)argument;
184 /* Hope compiler will optimize it out by moving call
185 * instruction after the ifs... */
188 printf(format, argument, /*unused:*/ argument, argument);
190 printf(format, precision, argument, /*unused:*/ argument);
193 printf(format, field_width, argument, /*unused:*/ argument);
195 printf(format, field_width, precision, argument);
204 dv = my_xstrtod(argument);
205 /* if (errno) return; */
210 printf(format, precision, dv);
213 printf(format, field_width, dv);
215 printf(format, field_width, precision, dv);
220 format[fmt_length] = saved;
223 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
224 static int get_width_prec(const char *str)
226 int v = bb_strtoi(str, NULL, 10);
228 bb_error_msg("%s: invalid number", str);
234 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
235 Return advanced ARGV. */
236 static char **print_formatted(char *f, char **argv)
238 char *direc_start; /* Start of % directive. */
239 unsigned direc_length; /* Length of % directive. */
240 int field_width; /* Arg to first '*' */
241 int precision; /* Arg to second '*' */
242 char **saved_argv = argv;
249 field_width = precision = 0;
256 print_esc_string(*argv);
261 if (strchr("-+ #", *f)) {
269 field_width = get_width_prec(*argv++);
271 while (isdigit(*f)) {
283 precision = get_width_prec(*argv++);
285 while (isdigit(*f)) {
292 /* Remove "lLhz" size modifiers, repeatedly.
293 * bash does not like "%lld", but coreutils
294 * would happily take even "%Llllhhzhhzd"!
295 * We will be permissive like coreutils */
296 while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
297 overlapping_strcpy(f, f + 1);
299 /* Add "ll" if integer modifier, then print */
301 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
302 char *p = strchr(format_chars, *f);
303 /* needed - try "printf %" without it */
305 bb_error_msg("%s: invalid format", direc_start);
306 /* causes main() to exit with error */
307 return saved_argv - 1;
310 if (p - format_chars <= 5) {
311 /* it is one of "diouxX" */
312 p = xmalloc(direc_length + 3);
313 memcpy(p, direc_start, direc_length);
314 p[direc_length + 1] = p[direc_length - 1];
315 p[direc_length - 1] = 'l';
316 p[direc_length] = 'l';
317 //bb_error_msg("<%s>", p);
324 print_direc(direc_start, direc_length, field_width,
328 print_direc(direc_start, direc_length, field_width,
336 return saved_argv; /* causes main() to exit */
338 bb_putchar(bb_process_escape_sequence((const char **)&f));
349 int printf_main(int argc UNUSED_PARAM, char **argv)
354 /* We must check that stdout is not closed.
355 * The reason for this is highly non-obvious.
356 * printf_main is used from shell.
357 * Shell must correctly handle 'printf "%s" foo'
358 * if stdout is closed. With stdio, output gets shoveled into
359 * stdout buffer, and even fflush cannot clear it out. It seems that
360 * even if libc receives EBADF on write attempts, it feels determined
361 * to output data no matter what. So it will try later,
362 * and possibly will clobber future output. Not good. */
363 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
364 if (fcntl(1, F_GETFL) == -1)
365 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
366 //if (dup2(1, 1) != 1) - old way
369 /* bash builtin errors out on "printf '-%s-\n' foo",
370 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
371 * We will mimic coreutils. */
372 if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
375 if (ENABLE_ASH_BUILTIN_PRINTF
376 && applet_name[0] != 'p'
378 bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
379 return 2; /* bash compat */
389 argv2 = print_formatted(format, argv);
390 } while (argv2 > argv && *argv2);
392 /* coreutils compat (bash doesn't do this):
394 fprintf(stderr, "excess args ignored");
397 return (argv2 < argv); /* if true, print_formatted errored out */