upload tizen1.0 source
[external/busybox.git] / util-linux / 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.
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("%s: invalid number", 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(char *str)
126 {
127         while (*str) {
128                 if (*str == '\\') {
129                         str++;
130                         bb_putchar(bb_process_escape_sequence((const char **)&str));
131                 } else {
132                         bb_putchar(*str);
133                         str++;
134                 }
135         }
136 }
137
138 static void print_direc(char *format, unsigned fmt_length,
139                 int field_width, int precision,
140                 const char *argument)
141 {
142         long long llv;
143         double dv;
144         char saved;
145         char *have_prec, *have_width;
146
147         saved = format[fmt_length];
148         format[fmt_length] = '\0';
149
150         have_prec = strstr(format, ".*");
151         have_width = strchr(format, '*');
152         if (have_width - 1 == have_prec)
153                 have_width = NULL;
154
155         errno = 0;
156
157         switch (format[fmt_length - 1]) {
158         case 'c':
159                 printf(format, *argument);
160                 break;
161         case 'd':
162         case 'i':
163                 llv = my_xstrtoll(argument);
164  print_long:
165                 if (!have_width) {
166                         if (!have_prec)
167                                 printf(format, llv);
168                         else
169                                 printf(format, precision, llv);
170                 } else {
171                         if (!have_prec)
172                                 printf(format, field_width, llv);
173                         else
174                                 printf(format, field_width, precision, llv);
175                 }
176                 break;
177         case 'o':
178         case 'u':
179         case 'x':
180         case 'X':
181                 llv = my_xstrtoull(argument);
182                 /* cheat: unsigned long and long have same width, so... */
183                 goto print_long;
184         case 's':
185                 /* Are char* and long long the same? */
186                 if (sizeof(argument) == sizeof(llv)) {
187                         llv = (long long)(ptrdiff_t)argument;
188                         goto print_long;
189                 } else {
190                         /* Hope compiler will optimize it out by moving call
191                          * instruction after the ifs... */
192                         if (!have_width) {
193                                 if (!have_prec)
194                                         printf(format, argument, /*unused:*/ argument, argument);
195                                 else
196                                         printf(format, precision, argument, /*unused:*/ argument);
197                         } else {
198                                 if (!have_prec)
199                                         printf(format, field_width, argument, /*unused:*/ argument);
200                                 else
201                                         printf(format, field_width, precision, argument);
202                         }
203                         break;
204                 }
205         case 'f':
206         case 'e':
207         case 'E':
208         case 'g':
209         case 'G':
210                 dv = my_xstrtod(argument);
211                 if (!have_width) {
212                         if (!have_prec)
213                                 printf(format, dv);
214                         else
215                                 printf(format, precision, dv);
216                 } else {
217                         if (!have_prec)
218                                 printf(format, field_width, dv);
219                         else
220                                 printf(format, field_width, precision, dv);
221                 }
222                 break;
223         } /* switch */
224
225         format[fmt_length] = saved;
226 }
227
228 /* Handle params for "%*.*f". Negative numbers are ok (compat). */
229 static int get_width_prec(const char *str)
230 {
231         int v = bb_strtoi(str, NULL, 10);
232         if (errno) {
233                 bb_error_msg("%s: invalid number", str);
234                 v = 0;
235         }
236         return v;
237 }
238
239 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
240    Return advanced ARGV.  */
241 static char **print_formatted(char *f, char **argv, int *conv_err)
242 {
243         char *direc_start;      /* Start of % directive.  */
244         unsigned direc_length;  /* Length of % directive.  */
245         int field_width;        /* Arg to first '*' */
246         int precision;          /* Arg to second '*' */
247         char **saved_argv = argv;
248
249         for (; *f; ++f) {
250                 switch (*f) {
251                 case '%':
252                         direc_start = f++;
253                         direc_length = 1;
254                         field_width = precision = 0;
255                         if (*f == '%') {
256                                 bb_putchar('%');
257                                 break;
258                         }
259                         if (*f == 'b') {
260                                 if (*argv) {
261                                         print_esc_string(*argv);
262                                         ++argv;
263                                 }
264                                 break;
265                         }
266                         if (strchr("-+ #", *f)) {
267                                 ++f;
268                                 ++direc_length;
269                         }
270                         if (*f == '*') {
271                                 ++f;
272                                 ++direc_length;
273                                 if (*argv)
274                                         field_width = get_width_prec(*argv++);
275                         } else {
276                                 while (isdigit(*f)) {
277                                         ++f;
278                                         ++direc_length;
279                                 }
280                         }
281                         if (*f == '.') {
282                                 ++f;
283                                 ++direc_length;
284                                 if (*f == '*') {
285                                         ++f;
286                                         ++direc_length;
287                                         if (*argv)
288                                                 precision = get_width_prec(*argv++);
289                                 } else {
290                                         while (isdigit(*f)) {
291                                                 ++f;
292                                                 ++direc_length;
293                                         }
294                                 }
295                         }
296
297                         /* Remove "lLhz" size modifiers, repeatedly.
298                          * bash does not like "%lld", but coreutils
299                          * happily takes even "%Llllhhzhhzd"!
300                          * We are permissive like coreutils */
301                         while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
302                                 overlapping_strcpy(f, f + 1);
303                         }
304                         /* Add "ll" if integer modifier, then print */
305                         {
306                                 static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
307                                 char *p = strchr(format_chars, *f);
308                                 /* needed - try "printf %" without it */
309                                 if (p == NULL) {
310                                         bb_error_msg("%s: invalid format", direc_start);
311                                         /* causes main() to exit with error */
312                                         return saved_argv - 1;
313                                 }
314                                 ++direc_length;
315                                 if (p - format_chars <= 5) {
316                                         /* it is one of "diouxX" */
317                                         p = xmalloc(direc_length + 3);
318                                         memcpy(p, direc_start, direc_length);
319                                         p[direc_length + 1] = p[direc_length - 1];
320                                         p[direc_length - 1] = 'l';
321                                         p[direc_length] = 'l';
322                                         //bb_error_msg("<%s>", p);
323                                         direc_length += 2;
324                                         direc_start = p;
325                                 } else {
326                                         p = NULL;
327                                 }
328                                 if (*argv) {
329                                         print_direc(direc_start, direc_length, field_width,
330                                                                 precision, *argv++);
331                                 } else {
332                                         print_direc(direc_start, direc_length, field_width,
333                                                                 precision, "");
334                                 }
335                                 *conv_err |= errno;
336                                 free(p);
337                         }
338                         break;
339                 case '\\':
340                         if (*++f == 'c') {
341                                 return saved_argv; /* causes main() to exit */
342                         }
343                         bb_putchar(bb_process_escape_sequence((const char **)&f));
344                         f--;
345                         break;
346                 default:
347                         bb_putchar(*f);
348                 }
349         }
350
351         return argv;
352 }
353
354 int printf_main(int argc UNUSED_PARAM, char **argv)
355 {
356         int conv_err;
357         char *format;
358         char **argv2;
359
360         /* We must check that stdout is not closed.
361          * The reason for this is highly non-obvious.
362          * printf_main is used from shell.
363          * Shell must correctly handle 'printf "%s" foo'
364          * if stdout is closed. With stdio, output gets shoveled into
365          * stdout buffer, and even fflush cannot clear it out. It seems that
366          * even if libc receives EBADF on write attempts, it feels determined
367          * to output data no matter what. So it will try later,
368          * and possibly will clobber future output. Not good. */
369 // TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
370         if (fcntl(1, F_GETFL) == -1)
371                 return 1; /* match coreutils 6.10 (sans error msg to stderr) */
372         //if (dup2(1, 1) != 1) - old way
373         //      return 1;
374
375         /* bash builtin errors out on "printf '-%s-\n' foo",
376          * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
377          * We will mimic coreutils. */
378         if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
379                 argv++;
380         if (!argv[1]) {
381                 if (ENABLE_ASH_BUILTIN_PRINTF
382                  && applet_name[0] != 'p'
383                 ) {
384                         bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
385                         return 2; /* bash compat */
386                 }
387                 bb_show_usage();
388         }
389
390         format = argv[1];
391         argv2 = argv + 2;
392
393         conv_err = 0;
394         do {
395                 argv = argv2;
396                 argv2 = print_formatted(format, argv, &conv_err);
397         } while (argv2 > argv && *argv2);
398
399         /* coreutils compat (bash doesn't do this):
400         if (*argv)
401                 fprintf(stderr, "excess args ignored");
402         */
403
404         return (argv2 < argv) /* if true, print_formatted errored out */
405                 || conv_err; /* print_formatted saw invalid number */
406 }