/src/r-oss-fuzz/harnesses/formula.c
Line | Count | Source |
1 | | /* |
2 | | * libFuzzer harness for model formulas and symbolic differentiation: |
3 | | * stats' C code in src/library/stats/src/model.c (termsform, updateform, |
4 | | * modelframe, modelmatrix) and deriv.c (D, deriv). |
5 | | * |
6 | | * Every modelling function in R starts by taking a formula apart with |
7 | | * terms(), which in C encodes each variable as a bit, expands *, ^, /, |
8 | | * %in% and - into bit-pattern terms and sorts them; model.frame() and |
9 | | * model.matrix() then turn the terms into columns, contrasts included. |
10 | | * Formulas reach these from user input more often than one might hope |
11 | | * (as.formula(paste(...)) of web form fields, reformulate()). D() and |
12 | | * deriv() rewrite expressions the same way, without evaluating them. |
13 | | * |
14 | | * Input layout: byte 0 selects the slot, byte 1 is a variant v that |
15 | | * each slot splits into its own options, the rest is R source text. |
16 | | * The text is parsed here in C, not evaluated; it must be exactly one |
17 | | * expression, which becomes the formula (wrapped in ~ when it is not |
18 | | * already one) or the expression to differentiate. |
19 | | * |
20 | | * Guards, applied to the parsed expression before R sees it: |
21 | | * |
22 | | * - Formula algebra is exponential by design: (a+b+...+z)^26 really has |
23 | | * 2^26 terms, and (a+b):(c+d):(e+f)... doubles with every factor. |
24 | | * term_bound() computes an upper bound on the number of terms and |
25 | | * the terms slots skip inputs over FORMULA_MAX_TERMS, or with an |
26 | | * exponent over FORMULA_MAX_POWER (see term_bound). |
27 | | * - So is differentiation: d(u^v) contains u and v twice over, so |
28 | | * x^x^x^... grows by a factor of two per level. The D/deriv slot |
29 | | * skips expressions nested deeper than DERIV_MAX_DEPTH. |
30 | | * - model.frame() evaluates every variable expression in the formula. |
31 | | * The model slot runs only when every name in the input is in |
32 | | * eval_names (operators, a few pure functions, and the columns of |
33 | | * the fixed data frame), so the input can call nothing else. |
34 | | * - The data's ten rows do not bound what those calls build, so the |
35 | | * model slot bounds `:`, interaction() and the columns of |
36 | | * model.matrix() itself (see model_source). |
37 | | */ |
38 | | |
39 | | #include <math.h> |
40 | | #include <stdint.h> |
41 | | #include <string.h> |
42 | | |
43 | | #include "common.h" |
44 | | |
45 | 24.7k | #define FUZZ_MAX_INPUT 4096 |
46 | 74.2k | #define FUZZ_HEADER 2 |
47 | 10.3k | #define N_CALLS 4 |
48 | | |
49 | 9.54k | #define FORMULA_MAX_TERMS 4096.0 |
50 | 7.39k | #define FORMULA_MAX_POWER 64.0 |
51 | 821 | #define DERIV_MAX_DEPTH 12 |
52 | | |
53 | | /* The data frame's columns: numeric, factor, ordered, logical and a |
54 | | * matrix column, with an NA in most, so na.action has work to do. */ |
55 | | static const char data_source[] = R"( |
56 | | data.frame( |
57 | | y = c(1.5, -2, 3, NA, 0, 1e300, -Inf, 4, 2, 7), |
58 | | x = c(1:9, NA) / 3, |
59 | | z = c(rep(c(0.1, 1, 10), 3), -1), |
60 | | w = c(rep(1, 9), 0), |
61 | | f = factor(c("a", "b", "c", "a", "b", NA, "c", "a", "b", "c")), |
62 | | g = factor(rep(c("u", "v"), 5)), |
63 | | o = factor(c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1), ordered = TRUE), |
64 | | l = c(TRUE, FALSE, NA, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE), |
65 | | m = I(matrix(c(1:19, NA), 10)) |
66 | | ) |
67 | | )"; |
68 | | |
69 | | /* The names model.frame() may evaluate: the data's columns and "." |
70 | | * (both looked up in the data first), the formula operators, and |
71 | | * functions without side effects whose cost is bounded by their |
72 | | * arguments' lengths, which the 10-row data bounds in turn. */ |
73 | | static const char *const eval_names[] = { |
74 | | "y", "x", "z", "w", "f", "g", "o", "l", "m", ".", |
75 | | "~", "+", "-", "*", "/", ":", "^", "%in%", "(", "|", "&", "==", |
76 | | "I", "log", "exp", "sqrt", "abs", "sin", "cos", "offset", "cbind", |
77 | | "factor", "as.numeric", "interaction", |
78 | | }; |
79 | 6.00M | #define N_EVAL_NAMES (sizeof(eval_names) / sizeof(eval_names[0])) |
80 | | |
81 | | /* fo(e): e as a formula object, without evaluating it. Its |
82 | | * environment is the global one, where nothing but the search path |
83 | | * resolves; the model slot additionally checks every name first. */ |
84 | | static const char as_formula_source[] = R"( |
85 | | function(e) { |
86 | | if (!(is.call(e) && identical(e[[1L]], as.name("~")))) |
87 | | e <- call("~", e) |
88 | | structure(e, class = "formula", .Environment = globalenv()) |
89 | | } |
90 | | )"; |
91 | | |
92 | | /* [0] terms(): term expansion and ordering, specials, the "." in the |
93 | | * data, and the R-level editors built on the result. */ |
94 | | static const char terms_source[] = R"( |
95 | | function(e, v, fo, data) { |
96 | | t <- terms(fo(e), specials = c("s", "strata", "offset"), |
97 | | keep.order = v %% 2L == 1L, |
98 | | simplify = v %/% 2L %% 2L == 1L, |
99 | | allowDotAsName = v %/% 4L %% 2L == 1L, |
100 | | data = if (v %/% 8L %% 2L) data) |
101 | | labels <- attr(t, "term.labels") |
102 | | if (length(labels)) { |
103 | | drop.terms(t, 1L, keep.response = v %/% 16L %% 2L == 1L) |
104 | | reformulate(labels, response = if (v %/% 32L %% 2L) "y", |
105 | | intercept = v %/% 64L %% 2L == 0L) |
106 | | } |
107 | | delete.response(t) |
108 | | all.vars(t) |
109 | | } |
110 | | )"; |
111 | | |
112 | | /* [1] update(): the input as the new formula over a fixed old one, or |
113 | | * as the old one under a fixed new one. The fixed formulas contain no |
114 | | * ^, so substituting one into the other keeps the term bound. */ |
115 | | static const char update_source[] = R"( |
116 | | local({ |
117 | | old <- list(y ~ x + f, cbind(y, z) ~ x * f + offset(w), ~ f:g - 1, |
118 | | log(y) ~ (x + z) %in% g) |
119 | | new <- list(. ~ . + z, ~ . - x, . ~ .:f, log(.) ~ . * g, y ~ .) |
120 | | function(e, v, fo, data) { |
121 | | e <- fo(e) |
122 | | if (v %% 2L) |
123 | | update.formula(old[[v %/% 2L %% 4L + 1L]], e) |
124 | | else |
125 | | update.formula(e, new[[v %/% 2L %% 5L + 1L]]) |
126 | | } |
127 | | }) |
128 | | )"; |
129 | | |
130 | | /* [2] model.frame() and model.matrix() over the fixed data: contrasts, |
131 | | * interactions of factors with matrices, na.action, zero-row data. |
132 | | * |
133 | | * The data has ten rows, but a few bytes of the input can make far more |
134 | | * work than that. `:` builds a sequence of any length (oss-fuzz testcase |
135 | | * 5546078118936576: 7022242 elements inside interaction(), 9.6 s in |
136 | | * release R), and on two factors, like interaction(), a factor whose |
137 | | * levels multiply with every argument: 14 copies of the three-level f |
138 | | * took 13 s. The variables are evaluated in the formula's environment, |
139 | | * where both are bounded versions, to 1000 elements or levels (a |
140 | | * factor's contrast matrix has its levels squared in cells); `:` is |
141 | | * bounded on the first element of each argument, as in the eval target. |
142 | | * model.matrix() then gives each term the product of its variables' |
143 | | * widths in columns, a factor's levels or a matrix's columns (seven |
144 | | * factor() variables in one term made 944785), so the slot stops before |
145 | | * it past 4096 columns. */ |
146 | | static const char model_source[] = R"( |
147 | | local({ |
148 | | contrasts <- c("contr.treatment", "contr.sum", "contr.helmert", |
149 | | "contr.SAS", "contr.poly") |
150 | | actions <- list(na.omit, na.exclude, na.pass, na.fail) |
151 | | bounded <- new.env(parent = globalenv()) |
152 | | bounded[[":"]] <- function(from, to) { |
153 | | if (is.factor(from) && is.factor(to)) { |
154 | | if (nlevels(from) * nlevels(to) > 1000) |
155 | | stop("too many levels for the formula target") |
156 | | } else if (length(from) >= 1L && length(to) >= 1L) { |
157 | | f <- as.double(from[[1L]]) |
158 | | t <- as.double(to[[1L]]) |
159 | | if (is.finite(f) && is.finite(t) && abs(t - f) >= 1000) |
160 | | stop("sequence too long for the formula target") |
161 | | } |
162 | | base::`:`(from, to) |
163 | | } |
164 | | bounded$interaction <- function(...) { |
165 | | args <- list(...) |
166 | | if (length(args) == 1L && is.list(args[[1L]])) |
167 | | args <- args[[1L]] |
168 | | n <- 1 |
169 | | for (a in args) |
170 | | n <- n * nlevels(as.factor(a)) |
171 | | if (n > 1000) |
172 | | stop("too many levels for the formula target") |
173 | | base::interaction(...) |
174 | | } |
175 | | function(e, v, fo, data) { |
176 | | e <- fo(e) |
177 | | environment(e) <- bounded |
178 | | d <- data[seq_len(v %% 11L), , drop = FALSE] |
179 | | v <- v %/% 11L |
180 | | mf <- model.frame(e, data = d, na.action = actions[[v %% 4L + 1L]], |
181 | | drop.unused.levels = v %/% 4L %% 2L == 1L) |
182 | | |
183 | | ## model.matrix() turns a logical variable into a factor with |
184 | | ## levels FALSE and TRUE, and a character one into a factor of |
185 | | ## its values. |
186 | | width <- vapply(mf, NCOL, 0L) |
187 | | width[vapply(mf, is.logical, NA)] <- 2L |
188 | | is_character <- vapply(mf, is.character, NA) |
189 | | width[is_character] <- lengths(lapply(mf[is_character], unique)) |
190 | | is_factor <- vapply(mf, is.factor, NA) |
191 | | width[is_factor] <- vapply(mf[is_factor], nlevels, 0L) |
192 | | factors <- attr(attr(mf, "terms"), "factors") |
193 | | if (length(factors)) { |
194 | | columns <- apply(factors != 0, 2L, function(k) |
195 | | prod(width[rownames(factors)[k]])) |
196 | | if (sum(columns) > 4096) |
197 | | stop("too many columns for the formula target") |
198 | | } |
199 | | |
200 | | ct <- contrasts[v %/% 8L %% 5L + 1L] |
201 | | model.matrix(e, mf, contrasts.arg = list(f = ct, g = ct, o = ct)) |
202 | | model.response(mf) |
203 | | model.offset(mf) |
204 | | } |
205 | | }) |
206 | | )"; |
207 | | |
208 | | /* [3] symbolic derivatives in x and y; deriv() also builds the |
209 | | * gradient (and Hessian) code it would return as a function. */ |
210 | | static const char deriv_source[] = R"( |
211 | | function(e, v, fo, data) { |
212 | | D(e, c("x", "y")[v %% 2L + 1L]) |
213 | | deriv(e, c("x", "y"), hessian = v %/% 2L %% 2L == 1L, |
214 | | function.arg = v %/% 4L %% 2L == 1L) |
215 | | } |
216 | | )"; |
217 | | |
218 | | static const char *const sources[N_CALLS] = { |
219 | | terms_source, |
220 | | update_source, |
221 | | model_source, |
222 | | deriv_source, |
223 | | }; |
224 | | |
225 | | enum { SLOT_TERMS, SLOT_UPDATE, SLOT_MODEL, SLOT_DERIV }; |
226 | | |
227 | | static SEXP calls[N_CALLS]; |
228 | | static SEXP expr_cell, variant; |
229 | | |
230 | | /* Upper bound on the number of terms terms() expands e into. Anything |
231 | | * that is not one of the formula operators is a single variable; "." |
232 | | * stands for the data's nine columns. l^k has at most every subset of |
233 | | * l's terms, and at most (l + 1)^k of them when k is a number. |
234 | | * Doubles saturate at Inf, which compares above any limit. */ |
235 | | static double term_bound(SEXP e) |
236 | 466k | { |
237 | 466k | if (TYPEOF(e) == SYMSXP) |
238 | 106k | return strcmp(CHAR(PRINTNAME(e)), ".") == 0 ? 9.0 : 1.0; |
239 | 360k | if (TYPEOF(e) != LANGSXP || TYPEOF(CAR(e)) != SYMSXP) |
240 | 58.0k | return 1.0; |
241 | | |
242 | 302k | const char *op = CHAR(PRINTNAME(CAR(e))); |
243 | 302k | SEXP args = CDR(e); |
244 | 302k | SEXP right = args != R_NilValue && CDR(args) != R_NilValue |
245 | 302k | ? CADR(args) : NULL; |
246 | 302k | double l = args != R_NilValue ? term_bound(CAR(args)) : 1.0; |
247 | 302k | double r = right != NULL ? term_bound(right) : 0.0; |
248 | | |
249 | 302k | if (strcmp(op, "~") == 0 || strcmp(op, "+") == 0 || strcmp(op, "-") == 0) |
250 | 196k | return l + r; |
251 | 105k | if (strcmp(op, ":") == 0 || strcmp(op, "%in%") == 0) |
252 | 11.1k | return l * (r > 0 ? r : 1.0); |
253 | 94.4k | if (strcmp(op, "*") == 0 || strcmp(op, "/") == 0) |
254 | 25.4k | return l + r + l * r; |
255 | 69.0k | if (strcmp(op, "^") == 0) { |
256 | 30.8k | double bound = pow(2.0, l); |
257 | 30.8k | if (right != NULL && (TYPEOF(right) == REALSXP |
258 | 24.3k | || TYPEOF(right) == INTSXP) |
259 | 7.39k | && XLENGTH(right) == 1) { |
260 | 7.39k | double k = Rf_asReal(right); |
261 | | /* PowerTerms crosses once per unit of the exponent even after |
262 | | * every term exists, so the cost grows with k itself: |
263 | | * .^4662 took 13 s with nine data columns. */ |
264 | 7.39k | if (k > FORMULA_MAX_POWER) |
265 | 820 | return R_PosInf; |
266 | 6.57k | if (k >= 1 && pow(l + 1.0, k) < bound) |
267 | 373 | bound = pow(l + 1.0, k); |
268 | 6.57k | } |
269 | 29.9k | return bound; |
270 | 30.8k | } |
271 | 38.2k | if (strcmp(op, "(") == 0) |
272 | 1.56k | return l; |
273 | 36.6k | return 1.0; |
274 | 38.2k | } |
275 | | |
276 | | static int max_depth(SEXP e) |
277 | 14.6k | { |
278 | 14.6k | if (TYPEOF(e) != LANGSXP) |
279 | 9.42k | return 0; |
280 | 5.20k | int deepest = 0; |
281 | 19.0k | for (SEXP a = e; a != R_NilValue; a = CDR(a)) { |
282 | 13.8k | int d = max_depth(CAR(a)); |
283 | 13.8k | if (d > deepest) |
284 | 3.68k | deepest = d; |
285 | 13.8k | } |
286 | 5.20k | return deepest + 1; |
287 | 14.6k | } |
288 | | |
289 | | static int is_eval_name(SEXP sym) |
290 | 493k | { |
291 | 493k | const char *name = CHAR(PRINTNAME(sym)); |
292 | 6.00M | for (size_t i = 0; i < N_EVAL_NAMES; i++) |
293 | 6.00M | if (strcmp(name, eval_names[i]) == 0) |
294 | 493k | return 1; |
295 | 52 | return 0; |
296 | 493k | } |
297 | | |
298 | | /* TRUE when every symbol in e, call heads and argument names included, |
299 | | * is in eval_names. */ |
300 | | static int only_eval_names(SEXP e) |
301 | 950k | { |
302 | 950k | switch (TYPEOF(e)) { |
303 | 506k | case SYMSXP: |
304 | 506k | return e == R_MissingArg || is_eval_name(e); |
305 | 365k | case LANGSXP: |
306 | 365k | case LISTSXP: |
307 | 1.30M | for (SEXP a = e; a != R_NilValue; a = CDR(a)) { |
308 | 942k | if (TAG(a) != R_NilValue && !is_eval_name(TAG(a))) |
309 | 8 | return 0; |
310 | 942k | if (!only_eval_names(CAR(a))) |
311 | 250 | return 0; |
312 | 942k | } |
313 | 365k | return 1; |
314 | 23 | case NILSXP: |
315 | 112 | case LGLSXP: |
316 | 11.2k | case INTSXP: |
317 | 54.4k | case REALSXP: |
318 | 75.5k | case CPLXSXP: |
319 | 78.0k | case STRSXP: |
320 | 78.0k | return 1; |
321 | 0 | default: |
322 | 0 | return 0; |
323 | 950k | } |
324 | 950k | } |
325 | | |
326 | | /* Parse the text into expr_cell's single element under a toplevel |
327 | | * context; the parser can raise R errors (memory, nesting) itself. */ |
328 | | typedef struct { |
329 | | const char *text; |
330 | | int ok; |
331 | | } parse_job_t; |
332 | | |
333 | | static void do_parse(void *data) |
334 | 12.3k | { |
335 | 12.3k | parse_job_t *job = data; |
336 | 12.3k | ParseStatus status; |
337 | 12.3k | SEXP text, parsed; |
338 | 12.3k | Rf_protect(text = Rf_mkString(job->text)); |
339 | 12.3k | Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue)); |
340 | 12.3k | if (status == PARSE_OK && XLENGTH(parsed) == 1) { |
341 | 10.3k | SETCAR(expr_cell, VECTOR_ELT(parsed, 0)); |
342 | 10.3k | job->ok = 1; |
343 | 10.3k | } |
344 | 12.3k | Rf_unprotect(2); |
345 | 12.3k | } |
346 | | |
347 | | int fuzz_target_init(int *argc, char ***argv) |
348 | 2 | { |
349 | 2 | (void)argc; |
350 | 2 | (void)argv; |
351 | 2 | fuzz_init_r(); |
352 | | |
353 | 2 | SEXP fo, data, quote_call; |
354 | 2 | Rf_protect(fo = fuzz_make_wrapper(as_formula_source)); |
355 | 2 | Rf_protect(data = fuzz_make_wrapper(data_source)); |
356 | 2 | Rf_protect(variant = Rf_ScalarInteger(0)); |
357 | | |
358 | | /* The expression reaches each slot as quote(<expr>), so evaluating |
359 | | * the argument hands it over unevaluated. All slots share the one |
360 | | * quote() call, and expr_cell is its argument cell: a SETCAR there |
361 | | * stages the parsed input for whichever slot runs. */ |
362 | 2 | Rf_protect(quote_call = Rf_lang2(Rf_install("quote"), R_NilValue)); |
363 | 2 | expr_cell = CDR(quote_call); |
364 | 10 | for (int i = 0; i < N_CALLS; i++) { |
365 | 8 | SEXP wrapper; |
366 | 8 | Rf_protect(wrapper = fuzz_make_wrapper(sources[i])); |
367 | 8 | Rf_protect(calls[i] = Rf_lang5(wrapper, quote_call, variant, fo, data)); |
368 | 8 | } |
369 | 2 | fuzz_label_calls(calls, N_CALLS); |
370 | | |
371 | | /* Warmup: load stats' model code and the deriv tables. */ |
372 | 2 | SETCAR(expr_cell, Rf_install("x")); |
373 | 10 | for (int i = 0; i < N_CALLS; i++) |
374 | 8 | fuzz_eval_silent(calls[i], R_GlobalEnv); |
375 | 2 | return 0; |
376 | 2 | } |
377 | | |
378 | | int fuzz_target_run(const uint8_t *data, size_t size) |
379 | 12.3k | { |
380 | 12.3k | if (size < FUZZ_HEADER + 1 || size > FUZZ_MAX_INPUT |
381 | 12.3k | || memchr(data + FUZZ_HEADER, '\0', size - FUZZ_HEADER)) |
382 | 6 | return 0; |
383 | | |
384 | 12.3k | char buffer[FUZZ_MAX_INPUT]; |
385 | 12.3k | memcpy(buffer, data + FUZZ_HEADER, size - FUZZ_HEADER); |
386 | 12.3k | buffer[size - FUZZ_HEADER] = '\0'; |
387 | | |
388 | 12.3k | parse_job_t job = { buffer, 0 }; |
389 | 12.3k | SETCAR(expr_cell, R_NilValue); |
390 | 12.3k | if (!R_ToplevelExec(do_parse, &job) || !job.ok) |
391 | 2.00k | return 0; |
392 | | |
393 | 10.3k | int slot = data[0] % N_CALLS; |
394 | 10.3k | SEXP e = CAR(expr_cell); |
395 | 10.3k | if ((slot == SLOT_TERMS || slot == SLOT_UPDATE || slot == SLOT_MODEL) |
396 | 9.54k | && !(term_bound(e) <= FORMULA_MAX_TERMS)) |
397 | 11 | return 0; |
398 | 10.3k | if (slot == SLOT_MODEL && !only_eval_names(e)) |
399 | 52 | return 0; |
400 | 10.2k | if (slot == SLOT_DERIV && max_depth(e) > DERIV_MAX_DEPTH) |
401 | 13 | return 0; |
402 | | |
403 | 10.2k | INTEGER(variant)[0] = data[1]; |
404 | 10.2k | fuzz_eval_silent(calls[slot], R_GlobalEnv); |
405 | 10.2k | return 0; |
406 | 10.2k | } |