1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997-2002 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"
61 #include "bashgetopt.h"
64 #if !defined (PRIdMAX)
66 # define PRIdMAX "lld"
78 if (have_fieldwidth && have_precision) \
79 tw += printf(f, fieldwidth, precision, func); \
80 else if (have_fieldwidth) \
81 tw += printf(f, fieldwidth, func); \
82 else if (have_precision) \
83 tw += printf(f, precision, func); \
85 tw += printf(f, func); \
88 /* We free the buffer used by mklong() if it's `too big'. */
89 #define PRETURN(value) \
92 if (conv_bufsize > 4096 ) \
103 #define SKIP1 "#'-+ 0"
104 #define LENMODS "hjlLtz"
106 static void printf_erange __P((char *));
107 static void printstr __P((char *, char *, int, int, int));
108 static int tescape __P((char *, int, char *, int *));
109 static char *bexpand __P((char *, int, int *, int *));
110 static char *mklong __P((char *, char *, size_t));
111 static int getchr __P((void));
112 static char *getstr __P((void));
113 static int getint __P((void));
114 static intmax_t getintmax __P((void));
115 static uintmax_t getuintmax __P((void));
117 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD
118 typedef long double floatmax_t;
119 # define FLOATMAX_CONV "L"
120 # define strtofltmax strtold
122 typedef double floatmax_t;
123 # define FLOATMAX_CONV ""
124 # define strtofltmax strtod
126 static floatmax_t getfloatmax __P((void));
128 static int asciicode __P((void));
130 static WORD_LIST *garglist;
132 static int conversion_error;
134 static char *conv_buf;
135 static size_t conv_bufsize;
138 printf_builtin (list)
141 int ch, fieldwidth, precision;
142 int have_fieldwidth, have_precision;
144 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
146 conversion_error = 0;
147 retval = EXECUTION_SUCCESS;
149 if (no_options (list))
151 list = loptend; /* skip over possible `--' */
159 if (list->word->word == 0 || list->word->word[0] == '\0')
160 return (EXECUTION_SUCCESS);
162 format = list->word->word;
164 garglist = list->next;
166 /* If the format string is empty after preprocessing, return immediately. */
167 if (format == 0 || *format == 0)
168 return (EXECUTION_SUCCESS);
170 /* Basic algorithm is to scan the format string for conversion
171 specifications -- once one is found, find out if the field
172 width or precision is a '*'; if it is, gather up value. Note,
173 format strings are reused as necessary to use up the provided
174 arguments, arguments of zero/null string are provided to use
175 up the format string. */
179 /* find next format specification */
180 for (fmt = format; *fmt; fmt++)
182 precision = fieldwidth = 0;
183 have_fieldwidth = have_precision = 0;
189 /* A NULL fourth argument to tescape means to not do special
190 processing for \c. */
191 fmt += tescape (fmt, 1, &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 recognize `\c' and use that as a string terminator. If we see \c, set
535 *SAWC to 1 before returning. LEN is the length of STRING. */
537 /* Translate a single backslash-escape sequence starting at ESTART (the
538 character after the backslash) and return the number of characters
539 consumed by the sequence. CP is the place to return the translated
540 value. *SAWC is set to 1 if the escape sequence was \c, since that means
541 to short-circuit the rest of the processing. If SAWC is null, we don't
542 do the \c short-circuiting, and \c is treated as an unrecognized escape
545 tescape (estart, trans_squote, 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 /* %b octal constants are `\0' followed by one, two, or three
582 /* but, as an extension, the other echo-like octal escape
583 sequences are supported as well. */
584 case '1': case '2': case '3': case '4':
585 case '5': case '6': case '7':
586 for (temp = 2+(c=='0'), evalue = c - '0'; ISOCTAL (*p) && temp--; p++)
587 evalue = (evalue * 8) + OCTVALUE (*p);
591 /* And, as another extension, we allow \xNNN, where each N is a
594 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
595 evalue = (evalue * 16) + HEXVALUE (*p);
598 builtin_error ("missing hex digit for \\x");
605 case '\\': /* \\ -> \ */
609 case '\'': /* TRANS_SQUOTE != 0 means \' -> ' */
625 /* other backslash escapes are passed through unaltered */
634 bexpand (string, len, sawc, lenp)
636 int len, *sawc, *lenp;
639 char *ret, *r, *s, c;
641 if (string == 0 || *string == '\0')
647 return ((char *)NULL);
650 ret = (char *)xmalloc (len + 1);
651 for (r = ret, s = string; s && *s; )
654 if (c != '\\' || *s == '\0')
660 s += tescape (s, 0, &c, &temp);
678 mklong (str, modifiers, mlen)
686 len = slen + mlen + 1;
688 if (len > conv_bufsize)
690 conv_bufsize = (((len + 1023) >> 10) << 10);
691 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
694 FASTCOPY (str, conv_buf, slen - 1);
695 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
697 conv_buf[len - 2] = str[slen - 1];
698 conv_buf[len - 1] = '\0';
710 ret = (int)garglist->word->word[0];
711 garglist = garglist->next;
723 ret = garglist->word->word;
724 garglist = garglist->next;
737 printf_erange (garglist->word->word);
740 else if (ret < INT_MIN)
742 printf_erange (garglist->word->word);
758 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
762 ret = strtoimax (garglist->word->word, &ep, 0);
766 sh_invalidnum (garglist->word->word);
767 /* POSIX.2 says ``...a diagnostic message shall be written to standard
768 error, and the utility shall not exit with a zero exit status, but
769 shall continue processing any remaining operands and shall write the
770 value accumulated at the time the error was detected to standard
773 conversion_error = 1;
775 else if (errno == ERANGE)
776 printf_erange (garglist->word->word);
778 garglist = garglist->next;
791 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
795 ret = strtoumax (garglist->word->word, &ep, 0);
799 sh_invalidnum (garglist->word->word);
800 /* Same POSIX.2 conversion error requirements as getintmax(). */
802 conversion_error = 1;
804 else if (errno == ERANGE)
805 printf_erange (garglist->word->word);
807 garglist = garglist->next;
820 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
824 ret = strtofltmax (garglist->word->word, &ep);
828 sh_invalidnum (garglist->word->word);
829 /* Same thing about POSIX.2 conversion error requirements. */
831 conversion_error = 1;
833 else if (errno == ERANGE)
834 printf_erange (garglist->word->word);
836 garglist = garglist->next;
840 /* NO check is needed for garglist here. */
846 ch = garglist->word->word[1];
847 garglist = garglist->next;