VirtualBox

source: kBuild/trunk/src/kash/bltin/printf.c@ 2289

Last change on this file since 2289 was 1233, checked in by bird, 17 years ago

keywords.

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