2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
5 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
6 * Copyright (c) 1989, 1993
7 * The Regents of the University of California. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * Important: This file is used both as a standalone program /usr/bin/printf
35 * and as a builtin for /bin/sh (#define SHELL).
40 static char const copyright[] =
41 "@(#) Copyright (c) 1989, 1993\n\
42 The Regents of the University of California. All rights reserved.\n";
48 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
50 static const char rcsid[] =
54 #include <sys/types.h>
69 #define main printfcmd
70 #include "bltin/bltin.h"
74 #define PF(f, func) do { \
77 (void)printf(f, fieldwidth, precision, func); \
79 (void)printf(f, fieldwidth, func); \
81 (void)printf(f, precision, func); \
83 (void)printf(f, func); \
86 static int asciicode(void);
87 static char *printf_doformat(char *, int *);
88 static int escape(char *, int, size_t *);
89 static int getchr(void);
90 static int getfloating(long double *, int);
91 static int getint(int *);
92 static int getnum(intmax_t *, uintmax_t *, int);
95 static char *mknum(char *, char);
96 static void usage(void);
98 static const char digits[] = "0123456789";
100 static char end_fmt[1];
103 static char **myargv;
105 static char **maxargv;
108 main(int argc, char *argv[])
112 char *format, *fmt, *start;
116 (void) setlocale(LC_ALL, "");
121 argc -= argptr - argv;
124 while ((ch = getopt(argc, argv, "")) != -1)
144 * Basic algorithm is to scan the format string for conversion
145 * specifications -- once one is found, find out if the field
146 * width or precision is a '*'; if it is, gather up value. Note,
147 * format strings are reused as necessary to use up the provided
148 * arguments, arguments of zero/null string are provided to use
149 * up the format string.
151 fmt = format = *argv;
152 escape(fmt, 1, &len); /* backslash interpretation */
160 for (myargc = 0; gargv[myargc]; myargc++)
163 while (fmt < format + len) {
165 fwrite(start, 1, fmt - start, stdout);
171 fmt = printf_doformat(fmt, &rval);
172 if (fmt == NULL || fmt == end_fmt) {
176 return (fmt == NULL ? 1 : rval);
189 warnx("missing format character");
195 fwrite(start, 1, fmt - start, stdout);
202 /* Restart at the beginning of the format string. */
211 printf_doformat(char *fmt, int *rval)
213 static const char skip1[] = "#'-+ 0";
214 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
216 char start[strlen(fmt) + 1];
227 /* look for "n$" field index specifier */
228 l = strspn(fmt, digits);
229 if ((l > 0) && (fmt[l] == '$')) {
232 gargv = &myargv[idx - 1];
234 gargv = &myargv[myargc];
240 /* save format argument */
246 /* skip to field width */
247 while (*fmt && strchr(skip1, *fmt) != NULL) {
255 l = strspn(fmt, digits);
256 if ((l > 0) && (fmt[l] == '$')) {
259 warnx("incomplete use of n$");
263 gargv = &myargv[idx - 1];
265 gargv = &myargv[myargc];
268 } else if (fargv != NULL) {
269 warnx("incomplete use of n$");
273 if (getint(&fieldwidth))
284 /* skip to possible '.', get following precision */
285 while (isdigit(*fmt)) {
292 /* precision present? */
299 l = strspn(fmt, digits);
300 if ((l > 0) && (fmt[l] == '$')) {
303 warnx("incomplete use of n$");
307 gargv = &myargv[idx - 1];
309 gargv = &myargv[myargc];
312 } else if (fargv != NULL) {
313 warnx("incomplete use of n$");
317 if (getint(&precision))
327 /* skip to conversion char */
328 while (isdigit(*fmt)) {
336 warnx("missing format character");
343 * Look for a length modifier. POSIX doesn't have these, so
344 * we only support them for floating-point conversions, which
345 * are extensions. This is useful because the L modifier can
346 * be used to gain extra range and precision, while omitting
347 * it is more likely to produce consistent results on different
348 * architectures. This is not so important for integers
349 * because overflow is the only bad thing that can happen to
350 * them, but consider the command printf %a 1.1
355 if (!strchr("aAeEfFgG", *fmt)) {
356 warnx("bad modifier L for %%%c", *fmt);
363 /* save the current arg offset, and set to the format arg */
378 p = strdup(getstr());
380 warnx("%s", strerror(ENOMEM));
383 getout = escape(p, 0, &len);
405 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
411 signedconv = (convch == 'd' || convch == 'i');
412 if ((f = mknum(start, convch)) == NULL)
414 if (getnum(&val, &uval, signedconv))
425 case 'a': case 'A': {
428 if (getfloating(&p, mod_ldbl))
433 PF(start, (double)p);
437 warnx("illegal format character %c", convch);
441 /* return the gargv to the next element */
446 mknum(char *str, char ch)
449 static size_t copy_size;
453 len = strlen(str) + 2;
454 if (len > copy_size) {
455 newlen = ((len + 1023) >> 10) << 10;
456 if ((newcopy = realloc(copy, newlen)) == NULL) {
457 warnx("%s", strerror(ENOMEM));
464 memmove(copy, str, len - 3);
467 copy[len - 1] = '\0';
472 escape(char *fmt, int percent, size_t *len)
474 char *save, *store, c;
477 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
483 case '\0': /* EOS, user error */
488 case '\\': /* backslash */
489 case '\'': /* single quote */
492 case 'a': /* bell/alert */
495 case 'b': /* backspace */
506 case 'f': /* form-feed */
509 case 'n': /* newline */
512 case 'r': /* carriage-return */
515 case 't': /* horizontal tab */
518 case 'v': /* vertical tab */
522 case '0': case '1': case '2': case '3':
523 case '4': case '5': case '6': case '7':
524 c = (!percent && *fmt == '0') ? 4 : 3;
526 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
531 if (percent && value == '%') {
535 *store = (char)value;
552 return ((int)**gargv++);
570 if (getnum(&val, &uval, 1))
573 if (val < INT_MIN || val > INT_MAX) {
574 warnx("%s: %s", *gargv, strerror(ERANGE));
582 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
591 if (**gargv == '"' || **gargv == '\'') {
601 *ip = strtoimax(*gargv, &ep, 0);
603 *uip = strtoumax(*gargv, &ep, 0);
605 warnx("%s: expected numeric value", *gargv);
608 else if (*ep != '\0') {
609 warnx("%s: not completely converted", *gargv);
612 if (errno == ERANGE) {
613 warnx("%s: %s", *gargv, strerror(ERANGE));
621 getfloating(long double *dp, int mod_ldbl)
630 if (**gargv == '"' || **gargv == '\'') {
637 *dp = strtold(*gargv, &ep);
639 *dp = strtod(*gargv, &ep);
641 warnx("%s: expected numeric value", *gargv);
643 } else if (*ep != '\0') {
644 warnx("%s: not completely converted", *gargv);
647 if (errno == ERANGE) {
648 warnx("%s: %s", *gargv, strerror(ERANGE));
662 ch = (unsigned char)**gargv;
663 if (ch == '\'' || ch == '"') {
664 memset(&mbs, 0, sizeof(mbs));
665 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
668 wch = (unsigned char)gargv[0][1];
683 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");