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