hush: propagate (output,n) parameters into expand_one_var()
[oweals/busybox.git] / coreutils / printf.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * printf - format and print data
4  *
5  * Copyright 1999 Dave Cinege
6  * Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10 /* Usage: printf format [argument...]
11  *
12  * A front end to the printf function that lets it be used from the shell.
13  *
14  * Backslash escapes:
15  *
16  * \" = double quote
17  * \\ = backslash
18  * \a = alert (bell)
19  * \b = backspace
20  * \c = produce no further output
21  * \f = form feed
22  * \n = new line
23  * \r = carriage return
24  * \t = horizontal tab
25  * \v = vertical tab
26  * \0ooo = octal number (ooo is 0 to 3 digits)
27  * \xhhh = hexadecimal number (hhh is 1 to 3 digits)
28  *
29  * Additional directive:
30  *
31  * %b = print an argument string, interpreting backslash escapes
32  *
33  * The 'format' argument is re-used as many times as necessary
34  * to convert all of the given arguments.
35  *
36  * David MacKenzie <djm@gnu.ai.mit.edu>
37  */
38 /* 19990508 Busy Boxed! Dave Cinege */
39
40 //config:config PRINTF
41 //config:       bool "printf (3.3 kb)"
42 //config:       default y
43 //config:       help
44 //config:       printf is used to format and print specified strings.
45 //config:       It's similar to 'echo' except it has more options.
46
47 //applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))
48
49 //kbuild:lib-$(CONFIG_PRINTF) += printf.o
50 //kbuild:lib-$(CONFIG_ASH_PRINTF)  += printf.o
51 //kbuild:lib-$(CONFIG_HUSH_PRINTF) += printf.o
52
53 //usage:#define printf_trivial_usage
54 //usage:       "FORMAT [ARG]..."
55 //usage:#define printf_full_usage "\n\n"
56 //usage:       "Format and print ARG(s) according to FORMAT (a-la C printf)"
57 //usage:
58 //usage:#define printf_example_usage
59 //usage:       "$ printf \"Val=%d\\n\" 5\n"
60 //usage:       "Val=5\n"
61
62 #include "libbb.h"
63
64 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
65  * They report it:
66  *  bash: printf: XXX: invalid number
67  *  printf: XXX: expected a numeric value
68  *  bash: printf: 123XXX: invalid number
69  *  printf: 123XXX: value not completely converted
70  * but then they use 0 (or partially converted numeric prefix) as a value
71  * and continue. They exit with 1 in this case.
72  * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
73  * Both print error message and assume 0 if %*.*f width/precision is "bad"
74  *  (but negative numbers are not "bad").
75  * Both accept negative numbers for %u specifier.
76  *
77  * We try to be compatible.
78  */
79
80 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
81
82 static int multiconvert(const char *arg, void *result, converter convert)
83 {
84         if (*arg == '"' || *arg == '\'') {
85                 arg = utoa((unsigned char)arg[1]);
86         }
87         errno = 0;
88         convert(arg, result);
89         if (errno) {
90                 bb_error_msg("invalid number '%s'", arg);
91                 return 1;
92         }
93         return 0;
94 }
95
96 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
97 {
98         *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
99         /* both coreutils 6.10 and bash 3.2:
100          * $ printf '%x\n' -2
101          * fffffffffffffffe
102          * Mimic that:
103          */
104         if (errno) {
105                 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
106         }
107 }
108 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
109 {
110         *(long long*)result = bb_strtoll(arg, NULL, 0);
111 }
112 static void FAST_FUNC conv_strtod(const char *arg, void *result)
113 {
114         char *end;
115         /* Well, this one allows leading whitespace... so what? */
116         /* What I like much less is that "-" accepted too! :( */
117         *(double*)result = strtod(arg, &end);
118         if (end[0]) {
119                 errno = ERANGE;
120                 *(double*)result = 0;
121         }
122 }
123
124 /* Callers should check errno to detect errors */
125 static unsigned long long my_xstrtoull(const char *arg)
126 {
127         unsigned long long result;
128         if (multiconvert(arg, &result, conv_strtoull))
129                 result = 0;
130         return result;
131 }
132 static long long my_xstrtoll(const char *arg)
133 {
134         long long result;
135         if (multiconvert(arg, &result, conv_strtoll))
136                 result = 0;
137         return result;
138 }
139 static double my_xstrtod(const char *arg)
140 {
141         double result;
142         multiconvert(arg, &result, conv_strtod);
143         return result;
144 }
145
146 /* Handles %b; return 1 if output is to be short-circuited by \c */
147 static int print_esc_string(const char *str)
148 {
149         char c;
150         while ((c = *str) != '\0') {
151                 str++;
152                 if (c == '\\') {
153                         /* %b also accepts 4-digit octals of the form \0### */
154                         if (*str == '0') {
155                                 if ((unsigned char)(str[1] - '0') < 8) {
156                                         /* 2nd char is 0..7: skip leading '0' */
157                                         str++;
158                                 }
159                         }
160                         else if (*str == 'c') {
161                                 return 1;
162                         }
163                         {
164                                 /* optimization: don't force arg to be on-stack,
165                                  * use another variable for that. */
166                                 const char *z = str;
167                                 c = bb_process_escape_sequence(&z);
168                                 str = z;
169                         }
170                 }
171                 putchar(c);
172         }
173
174         return 0;
175 }
176
177 static void print_direc(char *format, unsigned fmt_length,
178                 int field_width, int precision,
179                 const char *argument)
180 {
181         long long llv;
182         double dv;
183         char saved;
184         char *have_prec, *have_width;
185
186         saved = format[fmt_length];
187         format[fmt_length] = '\0';
188
189         have_prec = strstr(format, ".*");
190         have_width = strchr(format, '*');
191         if (have_width - 1 == have_prec)
192                 have_width = NULL;
193
194         errno = 0;
195
196         switch (format[fmt_length - 1]) {
197         case 'c':
198                 printf(format, *argument);
199                 break;
200         case 'd':
201         case 'i':
202                 llv = my_xstrtoll(argument);
203  print_long:
204                 if (!have_width) {
205                         if (!have_prec)
206                                 printf(format, llv);
207                         else
208                                 printf(format, precision, llv);
209                 } else {
210                         if (!have_prec)
211                                 printf(format, field_width, llv);
212                         else
213                                 printf(format, field_width, precision, llv);
214                 }
215                 break;
216         case 'o':
217         case 'u':
218         case 'x':
219         case 'X':
220                 llv = my_xstrtoull(argument);
221                 /* cheat: unsigned long and long have same width, so... */
222                 goto print_long;
223         case 's':
224                 /* Are char* and long long the same? */
225                 if (sizeof(argument) == sizeof(llv)) {
226                         llv = (long long)(ptrdiff_t)argument;
227                         goto print_long;
228                 } else {
229                         /* Hope compiler will optimize it out by moving call
230                          * instruction after the ifs... */
231                         if (!have_width) {
232                                 if (!have_prec)
233                                         printf(format, argument, /*unused:*/ argument, argument);
234                                 else
235                                         printf(format, precision, argument, /*unused:*/ argument);
236                         } else {
237                                 if (!have_prec)
238                                         printf(format, field_width, argument, /*unused:*/ argument);
239                                 else
240                                         printf(format, field_width, precision, argument);
241                         }
242                         break;
243                 }
244         case 'f':
245         case 'e':
246         case 'E':
247         case 'g':
248         case 'G':
249                 dv = my_xstrtod(argument);
250                 if (!have_width) {
251                         if (!have_prec)
252                                 printf(format, dv);
253                         else
254                                 printf(format, precision, dv);
255                 } else {
256                         if (!have_prec)
257                                 printf(format, field_width, dv);
258                         else
259                                 printf(format, field_width, precision, dv);
260                 }
261                 break;
262         } /* switch */
263
264         format[fmt_length] = saved;
265 }
266
267 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
268 static int get_width_prec(const char *str)
269 {
270         int v = bb_strtoi(str, NULL, 10);
271         if (errno) {
272                 bb_error_msg("invalid number '%s'", str);
273                 v = 0;
274         }
275         return v;
276 }
277
278 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
279    Return advanced ARGV.  */
280 static char **print_formatted(char *f, char **argv, int *conv_err)
281 {
282         char *direc_start;      /* Start of % directive.  */
283         unsigned direc_length;  /* Length of % directive.  */
284         int field_width;        /* Arg to first '*' */
285         int precision;          /* Arg to second '*' */
286         char **saved_argv = argv;
287
288         for (; *f; ++f) {
289                 switch (*f) {
290                 case '%':
291                         direc_start = f++;
292                         direc_length = 1;
293                         field_width = precision = 0;
294                         if (*f == '%') {
295                                 bb_putchar('%');
296                                 break;
297                         }
298                         if (*f == 'b') {
299                                 if (*argv) {
300                                         if (print_esc_string(*argv))
301                                                 return saved_argv; /* causes main() to exit */
302                                         ++argv;
303                                 }
304                                 break;
305                         }
306                         if (*f && strchr("-+ #", *f)) {
307                                 ++f;
308                                 ++direc_length;
309                         }
310                         if (*f == '*') {
311                                 ++f;
312                                 ++direc_length;
313                                 if (*argv)
314                                         field_width = get_width_prec(*argv++);
315                         } else {
316                                 while (isdigit(*f)) {
317                                         ++f;
318                                         ++direc_length;
319                                 }
320                         }
321                         if (*f == '.') {
322                                 ++f;
323                                 ++direc_length;
324                                 if (*f == '*') {
325                                         ++f;
326                                         ++direc_length;
327                                         if (*argv)
328                                                 precision = get_width_prec(*argv++);
329                                 } else {
330                                         while (isdigit(*f)) {
331                                                 ++f;
332                                                 ++direc_length;
333                                         }
334                                 }
335                         }
336
337                         /* Remove "lLhz" size modifiers, repeatedly.
338                          * bash does not like "%lld", but coreutils
339                          * happily takes even "%Llllhhzhhzd"!
340                          * We are permissive like coreutils */
341                         while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
342                                 overlapping_strcpy(f, f + 1);
343                         }
344                         /* Add "ll" if integer modifier, then print */
345                         {
346                                 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
347                                 char *p = strchr(format_chars, *f);
348                                 /* needed - try "printf %" without it */
349                                 if (p == NULL || *f == '\0') {
350                                         bb_error_msg("%s: invalid format", direc_start);
351                                         /* causes main() to exit with error */
352                                         return saved_argv - 1;
353                                 }
354                                 ++direc_length;
355                                 if (p - format_chars <= 5) {
356                                         /* it is one of "diouxX" */
357                                         p = xmalloc(direc_length + 3);
358                                         memcpy(p, direc_start, direc_length);
359                                         p[direc_length + 1] = p[direc_length - 1];
360                                         p[direc_length - 1] = 'l';
361                                         p[direc_length] = 'l';
362                                         //bb_error_msg("<%s>", p);
363                                         direc_length += 2;
364                                         direc_start = p;
365                                 } else {
366                                         p = NULL;
367                                 }
368                                 if (*argv) {
369                                         print_direc(direc_start, direc_length, field_width,
370                                                                 precision, *argv++);
371                                 } else {
372                                         print_direc(direc_start, direc_length, field_width,
373                                                                 precision, "");
374                                 }
375                                 *conv_err |= errno;
376                                 free(p);
377                         }
378                         break;
379                 case '\\':
380                         if (*++f == 'c') {
381                                 return saved_argv; /* causes main() to exit */
382                         }
383                         bb_putchar(bb_process_escape_sequence((const char **)&f));
384                         f--;
385                         break;
386                 default:
387                         putchar(*f);
388                 }
389         }
390
391         return argv;
392 }
393
394 int printf_main(int argc UNUSED_PARAM, char **argv)
395 {
396         int conv_err;
397         char *format;
398         char **argv2;
399
400         /* We must check that stdout is not closed.
401          * The reason for this is highly non-obvious.
402          * printf_main is used from shell.
403          * Shell must correctly handle 'printf "%s" foo'
404          * if stdout is closed. With stdio, output gets shoveled into
405          * stdout buffer, and even fflush cannot clear it out. It seems that
406          * even if libc receives EBADF on write attempts, it feels determined
407          * to output data no matter what. So it will try later,
408          * and possibly will clobber future output. Not good. */
409 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
410         if (fcntl(1, F_GETFL) == -1)
411                 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
412         //if (dup2(1, 1) != 1) - old way
413         //      return 1;
414
415         /* bash builtin errors out on "printf '-%s-\n' foo",
416          * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
417          * We will mimic coreutils. */
418         if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
419                 argv++;
420         if (!argv[1]) {
421                 if (ENABLE_ASH_PRINTF
422                  && applet_name[0] != 'p'
423                 ) {
424                         bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
425                         return 2; /* bash compat */
426                 }
427                 bb_show_usage();
428         }
429
430         format = argv[1];
431         argv2 = argv + 2;
432
433         conv_err = 0;
434         do {
435                 argv = argv2;
436                 argv2 = print_formatted(format, argv, &conv_err);
437         } while (argv2 > argv && *argv2);
438
439         /* coreutils compat (bash doesn't do this):
440         if (*argv)
441                 fprintf(stderr, "excess args ignored");
442         */
443
444         return (argv2 < argv) /* if true, print_formatted errored out */
445                 || conv_err; /* print_formatted saw invalid number */
446 }