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 * 4. 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"
73 #define PF(f, func) do { \
77 (void)asprintf(&b, f, fieldwidth, precision, func); \
79 (void)asprintf(&b, f, fieldwidth, func); \
81 (void)asprintf(&b, f, precision, func); \
83 (void)asprintf(&b, f, func); \
85 (void)fputs(b, stdout); \
90 static int asciicode(void);
91 static char *printf_doformat(char *, int *);
92 static int escape(char *, int, size_t *);
93 static int getchr(void);
94 static int getfloating(long double *, int);
95 static int getint(int *);
96 static int getnum(intmax_t *, uintmax_t *, int);
99 static char *mknum(char *, char);
100 static void usage(void);
102 static const char digits[] = "0123456789";
104 static char end_fmt[1];
107 static char **myargv;
109 static char **maxargv;
112 main(int argc, char *argv[])
116 char *format, *fmt, *start;
120 (void) setlocale(LC_ALL, "");
125 argc -= argptr - argv;
128 while ((ch = getopt(argc, argv, "")) != -1)
148 * Basic algorithm is to scan the format string for conversion
149 * specifications -- once one is found, find out if the field
150 * width or precision is a '*'; if it is, gather up value. Note,
151 * format strings are reused as necessary to use up the provided
152 * arguments, arguments of zero/null string are provided to use
153 * up the format string.
155 fmt = format = *argv;
156 escape(fmt, 1, &len); /* backslash interpretation */
164 for (myargc = 0; gargv[myargc]; myargc++)
167 while (fmt < format + len) {
169 fwrite(start, 1, fmt - start, stdout);
175 fmt = printf_doformat(fmt, &rval);
176 if (fmt == NULL || fmt == end_fmt) {
180 return (fmt == NULL ? 1 : rval);
193 warnx("missing format character");
199 fwrite(start, 1, fmt - start, stdout);
206 /* Restart at the beginning of the format string. */
215 printf_doformat(char *fmt, int *rval)
217 static const char skip1[] = "#'-+ 0";
218 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
220 char start[strlen(fmt) + 1];
231 /* look for "n$" field index specifier */
232 l = strspn(fmt, digits);
233 if ((l > 0) && (fmt[l] == '$')) {
236 gargv = &myargv[idx - 1];
238 gargv = &myargv[myargc];
244 /* save format argument */
250 /* skip to field width */
251 while (*fmt && strchr(skip1, *fmt) != NULL) {
259 l = strspn(fmt, digits);
260 if ((l > 0) && (fmt[l] == '$')) {
263 warnx("incomplete use of n$");
267 gargv = &myargv[idx - 1];
269 gargv = &myargv[myargc];
272 } else if (fargv != NULL) {
273 warnx("incomplete use of n$");
277 if (getint(&fieldwidth))
288 /* skip to possible '.', get following precision */
289 while (isdigit(*fmt)) {
296 /* precision present? */
303 l = strspn(fmt, digits);
304 if ((l > 0) && (fmt[l] == '$')) {
307 warnx("incomplete use of n$");
311 gargv = &myargv[idx - 1];
313 gargv = &myargv[myargc];
316 } else if (fargv != NULL) {
317 warnx("incomplete use of n$");
321 if (getint(&precision))
331 /* skip to conversion char */
332 while (isdigit(*fmt)) {
340 warnx("missing format character");
347 * Look for a length modifier. POSIX doesn't have these, so
348 * we only support them for floating-point conversions, which
349 * are extensions. This is useful because the L modifier can
350 * be used to gain extra range and precision, while omitting
351 * it is more likely to produce consistent results on different
352 * architectures. This is not so important for integers
353 * because overflow is the only bad thing that can happen to
354 * them, but consider the command printf %a 1.1
359 if (!strchr("aAeEfFgG", *fmt)) {
360 warnx("bad modifier L for %%%c", *fmt);
367 /* save the current arg offset, and set to the format arg */
382 p = strdup(getstr());
384 warnx("%s", strerror(ENOMEM));
387 getout = escape(p, 0, &len);
408 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
414 signedconv = (convch == 'd' || convch == 'i');
415 if ((f = mknum(start, convch)) == NULL)
417 if (getnum(&val, &uval, signedconv))
428 case 'a': case 'A': {
431 if (getfloating(&p, mod_ldbl))
436 PF(start, (double)p);
440 warnx("illegal format character %c", convch);
444 /* return the gargv to the next element */
449 mknum(char *str, char ch)
452 static size_t copy_size;
456 len = strlen(str) + 2;
457 if (len > copy_size) {
458 newlen = ((len + 1023) >> 10) << 10;
459 if ((newcopy = realloc(copy, newlen)) == NULL) {
460 warnx("%s", strerror(ENOMEM));
467 memmove(copy, str, len - 3);
470 copy[len - 1] = '\0';
475 escape(char *fmt, int percent, size_t *len)
477 char *save, *store, c;
480 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
486 case '\0': /* EOS, user error */
491 case '\\': /* backslash */
492 case '\'': /* single quote */
495 case 'a': /* bell/alert */
498 case 'b': /* backspace */
509 case 'f': /* form-feed */
512 case 'n': /* newline */
515 case 'r': /* carriage-return */
518 case 't': /* horizontal tab */
521 case 'v': /* vertical tab */
525 case '0': case '1': case '2': case '3':
526 case '4': case '5': case '6': case '7':
527 c = (!percent && *fmt == '0') ? 4 : 3;
529 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
534 if (percent && value == '%') {
538 *store = (char)value;
555 return ((int)**gargv++);
573 if (getnum(&val, &uval, 1))
576 if (val < INT_MIN || val > INT_MAX) {
577 warnx("%s: %s", *gargv, strerror(ERANGE));
585 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
594 if (**gargv == '"' || **gargv == '\'') {
604 *ip = strtoimax(*gargv, &ep, 0);
606 *uip = strtoumax(*gargv, &ep, 0);
608 warnx("%s: expected numeric value", *gargv);
611 else if (*ep != '\0') {
612 warnx("%s: not completely converted", *gargv);
615 if (errno == ERANGE) {
616 warnx("%s: %s", *gargv, strerror(ERANGE));
624 getfloating(long double *dp, int mod_ldbl)
633 if (**gargv == '"' || **gargv == '\'') {
640 *dp = strtold(*gargv, &ep);
642 *dp = strtod(*gargv, &ep);
644 warnx("%s: expected numeric value", *gargv);
646 } else if (*ep != '\0') {
647 warnx("%s: not completely converted", *gargv);
650 if (errno == ERANGE) {
651 warnx("%s: %s", *gargv, strerror(ERANGE));
665 ch = (unsigned char)**gargv;
666 if (ch == '\'' || ch == '"') {
667 memset(&mbs, 0, sizeof(mbs));
668 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
671 wch = (unsigned char)gargv[0][1];
686 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");