1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997-2009 Free Software Foundation, Inc.
6 This file is part of GNU Bash, the Bourne Again SHell.
8 Bash is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 Bash is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Bash. If not, see <http://www.gnu.org/licenses/>.
24 $FUNCTION printf_builtin
25 $SHORT_DOC printf [-v var] format [arguments]
26 Formats and prints ARGUMENTS under control of the FORMAT.
29 -v var assign the output to shell variable VAR rather than
30 display it on the standard output
32 FORMAT is a character string which contains three types of objects: plain
33 characters, which are simply copied to standard output; character escape
34 sequences, which are converted and copied to the standard output; and
35 format specifications, each of which causes printing of the next successive
38 In addition to the standard format specifications described in printf(1)
39 and printf(3), printf interprets:
41 %b expand backslash escape sequences in the corresponding argument
42 %q quote the argument in a way that can be reused as shell input
45 Returns success unless an invalid option is given or a write or assignment
51 #include "../bashtypes.h"
54 #if defined (HAVE_LIMITS_H)
57 /* Assume 32-bit ints. */
58 # define INT_MAX 2147483647
59 # define INT_MIN (-2147483647-1)
62 #if defined (PREFER_STDARG)
69 #include <chartypes.h>
71 #ifdef HAVE_INTTYPES_H
72 # include <inttypes.h>
75 #include "../bashansi.h"
76 #include "../bashintl.h"
81 #include "bashgetopt.h"
84 #if defined (PRI_MACROS_BROKEN)
88 #if !defined (PRIdMAX)
90 # define PRIdMAX "lld"
104 b[0] = c; b[1] = '\0'; \
111 #define PF(f, func) \
115 if (have_fieldwidth && have_precision) \
116 nw = vflag ? vbprintf (f, fieldwidth, precision, func) : printf (f, fieldwidth, precision, func); \
117 else if (have_fieldwidth) \
118 nw = vflag ? vbprintf (f, fieldwidth, func) : printf (f, fieldwidth, func); \
119 else if (have_precision) \
120 nw = vflag ? vbprintf (f, precision, func) : printf (f, fieldwidth, func); \
122 nw = vflag ? vbprintf (f, func) : printf (f, func); \
124 if (ferror (stdout)) \
128 return (EXECUTION_FAILURE); \
132 /* We free the buffer used by mklong() if it's `too big'. */
133 #define PRETURN(value) \
138 bind_printf_variable (vname, vbuf, 0); \
139 stupidly_hack_special_variables (vname); \
141 if (conv_bufsize > 4096 ) \
155 terminate_immediately--; \
157 if (ferror (stdout)) \
161 return (EXECUTION_FAILURE); \
167 #define SKIP1 "#'-+ 0"
168 #define LENMODS "hjlLtz"
171 extern int asprintf __P((char **, const char *, ...)) __attribute__((__format__ (printf, 2, 3)));
175 extern int vsnprintf __P((char *, size_t, const char *, ...)) __attribute__((__format__ (printf, 3, 4)));
178 static void printf_erange __P((char *));
179 static int printstr __P((char *, char *, int, int, int));
180 static int tescape __P((char *, char *, int *));
181 static char *bexpand __P((char *, int, int *, int *));
182 static char *vbadd __P((char *, int));
183 static int vbprintf __P((const char *, ...)) __attribute__((__format__ (printf, 1, 2)));
184 static char *mklong __P((char *, char *, size_t));
185 static int getchr __P((void));
186 static char *getstr __P((void));
187 static int getint __P((void));
188 static intmax_t getintmax __P((void));
189 static uintmax_t getuintmax __P((void));
190 static SHELL_VAR *bind_printf_variable __P((char *, char *, int));
192 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
193 typedef long double floatmax_t;
194 # define FLOATMAX_CONV "L"
195 # define strtofltmax strtold
197 typedef double floatmax_t;
198 # define FLOATMAX_CONV ""
199 # define strtofltmax strtod
201 static floatmax_t getfloatmax __P((void));
203 static intmax_t asciicode __P((void));
205 static WORD_LIST *garglist;
207 static int conversion_error;
209 /* printf -v var support */
210 static int vflag = 0;
211 static char *vbuf, *vname;
212 static size_t vbsize;
217 static char *conv_buf;
218 static size_t conv_bufsize;
221 printf_builtin (list)
224 int ch, fieldwidth, precision;
225 int have_fieldwidth, have_precision;
226 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
228 conversion_error = 0;
229 retval = EXECUTION_SUCCESS;
233 reset_internal_getopt ();
234 while ((ch = internal_getopt (list, "v:")) != -1)
240 #if defined (ARRAY_VARS)
241 if (legal_identifier (vname) || valid_array_reference (vname))
243 if (legal_identifier (vname))
253 sh_invalidid (vname);
262 list = loptend; /* skip over possible `--' */
270 if (list->word->word == 0 || list->word->word[0] == '\0')
271 return (EXECUTION_SUCCESS);
273 format = list->word->word;
276 garglist = list->next;
278 /* If the format string is empty after preprocessing, return immediately. */
279 if (format == 0 || *format == 0)
280 return (EXECUTION_SUCCESS);
282 terminate_immediately++;
284 /* Basic algorithm is to scan the format string for conversion
285 specifications -- once one is found, find out if the field
286 width or precision is a '*'; if it is, gather up value. Note,
287 format strings are reused as necessary to use up the provided
288 arguments, arguments of zero/null string are provided to use
289 up the format string. */
293 /* find next format specification */
294 for (fmt = format; *fmt; fmt++)
296 precision = fieldwidth = 0;
297 have_fieldwidth = have_precision = 0;
302 /* A NULL third argument to tescape means to bypass the
303 special processing for arguments to %b. */
304 fmt += tescape (fmt, &nextch, (int *)NULL);
306 fmt--; /* for loop will increment it for us again */
316 /* ASSERT(*fmt == '%') */
319 if (*fmt == '%') /* %% prints a % */
325 /* found format specification, skip to field width */
326 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
329 /* Skip optional field width. */
334 fieldwidth = getint ();
340 /* Skip optional '.' and precision */
348 precision = getint ();
352 /* Negative precisions are allowed but treated as if the
353 precision were missing; I would like to allow a leading
354 `+' in the precision number as an extension, but lots
355 of asprintf/fprintf implementations get this wrong. */
357 if (*fmt == '-' || *fmt == '+')
367 /* skip possible format modifiers */
369 while (*fmt && strchr (LENMODS, *fmt))
374 builtin_error (_("`%s': missing format character"), start);
375 PRETURN (EXECUTION_FAILURE);
379 thisch = modstart[0];
380 nextch = modstart[1];
381 modstart[0] = convch;
411 if (legal_identifier (var))
412 bind_var_to_int (var, tw);
416 PRETURN (EXECUTION_FAILURE);
422 case 'b': /* expand escapes in argument */
429 xp = bexpand (p, strlen (p), &ch, &rlen);
433 /* Have to use printstr because of possible NUL bytes
434 in XP -- printf does not handle that well. */
435 r = printstr (start, xp, rlen, fieldwidth, precision);
440 retval = EXECUTION_FAILURE;
450 case 'q': /* print with shell quoting */
457 if (p && *p == 0) /* XXX - getstr never returns null */
458 xp = savestring ("''");
459 else if (ansic_shouldquote (p))
460 xp = ansic_quote (p, 0, (int *)0);
462 xp = sh_backslash_quote (p);
465 /* Use printstr to get fieldwidth and precision right. */
466 r = printstr (start, xp, strlen (xp), fieldwidth, precision);
476 PRETURN (EXECUTION_FAILURE);
487 p = pp = getintmax ();
490 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
495 /* Optimize the common case where the integer fits
496 in "long". This also works around some long
497 long and/or intmax_t library bugs in the common
498 case, e.g. glibc 2.2 x86. */
499 f = mklong (start, "l", 1);
514 p = pp = getuintmax ();
517 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
522 f = mklong (start, "l", 1);
534 #if defined (HAVE_PRINTF_A_FORMAT)
543 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
548 /* We don't output unrecognized format characters; we print an
549 error message and return a failure exit status. */
551 builtin_error (_("`%c': invalid format character"), convch);
552 PRETURN (EXECUTION_FAILURE);
555 modstart[0] = thisch;
556 modstart[1] = nextch;
563 PRETURN (EXECUTION_FAILURE);
566 while (garglist && garglist != list->next);
568 if (conversion_error)
569 retval = EXECUTION_FAILURE;
578 builtin_error (_("warning: %s: %s"), s, strerror(ERANGE));
581 /* We duplicate a lot of what printf(3) does here. */
583 printstr (fmt, string, len, fieldwidth, precision)
584 char *fmt; /* format */
585 char *string; /* expanded string argument */
586 int len; /* length of expanded string */
587 int fieldwidth; /* argument for width of `*' */
588 int precision; /* argument for precision of `*' */
593 int padlen, nc, ljust, i;
594 int fw, pr; /* fieldwidth and precision */
597 if (string == 0 || *string == '\0')
599 if (string == 0 || len == 0)
613 while (strchr (SKIP1, *fmt))
620 /* get fieldwidth, if present */
631 else if (DIGIT (*fmt))
635 fw = (fw * 10) + (*fmt++ - '0');
638 /* get precision, if present */
647 else if (DIGIT (*fmt))
651 pr = (pr * 10) + (*fmt++ - '0');
656 /* If we remove this, get rid of `s'. */
657 if (*fmt != 'b' && *fmt != 'q')
659 internal_error ("format parsing problem: %s", s);
664 /* chars from string to print */
665 nc = (pr >= 0 && pr <= len) ? pr : len;
673 /* leading pad characters */
674 for (; padlen > 0; padlen--)
677 /* output NC characters from STRING */
678 for (i = 0; i < nc; i++)
681 /* output any necessary trailing padding */
682 for (; padlen < 0; padlen++)
685 return (ferror (stdout) ? -1 : 0);
688 /* Convert STRING by expanding the escape sequences specified by the
689 POSIX standard for printf's `%b' format string. If SAWC is non-null,
690 perform the processing appropriate for %b arguments. In particular,
691 recognize `\c' and use that as a string terminator. If we see \c, set
692 *SAWC to 1 before returning. LEN is the length of STRING. */
694 /* Translate a single backslash-escape sequence starting at ESTART (the
695 character after the backslash) and return the number of characters
696 consumed by the sequence. CP is the place to return the translated
697 value. *SAWC is set to 1 if the escape sequence was \c, since that means
698 to short-circuit the rest of the processing. If SAWC is null, we don't
699 do the \c short-circuiting, and \c is treated as an unrecognized escape
700 sequence; we also bypass the other processing specific to %b arguments. */
702 tescape (estart, cp, sawc)
714 #if defined (__STDC__)
715 case 'a': *cp = '\a'; break;
717 case 'a': *cp = '\007'; break;
720 case 'b': *cp = '\b'; break;
723 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
725 case 'f': *cp = '\f'; break;
727 case 'n': *cp = '\n'; break;
729 case 'r': *cp = '\r'; break;
731 case 't': *cp = '\t'; break;
733 case 'v': *cp = '\v'; break;
735 /* The octal escape sequences are `\0' followed by up to three octal
736 digits (if SAWC), or `\' followed by up to three octal digits (if
737 !SAWC). As an extension, we allow the latter form even if SAWC. */
738 case '0': case '1': case '2': case '3':
739 case '4': case '5': case '6': case '7':
740 evalue = OCTVALUE (c);
741 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
742 evalue = (evalue * 8) + OCTVALUE (*p);
746 /* And, as another extension, we allow \xNNN, where each N is a
750 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
752 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
754 evalue = (evalue * 16) + HEXVALUE (*p);
757 builtin_error (_("missing hex digit for \\x"));
764 case '\\': /* \\ -> \ */
768 /* SAWC == 0 means that \', \", and \? are recognized as escape
769 sequences, though the only processing performed is backslash
771 case '\'': case '"': case '?':
787 /* other backslash escapes are passed through unaltered */
796 bexpand (string, len, sawc, lenp)
798 int len, *sawc, *lenp;
801 char *ret, *r, *s, c;
804 if (string == 0 || *string == '\0')
806 if (string == 0 || len == 0)
813 return ((char *)NULL);
816 ret = (char *)xmalloc (len + 1);
817 for (r = ret, s = string; s && *s; )
820 if (c != '\\' || *s == '\0')
826 s += tescape (s, &c, &temp);
850 nlen = vblen + blen + 1;
853 vbsize = ((nlen + 63) >> 6) << 6;
854 vbuf = (char *)xrealloc (vbuf, vbsize);
858 vbuf[vblen++] = buf[0];
861 FASTCOPY (buf, vbuf + vblen, blen);
867 if (strlen (vbuf) != vblen)
868 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
875 #if defined (PREFER_STDARG)
876 vbprintf (const char *format, ...)
878 vbprintf (format, va_alist)
887 SH_VA_START (args, format);
888 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
891 nlen = vblen + blen + 1;
894 vbsize = ((nlen + 63) >> 6) << 6;
895 vbuf = (char *)xrealloc (vbuf, vbsize);
896 SH_VA_START (args, format);
897 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
905 if (strlen (vbuf) != vblen)
906 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
913 mklong (str, modifiers, mlen)
921 len = slen + mlen + 1;
923 if (len > conv_bufsize)
925 conv_bufsize = (((len + 1023) >> 10) << 10);
926 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
929 FASTCOPY (str, conv_buf, slen - 1);
930 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
932 conv_buf[len - 2] = str[slen - 1];
933 conv_buf[len - 1] = '\0';
945 ret = (int)garglist->word->word[0];
946 garglist = garglist->next;
958 ret = garglist->word->word;
959 garglist = garglist->next;
972 printf_erange (garglist->word->word);
975 else if (ret < INT_MIN)
977 printf_erange (garglist->word->word);
993 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
997 ret = strtoimax (garglist->word->word, &ep, 0);
1001 sh_invalidnum (garglist->word->word);
1002 /* POSIX.2 says ``...a diagnostic message shall be written to standard
1003 error, and the utility shall not exit with a zero exit status, but
1004 shall continue processing any remaining operands and shall write the
1005 value accumulated at the time the error was detected to standard
1008 ret = 0; /* return partially-converted value from strtoimax */
1010 conversion_error = 1;
1012 else if (errno == ERANGE)
1013 printf_erange (garglist->word->word);
1015 garglist = garglist->next;
1028 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1029 return asciicode ();
1032 ret = strtoumax (garglist->word->word, &ep, 0);
1036 sh_invalidnum (garglist->word->word);
1037 /* Same POSIX.2 conversion error requirements as getintmax(). */
1039 conversion_error = 1;
1041 else if (errno == ERANGE)
1042 printf_erange (garglist->word->word);
1044 garglist = garglist->next;
1057 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1058 return asciicode ();
1061 ret = strtofltmax (garglist->word->word, &ep);
1065 sh_invalidnum (garglist->word->word);
1066 /* Same thing about POSIX.2 conversion error requirements. */
1068 conversion_error = 1;
1070 else if (errno == ERANGE)
1071 printf_erange (garglist->word->word);
1073 garglist = garglist->next;
1077 /* NO check is needed for garglist here. */
1081 register intmax_t ch;
1082 #if defined (HANDLE_MULTIBYTE)
1084 size_t mblength, slen;
1088 #if defined (HANDLE_MULTIBYTE)
1089 slen = strlen (garglist->word->word+1);
1090 mblength = MBLEN (garglist->word->word+1, slen);
1093 mblength = mbtowc (&wc, garglist->word->word+1, slen);
1098 ch = (unsigned char)garglist->word->word[1];
1100 garglist = garglist->next;
1105 bind_printf_variable (name, value, flags)
1110 #if defined (ARRAY_VARS)
1111 if (valid_array_reference (name) == 0)
1112 return (bind_variable (name, value, flags));
1114 return (assign_array_element (name, value, flags));
1115 #else /* !ARRAY_VARS */
1116 return bind_variable (name, value, flags);
1117 #endif /* !ARRAY_VARS */