1 This file is printf.def
, from which is created printf.c.
2 It implements the builtin
"printf" in Bash.
4 Copyright (C
) 1997-2007 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)
52 #if
defined (PREFER_STDARG
)
59 #include
<chartypes.h
>
61 #ifdef HAVE_INTTYPES_H
62 # include
<inttypes.h
>
65 #include
"../bashansi.h"
66 #include
"../bashintl.h"
70 #include
"bashgetopt.h"
73 #if
defined (PRI_MACROS_BROKEN
)
77 #if
!defined (PRIdMAX
)
79 # define PRIdMAX
"lld"
93 b
[0] = c
; b
[1] = '\0'; \
100 #define
PF(f
, func
) \
105 if (have_fieldwidth
&& have_precision
) \
106 nw
= asprintf(&b
, f
, fieldwidth
, precision
, func
); \
107 else
if (have_fieldwidth
) \
108 nw
= asprintf(&b
, f
, fieldwidth
, func
); \
109 else
if (have_precision
) \
110 nw
= asprintf(&b
, f
, precision
, func
); \
112 nw
= asprintf(&b
, f
, func
); \
117 (void
)vbadd (b
, nw
); \
119 (void
)fputs (b
, stdout
); \
120 if (ferror (stdout
)) \
124 return (EXECUTION_FAILURE
); \
130 /* We free the buffer used by
mklong() if it
's `too big'.
*/
131 #define
PRETURN(value
) \
136 bind_variable (vname
, vbuf
, 0); \
137 stupidly_hack_special_variables (vname
); \
139 if (conv_bufsize
> 4096 ) \
152 if (ferror (stdout
)) \
155 return (EXECUTION_FAILURE
); \
161 #define SKIP1
"#'-+ 0"
162 #define LENMODS
"hjlLtz"
164 #ifndef HAVE_ASPRINTF
165 extern int asprintf
__P((char
**, const char
*, ...
)) __attribute__((__format__ (printf
, 2, 3)));
168 static void printf_erange
__P((char *)
);
169 static int printstr
__P((char
*, char
*, int
, int
, int
));
170 static int tescape
__P((char
*, char
*, int *)
);
171 static char
*bexpand
__P((char
*, int
, int
*, int *)
);
172 static char
*vbadd
__P((char
*, int
));
173 static char
*mklong
__P((char
*, char
*, size_t
));
174 static int getchr
__P((void
));
175 static char
*getstr
__P((void
));
176 static int getint
__P((void
));
177 static intmax_t getintmax
__P((void
));
178 static uintmax_t getuintmax
__P((void
));
180 #if
defined (HAVE_LONG_DOUBLE
) && HAVE_DECL_STRTOLD
&& !defined(STRTOLD_BROKEN
)
181 typedef long double floatmax_t
;
182 # define FLOATMAX_CONV
"L"
183 # define strtofltmax strtold
185 typedef double floatmax_t
;
186 # define FLOATMAX_CONV
""
187 # define strtofltmax strtod
189 static floatmax_t getfloatmax
__P((void
));
191 static int asciicode
__P((void
));
193 static WORD_LIST
*garglist
;
195 static int conversion_error
;
197 /* printf
-v var support
*/
198 static int vflag
= 0;
199 static char
*vbuf
, *vname
;
200 static size_t vbsize
;
205 static char
*conv_buf
;
206 static size_t conv_bufsize
;
209 printf_builtin (list
)
212 int ch
, fieldwidth
, precision
;
213 int have_fieldwidth
, have_precision
;
214 char convch
, thisch
, nextch
, *format
, *modstart
, *fmt
, *start
;
216 conversion_error
= 0;
217 retval
= EXECUTION_SUCCESS
;
221 reset_internal_getopt ();
222 while ((ch
= internal_getopt (list
, "v:")) != -1)
227 if (legal_identifier (vname
= list_optarg
))
234 sh_invalidid (vname
);
243 list
= loptend
; /* skip over possible `
--' */
251 if (list->word->word == 0 || list->word->word[0] == '\
0')
252 return (EXECUTION_SUCCESS);
254 format = list->word->word;
257 garglist = list->next;
259 /* If the format string is empty after preprocessing, return immediately. */
260 if (format == 0 || *format == 0)
261 return (EXECUTION_SUCCESS);
263 /* Basic algorithm is to scan the format string for conversion
264 specifications -- once one is found, find out if the field
265 width or precision is a '*'; if it is, gather up value. Note,
266 format strings are reused as necessary to use up the provided
267 arguments, arguments of zero/null string are provided to use
268 up the format string. */
272 /* find next format specification */
273 for (fmt = format; *fmt; fmt++)
275 precision = fieldwidth = 0;
276 have_fieldwidth = have_precision = 0;
281 /* A NULL third argument to tescape means to bypass the
282 special processing for arguments to %b. */
283 fmt += tescape (fmt, &nextch, (int *)NULL);
285 fmt--; /* for loop will increment it for us again */
295 /* ASSERT(*fmt == '%') */
298 if (*fmt == '%') /* %% prints a % */
304 /* found format specification, skip to field width */
305 for (; *fmt && strchr(SKIP1, *fmt); ++fmt)
308 /* Skip optional field width. */
313 fieldwidth = getint ();
319 /* Skip optional '.
' and precision */
327 precision = getint ();
331 /* Negative precisions are allowed but treated as if the
332 precision were missing; I would like to allow a leading
333 `+' in the precision number as an extension
, but lots
334 of asprintf
/fprintf implementations get this wrong.
*/
336 if (*fmt == '-' || *fmt == '+')
346 /* skip possible format modifiers */
348 while (*fmt && strchr (LENMODS, *fmt))
353 builtin_error (_("`%s': missing format character"), start);
354 PRETURN (EXECUTION_FAILURE);
358 thisch = modstart[0];
359 nextch = modstart[1];
360 modstart[0] = convch;
390 if (legal_identifier (var))
391 bind_var_to_int (var, tw);
395 PRETURN (EXECUTION_FAILURE);
401 case 'b': /* expand escapes in argument */
408 xp = bexpand (p, strlen (p), &ch, &rlen);
412 /* Have to use printstr because of possible NUL bytes
413 in XP -- printf does not handle that well. */
414 r = printstr (start, xp, rlen, fieldwidth, precision);
419 retval = EXECUTION_FAILURE;
429 case 'q': /* print with shell quoting */
436 if (p && *p == 0) /* XXX - getstr never returns null */
437 xp = savestring ("''");
438 else if (ansic_shouldquote (p))
439 xp = ansic_quote (p, 0, (int *)0);
441 xp
= sh_backslash_quote (p
);
444 /* Use printstr to get fieldwidth and precision right.
*/
445 r
= printstr (start
, xp
, strlen (xp
), fieldwidth
, precision
);
455 PRETURN (EXECUTION_FAILURE
);
466 p
= pp
= getintmax ();
469 f
= mklong (start
, PRIdMAX
, sizeof (PRIdMAX
) - 2);
474 /* Optimize the common case where the integer fits
475 in
"long". This also works around some long
476 long and
/or intmax_t library bugs in the common
477 case
, e.g. glibc
2.2 x86.
*/
478 f
= mklong (start
, "l", 1);
493 p
= pp
= getuintmax ();
496 f
= mklong (start
, PRIdMAX
, sizeof (PRIdMAX
) - 2);
501 f
= mklong (start
, "l", 1);
513 #if
defined (HAVE_PRINTF_A_FORMAT
)
522 f
= mklong (start
, FLOATMAX_CONV
, sizeof(FLOATMAX_CONV
) - 1);
527 /* We don
't output unrecognized format characters; we print an
528 error message and return a failure exit status. */
530 builtin_error (_("`%c': invalid format character
"), convch);
531 PRETURN (EXECUTION_FAILURE);
534 modstart[0] = thisch;
535 modstart[1] = nextch;
542 PRETURN (EXECUTION_FAILURE);
545 while (garglist && garglist != list->next);
547 if (conversion_error)
548 retval = EXECUTION_FAILURE;
557 builtin_error ("warning
: %s
: %s
", s, strerror(ERANGE));
560 /* We duplicate a lot of what printf(3) does here. */
562 printstr (fmt, string, len, fieldwidth, precision)
563 char *fmt; /* format */
564 char *string; /* expanded string argument */
565 int len; /* length of expanded string */
566 int fieldwidth; /* argument for width of `*' */
567 int precision; /* argument for precision of `*' */
572 int padlen, nc, ljust, i;
573 int fw, pr; /* fieldwidth and precision */
576 if (string == 0 || *string == '\0')
578 if (string == 0 || len == 0)
592 while (strchr (SKIP1, *fmt))
599 /* get fieldwidth, if present */
610 else if (DIGIT (*fmt))
614 fw = (fw * 10) + (*fmt++ - '0');
617 /* get precision, if present */
626 else if (DIGIT (*fmt))
630 pr = (pr * 10) + (*fmt++ - '0');
635 /* If we remove this, get rid of `s'. */
636 if (*fmt != 'b' && *fmt != 'q')
638 internal_error ("format parsing problem
: %s
", s);
643 /* chars from string to print */
644 nc = (pr >= 0 && pr <= len) ? pr : len;
652 /* leading pad characters */
653 for (; padlen > 0; padlen--)
656 /* output NC characters from STRING */
657 for (i = 0; i < nc; i++)
660 /* output any necessary trailing padding */
661 for (; padlen < 0; padlen++)
664 return (ferror (stdout) ? -1 : 0);
667 /* Convert STRING by expanding the escape sequences specified by the
668 POSIX standard for printf's `%b' format string. If SAWC is non-null,
669 perform the processing appropriate for %b arguments. In particular,
670 recognize `\c' and use that as a string terminator. If we see \c, set
671 *SAWC to 1 before returning. LEN is the length of STRING. */
673 /* Translate a single backslash-escape sequence starting at ESTART (the
674 character after the backslash) and return the number of characters
675 consumed by the sequence. CP is the place to return the translated
676 value. *SAWC is set to 1 if the escape sequence was \c, since that means
677 to short-circuit the rest of the processing. If SAWC is null, we don't
678 do the \c short-circuiting, and \c is treated as an unrecognized escape
679 sequence; we also bypass the other processing specific to %b arguments. */
681 tescape (estart, cp, sawc)
693 #if defined (__STDC__)
694 case 'a': *cp = '\a'; break;
696 case 'a': *cp = '\007'; break;
699 case 'b': *cp = '\b'; break;
702 case 'E': *cp = '\033'; break; /* ESC -- non-ANSI */
704 case 'f': *cp = '\f'; break;
706 case 'n': *cp = '\n'; break;
708 case 'r': *cp = '\r'; break;
710 case 't': *cp = '\t'; break;
712 case 'v': *cp = '\v'; break;
714 /* The octal escape sequences are `\0' followed by up to three octal
715 digits (if SAWC), or `\' followed by up to three octal digits (if
716 !SAWC). As an extension, we allow the latter form even if SAWC. */
717 case '0': case '1': case '2': case '3':
718 case '4': case '5': case '6': case '7':
719 evalue = OCTVALUE (c);
720 for (temp = 2 + (!evalue && !!sawc); ISOCTAL (*p) && temp--; p++)
721 evalue = (evalue * 8) + OCTVALUE (*p);
725 /* And, as another extension, we allow \xNNN, where each N is a
729 for (evalue = 0; ISXDIGIT ((unsigned char)*p); p++)
731 for (temp = 2, evalue = 0; ISXDIGIT ((unsigned char)*p) && temp--; p++)
733 evalue = (evalue * 16) + HEXVALUE (*p);
736 builtin_error (_("missing hex digit for
\\x
"));
743 case '\\': /* \\ -> \ */
747 /* SAWC == 0 means that \', \", and \? are recognized as escape
748 sequences, though the only processing performed is backslash
750 case '\'': case '"': case '?
':
766 /* other backslash escapes are passed through unaltered */
775 bexpand (string, len, sawc, lenp)
777 int len, *sawc, *lenp;
780 char *ret, *r, *s, c;
783 if (string == 0 || *string == '\
0')
785 if (string == 0 || len == 0)
792 return ((char *)NULL);
795 ret = (char *)xmalloc (len + 1);
796 for (r = ret, s = string; s && *s; )
799 if (c != '\\' || *s == '\
0')
805 s += tescape (s, &c, &temp);
829 nlen = vblen + blen + 1;
832 vbsize = ((nlen + 63) >> 6) << 6;
833 vbuf = (char *)xrealloc (vbuf, vbsize);
837 vbuf[vblen++] = buf[0];
840 FASTCOPY (buf, vbuf + vblen, blen);
846 if (strlen (vbuf) != vblen)
847 internal_error ("printf:vbadd: vblen (%d) != strlen (vbuf) (%d)", vblen, (int)strlen (vbuf));
854 mklong (str, modifiers, mlen)
862 len = slen + mlen + 1;
864 if (len > conv_bufsize)
866 conv_bufsize = (((len + 1023) >> 10) << 10);
867 conv_buf = (char *)xrealloc (conv_buf, conv_bufsize);
870 FASTCOPY (str, conv_buf, slen - 1);
871 FASTCOPY (modifiers, conv_buf + slen - 1, mlen);
873 conv_buf[len - 2] = str[slen - 1];
874 conv_buf[len - 1] = '\
0';
886 ret = (int)garglist->word->word[0];
887 garglist = garglist->next;
899 ret = garglist->word->word;
900 garglist = garglist->next;
913 printf_erange (garglist->word->word);
916 else if (ret < INT_MIN)
918 printf_erange (garglist->word->word);
934 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
938 ret = strtoimax (garglist->word->word, &ep, 0);
942 sh_invalidnum (garglist->word->word);
943 /* POSIX.2 says ``...a diagnostic message shall be written to standard
944 error, and the utility shall not exit with a zero exit status, but
945 shall continue processing any remaining operands and shall write the
946 value accumulated at the time the error was detected to standard
949 conversion_error = 1;
951 else if (errno == ERANGE)
952 printf_erange (garglist->word->word);
954 garglist = garglist->next;
967 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
971 ret = strtoumax (garglist->word->word, &ep, 0);
975 sh_invalidnum (garglist->word->word);
976 /* Same POSIX.2 conversion error requirements as getintmax(). */
978 conversion_error = 1;
980 else if (errno == ERANGE)
981 printf_erange (garglist->word->word);
983 garglist = garglist->next;
996 if (garglist->word->word[0] == '\'' || garglist->word->word[0] == '"')
1000 ret = strtofltmax (garglist->word->word, &ep);
1004 sh_invalidnum (garglist->word->word);
1005 /* Same thing about POSIX.2 conversion error requirements. */
1007 conversion_error = 1;
1009 else if (errno == ERANGE)
1010 printf_erange (garglist->word->word);
1012 garglist = garglist->next;
1016 /* NO check is needed for garglist here. */
1022 ch = garglist->word->word[1];
1023 garglist = garglist->next;