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