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