2beea71895e4a5d844deb8c28225162b3cfab714
[oweals/busybox.git] / coreutils / printf.c
1 /* vi: set sw=4 ts=4: */
2 /* printf - format and print data
3
4    Copyright 1999 Dave Cinege
5    Portions copyright (C) 1990-1996 Free Software Foundation, Inc.
6
7    Licensed under GPL v2 or later, see file LICENSE in this tarball for details.
8 */
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
39 //   19990508 Busy Boxed! Dave Cinege
40
41 #include "libbb.h"
42
43 /* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
44  * They report 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.
55  *
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.
60  */
61
62 typedef void FAST_FUNC (*converter)(const char *arg, void *result);
63
64 static int multiconvert(const char *arg, void *result, converter convert)
65 {
66         if (*arg == '"' || *arg == '\'') {
67                 arg = utoa((unsigned char)arg[1]);
68         }
69         errno = 0;
70         convert(arg, result);
71         if (errno) {
72                 bb_error_msg("%s: invalid number", arg);
73                 return 1;
74         }
75         return 0;
76 }
77
78 static void FAST_FUNC conv_strtoull(const char *arg, void *result)
79 {
80         *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
81         /* both coreutils 6.10 and bash 3.2:
82          * $ printf '%x\n' -2
83          * fffffffffffffffe
84          * Mimic that:
85          */
86         if (errno) {
87                 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
88         }
89 }
90 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
91 {
92         *(long long*)result = bb_strtoll(arg, NULL, 0);
93 }
94 static void FAST_FUNC conv_strtod(const char *arg, void *result)
95 {
96         char *end;
97         /* Well, this one allows leading whitespace... so what? */
98         /* What I like much less is that "-" accepted too! :( */
99         *(double*)result = strtod(arg, &end);
100         if (end[0]) {
101                 errno = ERANGE;
102                 *(double*)result = 0;
103         }
104 }
105
106 /* Callers should check errno to detect errors */
107 static unsigned long long my_xstrtoull(const char *arg)
108 {
109         unsigned long long result;
110         if (multiconvert(arg, &result, conv_strtoull))
111                 result = 0;
112         return result;
113 }
114 static long long my_xstrtoll(const char *arg)
115 {
116         long long result;
117         if (multiconvert(arg, &result, conv_strtoll))
118                 result = 0;
119         return result;
120 }
121 static double my_xstrtod(const char *arg)
122 {
123         double result;
124         multiconvert(arg, &result, conv_strtod);
125         return result;
126 }
127
128 static void print_esc_string(char *str)
129 {
130         while (*str) {
131                 if (*str == '\\') {
132                         str++;
133                         bb_putchar(bb_process_escape_sequence((const char **)&str));
134                 } else {
135                         bb_putchar(*str);
136                         str++;
137                 }
138         }
139 }
140
141 static void print_direc(char *format, unsigned fmt_length,
142                 int field_width, int precision,
143                 const char *argument)
144 {
145         long long llv;
146         double dv;
147         char saved;
148         char *have_prec, *have_width;
149
150         saved = format[fmt_length];
151         format[fmt_length] = '\0';
152
153         have_prec = strstr(format, ".*");
154         have_width = strchr(format, '*');
155         if (have_width - 1 == have_prec)
156                 have_width = NULL;
157
158         switch (format[fmt_length - 1]) {
159         case 'c':
160                 printf(format, *argument);
161                 break;
162         case 'd':
163         case 'i':
164                 llv = my_xstrtoll(argument);
165  print_long:
166                 /* if (errno) return; - see comment at the top */
167                 if (!have_width) {
168                         if (!have_prec)
169                                 printf(format, llv);
170                         else
171                                 printf(format, precision, llv);
172                 } else {
173                         if (!have_prec)
174                                 printf(format, field_width, llv);
175                         else
176                                 printf(format, field_width, precision, llv);
177                 }
178                 break;
179         case 'o':
180         case 'u':
181         case 'x':
182         case 'X':
183                 llv = my_xstrtoull(argument);
184                 /* cheat: unsigned long and long have same width, so... */
185                 goto print_long;
186         case 's':
187                 /* Are char* and long long the same? */
188                 if (sizeof(argument) == sizeof(llv)) {
189                         llv = (long long)(ptrdiff_t)argument;
190                         goto print_long;
191                 } else {
192                         /* Hope compiler will optimize it out by moving call
193                          * instruction after the ifs... */
194                         if (!have_width) {
195                                 if (!have_prec)
196                                         printf(format, argument, /*unused:*/ argument, argument);
197                                 else
198                                         printf(format, precision, argument, /*unused:*/ argument);
199                         } else {
200                                 if (!have_prec)
201                                         printf(format, field_width, argument, /*unused:*/ argument);
202                                 else
203                                         printf(format, field_width, precision, argument);
204                         }
205                         break;
206                 }
207         case 'f':
208         case 'e':
209         case 'E':
210         case 'g':
211         case 'G':
212                 dv = my_xstrtod(argument);
213                 /* if (errno) return; */
214                 if (!have_width) {
215                         if (!have_prec)
216                                 printf(format, dv);
217                         else
218                                 printf(format, precision, dv);
219                 } else {
220                         if (!have_prec)
221                                 printf(format, field_width, dv);
222                         else
223                                 printf(format, field_width, precision, dv);
224                 }
225                 break;
226         } /* switch */
227
228         format[fmt_length] = saved;
229 }
230
231 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
232 static int get_width_prec(const char *str)
233 {
234         int v = bb_strtoi(str, NULL, 10);
235         if (errno) {
236                 bb_error_msg("%s: invalid number", str);
237                 v = 0;
238         }
239         return v;
240 }
241
242 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
243    Return advanced ARGV.  */
244 static char **print_formatted(char *f, char **argv)
245 {
246         char *direc_start;      /* Start of % directive.  */
247         unsigned direc_length;  /* Length of % directive.  */
248         int field_width;        /* Arg to first '*' */
249         int precision;          /* Arg to second '*' */
250         char **saved_argv = argv;
251
252         for (; *f; ++f) {
253                 switch (*f) {
254                 case '%':
255                         direc_start = f++;
256                         direc_length = 1;
257                         field_width = precision = 0;
258                         if (*f == '%') {
259                                 bb_putchar('%');
260                                 break;
261                         }
262                         if (*f == 'b') {
263                                 if (*argv) {
264                                         print_esc_string(*argv);
265                                         ++argv;
266                                 }
267                                 break;
268                         }
269                         if (strchr("-+ #", *f)) {
270                                 ++f;
271                                 ++direc_length;
272                         }
273                         if (*f == '*') {
274                                 ++f;
275                                 ++direc_length;
276                                 if (*argv)
277                                         field_width = get_width_prec(*argv++);
278                         } else {
279                                 while (isdigit(*f)) {
280                                         ++f;
281                                         ++direc_length;
282                                 }
283                         }
284                         if (*f == '.') {
285                                 ++f;
286                                 ++direc_length;
287                                 if (*f == '*') {
288                                         ++f;
289                                         ++direc_length;
290                                         if (*argv)
291                                                 precision = get_width_prec(*argv++);
292                                 } else {
293                                         while (isdigit(*f)) {
294                                                 ++f;
295                                                 ++direc_length;
296                                         }
297                                 }
298                         }
299
300                         /* Remove "lLhz" size modifiers, repeatedly.
301                          * bash does not like "%lld", but coreutils
302                          * would happily take even "%Llllhhzhhzd"!
303                          * We will be permissive like coreutils */
304                         while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
305                                 overlapping_strcpy(f, f + 1);
306                         }
307                         /* Add "ll" if integer modifier, then print */
308                         {
309                                 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
310                                 char *p = strchr(format_chars, *f);
311                                 /* needed - try "printf %" without it */
312                                 if (p == NULL) {
313                                         bb_error_msg("%s: invalid format", direc_start);
314                                         /* causes main() to exit with error */
315                                         return saved_argv - 1;
316                                 }
317                                 ++direc_length;
318                                 if (p - format_chars <= 5) {
319                                         /* it is one of "diouxX" */
320                                         p = xmalloc(direc_length + 3);
321                                         memcpy(p, direc_start, direc_length);
322                                         p[direc_length + 1] = p[direc_length - 1];
323                                         p[direc_length - 1] = 'l';
324                                         p[direc_length] = 'l';
325                                         //bb_error_msg("<%s>", p);
326                                         direc_length += 2;
327                                         direc_start = p;
328                                 } else {
329                                         p = NULL;
330                                 }
331                                 if (*argv) {
332                                         print_direc(direc_start, direc_length, field_width,
333                                                                 precision, *argv);
334                                         ++argv;
335                                 } else {
336                                         print_direc(direc_start, direc_length, field_width,
337                                                                 precision, "");
338                                 }
339                                 free(p);
340                         }
341                         break;
342                 case '\\':
343                         if (*++f == 'c') {
344                                 return saved_argv; /* causes main() to exit */
345                         }
346                         bb_putchar(bb_process_escape_sequence((const char **)&f));
347                         f--;
348                         break;
349                 default:
350                         bb_putchar(*f);
351                 }
352         }
353
354         return argv;
355 }
356
357 int printf_main(int argc UNUSED_PARAM, char **argv)
358 {
359         char *format;
360         char **argv2;
361
362         /* We must check that stdout is not closed.
363          * The reason for this is highly non-obvious.
364          * printf_main is used from shell.
365          * Shell must correctly handle 'printf "%s" foo'
366          * if stdout is closed. With stdio, output gets shoveled into
367          * stdout buffer, and even fflush cannot clear it out. It seems that
368          * even if libc receives EBADF on write attempts, it feels determined
369          * to output data no matter what. So it will try later,
370          * and possibly will clobber future output. Not good. */
371 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
372         if (fcntl(1, F_GETFL) == -1)
373                 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
374         //if (dup2(1, 1) != 1) - old way
375         //      return 1;
376
377         /* bash builtin errors out on "printf '-%s-\n' foo",
378          * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
379          * We will mimic coreutils. */
380         if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
381                 argv++;
382         if (!argv[1]) {
383                 if (ENABLE_ASH_BUILTIN_PRINTF
384                  && applet_name[0] != 'p'
385                 ) {
386                         bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
387                         return 2; /* bash compat */
388                 }
389                 bb_show_usage();
390         }
391
392         format = argv[1];
393         argv2 = argv + 2;
394
395         do {
396                 argv = argv2;
397                 argv2 = print_formatted(format, argv);
398         } while (argv2 > argv && *argv2);
399
400         /* coreutils compat (bash doesn't do this):
401         if (*argv)
402                 fprintf(stderr, "excess args ignored");
403         */
404
405         return (argv2 < argv); /* if true, print_formatted errored out */
406 }