ntpd: default to FEATURE_NTP_AUTH=y
[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.3 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         *(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
99         /* both coreutils 6.10 and bash 3.2:
100          * $ printf '%x\n' -2
101          * fffffffffffffffe
102          * Mimic that:
103          */
104         if (errno) {
105                 *(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
106         }
107 }
108 static void FAST_FUNC conv_strtoll(const char *arg, void *result)
109 {
110         *(long long*)result = bb_strtoll(arg, NULL, 0);
111 }
112 static void FAST_FUNC conv_strtod(const char *arg, void *result)
113 {
114         char *end;
115         /* Well, this one allows leading whitespace... so what? */
116         /* What I like much less is that "-" accepted too! :( */
117         *(double*)result = strtod(arg, &end);
118         if (end[0]) {
119                 errno = ERANGE;
120                 *(double*)result = 0;
121         }
122 }
123
124 /* Callers should check errno to detect errors */
125 static unsigned long long my_xstrtoull(const char *arg)
126 {
127         unsigned long long result;
128         if (multiconvert(arg, &result, conv_strtoull))
129                 result = 0;
130         return result;
131 }
132 static long long my_xstrtoll(const char *arg)
133 {
134         long long result;
135         if (multiconvert(arg, &result, conv_strtoll))
136                 result = 0;
137         return result;
138 }
139 static double my_xstrtod(const char *arg)
140 {
141         double result;
142         multiconvert(arg, &result, conv_strtod);
143         return result;
144 }
145
146 /* Handles %b; return 1 if output is to be short-circuited by \c */
147 static int print_esc_string(const char *str)
148 {
149         char c;
150         while ((c = *str) != '\0') {
151                 str++;
152                 if (c == '\\') {
153                         /* %b also accepts 4-digit octals of the form \0### */
154                         if (*str == '0') {
155                                 if ((unsigned char)(str[1] - '0') < 8) {
156                                         /* 2nd char is 0..7: skip leading '0' */
157                                         str++;
158                                 }
159                         }
160                         else if (*str == 'c') {
161                                 return 1;
162                         }
163                         {
164                                 /* optimization: don't force arg to be on-stack,
165                                  * use another variable for that. */
166                                 const char *z = str;
167                                 c = bb_process_escape_sequence(&z);
168                                 str = z;
169                         }
170                 }
171                 putchar(c);
172         }
173
174         return 0;
175 }
176
177 static void print_direc(char *format, unsigned fmt_length,
178                 int field_width, int precision,
179                 const char *argument)
180 {
181         long long llv;
182         double dv;
183         char saved;
184         char *have_prec, *have_width;
185
186         saved = format[fmt_length];
187         format[fmt_length] = '\0';
188
189         have_prec = strstr(format, ".*");
190         have_width = strchr(format, '*');
191         if (have_width - 1 == have_prec)
192                 have_width = NULL;
193
194         /* multiconvert sets errno = 0, but %s needs it cleared */
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(skip_whitespace(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(skip_whitespace(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 }