xref: /openbsd-src/lib/libcurses/base/safe_sprintf.c (revision cd1eb269cafb12c415be1749cd4a4b5422710415)
1 /* $OpenBSD: safe_sprintf.c,v 1.5 2010/01/12 23:22:06 nicm Exp $ */
2 
3 /****************************************************************************
4  * Copyright (c) 1998-2003,2007 Free Software Foundation, Inc.              *
5  *                                                                          *
6  * Permission is hereby granted, free of charge, to any person obtaining a  *
7  * copy of this software and associated documentation files (the            *
8  * "Software"), to deal in the Software without restriction, including      *
9  * without limitation the rights to use, copy, modify, merge, publish,      *
10  * distribute, distribute with modifications, sublicense, and/or sell       *
11  * copies of the Software, and to permit persons to whom the Software is    *
12  * furnished to do so, subject to the following conditions:                 *
13  *                                                                          *
14  * The above copyright notice and this permission notice shall be included  *
15  * in all copies or substantial portions of the Software.                   *
16  *                                                                          *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
20  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
23  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
24  *                                                                          *
25  * Except as contained in this notice, the name(s) of the above copyright   *
26  * holders shall not be used in advertising or otherwise to promote the     *
27  * sale, use or other dealings in this Software without prior written       *
28  * authorization.                                                           *
29  ****************************************************************************/
30 
31 /****************************************************************************
32  *  Author: Thomas E. Dickey <dickey@clark.net> 1997                        *
33  ****************************************************************************/
34 
35 #include <curses.priv.h>
36 #include <ctype.h>
37 
38 MODULE_ID("$Id: safe_sprintf.c,v 1.5 2010/01/12 23:22:06 nicm Exp $")
39 
40 #if USE_SAFE_SPRINTF
41 
42 typedef enum {
43     Flags, Width, Prec, Type, Format
44 } PRINTF;
45 
46 #define VA_INTGR(type) ival = va_arg(ap, type)
47 #define VA_FLOAT(type) fval = va_arg(ap, type)
48 #define VA_POINT(type) pval = (void *)va_arg(ap, type)
49 
50 /*
51  * Scan a variable-argument list for printf to determine the number of
52  * characters that would be emitted.
53  */
54 static int
55 _nc_printf_length(const char *fmt, va_list ap)
56 {
57     size_t length = BUFSIZ;
58     char *buffer;
59     char *format;
60     int len = 0;
61     size_t fmt_len;
62     char fmt_arg[BUFSIZ];
63 
64     if (fmt == 0 || *fmt == '\0')
65 	return 0;
66     fmt_len = strlen(fmt) + 1;
67     if ((format = typeMalloc(char, fmt_len)) == 0)
68 	  return -1;
69     if ((buffer = typeMalloc(char, length)) == 0) {
70 	free(format);
71 	return -1;
72     }
73 
74     while (*fmt != '\0') {
75 	if (*fmt == '%') {
76 	    static char dummy[] = "";
77 	    PRINTF state = Flags;
78 	    char *pval = dummy;	/* avoid const-cast */
79 	    double fval = 0.0;
80 	    int done = FALSE;
81 	    int ival = 0;
82 	    int prec = -1;
83 	    int type = 0;
84 	    int used = 0;
85 	    int width = -1;
86 	    size_t f = 0;
87 
88 	    format[f++] = *fmt;
89 	    while (*++fmt != '\0' && len >= 0 && !done) {
90 		format[f++] = *fmt;
91 
92 		if (isdigit(UChar(*fmt))) {
93 		    int num = *fmt - '0';
94 		    if (state == Flags && num != 0)
95 			state = Width;
96 		    if (state == Width) {
97 			if (width < 0)
98 			    width = 0;
99 			width = (width * 10) + num;
100 		    } else if (state == Prec) {
101 			if (prec < 0)
102 			    prec = 0;
103 			prec = (prec * 10) + num;
104 		    }
105 		} else if (*fmt == '*') {
106 		    VA_INTGR(int);
107 		    if (state == Flags)
108 			state = Width;
109 		    if (state == Width) {
110 			width = ival;
111 		    } else if (state == Prec) {
112 			prec = ival;
113 		    }
114 		    sprintf(fmt_arg, "%d", ival);
115 		    fmt_len += strlen(fmt_arg);
116 		    if ((format = realloc(format, fmt_len)) == 0) {
117 			return -1;
118 		    }
119 		    strcpy(&format[--f], fmt_arg);
120 		    f = strlen(format);
121 		} else if (isalpha(UChar(*fmt))) {
122 		    done = TRUE;
123 		    switch (*fmt) {
124 		    case 'Z':	/* FALLTHRU */
125 		    case 'h':	/* FALLTHRU */
126 		    case 'l':	/* FALLTHRU */
127 			done = FALSE;
128 			type = *fmt;
129 			break;
130 		    case 'i':	/* FALLTHRU */
131 		    case 'd':	/* FALLTHRU */
132 		    case 'u':	/* FALLTHRU */
133 		    case 'x':	/* FALLTHRU */
134 		    case 'X':	/* FALLTHRU */
135 			if (type == 'l')
136 			    VA_INTGR(long);
137 			else if (type == 'Z')
138 			    VA_INTGR(size_t);
139 			else
140 			    VA_INTGR(int);
141 			used = 'i';
142 			break;
143 		    case 'f':	/* FALLTHRU */
144 		    case 'e':	/* FALLTHRU */
145 		    case 'E':	/* FALLTHRU */
146 		    case 'g':	/* FALLTHRU */
147 		    case 'G':	/* FALLTHRU */
148 			VA_FLOAT(double);
149 			used = 'f';
150 			break;
151 		    case 'c':
152 			VA_INTGR(int);
153 			used = 'i';
154 			break;
155 		    case 's':
156 			VA_POINT(char *);
157 			if (prec < 0)
158 			    prec = strlen(pval);
159 			if (prec > (int) length) {
160 			    length = length + prec;
161 			    buffer = typeRealloc(char, length, buffer);
162 			    if (buffer == 0) {
163 				free(format);
164 				return -1;
165 			    }
166 			}
167 			used = 'p';
168 			break;
169 		    case 'p':
170 			VA_POINT(void *);
171 			used = 'p';
172 			break;
173 		    case 'n':
174 			VA_POINT(int *);
175 			used = 0;
176 			break;
177 		    default:
178 			break;
179 		    }
180 		} else if (*fmt == '.') {
181 		    state = Prec;
182 		} else if (*fmt == '%') {
183 		    done = TRUE;
184 		    used = 'p';
185 		}
186 	    }
187 	    format[f] = '\0';
188 	    switch (used) {
189 	    case 'i':
190 		sprintf(buffer, format, ival);
191 		break;
192 	    case 'f':
193 		sprintf(buffer, format, fval);
194 		break;
195 	    default:
196 		sprintf(buffer, format, pval);
197 		break;
198 	    }
199 	    len += (int) strlen(buffer);
200 	} else {
201 	    fmt++;
202 	    len++;
203 	}
204     }
205 
206     free(buffer);
207     free(format);
208     return len;
209 }
210 #endif
211 
212 #define my_buffer _nc_globals.safeprint_buf
213 #define my_length _nc_globals.safeprint_used
214 
215 /*
216  * Wrapper for vsprintf that allocates a buffer big enough to hold the result.
217  */
218 NCURSES_EXPORT(char *)
219 _nc_printf_string(const char *fmt, va_list ap)
220 {
221     char *result = 0;
222 
223     if (fmt != 0) {
224 #if USE_SAFE_SPRINTF
225 	int len = _nc_printf_length(fmt, ap);
226 
227 	if ((int) my_length < len + 1) {
228 	    my_length = 2 * (len + 1);
229 	    my_buffer = typeRealloc(char, my_length, my_buffer);
230 	}
231 	if (my_buffer != 0) {
232 	    *my_buffer = '\0';
233 	    if (len >= 0) {
234 		vsprintf(my_buffer, fmt, ap);
235 	    }
236 	    result = my_buffer;
237 	}
238 #else
239 #define MyCols _nc_globals.safeprint_cols
240 #define MyRows _nc_globals.safeprint_rows
241 
242 	if (screen_lines > MyRows || screen_columns > MyCols) {
243 	    if (screen_lines > MyRows)
244 		MyRows = screen_lines;
245 	    if (screen_columns > MyCols)
246 		MyCols = screen_columns;
247 	    my_length = (MyRows * (MyCols + 1)) + 1;
248 	    my_buffer = typeRealloc(char, my_length, my_buffer);
249 	}
250 
251 	if (my_buffer != 0) {
252 # if HAVE_VSNPRINTF
253 	    vsnprintf(my_buffer, my_length, fmt, ap);	/* GNU extension */
254 # else
255 	    vsprintf(my_buffer, fmt, ap);	/* ANSI */
256 # endif
257 	    result = my_buffer;
258 	}
259 #endif
260     } else if (my_buffer != 0) {	/* see _nc_freeall() */
261 	free(my_buffer);
262 	my_buffer = 0;
263 	my_length = 0;
264     }
265     return result;
266 }
267