VirtualBox

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

Last change on this file since 2134 was 2132, checked in by bird, 16 years ago

printf.c: warning

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