2 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
3 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * Important: This file is used both as a standalone program /usr/bin/printf
33 * and as a builtin for /bin/sh (#define SHELL).
38 static char const copyright[] =
39 "@(#) Copyright (c) 1989, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
46 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
48 static const char rcsid[] =
52 #include <sys/types.h>
67 #define main printfcmd
68 #include "bltin/bltin.h"
72 #define PF(f, func) do { \
75 (void)printf(f, fieldwidth, precision, func); \
77 (void)printf(f, fieldwidth, func); \
79 (void)printf(f, precision, func); \
81 (void)printf(f, func); \
84 static int asciicode(void);
85 static char *printf_doformat(char *, int *);
86 static int escape(char *, int, size_t *);
87 static int getchr(void);
88 static int getfloating(long double *, int);
89 static int getint(int *);
90 static int getnum(intmax_t *, uintmax_t *, int);
93 static char *mknum(char *, char);
94 static void usage(void);
96 static const char digits[] = "0123456789";
98 static char end_fmt[1];
101 static char **myargv;
103 static char **maxargv;
106 main(int argc, char *argv[])
110 char *format, *fmt, *start;
114 (void) setlocale(LC_ALL, "");
119 argc -= argptr - argv;
122 while ((ch = getopt(argc, argv, "")) != -1)
142 * Basic algorithm is to scan the format string for conversion
143 * specifications -- once one is found, find out if the field
144 * width or precision is a '*'; if it is, gather up value. Note,
145 * format strings are reused as necessary to use up the provided
146 * arguments, arguments of zero/null string are provided to use
147 * up the format string.
149 fmt = format = *argv;
150 escape(fmt, 1, &len); /* backslash interpretation */
158 for (myargc = 0; gargv[myargc]; myargc++)
161 while (fmt < format + len) {
163 fwrite(start, 1, fmt - start, stdout);
169 fmt = printf_doformat(fmt, &rval);
170 if (fmt == NULL || fmt == end_fmt) {
174 return (fmt == NULL ? 1 : rval);
187 warnx("missing format character");
193 fwrite(start, 1, fmt - start, stdout);
200 /* Restart at the beginning of the format string. */
209 printf_doformat(char *fmt, int *rval)
211 static const char skip1[] = "#'-+ 0";
212 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
214 char start[strlen(fmt) + 1];
225 /* look for "n$" field index specifier */
226 l = strspn(fmt, digits);
227 if ((l > 0) && (fmt[l] == '$')) {
230 gargv = &myargv[idx - 1];
232 gargv = &myargv[myargc];
238 /* save format argument */
244 /* skip to field width */
245 while (*fmt && strchr(skip1, *fmt) != NULL) {
253 l = strspn(fmt, digits);
254 if ((l > 0) && (fmt[l] == '$')) {
257 warnx("incomplete use of n$");
261 gargv = &myargv[idx - 1];
263 gargv = &myargv[myargc];
266 } else if (fargv != NULL) {
267 warnx("incomplete use of n$");
271 if (getint(&fieldwidth))
282 /* skip to possible '.', get following precision */
283 while (isdigit(*fmt)) {
290 /* precision present? */
297 l = strspn(fmt, digits);
298 if ((l > 0) && (fmt[l] == '$')) {
301 warnx("incomplete use of n$");
305 gargv = &myargv[idx - 1];
307 gargv = &myargv[myargc];
310 } else if (fargv != NULL) {
311 warnx("incomplete use of n$");
315 if (getint(&precision))
325 /* skip to conversion char */
326 while (isdigit(*fmt)) {
334 warnx("missing format character");
341 * Look for a length modifier. POSIX doesn't have these, so
342 * we only support them for floating-point conversions, which
343 * are extensions. This is useful because the L modifier can
344 * be used to gain extra range and precision, while omitting
345 * it is more likely to produce consistent results on different
346 * architectures. This is not so important for integers
347 * because overflow is the only bad thing that can happen to
348 * them, but consider the command printf %a 1.1
353 if (!strchr("aAeEfFgG", *fmt)) {
354 warnx("bad modifier L for %%%c", *fmt);
361 /* save the current arg offset, and set to the format arg */
376 p = strdup(getstr());
378 warnx("%s", strerror(ENOMEM));
381 getout = escape(p, 0, &len);
403 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
409 signedconv = (convch == 'd' || convch == 'i');
410 if ((f = mknum(start, convch)) == NULL)
412 if (getnum(&val, &uval, signedconv))
423 case 'a': case 'A': {
426 if (getfloating(&p, mod_ldbl))
431 PF(start, (double)p);
435 warnx("illegal format character %c", convch);
439 /* return the gargv to the next element */
444 mknum(char *str, char ch)
447 static size_t copy_size;
451 len = strlen(str) + 2;
452 if (len > copy_size) {
453 newlen = ((len + 1023) >> 10) << 10;
454 if ((newcopy = realloc(copy, newlen)) == NULL) {
455 warnx("%s", strerror(ENOMEM));
462 memmove(copy, str, len - 3);
465 copy[len - 1] = '\0';
470 escape(char *fmt, int percent, size_t *len)
472 char *save, *store, c;
475 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
481 case '\0': /* EOS, user error */
486 case '\\': /* backslash */
487 case '\'': /* single quote */
490 case 'a': /* bell/alert */
493 case 'b': /* backspace */
504 case 'f': /* form-feed */
507 case 'n': /* newline */
510 case 'r': /* carriage-return */
513 case 't': /* horizontal tab */
516 case 'v': /* vertical tab */
520 case '0': case '1': case '2': case '3':
521 case '4': case '5': case '6': case '7':
522 c = (!percent && *fmt == '0') ? 4 : 3;
524 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
529 if (percent && value == '%') {
533 *store = (char)value;
550 return ((int)**gargv++);
568 if (getnum(&val, &uval, 1))
571 if (val < INT_MIN || val > INT_MAX) {
572 warnx("%s: %s", *gargv, strerror(ERANGE));
580 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
589 if (**gargv == '"' || **gargv == '\'') {
599 *ip = strtoimax(*gargv, &ep, 0);
601 *uip = strtoumax(*gargv, &ep, 0);
603 warnx("%s: expected numeric value", *gargv);
606 else if (*ep != '\0') {
607 warnx("%s: not completely converted", *gargv);
610 if (errno == ERANGE) {
611 warnx("%s: %s", *gargv, strerror(ERANGE));
619 getfloating(long double *dp, int mod_ldbl)
628 if (**gargv == '"' || **gargv == '\'') {
635 *dp = strtold(*gargv, &ep);
637 *dp = strtod(*gargv, &ep);
639 warnx("%s: expected numeric value", *gargv);
641 } else if (*ep != '\0') {
642 warnx("%s: not completely converted", *gargv);
645 if (errno == ERANGE) {
646 warnx("%s: %s", *gargv, strerror(ERANGE));
660 ch = (unsigned char)**gargv;
661 if (ch == '\'' || ch == '"') {
662 memset(&mbs, 0, sizeof(mbs));
663 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
666 wch = (unsigned char)gargv[0][1];
681 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");