1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997-2010 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),
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
43 %(fmt)T output the date-time string resulting from using FMT as a format
44 string for strftime(3)
46 The format is re-used as necessary to consume all of the arguments. If
47 there are fewer arguments than the format requires, extra format
48 specifications behave as if a zero value or null string, as appropriate,
52 Returns success unless an invalid option is given or a write or assignment
58 #include "../bashtypes.h"
61 #if defined (HAVE_LIMITS_H)
64 /* Assume 32-bit ints. */
65 # define INT_MAX 2147483647
66 # define INT_MIN (-2147483647-1)
69 #if defined (PREFER_STDARG)
76 #include <chartypes.h>
78 #ifdef HAVE_INTTYPES_H
79 # include <inttypes.h>
82 #include "posixtime.h"
83 #include "../bashansi.h"
84 #include "../bashintl.h"
86 #define NEED_STRFTIME_DECL
91 #include "bashgetopt.h"
94 #if defined (PRI_MACROS_BROKEN)
98 #if !defined (PRIdMAX)
100 # define PRIdMAX "lld"
102 # define PRIdMAX "ld"
114 b[0] = c; b[1] = '\0'; \
121 #define PF(f, func) \
125 if (have_fieldwidth && have_precision) \
126 nw = vflag ? vbprintf (f, fieldwidth, precision, func) : printf (f, fieldwidth, precision, func); \
127 else if (have_fieldwidth) \
128 nw = vflag ? vbprintf (f, fieldwidth, func) : printf (f, fieldwidth, func); \
129 else if (have_precision) \
130 nw = vflag ? vbprintf (f, precision, func) : printf (f, precision, func); \
132 nw = vflag ? vbprintf (f, func) : printf (f, func); \
134 if (ferror (stdout)) \
138 return (EXECUTION_FAILURE); \
142 /* We free the buffer used by mklong() if it's `too big'. */
143 #define PRETURN(value) \
148 bind_printf_variable (vname, vbuf, 0); \
149 stupidly_hack_special_variables (vname); \
151 if (conv_bufsize > 4096 ) \
165 terminate_immediately--; \
166 if (ferror (stdout) == 0) \
168 if (ferror (stdout)) \
172 return (EXECUTION_FAILURE); \
178 #define SKIP1 "#'-+ 0"
179 #define LENMODS "hjlLtz"
181 extern time_t shell_start_time;
184 extern int asprintf __P((char **, const char *, ...)) __attribute__((__format__ (printf, 2, 3)));
188 extern int vsnprintf __P((char *, size_t, const char *, va_list)) __attribute__((__format__ (printf, 3, 0)));
191 static void printf_erange __P((char *));
192 static int printstr __P((char *, char *, int, int, int));
193 static int tescape __P((char *, char *, int *, int *));
194 static char *bexpand __P((char *, int, int *, int *));
195 static char *vbadd __P((char *, int));
196 static int vbprintf __P((const char *, ...)) __attribute__((__format__ (printf, 1, 2)));
197 static char *mklong __P((char *, char *, size_t));
198 static int getchr __P((void));
199 static char *getstr __P((void));
200 static int getint __P((void));
201 static intmax_t getintmax __P((void));
202 static uintmax_t getuintmax __P((void));
203 static SHELL_VAR *bind_printf_variable __P((char *, char *, int));
205 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
206 typedef long double floatmax_t;
207 # define FLOATMAX_CONV "L"
208 # define strtofltmax strtold
210 typedef double floatmax_t;
211 # define FLOATMAX_CONV ""
212 # define strtofltmax strtod
214 static floatmax_t getfloatmax __P((void));
216 static intmax_t asciicode __P((void));
218 static WORD_LIST *garglist;
220 static int conversion_error;
222 /* printf -v var support */
223 static int vflag = 0;
224 static char *vbuf, *vname;
225 static size_t vbsize;
230 static char *conv_buf;
231 static size_t conv_bufsize;
234 printf_builtin (list)
237 int ch, fieldwidth, precision;
238 int have_fieldwidth, have_precision;
239 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
240 #if defined (HANDLE_MULTIBYTE)
241 char mbch[25]; /* 25 > MB_LEN_MAX, plus can handle 4-byte UTF-8 and large Unicode characters*/
245 conversion_error = 0;
246 retval = EXECUTION_SUCCESS;
250 reset_internal_getopt ();
251 while ((ch = internal_getopt (list, "v:")) != -1)
257 #if defined (ARRAY_VARS)
258 if (legal_identifier (vname) || valid_array_reference (vname))
260 if (legal_identifier (vname))
265 vbuf = xmalloc (vbsize = 16);
272 sh_invalidid (vname);
281 list = loptend; /* skip over possible `--' */
289 if (list->word->word == 0 || list->word->word[0] == '\0')
290 return (EXECUTION_SUCCESS);
292 format = list->word->word;
295 garglist = list->next;
297 /* If the format string is empty after preprocessing, return immediately. */
298 if (format == 0 || *format == 0)
299 return (EXECUTION_SUCCESS);
301 terminate_immediately++;
303 /* Basic algorithm is to scan the format string for conversion
304 specifications -- once one is found, find out if the field
305 width or precision is a '*'; if it is, gather up value. Note,
306 format strings are reused as necessary to use up the provided
307 arguments, arguments of zero/null string are provided to use
308 up the format string. */
312 /* find next format specification */
313 for (fmt = format; *fmt; fmt++)
315 precision = fieldwidth = 0;
316 have_fieldwidth = have_precision = 0;
321 /* A NULL third argument to tescape means to bypass the
322 special processing for arguments to %b. */
323 #if defined (HANDLE_MULTIBYTE)
324 /* Accommodate possible use of \u or \U, which can result in
325 multibyte characters */
326 memset (mbch, '\0', sizeof (mbch));
327 fmt += tescape (fmt, mbch, &mblen, (int *)NULL);
328 for (mbind = 0; mbind < mblen; mbind++)
331 fmt += tescape (fmt, &nextch, (int *)NULL, (int *)NULL);
334 fmt--; /* for loop will increment it for us again */
344 /* ASSERT(*fmt == '%') */
347 if (*fmt == '%') /* %% prints a % */
353 /* found format specification, skip to field width */
354 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
357 /* Skip optional field width. */
362 fieldwidth = getint ();
368 /* Skip optional '.' and precision */
376 precision = getint ();
380 /* Negative precisions are allowed but treated as if the
381 precision were missing; I would like to allow a leading
382 `+' in the precision number as an extension, but lots
383 of asprintf/fprintf implementations get this wrong. */
385 if (*fmt == '-' || *fmt == '+')
395 /* skip possible format modifiers */
397 while (*fmt && strchr (LENMODS, *fmt))
402 builtin_error (_("`%s': missing format character"), start);
403 PRETURN (EXECUTION_FAILURE);
407 thisch = modstart[0];
408 nextch = modstart[1];
409 modstart[0] = convch;
434 char *timefmt, timebuf[128], *t;
440 modstart[1] = nextch; /* restore char after left paren */
441 timefmt = xmalloc (strlen (fmt) + 3);
442 fmt++; /* skip over left paren */
443 for (t = timefmt, n = 1; *fmt; )
447 else if (*fmt == ')')
456 builtin_warning (_("`%c': invalid time format specification"), *fmt);
462 if (timefmt[0] == '\0')
465 timefmt[1] = 'X'; /* locale-specific current time - should we use `+'? */
468 /* argument is seconds since the epoch with special -1 and -2 */
469 /* default argument is equivalent to -1; special case */
470 arg = garglist ? getintmax () : -1;
472 secs = NOW; /* roughly date +%s */
474 secs = shell_start_time; /* roughly $SECONDS */
477 #if defined (HAVE_TZSET)
478 sv_tz ("TZ"); /* XXX -- just make sure */
480 tm = localtime (&secs);
484 tm = localtime (&secs);
486 n = tm ? strftime (timebuf, sizeof (timebuf), timefmt, tm) : 0;
491 timebuf[sizeof(timebuf) - 1] = '\0';
492 /* convert to %s format that preserves fieldwidth and precision */
495 n = printstr (start, timebuf, strlen (timebuf), fieldwidth, precision); /* XXX - %s for now */
498 if (ferror (stdout) == 0)
503 PRETURN (EXECUTION_FAILURE);
515 if (legal_identifier (var))
516 bind_var_to_int (var, tw);
520 PRETURN (EXECUTION_FAILURE);
526 case 'b': /* expand escapes in argument */
533 xp = bexpand (p, strlen (p), &ch, &rlen);
537 /* Have to use printstr because of possible NUL bytes
538 in XP -- printf does not handle that well. */
539 r = printstr (start, xp, rlen, fieldwidth, precision);
542 if (ferror (stdout) == 0)
547 retval = EXECUTION_FAILURE;
557 case 'q': /* print with shell quoting */
564 if (p && *p == 0) /* XXX - getstr never returns null */
565 xp = savestring ("''");
566 else if (ansic_shouldquote (p))
567 xp = ansic_quote (p, 0, (int *)0);
569 xp = sh_backslash_quote (p, 0, 1);
572 /* Use printstr to get fieldwidth and precision right. */
573 r = printstr (start, xp, strlen (xp), fieldwidth, precision);
583 PRETURN (EXECUTION_FAILURE);
594 p = pp = getintmax ();
597 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
602 /* Optimize the common case where the integer fits
603 in "long". This also works around some long
604 long and/or intmax_t library bugs in the common
605 case, e.g. glibc 2.2 x86. */
606 f = mklong (start, "l", 1);
621 p = pp = getuintmax ();
624 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
629 f = mklong (start, "l", 1);
641 #if defined (HAVE_PRINTF_A_FORMAT)
650 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
655 /* We don't output unrecognized format characters; we print an
656 error message and return a failure exit status. */
658 builtin_error (_("`%c': invalid format character"), convch);
659 PRETURN (EXECUTION_FAILURE);
662 modstart[0] = thisch;
663 modstart[1] = nextch;
668 /* PRETURN will print error message. */
669 PRETURN (EXECUTION_FAILURE);
672 while (garglist && garglist != list->next);
674 if (conversion_error)
675 retval = EXECUTION_FAILURE;
684 builtin_error (_("warning: %s: %s"), s, strerror(ERANGE));
687 /* We duplicate a lot of what printf(3) does here. */
689 printstr (fmt, string, len, fieldwidth, precision)
690 char *fmt; /* format */
691 char *string; /* expanded string argument */
692 int len; /* length of expanded string */
693 int fieldwidth; /* argument for width of `*' */
694 int precision; /* argument for precision of `*' */
699 int padlen, nc, ljust, i;
700 int fw, pr; /* fieldwidth and precision */
703 if (string == 0 || len == 0)
718 while (strchr (SKIP1, *fmt))
725 /* get fieldwidth, if present. rely on caller to clamp fieldwidth at INT_MAX */
736 else if (DIGIT (*fmt))
740 mfw = (mfw * 10) + (*fmt++ - '0');
741 /* Error if fieldwidth > INT_MAX here? */
742 fw = (mfw < 0 || mfw > INT_MAX) ? INT_MAX : mfw;
745 /* get precision, if present */
754 else if (DIGIT (*fmt))
758 mpr = (mpr * 10) + (*fmt++ - '0');
759 /* Error if precision > INT_MAX here? */
760 pr = (mpr < 0 || mpr > INT_MAX) ? INT_MAX : mpr;
765 /* If we remove this, get rid of `s'. */
766 if (*fmt != 'b' && *fmt != 'q')
768 internal_error (_("format parsing problem: %s"), s);
773 /* chars from string to print */
774 nc = (pr >= 0 && pr <= len) ? pr : len;
782 /* leading pad characters */
783 for (; padlen > 0; padlen--)
786 /* output NC characters from STRING */
787 for (i = 0; i < nc; i++)
790 /* output any necessary trailing padding */
791 for (; padlen < 0; padlen++)
794 return (ferror (stdout) ? -1 : 0);
797 /* Convert STRING by expanding the escape sequences specified by the
798 POSIX standard for printf's `%b' format string. If SAWC is non-null,
799 perform the processing appropriate for %b arguments. In particular,
800 recognize `\c' and use that as a string terminator. If we see \c, set
801 *SAWC to 1 before returning. LEN is the length of STRING. */
803 /* Translate a single backslash-escape sequence starting at ESTART (the
804 character after the backslash) and return the number of characters
805 consumed by the sequence. CP is the place to return the translated
806 value. *SAWC is set to 1 if the escape sequence was \c, since that means
807 to short-circuit the rest of the processing. If SAWC is null, we don't
808 do the \c short-circuiting, and \c is treated as an unrecognized escape
809 sequence; we also bypass the other processing specific to %b arguments. */
811 tescape (estart, cp, lenp, sawc)
818 unsigned long uvalue;
826 #if defined (__STDC__)
827 case 'a': *cp = '\a'; break;
829 case 'a': *cp = '\007'; break;
832 case 'b': *cp = '\b'; break;
835 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
837 case 'f': *cp = '\f'; break;
839 case 'n': *cp = '\n'; break;
841 case 'r': *cp = '\r'; break;
843 case 't': *cp = '\t'; break;
845 case 'v': *cp = '\v'; break;
847 /* The octal escape sequences are `\0' followed by up to three octal
848 digits (if SAWC), or `\' followed by up to three octal digits (if
849 !SAWC). As an extension, we allow the latter form even if SAWC. */
850 case '0': case '1': case '2': case '3':
851 case '4': case '5': case '6': case '7':
852 evalue = OCTVALUE (c);
853 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
854 evalue = (evalue * 8) + OCTVALUE (*p);
858 /* And, as another extension, we allow \xNN, where each N is a
861 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
862 evalue = (evalue * 16) + HEXVALUE (*p);
865 builtin_error (_("missing hex digit for \\x"));
872 #if defined (HANDLE_MULTIBYTE)
875 temp = (c == 'u') ? 4 : 8; /* \uNNNN \UNNNNNNNN */
876 for (uvalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
877 uvalue = (uvalue * 16) + HEXVALUE (*p);
880 builtin_error (_("missing unicode digit for \\%c"), c);
884 if (uvalue <= 0x7f) /* <= 0x7f translates directly */
888 temp = u32cconv (uvalue, cp);
896 case '\\': /* \\ -> \ */
900 /* SAWC == 0 means that \', \", and \? are recognized as escape
901 sequences, though the only processing performed is backslash
903 case '\'': case '"': case '?':
919 /* other backslash escapes are passed through unaltered */
928 bexpand (string, len, sawc, lenp)
930 int len, *sawc, *lenp;
933 char *ret, *r, *s, c;
934 #if defined (HANDLE_MULTIBYTE)
939 if (string == 0 || len == 0)
945 return ((char *)NULL);
948 ret = (char *)xmalloc (len + 1);
949 for (r = ret, s = string; s && *s; )
952 if (c != '\\' || *s == '\0')
958 #if defined (HANDLE_MULTIBYTE)
959 memset (mbch, '\0', sizeof (mbch));
960 s += tescape (s, mbch, &mblen, &temp);
962 s += tescape (s, &c, (int *)NULL, &temp);
971 #if defined (HANDLE_MULTIBYTE)
972 for (mbind = 0; mbind < mblen; mbind++)
992 nlen = vblen + blen + 1;
995 vbsize = ((nlen + 63) >> 6) << 6;
996 vbuf = (char *)xrealloc (vbuf, vbsize);
1000 vbuf[vblen++] = buf[0];
1003 FASTCOPY (buf, vbuf + vblen, blen);
1009 if (strlen (vbuf) != vblen)
1010 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
1017 #if defined (PREFER_STDARG)
1018 vbprintf (const char *format, ...)
1020 vbprintf (format, va_alist)
1029 SH_VA_START (args, format);
1030 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
1033 nlen = vblen + blen + 1;
1036 vbsize = ((nlen + 63) >> 6) << 6;
1037 vbuf = (char *)xrealloc (vbuf, vbsize);
1038 SH_VA_START (args, format);
1039 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
1047 if (strlen (vbuf) != vblen)
1048 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
1055 mklong (str, modifiers, mlen)
1062 slen = strlen (str);
1063 len = slen + mlen + 1;
1065 if (len > conv_bufsize)
1067 conv_bufsize = (((len + 1023) >> 10) << 10);
1068 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
1071 FASTCOPY (str, conv_buf, slen - 1);
1072 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
1074 conv_buf[len - 2] = str[slen - 1];
1075 conv_buf[len - 1] = '\0';
1087 ret = (int)garglist->word->word[0];
1088 garglist = garglist->next;
1100 ret = garglist->word->word;
1101 garglist = garglist->next;
1117 printf_erange (garglist->word->word);
1120 else if (ret < INT_MIN)
1122 printf_erange (garglist->word->word);
1138 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1139 return asciicode ();
1142 ret = strtoimax (garglist->word->word, &ep, 0);
1146 sh_invalidnum (garglist->word->word);
1147 /* POSIX.2 says ``...a diagnostic message shall be written to standard
1148 error, and the utility shall not exit with a zero exit status, but
1149 shall continue processing any remaining operands and shall write the
1150 value accumulated at the time the error was detected to standard
1153 ret = 0; /* return partially-converted value from strtoimax */
1155 conversion_error = 1;
1157 else if (errno == ERANGE)
1158 printf_erange (garglist->word->word);
1160 garglist = garglist->next;
1173 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1174 return asciicode ();
1177 ret = strtoumax (garglist->word->word, &ep, 0);
1181 sh_invalidnum (garglist->word->word);
1182 /* Same POSIX.2 conversion error requirements as getintmax(). */
1184 conversion_error = 1;
1186 else if (errno == ERANGE)
1187 printf_erange (garglist->word->word);
1189 garglist = garglist->next;
1202 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1203 return asciicode ();
1206 ret = strtofltmax (garglist->word->word, &ep);
1210 sh_invalidnum (garglist->word->word);
1211 /* Same thing about POSIX.2 conversion error requirements. */
1213 conversion_error = 1;
1215 else if (errno == ERANGE)
1216 printf_erange (garglist->word->word);
1218 garglist = garglist->next;
1222 /* NO check is needed for garglist here. */
1226 register intmax_t ch;
1227 #if defined (HANDLE_MULTIBYTE)
1229 size_t mblength, slen;
1233 #if defined (HANDLE_MULTIBYTE)
1234 slen = strlen (garglist->word->word+1);
1235 mblength = MBLEN (garglist->word->word+1, slen);
1238 mblength = mbtowc (&wc, garglist->word->word+1, slen);
1243 ch = (unsigned char)garglist->word->word[1];
1245 garglist = garglist->next;
1250 bind_printf_variable (name, value, flags)
1257 #if defined (ARRAY_VARS)
1258 if (valid_array_reference (name) == 0)
1259 v = bind_variable (name, value, flags);
1261 v = assign_array_element (name, value, flags);
1262 #else /* !ARRAY_VARS */
1263 v = bind_variable (name, value, flags);
1264 #endif /* !ARRAY_VARS */
1266 if (v && readonly_p (v) == 0 && noassign_p (v) == 0)
1267 VUNSETATTR (v, att_invisible);