xref: /freebsd/usr.bin/printf/printf.c (revision c68159a6d8eede11766cf13896d0f7670dbd51aa)
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 const 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 #if 0
44 static char const sccsid[] = "@(#)printf.c	8.1 (Berkeley) 7/20/93";
45 #endif
46 static const char rcsid[] =
47   "$FreeBSD$";
48 #endif /* not lint */
49 
50 #include <sys/types.h>
51 
52 #include <err.h>
53 #include <errno.h>
54 #include <limits.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 
60 #ifdef SHELL
61 #define main printfcmd
62 #include "bltin/bltin.h"
63 #include "memalloc.h"
64 #else
65 #define	warnx1(a, b, c)		warnx(a)
66 #define	warnx2(a, b, c)		warnx(a, b)
67 #define	warnx3(a, b, c)		warnx(a, b, c)
68 #endif
69 
70 #define PF(f, func) { \
71 	char *b = NULL; \
72 	if (fieldwidth) \
73 		if (precision) \
74 			(void)asprintf(&b, f, fieldwidth, precision, func); \
75 		else \
76 			(void)asprintf(&b, f, fieldwidth, func); \
77 	else if (precision) \
78 		(void)asprintf(&b, f, precision, func); \
79 	else \
80 		(void)asprintf(&b, f, func); \
81 	if (b) { \
82 		(void)fputs(b, stdout); \
83 		free(b); \
84 	} \
85 }
86 
87 static int	 asciicode __P((void));
88 static void	 escape __P((char *));
89 static int	 getchr __P((void));
90 static double	 getdouble __P((void));
91 static int	 getint __P((int *));
92 static int	 getquad __P((quad_t *));
93 static char	*getstr __P((void));
94 static char	*mklong __P((char *, int));
95 static void	 usage __P((void));
96 
97 static char **gargv;
98 
99 int
100 #ifdef BUILTIN
101 progprintf(argc, argv)
102 #else
103 main(argc, argv)
104 #endif
105 	int argc;
106 	char *argv[];
107 {
108 	static char *skip1, *skip2;
109 	int ch, end, fieldwidth, precision;
110 	char convch, nextch, *format, *fmt, *start;
111 
112 	while ((ch = getopt(argc, argv, "")) != -1)
113 		switch (ch) {
114 		case '?':
115 		default:
116 			usage();
117 			return (1);
118 		}
119 	argc -= optind;
120 	argv += optind;
121 
122 	if (argc < 1) {
123 		usage();
124 		return (1);
125 	}
126 
127 	/*
128 	 * Basic algorithm is to scan the format string for conversion
129 	 * specifications -- once one is found, find out if the field
130 	 * width or precision is a '*'; if it is, gather up value.  Note,
131 	 * format strings are reused as necessary to use up the provided
132 	 * arguments, arguments of zero/null string are provided to use
133 	 * up the format string.
134 	 */
135 	skip1 = "#-+ 0";
136 	skip2 = "0123456789";
137 
138 	escape(fmt = format = *argv);		/* backslash interpretation */
139 	gargv = ++argv;
140 	for (;;) {
141 		end = 0;
142 		/* find next format specification */
143 next:		for (start = fmt;; ++fmt) {
144 			if (!*fmt) {
145 				/* avoid infinite loop */
146 				if (end == 1) {
147 					warnx1("missing format character",
148 					    NULL, NULL);
149 					return (1);
150 				}
151 				end = 1;
152 				if (fmt > start)
153 					(void)printf("%s", start);
154 				if (!*gargv)
155 					return (0);
156 				fmt = format;
157 				goto next;
158 			}
159 			/* %% prints a % */
160 			if (*fmt == '%') {
161 				if (*++fmt != '%')
162 					break;
163 				*fmt++ = '\0';
164 				(void)printf("%s", start);
165 				goto next;
166 			}
167 		}
168 
169 		/* skip to field width */
170 		for (; strchr(skip1, *fmt); ++fmt);
171 		if (*fmt == '*') {
172 			if (getint(&fieldwidth))
173 				return (1);
174 			++fmt;
175 		} else {
176 			fieldwidth = 0;
177 
178 			/* skip to possible '.', get following precision */
179 			for (; strchr(skip2, *fmt); ++fmt);
180 		}
181 		if (*fmt == '.') {
182 			/* precision present? */
183 			++fmt;
184 			if (*fmt == '*') {
185 				if (getint(&precision))
186 					return (1);
187 				++fmt;
188 			} else {
189 				precision = 0;
190 
191 				/* skip to conversion char */
192 				for (; strchr(skip2, *fmt); ++fmt);
193 			}
194 		} else
195 			precision = 0;
196 		if (!*fmt) {
197 			warnx1("missing format character", NULL, NULL);
198 			return (1);
199 		}
200 
201 		convch = *fmt;
202 		nextch = *++fmt;
203 		*fmt = '\0';
204 		switch(convch) {
205 		case 'c': {
206 			char p;
207 
208 			p = getchr();
209 			PF(start, p);
210 			break;
211 		}
212 		case 's': {
213 			char *p;
214 
215 			p = getstr();
216 			PF(start, p);
217 			break;
218 		}
219 		case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
220 			quad_t p;
221 			char *f;
222 
223 			if ((f = mklong(start, convch)) == NULL)
224 				return (1);
225 			if (getquad(&p))
226 				return (1);
227 			PF(f, p);
228 			break;
229 		}
230 		case 'e': case 'E': case 'f': case 'g': case 'G': {
231 			double p;
232 
233 			p = getdouble();
234 			PF(start, p);
235 			break;
236 		}
237 		default:
238 			warnx2("illegal format character %c", convch, NULL);
239 			return (1);
240 		}
241 		*fmt = nextch;
242 	}
243 	/* NOTREACHED */
244 }
245 
246 static char *
247 mklong(str, ch)
248 	char *str;
249 	int ch;
250 {
251 	static char *copy;
252 	static size_t copy_size;
253 	size_t len, newlen;
254 	char *newcopy;
255 
256 	len = strlen(str) + 2;
257 	if (len > copy_size) {
258 		newlen = ((len + 1023) >> 10) << 10;
259 #ifdef SHELL
260 		if ((newcopy = ckrealloc(copy, newlen)) == NULL)
261 #else
262 		if ((newcopy = realloc(copy, newlen)) == NULL)
263 #endif
264 			return (NULL);
265 		copy = newcopy;
266 		copy_size = newlen;
267 	}
268 
269 	memmove(copy, str, len - 3);
270 	copy[len - 3] = 'q';
271 	copy[len - 2] = ch;
272 	copy[len - 1] = '\0';
273 	return (copy);
274 }
275 
276 static void
277 escape(fmt)
278 	register char *fmt;
279 {
280 	register char *store;
281 	register int value, c;
282 
283 	for (store = fmt; (c = *fmt); ++fmt, ++store) {
284 		if (c != '\\') {
285 			*store = c;
286 			continue;
287 		}
288 		switch (*++fmt) {
289 		case '\0':		/* EOS, user error */
290 			*store = '\\';
291 			*++store = '\0';
292 			return;
293 		case '\\':		/* backslash */
294 		case '\'':		/* single quote */
295 			*store = *fmt;
296 			break;
297 		case 'a':		/* bell/alert */
298 			*store = '\7';
299 			break;
300 		case 'b':		/* backspace */
301 			*store = '\b';
302 			break;
303 		case 'f':		/* form-feed */
304 			*store = '\f';
305 			break;
306 		case 'n':		/* newline */
307 			*store = '\n';
308 			break;
309 		case 'r':		/* carriage-return */
310 			*store = '\r';
311 			break;
312 		case 't':		/* horizontal tab */
313 			*store = '\t';
314 			break;
315 		case 'v':		/* vertical tab */
316 			*store = '\13';
317 			break;
318 					/* octal constant */
319 		case '0': case '1': case '2': case '3':
320 		case '4': case '5': case '6': case '7':
321 			for (c = 3, value = 0;
322 			    c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
323 				value <<= 3;
324 				value += *fmt - '0';
325 			}
326 			--fmt;
327 			*store = value;
328 			break;
329 		default:
330 			*store = *fmt;
331 			break;
332 		}
333 	}
334 	*store = '\0';
335 }
336 
337 static int
338 getchr()
339 {
340 	if (!*gargv)
341 		return ('\0');
342 	return ((int)**gargv++);
343 }
344 
345 static char *
346 getstr()
347 {
348 	if (!*gargv)
349 		return ("");
350 	return (*gargv++);
351 }
352 
353 static char *Number = "+-.0123456789";
354 static int
355 getint(ip)
356 	int *ip;
357 {
358 	quad_t val;
359 
360 	if (getquad(&val))
361 		return (1);
362 	if (val < INT_MIN || val > INT_MAX) {
363 		warnx3("%s: %s", *gargv, strerror(ERANGE));
364 		return (1);
365 	}
366 	*ip = (int)val;
367 	return (0);
368 }
369 
370 static int
371 getquad(lp)
372 	quad_t *lp;
373 {
374 	quad_t val;
375 	char *ep;
376 
377 	if (!*gargv) {
378 		*lp = 0;
379 		return (0);
380 	}
381 	if (strchr(Number, **gargv)) {
382 		errno = 0;
383 		val = strtoq(*gargv, &ep, 0);
384 		if (*ep != '\0') {
385 			warnx2("%s: illegal number", *gargv, NULL);
386 			return (1);
387 		}
388 		if (errno == ERANGE)
389 			if (val == QUAD_MAX) {
390 				warnx3("%s: %s", *gargv, strerror(ERANGE));
391 				return (1);
392 			}
393 			if (val == QUAD_MIN) {
394 				warnx3("%s: %s", *gargv, strerror(ERANGE));
395 				return (1);
396 			}
397 
398 		*lp = val;
399 		++gargv;
400 		return (0);
401 	}
402 	*lp =  (long)asciicode();
403 	return (0);
404 }
405 
406 static double
407 getdouble()
408 {
409 	if (!*gargv)
410 		return ((double)0);
411 	if (strchr(Number, **gargv))
412 		return (atof(*gargv++));
413 	return ((double)asciicode());
414 }
415 
416 static int
417 asciicode()
418 {
419 	register int ch;
420 
421 	ch = **gargv;
422 	if (ch == '\'' || ch == '"')
423 		ch = (*gargv)[1];
424 	++gargv;
425 	return (ch);
426 }
427 
428 static void
429 usage()
430 {
431 	(void)fprintf(stderr, "usage: printf format [arg ...]\n");
432 }
433