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_variable (vname, vbuf, 0); \
139 stupidly_hack_special_variables (vname); \
141 if (conv_bufsize > 4096 ) \
155 terminate_immediately--; \
157 if (ferror (stdout)) \
160 return (EXECUTION_FAILURE); \
166 #define SKIP1 "#'-+ 0"
167 #define LENMODS "hjlLtz"
169 #ifndef HAVE_ASPRINTF
170 extern int asprintf __P((char **, const char *, ...)) __attribute__((__format__ (printf, 2, 3)));
173 #ifndef HAVE_VSNPRINTF
174 extern int vsnprintf __P((char *, size_t, const char *, ...)) __attribute__((__format__ (printf, 3, 4)));
177 static void printf_erange __P((char *));
178 static int printstr __P((char *, char *, int, int, int));
179 static int tescape __P((char *, char *, int *));
180 static char *bexpand __P((char *, int, int *, int *));
181 static char *vbadd __P((char *, int));
182 static int vbprintf __P((const char *, ...)) __attribute__((__format__ (printf, 1, 2)));
183 static char *mklong __P((char *, char *, size_t));
184 static int getchr __P((void));
185 static char *getstr __P((void));
186 static int getint __P((void));
187 static intmax_t getintmax __P((void));
188 static uintmax_t getuintmax __P((void));
190 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
191 typedef long double floatmax_t;
192 # define FLOATMAX_CONV "L"
193 # define strtofltmax strtold
195 typedef double floatmax_t;
196 # define FLOATMAX_CONV ""
197 # define strtofltmax strtod
199 static floatmax_t getfloatmax __P((void));
201 static intmax_t asciicode __P((void));
203 static WORD_LIST *garglist;
205 static int conversion_error;
207 /* printf -v var support */
208 static int vflag = 0;
209 static char *vbuf, *vname;
210 static size_t vbsize;
215 static char *conv_buf;
216 static size_t conv_bufsize;
219 printf_builtin (list)
222 int ch, fieldwidth, precision;
223 int have_fieldwidth, have_precision;
224 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
226 conversion_error = 0;
227 retval = EXECUTION_SUCCESS;
231 reset_internal_getopt ();
232 while ((ch = internal_getopt (list, "v:")) != -1)
237 if (legal_identifier (vname = list_optarg))
246 sh_invalidid (vname);
255 list = loptend; /* skip over possible `--' */
263 if (list->word->word == 0 || list->word->word[0] == '\0')
264 return (EXECUTION_SUCCESS);
266 format = list->word->word;
269 garglist = list->next;
271 /* If the format string is empty after preprocessing, return immediately. */
272 if (format == 0 || *format == 0)
273 return (EXECUTION_SUCCESS);
275 terminate_immediately++;
277 /* Basic algorithm is to scan the format string for conversion
278 specifications -- once one is found, find out if the field
279 width or precision is a '*'; if it is, gather up value. Note,
280 format strings are reused as necessary to use up the provided
281 arguments, arguments of zero/null string are provided to use
282 up the format string. */
286 /* find next format specification */
287 for (fmt = format; *fmt; fmt++)
289 precision = fieldwidth = 0;
290 have_fieldwidth = have_precision = 0;
295 /* A NULL third argument to tescape means to bypass the
296 special processing for arguments to %b. */
297 fmt += tescape (fmt, &nextch, (int *)NULL);
299 fmt--; /* for loop will increment it for us again */
309 /* ASSERT(*fmt == '%') */
312 if (*fmt == '%') /* %% prints a % */
318 /* found format specification, skip to field width */
319 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
322 /* Skip optional field width. */
327 fieldwidth = getint ();
333 /* Skip optional '.' and precision */
341 precision = getint ();
345 /* Negative precisions are allowed but treated as if the
346 precision were missing; I would like to allow a leading
347 `+' in the precision number as an extension, but lots
348 of asprintf/fprintf implementations get this wrong. */
350 if (*fmt == '-' || *fmt == '+')
360 /* skip possible format modifiers */
362 while (*fmt && strchr (LENMODS, *fmt))
367 builtin_error (_("`%s': missing format character"), start);
368 PRETURN (EXECUTION_FAILURE);
372 thisch = modstart[0];
373 nextch = modstart[1];
374 modstart[0] = convch;
404 if (legal_identifier (var))
405 bind_var_to_int (var, tw);
409 PRETURN (EXECUTION_FAILURE);
415 case 'b': /* expand escapes in argument */
422 xp = bexpand (p, strlen (p), &ch, &rlen);
426 /* Have to use printstr because of possible NUL bytes
427 in XP -- printf does not handle that well. */
428 r = printstr (start, xp, rlen, fieldwidth, precision);
433 retval = EXECUTION_FAILURE;
443 case 'q': /* print with shell quoting */
450 if (p && *p == 0) /* XXX - getstr never returns null */
451 xp = savestring ("''");
452 else if (ansic_shouldquote (p))
453 xp = ansic_quote (p, 0, (int *)0);
455 xp = sh_backslash_quote (p);
458 /* Use printstr to get fieldwidth and precision right. */
459 r = printstr (start, xp, strlen (xp), fieldwidth, precision);
469 PRETURN (EXECUTION_FAILURE);
480 p = pp = getintmax ();
483 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
488 /* Optimize the common case where the integer fits
489 in "long". This also works around some long
490 long and/or intmax_t library bugs in the common
491 case, e.g. glibc 2.2 x86. */
492 f = mklong (start, "l", 1);
507 p = pp = getuintmax ();
510 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
515 f = mklong (start, "l", 1);
527 #if defined (HAVE_PRINTF_A_FORMAT)
536 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
541 /* We don't output unrecognized format characters; we print an
542 error message and return a failure exit status. */
544 builtin_error (_("`%c': invalid format character"), convch);
545 PRETURN (EXECUTION_FAILURE);
548 modstart[0] = thisch;
549 modstart[1] = nextch;
556 PRETURN (EXECUTION_FAILURE);
559 while (garglist && garglist != list->next);
561 if (conversion_error)
562 retval = EXECUTION_FAILURE;
571 builtin_error (_("warning: %s: %s"), s, strerror(ERANGE));
574 /* We duplicate a lot of what printf(3) does here. */
576 printstr (fmt, string, len, fieldwidth, precision)
577 char *fmt; /* format */
578 char *string; /* expanded string argument */
579 int len; /* length of expanded string */
580 int fieldwidth; /* argument for width of `*' */
581 int precision; /* argument for precision of `*' */
586 int padlen, nc, ljust, i;
587 int fw, pr; /* fieldwidth and precision */
590 if (string == 0 || *string == '\0')
592 if (string == 0 || len == 0)
606 while (strchr (SKIP1, *fmt))
613 /* get fieldwidth, if present */
624 else if (DIGIT (*fmt))
628 fw = (fw * 10) + (*fmt++ - '0');
631 /* get precision, if present */
640 else if (DIGIT (*fmt))
644 pr = (pr * 10) + (*fmt++ - '0');
649 /* If we remove this, get rid of `s'. */
650 if (*fmt != 'b' && *fmt != 'q')
652 internal_error ("format parsing problem: %s", s);
657 /* chars from string to print */
658 nc = (pr >= 0 && pr <= len) ? pr : len;
666 /* leading pad characters */
667 for (; padlen > 0; padlen--)
670 /* output NC characters from STRING */
671 for (i = 0; i < nc; i++)
674 /* output any necessary trailing padding */
675 for (; padlen < 0; padlen++)
678 return (ferror (stdout) ? -1 : 0);
681 /* Convert STRING by expanding the escape sequences specified by the
682 POSIX standard for printf's `%b' format string. If SAWC is non-null,
683 perform the processing appropriate for %b arguments. In particular,
684 recognize `\c' and use that as a string terminator. If we see \c, set
685 *SAWC to 1 before returning. LEN is the length of STRING. */
687 /* Translate a single backslash-escape sequence starting at ESTART (the
688 character after the backslash) and return the number of characters
689 consumed by the sequence. CP is the place to return the translated
690 value. *SAWC is set to 1 if the escape sequence was \c, since that means
691 to short-circuit the rest of the processing. If SAWC is null, we don't
692 do the \c short-circuiting, and \c is treated as an unrecognized escape
693 sequence; we also bypass the other processing specific to %b arguments. */
695 tescape (estart, cp, sawc)
707 #if defined (__STDC__)
708 case 'a': *cp = '\a'; break;
710 case 'a': *cp = '\007'; break;
713 case 'b': *cp = '\b'; break;
716 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
718 case 'f': *cp = '\f'; break;
720 case 'n': *cp = '\n'; break;
722 case 'r': *cp = '\r'; break;
724 case 't': *cp = '\t'; break;
726 case 'v': *cp = '\v'; break;
728 /* The octal escape sequences are `\0' followed by up to three octal
729 digits (if SAWC), or `\' followed by up to three octal digits (if
730 !SAWC). As an extension, we allow the latter form even if SAWC. */
731 case '0': case '1': case '2': case '3':
732 case '4': case '5': case '6': case '7':
733 evalue = OCTVALUE (c);
734 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
735 evalue = (evalue * 8) + OCTVALUE (*p);
739 /* And, as another extension, we allow \xNNN, where each N is a
743 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
745 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
747 evalue = (evalue * 16) + HEXVALUE (*p);
750 builtin_error (_("missing hex digit for \\x"));
757 case '\\': /* \\ -> \ */
761 /* SAWC == 0 means that \', \", and \? are recognized as escape
762 sequences, though the only processing performed is backslash
764 case '\'': case '"': case '?':
780 /* other backslash escapes are passed through unaltered */
789 bexpand (string, len, sawc, lenp)
791 int len, *sawc, *lenp;
794 char *ret, *r, *s, c;
797 if (string == 0 || *string == '\0')
799 if (string == 0 || len == 0)
806 return ((char *)NULL);
809 ret = (char *)xmalloc (len + 1);
810 for (r = ret, s = string; s && *s; )
813 if (c != '\\' || *s == '\0')
819 s += tescape (s, &c, &temp);
843 nlen = vblen + blen + 1;
846 vbsize = ((nlen + 63) >> 6) << 6;
847 vbuf = (char *)xrealloc (vbuf, vbsize);
851 vbuf[vblen++] = buf[0];
854 FASTCOPY (buf, vbuf + vblen, blen);
860 if (strlen (vbuf) != vblen)
861 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
868 #if defined (PREFER_STDARG)
869 vbprintf (const char *format, ...)
871 vbprintf (format, va_alist)
880 SH_VA_START (args, format);
881 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
884 nlen = vblen + blen + 1;
887 vbsize = ((nlen + 63) >> 6) << 6;
888 vbuf = (char *)xrealloc (vbuf, vbsize);
889 SH_VA_START (args, format);
890 blen = vsnprintf (vbuf + vblen, vbsize - vblen, format, args);
898 if (strlen (vbuf) != vblen)
899 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
906 mklong (str, modifiers, mlen)
914 len = slen + mlen + 1;
916 if (len > conv_bufsize)
918 conv_bufsize = (((len + 1023) >> 10) << 10);
919 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
922 FASTCOPY (str, conv_buf, slen - 1);
923 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
925 conv_buf[len - 2] = str[slen - 1];
926 conv_buf[len - 1] = '\0';
938 ret = (int)garglist->word->word[0];
939 garglist = garglist->next;
951 ret = garglist->word->word;
952 garglist = garglist->next;
965 printf_erange (garglist->word->word);
968 else if (ret < INT_MIN)
970 printf_erange (garglist->word->word);
986 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
990 ret = strtoimax (garglist->word->word, &ep, 0);
994 sh_invalidnum (garglist->word->word);
995 /* POSIX.2 says ``...a diagnostic message shall be written to standard
996 error, and the utility shall not exit with a zero exit status, but
997 shall continue processing any remaining operands and shall write the
998 value accumulated at the time the error was detected to standard
1001 conversion_error = 1;
1003 else if (errno == ERANGE)
1004 printf_erange (garglist->word->word);
1006 garglist = garglist->next;
1019 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1020 return asciicode ();
1023 ret = strtoumax (garglist->word->word, &ep, 0);
1027 sh_invalidnum (garglist->word->word);
1028 /* Same POSIX.2 conversion error requirements as getintmax(). */
1030 conversion_error = 1;
1032 else if (errno == ERANGE)
1033 printf_erange (garglist->word->word);
1035 garglist = garglist->next;
1048 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1049 return asciicode ();
1052 ret = strtofltmax (garglist->word->word, &ep);
1056 sh_invalidnum (garglist->word->word);
1057 /* Same thing about POSIX.2 conversion error requirements. */
1059 conversion_error = 1;
1061 else if (errno == ERANGE)
1062 printf_erange (garglist->word->word);
1064 garglist = garglist->next;
1068 /* NO check is needed for garglist here. */
1072 register intmax_t ch;
1073 #if defined (HANDLE_MULTIBYTE)
1075 size_t mblength, slen;
1079 #if defined (HANDLE_MULTIBYTE)
1080 slen = strlen (garglist->word->word+1);
1081 mblength = MBLEN (garglist->word->word+1, slen);
1084 mblength = mbtowc (&wc, garglist->word->word+1, slen);
1089 ch = (unsigned char)garglist->word->word[1];
1091 garglist = garglist->next;