1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997-2005 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 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
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
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
25 $FUNCTION printf_builtin
26 $SHORT_DOC printf [-v var] 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 If the -v option is supplied, the output is placed into the value of the
36 shell variable VAR rather than being sent to the standard output.
41 #include "../bashtypes.h"
44 #if defined (HAVE_LIMITS_H)
47 /* Assume 32-bit ints. */
48 # define INT_MAX 2147483647
49 # define INT_MIN (-2147483647-1)
53 #include <chartypes.h>
55 #ifdef HAVE_INTTYPES_H
56 # include <inttypes.h>
59 #include "../bashansi.h"
60 #include "../bashintl.h"
64 #include "bashgetopt.h"
67 #if !defined (PRIdMAX)
69 # define PRIdMAX "lld"
83 b[0] = c; b[1] = '\0'; \
94 if (have_fieldwidth && have_precision) \
95 nw = asprintf(&b, f, fieldwidth, precision, func); \
96 else if (have_fieldwidth) \
97 nw = asprintf(&b, f, fieldwidth, func); \
98 else if (have_precision) \
99 nw = asprintf(&b, f, precision, func); \
101 nw = asprintf(&b, f, func); \
106 (void)vbadd (b, nw); \
108 (void)fputs (b, stdout); \
113 /* We free the buffer used by mklong() if it's `too big'. */
114 #define PRETURN(value) \
119 bind_variable (vname, vbuf, 0); \
120 stupidly_hack_special_variables (vname); \
122 if (conv_bufsize > 4096 ) \
139 #define SKIP1 "#'-+ 0"
140 #define LENMODS "hjlLtz"
142 static void printf_erange __P((char *));
143 static int printstr __P((char *, char *, int, int, int));
144 static int tescape __P((char *, char *, int *));
145 static char *bexpand __P((char *, int, int *, int *));
146 static char *vbadd __P((char *, int));
147 static char *mklong __P((char *, char *, size_t));
148 static int getchr __P((void));
149 static char *getstr __P((void));
150 static int getint __P((void));
151 static intmax_t getintmax __P((void));
152 static uintmax_t getuintmax __P((void));
154 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
155 typedef long double floatmax_t;
156 # define FLOATMAX_CONV "L"
157 # define strtofltmax strtold
159 typedef double floatmax_t;
160 # define FLOATMAX_CONV ""
161 # define strtofltmax strtod
163 static floatmax_t getfloatmax __P((void));
165 static int asciicode __P((void));
167 static WORD_LIST *garglist;
169 static int conversion_error;
171 /* printf -v var support */
172 static int vflag = 0;
173 static char *vbuf, *vname;
174 static size_t vbsize;
179 static char *conv_buf;
180 static size_t conv_bufsize;
183 printf_builtin (list)
186 int ch, fieldwidth, precision;
187 int have_fieldwidth, have_precision;
188 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
190 conversion_error = 0;
191 retval = EXECUTION_SUCCESS;
195 reset_internal_getopt ();
196 while ((ch = internal_getopt (list, "v:")) != -1)
201 if (legal_identifier (vname = list_optarg))
208 sh_invalidid (vname);
217 list = loptend; /* skip over possible `--' */
225 if (list->word->word == 0 || list->word->word[0] == '\0')
226 return (EXECUTION_SUCCESS);
228 format = list->word->word;
231 garglist = list->next;
233 /* If the format string is empty after preprocessing, return immediately. */
234 if (format == 0 || *format == 0)
235 return (EXECUTION_SUCCESS);
237 /* Basic algorithm is to scan the format string for conversion
238 specifications -- once one is found, find out if the field
239 width or precision is a '*'; if it is, gather up value. Note,
240 format strings are reused as necessary to use up the provided
241 arguments, arguments of zero/null string are provided to use
242 up the format string. */
246 /* find next format specification */
247 for (fmt = format; *fmt; fmt++)
249 precision = fieldwidth = 0;
250 have_fieldwidth = have_precision = 0;
255 /* A NULL third argument to tescape means to bypass the
256 special processing for arguments to %b. */
257 fmt += tescape (fmt, &nextch, (int *)NULL);
259 fmt--; /* for loop will increment it for us again */
269 /* ASSERT(*fmt == '%') */
272 if (*fmt == '%') /* %% prints a % */
278 /* found format specification, skip to field width */
279 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
282 /* Skip optional field width. */
287 fieldwidth = getint ();
293 /* Skip optional '.' and precision */
301 precision = getint ();
305 /* Negative precisions are allowed but treated as if the
306 precision were missing; I would like to allow a leading
307 `+' in the precision number as an extension, but lots
308 of asprintf/fprintf implementations get this wrong. */
310 if (*fmt == '-' || *fmt == '+')
320 /* skip possible format modifiers */
322 while (*fmt && strchr (LENMODS, *fmt))
327 builtin_error (_("`%s': missing format character"), start);
328 PRETURN (EXECUTION_FAILURE);
332 thisch = modstart[0];
333 nextch = modstart[1];
334 modstart[0] = convch;
364 if (legal_identifier (var))
365 bind_var_to_int (var, tw);
369 PRETURN (EXECUTION_FAILURE);
375 case 'b': /* expand escapes in argument */
382 xp = bexpand (p, strlen (p), &ch, &rlen);
386 /* Have to use printstr because of possible NUL bytes
387 in XP -- printf does not handle that well. */
388 r = printstr (start, xp, rlen, fieldwidth, precision);
393 retval = EXECUTION_FAILURE;
403 case 'q': /* print with shell quoting */
410 if (ansic_shouldquote (p))
411 xp = ansic_quote (p, 0, (int *)0);
413 xp = sh_backslash_quote (p);
416 /* Use printstr to get fieldwidth and precision right. */
417 r = printstr (start, xp, strlen (xp), fieldwidth, precision);
427 PRETURN (EXECUTION_FAILURE);
438 p = pp = getintmax ();
441 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
446 /* Optimize the common case where the integer fits
447 in "long". This also works around some long
448 long and/or intmax_t library bugs in the common
449 case, e.g. glibc 2.2 x86. */
450 f = mklong (start, "l", 1);
465 p = pp = getuintmax ();
468 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
473 f = mklong (start, "l", 1);
485 #if defined (HAVE_PRINTF_A_FORMAT)
494 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
499 /* We don't output unrecognized format characters; we print an
500 error message and return a failure exit status. */
502 builtin_error (_("`%c': invalid format character"), convch);
503 PRETURN (EXECUTION_FAILURE);
506 modstart[0] = thisch;
507 modstart[1] = nextch;
514 PRETURN (EXECUTION_FAILURE);
517 while (garglist && garglist != list->next);
519 if (conversion_error)
520 retval = EXECUTION_FAILURE;
529 builtin_error ("warning: %s: %s", s, strerror(ERANGE));
532 /* We duplicate a lot of what printf(3) does here. */
534 printstr (fmt, string, len, fieldwidth, precision)
535 char *fmt; /* format */
536 char *string; /* expanded string argument */
537 int len; /* length of expanded string */
538 int fieldwidth; /* argument for width of `*' */
539 int precision; /* argument for precision of `*' */
544 int padlen, nc, ljust, i;
545 int fw, pr; /* fieldwidth and precision */
548 if (string == 0 || *string == '\0')
550 if (string == 0 || len == 0)
564 while (strchr (SKIP1, *fmt))
571 /* get fieldwidth, if present */
582 else if (DIGIT (*fmt))
586 fw = (fw * 10) + (*fmt++ - '0');
589 /* get precision, if present */
598 else if (DIGIT (*fmt))
602 pr = (pr * 10) + (*fmt++ - '0');
607 /* If we remove this, get rid of `s'. */
608 if (*fmt != 'b' && *fmt != 'q')
610 internal_error ("format parsing problem: %s", s);
615 /* chars from string to print */
616 nc = (pr >= 0 && pr <= len) ? pr : len;
624 /* leading pad characters */
625 for (; padlen > 0; padlen--)
628 /* output NC characters from STRING */
629 for (i = 0; i < nc; i++)
632 /* output any necessary trailing padding */
633 for (; padlen < 0; padlen++)
636 return (ferror (stdout) ? -1 : 0);
639 /* Convert STRING by expanding the escape sequences specified by the
640 POSIX standard for printf's `%b' format string. If SAWC is non-null,
641 perform the processing appropriate for %b arguments. In particular,
642 recognize `\c' and use that as a string terminator. If we see \c, set
643 *SAWC to 1 before returning. LEN is the length of STRING. */
645 /* Translate a single backslash-escape sequence starting at ESTART (the
646 character after the backslash) and return the number of characters
647 consumed by the sequence. CP is the place to return the translated
648 value. *SAWC is set to 1 if the escape sequence was \c, since that means
649 to short-circuit the rest of the processing. If SAWC is null, we don't
650 do the \c short-circuiting, and \c is treated as an unrecognized escape
651 sequence; we also bypass the other processing specific to %b arguments. */
653 tescape (estart, cp, sawc)
665 #if defined (__STDC__)
666 case 'a': *cp = '\a'; break;
668 case 'a': *cp = '\007'; break;
671 case 'b': *cp = '\b'; break;
674 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
676 case 'f': *cp = '\f'; break;
678 case 'n': *cp = '\n'; break;
680 case 'r': *cp = '\r'; break;
682 case 't': *cp = '\t'; break;
684 case 'v': *cp = '\v'; break;
686 /* The octal escape sequences are `\0' followed by up to three octal
687 digits (if SAWC), or `\' followed by up to three octal digits (if
688 !SAWC). As an extension, we allow the latter form even if SAWC. */
689 case '0': case '1': case '2': case '3':
690 case '4': case '5': case '6': case '7':
691 evalue = OCTVALUE (c);
692 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
693 evalue = (evalue * 8) + OCTVALUE (*p);
697 /* And, as another extension, we allow \xNNN, where each N is a
701 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
703 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
705 evalue = (evalue * 16) + HEXVALUE (*p);
708 builtin_error (_("missing hex digit for \\x"));
715 case '\\': /* \\ -> \ */
719 /* SAWC == 0 means that \', \", and \? are recognized as escape
720 sequences, though the only processing performed is backslash
722 case '\'': case '"': case '?':
738 /* other backslash escapes are passed through unaltered */
747 bexpand (string, len, sawc, lenp)
749 int len, *sawc, *lenp;
752 char *ret, *r, *s, c;
755 if (string == 0 || *string == '\0')
757 if (string == 0 || len == 0)
764 return ((char *)NULL);
767 ret = (char *)xmalloc (len + 1);
768 for (r = ret, s = string; s && *s; )
771 if (c != '\\' || *s == '\0')
777 s += tescape (s, &c, &temp);
801 nlen = vblen + blen + 1;
804 vbsize = ((nlen + 63) >> 6) << 6;
805 vbuf = (char *)xrealloc (vbuf, vbsize);
809 vbuf[vblen++] = buf[0];
812 FASTCOPY (buf, vbuf + vblen, blen);
818 if (strlen (vbuf) != vblen)
819 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, strlen (vbuf));
826 mklong (str, modifiers, mlen)
834 len = slen + mlen + 1;
836 if (len > conv_bufsize)
838 conv_bufsize = (((len + 1023) >> 10) << 10);
839 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
842 FASTCOPY (str, conv_buf, slen - 1);
843 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
845 conv_buf[len - 2] = str[slen - 1];
846 conv_buf[len - 1] = '\0';
858 ret = (int)garglist->word->word[0];
859 garglist = garglist->next;
871 ret = garglist->word->word;
872 garglist = garglist->next;
885 printf_erange (garglist->word->word);
888 else if (ret < INT_MIN)
890 printf_erange (garglist->word->word);
906 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
910 ret = strtoimax (garglist->word->word, &ep, 0);
914 sh_invalidnum (garglist->word->word);
915 /* POSIX.2 says ``...a diagnostic message shall be written to standard
916 error, and the utility shall not exit with a zero exit status, but
917 shall continue processing any remaining operands and shall write the
918 value accumulated at the time the error was detected to standard
921 conversion_error = 1;
923 else if (errno == ERANGE)
924 printf_erange (garglist->word->word);
926 garglist = garglist->next;
939 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
943 ret = strtoumax (garglist->word->word, &ep, 0);
947 sh_invalidnum (garglist->word->word);
948 /* Same POSIX.2 conversion error requirements as getintmax(). */
950 conversion_error = 1;
952 else if (errno == ERANGE)
953 printf_erange (garglist->word->word);
955 garglist = garglist->next;
968 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
972 ret = strtofltmax (garglist->word->word, &ep);
976 sh_invalidnum (garglist->word->word);
977 /* Same thing about POSIX.2 conversion error requirements. */
979 conversion_error = 1;
981 else if (errno == ERANGE)
982 printf_erange (garglist->word->word);
984 garglist = garglist->next;
988 /* NO check is needed for garglist here. */
994 ch = garglist->word->word[1];
995 garglist = garglist->next;