1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Chris Torek.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#if defined(LIBC_SCCS) && !defined(lint)
36static char sccsid[] = "@(#)vfprintf.c	8.1 (Berkeley) 6/4/93";
37#endif /* LIBC_SCCS and not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD$");
40
41/*
42 * This is the code responsible for handling positional arguments
43 * (%m$ and %m$.n$) for vfprintf() and vfwprintf().
44 */
45
46#include "namespace.h"
47#include <sys/types.h>
48
49#include <limits.h>
50#include <stdarg.h>
51#include <stddef.h>
52#include <stdint.h>
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <wchar.h>
57
58#include "un-namespace.h"
59#include "printflocal.h"
60
61#ifdef	NL_ARGMAX
62#define	MAX_POSARG	NL_ARGMAX
63#else
64#define	MAX_POSARG	65536
65#endif
66
67/*
68 * Type ids for argument type table.
69 */
70enum typeid {
71	T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
72	T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
73	T_PTRDIFFT, TP_PTRDIFFT, T_SSIZET, T_SIZET, TP_SSIZET,
74	T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
75	T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
76};
77
78/* An expandable array of types. */
79struct typetable {
80	enum typeid *table; /* table of types */
81	enum typeid stattable[STATIC_ARG_TBL_SIZE];
82	u_int tablesize;	/* current size of type table */
83	u_int tablemax;		/* largest used index in table */
84	u_int nextarg;		/* 1-based argument index */
85};
86
87static int	__grow_type_table(struct typetable *);
88static void	build_arg_table (struct typetable *, va_list, union arg **);
89
90/*
91 * Initialize a struct typetable.
92 */
93static inline void
94inittypes(struct typetable *types)
95{
96	u_int n;
97
98	types->table = types->stattable;
99	types->tablesize = STATIC_ARG_TBL_SIZE;
100	types->tablemax = 0;
101	types->nextarg = 1;
102	for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
103		types->table[n] = T_UNUSED;
104}
105
106/*
107 * struct typetable destructor.
108 */
109static inline void
110freetypes(struct typetable *types)
111{
112
113	if (types->table != types->stattable)
114		free (types->table);
115}
116
117/*
118 * Ensure that there is space to add a new argument type to the type table.
119 * Expand the table if necessary. Returns 0 on success.
120 */
121static inline int
122_ensurespace(struct typetable *types)
123{
124
125	if (types->nextarg >= types->tablesize) {
126		if (__grow_type_table(types))
127			return (-1);
128	}
129	if (types->nextarg > types->tablemax)
130		types->tablemax = types->nextarg;
131	return (0);
132}
133
134/*
135 * Add an argument type to the table, expanding if necessary.
136 * Returns 0 on success.
137 */
138static inline int
139addtype(struct typetable *types, enum typeid type)
140{
141
142	if (_ensurespace(types))
143		return (-1);
144	types->table[types->nextarg++] = type;
145	return (0);
146}
147
148static inline int
149addsarg(struct typetable *types, int flags)
150{
151
152	if (_ensurespace(types))
153		return (-1);
154	if (flags & INTMAXT)
155		types->table[types->nextarg++] = T_INTMAXT;
156	else if (flags & SIZET)
157		types->table[types->nextarg++] = T_SSIZET;
158	else if (flags & PTRDIFFT)
159		types->table[types->nextarg++] = T_PTRDIFFT;
160	else if (flags & LLONGINT)
161		types->table[types->nextarg++] = T_LLONG;
162	else if (flags & LONGINT)
163		types->table[types->nextarg++] = T_LONG;
164	else
165		types->table[types->nextarg++] = T_INT;
166	return (0);
167}
168
169static inline int
170adduarg(struct typetable *types, int flags)
171{
172
173	if (_ensurespace(types))
174		return (-1);
175	if (flags & INTMAXT)
176		types->table[types->nextarg++] = T_UINTMAXT;
177	else if (flags & SIZET)
178		types->table[types->nextarg++] = T_SIZET;
179	else if (flags & PTRDIFFT)
180		types->table[types->nextarg++] = T_SIZET;
181	else if (flags & LLONGINT)
182		types->table[types->nextarg++] = T_U_LLONG;
183	else if (flags & LONGINT)
184		types->table[types->nextarg++] = T_U_LONG;
185	else
186		types->table[types->nextarg++] = T_U_INT;
187	return (0);
188}
189
190/*
191 * Add * arguments to the type array.
192 */
193static inline int
194addaster(struct typetable *types, char **fmtp)
195{
196	char *cp;
197	u_int n2;
198
199	n2 = 0;
200	cp = *fmtp;
201	while (is_digit(*cp)) {
202		n2 = 10 * n2 + to_digit(*cp);
203		cp++;
204	}
205	if (*cp == '$') {
206		u_int hold = types->nextarg;
207		types->nextarg = n2;
208		if (addtype(types, T_INT))
209			return (-1);
210		types->nextarg = hold;
211		*fmtp = ++cp;
212	} else {
213		if (addtype(types, T_INT))
214			return (-1);
215	}
216	return (0);
217}
218
219static inline int
220addwaster(struct typetable *types, wchar_t **fmtp)
221{
222	wchar_t *cp;
223	u_int n2;
224
225	n2 = 0;
226	cp = *fmtp;
227	while (is_digit(*cp)) {
228		n2 = 10 * n2 + to_digit(*cp);
229		cp++;
230	}
231	if (*cp == '$') {
232		u_int hold = types->nextarg;
233		types->nextarg = n2;
234		if (addtype(types, T_INT))
235			return (-1);
236		types->nextarg = hold;
237		*fmtp = ++cp;
238	} else {
239		if (addtype(types, T_INT))
240			return (-1);
241	}
242	return (0);
243}
244
245/*
246 * Find all arguments when a positional parameter is encountered.  Returns a
247 * table, indexed by argument number, of pointers to each arguments.  The
248 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
249 * It will be replaces with a malloc-ed one if it overflows.
250 * Returns 0 on success. On failure, returns nonzero and sets errno.
251 */
252int
253__find_arguments (const char *fmt0, va_list ap, union arg **argtable)
254{
255	char *fmt;		/* format string */
256	int ch;			/* character from fmt */
257	u_int n;		/* handy integer (short term usage) */
258	int error;
259	int flags;		/* flags as above */
260	struct typetable types;	/* table of types */
261
262	fmt = (char *)fmt0;
263	inittypes(&types);
264	error = 0;
265
266	/*
267	 * Scan the format for conversions (`%' character).
268	 */
269	for (;;) {
270		while ((ch = *fmt) != '\0' && ch != '%')
271			fmt++;
272		if (ch == '\0')
273			goto done;
274		fmt++;		/* skip over '%' */
275
276		flags = 0;
277
278rflag:		ch = *fmt++;
279reswitch:	switch (ch) {
280		case ' ':
281		case '#':
282			goto rflag;
283		case '*':
284			if ((error = addaster(&types, &fmt)))
285				goto error;
286			goto rflag;
287		case '-':
288		case '+':
289		case '\'':
290			goto rflag;
291		case '.':
292			if ((ch = *fmt++) == '*') {
293				if ((error = addaster(&types, &fmt)))
294					goto error;
295				goto rflag;
296			}
297			while (is_digit(ch)) {
298				ch = *fmt++;
299			}
300			goto reswitch;
301		case '0':
302			goto rflag;
303		case '1': case '2': case '3': case '4':
304		case '5': case '6': case '7': case '8': case '9':
305			n = 0;
306			do {
307				n = 10 * n + to_digit(ch);
308				/* Detect overflow */
309				if (n > MAX_POSARG) {
310					error = -1;
311					goto error;
312				}
313				ch = *fmt++;
314			} while (is_digit(ch));
315			if (ch == '$') {
316				types.nextarg = n;
317				goto rflag;
318			}
319			goto reswitch;
320#ifndef NO_FLOATING_POINT
321		case 'L':
322			flags |= LONGDBL;
323			goto rflag;
324#endif
325		case 'h':
326			if (flags & SHORTINT) {
327				flags &= ~SHORTINT;
328				flags |= CHARINT;
329			} else
330				flags |= SHORTINT;
331			goto rflag;
332		case 'j':
333			flags |= INTMAXT;
334			goto rflag;
335		case 'l':
336			if (flags & LONGINT) {
337				flags &= ~LONGINT;
338				flags |= LLONGINT;
339			} else
340				flags |= LONGINT;
341			goto rflag;
342		case 'q':
343			flags |= LLONGINT;	/* not necessarily */
344			goto rflag;
345		case 't':
346			flags |= PTRDIFFT;
347			goto rflag;
348		case 'z':
349			flags |= SIZET;
350			goto rflag;
351		case 'C':
352			flags |= LONGINT;
353			/*FALLTHROUGH*/
354		case 'c':
355			error = addtype(&types,
356					(flags & LONGINT) ? T_WINT : T_INT);
357			if (error)
358				goto error;
359			break;
360		case 'D':
361			flags |= LONGINT;
362			/*FALLTHROUGH*/
363		case 'd':
364		case 'i':
365			if ((error = addsarg(&types, flags)))
366				goto error;
367			break;
368#ifndef NO_FLOATING_POINT
369		case 'a':
370		case 'A':
371		case 'e':
372		case 'E':
373		case 'f':
374		case 'g':
375		case 'G':
376			error = addtype(&types,
377			    (flags & LONGDBL) ? T_LONG_DOUBLE : T_DOUBLE);
378			if (error)
379				goto error;
380			break;
381#endif /* !NO_FLOATING_POINT */
382		case 'n':
383			if (flags & INTMAXT)
384				error = addtype(&types, TP_INTMAXT);
385			else if (flags & PTRDIFFT)
386				error = addtype(&types, TP_PTRDIFFT);
387			else if (flags & SIZET)
388				error = addtype(&types, TP_SSIZET);
389			else if (flags & LLONGINT)
390				error = addtype(&types, TP_LLONG);
391			else if (flags & LONGINT)
392				error = addtype(&types, TP_LONG);
393			else if (flags & SHORTINT)
394				error = addtype(&types, TP_SHORT);
395			else if (flags & CHARINT)
396				error = addtype(&types, TP_SCHAR);
397			else
398				error = addtype(&types, TP_INT);
399			if (error)
400				goto error;
401			continue;	/* no output */
402		case 'O':
403			flags |= LONGINT;
404			/*FALLTHROUGH*/
405		case 'o':
406			if ((error = adduarg(&types, flags)))
407				goto error;
408			break;
409		case 'p':
410			if ((error = addtype(&types, TP_VOID)))
411				goto error;
412			break;
413		case 'S':
414			flags |= LONGINT;
415			/*FALLTHROUGH*/
416		case 's':
417			error = addtype(&types,
418					(flags & LONGINT) ? TP_WCHAR : TP_CHAR);
419			if (error)
420				goto error;
421			break;
422		case 'U':
423			flags |= LONGINT;
424			/*FALLTHROUGH*/
425		case 'u':
426		case 'X':
427		case 'x':
428			if ((error = adduarg(&types, flags)))
429				goto error;
430			break;
431		default:	/* "%?" prints ?, unless ? is NUL */
432			if (ch == '\0')
433				goto done;
434			break;
435		}
436	}
437done:
438	build_arg_table(&types, ap, argtable);
439error:
440	freetypes(&types);
441	return (error || *argtable == NULL);
442}
443
444/* wchar version of __find_arguments. */
445int
446__find_warguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
447{
448	wchar_t *fmt;		/* format string */
449	wchar_t ch;		/* character from fmt */
450	u_int n;		/* handy integer (short term usage) */
451	int error;
452	int flags;		/* flags as above */
453	struct typetable types;	/* table of types */
454
455	fmt = (wchar_t *)fmt0;
456	inittypes(&types);
457	error = 0;
458
459	/*
460	 * Scan the format for conversions (`%' character).
461	 */
462	for (;;) {
463		while ((ch = *fmt) != '\0' && ch != '%')
464			fmt++;
465		if (ch == '\0')
466			goto done;
467		fmt++;		/* skip over '%' */
468
469		flags = 0;
470
471rflag:		ch = *fmt++;
472reswitch:	switch (ch) {
473		case ' ':
474		case '#':
475			goto rflag;
476		case '*':
477			if ((error = addwaster(&types, &fmt)))
478				goto error;
479			goto rflag;
480		case '-':
481		case '+':
482		case '\'':
483			goto rflag;
484		case '.':
485			if ((ch = *fmt++) == '*') {
486				if ((error = addwaster(&types, &fmt)))
487					goto error;
488				goto rflag;
489			}
490			while (is_digit(ch)) {
491				ch = *fmt++;
492			}
493			goto reswitch;
494		case '0':
495			goto rflag;
496		case '1': case '2': case '3': case '4':
497		case '5': case '6': case '7': case '8': case '9':
498			n = 0;
499			do {
500				n = 10 * n + to_digit(ch);
501				/* Detect overflow */
502				if (n > MAX_POSARG) {
503					error = -1;
504					goto error;
505				}
506				ch = *fmt++;
507			} while (is_digit(ch));
508			if (ch == '$') {
509				types.nextarg = n;
510				goto rflag;
511			}
512			goto reswitch;
513#ifndef NO_FLOATING_POINT
514		case 'L':
515			flags |= LONGDBL;
516			goto rflag;
517#endif
518		case 'h':
519			if (flags & SHORTINT) {
520				flags &= ~SHORTINT;
521				flags |= CHARINT;
522			} else
523				flags |= SHORTINT;
524			goto rflag;
525		case 'j':
526			flags |= INTMAXT;
527			goto rflag;
528		case 'l':
529			if (flags & LONGINT) {
530				flags &= ~LONGINT;
531				flags |= LLONGINT;
532			} else
533				flags |= LONGINT;
534			goto rflag;
535		case 'q':
536			flags |= LLONGINT;	/* not necessarily */
537			goto rflag;
538		case 't':
539			flags |= PTRDIFFT;
540			goto rflag;
541		case 'z':
542			flags |= SIZET;
543			goto rflag;
544		case 'C':
545			flags |= LONGINT;
546			/*FALLTHROUGH*/
547		case 'c':
548			error = addtype(&types,
549					(flags & LONGINT) ? T_WINT : T_INT);
550			if (error)
551				goto error;
552			break;
553		case 'D':
554			flags |= LONGINT;
555			/*FALLTHROUGH*/
556		case 'd':
557		case 'i':
558			if ((error = addsarg(&types, flags)))
559				goto error;
560			break;
561#ifndef NO_FLOATING_POINT
562		case 'a':
563		case 'A':
564		case 'e':
565		case 'E':
566		case 'f':
567		case 'g':
568		case 'G':
569			error = addtype(&types,
570			    (flags & LONGDBL) ? T_LONG_DOUBLE : T_DOUBLE);
571			if (error)
572				goto error;
573			break;
574#endif /* !NO_FLOATING_POINT */
575		case 'n':
576			if (flags & INTMAXT)
577				error = addtype(&types, TP_INTMAXT);
578			else if (flags & PTRDIFFT)
579				error = addtype(&types, TP_PTRDIFFT);
580			else if (flags & SIZET)
581				error = addtype(&types, TP_SSIZET);
582			else if (flags & LLONGINT)
583				error = addtype(&types, TP_LLONG);
584			else if (flags & LONGINT)
585				error = addtype(&types, TP_LONG);
586			else if (flags & SHORTINT)
587				error = addtype(&types, TP_SHORT);
588			else if (flags & CHARINT)
589				error = addtype(&types, TP_SCHAR);
590			else
591				error = addtype(&types, TP_INT);
592			if (error)
593				goto error;
594			continue;	/* no output */
595		case 'O':
596			flags |= LONGINT;
597			/*FALLTHROUGH*/
598		case 'o':
599			if ((error = adduarg(&types, flags)))
600				goto error;
601			break;
602		case 'p':
603			if ((error = addtype(&types, TP_VOID)))
604				goto error;
605			break;
606		case 'S':
607			flags |= LONGINT;
608			/*FALLTHROUGH*/
609		case 's':
610			error = addtype(&types,
611			    (flags & LONGINT) ? TP_WCHAR : TP_CHAR);
612			if (error)
613				goto error;
614			break;
615		case 'U':
616			flags |= LONGINT;
617			/*FALLTHROUGH*/
618		case 'u':
619		case 'X':
620		case 'x':
621			if ((error = adduarg(&types, flags)))
622				goto error;
623			break;
624		default:	/* "%?" prints ?, unless ? is NUL */
625			if (ch == '\0')
626				goto done;
627			break;
628		}
629	}
630done:
631	build_arg_table(&types, ap, argtable);
632error:
633	freetypes(&types);
634	return (error || *argtable == NULL);
635}
636
637/*
638 * Increase the size of the type table. Returns 0 on success.
639 */
640static int
641__grow_type_table(struct typetable *types)
642{
643	enum typeid *const oldtable = types->table;
644	const int oldsize = types->tablesize;
645	enum typeid *newtable;
646	u_int n, newsize;
647
648	/* Detect overflow */
649	if (types->nextarg > NL_ARGMAX)
650		return (-1);
651
652	newsize = oldsize * 2;
653	if (newsize < types->nextarg + 1)
654		newsize = types->nextarg + 1;
655	if (oldsize == STATIC_ARG_TBL_SIZE) {
656		if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
657			return (-1);
658		bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
659	} else {
660		newtable = reallocarray(oldtable, newsize, sizeof(enum typeid));
661		if (newtable == NULL)
662			return (-1);
663	}
664	for (n = oldsize; n < newsize; n++)
665		newtable[n] = T_UNUSED;
666
667	types->table = newtable;
668	types->tablesize = newsize;
669
670	return (0);
671}
672
673/*
674 * Build the argument table from the completed type table.
675 * On malloc failure, *argtable is set to NULL.
676 */
677static void
678build_arg_table(struct typetable *types, va_list ap, union arg **argtable)
679{
680	u_int n;
681
682	if (types->tablemax >= STATIC_ARG_TBL_SIZE) {
683		*argtable = (union arg *)
684		    malloc (sizeof (union arg) * (types->tablemax + 1));
685		if (*argtable == NULL)
686			return;
687	}
688
689	(*argtable) [0].intarg = 0;
690	for (n = 1; n <= types->tablemax; n++) {
691		switch (types->table[n]) {
692		    case T_UNUSED: /* whoops! */
693			(*argtable) [n].intarg = va_arg (ap, int);
694			break;
695		    case TP_SCHAR:
696			(*argtable) [n].pschararg = va_arg (ap, signed char *);
697			break;
698		    case TP_SHORT:
699			(*argtable) [n].pshortarg = va_arg (ap, short *);
700			break;
701		    case T_INT:
702			(*argtable) [n].intarg = va_arg (ap, int);
703			break;
704		    case T_U_INT:
705			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
706			break;
707		    case TP_INT:
708			(*argtable) [n].pintarg = va_arg (ap, int *);
709			break;
710		    case T_LONG:
711			(*argtable) [n].longarg = va_arg (ap, long);
712			break;
713		    case T_U_LONG:
714			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
715			break;
716		    case TP_LONG:
717			(*argtable) [n].plongarg = va_arg (ap, long *);
718			break;
719		    case T_LLONG:
720			(*argtable) [n].longlongarg = va_arg (ap, long long);
721			break;
722		    case T_U_LLONG:
723			(*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
724			break;
725		    case TP_LLONG:
726			(*argtable) [n].plonglongarg = va_arg (ap, long long *);
727			break;
728		    case T_PTRDIFFT:
729			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
730			break;
731		    case TP_PTRDIFFT:
732			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
733			break;
734		    case T_SIZET:
735			(*argtable) [n].sizearg = va_arg (ap, size_t);
736			break;
737		    case T_SSIZET:
738			(*argtable) [n].sizearg = va_arg (ap, ssize_t);
739			break;
740		    case TP_SSIZET:
741			(*argtable) [n].pssizearg = va_arg (ap, ssize_t *);
742			break;
743		    case T_INTMAXT:
744			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
745			break;
746		    case T_UINTMAXT:
747			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
748			break;
749		    case TP_INTMAXT:
750			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
751			break;
752		    case T_DOUBLE:
753#ifndef NO_FLOATING_POINT
754			(*argtable) [n].doublearg = va_arg (ap, double);
755#endif
756			break;
757		    case T_LONG_DOUBLE:
758#ifndef NO_FLOATING_POINT
759			(*argtable) [n].longdoublearg = va_arg (ap, long double);
760#endif
761			break;
762		    case TP_CHAR:
763			(*argtable) [n].pchararg = va_arg (ap, char *);
764			break;
765		    case TP_VOID:
766			(*argtable) [n].pvoidarg = va_arg (ap, void *);
767			break;
768		    case T_WINT:
769			(*argtable) [n].wintarg = va_arg (ap, wint_t);
770			break;
771		    case TP_WCHAR:
772			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
773			break;
774		}
775	}
776}
777