VirtualBox

source: kBuild/trunk/src/kmk/kmkbuiltin/printf.c@ 1223

Last change on this file since 1223 was 1183, checked in by bird, 17 years ago

Added --version and --help to all builtins.

  • Property svn:eol-style set to native
File size: 14.5 KB
Line 
1/* $NetBSD: printf.c,v 1.31 2005/03/22 23:55:46 dsl 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\n\
36 The Regents of the University of California. All rights reserved.\n");
37#endif
38#endif
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)printf.c 8.2 (Berkeley) 3/22/95";
43#else
44__RCSID("$NetBSD: printf.c,v 1.31 2005/03/22 23:55:46 dsl 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 __sun__
63# include "solfakes.h"
64#endif
65#ifdef _MSC_VER
66# include "mscfakes.h"
67#endif
68
69#include "kmkbuiltin.h"
70
71
72#ifdef __GNUC__
73#define ESCAPE '\e'
74#else
75#define ESCAPE 033
76#endif
77
78
79static size_t b_length;
80static char *b_fmt;
81static int rval;
82static char **gargv;
83static struct option long_options[] =
84{
85 { "help", no_argument, 0, 261 },
86 { "version", no_argument, 0, 262 },
87 { 0, 0, 0, 0 },
88};
89
90
91static void conv_escape_str(char *, void (*)(int));
92static char *conv_escape(char *, char *);
93static char *conv_expand(const char *);
94static int getchr(void);
95static double getdouble(void);
96static int getwidth(void);
97static intmax_t getintmax(void);
98static uintmax_t getuintmax(void);
99static char *getstr(void);
100static char *mklong(const char *, int);
101static void check_conversion(const char *, const char *);
102static int usage(FILE *);
103
104static void b_count(int);
105static void b_output(int);
106
107#ifdef BUILTIN /* csh builtin */
108#define kmk_builtin_printf progprintf
109#endif
110
111#ifdef SHELL /* sh (aka ash) builtin */
112#define kmk_builtin_printf printfcmd
113#include "../../bin/sh/bltin/bltin.h"
114#endif /* SHELL */
115
116#define PF(f, func) { \
117 if (fieldwidth != -1) { \
118 if (precision != -1) \
119 (void)printf(f, fieldwidth, precision, func); \
120 else \
121 (void)printf(f, fieldwidth, func); \
122 } else if (precision != -1) \
123 (void)printf(f, precision, func); \
124 else \
125 (void)printf(f, func); \
126}
127
128#define APF(cpp, f, func) { \
129 if (fieldwidth != -1) { \
130 if (precision != -1) \
131 (void)asprintf(cpp, f, fieldwidth, precision, func); \
132 else \
133 (void)asprintf(cpp, f, fieldwidth, func); \
134 } else if (precision != -1) \
135 (void)asprintf(cpp, f, precision, func); \
136 else \
137 (void)asprintf(cpp, f, func); \
138}
139
140int kmk_builtin_printf(int argc, char *argv[], char **envp)
141{
142 char *fmt, *start;
143 int fieldwidth, precision;
144 char nextch;
145 char *format;
146 int ch;
147
148 /* kmk: reinitialize globals */
149 b_length = 0;
150 b_fmt = NULL;
151 rval = 0;
152 gargv = NULL;
153
154 /* kmk: reset getopt and set progname */
155 g_progname = argv[0];
156 opterr = 1;
157 optarg = NULL;
158 optopt = 0;
159 optind = 0; /* init */
160
161#if !defined(SHELL) && !defined(BUILTIN) && !defined(kmk_builtin_printf) /* kmk did this already. */
162 (void)setlocale (LC_ALL, "");
163#endif
164
165 while ((ch = getopt_long(argc, argv, "", long_options, NULL)) != -1) {
166 switch (ch) {
167 case 261:
168 usage(stdout);
169 return 0;
170 case 262:
171 return kbuild_version(argv[0]);
172 case '?':
173 default:
174 return usage(stderr);
175 }
176 }
177 argc -= optind;
178 argv += optind;
179
180 if (argc < 1) {
181 return usage(stderr);
182 }
183
184 format = *argv;
185 gargv = ++argv;
186
187#define SKIP1 "#-+ 0"
188#define SKIP2 "*0123456789"
189 do {
190 /*
191 * Basic algorithm is to scan the format string for conversion
192 * specifications -- once one is found, find out if the field
193 * width or precision is a '*'; if it is, gather up value.
194 * Note, format strings are reused as necessary to use up the
195 * provided arguments, arguments of zero/null string are
196 * provided to use up the format string.
197 */
198
199 /* find next format specification */
200 for (fmt = format; (ch = *fmt++) != '\0';) {
201 if (ch == '\\') {
202 char c_ch;
203 fmt = conv_escape(fmt, &c_ch);
204 putchar(c_ch);
205 continue;
206 }
207 if (ch != '%' || (*fmt == '%' && ++fmt)) {
208 (void)putchar(ch);
209 continue;
210 }
211
212 /* Ok - we've found a format specification,
213 Save its address for a later printf(). */
214 start = fmt - 1;
215
216 /* skip to field width */
217 fmt += strspn(fmt, SKIP1);
218 fieldwidth = *fmt == '*' ? getwidth() : -1;
219
220 /* skip to possible '.', get following precision */
221 fmt += strspn(fmt, SKIP2);
222 if (*fmt == '.')
223 ++fmt;
224 precision = *fmt == '*' ? getwidth() : -1;
225
226 fmt += strspn(fmt, SKIP2);
227
228 ch = *fmt;
229 if (!ch) {
230 warnx("missing format character");
231 return (1);
232 }
233 /* null terminate format string to we can use it
234 as an argument to printf. */
235 nextch = fmt[1];
236 fmt[1] = 0;
237 switch (ch) {
238
239 case 'B': {
240 const char *p = conv_expand(getstr());
241 *fmt = 's';
242 PF(start, p);
243 break;
244 }
245 case 'b': {
246 /* There has to be a better way to do this,
247 * but the string we generate might have
248 * embedded nulls. */
249 static char *a, *t;
250 char *cp = getstr();
251 /* Free on entry in case shell longjumped out */
252 if (a != NULL)
253 free(a);
254 a = NULL;
255 if (t != NULL)
256 free(t);
257 t = NULL;
258 /* Count number of bytes we want to output */
259 b_length = 0;
260 conv_escape_str(cp, b_count);
261 t = malloc(b_length + 1);
262 if (t == NULL)
263 break;
264 memset(t, 'x', b_length);
265 t[b_length] = 0;
266 /* Get printf to calculate the lengths */
267 *fmt = 's';
268 APF(&a, start, t);
269 b_fmt = a;
270 /* Output leading spaces and data bytes */
271 conv_escape_str(cp, b_output);
272 /* Add any trailing spaces */
273 printf("%s", b_fmt);
274 break;
275 }
276 case 'c': {
277 char p = getchr();
278 PF(start, p);
279 break;
280 }
281 case 's': {
282 char *p = getstr();
283 PF(start, p);
284 break;
285 }
286 case 'd':
287 case 'i': {
288 intmax_t p = getintmax();
289 char *f = mklong(start, ch);
290 PF(f, p);
291 break;
292 }
293 case 'o':
294 case 'u':
295 case 'x':
296 case 'X': {
297 uintmax_t p = getuintmax();
298 char *f = mklong(start, ch);
299 PF(f, p);
300 break;
301 }
302 case 'e':
303 case 'E':
304 case 'f':
305 case 'g':
306 case 'G': {
307 double p = getdouble();
308 PF(start, p);
309 break;
310 }
311 default:
312 warnx("%s: invalid directive", start);
313 return 1;
314 }
315 *fmt++ = ch;
316 *fmt = nextch;
317 /* escape if a \c was encountered */
318 if (rval & 0x100)
319 return rval & ~0x100;
320 }
321 } while (gargv != argv && *gargv);
322
323 return rval;
324}
325
326/* helper functions for conv_escape_str */
327
328static void
329/*ARGSUSED*/
330b_count(int ch)
331{
332 b_length++;
333}
334
335/* Output one converted character for every 'x' in the 'format' */
336
337static void
338b_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 */
360static void
361conv_escape_str(char *str, void (*do_putchar)(int))
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);
420 do_putchar(c);
421 }
422}
423
424/*
425 * Print "standard" escape characters
426 */
427static char *
428conv_escape(char *str, char *conv_ch)
429{
430 int value;
431 int ch;
432 char num_buf[4], *num_end;
433
434 ch = *str++;
435
436 switch (ch) {
437 case '0': case '1': case '2': case '3':
438 case '4': case '5': case '6': case '7':
439 num_buf[0] = ch;
440 ch = str[0];
441 num_buf[1] = ch;
442 num_buf[2] = ch ? str[1] : 0;
443 num_buf[3] = 0;
444 value = strtoul(num_buf, &num_end, 8);
445 str += num_end - (num_buf + 1);
446 break;
447
448 case 'x':
449 /* Hexadecimal character constants are not required to be
450 supported (by SuS v1) because there is no consistent
451 way to detect the end of the constant.
452 Supporting 2 byte constants is a compromise. */
453 ch = str[0];
454 num_buf[0] = ch;
455 num_buf[1] = ch ? str[1] : 0;
456 num_buf[2] = 0;
457 value = strtoul(num_buf, &num_end, 16);
458 str += num_end - num_buf;
459 break;
460
461 case '\\': value = '\\'; break; /* backslash */
462 case '\'': value = '\''; break; /* single quote */
463 case '"': value = '"'; break; /* double quote */
464 case 'a': value = '\a'; break; /* alert */
465 case 'b': value = '\b'; break; /* backspace */
466 case 'e': value = ESCAPE; break; /* escape */
467 case 'f': value = '\f'; break; /* form-feed */
468 case 'n': value = '\n'; break; /* newline */
469 case 'r': value = '\r'; break; /* carriage-return */
470 case 't': value = '\t'; break; /* tab */
471 case 'v': value = '\v'; break; /* vertical-tab */
472
473 default:
474 warnx("unknown escape sequence `\\%c'", ch);
475 rval = 1;
476 value = ch;
477 break;
478 }
479
480 *conv_ch = value;
481 return str;
482}
483
484/* expand a string so that everything is printable */
485
486static char *
487conv_expand(const char *str)
488{
489 static char *conv_str;
490 static char no_memory[] = "<no memory>";
491 char *cp;
492 int ch;
493
494 if (conv_str)
495 free(conv_str);
496 /* get a buffer that is definitely large enough.... */
497 conv_str = malloc(4 * strlen(str) + 1);
498 if (!conv_str)
499 return no_memory;
500 cp = conv_str;
501
502 while ((ch = *(const unsigned char *)str++) != '\0') {
503 switch (ch) {
504 /* Use C escapes for expected control characters */
505 case '\\': ch = '\\'; break; /* backslash */
506 case '\'': ch = '\''; break; /* single quote */
507 case '"': ch = '"'; break; /* double quote */
508 case '\a': ch = 'a'; break; /* alert */
509 case '\b': ch = 'b'; break; /* backspace */
510 case ESCAPE: ch = 'e'; break; /* escape */
511 case '\f': ch = 'f'; break; /* form-feed */
512 case '\n': ch = 'n'; break; /* newline */
513 case '\r': ch = 'r'; break; /* carriage-return */
514 case '\t': ch = 't'; break; /* tab */
515 case '\v': ch = 'v'; break; /* vertical-tab */
516 default:
517 /* Copy anything printable */
518 if (isprint(ch)) {
519 *cp++ = ch;
520 continue;
521 }
522 /* Use vis(3) encodings for the rest */
523 *cp++ = '\\';
524 if (ch & 0200) {
525 *cp++ = 'M';
526 ch &= ~0200;
527 }
528 if (ch == 0177) {
529 *cp++ = '^';
530 *cp++ = '?';
531 continue;
532 }
533 if (ch < 040) {
534 *cp++ = '^';
535 *cp++ = ch | 0100;
536 continue;
537 }
538 *cp++ = '-';
539 *cp++ = ch;
540 continue;
541 }
542 *cp++ = '\\';
543 *cp++ = ch;
544 }
545
546 *cp = 0;
547 return conv_str;
548}
549
550static char *
551mklong(const char *str, int ch)
552{
553 static char copy[64];
554 size_t len;
555
556 len = strlen(str) + 2;
557 if (len > sizeof copy) {
558 warnx("format %s too complex\n", str);
559 len = 4;
560 }
561 (void)memmove(copy, str, len - 3);
562 copy[len - 3] = 'j';
563 copy[len - 2] = ch;
564 copy[len - 1] = '\0';
565 return copy;
566}
567
568static int
569getchr(void)
570{
571 if (!*gargv)
572 return 0;
573 return (int)**gargv++;
574}
575
576static char *
577getstr(void)
578{
579 static char empty[] = "";
580 if (!*gargv)
581 return empty;
582 return *gargv++;
583}
584
585static int
586getwidth(void)
587{
588 long val;
589 char *s, *ep;
590
591 s = *gargv;
592 if (!*gargv)
593 return (0);
594 gargv++;
595
596 errno = 0;
597 val = strtoul(s, &ep, 0);
598 check_conversion(s, ep);
599
600 /* Arbitrarily 'restrict' field widths to 1Mbyte */
601 if (val < 0 || val > 1 << 20) {
602 warnx("%s: invalid field width", s);
603 return 0;
604 }
605
606 return val;
607}
608
609static intmax_t
610getintmax(void)
611{
612 intmax_t val;
613 char *cp, *ep;
614
615 cp = *gargv;
616 if (cp == NULL)
617 return 0;
618 gargv++;
619
620 if (*cp == '\"' || *cp == '\'')
621 return *(cp+1);
622
623 errno = 0;
624 val = strtoimax(cp, &ep, 0);
625 check_conversion(cp, ep);
626 return val;
627}
628
629static uintmax_t
630getuintmax(void)
631{
632 uintmax_t val;
633 char *cp, *ep;
634
635 cp = *gargv;
636 if (cp == NULL)
637 return 0;
638 gargv++;
639
640 if (*cp == '\"' || *cp == '\'')
641 return *(cp + 1);
642
643 /* strtoumax won't error -ve values */
644 while (isspace(*(unsigned char *)cp))
645 cp++;
646 if (*cp == '-') {
647 warnx("%s: expected positive numeric value", cp);
648 rval = 1;
649 return 0;
650 }
651
652 errno = 0;
653 val = strtoumax(cp, &ep, 0);
654 check_conversion(cp, ep);
655 return val;
656}
657
658static double
659getdouble(void)
660{
661 double val;
662 char *ep;
663
664 if (!*gargv)
665 return (0.0);
666
667 if (**gargv == '\"' || **gargv == '\'')
668 return (double) *((*gargv++)+1);
669
670 errno = 0;
671 val = strtod(*gargv, &ep);
672 check_conversion(*gargv++, ep);
673 return val;
674}
675
676static void
677check_conversion(const char *s, const char *ep)
678{
679 if (*ep) {
680 if (ep == s)
681 warnx("%s: expected numeric value", s);
682 else
683 warnx("%s: not completely converted", s);
684 rval = 1;
685 } else if (errno == ERANGE) {
686 warnx("%s: %s", s, strerror(ERANGE));
687 rval = 1;
688 }
689}
690
691static int
692usage(FILE *pf)
693{
694 fprintf(pf, "usage: %s format [arg ...]\n"
695 " or: %s --help\n"
696 " or: %s --version\n",
697 g_progname, g_progname, g_progname);
698 return 1;
699}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette