2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright 2018 Staysail Systems, Inc. <info@staysail.tech>
5 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
6 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
7 * Copyright (c) 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Important: This file is used both as a standalone program /usr/bin/printf
36 * and as a builtin for /bin/sh (#define SHELL).
41 static char const copyright[] =
42 "@(#) Copyright (c) 1989, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
49 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
51 static const char rcsid[] =
55 #include <sys/types.h>
70 #define main printfcmd
71 #include "bltin/bltin.h"
75 #define PF(f, func) do { \
78 (void)printf(f, fieldwidth, precision, func); \
80 (void)printf(f, fieldwidth, func); \
82 (void)printf(f, precision, func); \
84 (void)printf(f, func); \
87 static int asciicode(void);
88 static char *printf_doformat(char *, int *);
89 static int escape(char *, int, size_t *);
90 static int getchr(void);
91 static int getfloating(long double *, int);
92 static int getint(int *);
93 static int getnum(intmax_t *, uintmax_t *, int);
96 static char *mknum(char *, char);
97 static void usage(void);
99 static const char digits[] = "0123456789";
101 static char end_fmt[1];
104 static char **myargv;
106 static char **maxargv;
109 main(int argc, char *argv[])
113 char *format, *fmt, *start;
117 (void) setlocale(LC_ALL, "");
122 argc -= argptr - argv;
125 while ((ch = getopt(argc, argv, "")) != -1)
145 * Basic algorithm is to scan the format string for conversion
146 * specifications -- once one is found, find out if the field
147 * width or precision is a '*'; if it is, gather up value. Note,
148 * format strings are reused as necessary to use up the provided
149 * arguments, arguments of zero/null string are provided to use
150 * up the format string.
152 fmt = format = *argv;
153 escape(fmt, 1, &len); /* backslash interpretation */
161 for (myargc = 0; gargv[myargc]; myargc++)
164 while (fmt < format + len) {
166 fwrite(start, 1, fmt - start, stdout);
172 fmt = printf_doformat(fmt, &rval);
173 if (fmt == NULL || fmt == end_fmt) {
177 return (fmt == NULL ? 1 : rval);
190 warnx("missing format character");
196 fwrite(start, 1, fmt - start, stdout);
203 /* Restart at the beginning of the format string. */
212 printf_doformat(char *fmt, int *rval)
214 static const char skip1[] = "#'-+ 0";
215 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
217 char start[strlen(fmt) + 1];
228 /* look for "n$" field index specifier */
229 l = strspn(fmt, digits);
230 if ((l > 0) && (fmt[l] == '$')) {
233 gargv = &myargv[idx - 1];
235 gargv = &myargv[myargc];
241 /* save format argument */
247 /* skip to field width */
248 while (*fmt && strchr(skip1, *fmt) != NULL) {
256 l = strspn(fmt, digits);
257 if ((l > 0) && (fmt[l] == '$')) {
260 warnx("incomplete use of n$");
264 gargv = &myargv[idx - 1];
266 gargv = &myargv[myargc];
269 } else if (fargv != NULL) {
270 warnx("incomplete use of n$");
274 if (getint(&fieldwidth))
285 /* skip to possible '.', get following precision */
286 while (isdigit(*fmt)) {
293 /* precision present? */
300 l = strspn(fmt, digits);
301 if ((l > 0) && (fmt[l] == '$')) {
304 warnx("incomplete use of n$");
308 gargv = &myargv[idx - 1];
310 gargv = &myargv[myargc];
313 } else if (fargv != NULL) {
314 warnx("incomplete use of n$");
318 if (getint(&precision))
328 /* skip to conversion char */
329 while (isdigit(*fmt)) {
337 warnx("missing format character");
344 * Look for a length modifier. POSIX doesn't have these, so
345 * we only support them for floating-point conversions, which
346 * are extensions. This is useful because the L modifier can
347 * be used to gain extra range and precision, while omitting
348 * it is more likely to produce consistent results on different
349 * architectures. This is not so important for integers
350 * because overflow is the only bad thing that can happen to
351 * them, but consider the command printf %a 1.1
356 if (!strchr("aAeEfFgG", *fmt)) {
357 warnx("bad modifier L for %%%c", *fmt);
364 /* save the current arg offset, and set to the format arg */
379 /* Convert "b" to "s" for output. */
380 start[strlen(start) - 1] = 's';
381 if ((p = strdup(getstr())) == NULL) {
382 warnx("%s", strerror(ENOMEM));
385 getout = escape(p, 0, &len);
387 /* Restore format for next loop. */
409 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
415 signedconv = (convch == 'd' || convch == 'i');
416 if ((f = mknum(start, convch)) == NULL)
418 if (getnum(&val, &uval, signedconv))
429 case 'a': case 'A': {
432 if (getfloating(&p, mod_ldbl))
437 PF(start, (double)p);
441 warnx("illegal format character %c", convch);
445 /* return the gargv to the next element */
450 mknum(char *str, char ch)
453 static size_t copy_size;
457 len = strlen(str) + 2;
458 if (len > copy_size) {
459 newlen = ((len + 1023) >> 10) << 10;
460 if ((newcopy = realloc(copy, newlen)) == NULL) {
461 warnx("%s", strerror(ENOMEM));
468 memmove(copy, str, len - 3);
471 copy[len - 1] = '\0';
476 escape(char *fmt, int percent, size_t *len)
478 char *save, *store, c;
481 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
487 case '\0': /* EOS, user error */
492 case '\\': /* backslash */
493 case '\'': /* single quote */
496 case 'a': /* bell/alert */
499 case 'b': /* backspace */
510 case 'f': /* form-feed */
513 case 'n': /* newline */
516 case 'r': /* carriage-return */
519 case 't': /* horizontal tab */
522 case 'v': /* vertical tab */
526 case '0': case '1': case '2': case '3':
527 case '4': case '5': case '6': case '7':
528 c = (!percent && *fmt == '0') ? 4 : 3;
530 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
535 if (percent && value == '%') {
539 *store = (char)value;
556 return ((int)**gargv++);
574 if (getnum(&val, &uval, 1))
577 if (val < INT_MIN || val > INT_MAX) {
578 warnx("%s: %s", *gargv, strerror(ERANGE));
586 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
595 if (**gargv == '"' || **gargv == '\'') {
605 *ip = strtoimax(*gargv, &ep, 0);
607 *uip = strtoumax(*gargv, &ep, 0);
609 warnx("%s: expected numeric value", *gargv);
612 else if (*ep != '\0') {
613 warnx("%s: not completely converted", *gargv);
616 if (errno == ERANGE) {
617 warnx("%s: %s", *gargv, strerror(ERANGE));
625 getfloating(long double *dp, int mod_ldbl)
634 if (**gargv == '"' || **gargv == '\'') {
641 *dp = strtold(*gargv, &ep);
643 *dp = strtod(*gargv, &ep);
645 warnx("%s: expected numeric value", *gargv);
647 } else if (*ep != '\0') {
648 warnx("%s: not completely converted", *gargv);
651 if (errno == ERANGE) {
652 warnx("%s: %s", *gargv, strerror(ERANGE));
666 ch = (unsigned char)**gargv;
667 if (ch == '\'' || ch == '"') {
668 memset(&mbs, 0, sizeof(mbs));
669 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
672 wch = (unsigned char)gargv[0][1];
687 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");