]>
git.saurik.com Git - apple/shell_cmds.git/blob - printf/printf.c
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
[] =
49 "$FreeBSD: head/usr.bin/printf/printf.c 279503 2015-03-01 21:46:55Z jilles $";
52 #include <sys/types.h>
67 #define main printfcmd
68 #include "bltin/bltin.h"
72 #define PF(f, func) do { \
76 (void)asprintf(&b, f, fieldwidth, precision, func); \
78 (void)asprintf(&b, f, fieldwidth, func); \
80 (void)asprintf(&b, f, precision, func); \
82 (void)asprintf(&b, f, func); \
84 (void)fputs(b, stdout); \
89 static int asciicode(void);
90 static char *printf_doformat(char *, int *);
91 static int escape(char *, int, size_t *);
92 static int getchr(void);
93 static int getfloating(long double *, int);
94 static int getint(int *);
95 static int getnum(intmax_t *, uintmax_t *, int);
98 static char *mknum(char *, char);
99 static void usage(void);
101 static const char digits
[] = "0123456789";
103 static char end_fmt
[1];
106 static char **myargv
;
108 static char **maxargv
;
111 main(int argc
, char *argv
[])
115 char *format
, *fmt
, *start
;
119 (void) setlocale(LC_ALL
, "");
124 argc
-= argptr
- argv
;
127 while ((ch
= getopt(argc
, argv
, "")) != -1)
147 * Basic algorithm is to scan the format string for conversion
148 * specifications -- once one is found, find out if the field
149 * width or precision is a '*'; if it is, gather up value. Note,
150 * format strings are reused as necessary to use up the provided
151 * arguments, arguments of zero/null string are provided to use
152 * up the format string.
154 fmt
= format
= *argv
;
155 escape(fmt
, 1, &len
); /* backslash interpretation */
163 for (myargc
= 0; gargv
[myargc
]; myargc
++)
166 while (fmt
< format
+ len
) {
168 fwrite(start
, 1, fmt
- start
, stdout
);
174 fmt
= printf_doformat(fmt
, &rval
);
175 if (fmt
== NULL
|| fmt
== end_fmt
) {
179 return (fmt
== NULL
? 1 : rval
);
192 warnx("missing format character");
198 fwrite(start
, 1, fmt
- start
, stdout
);
205 /* Restart at the beginning of the format string. */
214 printf_doformat(char *fmt
, int *rval
)
216 static const char skip1
[] = "#'-+ 0";
217 int fieldwidth
, haveprec
, havewidth
, mod_ldbl
, precision
;
219 char start
[strlen(fmt
) + 1];
230 /* look for "n$" field index specifier */
231 l
= strspn(fmt
, digits
);
232 if ((l
> 0) && (fmt
[l
] == '$')) {
235 gargv
= &myargv
[idx
- 1];
237 gargv
= &myargv
[myargc
];
243 /* save format argument */
249 /* skip to field width */
250 while (*fmt
&& strchr(skip1
, *fmt
) != NULL
) {
258 l
= strspn(fmt
, digits
);
259 if ((l
> 0) && (fmt
[l
] == '$')) {
262 warnx("incomplete use of n$");
266 gargv
= &myargv
[idx
- 1];
268 gargv
= &myargv
[myargc
];
271 } else if (fargv
!= NULL
) {
272 warnx("incomplete use of n$");
276 if (getint(&fieldwidth
))
287 /* skip to possible '.', get following precision */
288 while (isdigit(*fmt
)) {
295 /* precision present? */
302 l
= strspn(fmt
, digits
);
303 if ((l
> 0) && (fmt
[l
] == '$')) {
306 warnx("incomplete use of n$");
310 gargv
= &myargv
[idx
- 1];
312 gargv
= &myargv
[myargc
];
315 } else if (fargv
!= NULL
) {
316 warnx("incomplete use of n$");
320 if (getint(&precision
))
330 /* skip to conversion char */
331 while (isdigit(*fmt
)) {
339 warnx("missing format character");
346 * Look for a length modifier. POSIX doesn't have these, so
347 * we only support them for floating-point conversions, which
348 * are extensions. This is useful because the L modifier can
349 * be used to gain extra range and precision, while omitting
350 * it is more likely to produce consistent results on different
351 * architectures. This is not so important for integers
352 * because overflow is the only bad thing that can happen to
353 * them, but consider the command printf %a 1.1
358 if (!strchr("aAeEfFgG", *fmt
)) {
359 warnx("bad modifier L for %%%c", *fmt
);
366 /* save the current arg offset, and set to the format arg */
381 p
= strdup(getstr());
383 warnx("%s", strerror(ENOMEM
));
386 getout
= escape(p
, 0, &len
);
407 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
413 signedconv
= (convch
== 'd' || convch
== 'i');
414 if ((f
= mknum(start
, convch
)) == NULL
)
416 if (getnum(&val
, &uval
, signedconv
))
427 case 'a': case 'A': {
430 if (getfloating(&p
, mod_ldbl
))
435 PF(start
, (double)p
);
439 warnx("illegal format character %c", convch
);
443 /* return the gargv to the next element */
448 mknum(char *str
, char ch
)
451 static size_t copy_size
;
455 len
= strlen(str
) + 2;
456 if (len
> copy_size
) {
457 newlen
= ((len
+ 1023) >> 10) << 10;
458 if ((newcopy
= realloc(copy
, newlen
)) == NULL
) {
459 warnx("%s", strerror(ENOMEM
));
466 memmove(copy
, str
, len
- 3);
469 copy
[len
- 1] = '\0';
474 escape(char *fmt
, int percent
, size_t *len
)
476 char *save
, *store
, c
;
479 for (save
= store
= fmt
; ((c
= *fmt
) != 0); ++fmt
, ++store
) {
485 case '\0': /* EOS, user error */
490 case '\\': /* backslash */
491 case '\'': /* single quote */
494 case 'a': /* bell/alert */
497 case 'b': /* backspace */
508 case 'f': /* form-feed */
511 case 'n': /* newline */
514 case 'r': /* carriage-return */
517 case 't': /* horizontal tab */
520 case 'v': /* vertical tab */
524 case '0': case '1': case '2': case '3':
525 case '4': case '5': case '6': case '7':
526 c
= (!percent
&& *fmt
== '0') ? 4 : 3;
528 c
-- && *fmt
>= '0' && *fmt
<= '7'; ++fmt
) {
533 if (percent
&& value
== '%') {
537 *store
= (char)value
;
554 return ((int)**gargv
++);
572 if (getnum(&val
, &uval
, 1))
575 if (val
< INT_MIN
|| val
> INT_MAX
) {
576 warnx("%s: %s", *gargv
, strerror(ERANGE
));
584 getnum(intmax_t *ip
, uintmax_t *uip
, int signedconv
)
593 if (**gargv
== '"' || **gargv
== '\'') {
603 *ip
= strtoimax(*gargv
, &ep
, 0);
605 *uip
= strtoumax(*gargv
, &ep
, 0);
607 warnx("%s: expected numeric value", *gargv
);
610 else if (*ep
!= '\0') {
611 warnx("%s: not completely converted", *gargv
);
614 if (errno
== ERANGE
) {
615 warnx("%s: %s", *gargv
, strerror(ERANGE
));
623 getfloating(long double *dp
, int mod_ldbl
)
632 if (**gargv
== '"' || **gargv
== '\'') {
639 *dp
= strtold(*gargv
, &ep
);
641 *dp
= strtod(*gargv
, &ep
);
643 warnx("%s: expected numeric value", *gargv
);
645 } else if (*ep
!= '\0') {
646 warnx("%s: not completely converted", *gargv
);
649 if (errno
== ERANGE
) {
650 warnx("%s: %s", *gargv
, strerror(ERANGE
));
664 ch
= (unsigned char)**gargv
;
665 if (ch
== '\'' || ch
== '"') {
666 memset(&mbs
, 0, sizeof(mbs
));
667 switch (mbrtowc(&wch
, *gargv
+ 1, MB_LEN_MAX
, &mbs
)) {
670 wch
= (unsigned char)gargv
[0][1];
685 (void)fprintf(stderr
, "usage: printf format [arguments ...]\n");