b7752369c56089c7b286b8c7951ef24fa949f1c9
[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 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 typedef void (*converter)(const char *arg, void *result);
44
45 static void multiconvert(const char *arg, void *result, converter convert)
46 {
47         char s[sizeof(int)*3 + 2];
48
49         if (*arg == '"' || *arg == '\'') {
50                 sprintf(s, "%d", (unsigned char)arg[1]);
51                 arg = s;
52         }
53         convert(arg, result);
54         /* if there was conversion error, print unconverted string */
55         if (errno)
56                 fputs(arg, stderr);
57 }
58
59 static void conv_strtoul(const char *arg, void *result)
60 {
61         *(unsigned long*)result = bb_strtoul(arg, NULL, 0);
62 }
63 static void conv_strtol(const char *arg, void *result)
64 {
65         *(long*)result = bb_strtol(arg, NULL, 0);
66 }
67 static void conv_strtod(const char *arg, void *result)
68 {
69         char *end;
70         /* Well, this one allows leading whitespace... so what */
71         /* What I like much less is that "-" is accepted too! :( */
72         *(double*)result = strtod(arg, &end);
73         if (end[0]) errno = ERANGE;
74 }
75
76 static unsigned long my_xstrtoul(const char *arg)
77 {
78         unsigned long result;
79         multiconvert(arg, &result, conv_strtoul);
80         return result;
81 }
82
83 static long my_xstrtol(const char *arg)
84 {
85         long result;
86         multiconvert(arg, &result, conv_strtol);
87         return result;
88 }
89
90 static double my_xstrtod(const char *arg)
91 {
92         double result;
93         multiconvert(arg, &result, conv_strtod);
94         return result;
95 }
96
97 static void print_esc_string(char *str)
98 {
99         for (; *str; str++) {
100                 if (*str == '\\') {
101                         str++;
102                         bb_putchar(bb_process_escape_sequence((const char **)&str));
103                 } else {
104                         bb_putchar(*str);
105                 }
106
107         }
108 }
109
110 static void print_direc(char *format, unsigned fmt_length,
111                 int field_width, int precision,
112                 const char *argument)
113 {
114         char saved;
115
116         saved = format[fmt_length];
117         format[fmt_length] = '\0';
118
119         switch (format[fmt_length - 1]) {
120         case 'd':
121         case 'i':
122                 if (field_width < 0) {
123                         if (precision < 0)
124                                 printf(format, my_xstrtol(argument));
125                         else
126                                 printf(format, precision, my_xstrtol(argument));
127                 } else {
128                         if (precision < 0)
129                                 printf(format, field_width, my_xstrtol(argument));
130                         else
131                                 printf(format, field_width, precision, my_xstrtol(argument));
132                 }
133                 break;
134         case 'o':
135         case 'u':
136         case 'x':
137         case 'X':
138                 if (field_width < 0) {
139                         if (precision < 0)
140                                 printf(format, my_xstrtoul(argument));
141                         else
142                                 printf(format, precision, my_xstrtoul(argument));
143                 } else {
144                         if (precision < 0)
145                                 printf(format, field_width, my_xstrtoul(argument));
146                         else
147                                 printf(format, field_width, precision, my_xstrtoul(argument));
148                 }
149                 break;
150         case 'f':
151         case 'e':
152         case 'E':
153         case 'g':
154         case 'G':
155                 if (field_width < 0) {
156                         if (precision < 0)
157                                 printf(format, my_xstrtod(argument));
158                         else
159                                 printf(format, precision, my_xstrtod(argument));
160                 } else {
161                         if (precision < 0)
162                                 printf(format, field_width, my_xstrtod(argument));
163                         else
164                                 printf(format, field_width, precision, my_xstrtod(argument));
165                 }
166                 break;
167         case 'c':
168                 printf(format, *argument);
169                 break;
170         case 's':
171                 if (field_width < 0) {
172                         if (precision < 0)
173                                 printf(format, argument);
174                         else
175                                 printf(format, precision, argument);
176                 } else {
177                         if (precision < 0)
178                                 printf(format, field_width, argument);
179                         else
180                                 printf(format, field_width, precision, argument);
181                 }
182                 break;
183         }
184
185         format[fmt_length] = saved;
186 }
187
188 /* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
189    Return advanced ARGV.  */
190 static char **print_formatted(char *f, char **argv)
191 {
192         char *direc_start;      /* Start of % directive.  */
193         unsigned direc_length;  /* Length of % directive.  */
194         int field_width;        /* Arg to first '*', or -1 if none.  */
195         int precision;          /* Arg to second '*', or -1 if none.  */
196         char **saved_argv = argv;
197
198         for (; *f; ++f) {
199                 switch (*f) {
200                 case '%':
201                         direc_start = f++;
202                         direc_length = 1;
203                         field_width = precision = -1;
204                         if (*f == '%') {
205                                 bb_putchar('%');
206                                 break;
207                         }
208                         if (*f == 'b') {
209                                 if (*argv) {
210                                         print_esc_string(*argv);
211                                         ++argv;
212                                 }
213                                 break;
214                         }
215                         if (strchr("-+ #", *f)) {
216                                 ++f;
217                                 ++direc_length;
218                         }
219                         if (*f == '*') {
220                                 ++f;
221                                 ++direc_length;
222                                 if (*argv) {
223                                         field_width = my_xstrtoul(*argv);
224                                         ++argv;
225                                 } else
226                                         field_width = 0;
227                         } else {
228                                 while (isdigit(*f)) {
229                                         ++f;
230                                         ++direc_length;
231                                 }
232                         }
233                         if (*f == '.') {
234                                 ++f;
235                                 ++direc_length;
236                                 if (*f == '*') {
237                                         ++f;
238                                         ++direc_length;
239                                         if (*argv) {
240                                                 precision = my_xstrtoul(*argv);
241                                                 ++argv;
242                                         } else
243                                                 precision = 0;
244                                 } else
245                                         while (isdigit(*f)) {
246                                                 ++f;
247                                                 ++direc_length;
248                                         }
249                         }
250                         if (*f == 'l' || *f == 'L' || *f == 'h') {
251                                 ++f;
252                                 ++direc_length;
253                         }
254                         /*
255                         if (!strchr ("diouxXfeEgGcs", *f))
256                         fprintf(stderr, "%%%c: invalid directive", *f);
257                         */
258                         ++direc_length;
259                         if (*argv) {
260                                 print_direc(direc_start, direc_length, field_width,
261                                                         precision, *argv);
262                                 ++argv;
263                         } else
264                                 print_direc(direc_start, direc_length, field_width,
265                                                         precision, "");
266                         break;
267                 case '\\':
268                         if (*++f == 'c') {
269                                 return saved_argv; /* causes main() to exit */
270                         }
271                         bb_putchar(bb_process_escape_sequence((const char **)&f));
272                         f--;
273                         break;
274                 default:
275                         bb_putchar(*f);
276                 }
277         }
278
279         return argv;
280 }
281
282 int printf_main(int argc ATTRIBUTE_UNUSED, char **argv)
283 {
284         char *format;
285         char **argv2;
286
287         /* We must check that stdout is not closed.
288          * The reason for this is highly non-obvious. printf_main is used from shell.
289          * Shell must correctly handle 'printf "%s" foo'
290          * if stdout is closed. With stdio, output gets shoveled into
291          * stdout buffer, and even fflush cannot clear it out. It seems that
292          * even if libc receives EBADF on write attempts, it feels determined
293          * to output data no matter what. So it will try later,
294          * and possibly will clobber future output. Not good. */
295         if (dup2(1, 1) != 1)
296                 return -1;
297
298         /* bash builtin errors out on "printf '-%s-\n' foo",
299          * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
300          * We will mimic coreutils. */
301         if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && argv[1][2] == '\0')
302                 argv++;
303         if (!argv[1])
304                 bb_show_usage();
305
306         format = argv[1];
307         argv2 = argv + 2;
308
309         do {
310                 argv = argv2;
311                 argv2 = print_formatted(format, argv);
312         } while (argv2 != argv && *argv2);
313
314         /* coreutils compat (bash doesn't do this):
315         if (*argv)
316                 fprintf(stderr, "excess args ignored");
317         */
318
319         return EXIT_SUCCESS;
320 }