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