Imported from ../bash-3.0.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-2003 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 #include "../bashintl.h"
59
60 #include "../shell.h"
61 #include "stdc.h"
62 #include "bashgetopt.h"
63 #include "common.h"
64
65 #if !defined (PRIdMAX)
66 #  if HAVE_LONG_LONG
67 #    define PRIdMAX     "lld"
68 #  else
69 #    define PRIdMAX     "ld"
70 #  endif
71 #endif
72
73 #if !defined (errno)
74 extern int errno;
75 #endif
76
77 #define PF(f, func) \
78   do { \
79     if (have_fieldwidth && have_precision) \
80       tw += printf(f, fieldwidth, precision, func); \
81     else if (have_fieldwidth) \
82       tw += printf(f, fieldwidth, func); \
83     else if (have_precision) \
84       tw += printf(f, precision, func); \
85     else \
86       tw += printf(f, func); \
87   } while (0)
88
89 /* We free the buffer used by mklong() if it's `too big'. */
90 #define PRETURN(value) \
91   do \
92     { \
93       if (conv_bufsize > 4096 ) \
94         { \
95           free(conv_buf); \
96           conv_bufsize = 0; \
97           conv_buf = 0; \
98         } \
99       fflush (stdout); \
100       return (value); \
101     } \
102   while (0)
103
104 #define SKIP1 "#'-+ 0"
105 #define LENMODS "hjlLtz"
106
107 static void printf_erange __P((char *));
108 static void printstr __P((char *, char *, int, int, int));
109 static int tescape __P((char *, char *, int *));
110 static char *bexpand __P((char *, int, int *, int *));
111 static char *mklong __P((char *, char *, size_t));
112 static int getchr __P((void));
113 static char *getstr __P((void));
114 static int  getint __P((void));
115 static intmax_t getintmax __P((void));
116 static uintmax_t getuintmax __P((void));
117
118 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
119 typedef long double floatmax_t;
120 #  define FLOATMAX_CONV "L"
121 #  define strtofltmax   strtold
122 #else
123 typedef double floatmax_t;
124 #  define FLOATMAX_CONV ""
125 #  define strtofltmax   strtod
126 #endif
127 static floatmax_t getfloatmax __P((void));
128
129 static int asciicode __P((void));
130
131 static WORD_LIST *garglist;
132 static int retval;
133 static int conversion_error;
134
135 static char *conv_buf;
136 static size_t conv_bufsize;
137
138 int
139 printf_builtin (list)
140      WORD_LIST *list;
141 {
142   int ch, fieldwidth, precision;
143   int have_fieldwidth, have_precision;
144   intmax_t tw;
145   char convch, thisch, nextch, *format, *modstart, *fmt, *start;
146
147   conversion_error = 0;
148   retval = EXECUTION_SUCCESS;
149
150   if (no_options (list))
151     return (EX_USAGE);
152   list = loptend;       /* skip over possible `--' */
153
154   if (list == 0)
155     {
156       builtin_usage ();
157       return (EX_USAGE);
158     }
159
160   if (list->word->word == 0 || list->word->word[0] == '\0')
161     return (EXECUTION_SUCCESS);
162
163   format = list->word->word;
164
165   garglist = list->next;
166
167   /* If the format string is empty after preprocessing, return immediately. */
168   if (format == 0 || *format == 0)
169     return (EXECUTION_SUCCESS);
170           
171   /* Basic algorithm is to scan the format string for conversion
172      specifications -- once one is found, find out if the field
173      width or precision is a '*'; if it is, gather up value.  Note,
174      format strings are reused as necessary to use up the provided
175      arguments, arguments of zero/null string are provided to use
176      up the format string. */
177   do
178     {
179       tw = 0;
180       /* find next format specification */
181       for (fmt = format; *fmt; fmt++)
182         {
183           precision = fieldwidth = 0;
184           have_fieldwidth = have_precision = 0;
185
186           if (*fmt == '\\')
187             {
188               fmt++;
189               /* A NULL third argument to tescape means to bypass the
190                  special processing for arguments to %b. */
191               fmt += tescape (fmt, &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    perform the processing appropriate for %b arguments.  In particular,
535    recognize `\c' and use that as a string terminator.  If we see \c, set
536    *SAWC to 1 before returning.  LEN is the length of STRING. */
537
538 /* Translate a single backslash-escape sequence starting at ESTART (the
539    character after the backslash) and return the number of characters
540    consumed by the sequence.  CP is the place to return the translated
541    value.  *SAWC is set to 1 if the escape sequence was \c, since that means
542    to short-circuit the rest of the processing.  If SAWC is null, we don't
543    do the \c short-circuiting, and \c is treated as an unrecognized escape
544    sequence; we also bypass the other processing specific to %b arguments.  */
545 static int
546 tescape (estart, cp, sawc)
547      char *estart;
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       /* The octal escape sequences are `\0' followed by up to three octal
580          digits (if SAWC), or `\' followed by up to three octal digits (if
581          !SAWC).  As an extension, we allow the latter form even if SAWC. */
582       case '0': case '1': case '2': case '3':
583       case '4': case '5': case '6': case '7':
584         evalue = OCTVALUE (c);
585         for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
586           evalue = (evalue * 8) + OCTVALUE (*p);
587         *cp = evalue & 0xFF;
588         break;
589
590       /* And, as another extension, we allow \xNNN, where each N is a
591          hex digit. */
592       case 'x':
593 #if 0
594         for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
595 #else
596         for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
597 #endif
598           evalue = (evalue * 16) + HEXVALUE (*p);
599         if (p == estart + 1)
600           {
601             builtin_error (_("missing hex digit for \\x"));
602             *cp = '\\';
603             return 0;
604           }
605         *cp = evalue & 0xFF;
606         break;
607
608       case '\\':        /* \\ -> \ */
609         *cp = c;
610         break;
611
612       /* SAWC == 0 means that \', \", and \? are recognized as escape
613          sequences, though the only processing performed is backslash
614          removal. */
615       case '\'': case '"': case '?':
616         if (!sawc)
617           *cp = c;
618         else
619           {
620             *cp = '\\';
621             return 0;
622           }
623         break;
624
625       case 'c':
626         if (sawc)
627           {
628             *sawc = 1;
629             break;
630           }
631       /* other backslash escapes are passed through unaltered */
632       default:
633         *cp = '\\';
634         return 0;
635       }
636   return (p - estart);
637 }
638
639 static char *
640 bexpand (string, len, sawc, lenp)
641      char *string;
642      int len, *sawc, *lenp;
643 {
644   int temp;
645   char *ret, *r, *s, c;
646
647   if (string == 0 || *string == '\0')
648     {
649       if (sawc)
650         *sawc = 0;
651       if (lenp)
652         *lenp = 0;
653       return ((char *)NULL);
654     }
655
656   ret = (char *)xmalloc (len + 1);
657   for (r = ret, s = string; s && *s; )
658     {
659       c = *s++;
660       if (c != '\\' || *s == '\0')
661         {
662           *r++ = c;
663           continue;
664         }
665       temp = 0;
666       s += tescape (s, &c, &temp);
667       if (temp)
668         {
669           if (sawc)
670             *sawc = 1;
671           break;
672         }
673
674       *r++ = c;
675     }
676
677   *r = '\0';
678   if (lenp)
679     *lenp = r - ret;
680   return ret;
681 }
682
683 static char *
684 mklong (str, modifiers, mlen)
685      char *str;
686      char *modifiers;
687      size_t mlen;
688 {
689   size_t len, slen;
690
691   slen = strlen (str);
692   len = slen + mlen + 1;
693
694   if (len > conv_bufsize)
695     {
696       conv_bufsize = (((len + 1023) >> 10) << 10);
697       conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
698     }
699
700   FASTCOPY (str, conv_buf, slen - 1);
701   FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
702
703   conv_buf[len - 2] = str[slen - 1];
704   conv_buf[len - 1] = '\0';
705   return (conv_buf);
706 }
707
708 static int
709 getchr ()
710 {
711   int ret;
712
713   if (garglist == 0)
714     return ('\0');
715
716   ret = (int)garglist->word->word[0];
717   garglist = garglist->next;
718   return ret;
719 }
720
721 static char *
722 getstr ()
723 {
724   char *ret;
725
726   if (garglist == 0)
727     return ("");
728
729   ret = garglist->word->word;
730   garglist = garglist->next;
731   return ret;
732 }
733
734 static int
735 getint ()
736 {
737   intmax_t ret;
738
739   ret = getintmax ();
740
741   if (ret > INT_MAX)
742     {
743       printf_erange (garglist->word->word);
744       ret = INT_MAX;
745     }
746   else if (ret < INT_MIN)
747     {
748       printf_erange (garglist->word->word);
749       ret = INT_MIN;
750     }
751
752   return ((int)ret);
753 }
754
755 static intmax_t
756 getintmax ()
757 {
758   intmax_t ret;
759   char *ep;
760
761   if (garglist == 0)
762     return (0);
763
764   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
765     return asciicode ();
766
767   errno = 0;
768   ret = strtoimax (garglist->word->word, &ep, 0);
769
770   if (*ep)
771     {
772       sh_invalidnum (garglist->word->word);
773       /* POSIX.2 says ``...a diagnostic message shall be written to standard
774          error, and the utility shall not exit with a zero exit status, but
775          shall continue processing any remaining operands and shall write the
776          value accumulated at the time the error was detected to standard
777          output.''  Yecch. */
778       ret = 0;
779       conversion_error = 1;
780     }
781   else if (errno == ERANGE)
782     printf_erange (garglist->word->word);
783
784   garglist = garglist->next;
785   return (ret);
786 }
787
788 static uintmax_t
789 getuintmax ()
790 {
791   uintmax_t ret;
792   char *ep;
793
794   if (garglist == 0)
795     return (0);
796
797   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
798     return asciicode ();
799
800   errno = 0;
801   ret = strtoumax (garglist->word->word, &ep, 0);
802   
803   if (*ep)
804     {
805       sh_invalidnum (garglist->word->word);
806       /* Same POSIX.2 conversion error requirements as getintmax(). */
807       ret = 0;
808       conversion_error = 1;
809     }
810   else if (errno == ERANGE)
811     printf_erange (garglist->word->word);
812
813   garglist = garglist->next;
814   return (ret);
815 }
816
817 static floatmax_t
818 getfloatmax ()
819 {
820   floatmax_t ret;
821   char *ep;
822
823   if (garglist == 0)
824     return (0);
825
826   if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
827     return asciicode ();
828
829   errno = 0;
830   ret = strtofltmax (garglist->word->word, &ep);
831
832   if (*ep)
833     {
834       sh_invalidnum (garglist->word->word);
835       /* Same thing about POSIX.2 conversion error requirements. */
836       ret = 0;
837       conversion_error = 1;
838     }
839   else if (errno == ERANGE)
840     printf_erange (garglist->word->word);
841
842   garglist = garglist->next;
843   return (ret);
844 }
845
846 /* NO check is needed for garglist here. */
847 static int
848 asciicode ()
849 {
850   register int ch;
851
852   ch = garglist->word->word[1];
853   garglist = garglist->next;
854   return (ch);
855 }