printf.c revision 1.37.8.3 1 /* $NetBSD: printf.c,v 1.37.8.3 2018/09/23 17:16:33 martin 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.37.8.3 2018/09/23 17:16:33 martin 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 void check_conversion(const char *, const char *);
78 static void usage(void);
79
80 static void b_count(int);
81 static void b_output(int);
82 static size_t b_length;
83 static char *b_fmt;
84
85 static int rval;
86 static char **gargv;
87
88 #ifdef BUILTIN /* csh builtin */
89 #define main progprintf
90 #endif
91
92 #ifdef SHELL /* sh (aka ash) builtin */
93 #define main printfcmd
94 #include "../../bin/sh/bltin/bltin.h"
95 #endif /* SHELL */
96
97 #define PF(f, func) { \
98 if (fieldwidth != -1) { \
99 if (precision != -1) \
100 error = printf(f, fieldwidth, precision, func); \
101 else \
102 error = printf(f, fieldwidth, func); \
103 } else if (precision != -1) \
104 error = printf(f, precision, func); \
105 else \
106 error = printf(f, func); \
107 }
108
109 #define APF(cpp, f, func) { \
110 if (fieldwidth != -1) { \
111 if (precision != -1) \
112 error = asprintf(cpp, f, fieldwidth, precision, func); \
113 else \
114 error = asprintf(cpp, f, fieldwidth, func); \
115 } else if (precision != -1) \
116 error = asprintf(cpp, f, precision, func); \
117 else \
118 error = asprintf(cpp, f, func); \
119 }
120
121 #ifdef main
122 int main(int, char *[]);
123 #endif
124 int main(int argc, char *argv[])
125 {
126 char *fmt, *start;
127 int fieldwidth, precision;
128 char nextch;
129 char *format;
130 char ch;
131 int error, o;
132
133 #if !defined(SHELL) && !defined(BUILTIN)
134 (void)setlocale (LC_ALL, "");
135 #endif
136
137 rval = 0; /* clear for builtin versions (avoid holdover) */
138
139 while ((o = getopt(argc, argv, "")) != -1) {
140 switch (o) {
141 case '?':
142 default:
143 usage();
144 return 1;
145 }
146 }
147 argc -= optind;
148 argv += optind;
149
150 if (argc < 1) {
151 usage();
152 return 1;
153 }
154
155 format = *argv;
156 gargv = ++argv;
157
158 #define SKIP1 "#-+ 0'"
159 #define SKIP2 "0123456789"
160 do {
161 /*
162 * Basic algorithm is to scan the format string for conversion
163 * specifications -- once one is found, find out if the field
164 * width or precision is a '*'; if it is, gather up value.
165 * Note, format strings are reused as necessary to use up the
166 * provided arguments, arguments of zero/null string are
167 * provided to use up the format string.
168 */
169
170 /* find next format specification */
171 for (fmt = format; (ch = *fmt++) != '\0';) {
172 if (ch == '\\') {
173 char c_ch;
174 fmt = conv_escape(fmt, &c_ch, 0);
175 putchar(c_ch);
176 continue;
177 }
178 if (ch != '%' || (*fmt == '%' && ++fmt)) {
179 (void)putchar(ch);
180 continue;
181 }
182
183 /* Ok - we've found a format specification,
184 Save its address for a later printf(). */
185 start = fmt - 1;
186
187 /* skip to field width */
188 fmt += strspn(fmt, SKIP1);
189 if (*fmt == '*') {
190 fmt++;
191 fieldwidth = getwidth();
192 } else
193 fieldwidth = -1;
194
195 /* skip to possible '.', get following precision */
196 fmt += strspn(fmt, SKIP2);
197 if (*fmt == '.') {
198 fmt++;
199 if (*fmt == '*') {
200 fmt++;
201 precision = getwidth();
202 } else
203 precision = -1;
204 } else
205 precision = -1;
206
207 fmt += strspn(fmt, SKIP2);
208
209 ch = *fmt;
210 if (!ch) {
211 warnx("missing format character");
212 return (1);
213 }
214 /* null terminate format string to we can use it
215 as an argument to printf. */
216 nextch = fmt[1];
217 fmt[1] = 0;
218 switch (ch) {
219
220 case 'B': {
221 const char *p = conv_expand(getstr());
222 if (p == NULL)
223 goto out;
224 *fmt = 's';
225 PF(start, p);
226 if (error < 0)
227 goto out;
228 break;
229 }
230 case 'b': {
231 /* There has to be a better way to do this,
232 * but the string we generate might have
233 * embedded nulls. */
234 static char *a, *t;
235 char *cp = getstr();
236 /* Free on entry in case shell longjumped out */
237 if (a != NULL)
238 free(a);
239 a = NULL;
240 if (t != NULL)
241 free(t);
242 t = NULL;
243 /* Count number of bytes we want to output */
244 b_length = 0;
245 conv_escape_str(cp, b_count, 0);
246 t = malloc(b_length + 1);
247 if (t == NULL)
248 goto out;
249 (void)memset(t, 'x', b_length);
250 t[b_length] = 0;
251 /* Get printf to calculate the lengths */
252 *fmt = 's';
253 APF(&a, start, t);
254 if (error == -1)
255 goto out;
256 b_fmt = a;
257 /* Output leading spaces and data bytes */
258 conv_escape_str(cp, b_output, 1);
259 /* Add any trailing spaces */
260 printf("%s", b_fmt);
261 break;
262 }
263 case 'c': {
264 char p = getchr();
265 PF(start, p);
266 if (error < 0)
267 goto out;
268 break;
269 }
270 case 's': {
271 char *p = getstr();
272 PF(start, p);
273 if (error < 0)
274 goto out;
275 break;
276 }
277 case 'd':
278 case 'i': {
279 intmax_t p = getintmax();
280 char *f = mklong(start, ch);
281 PF(f, p);
282 if (error < 0)
283 goto out;
284 break;
285 }
286 case 'o':
287 case 'u':
288 case 'x':
289 case 'X': {
290 uintmax_t p = (uintmax_t)getintmax();
291 char *f = mklong(start, ch);
292 PF(f, p);
293 if (error < 0)
294 goto out;
295 break;
296 }
297 case 'e':
298 case 'E':
299 case 'f':
300 case 'g':
301 case 'G': {
302 double p = getdouble();
303 PF(start, p);
304 if (error < 0)
305 goto out;
306 break;
307 }
308 default:
309 warnx("%s: invalid directive", start);
310 return 1;
311 }
312 *fmt++ = ch;
313 *fmt = nextch;
314 /* escape if a \c was encountered */
315 if (rval & 0x100)
316 return rval & ~0x100;
317 }
318 } while (gargv != argv && *gargv);
319
320 return rval & ~0x100;
321 out:
322 warn("print failed");
323 return 1;
324 }
325
326 /* helper functions for conv_escape_str */
327
328 static void
329 /*ARGSUSED*/
330 b_count(int ch)
331 {
332 b_length++;
333 }
334
335 /* Output one converted character for every 'x' in the 'format' */
336
337 static void
338 b_output(int ch)
339 {
340 for (;;) {
341 switch (*b_fmt++) {
342 case 0:
343 b_fmt--;
344 return;
345 case ' ':
346 putchar(' ');
347 break;
348 default:
349 putchar(ch);
350 return;
351 }
352 }
353 }
354
355
356 /*
357 * Print SysV echo(1) style escape string
358 * Halts processing string if a \c escape is encountered.
359 */
360 static void
361 conv_escape_str(char *str, void (*do_putchar)(int), int quiet)
362 {
363 int value;
364 int ch;
365 char c;
366
367 while ((ch = *str++) != '\0') {
368 if (ch != '\\') {
369 do_putchar(ch);
370 continue;
371 }
372
373 ch = *str++;
374 if (ch == 'c') {
375 /* \c as in SYSV echo - abort all processing.... */
376 rval |= 0x100;
377 break;
378 }
379
380 /*
381 * %b string octal constants are not like those in C.
382 * They start with a \0, and are followed by 0, 1, 2,
383 * or 3 octal digits.
384 */
385 if (ch == '0') {
386 int octnum = 0, i;
387 for (i = 0; i < 3; i++) {
388 if (!isdigit((unsigned char)*str) || *str > '7')
389 break;
390 octnum = (octnum << 3) | (*str++ - '0');
391 }
392 do_putchar(octnum);
393 continue;
394 }
395
396 /* \[M][^|-]C as defined by vis(3) */
397 if (ch == 'M' && *str == '-') {
398 do_putchar(0200 | str[1]);
399 str += 2;
400 continue;
401 }
402 if (ch == 'M' && *str == '^') {
403 str++;
404 value = 0200;
405 ch = '^';
406 } else
407 value = 0;
408 if (ch == '^') {
409 ch = *str++;
410 if (ch == '?')
411 value |= 0177;
412 else
413 value |= ch & 037;
414 do_putchar(value);
415 continue;
416 }
417
418 /* Finally test for sequences valid in the format string */
419 str = conv_escape(str - 1, &c, quiet);
420 do_putchar(c);
421 }
422 }
423
424 /*
425 * Print "standard" escape characters
426 */
427 static char *
428 conv_escape(char *str, char *conv_ch, int quiet)
429 {
430 char value;
431 char ch;
432 char num_buf[4], *num_end;
433
434 ch = *str++;
435
436 switch (ch) {
437 case '\0':
438 if (!quiet)
439 warnx("incomplete escape sequence");
440 rval = 1;
441 value = '\\';
442 --str;
443 break;
444
445 case '0': case '1': case '2': case '3':
446 case '4': case '5': case '6': case '7':
447 num_buf[0] = ch;
448 ch = str[0];
449 num_buf[1] = ch;
450 num_buf[2] = (char)(ch != '\0' ? str[1] : '\0');
451 num_buf[3] = '\0';
452 value = (char)strtoul(num_buf, &num_end, 8);
453 str += num_end - (num_buf + 1);
454 break;
455
456 case 'x':
457 /* Hexadecimal character constants are not required to be
458 supported (by SuS v1) because there is no consistent
459 way to detect the end of the constant.
460 Supporting 2 byte constants is a compromise. */
461 ch = str[0];
462 num_buf[0] = ch;
463 num_buf[1] = (char)(ch != '\0' ? str[1] : '\0');
464 num_buf[2] = '\0';
465 value = (char)strtoul(num_buf, &num_end, 16);
466 str += num_end - num_buf;
467 break;
468
469 case '\\': value = '\\'; break; /* backslash */
470 case '\'': value = '\''; break; /* single quote */
471 case '"': value = '"'; break; /* double quote */
472 case 'a': value = '\a'; break; /* alert */
473 case 'b': value = '\b'; break; /* backspace */
474 case 'e': value = ESCAPE; break; /* escape */
475 case 'f': value = '\f'; break; /* form-feed */
476 case 'n': value = '\n'; break; /* newline */
477 case 'r': value = '\r'; break; /* carriage-return */
478 case 't': value = '\t'; break; /* tab */
479 case 'v': value = '\v'; break; /* vertical-tab */
480
481 default:
482 if (!quiet)
483 warnx("unknown escape sequence `\\%c'", ch);
484 rval = 1;
485 value = ch;
486 break;
487 }
488
489 *conv_ch = value;
490 return str;
491 }
492
493 /* expand a string so that everything is printable */
494
495 static char *
496 conv_expand(const char *str)
497 {
498 static char *conv_str;
499 char *cp;
500 char ch;
501
502 if (conv_str)
503 free(conv_str);
504 /* get a buffer that is definitely large enough.... */
505 conv_str = malloc(4 * strlen(str) + 1);
506 if (!conv_str)
507 return NULL;
508 cp = conv_str;
509
510 while ((ch = *(const char *)str++) != '\0') {
511 switch (ch) {
512 /* Use C escapes for expected control characters */
513 case '\\': ch = '\\'; break; /* backslash */
514 case '\'': ch = '\''; break; /* single quote */
515 case '"': ch = '"'; break; /* double quote */
516 case '\a': ch = 'a'; break; /* alert */
517 case '\b': ch = 'b'; break; /* backspace */
518 case ESCAPE: ch = 'e'; break; /* escape */
519 case '\f': ch = 'f'; break; /* form-feed */
520 case '\n': ch = 'n'; break; /* newline */
521 case '\r': ch = 'r'; break; /* carriage-return */
522 case '\t': ch = 't'; break; /* tab */
523 case '\v': ch = 'v'; break; /* vertical-tab */
524 default:
525 /* Copy anything printable */
526 if (isprint((unsigned char)ch)) {
527 *cp++ = ch;
528 continue;
529 }
530 /* Use vis(3) encodings for the rest */
531 *cp++ = '\\';
532 if (ch & 0200) {
533 *cp++ = 'M';
534 ch &= (char)~0200;
535 }
536 if (ch == 0177) {
537 *cp++ = '^';
538 *cp++ = '?';
539 continue;
540 }
541 if (ch < 040) {
542 *cp++ = '^';
543 *cp++ = ch | 0100;
544 continue;
545 }
546 *cp++ = '-';
547 *cp++ = ch;
548 continue;
549 }
550 *cp++ = '\\';
551 *cp++ = ch;
552 }
553
554 *cp = 0;
555 return conv_str;
556 }
557
558 static char *
559 mklong(const char *str, char ch)
560 {
561 static char copy[64];
562 size_t len;
563
564 len = strlen(str) + 2;
565 if (len > sizeof copy) {
566 warnx("format %s too complex", str);
567 len = 4;
568 }
569 (void)memmove(copy, str, len - 3);
570 copy[len - 3] = 'j';
571 copy[len - 2] = ch;
572 copy[len - 1] = '\0';
573 return copy;
574 }
575
576 static char
577 getchr(void)
578 {
579 if (!*gargv)
580 return 0;
581 return **gargv++;
582 }
583
584 static char *
585 getstr(void)
586 {
587 static char empty[] = "";
588 if (!*gargv)
589 return empty;
590 return *gargv++;
591 }
592
593 static int
594 getwidth(void)
595 {
596 unsigned long val;
597 char *s, *ep;
598
599 s = *gargv;
600 if (!*gargv)
601 return (0);
602 gargv++;
603
604 errno = 0;
605 val = strtoul(s, &ep, 0);
606 check_conversion(s, ep);
607
608 /* Arbitrarily 'restrict' field widths to 1Mbyte */
609 if (val > 1 << 20) {
610 warnx("%s: invalid field width", s);
611 return 0;
612 }
613
614 return (int)val;
615 }
616
617 static intmax_t
618 getintmax(void)
619 {
620 intmax_t val;
621 char *cp, *ep;
622
623 cp = *gargv;
624 if (cp == NULL)
625 return 0;
626 gargv++;
627
628 if (*cp == '\"' || *cp == '\'')
629 return *(cp + 1);
630
631 errno = 0;
632 val = strtoimax(cp, &ep, 0);
633 check_conversion(cp, ep);
634 return val;
635 }
636
637 static double
638 getdouble(void)
639 {
640 double val;
641 char *ep;
642
643 if (!*gargv)
644 return (0.0);
645
646 if (**gargv == '\"' || **gargv == '\'')
647 return (double) *((*gargv++)+1);
648
649 errno = 0;
650 val = strtod(*gargv, &ep);
651 check_conversion(*gargv++, ep);
652 return val;
653 }
654
655 static void
656 check_conversion(const char *s, const char *ep)
657 {
658 if (*ep) {
659 if (ep == s)
660 warnx("%s: expected numeric value", s);
661 else
662 warnx("%s: not completely converted", s);
663 rval = 1;
664 } else if (errno == ERANGE) {
665 warnx("%s: %s", s, strerror(ERANGE));
666 rval = 1;
667 }
668 }
669
670 static void
671 usage(void)
672 {
673 (void)fprintf(stderr, "Usage: %s format [arg ...]\n", getprogname());
674 }
675