Update internal.h to conditionally include asm/string.h
[oweals/busybox.git] / printf.c
1 /* vi: set sw=4 ts=4: */
2 /* printf - format and print data
3    Copyright (C) 90, 91, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Usage: printf format [argument...]
20
21    A front end to the printf function that lets it be used from the shell.
22
23    Backslash escapes:
24
25    \" = double quote
26    \\ = backslash
27    \a = alert (bell)
28    \b = backspace
29    \c = produce no further output
30    \f = form feed
31    \n = new line
32    \r = carriage return
33    \t = horizontal tab
34    \v = vertical tab
35    \0ooo = octal number (ooo is 0 to 3 digits)
36    \xhhh = hexadecimal number (hhh is 1 to 3 digits)
37
38    Additional directive:
39
40    %b = print an argument string, interpreting backslash escapes
41
42    The `format' argument is re-used as many times as necessary
43    to convert all of the given arguments.
44
45    David MacKenzie <djm@gnu.ai.mit.edu> */
46
47
48 //   19990508 Busy Boxed! Dave Cinege
49
50 #include "internal.h"
51 #include <unistd.h>
52 #include <stdio.h>
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <stdlib.h>
58 #include <fcntl.h>
59 #include <ctype.h>
60 #include <libintl.h>
61
62
63 #ifndef S_IFMT
64 # define S_IFMT 0170000
65 #endif
66 #if !defined(S_ISBLK) && defined(S_IFBLK)
67 # define        S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
68 #endif
69 #if !defined(S_ISCHR) && defined(S_IFCHR)
70 # define        S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
71 #endif
72 #if !defined(S_ISDIR) && defined(S_IFDIR)
73 # define        S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
74 #endif
75 #if !defined(S_ISREG) && defined(S_IFREG)
76 # define        S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
77 #endif
78 #if !defined(S_ISFIFO) && defined(S_IFIFO)
79 # define        S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
80 #endif
81 #if !defined(S_ISLNK) && defined(S_IFLNK)
82 # define        S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
83 #endif
84 #if !defined(S_ISSOCK) && defined(S_IFSOCK)
85 # define        S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
86 #endif
87 #if !defined(S_ISMPB) && defined(S_IFMPB)       /* V7 */
88 # define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
89 # define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
90 #endif
91 #if !defined(S_ISNWK) && defined(S_IFNWK)       /* HP/UX */
92 # define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
93 #endif
94
95 #define IN_CTYPE_DOMAIN(c) 1
96
97 #ifdef isblank
98 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
99 #else
100 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
101 #endif
102 #ifdef isgraph
103 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
104 #else
105 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
106 #endif
107
108 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
109 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
110 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
111 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
112 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
113 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
114 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
115 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
116 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
117 #define ISDIGIT_LOCALE(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
118 #define ISDIGIT(c) ((unsigned) (c) - '0' <= 9)
119
120 #define isodigit(c) ((c) >= '0' && (c) <= '7')
121 #define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0')
122 #define octtobin(c) ((c) - '0')
123
124 static double xstrtod __P((char *s));
125 static int print_esc __P((char *escstart));
126 static int print_formatted __P((char *format, int argc, char **argv));
127 static long xstrtol __P((char *s));
128 static unsigned long xstrtoul __P((char *s));
129 static void print_direc
130 __P(
131
132         (char *start, size_t length, int field_width, int precision,
133          char *argument));
134 static void print_esc_char __P((int c));
135 static void print_esc_string __P((char *str));
136 static void verify __P((char *s, char *end));
137
138 /* The value to return to the calling program.  */
139 static int exit_status;
140
141 static const char printf_usage[] = "printf FORMAT [ARGUMENT...]\n"
142 #ifndef BB_FEATURE_TRIVIAL_HELP
143         "\nFormats and prints ARGUMENT(s) according to FORMAT,\n"
144         "Where FORMAT controls the output exactly as in C printf.\n"
145 #endif
146         ;
147
148 int printf_main(int argc, char **argv)
149 {
150         char *format;
151         int args_used;
152
153         exit_status = 0;
154         if (argc <= 1 || **(argv + 1) == '-') {
155                 usage(printf_usage);
156         }
157
158         format = argv[1];
159         argc -= 2;
160         argv += 2;
161
162         do {
163                 args_used = print_formatted(format, argc, argv);
164                 argc -= args_used;
165                 argv += args_used;
166         }
167         while (args_used > 0 && argc > 0);
168
169 /*
170   if (argc > 0)
171     fprintf(stderr, "excess args ignored");
172 */
173
174         exit(exit_status);
175 }
176
177 /* Print the text in FORMAT, using ARGV (with ARGC elements) for
178    arguments to any `%' directives.
179    Return the number of elements of ARGV used.  */
180
181 static int print_formatted(char *format, int argc, char **argv)
182 {
183         int save_argc = argc;           /* Preserve original value.  */
184         char *f;                                        /* Pointer into `format'.  */
185         char *direc_start;                      /* Start of % directive.  */
186         size_t direc_length;            /* Length of % directive.  */
187         int field_width;                        /* Arg to first '*', or -1 if none.  */
188         int precision;                          /* Arg to second '*', or -1 if none.  */
189
190         for (f = format; *f; ++f) {
191                 switch (*f) {
192                 case '%':
193                         direc_start = f++;
194                         direc_length = 1;
195                         field_width = precision = -1;
196                         if (*f == '%') {
197                                 putchar('%');
198                                 break;
199                         }
200                         if (*f == 'b') {
201                                 if (argc > 0) {
202                                         print_esc_string(*argv);
203                                         ++argv;
204                                         --argc;
205                                 }
206                                 break;
207                         }
208                         if (strchr("-+ #", *f)) {
209                                 ++f;
210                                 ++direc_length;
211                         }
212                         if (*f == '*') {
213                                 ++f;
214                                 ++direc_length;
215                                 if (argc > 0) {
216                                         field_width = xstrtoul(*argv);
217                                         ++argv;
218                                         --argc;
219                                 } else
220                                         field_width = 0;
221                         } else
222                                 while (ISDIGIT(*f)) {
223                                         ++f;
224                                         ++direc_length;
225                                 }
226                         if (*f == '.') {
227                                 ++f;
228                                 ++direc_length;
229                                 if (*f == '*') {
230                                         ++f;
231                                         ++direc_length;
232                                         if (argc > 0) {
233                                                 precision = xstrtoul(*argv);
234                                                 ++argv;
235                                                 --argc;
236                                         } else
237                                                 precision = 0;
238                                 } else
239                                         while (ISDIGIT(*f)) {
240                                                 ++f;
241                                                 ++direc_length;
242                                         }
243                         }
244                         if (*f == 'l' || *f == 'L' || *f == 'h') {
245                                 ++f;
246                                 ++direc_length;
247                         }
248                         /*  
249                            if (!strchr ("diouxXfeEgGcs", *f))
250                            fprintf(stderr, "%%%c: invalid directive", *f);
251                          */
252                         ++direc_length;
253                         if (argc > 0) {
254                                 print_direc(direc_start, direc_length, field_width,
255                                                         precision, *argv);
256                                 ++argv;
257                                 --argc;
258                         } else
259                                 print_direc(direc_start, direc_length, field_width,
260                                                         precision, "");
261                         break;
262
263                 case '\\':
264                         f += print_esc(f);
265                         break;
266
267                 default:
268                         putchar(*f);
269                 }
270         }
271
272         return save_argc - argc;
273 }
274
275 /* Print a \ escape sequence starting at ESCSTART.
276    Return the number of characters in the escape sequence
277    besides the backslash. */
278
279 static int print_esc(char *escstart)
280 {
281         register char *p = escstart + 1;
282         int esc_value = 0;                      /* Value of \nnn escape. */
283         int esc_length;                         /* Length of \nnn escape. */
284
285         /* \0ooo and \xhhh escapes have maximum length of 3 chars. */
286         if (*p == 'x') {
287                 for (esc_length = 0, ++p;
288                          esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p)
289                         esc_value = esc_value * 16 + hextobin(*p);
290 /*      if (esc_length == 0)
291         fprintf(stderr, "missing hex in esc");
292 */
293                 putchar(esc_value);
294         } else if (*p == '0') {
295                 for (esc_length = 0, ++p;
296                          esc_length < 3 && isodigit(*p); ++esc_length, ++p)
297                         esc_value = esc_value * 8 + octtobin(*p);
298                 putchar(esc_value);
299         } else if (strchr("\"\\abcfnrtv", *p))
300                 print_esc_char(*p++);
301 /*  else
302     fprintf(stderr, "\\%c: invalid esc", *p);
303 */
304         return p - escstart - 1;
305 }
306
307 /* Output a single-character \ escape.  */
308
309 static void print_esc_char(int c)
310 {
311         switch (c) {
312         case 'a':                                       /* Alert. */
313                 putchar(7);
314                 break;
315         case 'b':                                       /* Backspace. */
316                 putchar(8);
317                 break;
318         case 'c':                                       /* Cancel the rest of the output. */
319                 exit(0);
320                 break;
321         case 'f':                                       /* Form feed. */
322                 putchar(12);
323                 break;
324         case 'n':                                       /* New line. */
325                 putchar(10);
326                 break;
327         case 'r':                                       /* Carriage return. */
328                 putchar(13);
329                 break;
330         case 't':                                       /* Horizontal tab. */
331                 putchar(9);
332                 break;
333         case 'v':                                       /* Vertical tab. */
334                 putchar(11);
335                 break;
336         default:
337                 putchar(c);
338                 break;
339         }
340 }
341
342 /* Print string STR, evaluating \ escapes. */
343
344 static void print_esc_string(char *str)
345 {
346         for (; *str; str++)
347                 if (*str == '\\')
348                         str += print_esc(str);
349                 else
350                         putchar(*str);
351 }
352
353 static void
354 print_direc(char *start, size_t length, int field_width, int precision,
355                         char *argument)
356 {
357         char *p;                                        /* Null-terminated copy of % directive. */
358
359         p = xmalloc((unsigned) (length + 1));
360         strncpy(p, start, length);
361         p[length] = 0;
362
363         switch (p[length - 1]) {
364         case 'd':
365         case 'i':
366                 if (field_width < 0) {
367                         if (precision < 0)
368                                 printf(p, xstrtol(argument));
369                         else
370                                 printf(p, precision, xstrtol(argument));
371                 } else {
372                         if (precision < 0)
373                                 printf(p, field_width, xstrtol(argument));
374                         else
375                                 printf(p, field_width, precision, xstrtol(argument));
376                 }
377                 break;
378
379         case 'o':
380         case 'u':
381         case 'x':
382         case 'X':
383                 if (field_width < 0) {
384                         if (precision < 0)
385                                 printf(p, xstrtoul(argument));
386                         else
387                                 printf(p, precision, xstrtoul(argument));
388                 } else {
389                         if (precision < 0)
390                                 printf(p, field_width, xstrtoul(argument));
391                         else
392                                 printf(p, field_width, precision, xstrtoul(argument));
393                 }
394                 break;
395
396         case 'f':
397         case 'e':
398         case 'E':
399         case 'g':
400         case 'G':
401                 if (field_width < 0) {
402                         if (precision < 0)
403                                 printf(p, xstrtod(argument));
404                         else
405                                 printf(p, precision, xstrtod(argument));
406                 } else {
407                         if (precision < 0)
408                                 printf(p, field_width, xstrtod(argument));
409                         else
410                                 printf(p, field_width, precision, xstrtod(argument));
411                 }
412                 break;
413
414         case 'c':
415                 printf(p, *argument);
416                 break;
417
418         case 's':
419                 if (field_width < 0) {
420                         if (precision < 0)
421                                 printf(p, argument);
422                         else
423                                 printf(p, precision, argument);
424                 } else {
425                         if (precision < 0)
426                                 printf(p, field_width, argument);
427                         else
428                                 printf(p, field_width, precision, argument);
429                 }
430                 break;
431         }
432
433         free(p);
434 }
435
436 static unsigned long xstrtoul(char *s)
437 {
438         char *end;
439         unsigned long val;
440
441         errno = 0;
442         val = strtoul(s, &end, 0);
443         verify(s, end);
444         return val;
445 }
446
447 static long xstrtol(char *s)
448 {
449         char *end;
450         long val;
451
452         errno = 0;
453         val = strtol(s, &end, 0);
454         verify(s, end);
455         return val;
456 }
457
458 static double xstrtod(char *s)
459 {
460         char *end;
461         double val;
462
463         errno = 0;
464         val = strtod(s, &end);
465         verify(s, end);
466         return val;
467 }
468
469 static void verify(char *s, char *end)
470 {
471         if (errno) {
472                 fprintf(stderr, "%s", s);
473                 exit_status = 1;
474         } else if (*end) {
475                 /*
476                    if (s == end)
477                    fprintf(stderr, "%s: expected numeric", s);
478                    else
479                    fprintf(stderr, "%s: not completely converted", s);
480                  */
481                 exit_status = 1;
482         }
483 }