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 #include <sys/types.h>
47 #define warnx1(a, b, c) warnx(a)
48 #define warnx2(a, b, c) warnx(a, b)
49 #define warnx3(a, b, c) warnx(a, b, c)
51 #define PTRDIFF(x, y) ((uintptr_t)(x) - (uintptr_t)(y))
53 #define _(x) gettext(x)
55 #define PF(f, func) do { \
59 (void) asprintf(&b, f, fieldwidth, precision, func); \
61 (void) asprintf(&b, f, fieldwidth, func); \
63 (void) asprintf(&b, f, precision, func); \
65 (void) asprintf(&b, f, func); \
67 (void) fputs(b, stdout); \
70 _NOTE(CONSTCOND) } while (0)
72 static int asciicode(void);
73 static char *doformat(char *, int *);
74 static int escape(char *, int, size_t *);
75 static int getchr(void);
76 static int getfloating(long double *, int);
77 static int getint(int *);
78 static int getnum(intmax_t *, uintmax_t *, int);
81 static char *mknum(char *, char);
82 static void usage(void);
84 static const char digits
[] = "0123456789";
89 static char **maxargv
;
92 main(int argc
, char *argv
[])
96 char *format
, *fmt
, *start
;
98 (void) setlocale(LC_ALL
, "");
104 * POSIX says: Standard utilities that do not accept options,
105 * but that do accept operands, shall recognize "--" as a
106 * first argument to be discarded.
108 if (argc
&& strcmp(argv
[0], "--") == 0) {
119 * Basic algorithm is to scan the format string for conversion
120 * specifications -- once one is found, find out if the field
121 * width or precision is a '*'; if it is, gather up value. Note,
122 * format strings are reused as necessary to use up the provided
123 * arguments, arguments of zero/null string are provided to use
124 * up the format string.
126 fmt
= format
= *argv
;
127 (void) escape(fmt
, 1, &len
); /* backslash interpretation */
135 for (myargc
= 0; gargv
[myargc
]; myargc
++)
138 while (fmt
< format
+ len
) {
140 (void) fwrite(start
, 1, PTRDIFF(fmt
, start
),
147 fmt
= doformat(fmt
, &rval
);
161 warnx1(_("missing format character"), NULL
, NULL
);
164 (void) fwrite(start
, 1, PTRDIFF(fmt
, start
), stdout
);
167 /* Restart at the beginning of the format string. */
176 doformat(char *fmt
, int *rval
)
178 static const char skip1
[] = "#'-+ 0";
179 int fieldwidth
, haveprec
, havewidth
, mod_ldbl
, precision
;
186 start
= alloca(strlen(fmt
) + 1);
194 /* look for "n$" field index specifier */
195 l
= strspn(fmt
, digits
);
196 if ((l
> 0) && (fmt
[l
] == '$')) {
199 gargv
= &myargv
[idx
- 1];
201 gargv
= &myargv
[myargc
];
203 if (gargv
> maxargv
) {
208 /* save format argument */
214 /* skip to field width */
215 while (*fmt
&& strchr(skip1
, *fmt
) != NULL
) {
224 l
= strspn(fmt
, digits
);
225 if ((l
> 0) && (fmt
[l
] == '$')) {
228 warnx1(_("incomplete use of n$"), NULL
, NULL
);
232 gargv
= &myargv
[idx
- 1];
234 gargv
= &myargv
[myargc
];
237 } else if (fargv
!= NULL
) {
238 warnx1(_("incomplete use of n$"), NULL
, NULL
);
242 if (getint(&fieldwidth
))
244 if (gargv
> maxargv
) {
254 /* skip to possible '.', get following precision */
255 while (isdigit(*fmt
)) {
262 /* precision present? */
269 l
= strspn(fmt
, digits
);
270 if ((l
> 0) && (fmt
[l
] == '$')) {
273 warnx1(_("incomplete use of n$"),
278 gargv
= &myargv
[idx
- 1];
280 gargv
= &myargv
[myargc
];
283 } else if (fargv
!= NULL
) {
284 warnx1(_("incomplete use of n$"), NULL
, NULL
);
288 if (getint(&precision
))
290 if (gargv
> maxargv
) {
299 /* skip to conversion char */
300 while (isdigit(*fmt
)) {
308 warnx1(_("missing format character"), NULL
, NULL
);
315 * Look for a length modifier. POSIX doesn't have these, so
316 * we only support them for floating-point conversions, which
317 * are extensions. This is useful because the L modifier can
318 * be used to gain extra range and precision, while omitting
319 * it is more likely to produce consistent results on different
320 * architectures. This is not so important for integers
321 * because overflow is the only bad thing that can happen to
322 * them, but consider the command printf %a 1.1
327 if (!strchr("aAeEfFgG", *fmt
)) {
328 warnx2(_("bad modifier L for %%%c"), *fmt
, NULL
);
335 /* save the current arg offset, and set to the format arg */
350 p
= strdup(getstr());
352 warnx2("%s", strerror(ENOMEM
), NULL
);
355 getout
= escape(p
, 0, &len
);
356 (void) fputs(p
, stdout
);
377 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
383 signedconv
= (convch
== 'd' || convch
== 'i');
384 if ((f
= mknum(start
, convch
)) == NULL
)
386 if (getnum(&val
, &uval
, signedconv
))
397 case 'a': case 'A': {
400 if (getfloating(&p
, mod_ldbl
))
405 PF(start
, (double)p
);
409 warnx2(_("illegal format character %c"), convch
, NULL
);
414 /* return the gargv to the next element */
419 mknum(char *str
, char ch
)
422 static size_t copy_size
;
426 len
= strlen(str
) + 2;
427 if (len
> copy_size
) {
428 newlen
= ((len
+ 1023) >> 10) << 10;
429 if ((newcopy
= realloc(copy
, newlen
)) == NULL
) {
430 warnx2("%s", strerror(ENOMEM
), NULL
);
437 (void) memmove(copy
, str
, len
- 3);
440 copy
[len
- 1] = '\0';
445 escape(char *fmt
, int percent
, size_t *len
)
447 char *save
, *store
, c
;
450 for (save
= store
= fmt
; ((c
= *fmt
) != 0); ++fmt
, ++store
) {
456 case '\0': /* EOS, user error */
459 *len
= PTRDIFF(store
, save
);
461 case '\\': /* backslash */
462 case '\'': /* single quote */
465 case 'a': /* bell/alert */
468 case 'b': /* backspace */
474 *len
= PTRDIFF(store
, save
);
479 case 'f': /* form-feed */
482 case 'n': /* newline */
485 case 'r': /* carriage-return */
488 case 't': /* horizontal tab */
491 case 'v': /* vertical tab */
495 case '0': case '1': case '2': case '3':
496 case '4': case '5': case '6': case '7':
497 c
= (!percent
&& *fmt
== '0') ? 4 : 3;
499 c
-- && *fmt
>= '0' && *fmt
<= '7'; ++fmt
) {
504 if (percent
&& value
== '%') {
508 *store
= (char)value
;
516 *len
= PTRDIFF(store
, save
);
525 return ((int)**gargv
++);
543 if (getnum(&val
, &uval
, 1))
546 if (val
< INT_MIN
|| val
> INT_MAX
) {
547 warnx3("%s: %s", *gargv
, strerror(ERANGE
));
555 getnum(intmax_t *ip
, uintmax_t *uip
, int signedconv
)
564 if (**gargv
== '"' || **gargv
== '\'') {
574 *ip
= strtoimax(*gargv
, &ep
, 0);
576 *uip
= strtoumax(*gargv
, &ep
, 0);
578 warnx2(_("%s: expected numeric value"), *gargv
, NULL
);
580 } else if (*ep
!= '\0') {
581 warnx2(_("%s: not completely converted"), *gargv
, NULL
);
584 if (errno
== ERANGE
) {
585 warnx3("%s: %s", *gargv
, strerror(ERANGE
));
593 getfloating(long double *dp
, int mod_ldbl
)
602 if (**gargv
== '"' || **gargv
== '\'') {
609 *dp
= strtold(*gargv
, &ep
);
611 *dp
= strtod(*gargv
, &ep
);
613 warnx2(_("%s: expected numeric value"), *gargv
, NULL
);
615 } else if (*ep
!= '\0') {
616 warnx2(_("%s: not completely converted"), *gargv
, NULL
);
619 if (errno
== ERANGE
) {
620 warnx3("%s: %s", *gargv
, strerror(ERANGE
));
633 if (ch
== '\'' || ch
== '"')
642 (void) fprintf(stderr
, _("usage: printf format [arguments ...]\n"));