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