printf.c revision 1.56 1 /* $NetBSD: printf.c,v 1.56 2024/08/06 07:48:16 kre Exp $ */
2
3 /*
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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.
18 *
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
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 #if !defined(BUILTIN) && !defined(SHELL)
35 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
36 The Regents of the University of California. All rights reserved.");
37 #endif
38 #endif
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)printf.c 8.2 (Berkeley) 3/22/95";
43 #else
44 __RCSID("$NetBSD: printf.c,v 1.56 2024/08/06 07:48:16 kre Exp $");
45 #endif
46 #endif /* not lint */
47
48 #include <sys/types.h>
49
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <inttypes.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61
62 #ifdef __GNUC__
63 #define ESCAPE '\e'
64 #else
65 #define ESCAPE 033
66 #endif
67
68 static void conv_escape_str(char *, void (*)(int), int);
69 static char *conv_escape(char *, char *, int);
70 static char *conv_expand(const char *);
71 static char getchr(void);
72 static double getdouble(void);
73 static int getwidth(void);
74 static intmax_t getintmax(void);
75 static char *getstr(void);
76 static char *mklong(const char *, char);
77 static intmax_t wide_char(const char *);
78 static void check_conversion(const char *, const char *);
79 static void usage(void);
80
81 static void b_count(int);
82 static void b_output(int);
83 static size_t b_length;
84 static char *b_fmt;
85
86 static int rval;
87 static char **gargv;
88
89 #ifdef BUILTIN /* csh builtin */
90 #define main progprintf
91 #endif
92
93 #ifdef SHELL /* sh (aka ash) builtin */
94 #define main printfcmd
95 #include "../../bin/sh/bltin/bltin.h"
96 #endif /* SHELL */
97
98 #define PF(f, func) { \
99 if (fieldwidth != -1) { \
100 if (precision != -1) \
101 error = printf(f, fieldwidth, precision, func); \
102 else \
103 error = printf(f, fieldwidth, func); \
104 } else if (precision != -1) \
105 error = printf(f, precision, func); \
106 else \
107 error = printf(f, func); \
108 }
109
110 #define APF(cpp, f, func) { \
111 if (fieldwidth != -1) { \
112 if (precision != -1) \
113 error = asprintf(cpp, f, fieldwidth, precision, func); \
114 else \
115 error = asprintf(cpp, f, fieldwidth, func); \
116 } else if (precision != -1) \
117 error = asprintf(cpp, f, precision, func); \
118 else \
119 error = asprintf(cpp, f, func); \
120 }
121
122 #define isodigit(c) ((c) >= '0' && (c) <= '7')
123 #define octtobin(c) ((c) - '0')
124 #define check(c, a) (c) >= (a) && (c) <= (a) + 5 ? (c) - (a) + 10
125 #define hextobin(c) (check(c, 'a') : check(c, 'A') : (c) - '0')
126 #ifdef main
127 int main(int, char *[]);
128 #endif
129
130 int
131 main(int argc, char *argv[])
132 {
133 char *fmt, *start;
134 int fieldwidth, precision;
135 char nextch;
136 char *format;
137 char ch;
138 int error;
139
140 #if !defined(SHELL) && !defined(BUILTIN)
141 (void)setlocale (LC_ALL, "");
142 #endif
143
144 rval = 0; /* clear for builtin versions (avoid holdover) */
145 clearerr(stdout); /* for the builtin version */
146
147 if (argc > 2 && strchr(argv[1], '%') == NULL) {
148 int o;
149
150 /*
151 * We only do this for argc > 2, as:
152 *
153 * for argc <= 1
154 * at best we have a bare "printf" so there cannot be
155 * any options, thus getopts() would be a waste of time.
156 * The usage() below is assured.
157 *
158 * for argc == 2
159 * There is only one arg (argv[1]) which logically must
160 * be intended to be the (required) format string for
161 * printf, without which we can do nothing so rather
162 * than usage() if it happens to start with a '-' we
163 * just avoid getopts() and treat it as a format string.
164 *
165 * Then, for argc > 2, we also skip this if there is a '%'
166 * anywhere in argv[1] as it is likely that would be intended
167 * to be the format string, rather than options, even if it
168 * starts with a '-' so we skip getopts() in that case as well.
169 *
170 * Note that this would fail should there ever be an option
171 * which takes an arbitrary string value, which could be given
172 * as -Oabc%def so should that ever become possible, remove
173 * the strchr() test above.
174 */
175
176 while ((o = getopt(argc, argv, "")) != -1) {
177 switch (o) {
178 case '?':
179 default:
180 usage();
181 return 1;
182 }
183 }
184 argc -= optind;
185 argv += optind;
186 } else {
187 argc -= 1; /* drop argv[0] (the program name) */
188 argv += 1;
189 }
190
191 if (argc < 1) { /* Nothing left at all? */
192 usage();
193 return 1;
194 }
195
196 format = *argv; /* First remaining arg is the format string */
197 gargv = ++argv; /* remaining args are for that to consume */
198
199 #define SKIP1 "#-+ 0'"
200 #define SKIP2 "0123456789"
201 do {
202 /*
203 * Basic algorithm is to scan the format string for conversion
204 * specifications -- once one is found, find out if the field
205 * width or precision is a '*'; if it is, gather up value.
206 * Note, format strings are reused as necessary to use up the
207 * provided arguments, arguments of zero/null string are
208 * provided to use up the format string.
209 */
210
211 /* find next format specification */
212 for (fmt = format; (ch = *fmt++) != '\0';) {
213 if (ch == '\\') {
214 char c_ch;
215 fmt = conv_escape(fmt, &c_ch, 0);
216 putchar(c_ch);
217 continue;
218 }
219 if (ch != '%' || (*fmt == '%' && ++fmt)) {
220 (void)putchar(ch);
221 continue;
222 }
223
224 /*
225 * Ok - we've found a format specification,
226 * Save its address for a later printf().
227 */
228 start = fmt - 1;
229
230 /* skip to field width */
231 fmt += strspn(fmt, SKIP1);
232 if (*fmt == '*') {
233 fmt++;
234 fieldwidth = getwidth();
235 } else {
236 fieldwidth = -1;
237
238 /* skip to possible '.' for precision */
239 fmt += strspn(fmt, SKIP2);
240 }
241
242 if (*fmt == '.') {
243 /* get following precision */
244 fmt++;
245 if (*fmt == '*') {
246 fmt++;
247 precision = getwidth();
248 } else {
249 precision = -1;
250 fmt += strspn(fmt, SKIP2);
251 }
252 } else
253 precision = -1;
254
255 ch = *fmt;
256 if (!ch) {
257 warnx("%s: missing format character", start);
258 return 1;
259 }
260
261 /*
262 * null terminate format string to we can use it
263 * as an argument to printf.
264 */
265 nextch = fmt[1];
266 fmt[1] = 0;
267
268 switch (ch) {
269
270 case 'B': {
271 const char *p = conv_expand(getstr());
272
273 if (p == NULL)
274 goto out;
275 *fmt = 's';
276 PF(start, p);
277 if (error < 0)
278 goto out;
279 break;
280 }
281 case 'b': {
282 /*
283 * There has to be a better way to do this,
284 * but the string we generate might have
285 * embedded nulls
286 */
287 static char *a, *t;
288 char *cp = getstr();
289
290 /* Free on entry in case shell longjumped out */
291 if (a != NULL)
292 free(a);
293 a = NULL;
294 if (t != NULL)
295 free(t);
296 t = NULL;
297
298 /* Count number of bytes we want to output */
299 b_length = 0;
300 conv_escape_str(cp, b_count, 0);
301 t = malloc(b_length + 1);
302 if (t == NULL)
303 goto out;
304 (void)memset(t, 'x', b_length);
305 t[b_length] = 0;
306
307 /* Get printf to calculate the lengths */
308 *fmt = 's';
309 APF(&a, start, t);
310 if (error == -1)
311 goto out;
312 b_fmt = a;
313
314 /* Output leading spaces and data bytes */
315 conv_escape_str(cp, b_output, 1);
316
317 /* Add any trailing spaces */
318 printf("%s", b_fmt);
319 break;
320 }
321 case 'c': {
322 char p = getchr();
323
324 PF(start, p);
325 if (error < 0)
326 goto out;
327 break;
328 }
329 case 's': {
330 char *p = getstr();
331
332 PF(start, p);
333 if (error < 0)
334 goto out;
335 break;
336 }
337 case 'd':
338 case 'i': {
339 intmax_t p = getintmax();
340 char *f = mklong(start, ch);
341
342 PF(f, p);
343 if (error < 0)
344 goto out;
345 break;
346 }
347 case 'o':
348 case 'u':
349 case 'x':
350 case 'X': {
351 uintmax_t p = (uintmax_t)getintmax();
352 char *f = mklong(start, ch);
353
354 PF(f, p);
355 if (error < 0)
356 goto out;
357 break;
358 }
359 case 'a':
360 case 'A':
361 case 'e':
362 case 'E':
363 case 'f':
364 case 'F':
365 case 'g':
366 case 'G': {
367 double p = getdouble();
368
369 PF(start, p);
370 if (error < 0)
371 goto out;
372 break;
373 }
374 case '%':
375 /* Don't ask, but this is useful ... */
376 if (fieldwidth == 'N' && precision == 'B')
377 return 0;
378 /* FALLTHROUGH */
379 default:
380 warnx("%s: invalid directive", start);
381 return 1;
382 }
383 *fmt++ = ch;
384 *fmt = nextch;
385 /* escape if a \c was encountered */
386 if (rval & 0x100)
387 goto done;
388 }
389 } while (gargv != argv && *gargv);
390
391 done:
392 (void)fflush(stdout);
393 if (ferror(stdout)) {
394 clearerr(stdout);
395 err(1, "write error");
396 }
397 return rval & ~0x100;
398 out:
399 warn("print failed");
400 return 1;
401 }
402
403 /* helper functions for conv_escape_str */
404
405 static void
406 /*ARGSUSED*/
407 b_count(int ch)
408 {
409 b_length++;
410 }
411
412 /* Output one converted character for every 'x' in the 'format' */
413
414 static void
415 b_output(int ch)
416 {
417 for (;;) {
418 switch (*b_fmt++) {
419 case 0:
420 b_fmt--;
421 return;
422 case ' ':
423 putchar(' ');
424 break;
425 default:
426 putchar(ch);
427 return;
428 }
429 }
430 }
431
432
433 /*
434 * Print SysV echo(1) style escape string
435 * Halts processing string if a \c escape is encountered.
436 */
437 static void
438 conv_escape_str(char *str, void (*do_putchar)(int), int quiet)
439 {
440 int value;
441 int ch;
442 char c;
443
444 while ((ch = *str++) != '\0') {
445 if (ch != '\\') {
446 do_putchar(ch);
447 continue;
448 }
449
450 ch = *str++;
451 if (ch == 'c') {
452 /* \c as in SYSV echo - abort all processing.... */
453 rval |= 0x100;
454 break;
455 }
456
457 /*
458 * %b string octal constants are not like those in C.
459 * They start with a \0, and are followed by 0, 1, 2,
460 * or 3 octal digits.
461 */
462 if (ch == '0') {
463 int octnum = 0, i;
464 for (i = 0; i < 3; i++) {
465 if (!isdigit((unsigned char)*str) || *str > '7')
466 break;
467 octnum = (octnum << 3) | (*str++ - '0');
468 }
469 do_putchar(octnum);
470 continue;
471 }
472
473 /* \[M][^|-]C as defined by vis(3) */
474 if (ch == 'M' && *str == '-') {
475 do_putchar(0200 | str[1]);
476 str += 2;
477 continue;
478 }
479 if (ch == 'M' && *str == '^') {
480 str++;
481 value = 0200;
482 ch = '^';
483 } else
484 value = 0;
485 if (ch == '^') {
486 ch = *str++;
487 if (ch == '?')
488 value |= 0177;
489 else
490 value |= ch & 037;
491 do_putchar(value);
492 continue;
493 }
494
495 /* Finally test for sequences valid in the format string */
496 str = conv_escape(str - 1, &c, quiet);
497 do_putchar(c);
498 }
499 }
500
501 /*
502 * Print "standard" escape characters
503 */
504 static char *
505 conv_escape(char *str, char *conv_ch, int quiet)
506 {
507 int value = 0;
508 char ch, *begin;
509 int c;
510
511 ch = *str++;
512
513 switch (ch) {
514 case '\0':
515 if (!quiet)
516 warnx("incomplete escape sequence");
517 rval = 1;
518 value = '\\';
519 --str;
520 break;
521
522 case '0': case '1': case '2': case '3':
523 case '4': case '5': case '6': case '7':
524 str--;
525 for (c = 3; c-- && isodigit(*str); str++) {
526 value <<= 3;
527 value += octtobin(*str);
528 }
529 break;
530
531 case 'x':
532 /*
533 * Hexadecimal character constants are not required to be
534 * supported (by SuS v1) because there is no consistent
535 * way to detect the end of the constant.
536 * Supporting 2 byte constants is a compromise.
537 */
538 begin = str;
539 for (c = 2; c-- && isxdigit((unsigned char)*str); str++) {
540 value <<= 4;
541 value += hextobin(*str);
542 }
543 if (str == begin) {
544 if (!quiet)
545 warnx("\\x%s: missing hexadecimal number "
546 "in escape", begin);
547 rval = 1;
548 }
549 break;
550
551 case '\\': value = '\\'; break; /* backslash */
552 case '\'': value = '\''; break; /* single quote */
553 case '"': value = '"'; break; /* double quote */
554 case 'a': value = '\a'; break; /* alert */
555 case 'b': value = '\b'; break; /* backspace */
556 case 'e': value = ESCAPE; break; /* escape */
557 case 'E': value = ESCAPE; break; /* escape */
558 case 'f': value = '\f'; break; /* form-feed */
559 case 'n': value = '\n'; break; /* newline */
560 case 'r': value = '\r'; break; /* carriage-return */
561 case 't': value = '\t'; break; /* tab */
562 case 'v': value = '\v'; break; /* vertical-tab */
563
564 default:
565 if (!quiet)
566 warnx("unknown escape sequence `\\%c'", ch);
567 rval = 1;
568 value = ch;
569 break;
570 }
571
572 *conv_ch = (char)value;
573 return str;
574 }
575
576 /* expand a string so that everything is printable */
577
578 static char *
579 conv_expand(const char *str)
580 {
581 static char *conv_str;
582 char *cp;
583 char ch;
584
585 if (conv_str)
586 free(conv_str);
587 /* get a buffer that is definitely large enough.... */
588 conv_str = malloc(4 * strlen(str) + 1);
589 if (!conv_str)
590 return NULL;
591 cp = conv_str;
592
593 while ((ch = *(const char *)str++) != '\0') {
594 switch (ch) {
595 /* Use C escapes for expected control characters */
596 case '\\': ch = '\\'; break; /* backslash */
597 case '\'': ch = '\''; break; /* single quote */
598 case '"': ch = '"'; break; /* double quote */
599 case '\a': ch = 'a'; break; /* alert */
600 case '\b': ch = 'b'; break; /* backspace */
601 case ESCAPE: ch = 'e'; break; /* escape */
602 case '\f': ch = 'f'; break; /* form-feed */
603 case '\n': ch = 'n'; break; /* newline */
604 case '\r': ch = 'r'; break; /* carriage-return */
605 case '\t': ch = 't'; break; /* tab */
606 case '\v': ch = 'v'; break; /* vertical-tab */
607 default:
608 /* Copy anything printable */
609 if (isprint((unsigned char)ch)) {
610 *cp++ = ch;
611 continue;
612 }
613 /* Use vis(3) encodings for the rest */
614 *cp++ = '\\';
615 if (ch & 0200) {
616 *cp++ = 'M';
617 ch &= (char)~0200;
618 }
619 if (ch == 0177) {
620 *cp++ = '^';
621 *cp++ = '?';
622 continue;
623 }
624 if (ch < 040) {
625 *cp++ = '^';
626 *cp++ = ch | 0100;
627 continue;
628 }
629 *cp++ = '-';
630 *cp++ = ch;
631 continue;
632 }
633 *cp++ = '\\';
634 *cp++ = ch;
635 }
636
637 *cp = 0;
638 return conv_str;
639 }
640
641 static char *
642 mklong(const char *str, char ch)
643 {
644 static char copy[64];
645 size_t len;
646
647 len = strlen(str) + 2;
648 if (len > sizeof copy) {
649 warnx("format \"%s\" too complex", str);
650 len = 4;
651 rval = 1;
652 }
653 (void)memmove(copy, str, len - 3);
654 copy[len - 3] = 'j';
655 copy[len - 2] = ch;
656 copy[len - 1] = '\0';
657 return copy;
658 }
659
660 static char
661 getchr(void)
662 {
663 if (!*gargv)
664 return 0;
665 return **gargv++;
666 }
667
668 static char *
669 getstr(void)
670 {
671 static char empty[] = "";
672 if (!*gargv)
673 return empty;
674 return *gargv++;
675 }
676
677 static int
678 getwidth(void)
679 {
680 unsigned long val;
681 char *s, *ep;
682
683 s = *gargv;
684 if (s == NULL)
685 return 0;
686 gargv++;
687
688 errno = 0;
689 val = strtoul(s, &ep, 0);
690 check_conversion(s, ep);
691
692 /* Arbitrarily 'restrict' field widths to 1Mbyte */
693 if (val > 1 << 20) {
694 warnx("%s: invalid field width", s);
695 return 0;
696 }
697
698 return (int)val;
699 }
700
701 static intmax_t
702 getintmax(void)
703 {
704 intmax_t val;
705 char *cp, *ep;
706
707 cp = *gargv;
708 if (cp == NULL)
709 return 0;
710 gargv++;
711
712 if (*cp == '\"' || *cp == '\'')
713 return wide_char(cp);
714
715 errno = 0;
716 val = strtoimax(cp, &ep, 0);
717 check_conversion(cp, ep);
718 return val;
719 }
720
721 static double
722 getdouble(void)
723 {
724 double val;
725 char *ep;
726
727 if (!*gargv)
728 return 0.0;
729
730 /* This is a NetBSD extension, not required by POSIX (it is useless) */
731 if (*(ep = *gargv) == '\"' || *ep == '\'')
732 return (double)wide_char(ep);
733
734 errno = 0;
735 val = strtod(*gargv, &ep);
736 check_conversion(*gargv++, ep);
737 return val;
738 }
739
740 /*
741 * XXX This is just a placeholder for a later version which
742 * will do mbtowc() on p+1 (and after checking that all of the
743 * string has been consumed) return that value.
744 *
745 * This (mbtowc) behaviour is required by POSIX (as is the check
746 * that the whole arg is consumed).
747 *
748 * What follows is actually correct if we assume that LC_CTYPE=C
749 * (or something else similar that is a single byte charset).
750 */
751 static intmax_t
752 wide_char(const char *p)
753 {
754 intmax_t ch = (intmax_t)(unsigned char)p[1];
755
756 if (ch != 0 && p[2] != '\0') {
757 warnx("%s: not completely converted", p);
758 rval = 1;
759 }
760
761 return ch;
762 }
763
764 static void
765 check_conversion(const char *s, const char *ep)
766 {
767 if (*ep) {
768 if (ep == s)
769 warnx("%s: expected numeric value", s);
770 else
771 warnx("%s: not completely converted", s);
772 rval = 1;
773 } else if (errno == ERANGE) {
774 warnx("%s: %s", s, strerror(ERANGE));
775 rval = 1;
776 }
777 }
778
779 static void
780 usage(void)
781 {
782 (void)fprintf(stderr, "Usage: %s format [arg ...]\n", getprogname());
783 }
784