2 * Copyright 2018 Staysail Systems, Inc. <info@staysail.tech>
3 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
4 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
5 * Copyright (c) 1989, 1993
6 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * Important: This file is used both as a standalone program /usr/bin/printf
34 * and as a builtin for /bin/sh (#define SHELL).
39 static char const copyright[] =
40 "@(#) Copyright (c) 1989, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
47 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
49 static const char rcsid[] =
53 #include <sys/types.h>
68 #define main printfcmd
69 #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 /* Convert "b" to "s" for output. */
383 start[strlen(start) - 1] = 's';
384 if ((p = strdup(getstr())) == NULL) {
385 warnx("%s", strerror(ENOMEM));
388 getout = escape(p, 0, &len);
390 /* Restore format for next loop. */
411 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
417 signedconv = (convch == 'd' || convch == 'i');
418 if ((f = mknum(start, convch)) == NULL)
420 if (getnum(&val, &uval, signedconv))
431 case 'a': case 'A': {
434 if (getfloating(&p, mod_ldbl))
439 PF(start, (double)p);
443 warnx("illegal format character %c", convch);
447 /* return the gargv to the next element */
452 mknum(char *str, char ch)
455 static size_t copy_size;
459 len = strlen(str) + 2;
460 if (len > copy_size) {
461 newlen = ((len + 1023) >> 10) << 10;
462 if ((newcopy = realloc(copy, newlen)) == NULL) {
463 warnx("%s", strerror(ENOMEM));
470 memmove(copy, str, len - 3);
473 copy[len - 1] = '\0';
478 escape(char *fmt, int percent, size_t *len)
480 char *save, *store, c;
483 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
489 case '\0': /* EOS, user error */
494 case '\\': /* backslash */
495 case '\'': /* single quote */
498 case 'a': /* bell/alert */
501 case 'b': /* backspace */
512 case 'f': /* form-feed */
515 case 'n': /* newline */
518 case 'r': /* carriage-return */
521 case 't': /* horizontal tab */
524 case 'v': /* vertical tab */
528 case '0': case '1': case '2': case '3':
529 case '4': case '5': case '6': case '7':
530 c = (!percent && *fmt == '0') ? 4 : 3;
532 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
537 if (percent && value == '%') {
541 *store = (char)value;
558 return ((int)**gargv++);
576 if (getnum(&val, &uval, 1))
579 if (val < INT_MIN || val > INT_MAX) {
580 warnx("%s: %s", *gargv, strerror(ERANGE));
588 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
597 if (**gargv == '"' || **gargv == '\'') {
607 *ip = strtoimax(*gargv, &ep, 0);
609 *uip = strtoumax(*gargv, &ep, 0);
611 warnx("%s: expected numeric value", *gargv);
614 else if (*ep != '\0') {
615 warnx("%s: not completely converted", *gargv);
618 if (errno == ERANGE) {
619 warnx("%s: %s", *gargv, strerror(ERANGE));
627 getfloating(long double *dp, int mod_ldbl)
636 if (**gargv == '"' || **gargv == '\'') {
643 *dp = strtold(*gargv, &ep);
645 *dp = strtod(*gargv, &ep);
647 warnx("%s: expected numeric value", *gargv);
649 } else if (*ep != '\0') {
650 warnx("%s: not completely converted", *gargv);
653 if (errno == ERANGE) {
654 warnx("%s: %s", *gargv, strerror(ERANGE));
668 ch = (unsigned char)**gargv;
669 if (ch == '\'' || ch == '"') {
670 memset(&mbs, 0, sizeof(mbs));
671 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
674 wch = (unsigned char)gargv[0][1];
689 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");