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'; \
95 if (have_fieldwidth && have_precision) \
96 nw = asprintf(&b, f, fieldwidth, precision, func); \
97 else if (have_fieldwidth) \
98 nw = asprintf(&b, f, fieldwidth, func); \
99 else if (have_precision) \
100 nw = asprintf(&b, f, precision, func); \
102 nw = asprintf(&b, f, func); \
107 (void)vbadd (b, nw); \
109 (void)fputs (b, stdout); \
110 if (ferror (stdout)) \
114 return (EXECUTION_FAILURE); \
120 /* We free the buffer used by mklong() if it's `too big'. */
121 #define PRETURN(value) \
126 bind_variable (vname, vbuf, 0); \
127 stupidly_hack_special_variables (vname); \
129 if (conv_bufsize > 4096 ) \
142 if (ferror (stdout)) \
145 return (EXECUTION_FAILURE); \
151 #define SKIP1 "#'-+ 0"
152 #define LENMODS "hjlLtz"
154 static void printf_erange __P((char *));
155 static int printstr __P((char *, char *, int, int, int));
156 static int tescape __P((char *, char *, int *));
157 static char *bexpand __P((char *, int, int *, int *));
158 static char *vbadd __P((char *, int));
159 static char *mklong __P((char *, char *, size_t));
160 static int getchr __P((void));
161 static char *getstr __P((void));
162 static int getint __P((void));
163 static intmax_t getintmax __P((void));
164 static uintmax_t getuintmax __P((void));
166 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
167 typedef long double floatmax_t;
168 # define FLOATMAX_CONV "L"
169 # define strtofltmax strtold
171 typedef double floatmax_t;
172 # define FLOATMAX_CONV ""
173 # define strtofltmax strtod
175 static floatmax_t getfloatmax __P((void));
177 static int asciicode __P((void));
179 static WORD_LIST *garglist;
181 static int conversion_error;
183 /* printf -v var support */
184 static int vflag = 0;
185 static char *vbuf, *vname;
186 static size_t vbsize;
191 static char *conv_buf;
192 static size_t conv_bufsize;
195 printf_builtin (list)
198 int ch, fieldwidth, precision;
199 int have_fieldwidth, have_precision;
200 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
202 conversion_error = 0;
203 retval = EXECUTION_SUCCESS;
207 reset_internal_getopt ();
208 while ((ch = internal_getopt (list, "v:")) != -1)
213 if (legal_identifier (vname = list_optarg))
220 sh_invalidid (vname);
229 list = loptend; /* skip over possible `--' */
237 if (list->word->word == 0 || list->word->word[0] == '\0')
238 return (EXECUTION_SUCCESS);
240 format = list->word->word;
243 garglist = list->next;
245 /* If the format string is empty after preprocessing, return immediately. */
246 if (format == 0 || *format == 0)
247 return (EXECUTION_SUCCESS);
249 /* Basic algorithm is to scan the format string for conversion
250 specifications -- once one is found, find out if the field
251 width or precision is a '*'; if it is, gather up value. Note,
252 format strings are reused as necessary to use up the provided
253 arguments, arguments of zero/null string are provided to use
254 up the format string. */
258 /* find next format specification */
259 for (fmt = format; *fmt; fmt++)
261 precision = fieldwidth = 0;
262 have_fieldwidth = have_precision = 0;
267 /* A NULL third argument to tescape means to bypass the
268 special processing for arguments to %b. */
269 fmt += tescape (fmt, &nextch, (int *)NULL);
271 fmt--; /* for loop will increment it for us again */
281 /* ASSERT(*fmt == '%') */
284 if (*fmt == '%') /* %% prints a % */
290 /* found format specification, skip to field width */
291 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
294 /* Skip optional field width. */
299 fieldwidth = getint ();
305 /* Skip optional '.' and precision */
313 precision = getint ();
317 /* Negative precisions are allowed but treated as if the
318 precision were missing; I would like to allow a leading
319 `+' in the precision number as an extension, but lots
320 of asprintf/fprintf implementations get this wrong. */
322 if (*fmt == '-' || *fmt == '+')
332 /* skip possible format modifiers */
334 while (*fmt && strchr (LENMODS, *fmt))
339 builtin_error (_("`%s': missing format character"), start);
340 PRETURN (EXECUTION_FAILURE);
344 thisch = modstart[0];
345 nextch = modstart[1];
346 modstart[0] = convch;
376 if (legal_identifier (var))
377 bind_var_to_int (var, tw);
381 PRETURN (EXECUTION_FAILURE);
387 case 'b': /* expand escapes in argument */
394 xp = bexpand (p, strlen (p), &ch, &rlen);
398 /* Have to use printstr because of possible NUL bytes
399 in XP -- printf does not handle that well. */
400 r = printstr (start, xp, rlen, fieldwidth, precision);
405 retval = EXECUTION_FAILURE;
415 case 'q': /* print with shell quoting */
422 if (p && *p == 0) /* XXX - getstr never returns null */
423 xp = savestring ("''");
424 else if (ansic_shouldquote (p))
425 xp = ansic_quote (p, 0, (int *)0);
427 xp = sh_backslash_quote (p);
430 /* Use printstr to get fieldwidth and precision right. */
431 r = printstr (start, xp, strlen (xp), fieldwidth, precision);
441 PRETURN (EXECUTION_FAILURE);
452 p = pp = getintmax ();
455 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
460 /* Optimize the common case where the integer fits
461 in "long". This also works around some long
462 long and/or intmax_t library bugs in the common
463 case, e.g. glibc 2.2 x86. */
464 f = mklong (start, "l", 1);
479 p = pp = getuintmax ();
482 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
487 f = mklong (start, "l", 1);
499 #if defined (HAVE_PRINTF_A_FORMAT)
508 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
513 /* We don't output unrecognized format characters; we print an
514 error message and return a failure exit status. */
516 builtin_error (_("`%c': invalid format character"), convch);
517 PRETURN (EXECUTION_FAILURE);
520 modstart[0] = thisch;
521 modstart[1] = nextch;
528 PRETURN (EXECUTION_FAILURE);
531 while (garglist && garglist != list->next);
533 if (conversion_error)
534 retval = EXECUTION_FAILURE;
543 builtin_error ("warning: %s: %s", s, strerror(ERANGE));
546 /* We duplicate a lot of what printf(3) does here. */
548 printstr (fmt, string, len, fieldwidth, precision)
549 char *fmt; /* format */
550 char *string; /* expanded string argument */
551 int len; /* length of expanded string */
552 int fieldwidth; /* argument for width of `*' */
553 int precision; /* argument for precision of `*' */
558 int padlen, nc, ljust, i;
559 int fw, pr; /* fieldwidth and precision */
562 if (string == 0 || *string == '\0')
564 if (string == 0 || len == 0)
578 while (strchr (SKIP1, *fmt))
585 /* get fieldwidth, if present */
596 else if (DIGIT (*fmt))
600 fw = (fw * 10) + (*fmt++ - '0');
603 /* get precision, if present */
612 else if (DIGIT (*fmt))
616 pr = (pr * 10) + (*fmt++ - '0');
621 /* If we remove this, get rid of `s'. */
622 if (*fmt != 'b' && *fmt != 'q')
624 internal_error ("format parsing problem: %s", s);
629 /* chars from string to print */
630 nc = (pr >= 0 && pr <= len) ? pr : len;
638 /* leading pad characters */
639 for (; padlen > 0; padlen--)
642 /* output NC characters from STRING */
643 for (i = 0; i < nc; i++)
646 /* output any necessary trailing padding */
647 for (; padlen < 0; padlen++)
650 return (ferror (stdout) ? -1 : 0);
653 /* Convert STRING by expanding the escape sequences specified by the
654 POSIX standard for printf's `%b' format string. If SAWC is non-null,
655 perform the processing appropriate for %b arguments. In particular,
656 recognize `\c' and use that as a string terminator. If we see \c, set
657 *SAWC to 1 before returning. LEN is the length of STRING. */
659 /* Translate a single backslash-escape sequence starting at ESTART (the
660 character after the backslash) and return the number of characters
661 consumed by the sequence. CP is the place to return the translated
662 value. *SAWC is set to 1 if the escape sequence was \c, since that means
663 to short-circuit the rest of the processing. If SAWC is null, we don't
664 do the \c short-circuiting, and \c is treated as an unrecognized escape
665 sequence; we also bypass the other processing specific to %b arguments. */
667 tescape (estart, cp, sawc)
679 #if defined (__STDC__)
680 case 'a': *cp = '\a'; break;
682 case 'a': *cp = '\007'; break;
685 case 'b': *cp = '\b'; break;
688 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
690 case 'f': *cp = '\f'; break;
692 case 'n': *cp = '\n'; break;
694 case 'r': *cp = '\r'; break;
696 case 't': *cp = '\t'; break;
698 case 'v': *cp = '\v'; break;
700 /* The octal escape sequences are `\0' followed by up to three octal
701 digits (if SAWC), or `\' followed by up to three octal digits (if
702 !SAWC). As an extension, we allow the latter form even if SAWC. */
703 case '0': case '1': case '2': case '3':
704 case '4': case '5': case '6': case '7':
705 evalue = OCTVALUE (c);
706 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
707 evalue = (evalue * 8) + OCTVALUE (*p);
711 /* And, as another extension, we allow \xNNN, where each N is a
715 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
717 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
719 evalue = (evalue * 16) + HEXVALUE (*p);
722 builtin_error (_("missing hex digit for \\x"));
729 case '\\': /* \\ -> \ */
733 /* SAWC == 0 means that \', \", and \? are recognized as escape
734 sequences, though the only processing performed is backslash
736 case '\'': case '"': case '?':
752 /* other backslash escapes are passed through unaltered */
761 bexpand (string, len, sawc, lenp)
763 int len, *sawc, *lenp;
766 char *ret, *r, *s, c;
769 if (string == 0 || *string == '\0')
771 if (string == 0 || len == 0)
778 return ((char *)NULL);
781 ret = (char *)xmalloc (len + 1);
782 for (r = ret, s = string; s && *s; )
785 if (c != '\\' || *s == '\0')
791 s += tescape (s, &c, &temp);
815 nlen = vblen + blen + 1;
818 vbsize = ((nlen + 63) >> 6) << 6;
819 vbuf = (char *)xrealloc (vbuf, vbsize);
823 vbuf[vblen++] = buf[0];
826 FASTCOPY (buf, vbuf + vblen, blen);
832 if (strlen (vbuf) != vblen)
833 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
840 mklong (str, modifiers, mlen)
848 len = slen + mlen + 1;
850 if (len > conv_bufsize)
852 conv_bufsize = (((len + 1023) >> 10) << 10);
853 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
856 FASTCOPY (str, conv_buf, slen - 1);
857 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
859 conv_buf[len - 2] = str[slen - 1];
860 conv_buf[len - 1] = '\0';
872 ret = (int)garglist->word->word[0];
873 garglist = garglist->next;
885 ret = garglist->word->word;
886 garglist = garglist->next;
899 printf_erange (garglist->word->word);
902 else if (ret < INT_MIN)
904 printf_erange (garglist->word->word);
920 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
924 ret = strtoimax (garglist->word->word, &ep, 0);
928 sh_invalidnum (garglist->word->word);
929 /* POSIX.2 says ``...a diagnostic message shall be written to standard
930 error, and the utility shall not exit with a zero exit status, but
931 shall continue processing any remaining operands and shall write the
932 value accumulated at the time the error was detected to standard
935 conversion_error = 1;
937 else if (errno == ERANGE)
938 printf_erange (garglist->word->word);
940 garglist = garglist->next;
953 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
957 ret = strtoumax (garglist->word->word, &ep, 0);
961 sh_invalidnum (garglist->word->word);
962 /* Same POSIX.2 conversion error requirements as getintmax(). */
964 conversion_error = 1;
966 else if (errno == ERANGE)
967 printf_erange (garglist->word->word);
969 garglist = garglist->next;
982 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
986 ret = strtofltmax (garglist->word->word, &ep);
990 sh_invalidnum (garglist->word->word);
991 /* Same thing about POSIX.2 conversion error requirements. */
993 conversion_error = 1;
995 else if (errno == ERANGE)
996 printf_erange (garglist->word->word);
998 garglist = garglist->next;
1002 /* NO check is needed for garglist here. */
1008 ch = garglist->word->word[1];
1009 garglist = garglist->next;