1 This file is printf.def, from which is created printf.c.
2 It implements the builtin "printf" in Bash.
4 Copyright (C) 1997 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"
59 #define NEED_STRTOIMAX_DECL
63 #include "bashgetopt.h"
66 /* This should use the ISO C constant format strings; I'll do that later. */
67 #if SIZEOF_LONG < SIZEOF_LONG_LONG
68 # define INTMAX_CONV "ll"
70 # define INTMAX_CONV "l"
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 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 *));
111 static int getchr __P((void));
112 static char *getstr __P((void));
113 static int getint __P((void));
114 static long getlong __P((void));
115 static unsigned long getulong __P((void));
116 #if defined (HAVE_LONG_LONG)
117 static long long getllong __P((void));
118 static unsigned long long getullong __P((void));
120 static intmax_t getintmax __P((void));
121 static uintmax_t getuintmax __P((void));
122 static double getdouble __P((void));
123 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD
124 static long double getldouble __P((void));
126 static int asciicode __P((void));
128 static WORD_LIST *garglist;
130 static int conversion_error;
132 static char *conv_buf;
133 static size_t conv_bufsize;
136 printf_builtin (list)
139 int ch, fieldwidth, precision;
140 int have_fieldwidth, have_precision;
142 char convch, thisch, nextch, *format, *modstart, *fmt, *start;
144 conversion_error = 0;
145 retval = EXECUTION_SUCCESS;
146 reset_internal_getopt ();
147 if (internal_getopt (list, "") != -1)
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;
190 /* A NULL fourth argument to tescape means to not do special
191 processing for \c. */
192 fmt += tescape (fmt, 1, &nextch, (int *)NULL);
194 fmt--; /* for loop will increment it for us again */
204 /* ASSERT(*fmt == '%') */
207 if (*fmt == '%') /* %% prints a % */
213 /* found format specification, skip to field width */
214 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
217 /* Skip optional field width. */
222 fieldwidth = getint ();
228 /* Skip optional '.' and precision */
236 precision = getint ();
243 /* skip possible format modifiers */
245 while (*fmt && strchr (LENMODS, *fmt))
250 builtin_error ("`%s': missing format character", start);
251 PRETURN (EXECUTION_FAILURE);
255 thisch = modstart[0];
256 nextch = modstart[1];
257 modstart[0] = convch;
287 if (legal_identifier (var))
288 bind_var_to_int (var, tw);
291 builtin_error ("%s: invalid variable name", var);
292 PRETURN (EXECUTION_FAILURE);
298 case 'b': /* expand escapes in argument */
305 xp = bexpand (p, strlen (p), &ch, &rlen);
309 /* Have to use printstr because of possible NUL bytes
310 in XP -- printf does not handle that well. */
311 printstr (start, xp, rlen, fieldwidth, precision);
320 case 'q': /* print with shell quoting */
325 xp = sh_backslash_quote (p);
328 /* Use printstr to get fieldwidth and precision right. */
329 printstr (start, xp, strlen (xp), fieldwidth, precision);
339 #if defined (HAVE_LONG_LONG)
340 if (thisch == 'l' && nextch == 'l')
345 f = mklong (start, "ll");
355 f = mklong (start, INTMAX_CONV);
363 f = mklong (start, "l");
375 #if defined (HAVE_LONG_LONG)
376 if (thisch == 'l' && nextch == 'l')
378 unsigned long long p;
381 f = mklong (start, "ll");
391 f = mklong (start, INTMAX_CONV);
399 f = mklong (start, "l");
411 #if defined (HAVE_PRINTF_A_FORMAT)
417 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD
423 f = mklong (start, "L");
432 f = mklong (start, "");
438 /* We don't output unrecognized format characters; we print an
439 error message and return a failure exit status. */
441 builtin_error ("`%c': invalid format character", convch);
442 PRETURN (EXECUTION_FAILURE);
445 modstart[0] = thisch;
446 modstart[1] = nextch;
449 while (garglist && garglist != list->next);
451 if (conversion_error)
452 retval = EXECUTION_FAILURE;
457 /* We duplicate a lot of what printf(3) does here. */
459 printstr (fmt, string, len, fieldwidth, precision)
460 char *fmt; /* format */
461 char *string; /* expanded string argument */
462 int len; /* length of expanded string */
463 int fieldwidth; /* argument for width of `*' */
464 int precision; /* argument for precision of `*' */
469 int padlen, nc, ljust, i;
470 int fw, pr; /* fieldwidth and precision */
472 if (string == 0 || *string == '\0')
485 while (strchr (SKIP1, *fmt))
492 /* get fieldwidth, if present */
503 else if (DIGIT (*fmt))
507 fw = (fw * 10) + (*fmt++ - '0');
510 /* get precision, if present */
519 else if (DIGIT (*fmt))
523 pr = (pr * 10) + (*fmt++ - '0');
528 /* If we remove this, get rid of `s'. */
529 if (*fmt != 'b' && *fmt != 'q')
531 internal_error ("format parsing problem: %s", s);
536 /* chars from string to print */
537 nc = (pr >= 0 && pr <= len) ? pr : len;
545 /* leading pad characters */
546 for (; padlen > 0; padlen--)
549 /* output NC characters from STRING */
550 for (i = 0; i < nc; i++)
553 /* output any necessary trailing padding */
554 for (; padlen < 0; padlen++)
558 /* Convert STRING by expanding the escape sequences specified by the
559 POSIX standard for printf's `%b' format string. If SAWC is non-null,
560 recognize `\c' and use that as a string terminator. If we see \c, set
561 *SAWC to 1 before returning. LEN is the length of STRING. */
563 /* Translate a single backslash-escape sequence starting at ESTART (the
564 character after the backslash) and return the number of characters
565 consumed by the sequence. CP is the place to return the translated
566 value. *SAWC is set to 1 if the escape sequence was \c, since that means
567 to short-circuit the rest of the processing. If SAWC is null, we don't
568 do the \c short-circuiting, and \c is treated as an unrecognized escape
571 tescape (estart, trans_squote, cp, sawc)
584 #if defined (__STDC__)
585 case 'a': *cp = '\a'; break;
587 case 'a': *cp = '\007'; break;
590 case 'b': *cp = '\b'; break;
593 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
595 case 'f': *cp = '\f'; break;
597 case 'n': *cp = '\n'; break;
599 case 'r': *cp = '\r'; break;
601 case 't': *cp = '\t'; break;
603 case 'v': *cp = '\v'; break;
605 /* %b octal constants are `\0' followed by one, two, or three
608 for (temp = 3, evalue = 0; ISOCTAL (*p) && temp--; p++)
609 evalue = (evalue * 8) + OCTVALUE (*p);
613 /* but, as an extension, the other echo-like octal escape
614 sequences are supported as well. */
615 case '1': case '2': case '3': case '4':
616 case '5': case '6': case '7':
617 for (temp = 2, evalue = c - '0'; ISOCTAL (*p) && temp--; p++)
618 evalue = (evalue * 8) + OCTVALUE (*p);
622 /* And, as another extension, we allow \xNNN, where each N is a
625 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
626 evalue = (evalue * 16) + HEXVALUE (*p);
629 builtin_error ("missing hex digit for \\x");
636 case '\\': /* \\ -> \ */
640 case '\'': /* TRANS_SQUOTE != 0 means \' -> ' */
656 /* other backslash escapes are passed through unaltered */
665 bexpand (string, len, sawc, lenp)
667 int len, *sawc, *lenp;
670 char *ret, *r, *s, c;
672 if (string == 0 || *string == '\0')
678 return ((char *)NULL);
681 ret = (char *)xmalloc (len + 1);
682 for (r = ret, s = string; s && *s; )
685 if (c != '\\' || *s == '\0')
691 s += tescape (s, 0, &c, &temp);
709 mklong (str, modifiers)
713 size_t len, slen, mlen;
716 mlen = strlen (modifiers);
717 len = slen + mlen + 1;
719 if (len > conv_bufsize)
721 conv_bufsize = (((len + 1023) >> 10) << 10);
722 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
725 FASTCOPY (str, conv_buf, slen - 1);
726 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
728 conv_buf[len - 2] = str[slen - 1];
729 conv_buf[len - 1] = '\0';
741 ret = (int)garglist->word->word[0];
742 garglist = garglist->next;
754 ret = garglist->word->word;
755 garglist = garglist->next;
768 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
771 else if (ret < INT_MIN)
773 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
789 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
793 ret = strtol (garglist->word->word, &ep, 0);
797 builtin_error ("%s: invalid number", garglist->word->word);
798 /* POSIX.2 says ``...a diagnostic message shall be written to standard
799 error, and the utility shall not exit with a zero exit status, but
800 shall continue processing any remaining operands and shall write the
801 value accumulated at the time the error was detected to standard
804 conversion_error = 1;
806 else if (errno == ERANGE)
807 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
809 garglist = garglist->next;
822 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
826 ret = strtoul (garglist->word->word, &ep, 0);
830 builtin_error ("%s: invalid number", garglist->word->word);
831 /* Same thing about POSIX.2 conversion error requirements as getlong(). */
833 conversion_error = 1;
835 else if (errno == ERANGE)
836 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
838 garglist = garglist->next;
842 #if defined (HAVE_LONG_LONG)
853 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
857 ret = strtoll (garglist->word->word, &ep, 0);
861 builtin_error ("%s: invalid number", garglist->word->word);
862 /* POSIX.2 says ``...a diagnostic message shall be written to standard
863 error, and the utility shall not exit with a zero exit status, but
864 shall continue processing any remaining operands and shall write the
865 value accumulated at the time the error was detected to standard
868 conversion_error = 1;
870 else if (errno == ERANGE)
871 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
873 garglist = garglist->next;
877 static unsigned long long
880 unsigned long long ret;
886 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
890 ret = strtoull (garglist->word->word, &ep, 0);
894 builtin_error ("%s: invalid number", garglist->word->word);
895 /* Same thing about POSIX.2 conversion error requirements as getlong(). */
897 conversion_error = 1;
899 else if (errno == ERANGE)
900 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
902 garglist = garglist->next;
906 #endif /* HAVE_LONG_LONG */
917 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
921 ret = strtoimax (garglist->word->word, &ep, 0);
925 builtin_error ("%s: invalid number", garglist->word->word);
926 /* POSIX.2 says ``...a diagnostic message shall be written to standard
927 error, and the utility shall not exit with a zero exit status, but
928 shall continue processing any remaining operands and shall write the
929 value accumulated at the time the error was detected to standard
932 conversion_error = 1;
934 else if (errno == ERANGE)
935 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
937 garglist = garglist->next;
950 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
954 ret = strtoumax (garglist->word->word, &ep, 0);
958 builtin_error ("%s: invalid number", garglist->word->word);
959 /* Same thing about POSIX.2 conversion error requirements as getlong(). */
961 conversion_error = 1;
963 else if (errno == ERANGE)
964 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
966 garglist = garglist->next;
979 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
983 ret = strtod (garglist->word->word, &ep);
987 builtin_error ("%s: invalid number", garglist->word->word);
988 /* Same thing about POSIX.2 conversion error requirements. */
990 conversion_error = 1;
992 else if (errno == ERANGE)
993 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
995 garglist = garglist->next;
999 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD
1009 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1010 return (asciicode ());
1013 ret = strtold (garglist->word->word, &ep);
1017 builtin_error ("%s: invalid number", garglist->word->word);
1018 /* Same thing about POSIX.2 conversion error requirements. */
1020 conversion_error = 1;
1022 else if (errno == ERANGE)
1023 builtin_error ("warning: %s: %s", garglist->word->word, strerror(ERANGE));
1025 garglist = garglist->next;
1028 #endif /* HAVE_LONG_DOUBLE && HAVE_DECL_STRTOLD */
1030 /* NO check is needed for garglist here. */
1036 ch = garglist->word->word[1];
1037 garglist = garglist->next;