VirtualBox

source: kBuild/trunk/src/gmakenew/kmkbuiltin/printf.c@ 902

Last change on this file since 902 was 813, checked in by bird, 18 years ago

Some property fixes.

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