]>
git.saurik.com Git - apple/shell_cmds.git/blob - printf/printf.c
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
35 * Important: This file is used both as a standalone program /usr/bin/printf
36 * and as a builtin for /bin/sh (#define SHELL).
41 static char const copyright
[] =
42 "@(#) Copyright (c) 1989, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
49 static char const sccsid
[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
51 static const char rcsid
[] =
55 #include <sys/types.h>
70 #define main printfcmd
71 #include "bltin/bltin.h"
75 #define PF(f, func) do { \
78 (void)printf(f, fieldwidth, precision, func); \
80 (void)printf(f, fieldwidth, func); \
82 (void)printf(f, precision, func); \
84 (void)printf(f, func); \
87 static int asciicode(void);
88 static char *printf_doformat(char *, int *);
89 static int escape(char *, int, size_t *);
90 static int getchr(void);
91 static int getfloating(long double *, int);
92 static int getint(int *);
93 static int getnum(intmax_t *, uintmax_t *, int);
96 static char *mknum(char *, char);
97 static void usage(void);
99 static const char digits
[] = "0123456789";
101 static char end_fmt
[1];
104 static char **myargv
;
106 static char **maxargv
;
109 main(int argc
, char *argv
[])
113 char *format
, *fmt
, *start
;
117 (void) setlocale(LC_ALL
, "");
122 argc
-= argptr
- argv
;
125 while ((ch
= getopt(argc
, argv
, "")) != -1)
145 * Basic algorithm is to scan the format string for conversion
146 * specifications -- once one is found, find out if the field
147 * width or precision is a '*'; if it is, gather up value. Note,
148 * format strings are reused as necessary to use up the provided
149 * arguments, arguments of zero/null string are provided to use
150 * up the format string.
152 fmt
= format
= *argv
;
153 escape(fmt
, 1, &len
); /* backslash interpretation */
161 for (myargc
= 0; gargv
[myargc
]; myargc
++)
164 while (fmt
< format
+ len
) {
166 fwrite(start
, 1, fmt
- start
, stdout
);
172 fmt
= printf_doformat(fmt
, &rval
);
173 if (fmt
== NULL
|| fmt
== end_fmt
) {
177 return (fmt
== NULL
? 1 : rval
);
190 warnx("missing format character");
196 fwrite(start
, 1, fmt
- start
, stdout
);
203 /* Restart at the beginning of the format string. */
212 printf_doformat(char *fmt
, int *rval
)
214 static const char skip1
[] = "#'-+ 0";
215 int fieldwidth
, haveprec
, havewidth
, mod_ldbl
, precision
;
217 char start
[strlen(fmt
) + 1];
228 /* look for "n$" field index specifier */
229 l
= strspn(fmt
, digits
);
230 if ((l
> 0) && (fmt
[l
] == '$')) {
233 gargv
= &myargv
[idx
- 1];
235 gargv
= &myargv
[myargc
];
241 /* save format argument */
247 /* skip to field width */
248 while (*fmt
&& strchr(skip1
, *fmt
) != NULL
) {
256 l
= strspn(fmt
, digits
);
257 if ((l
> 0) && (fmt
[l
] == '$')) {
260 warnx("incomplete use of n$");
264 gargv
= &myargv
[idx
- 1];
266 gargv
= &myargv
[myargc
];
269 } else if (fargv
!= NULL
) {
270 warnx("incomplete use of n$");
274 if (getint(&fieldwidth
))
285 /* skip to possible '.', get following precision */
286 while (isdigit(*fmt
)) {
293 /* precision present? */
300 l
= strspn(fmt
, digits
);
301 if ((l
> 0) && (fmt
[l
] == '$')) {
304 warnx("incomplete use of n$");
308 gargv
= &myargv
[idx
- 1];
310 gargv
= &myargv
[myargc
];
313 } else if (fargv
!= NULL
) {
314 warnx("incomplete use of n$");
318 if (getint(&precision
))
328 /* skip to conversion char */
329 while (isdigit(*fmt
)) {
337 warnx("missing format character");
344 * Look for a length modifier. POSIX doesn't have these, so
345 * we only support them for floating-point conversions, which
346 * are extensions. This is useful because the L modifier can
347 * be used to gain extra range and precision, while omitting
348 * it is more likely to produce consistent results on different
349 * architectures. This is not so important for integers
350 * because overflow is the only bad thing that can happen to
351 * them, but consider the command printf %a 1.1
356 if (!strchr("aAeEfFgG", *fmt
)) {
357 warnx("bad modifier L for %%%c", *fmt
);
364 /* save the current arg offset, and set to the format arg */
379 /* Convert "b" to "s" for output. */
380 start
[strlen(start
) - 1] = 's';
381 if ((p
= strdup(getstr())) == NULL
) {
382 warnx("%s", strerror(ENOMEM
));
385 getout
= escape(p
, 0, &len
);
387 * Special-case conversion of zero; print it instead of
388 * feeding an empty string to printf("%s") which would not
391 if (len
== 1 && p
[0] == '\0') {
396 /* Restore format for next loop. */
418 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
424 signedconv
= (convch
== 'd' || convch
== 'i');
425 if ((f
= mknum(start
, convch
)) == NULL
)
427 if (getnum(&val
, &uval
, signedconv
))
438 case 'a': case 'A': {
441 if (getfloating(&p
, mod_ldbl
))
446 PF(start
, (double)p
);
450 warnx("illegal format character %c", convch
);
454 /* return the gargv to the next element */
459 mknum(char *str
, char ch
)
462 static size_t copy_size
;
466 len
= strlen(str
) + 2;
467 if (len
> copy_size
) {
468 newlen
= ((len
+ 1023) >> 10) << 10;
469 if ((newcopy
= realloc(copy
, newlen
)) == NULL
) {
470 warnx("%s", strerror(ENOMEM
));
477 memmove(copy
, str
, len
- 3);
480 copy
[len
- 1] = '\0';
485 escape(char *fmt
, int percent
, size_t *len
)
487 char *save
, *store
, c
;
490 for (save
= store
= fmt
; ((c
= *fmt
) != 0); ++fmt
, ++store
) {
496 case '\0': /* EOS, user error */
501 case '\\': /* backslash */
502 case '\'': /* single quote */
505 case 'a': /* bell/alert */
508 case 'b': /* backspace */
519 case 'f': /* form-feed */
522 case 'n': /* newline */
525 case 'r': /* carriage-return */
528 case 't': /* horizontal tab */
531 case 'v': /* vertical tab */
535 case '0': case '1': case '2': case '3':
536 case '4': case '5': case '6': case '7':
537 c
= (!percent
&& *fmt
== '0') ? 4 : 3;
539 c
-- && *fmt
>= '0' && *fmt
<= '7'; ++fmt
) {
544 if (percent
&& value
== '%') {
548 *store
= (char)value
;
565 return ((int)**gargv
++);
583 if (getnum(&val
, &uval
, 1))
586 if (val
< INT_MIN
|| val
> INT_MAX
) {
587 warnx("%s: %s", *gargv
, strerror(ERANGE
));
595 getnum(intmax_t *ip
, uintmax_t *uip
, int signedconv
)
604 if (**gargv
== '"' || **gargv
== '\'') {
614 *ip
= strtoimax(*gargv
, &ep
, 0);
616 *uip
= strtoumax(*gargv
, &ep
, 0);
618 warnx("%s: expected numeric value", *gargv
);
621 else if (*ep
!= '\0') {
622 warnx("%s: not completely converted", *gargv
);
625 if (errno
== ERANGE
) {
626 warnx("%s: %s", *gargv
, strerror(ERANGE
));
634 getfloating(long double *dp
, int mod_ldbl
)
643 if (**gargv
== '"' || **gargv
== '\'') {
650 *dp
= strtold(*gargv
, &ep
);
652 *dp
= strtod(*gargv
, &ep
);
654 warnx("%s: expected numeric value", *gargv
);
656 } else if (*ep
!= '\0') {
657 warnx("%s: not completely converted", *gargv
);
660 if (errno
== ERANGE
) {
661 warnx("%s: %s", *gargv
, strerror(ERANGE
));
675 ch
= (unsigned char)**gargv
;
676 if (ch
== '\'' || ch
== '"') {
677 memset(&mbs
, 0, sizeof(mbs
));
678 switch (mbrtowc(&wch
, *gargv
+ 1, MB_LEN_MAX
, &mbs
)) {
681 wch
= (unsigned char)gargv
[0][1];
696 (void)fprintf(stderr
, "usage: printf format [arguments ...]\n");