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 (strchr(skip1, *fmt) != NULL) {
259 l = strspn(fmt, digits);
260 if ((l > 0) && (fmt[l] == '$')) {
263 gargv = &myargv[idx - 1];
265 gargv = &myargv[myargc];
270 if (getint(&fieldwidth))
281 /* skip to possible '.', get following precision */
282 while (isdigit(*fmt)) {
289 /* precision present? */
296 l = strspn(fmt, digits);
297 if ((l > 0) && (fmt[l] == '$')) {
300 gargv = &myargv[idx - 1];
302 gargv = &myargv[myargc];
307 if (getint(&precision))
317 /* skip to conversion char */
318 while (isdigit(*fmt)) {
326 warnx("missing format character");
333 * Look for a length modifier. POSIX doesn't have these, so
334 * we only support them for floating-point conversions, which
335 * are extensions. This is useful because the L modifier can
336 * be used to gain extra range and precision, while omitting
337 * it is more likely to produce consistent results on different
338 * architectures. This is not so important for integers
339 * because overflow is the only bad thing that can happen to
340 * them, but consider the command printf %a 1.1
345 if (!strchr("aAeEfFgG", *fmt)) {
346 warnx("bad modifier L for %%%c", *fmt);
353 /* save the current arg offset, and set to the format arg */
368 p = strdup(getstr());
370 warnx("%s", strerror(ENOMEM));
373 getout = escape(p, 0, &len);
394 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
400 signedconv = (convch == 'd' || convch == 'i');
401 if ((f = mknum(start, convch)) == NULL)
403 if (getnum(&val, &uval, signedconv))
414 case 'a': case 'A': {
417 if (getfloating(&p, mod_ldbl))
422 PF(start, (double)p);
426 warnx("illegal format character %c", convch);
430 /* return the gargv to the next element */
435 mknum(char *str, char ch)
438 static size_t copy_size;
442 len = strlen(str) + 2;
443 if (len > copy_size) {
444 newlen = ((len + 1023) >> 10) << 10;
445 if ((newcopy = realloc(copy, newlen)) == NULL)
447 warnx("%s", strerror(ENOMEM));
454 memmove(copy, str, len - 3);
457 copy[len - 1] = '\0';
462 escape(char *fmt, int percent, size_t *len)
464 char *save, *store, c;
467 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
473 case '\0': /* EOS, user error */
478 case '\\': /* backslash */
479 case '\'': /* single quote */
482 case 'a': /* bell/alert */
485 case 'b': /* backspace */
496 case 'f': /* form-feed */
499 case 'n': /* newline */
502 case 'r': /* carriage-return */
505 case 't': /* horizontal tab */
508 case 'v': /* vertical tab */
512 case '0': case '1': case '2': case '3':
513 case '4': case '5': case '6': case '7':
514 c = (!percent && *fmt == '0') ? 4 : 3;
516 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
521 if (percent && value == '%') {
525 *store = (char)value;
542 return ((int)**gargv++);
560 if (getnum(&val, &uval, 1))
563 if (val < INT_MIN || val > INT_MAX) {
564 warnx("%s: %s", *gargv, strerror(ERANGE));
572 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
581 if (**gargv == '"' || **gargv == '\'') {
591 *ip = strtoimax(*gargv, &ep, 0);
593 *uip = strtoumax(*gargv, &ep, 0);
595 warnx("%s: expected numeric value", *gargv);
598 else if (*ep != '\0') {
599 warnx("%s: not completely converted", *gargv);
602 if (errno == ERANGE) {
603 warnx("%s: %s", *gargv, strerror(ERANGE));
611 getfloating(long double *dp, int mod_ldbl)
620 if (**gargv == '"' || **gargv == '\'') {
627 *dp = strtold(*gargv, &ep);
629 *dp = strtod(*gargv, &ep);
631 warnx("%s: expected numeric value", *gargv);
633 } else if (*ep != '\0') {
634 warnx("%s: not completely converted", *gargv);
637 if (errno == ERANGE) {
638 warnx("%s: %s", *gargv, strerror(ERANGE));
652 ch = (unsigned char)**gargv;
653 if (ch == '\'' || ch == '"') {
654 memset(&mbs, 0, sizeof(mbs));
655 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
658 wch = (unsigned char)gargv[0][1];
673 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");