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).
39 #include <sys/types.h>
54 #define main printfcmd
55 #include "bltin/bltin.h"
59 #define PF(f, func) do { \
62 (void)printf(f, fieldwidth, precision, func); \
64 (void)printf(f, fieldwidth, func); \
66 (void)printf(f, precision, func); \
68 (void)printf(f, func); \
71 static int asciicode(void);
72 static char *printf_doformat(char *, int *);
73 static int escape(char *, int, size_t *);
74 static int getchr(void);
75 static int getfloating(long double *, int);
76 static int getint(int *);
77 static int getnum(intmax_t *, uintmax_t *, int);
80 static char *mknum(char *, char);
81 static void usage(void);
83 static const char digits[] = "0123456789";
85 static char end_fmt[1];
90 static char **maxargv;
93 main(int argc, char *argv[])
97 char *format, *fmt, *start;
101 (void) setlocale(LC_ALL, "");
106 argc -= argptr - argv;
109 while ((ch = getopt(argc, argv, "")) != -1)
129 * Basic algorithm is to scan the format string for conversion
130 * specifications -- once one is found, find out if the field
131 * width or precision is a '*'; if it is, gather up value. Note,
132 * format strings are reused as necessary to use up the provided
133 * arguments, arguments of zero/null string are provided to use
134 * up the format string.
136 fmt = format = *argv;
137 escape(fmt, 1, &len); /* backslash interpretation */
145 for (myargc = 0; gargv[myargc]; myargc++)
148 while (fmt < format + len) {
150 fwrite(start, 1, fmt - start, stdout);
156 fmt = printf_doformat(fmt, &rval);
157 if (fmt == NULL || fmt == end_fmt) {
161 return (fmt == NULL ? 1 : rval);
174 warnx("missing format character");
180 fwrite(start, 1, fmt - start, stdout);
187 /* Restart at the beginning of the format string. */
196 printf_doformat(char *fmt, int *rval)
198 static const char skip1[] = "#'-+ 0";
199 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
201 char start[strlen(fmt) + 1];
212 /* look for "n$" field index specifier */
213 l = strspn(fmt, digits);
214 if ((l > 0) && (fmt[l] == '$')) {
217 gargv = &myargv[idx - 1];
219 gargv = &myargv[myargc];
225 /* save format argument */
231 /* skip to field width */
232 while (*fmt && strchr(skip1, *fmt) != NULL) {
240 l = strspn(fmt, digits);
241 if ((l > 0) && (fmt[l] == '$')) {
244 warnx("incomplete use of n$");
248 gargv = &myargv[idx - 1];
250 gargv = &myargv[myargc];
253 } else if (fargv != NULL) {
254 warnx("incomplete use of n$");
258 if (getint(&fieldwidth))
269 /* skip to possible '.', get following precision */
270 while (isdigit(*fmt)) {
277 /* precision present? */
284 l = strspn(fmt, digits);
285 if ((l > 0) && (fmt[l] == '$')) {
288 warnx("incomplete use of n$");
292 gargv = &myargv[idx - 1];
294 gargv = &myargv[myargc];
297 } else if (fargv != NULL) {
298 warnx("incomplete use of n$");
302 if (getint(&precision))
312 /* skip to conversion char */
313 while (isdigit(*fmt)) {
321 warnx("missing format character");
328 * Look for a length modifier. POSIX doesn't have these, so
329 * we only support them for floating-point conversions, which
330 * are extensions. This is useful because the L modifier can
331 * be used to gain extra range and precision, while omitting
332 * it is more likely to produce consistent results on different
333 * architectures. This is not so important for integers
334 * because overflow is the only bad thing that can happen to
335 * them, but consider the command printf %a 1.1
340 if (!strchr("aAeEfFgG", *fmt)) {
341 warnx("bad modifier L for %%%c", *fmt);
348 /* save the current arg offset, and set to the format arg */
363 /* Convert "b" to "s" for output. */
364 start[strlen(start) - 1] = 's';
365 if ((p = strdup(getstr())) == NULL) {
366 warnx("%s", strerror(ENOMEM));
369 getout = escape(p, 0, &len);
371 /* Restore format for next loop. */
393 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
399 signedconv = (convch == 'd' || convch == 'i');
400 if ((f = mknum(start, convch)) == NULL)
402 if (getnum(&val, &uval, signedconv))
413 case 'a': case 'A': {
416 if (getfloating(&p, mod_ldbl))
421 PF(start, (double)p);
425 warnx("illegal format character %c", convch);
429 /* return the gargv to the next element */
434 mknum(char *str, char ch)
437 static size_t copy_size;
441 len = strlen(str) + 2;
442 if (len > copy_size) {
443 newlen = ((len + 1023) >> 10) << 10;
444 if ((newcopy = realloc(copy, newlen)) == NULL) {
445 warnx("%s", strerror(ENOMEM));
452 memmove(copy, str, len - 3);
455 copy[len - 1] = '\0';
460 escape(char *fmt, int percent, size_t *len)
462 char *save, *store, c;
465 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
471 case '\0': /* EOS, user error */
476 case '\\': /* backslash */
477 case '\'': /* single quote */
480 case 'a': /* bell/alert */
483 case 'b': /* backspace */
494 case 'f': /* form-feed */
497 case 'n': /* newline */
500 case 'r': /* carriage-return */
503 case 't': /* horizontal tab */
506 case 'v': /* vertical tab */
510 case '0': case '1': case '2': case '3':
511 case '4': case '5': case '6': case '7':
512 c = (!percent && *fmt == '0') ? 4 : 3;
514 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
519 if (percent && value == '%') {
523 *store = (char)value;
540 return ((int)**gargv++);
558 if (getnum(&val, &uval, 1))
561 if (val < INT_MIN || val > INT_MAX) {
562 warnx("%s: %s", *gargv, strerror(ERANGE));
570 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
579 if (**gargv == '"' || **gargv == '\'') {
589 *ip = strtoimax(*gargv, &ep, 0);
591 *uip = strtoumax(*gargv, &ep, 0);
593 warnx("%s: expected numeric value", *gargv);
596 else if (*ep != '\0') {
597 warnx("%s: not completely converted", *gargv);
600 if (errno == ERANGE) {
601 warnx("%s: %s", *gargv, strerror(ERANGE));
609 getfloating(long double *dp, int mod_ldbl)
618 if (**gargv == '"' || **gargv == '\'') {
625 *dp = strtold(*gargv, &ep);
627 *dp = strtod(*gargv, &ep);
629 warnx("%s: expected numeric value", *gargv);
631 } else if (*ep != '\0') {
632 warnx("%s: not completely converted", *gargv);
635 if (errno == ERANGE) {
636 warnx("%s: %s", *gargv, strerror(ERANGE));
650 ch = (unsigned char)**gargv;
651 if (ch == '\'' || ch == '"') {
652 memset(&mbs, 0, sizeof(mbs));
653 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
656 wch = (unsigned char)gargv[0][1];
671 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");