xref: /freebsd/usr.bin/printf/printf.c (revision 5ebc7e6281887681c3a348a5a4c902e262ccd656)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #if !defined(BUILTIN) && !defined(SHELL)
35 #ifndef lint
36 static char copyright[] =
37 "@(#) Copyright (c) 1989, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 #endif
41 
42 #ifndef lint
43 static char sccsid[] = "@(#)printf.c	8.1 (Berkeley) 7/20/93";
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <limits.h>
51 #ifdef SHELL
52 #define	EOF	-1
53 #else
54 #include <stdio.h>
55 #endif
56 #include <stdlib.h>
57 #include <string.h>
58 
59 /*
60  * XXX
61  * This *has* to go away.  TK.
62  */
63 #ifdef SHELL
64 #define main printfcmd
65 #define warnx(a, b, c) {						\
66 	char buf[64];							\
67 	(void)sprintf(buf, sizeof(buf), a, b, c);			\
68 	error(buf);							\
69 }
70 #include "../../bin/sh/bltin/bltin.h"
71 #endif
72 
73 #define PF(f, func) { \
74 	if (fieldwidth) \
75 		if (precision) \
76 			(void)printf(f, fieldwidth, precision, func); \
77 		else \
78 			(void)printf(f, fieldwidth, func); \
79 	else if (precision) \
80 		(void)printf(f, precision, func); \
81 	else \
82 		(void)printf(f, func); \
83 }
84 
85 static int	 asciicode __P((void));
86 static void	 escape __P((char *));
87 static int	 getchr __P((void));
88 static double	 getdouble __P((void));
89 static int	 getint __P((int *));
90 static int	 getlong __P((long *));
91 static char	*getstr __P((void));
92 static char	*mklong __P((char *, int));
93 static void	 usage __P((void));
94 
95 static char **gargv;
96 
97 int
98 #ifdef BUILTIN
99 progprintf(argc, argv)
100 #else
101 main(argc, argv)
102 #endif
103 	int argc;
104 	char *argv[];
105 {
106 	extern int optind;
107 	static char *skip1, *skip2;
108 	int ch, end, fieldwidth, precision;
109 	char convch, nextch, *format, *fmt, *start;
110 
111 	while ((ch = getopt(argc, argv, "")) != EOF)
112 		switch (ch) {
113 		case '?':
114 		default:
115 			usage();
116 			return (1);
117 		}
118 	argc -= optind;
119 	argv += optind;
120 
121 	if (argc < 1) {
122 		usage();
123 		return (1);
124 	}
125 
126 	/*
127 	 * Basic algorithm is to scan the format string for conversion
128 	 * specifications -- once one is found, find out if the field
129 	 * width or precision is a '*'; if it is, gather up value.  Note,
130 	 * format strings are reused as necessary to use up the provided
131 	 * arguments, arguments of zero/null string are provided to use
132 	 * up the format string.
133 	 */
134 	skip1 = "#-+ 0";
135 	skip2 = "0123456789";
136 
137 	escape(fmt = format = *argv);		/* backslash interpretation */
138 	gargv = ++argv;
139 	for (;;) {
140 		end = 0;
141 		/* find next format specification */
142 next:		for (start = fmt;; ++fmt) {
143 			if (!*fmt) {
144 				/* avoid infinite loop */
145 				if (end == 1) {
146 					warnx("missing format character",
147 					    NULL, NULL);
148 					return (1);
149 				}
150 				end = 1;
151 				if (fmt > start)
152 					(void)printf("%s", start);
153 				if (!*gargv)
154 					return (0);
155 				fmt = format;
156 				goto next;
157 			}
158 			/* %% prints a % */
159 			if (*fmt == '%') {
160 				if (*++fmt != '%')
161 					break;
162 				*fmt++ = '\0';
163 				(void)printf("%s", start);
164 				goto next;
165 			}
166 		}
167 
168 		/* skip to field width */
169 		for (; strchr(skip1, *fmt); ++fmt);
170 		if (*fmt == '*') {
171 			if (getint(&fieldwidth))
172 				return (1);
173 			++fmt;
174 		} else {
175 			fieldwidth = 0;
176 
177 			/* skip to possible '.', get following precision */
178 			for (; strchr(skip2, *fmt); ++fmt);
179 		}
180 		if (*fmt == '.') {
181 			/* precision present? */
182 			++fmt;
183 			if (*fmt == '*') {
184 				if (getint(&precision))
185 					return (1);
186 				++fmt;
187 			} else {
188 				precision = 0;
189 
190 				/* skip to conversion char */
191 				for (; strchr(skip2, *fmt); ++fmt);
192 			}
193 		} else
194 			precision = 0;
195 		if (!*fmt) {
196 			warnx("missing format character", NULL, NULL);
197 			return (1);
198 		}
199 
200 		convch = *fmt;
201 		nextch = *++fmt;
202 		*fmt = '\0';
203 		switch(convch) {
204 		case 'c': {
205 			char p;
206 
207 			p = getchr();
208 			PF(start, p);
209 			break;
210 		}
211 		case 's': {
212 			char *p;
213 
214 			p = getstr();
215 			PF(start, p);
216 			break;
217 		}
218 		case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
219 			long p;
220 			char *f;
221 
222 			if ((f = mklong(start, convch)) == NULL)
223 				return (1);
224 			if (getlong(&p))
225 				return (1);
226 			PF(f, p);
227 			break;
228 		}
229 		case 'e': case 'E': case 'f': case 'g': case 'G': {
230 			double p;
231 
232 			p = getdouble();
233 			PF(start, p);
234 			break;
235 		}
236 		default:
237 			warnx("illegal format character %c",  convch, NULL);
238 			return (1);
239 		}
240 		*fmt = nextch;
241 	}
242 	/* NOTREACHED */
243 }
244 
245 static char *
246 mklong(str, ch)
247 	char *str;
248 	int ch;
249 {
250 	static char copy[64];
251 	int len;
252 
253 	len = strlen(str) + 2;
254 	memmove(copy, str, len - 3);
255 	copy[len - 3] = 'l';
256 	copy[len - 2] = ch;
257 	copy[len - 1] = '\0';
258 	return (copy);
259 }
260 
261 static void
262 escape(fmt)
263 	register char *fmt;
264 {
265 	register char *store;
266 	register int value, c;
267 
268 	for (store = fmt; c = *fmt; ++fmt, ++store) {
269 		if (c != '\\') {
270 			*store = c;
271 			continue;
272 		}
273 		switch (*++fmt) {
274 		case '\0':		/* EOS, user error */
275 			*store = '\\';
276 			*++store = '\0';
277 			return;
278 		case '\\':		/* backslash */
279 		case '\'':		/* single quote */
280 			*store = *fmt;
281 			break;
282 		case 'a':		/* bell/alert */
283 			*store = '\7';
284 			break;
285 		case 'b':		/* backspace */
286 			*store = '\b';
287 			break;
288 		case 'f':		/* form-feed */
289 			*store = '\f';
290 			break;
291 		case 'n':		/* newline */
292 			*store = '\n';
293 			break;
294 		case 'r':		/* carriage-return */
295 			*store = '\r';
296 			break;
297 		case 't':		/* horizontal tab */
298 			*store = '\t';
299 			break;
300 		case 'v':		/* vertical tab */
301 			*store = '\13';
302 			break;
303 					/* octal constant */
304 		case '0': case '1': case '2': case '3':
305 		case '4': case '5': case '6': case '7':
306 			for (c = 3, value = 0;
307 			    c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
308 				value <<= 3;
309 				value += *fmt - '0';
310 			}
311 			--fmt;
312 			*store = value;
313 			break;
314 		default:
315 			*store = *fmt;
316 			break;
317 		}
318 	}
319 	*store = '\0';
320 }
321 
322 static int
323 getchr()
324 {
325 	if (!*gargv)
326 		return ('\0');
327 	return ((int)**gargv++);
328 }
329 
330 static char *
331 getstr()
332 {
333 	if (!*gargv)
334 		return ("");
335 	return (*gargv++);
336 }
337 
338 static char *Number = "+-.0123456789";
339 static int
340 getint(ip)
341 	int *ip;
342 {
343 	long val;
344 
345 	if (getlong(&val))
346 		return (1);
347 	if (val > INT_MAX) {
348 		warnx("%s: %s", *gargv, strerror(ERANGE));
349 		return (1);
350 	}
351 	*ip = val;
352 	return (0);
353 }
354 
355 static int
356 getlong(lp)
357 	long *lp;
358 {
359 	long val;
360 	char *ep;
361 
362 	if (!*gargv) {
363 		*lp = 0;
364 		return (0);
365 	}
366 	if (strchr(Number, **gargv)) {
367 		errno = 0;
368 		val = strtol(*gargv, &ep, 0);
369 		if (*ep != '\0') {
370 			warnx("%s: illegal number", *gargv, NULL);
371 			return (1);
372 		}
373 		if (errno == ERANGE)
374 			if (val == LONG_MAX) {
375 				warnx("%s: %s", *gargv, strerror(ERANGE));
376 				return (1);
377 			}
378 			if (val == LONG_MIN) {
379 				warnx("%s: %s", *gargv, strerror(ERANGE));
380 				return (1);
381 			}
382 
383 		*lp = val;
384 		++gargv;
385 		return (0);
386 	}
387 	*lp =  (long)asciicode();
388 	return (0);
389 }
390 
391 static double
392 getdouble()
393 {
394 	if (!*gargv)
395 		return ((double)0);
396 	if (strchr(Number, **gargv))
397 		return (atof(*gargv++));
398 	return ((double)asciicode());
399 }
400 
401 static int
402 asciicode()
403 {
404 	register int ch;
405 
406 	ch = **gargv;
407 	if (ch == '\'' || ch == '"')
408 		ch = (*gargv)[1];
409 	++gargv;
410 	return (ch);
411 }
412 
413 static void
414 usage()
415 {
416 	(void)fprintf(stderr, "usage: printf format [arg ...]\n");
417 }
418