1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997-2003 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 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.
39 #include "../bashtypes.h"
42 #if defined (HAVE_LIMITS_H)
45 /* Assume 32-bit ints. */
46 # define INT_MAX 2147483647
47 # define INT_MIN (-2147483647-1)
51 #include <chartypes.h>
53 #ifdef HAVE_INTTYPES_H
54 # include <inttypes.h>
57 #include "../bashansi.h"
58 #include "../bashintl.h"
62 #include "bashgetopt.h"
65 #if !defined (PRIdMAX)
67 # define PRIdMAX "lld"
79 if (have_fieldwidth && have_precision) \
80 tw += printf(f, fieldwidth, precision, func); \
81 else if (have_fieldwidth) \
82 tw += printf(f, fieldwidth, func); \
83 else if (have_precision) \
84 tw += printf(f, precision, func); \
86 tw += printf(f, func); \
89 /* We free the buffer used by mklong() if it's `too big'. */
90 #define PRETURN(value) \
93 if (conv_bufsize > 4096 ) \
104 #define SKIP1 "#'-+ 0"
105 #define LENMODS "hjlLtz"
107 static void printf_erange __P((char *));
108 static void printstr __P((char *, char *, int, int, int));
109 static int tescape __P((char *, char *, int *));
110 static char *bexpand __P((char *, int, int *, int *));
111 static char *mklong __P((char *, char *, size_t));
112 static int getchr __P((void));
113 static char *getstr __P((void));
114 static int getint __P((void));
115 static intmax_t getintmax __P((void));
116 static uintmax_t getuintmax __P((void));
118 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
119 typedef long double floatmax_t;
120 # define FLOATMAX_CONV "L"
121 # define strtofltmax strtold
123 typedef double floatmax_t;
124 # define FLOATMAX_CONV ""
125 # define strtofltmax strtod
127 static floatmax_t getfloatmax __P((void));
129 static int asciicode __P((void));
131 static WORD_LIST *garglist;
133 static int conversion_error;
135 static char *conv_buf;
136 static size_t conv_bufsize;
139 printf_builtin (list)
142 int ch, fieldwidth, precision;
143 int have_fieldwidth, have_precision;
145 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
147 conversion_error = 0;
148 retval = EXECUTION_SUCCESS;
150 if (no_options (list))
152 list = loptend; /* skip over possible `--' */
160 if (list->word->word == 0 || list->word->word[0] == '\0')
161 return (EXECUTION_SUCCESS);
163 format = list->word->word;
165 garglist = list->next;
167 /* If the format string is empty after preprocessing, return immediately. */
168 if (format == 0 || *format == 0)
169 return (EXECUTION_SUCCESS);
171 /* Basic algorithm is to scan the format string for conversion
172 specifications -- once one is found, find out if the field
173 width or precision is a '*'; if it is, gather up value. Note,
174 format strings are reused as necessary to use up the provided
175 arguments, arguments of zero/null string are provided to use
176 up the format string. */
180 /* find next format specification */
181 for (fmt = format; *fmt; fmt++)
183 precision = fieldwidth = 0;
184 have_fieldwidth = have_precision = 0;
189 /* A NULL third argument to tescape means to bypass the
190 special processing for arguments to %b. */
191 fmt += tescape (fmt, &nextch, (int *)NULL);
193 fmt--; /* for loop will increment it for us again */
203 /* ASSERT(*fmt == '%') */
206 if (*fmt == '%') /* %% prints a % */
212 /* found format specification, skip to field width */
213 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
216 /* Skip optional field width. */
221 fieldwidth = getint ();
227 /* Skip optional '.' and precision */
235 precision = getint ();
242 /* skip possible format modifiers */
244 while (*fmt && strchr (LENMODS, *fmt))
249 builtin_error (_("`%s': missing format character"), start);
250 PRETURN (EXECUTION_FAILURE);
254 thisch = modstart[0];
255 nextch = modstart[1];
256 modstart[0] = convch;
286 if (legal_identifier (var))
287 bind_var_to_int (var, tw);
291 PRETURN (EXECUTION_FAILURE);
297 case 'b': /* expand escapes in argument */
304 xp = bexpand (p, strlen (p), &ch, &rlen);
308 /* Have to use printstr because of possible NUL bytes
309 in XP -- printf does not handle that well. */
310 printstr (start, xp, rlen, fieldwidth, precision);
319 case 'q': /* print with shell quoting */
324 if (ansic_shouldquote (p))
325 xp = ansic_quote (p, 0, (int *)0);
327 xp = sh_backslash_quote (p);
330 /* Use printstr to get fieldwidth and precision right. */
331 printstr (start, xp, strlen (xp), fieldwidth, precision);
344 p = pp = getintmax ();
347 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
352 /* Optimize the common case where the integer fits
353 in "long". This also works around some long
354 long and/or intmax_t library bugs in the common
355 case, e.g. glibc 2.2 x86. */
356 f = mklong (start, "l", 1);
371 p = pp = getuintmax ();
374 f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
379 f = mklong (start, "l", 1);
391 #if defined (HAVE_PRINTF_A_FORMAT)
400 f = mklong (start, FLOATMAX_CONV, sizeof(FLOATMAX_CONV) - 1);
405 /* We don't output unrecognized format characters; we print an
406 error message and return a failure exit status. */
408 builtin_error (_("`%c': invalid format character"), convch);
409 PRETURN (EXECUTION_FAILURE);
412 modstart[0] = thisch;
413 modstart[1] = nextch;
416 while (garglist && garglist != list->next);
418 if (conversion_error)
419 retval = EXECUTION_FAILURE;
428 builtin_error ("warning: %s: %s", s, strerror(ERANGE));
431 /* We duplicate a lot of what printf(3) does here. */
433 printstr (fmt, string, len, fieldwidth, precision)
434 char *fmt; /* format */
435 char *string; /* expanded string argument */
436 int len; /* length of expanded string */
437 int fieldwidth; /* argument for width of `*' */
438 int precision; /* argument for precision of `*' */
443 int padlen, nc, ljust, i;
444 int fw, pr; /* fieldwidth and precision */
446 if (string == 0 || *string == '\0')
459 while (strchr (SKIP1, *fmt))
466 /* get fieldwidth, if present */
477 else if (DIGIT (*fmt))
481 fw = (fw * 10) + (*fmt++ - '0');
484 /* get precision, if present */
493 else if (DIGIT (*fmt))
497 pr = (pr * 10) + (*fmt++ - '0');
502 /* If we remove this, get rid of `s'. */
503 if (*fmt != 'b' && *fmt != 'q')
505 internal_error ("format parsing problem: %s", s);
510 /* chars from string to print */
511 nc = (pr >= 0 && pr <= len) ? pr : len;
519 /* leading pad characters */
520 for (; padlen > 0; padlen--)
523 /* output NC characters from STRING */
524 for (i = 0; i < nc; i++)
527 /* output any necessary trailing padding */
528 for (; padlen < 0; padlen++)
532 /* Convert STRING by expanding the escape sequences specified by the
533 POSIX standard for printf's `%b' format string. If SAWC is non-null,
534 perform the processing appropriate for %b arguments. In particular,
535 recognize `\c' and use that as a string terminator. If we see \c, set
536 *SAWC to 1 before returning. LEN is the length of STRING. */
538 /* Translate a single backslash-escape sequence starting at ESTART (the
539 character after the backslash) and return the number of characters
540 consumed by the sequence. CP is the place to return the translated
541 value. *SAWC is set to 1 if the escape sequence was \c, since that means
542 to short-circuit the rest of the processing. If SAWC is null, we don't
543 do the \c short-circuiting, and \c is treated as an unrecognized escape
544 sequence; we also bypass the other processing specific to %b arguments. */
546 tescape (estart, cp, sawc)
558 #if defined (__STDC__)
559 case 'a': *cp = '\a'; break;
561 case 'a': *cp = '\007'; break;
564 case 'b': *cp = '\b'; break;
567 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
569 case 'f': *cp = '\f'; break;
571 case 'n': *cp = '\n'; break;
573 case 'r': *cp = '\r'; break;
575 case 't': *cp = '\t'; break;
577 case 'v': *cp = '\v'; break;
579 /* The octal escape sequences are `\0' followed by up to three octal
580 digits (if SAWC), or `\' followed by up to three octal digits (if
581 !SAWC). As an extension, we allow the latter form even if SAWC. */
582 case '0': case '1': case '2': case '3':
583 case '4': case '5': case '6': case '7':
584 evalue = OCTVALUE (c);
585 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
586 evalue = (evalue * 8) + OCTVALUE (*p);
590 /* And, as another extension, we allow \xNNN, where each N is a
594 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
596 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
598 evalue = (evalue * 16) + HEXVALUE (*p);
601 builtin_error (_("missing hex digit for \\x"));
608 case '\\': /* \\ -> \ */
612 /* SAWC == 0 means that \', \", and \? are recognized as escape
613 sequences, though the only processing performed is backslash
615 case '\'': case '"': case '?':
631 /* other backslash escapes are passed through unaltered */
640 bexpand (string, len, sawc, lenp)
642 int len, *sawc, *lenp;
645 char *ret, *r, *s, c;
647 if (string == 0 || *string == '\0')
653 return ((char *)NULL);
656 ret = (char *)xmalloc (len + 1);
657 for (r = ret, s = string; s && *s; )
660 if (c != '\\' || *s == '\0')
666 s += tescape (s, &c, &temp);
684 mklong (str, modifiers, mlen)
692 len = slen + mlen + 1;
694 if (len > conv_bufsize)
696 conv_bufsize = (((len + 1023) >> 10) << 10);
697 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
700 FASTCOPY (str, conv_buf, slen - 1);
701 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
703 conv_buf[len - 2] = str[slen - 1];
704 conv_buf[len - 1] = '\0';
716 ret = (int)garglist->word->word[0];
717 garglist = garglist->next;
729 ret = garglist->word->word;
730 garglist = garglist->next;
743 printf_erange (garglist->word->word);
746 else if (ret < INT_MIN)
748 printf_erange (garglist->word->word);
764 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
768 ret = strtoimax (garglist->word->word, &ep, 0);
772 sh_invalidnum (garglist->word->word);
773 /* POSIX.2 says ``...a diagnostic message shall be written to standard
774 error, and the utility shall not exit with a zero exit status, but
775 shall continue processing any remaining operands and shall write the
776 value accumulated at the time the error was detected to standard
779 conversion_error = 1;
781 else if (errno == ERANGE)
782 printf_erange (garglist->word->word);
784 garglist = garglist->next;
797 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
801 ret = strtoumax (garglist->word->word, &ep, 0);
805 sh_invalidnum (garglist->word->word);
806 /* Same POSIX.2 conversion error requirements as getintmax(). */
808 conversion_error = 1;
810 else if (errno == ERANGE)
811 printf_erange (garglist->word->word);
813 garglist = garglist->next;
826 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
830 ret = strtofltmax (garglist->word->word, &ep);
834 sh_invalidnum (garglist->word->word);
835 /* Same thing about POSIX.2 conversion error requirements. */
837 conversion_error = 1;
839 else if (errno == ERANGE)
840 printf_erange (garglist->word->word);
842 garglist = garglist->next;
846 /* NO check is needed for garglist here. */
852 ch = garglist->word->word[1];
853 garglist = garglist->next;