xref: /openbsd-src/usr.bin/printf/printf.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: printf.c,v 1.14 2008/09/08 17:04:20 martynas Exp $	*/
2 
3 /*
4  * Copyright (c) 1989 The Regents of the University of California.
5  * 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 #ifndef lint
33 #if !defined(SHELL) && !defined(BUILTIN)
34 char copyright[] =
35 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
36  All rights reserved.\n";
37 #endif
38 #endif /* not lint */
39 
40 #ifndef lint
41 /*static char sccsid[] = "from: @(#)printf.c	5.9 (Berkeley) 6/1/90";*/
42 static char rcsid[] = "$OpenBSD: printf.c,v 1.14 2008/09/08 17:04:20 martynas Exp $";
43 #endif /* not lint */
44 
45 #include <ctype.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <limits.h>
50 #include <locale.h>
51 #include <errno.h>
52 #include <err.h>
53 
54 static int	 print_escape_str(const char *);
55 static int	 print_escape(const char *);
56 
57 static int	 getchr(void);
58 static double	 getdouble(void);
59 static int	 getint(void);
60 static long	 getlong(void);
61 static unsigned long getulong(void);
62 static char	*getstr(void);
63 static char	*mklong(const char *, int);
64 static void      check_conversion(const char *, const char *);
65 static void	 usage(void);
66 
67 static int	rval;
68 static char  **gargv;
69 
70 #define isodigit(c)	((c) >= '0' && (c) <= '7')
71 #define octtobin(c)	((c) - '0')
72 #define hextobin(c)	((c) >= 'A' && (c) <= 'F' ? c - 'A' + 10 : (c) >= 'a' && (c) <= 'f' ? c - 'a' + 10 : c - '0')
73 
74 #ifdef SHELL
75 #define main printfcmd
76 #include "../../bin/sh/bltin/bltin.h"
77 #include <stdarg.h>
78 
79 static void
80 warnx(const char *fmt, ...)
81 {
82 
83 	char buf[64];
84 	va_list ap;
85 
86 	va_start(ap, fmt);
87 	vsnprintf(buf, sizeof buf, fmt, ap);
88 	va_end(ap);
89 
90 	error(buf);
91 }
92 #endif /* SHELL */
93 
94 #define PF(f, func) { \
95 	if (fieldwidth) \
96 		if (precision) \
97 			(void)printf(f, fieldwidth, precision, func); \
98 		else \
99 			(void)printf(f, fieldwidth, func); \
100 	else if (precision) \
101 		(void)printf(f, precision, func); \
102 	else \
103 		(void)printf(f, func); \
104 }
105 
106 int
107 #ifdef BUILTIN
108 progprintf(int argc, char *argv[])
109 #else
110 main(int argc, char *argv[])
111 #endif
112 {
113 	char *fmt, *start;
114 	int fieldwidth, precision;
115 	char convch, nextch;
116 	char *format;
117 
118 #if !defined(SHELL) && !defined(BUILTIN)
119 	setlocale (LC_ALL, "");
120 #endif
121 
122 	/* Need to accept/ignore "--" option. */
123 	if (argc > 1 && strcmp(argv[1], "--") == 0) {
124 		argc--;
125 		argv++;
126 	}
127 
128 	if (argc < 2) {
129 		usage();
130 		return (1);
131 	}
132 
133 	format = *++argv;
134 	gargv = ++argv;
135 
136 #define SKIP1	"#-+ 0"
137 #define SKIP2	"*0123456789"
138 	do {
139 		/*
140 		 * Basic algorithm is to scan the format string for conversion
141 		 * specifications -- once one is found, find out if the field
142 		 * width or precision is a '*'; if it is, gather up value.
143 		 * Note, format strings are reused as necessary to use up the
144 		 * provided arguments, arguments of zero/null string are
145 		 * provided to use up the format string.
146 		 */
147 
148 		/* find next format specification */
149 		for (fmt = format; *fmt; fmt++) {
150 			switch (*fmt) {
151 			case '%':
152 				start = fmt++;
153 
154 				if (*fmt == '%') {
155 					putchar ('%');
156 					break;
157 				} else if (*fmt == 'b') {
158 					char *p = getstr();
159 					if (print_escape_str(p)) {
160 						return (rval);
161 					}
162 					break;
163 				}
164 
165 				/* skip to field width */
166 				for (; strchr(SKIP1, *fmt); ++fmt) ;
167 				fieldwidth = *fmt == '*' ? getint() : 0;
168 
169 				/* skip to possible '.', get following precision */
170 				for (; strchr(SKIP2, *fmt); ++fmt) ;
171 				if (*fmt == '.')
172 					++fmt;
173 				precision = *fmt == '*' ? getint() : 0;
174 
175 				for (; strchr(SKIP2, *fmt); ++fmt) ;
176 				if (!*fmt) {
177 					warnx ("missing format character");
178 					return(1);
179 				}
180 
181 				convch = *fmt;
182 				nextch = *(fmt + 1);
183 				*(fmt + 1) = '\0';
184 				switch(convch) {
185 				case 'c': {
186 					char p = getchr();
187 					PF(start, p);
188 					break;
189 				}
190 				case 's': {
191 					char *p = getstr();
192 					PF(start, p);
193 					break;
194 				}
195 				case 'd':
196 				case 'i': {
197 					long p;
198 					char *f = mklong(start, convch);
199 					if (!f) {
200 						warnx("out of memory");
201 						return (1);
202 					}
203 					p = getlong();
204 					PF(f, p);
205 					break;
206 				}
207 				case 'o':
208 				case 'u':
209 				case 'x':
210 				case 'X': {
211 					unsigned long p;
212 					char *f = mklong(start, convch);
213 					if (!f) {
214 						warnx("out of memory");
215 						return (1);
216 					}
217 					p = getulong();
218 					PF(f, p);
219 					break;
220 				}
221 				case 'a':
222 				case 'A':
223 				case 'e':
224 				case 'E':
225 				case 'f':
226 				case 'F':
227 				case 'g':
228 				case 'G': {
229 					double p = getdouble();
230 					PF(start, p);
231 					break;
232 				}
233 				default:
234 					warnx ("%s: invalid directive", start);
235 					return(1);
236 				}
237 				*(fmt + 1) = nextch;
238 				break;
239 
240 			case '\\':
241 				fmt += print_escape(fmt);
242 				break;
243 
244 			default:
245 				putchar (*fmt);
246 				break;
247 			}
248 		}
249 	} while (gargv > argv && *gargv);
250 
251 	return (rval);
252 }
253 
254 
255 /*
256  * Print SysV echo(1) style escape string
257  *	Halts processing string and returns 1 if a \c escape is encountered.
258  */
259 static int
260 print_escape_str(const char *str)
261 {
262 	int value;
263 	int c;
264 
265 	while (*str) {
266 		if (*str == '\\') {
267 			str++;
268 			/*
269 			 * %b string octal constants are not like those in C.
270 			 * They start with a \0, and are followed by 0, 1, 2,
271 			 * or 3 octal digits.
272 			 */
273 			if (*str == '0') {
274 				str++;
275 				for (c = 3, value = 0; c-- && isodigit(*str); str++) {
276 					value <<= 3;
277 					value += octtobin(*str);
278 				}
279 				putchar (value);
280 				str--;
281 			} else if (*str == 'c') {
282 				return 1;
283 			} else {
284 				str--;
285 				str += print_escape(str);
286 			}
287 		} else {
288 			putchar (*str);
289 		}
290 		str++;
291 	}
292 
293 	return 0;
294 }
295 
296 /*
297  * Print "standard" escape characters
298  */
299 static int
300 print_escape(const char *str)
301 {
302 	const char *start = str;
303 	int value;
304 	int c;
305 
306 	str++;
307 
308 	switch (*str) {
309 	case '0': case '1': case '2': case '3':
310 	case '4': case '5': case '6': case '7':
311 		for (c = 3, value = 0; c-- && isodigit(*str); str++) {
312 			value <<= 3;
313 			value += octtobin(*str);
314 		}
315 		putchar(value);
316 		return str - start - 1;
317 		/* NOTREACHED */
318 
319 	case 'x':
320 		str++;
321 		for (value = 0; isxdigit(*str); str++) {
322 			value <<= 4;
323 			value += hextobin(*str);
324 		}
325 		if (value > UCHAR_MAX) {
326 			warnx ("escape sequence out of range for character");
327 			rval = 1;
328 		}
329 		putchar (value);
330 		return str - start - 1;
331 		/* NOTREACHED */
332 
333 	case '\\':			/* backslash */
334 		putchar('\\');
335 		break;
336 
337 	case '\'':			/* single quote */
338 		putchar('\'');
339 		break;
340 
341 	case '"':			/* double quote */
342 		putchar('"');
343 		break;
344 
345 	case 'a':			/* alert */
346 		putchar('\a');
347 		break;
348 
349 	case 'b':			/* backspace */
350 		putchar('\b');
351 		break;
352 
353 	case 'e':			/* escape */
354 #ifdef __GNUC__
355 		putchar('\e');
356 #else
357 		putchar(033);
358 #endif
359 		break;
360 
361 	case 'f':			/* form-feed */
362 		putchar('\f');
363 		break;
364 
365 	case 'n':			/* newline */
366 		putchar('\n');
367 		break;
368 
369 	case 'r':			/* carriage-return */
370 		putchar('\r');
371 		break;
372 
373 	case 't':			/* tab */
374 		putchar('\t');
375 		break;
376 
377 	case 'v':			/* vertical-tab */
378 		putchar('\v');
379 		break;
380 
381 	default:
382 		putchar(*str);
383 		warnx("unknown escape sequence `\\%c'", *str);
384 		rval = 1;
385 	}
386 
387 	return 1;
388 }
389 
390 static char *
391 mklong(const char *str, int ch)
392 {
393 	static char *copy;
394 	static int copysize;
395 	int len;
396 
397 	len = strlen(str) + 2;
398 	if (copysize < len) {
399 		char *newcopy;
400 		copysize = len + 256;
401 
402 		newcopy = realloc(copy, copysize);
403 		if (newcopy == NULL) {
404 			copysize = 0;
405 			free(copy);
406 			copy = NULL;
407 			return (NULL);
408 		}
409 		copy = newcopy;
410 	}
411 	(void) memmove(copy, str, len - 3);
412 	copy[len - 3] = 'l';
413 	copy[len - 2] = ch;
414 	copy[len - 1] = '\0';
415 	return (copy);
416 }
417 
418 static int
419 getchr(void)
420 {
421 	if (!*gargv)
422 		return((int)'\0');
423 	return((int)**gargv++);
424 }
425 
426 static char *
427 getstr(void)
428 {
429 	if (!*gargv)
430 		return("");
431 	return(*gargv++);
432 }
433 
434 static char *number = "+-.0123456789";
435 static int
436 getint(void)
437 {
438 	if (!*gargv)
439 		return(0);
440 
441 	if (strchr(number, **gargv))
442 		return(atoi(*gargv++));
443 
444 	return 0;
445 }
446 
447 static long
448 getlong(void)
449 {
450 	long val;
451 	char *ep;
452 
453 	if (!*gargv)
454 		return(0L);
455 
456 	if (**gargv == '\"' || **gargv == '\'')
457 		return (long) *((*gargv++)+1);
458 
459 	errno = 0;
460 	val = strtol (*gargv, &ep, 0);
461 	check_conversion(*gargv++, ep);
462 	return val;
463 }
464 
465 static unsigned long
466 getulong(void)
467 {
468 	unsigned long val;
469 	char *ep;
470 
471 	if (!*gargv)
472 		return(0UL);
473 
474 	if (**gargv == '\"' || **gargv == '\'')
475 		return (unsigned long) *((*gargv++)+1);
476 
477 	errno = 0;
478 	val = strtoul (*gargv, &ep, 0);
479 	check_conversion(*gargv++, ep);
480 	return val;
481 }
482 
483 static double
484 getdouble(void)
485 {
486 	double val;
487 	char *ep;
488 
489 	if (!*gargv)
490 		return(0.0);
491 
492 	if (**gargv == '\"' || **gargv == '\'')
493 		return (double) *((*gargv++)+1);
494 
495 	errno = 0;
496 	val = strtod (*gargv, &ep);
497 	check_conversion(*gargv++, ep);
498 	return val;
499 }
500 
501 static void
502 check_conversion(const char *s, const char *ep)
503 {
504 	if (*ep) {
505 		if (ep == s)
506 			warnx ("%s: expected numeric value", s);
507 		else
508 			warnx ("%s: not completely converted", s);
509 		rval = 1;
510 	} else if (errno == ERANGE) {
511 		warnx ("%s: %s", s, strerror(ERANGE));
512 		rval = 1;
513 	}
514 }
515 
516 static void
517 usage(void)
518 {
519 	(void)fprintf(stderr, "usage: printf format [arg ...]\n");
520 }
521