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
34 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
35 * @(#)printf.c 8.1 (Berkeley) 7/20/93
36 * $FreeBSD: head/usr.bin/printf/printf.c 337618 2018-08-11 11:13:34Z jilles $
39 * Important: This file is used both as a standalone program /usr/bin/printf
40 * and as a builtin for /bin/sh (#define SHELL).
43 #include <sys/types.h>
58 #define main printfcmd
59 #include "bltin/bltin.h"
63 #define PF(f, func) do { \
66 printf(f, fieldwidth, precision, func); \
68 printf(f, fieldwidth, func); \
70 printf(f, precision, func); \
75 static int asciicode(void);
76 static char *printf_doformat(char *, int *);
77 static int escape(char *, int, size_t *);
78 static int getchr(void);
79 static int getfloating(long double *, int);
80 static int getint(int *);
81 static int getnum(intmax_t *, uintmax_t *, int);
84 static char *mknum(char *, char);
85 static void usage(void);
87 static const char digits
[] = "0123456789";
89 static char end_fmt
[1];
94 static char **maxargv
;
97 main(int argc
, char *argv
[])
101 char *format
, *fmt
, *start
;
104 setlocale(LC_ALL
, "");
108 * We may not use getopt(3) because calling
109 * "printf -f%s oo" may not result in an invalid
111 * However common usage and other implementations seem
112 * to indicate that we need to allow -- as a discardable
115 if (argc
> 1 && strcmp(argv
[1], "--") == 0) {
131 * Basic algorithm is to scan the format string for conversion
132 * specifications -- once one is found, find out if the field
133 * width or precision is a '*'; if it is, gather up value. Note,
134 * format strings are reused as necessary to use up the provided
135 * arguments, arguments of zero/null string are provided to use
136 * up the format string.
138 fmt
= format
= *argv
;
139 escape(fmt
, 1, &len
); /* backslash interpretation */
147 for (myargc
= 0; gargv
[myargc
]; myargc
++)
150 while (fmt
< format
+ len
) {
152 fwrite(start
, 1, fmt
- start
, stdout
);
158 fmt
= printf_doformat(fmt
, &rval
);
159 if (fmt
== NULL
|| fmt
== end_fmt
) {
163 return (fmt
== NULL
? 1 : rval
);
176 warnx("missing format character");
182 fwrite(start
, 1, fmt
- start
, stdout
);
189 /* Restart at the beginning of the format string. */
198 printf_doformat(char *fmt
, int *rval
)
200 static const char skip1
[] = "#'-+ 0";
201 int fieldwidth
, haveprec
, havewidth
, mod_ldbl
, precision
;
203 char start
[strlen(fmt
) + 1];
214 /* look for "n$" field index specifier */
215 l
= strspn(fmt
, digits
);
216 if ((l
> 0) && (fmt
[l
] == '$')) {
219 gargv
= &myargv
[idx
- 1];
221 gargv
= &myargv
[myargc
];
227 /* save format argument */
233 /* skip to field width */
234 while (*fmt
&& strchr(skip1
, *fmt
) != NULL
) {
242 l
= strspn(fmt
, digits
);
243 if ((l
> 0) && (fmt
[l
] == '$')) {
246 warnx("incomplete use of n$");
250 gargv
= &myargv
[idx
- 1];
252 gargv
= &myargv
[myargc
];
255 } else if (fargv
!= NULL
) {
256 warnx("incomplete use of n$");
260 if (getint(&fieldwidth
))
271 /* skip to possible '.', get following precision */
272 while (isdigit(*fmt
)) {
279 /* precision present? */
286 l
= strspn(fmt
, digits
);
287 if ((l
> 0) && (fmt
[l
] == '$')) {
290 warnx("incomplete use of n$");
294 gargv
= &myargv
[idx
- 1];
296 gargv
= &myargv
[myargc
];
299 } else if (fargv
!= NULL
) {
300 warnx("incomplete use of n$");
304 if (getint(&precision
))
314 /* skip to conversion char */
315 while (isdigit(*fmt
)) {
323 warnx("missing format character");
330 * Look for a length modifier. POSIX doesn't have these, so
331 * we only support them for floating-point conversions, which
332 * are extensions. This is useful because the L modifier can
333 * be used to gain extra range and precision, while omitting
334 * it is more likely to produce consistent results on different
335 * architectures. This is not so important for integers
336 * because overflow is the only bad thing that can happen to
337 * them, but consider the command printf %a 1.1
342 if (!strchr("aAeEfFgG", *fmt
)) {
343 warnx("bad modifier L for %%%c", *fmt
);
350 /* save the current arg offset, and set to the format arg */
365 /* Convert "b" to "s" for output. */
366 start
[strlen(start
) - 1] = 's';
367 if ((p
= strdup(getstr())) == NULL
) {
368 warnx("%s", strerror(ENOMEM
));
371 getout
= escape(p
, 0, &len
);
373 /* Restore format for next loop. */
395 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
401 signedconv
= (convch
== 'd' || convch
== 'i');
402 if ((f
= mknum(start
, convch
)) == NULL
)
404 if (getnum(&val
, &uval
, signedconv
))
415 case 'a': case 'A': {
418 if (getfloating(&p
, mod_ldbl
))
423 PF(start
, (double)p
);
427 warnx("illegal format character %c", convch
);
431 /* return the gargv to the next element */
436 mknum(char *str
, char ch
)
439 static size_t copy_size
;
443 len
= strlen(str
) + 2;
444 if (len
> copy_size
) {
445 newlen
= ((len
+ 1023) >> 10) << 10;
446 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 fprintf(stderr
, "usage: printf format [arguments ...]\n");