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 * 3. 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
31 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
32 * @(#)printf.c 8.1 (Berkeley) 7/20/93
33 * $FreeBSD: head/usr.bin/printf/printf.c 279503 2015-03-01 21:46:55Z jilles $
36 * Important: This file is used both as a standalone program /usr/bin/printf
37 * and as a builtin for /bin/sh (#define SHELL).
40 #include <sys/types.h>
55 #define main printfcmd
56 #include "bltin/bltin.h"
60 #define PF(f, func) do { \
64 asprintf(&b, f, fieldwidth, precision, func); \
66 asprintf(&b, f, fieldwidth, func); \
68 asprintf(&b, f, precision, func); \
70 asprintf(&b, f, func); \
77 static int asciicode(void);
78 static char *printf_doformat(char *, int *);
79 static int escape(char *, int, size_t *);
80 static int getchr(void);
81 static int getfloating(long double *, int);
82 static int getint(int *);
83 static int getnum(intmax_t *, uintmax_t *, int);
86 static char *mknum(char *, char);
87 static void usage(void);
89 static const char digits
[] = "0123456789";
91 static char end_fmt
[1];
96 static char **maxargv
;
99 main(int argc
, char *argv
[])
103 char *format
, *fmt
, *start
;
106 setlocale(LC_ALL
, "");
110 * We may not use getopt(3) because calling
111 * "printf -f%s oo" may not result in an invalid
113 * However common usage and other implementations seem
114 * to indicate that we need to allow -- as a discardable
117 if (argc
> 1 && strcmp(argv
[1], "--") == 0) {
133 * Basic algorithm is to scan the format string for conversion
134 * specifications -- once one is found, find out if the field
135 * width or precision is a '*'; if it is, gather up value. Note,
136 * format strings are reused as necessary to use up the provided
137 * arguments, arguments of zero/null string are provided to use
138 * up the format string.
140 fmt
= format
= *argv
;
141 escape(fmt
, 1, &len
); /* backslash interpretation */
149 for (myargc
= 0; gargv
[myargc
]; myargc
++)
152 while (fmt
< format
+ len
) {
154 fwrite(start
, 1, fmt
- start
, stdout
);
160 fmt
= printf_doformat(fmt
, &rval
);
161 if (fmt
== NULL
|| fmt
== end_fmt
) {
165 return (fmt
== NULL
? 1 : rval
);
178 warnx("missing format character");
184 fwrite(start
, 1, fmt
- start
, stdout
);
191 /* Restart at the beginning of the format string. */
200 printf_doformat(char *fmt
, int *rval
)
202 static const char skip1
[] = "#'-+ 0";
203 int fieldwidth
, haveprec
, havewidth
, mod_ldbl
, precision
;
205 char start
[strlen(fmt
) + 1];
216 /* look for "n$" field index specifier */
217 l
= strspn(fmt
, digits
);
218 if ((l
> 0) && (fmt
[l
] == '$')) {
221 gargv
= &myargv
[idx
- 1];
223 gargv
= &myargv
[myargc
];
229 /* save format argument */
235 /* skip to field width */
236 while (*fmt
&& strchr(skip1
, *fmt
) != NULL
) {
244 l
= strspn(fmt
, digits
);
245 if ((l
> 0) && (fmt
[l
] == '$')) {
248 warnx("incomplete use of n$");
252 gargv
= &myargv
[idx
- 1];
254 gargv
= &myargv
[myargc
];
257 } else if (fargv
!= NULL
) {
258 warnx("incomplete use of n$");
262 if (getint(&fieldwidth
))
273 /* skip to possible '.', get following precision */
274 while (isdigit(*fmt
)) {
281 /* precision present? */
288 l
= strspn(fmt
, digits
);
289 if ((l
> 0) && (fmt
[l
] == '$')) {
292 warnx("incomplete use of n$");
296 gargv
= &myargv
[idx
- 1];
298 gargv
= &myargv
[myargc
];
301 } else if (fargv
!= NULL
) {
302 warnx("incomplete use of n$");
306 if (getint(&precision
))
316 /* skip to conversion char */
317 while (isdigit(*fmt
)) {
325 warnx("missing format character");
332 * Look for a length modifier. POSIX doesn't have these, so
333 * we only support them for floating-point conversions, which
334 * are extensions. This is useful because the L modifier can
335 * be used to gain extra range and precision, while omitting
336 * it is more likely to produce consistent results on different
337 * architectures. This is not so important for integers
338 * because overflow is the only bad thing that can happen to
339 * them, but consider the command printf %a 1.1
344 if (!strchr("aAeEfFgG", *fmt
)) {
345 warnx("bad modifier L for %%%c", *fmt
);
352 /* save the current arg offset, and set to the format arg */
367 p
= strdup(getstr());
369 warnx("%s", strerror(ENOMEM
));
372 getout
= escape(p
, 0, &len
);
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 fprintf(stderr
, "usage: printf format [arguments ...]\n");