Imported from ../bash-2.05b.tar.gz.
[platform/upstream/bash.git] / builtins / printf.def
1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
3
4 Copyright (C) 1997-2002 Free Software Foundation, Inc.
5
6 This file is part of GNU Bash, the Bourne Again SHell.
7
8 Bash is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License along
19 with Bash; see the file COPYING.  If not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21
22 $PRODUCES printf.c
23
24 $BUILTIN printf
25 $FUNCTION printf_builtin
26 $SHORT_DOC printf format [arguments]
27 printf formats and prints ARGUMENTS under control of the FORMAT. FORMAT
28 is a character string which contains three types of objects: plain
29 characters, which are simply copied to standard output, character escape
30 sequences which are converted and copied to the standard output, and
31 format specifications, each of which causes printing of the next successive
32 argument.  In addition to the standard printf(1) formats, %b means to
33 expand backslash escape sequences in the corresponding argument, and %q
34 means to quote the argument in a way that can be reused as shell input.
35 $END
36
37 #include <config.h>
38
39 #include "../bashtypes.h"
40
41 #include <errno.h>
42 #if defined (HAVE_LIMITS_H)
43 #  include <limits.h>
44 #else
45    /* Assume 32-bit ints. */
46 #  define INT_MAX               2147483647
47 #  define INT_MIN               (-2147483647-1)
48 #endif
49
50 #include <stdio.h>
51 #include <chartypes.h>
52
53 #ifdef HAVE_INTTYPES_H
54 #  include <inttypes.h>
55 #endif
56
57 #include "../bashansi.h"
58
59 #include "../shell.h"
60 #include "stdc.h"
61 #include "bashgetopt.h"
62 #include "common.h"
63
64 #if !defined (PRIdMAX)
65 #  if HAVE_LONG_LONG
66 #    define PRIdMAX     "lld"
67 #  else
68 #    define PRIdMAX     "ld"
69 #  endif
70 #endif
71
72 #if !defined (errno)
73 extern int errno;
74 #endif
75
76 #define PF(f, func) \
77   do { \
78     if (have_fieldwidth && have_precision) \
79       tw += printf(f, fieldwidth, precision, func); \
80     else if (have_fieldwidth) \
81       tw += printf(f, fieldwidth, func); \
82     else if (have_precision) \
83       tw += printf(f, precision, func); \
84     else \
85       tw += printf(f, func); \
86   } while (0)
87
88 /* We free the buffer used by mklong() if it's `too big'. */
89 #define PRETURN(value) \
90   do \
91     { \
92       if (conv_bufsize > 4096 ) \
93         { \
94           free(conv_buf); \
95           conv_bufsize = 0; \
96           conv_buf = 0; \
97         } \
98       fflush (stdout); \
99       return (value); \
100     } \
101   while (0)
102
103 #define SKIP1 "#'-+ 0"
104 #define LENMODS "hjlLtz"
105
106 static void printf_erange __P((char *));
107 static void printstr __P((char *, char *, int, int, int));
108 static int tescape __P((char *, int, char *, int *));
109 static char *bexpand __P((char *, int, int *, int *));
110 static char *mklong __P((char *, char *, size_t));
111 static int getchr __P((void));
112 static char *getstr __P((void));
113 static int  getint __P((void));
114 static intmax_t getintmax __P((void));
115 static uintmax_t getuintmax __P((void));
116
117 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD
118 typedef long double floatmax_t;
119 #  define FLOATMAX_CONV "L"
120 #  define strtofltmax   strtold
121 #else
122 typedef double floatmax_t;
123 #  define FLOATMAX_CONV ""
124 #  define strtofltmax   strtod
125 #endif
126 static floatmax_t getfloatmax __P((void));
127
128 static int asciicode __P((void));
129
130 static WORD_LIST *garglist;
131 static int retval;
132 static int conversion_error;
133
134 static char *conv_buf;
135 static size_t conv_bufsize;
136
137 int
138 printf_builtin (list)
139      WORD_LIST *list;
140 {
141   int ch, fieldwidth, precision;
142   int have_fieldwidth, have_precision;
143   intmax_t tw;
144   char convch, thisch, nextch, *format, *modstart, *fmt, *start;
145
146   conversion_error = 0;
147   retval = EXECUTION_SUCCESS;
148
149   if (no_options (list))
150     return (EX_USAGE);
151   list = loptend;       /* skip over possible `--' */
152
153   if (list == 0)
154     {
155       builtin_usage ();
156       return (EX_USAGE);
157     }
158
159   if (list->word->word == 0 || list->word->word[0] == '\0')
160     return (EXECUTION_SUCCESS);
161
162   format = list->word->word;
163
164   garglist = list->next;
165
166   /* If the format string is empty after preprocessing, return immediately. */
167   if (format == 0 || *format == 0)
168     return (EXECUTION_SUCCESS);
169           
170   /* Basic algorithm is to scan the format string for conversion
171      specifications -- once one is found, find out if the field
172      width or precision is a '*'; if it is, gather up value.  Note,
173      format strings are reused as necessary to use up the provided
174      arguments, arguments of zero/null string are provided to use
175      up the format string. */
176   do
177     {
178       tw = 0;
179       /* find next format specification */
180       for (fmt = format; *fmt; fmt++)
181         {
182           precision = fieldwidth = 0;
183           have_fieldwidth = have_precision = 0;
184
185
186           if (*fmt == '\\')
187             {
188               fmt++;
189               /* A NULL fourth argument to tescape means to not do special
190                  processing for \c. */
191               fmt += tescape (fmt, 1, &nextch, (int *)NULL);
192               putchar (nextch);
193               fmt--;    /* for loop will increment it for us again */
194               continue;
195             }
196
197           if (*fmt != '%')
198             {
199               putchar (*fmt);
200               continue;
201             }
202
203           /* ASSERT(*fmt == '%') */
204           start = fmt++;
205
206           if (*fmt == '%')              /* %% prints a % */
207             {
208               putchar ('%');
209               continue;
210             }
211
212           /* found format specification, skip to field width */
213           for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
214             ;
215
216           /* Skip optional field width. */
217           if (*fmt == '*')
218             {
219               fmt++;
220               have_fieldwidth = 1;
221               fieldwidth = getint ();
222             }
223           else
224             while (DIGIT (*fmt))
225               fmt++;
226
227           /* Skip optional '.' and precision */
228           if (*fmt == '.')
229             {
230               ++fmt;
231               if (*fmt == '*')
232                 {
233                   fmt++;
234                   have_precision = 1;
235                   precision = getint ();
236                 }
237               else
238                 while (DIGIT (*fmt))
239                   fmt++;
240             }
241
242           /* skip possible format modifiers */
243           modstart = fmt;
244           while (*fmt && strchr (LENMODS, *fmt))
245             fmt++;
246             
247           if (*fmt == 0)
248             {
249               builtin_error ("`%s': missing format character", start);
250               PRETURN (EXECUTION_FAILURE);
251             }
252
253           convch = *fmt;
254           thisch = modstart[0];
255           nextch = modstart[1];
256           modstart[0] = convch;
257           modstart[1] = '\0';
258
259           switch(convch)
260             {
261             case 'c':
262               {
263                 char p;
264
265                 p = getchr ();
266                 PF(start, p);
267                 break;
268               }
269
270             case 's':
271               {
272                 char *p;
273
274                 p = getstr ();
275                 PF(start, p);
276                 break;
277               }
278
279             case 'n':
280               {
281                 char *var;
282
283                 var = getstr ();
284                 if (var && *var)
285                   {
286                     if (legal_identifier (var))
287                       bind_var_to_int (var, tw);
288                     else
289                       {
290                         sh_invalidid (var);
291                         PRETURN (EXECUTION_FAILURE);
292                       }
293                   }
294                 break;
295               }
296
297             case 'b':           /* expand escapes in argument */
298               {
299                 char *p, *xp;
300                 int rlen;
301
302                 p = getstr ();
303                 ch = rlen = 0;
304                 xp = bexpand (p, strlen (p), &ch, &rlen);
305
306                 if (xp)
307                   {
308                     /* Have to use printstr because of possible NUL bytes
309                        in XP -- printf does not handle that well. */
310                     printstr (start, xp, rlen, fieldwidth, precision);
311                     free (xp);
312                   }
313
314                 if (ch)
315                   PRETURN (retval);
316                 break;
317               }
318
319             case 'q':           /* print with shell quoting */
320               {
321                 char *p, *xp;
322
323                 p = getstr ();
324                 if (ansic_shouldquote (p))
325                   xp = ansic_quote (p, 0, (int *)0);
326                 else
327                   xp = sh_backslash_quote (p);
328                 if (xp)
329                   {
330                     /* Use printstr to get fieldwidth and precision right. */
331                     printstr (start, xp, strlen (xp), fieldwidth, precision);
332                     free (xp);
333                   }
334                 break;
335               }
336
337             case 'd':
338             case 'i':
339               {
340                 char *f;
341                 long p;
342                 intmax_t pp;
343
344                 p = pp = getintmax ();
345                 if (p != pp)
346                   {
347                     f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
348                     PF (f, pp);
349                   }
350                 else
351                   {
352                     /* Optimize the common case where the integer fits
353                        in "long".  This also works around some long
354                        long and/or intmax_t library bugs in the common
355                        case, e.g. glibc 2.2 x86.  */
356                     f = mklong (start, "l", 1);
357                     PF (f, p);
358                   }
359                 break;
360               }
361
362             case 'o':
363             case 'u':
364             case 'x':
365             case 'X':
366               {
367                 char *f;
368                 unsigned long p;
369                 uintmax_t pp;
370
371                 p = pp = getuintmax ();
372                 if (p != pp)
373                   {
374                     f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
375                     PF (f, pp);
376                   }
377                 else
378                   {
379                     f = mklong (start, "l", 1);
380                     PF (f, p);
381                   }
382                 break;
383               }
384
385             case 'e':
386             case 'E':
387             case 'f':
388             case 'F':
389             case 'g':
390             case 'G':
391 #if defined (HAVE_PRINTF_A_FORMAT)
392             case 'a':
393             case 'A':
394 #endif
395               {
396                 char *f;
397                 floatmax_t p;
398
399                 p = getfloatmax ();
400                 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
401                 PF (f, p);
402                 break;
403               }
404
405             /* We don't output unrecognized format characters; we print an
406                error message and return a failure exit status. */
407             default:
408               builtin_error ("`%c': invalid format character", convch);
409               PRETURN (EXECUTION_FAILURE);
410             }
411
412           modstart[0] = thisch;
413           modstart[1] = nextch;
414         }
415     }
416   while (garglist && garglist != list->next);
417
418   if (conversion_error)
419     retval = EXECUTION_FAILURE;
420
421   PRETURN (retval);
422 }
423
424 static void
425 printf_erange (s)
426      char *s;
427 {
428   builtin_error ("warning: %s: %s", s, strerror(ERANGE));
429 }
430
431 /* We duplicate a lot of what printf(3) does here. */
432 static void
433 printstr (fmt, string, len, fieldwidth, precision)
434      char *fmt;                 /* format */
435      char *string;              /* expanded string argument */
436      int len;                   /* length of expanded string */
437      int fieldwidth;            /* argument for width of `*' */
438      int precision;             /* argument for precision of `*' */
439 {
440 #if 0
441   char *s;
442 #endif
443   int padlen, nc, ljust, i;
444   int fw, pr;                   /* fieldwidth and precision */
445
446   if (string == 0 || *string == '\0')
447     return;
448
449 #if 0
450   s = fmt;
451 #endif
452   if (*fmt == '%')
453     fmt++;
454
455   ljust = fw = 0;
456   pr = -1;
457
458   /* skip flags */
459   while (strchr (SKIP1, *fmt))
460     {
461       if (*fmt == '-')
462         ljust = 1;
463       fmt++;
464     }
465
466   /* get fieldwidth, if present */
467   if (*fmt == '*')
468     {
469       fmt++;
470       fw = fieldwidth;
471       if (fw < 0)
472         {
473           fw = -fw;
474           ljust = 1;
475         }
476     }
477   else if (DIGIT (*fmt))
478     {
479       fw = *fmt++ - '0';
480       while (DIGIT (*fmt))
481         fw = (fw * 10) + (*fmt++ - '0');
482     }
483
484   /* get precision, if present */
485   if (*fmt == '.')
486     {
487       fmt++;
488       if (*fmt == '*')
489         {
490           fmt++;
491           pr = precision;
492         }
493       else if (DIGIT (*fmt))
494         {
495           pr = *fmt++ - '0';
496           while (DIGIT (*fmt))
497             pr = (pr * 10) + (*fmt++ - '0');
498         }
499     }
500
501 #if 0
502   /* If we remove this, get rid of `s'. */
503   if (*fmt != 'b' && *fmt != 'q')
504     {
505       internal_error ("format parsing problem: %s", s);
506       fw = pr = 0;
507     }
508 #endif
509
510   /* chars from string to print */
511   nc = (pr >= 0 && pr <= len) ? pr : len;
512
513   padlen = fw - nc;
514   if (padlen < 0)
515     padlen = 0;
516   if (ljust)
517     padlen = -padlen;
518
519   /* leading pad characters */
520   for (; padlen > 0; padlen--)
521     putchar (' ');
522
523   /* output NC characters from STRING */
524   for (i = 0; i < nc; i++)
525     putchar (string[i]);
526
527   /* output any necessary trailing padding */
528   for (; padlen < 0; padlen++)
529     putchar (' ');
530 }
531   
532 /* Convert STRING by expanding the escape sequences specified by the
533    POSIX standard for printf's `%b' format string.  If SAWC is non-null,
534    recognize `\c' and use that as a string terminator.  If we see \c, set
535    *SAWC to 1 before returning.  LEN is the length of STRING. */
536
537 /* Translate a single backslash-escape sequence starting at ESTART (the
538    character after the backslash) and return the number of characters
539    consumed by the sequence.  CP is the place to return the translated
540    value.  *SAWC is set to 1 if the escape sequence was \c, since that means
541    to short-circuit the rest of the processing.  If SAWC is null, we don't
542    do the \c short-circuiting, and \c is treated as an unrecognized escape
543    sequence.  */
544 static int
545 tescape (estart, trans_squote, cp, sawc)
546      char *estart;
547      int trans_squote;
548      char *cp;
549      int *sawc;
550 {
551   register char *p;
552   int temp, c, evalue;
553
554   p = estart;
555
556   switch (c = *p++)
557     {
558 #if defined (__STDC__)
559       case 'a': *cp = '\a'; break;
560 #else
561       case 'a': *cp = '\007'; break;
562 #endif
563
564       case 'b': *cp = '\b'; break;
565
566       case 'e':
567       case 'E': *cp = '\033'; break;    /* ESC -- non-ANSI */
568
569       case 'f': *cp = '\f'; break;
570
571       case 'n': *cp = '\n'; break;
572
573       case 'r': *cp = '\r'; break;
574
575       case 't': *cp = '\t'; break;
576
577       case 'v': *cp = '\v'; break;
578
579       /* %b octal constants are `\0' followed by one, two, or three
580          octal digits... */
581       case '0':
582       /* but, as an extension, the other echo-like octal escape
583          sequences are supported as well. */
584       case '1': case '2': case '3': case '4':
585       case '5': case '6': case '7':
586         for (temp = 2+(c=='0'), evalue = c - '0'; ISOCTAL (*p) && temp--; p++)
587           evalue = (evalue * 8) + OCTVALUE (*p);
588         *cp = evalue & 0xFF;
589         break;
590
591       /* And, as another extension, we allow \xNNN, where each N is a
592          hex digit. */
593       case 'x':
594         for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
595           evalue = (evalue * 16) + HEXVALUE (*p);
596         if (temp == 2)
597           {
598             builtin_error ("missing hex digit for \\x");
599             *cp = '\\';
600             return 0;
601           }
602         *cp = evalue & 0xFF;
603         break;
604
605       case '\\':        /* \\ -> \ */
606         *cp = c;
607         break;
608
609       case '\'':        /* TRANS_SQUOTE != 0 means \' -> ' */
610         if (trans_squote)
611           *cp = c;
612         else
613           {
614             *cp = '\\';
615             return 0;
616           }
617         break;
618
619       case 'c':
620         if (sawc)
621           {
622             *sawc = 1;
623             break;
624           }
625       /* other backslash escapes are passed through unaltered */
626       default:
627         *cp = '\\';
628         return 0;
629       }
630   return (p - estart);
631 }
632
633 static char *
634 bexpand (string, len, sawc, lenp)
635      char *string;
636      int len, *sawc, *lenp;
637 {
638   int temp;
639   char *ret, *r, *s, c;
640
641   if (string == 0 || *string == '\0')
642     {
643       if (sawc)
644         *sawc = 0;
645       if (lenp)
646         *lenp = 0;
647       return ((char *)NULL);
648     }
649
650   ret = (char *)xmalloc (len + 1);
651   for (r = ret, s = string; s && *s; )
652     {
653       c = *s++;
654       if (c != '\\' || *s == '\0')
655         {
656           *r++ = c;
657           continue;
658         }
659       temp = 0;
660       s += tescape (s, 0, &c, &temp);
661       if (temp)
662         {
663           if (sawc)
664             *sawc = 1;
665           break;
666         }
667
668       *r++ = c;
669     }
670
671   *r = '\0';
672   if (lenp)
673     *lenp = r - ret;
674   return ret;
675 }
676
677 static char *
678 mklong (str, modifiers, mlen)
679      char *str;
680      char *modifiers;
681      size_t mlen;
682 {
683   size_t len, slen;
684
685   slen = strlen (str);
686   len = slen + mlen + 1;
687
688   if (len > conv_bufsize)
689     {
690       conv_bufsize = (((len + 1023) >> 10) << 10);
691       conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
692     }
693
694   FASTCOPY (str, conv_buf, slen - 1);
695   FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
696
697   conv_buf[len - 2] = str[slen - 1];
698   conv_buf[len - 1] = '\0';
699   return (conv_buf);
700 }
701
702 static int
703 getchr ()
704 {
705   int ret;
706
707   if (garglist == 0)
708     return ('\0');
709
710   ret = (int)garglist->word->word[0];
711   garglist = garglist->next;
712   return ret;
713 }
714
715 static char *
716 getstr ()
717 {
718   char *ret;
719
720   if (garglist == 0)
721     return ("");
722
723   ret = garglist->word->word;
724   garglist = garglist->next;
725   return ret;
726 }
727
728 static int
729 getint ()
730 {
731   intmax_t ret;
732
733   ret = getintmax ();
734
735   if (ret > INT_MAX)
736     {
737       printf_erange (garglist->word->word);
738       ret = INT_MAX;
739     }
740   else if (ret < INT_MIN)
741     {
742       printf_erange (garglist->word->word);
743       ret = INT_MIN;
744     }
745
746   return ((int)ret);
747 }
748
749 static intmax_t
750 getintmax ()
751 {
752   intmax_t ret;
753   char *ep;
754
755   if (garglist == 0)
756     return (0);
757
758   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
759     return asciicode ();
760
761   errno = 0;
762   ret = strtoimax (garglist->word->word, &ep, 0);
763
764   if (*ep)
765     {
766       sh_invalidnum (garglist->word->word);
767       /* POSIX.2 says ``...a diagnostic message shall be written to standard
768          error, and the utility shall not exit with a zero exit status, but
769          shall continue processing any remaining operands and shall write the
770          value accumulated at the time the error was detected to standard
771          output.''  Yecch. */
772       ret = 0;
773       conversion_error = 1;
774     }
775   else if (errno == ERANGE)
776     printf_erange (garglist->word->word);
777
778   garglist = garglist->next;
779   return (ret);
780 }
781
782 static uintmax_t
783 getuintmax ()
784 {
785   uintmax_t ret;
786   char *ep;
787
788   if (garglist == 0)
789     return (0);
790
791   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
792     return asciicode ();
793
794   errno = 0;
795   ret = strtoumax (garglist->word->word, &ep, 0);
796   
797   if (*ep)
798     {
799       sh_invalidnum (garglist->word->word);
800       /* Same POSIX.2 conversion error requirements as getintmax(). */
801       ret = 0;
802       conversion_error = 1;
803     }
804   else if (errno == ERANGE)
805     printf_erange (garglist->word->word);
806
807   garglist = garglist->next;
808   return (ret);
809 }
810
811 static floatmax_t
812 getfloatmax ()
813 {
814   floatmax_t ret;
815   char *ep;
816
817   if (garglist == 0)
818     return (0);
819
820   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
821     return asciicode ();
822
823   errno = 0;
824   ret = strtofltmax (garglist->word->word, &ep);
825
826   if (*ep)
827     {
828       sh_invalidnum (garglist->word->word);
829       /* Same thing about POSIX.2 conversion error requirements. */
830       ret = 0;
831       conversion_error = 1;
832     }
833   else if (errno == ERANGE)
834     printf_erange (garglist->word->word);
835
836   garglist = garglist->next;
837   return (ret);
838 }
839
840 /* NO check is needed for garglist here. */
841 static int
842 asciicode ()
843 {
844   register int ch;
845
846   ch = garglist->word->word[1];
847   garglist = garglist->next;
848   return (ch);
849 }