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