/src/r-oss-fuzz/harnesses/eval.c
Line | Count | Source |
1 | | /* |
2 | | * Evaluate R source in a fresh environment with selected primitives only. |
3 | | * |
4 | | * The parse target stops at R_ParseVector; this one runs what it parsed, |
5 | | * which is where the interpreter core lives (eval.c, envir.c, subset.c, |
6 | | * subassign.c, coerce.c, arithmetic.c). Each input is evaluated in a new |
7 | | * environment whose locked parent holds a small allowlist of primitives, |
8 | | * so the input can define closures, build and index vectors, loop and |
9 | | * branch, set attributes and dispatch S3 methods of its own, but cannot |
10 | | * reach I/O, native calls, namespaces, reflection or process-global state. |
11 | | * |
12 | | * The allowlist is not a security sandbox -- it cannot contain a bug in |
13 | | * the interpreter -- and does not need to be: the fuzzing host is |
14 | | * disposable. It exists so that fuzzing cycles go to the evaluator rather |
15 | | * than the filesystem, and so that every finding is a crash reachable from |
16 | | * ordinary R code. That second property is what makes a report from this |
17 | | * target unambiguous: nothing here needs .Internal, body<- or any other |
18 | | * "you asked for it" entry point. |
19 | | * |
20 | | * Each top-level expression is byte-compiled before it runs, so what is |
21 | | * fuzzed is the byte-code interpreter with the AST interpreter behind it, |
22 | | * the same mix a session runs; see eval_compile. |
23 | | */ |
24 | | |
25 | | /* 8 MiB, not common.h's 1 GiB: the budget below is counted in evaluations, |
26 | | * and one evaluation can do a whole vector's worth of work, so the vector |
27 | | * heap is what caps the work of any one evaluation. Base R itself needs |
28 | | * about 1 MiB of it. R ignores a maximum below its initial heap (64 MiB), |
29 | | * so fuzz_target_init lowers R_VSIZE to match. */ |
30 | 2 | #define FUZZ_R_MAX_VSIZE "8Mb" |
31 | | #include "common.h" |
32 | | |
33 | | #include <time.h> |
34 | | #include <R_ext/eventloop.h> /* R_PolledEvents */ |
35 | | |
36 | 37.5k | #define FUZZ_MAX_INPUT 8192 |
37 | 1.35M | #define FUZZ_MAX_DEPTH 64 |
38 | 1.92M | #define FUZZ_MAX_NODES 1024 |
39 | | |
40 | | /* Interrupt checks one input may make before it is cut off. eval() checks |
41 | | * for interrupts once per 10 evaluations (instrumentation/0001; stock R: |
42 | | * once per 1000) and C loops that call R_CheckUserInterrupt add |
43 | | * their own, so this is roughly 200k evaluations: well under a second even |
44 | | * with sanitizers, and deterministic, which a wall-clock limit is not. |
45 | | * See eval_poll_budget. */ |
46 | 16.7k | #define FUZZ_EVAL_BUDGET 20000 |
47 | | |
48 | | /* CPU seconds an input may use before the next budget check cuts it off, |
49 | | * whatever the budget says. A backstop for vector-heavy loops, where the |
50 | | * budget's unit of work is too coarse; see eval_poll_budget. */ |
51 | 14.0M | #define FUZZ_EVAL_CPU_LIMIT 1.0 |
52 | | |
53 | | /* The allowlist frame, the wrappers frame below it, compiler::compile, and |
54 | | * the closure that puts the allowlist frame's attributes back, with the |
55 | | * attributes it puts back. */ |
56 | | static SEXP eval_builtins, eval_wrappers, eval_compile_fn; |
57 | | static SEXP eval_reset_builtins_fn, eval_builtins_attributes; |
58 | | |
59 | | /* Remaining interrupt checks for the current input; 0 means no limit. */ |
60 | | static long eval_budget; |
61 | | static clock_t eval_cpu_start; |
62 | | |
63 | | /* Only primitives: importing a base closure would also import its enclosing |
64 | | * namespace and the capabilities reachable through its implementation. |
65 | | * No reflection or metaprogramming APIs are exposed; language objects from |
66 | | * quote() and substitute() are inert without eval(). Closures created by |
67 | | * the input inherit only the restricted environment. `:`, seq_len, |
68 | | * seq.int, `attr<-` and `attributes<-` are provided separately, through |
69 | | * wrappers (below); class<- and oldClass<- not at all. |
70 | | */ |
71 | | static const char *const eval_primitives[] = { |
72 | | "{", "(", "if", "for", "while", "repeat", "break", "next", |
73 | | "function", "return", "<-", "=", |
74 | | "+", "-", "*", "/", "^", "%%", "%/%", |
75 | | "==", "!=", "<", "<=", ">", ">=", "!", "&", "|", "&&", "||", |
76 | | "c", "list", "[", "[[", "$", "[<-", "[[<-", "$<-", |
77 | | "length", "is.null", "is.logical", "is.integer", "is.double", |
78 | | "is.complex", "is.character", "is.list", "is.na", "is.nan", "is.finite", |
79 | | "is.infinite", "as.integer", "as.double", "as.logical", "as.character", |
80 | | "as.complex", "as.raw", "abs", "sqrt", "floor", "ceiling", "trunc", |
81 | | "sum", "prod", "min", "max", "any", "all", "invisible", |
82 | | /* Language objects, argument introspection and switch. Not on.exit: |
83 | | * its code runs during the unwind the budget error starts, and |
84 | | * on.exit(return(1)) redirects that unwind back into the function, so |
85 | | * `h <- function() { on.exit(return(1)); repeat {} }; repeat h()` would |
86 | | * swallow every budget error and never end. Letting it in needs a |
87 | | * way to end an input that R code cannot redirect, which is an |
88 | | * instrumentation/ change to R_run_onexits, not an allowlist entry. */ |
89 | | "quote", "substitute", "missing", "nargs", "switch", |
90 | | /* Attributes other than class; see the wrappers for `attr<-`. */ |
91 | | "attr", "attributes", "names", "names<-", "dim", "dim<-", "dimnames", |
92 | | "dimnames<-", "levels<-", "unclass", "class", "oldClass", |
93 | | /* S3 dispatch on the implicit class to methods the input defines; |
94 | | * .GenericDefEnv is the allowlist frame itself, see eval_reset_builtins. |
95 | | * NextMethod is a closure and is not imported. */ |
96 | | "UseMethod", |
97 | | /* rep allocates its result, so the vector heap bounds it; the compact |
98 | | * sequence builders are wrapped below. */ |
99 | | "rep", "seq_along", |
100 | | /* Tier 2 (docs/eval.md): the remaining computational primitives. |
101 | | * Every result is allocated, so the vector heap bounds each call and |
102 | | * the budget bounds the number of calls. The primitives base has and |
103 | | * this list leaves out are each a capability or a way past a limit: |
104 | | * .Internal, .Primitive, the foreign-function interfaces (.C, .Call, |
105 | | * .External, .Fortran and their graphics forms), environments |
106 | | * (as.environment, baseenv, emptyenv, globalenv, pos.to.env, |
107 | | * environment<-; and ~, which captures the caller's), <<- (assigns in |
108 | | * the global environment when the name is not found), evaluation |
109 | | * (Exec, Tailcall, forceAndCall, standardGeneric), on.exit, |
110 | | * class<- and oldClass<- and @<- (slots are attributes, class |
111 | | * included; see the wrappers), process state (.isMethodsDispatchOn, |
112 | | * .cache_class, interactive, proc.time, gc.time, tracing, browser, |
113 | | * lazyLoadDBfetch) and the namespace operators :: and :::. */ |
114 | | "log", "exp", "expm1", "log1p", "log2", "log10", |
115 | | "sin", "cos", "tan", "sinpi", "cospi", "tanpi", |
116 | | "asin", "acos", "atan", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", |
117 | | "gamma", "lgamma", "digamma", "trigamma", |
118 | | "round", "signif", "sign", |
119 | | "Re", "Im", "Mod", "Arg", "Conj", |
120 | | "cumsum", "cumprod", "cummax", "cummin", "range", |
121 | | "%*%", "crossprod", "tcrossprod", |
122 | | "anyNA", "xtfrm", "nzchar", "enc2native", "enc2utf8", |
123 | | "as.numeric", "as.call", "call", "expression", "length<-", |
124 | | "storage.mode<-", "is.array", "is.atomic", "is.call", "is.expression", |
125 | | "is.function", "is.language", "is.matrix", "is.name", "is.numeric", |
126 | | "is.object", "is.pairlist", "is.raw", "is.recursive", "is.single", |
127 | | "is.symbol", "isS4", "@", ".class2", ".subset", ".subset2", |
128 | | "...elt", "...length", "...names", "declare", "unCfillPOSIXlt" |
129 | | }; |
130 | | |
131 | | /* |
132 | | * Wrappers: closures standing in for primitives whose plain form would |
133 | | * get past a limit. Each is bound in eval_wrappers, a frame of its own |
134 | | * below the allowlist, because the compiler inlines and constant-folds |
135 | | * calls to names it finds in the base-like frame (the COLON and SEQLEN |
136 | | * instructions; `:`, seq_len, seq.int and rep are in its foldFuns), and |
137 | | * an inlined call would bypass the wrapper (see eval_compile). The |
138 | | * wrappers share one private enclosure holding only the primitives their |
139 | | * bodies name (`function` included: it is a primitive looked up like any |
140 | | * other), the wrapped primitives under dotted names, and .Internal, bound |
141 | | * there to raise the errors and nowhere the input can see. So they add |
142 | | * no capability. |
143 | | * |
144 | | * `:`, seq_len and seq.int build compact ALTREP sequences, which cost |
145 | | * nothing to create whatever their length; the reductions without an |
146 | | * ALTREP shortcut (prod, or min/max/sum with two arguments) then walk 1e9 |
147 | | * elements in C without an interrupt check: 8-18 s under ASAN, which the |
148 | | * budget cannot see and ClusterFuzz would file as a timeout. Nothing |
149 | | * else in the allowlist builds a long vector without allocating it, and |
150 | | * allocation is bounded by the vector heap. `:` is capped on what it |
151 | | * uses: the first element of each argument, as a double, so a longer |
152 | | * vector or a character argument (`c(1e12, 1):5`, `"1":"1e9"`) is bounded |
153 | | * like a scalar. seq_len and seq.int have more argument forms, so they |
154 | | * are capped on the result instead: building it is free, and its length |
155 | | * is known before anything walks it. |
156 | | * |
157 | | * `attr<-` and `attributes<-` refuse two things. The class attribute: an |
158 | | * object with one dispatches every internal generic in the allowlist |
159 | | * (`[`, `+`, `length`, `c`, ...) to the S3 methods base registers for its |
160 | | * classes -- `[.data.frame`, `Ops.Date`, `$.DLLInfo` -- which are closures |
161 | | * over the base namespace running on input-shaped data, and a crash in |
162 | | * one of them on `class(x) <- "DLLInfo"` is the "you asked for it" report |
163 | | * this target is meant not to produce. UseMethod dispatches on the |
164 | | * implicit class (matrix, integer, function, ...) to methods the input |
165 | | * defines, which is the dispatch code this allowlist is for. And |
166 | | * environments: UseMethod hands the method .GenericDefEnv, which is the |
167 | | * allowlist frame itself, whose bindings are locked but whose attributes |
168 | | * are not (see eval_reset_builtins). The other setters in the allowlist |
169 | | * either reject environments (names<-, dim<-, dimnames<-) or set only |
170 | | * their own attribute (levels<-). |
171 | | */ |
172 | | static const char *const eval_wrapper_primitives[] = { |
173 | | "function", "{", "if", "&&", "||", ">=", ">", "==", "-", "<-", "length", |
174 | | "[[", "as.double", "is.finite", "abs", "is.character", "is.na", "!", |
175 | | "any", "names", "is.environment", ".Internal" |
176 | | }; |
177 | | |
178 | | static const char eval_colon_source[] = R"( |
179 | | function(from, to) { |
180 | | if (length(from) >= 1L && length(to) >= 1L) { |
181 | | f <- as.double(from[[1L]]) |
182 | | t <- as.double(to[[1L]]) |
183 | | if (is.finite(f) && is.finite(t) && abs(t - f) >= 1e6) |
184 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
185 | | } |
186 | | .colon(from, to) |
187 | | } |
188 | | )"; |
189 | | |
190 | | static const char eval_seq_len_source[] = R"( |
191 | | function(length.out) { |
192 | | x <- .seq_len(length.out) |
193 | | if (length(x) > 1e6) |
194 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
195 | | x |
196 | | } |
197 | | )"; |
198 | | |
199 | | static const char eval_seq_int_source[] = R"( |
200 | | function(...) { |
201 | | x <- .seq_int(...) |
202 | | if (length(x) > 1e6) |
203 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
204 | | x |
205 | | } |
206 | | )"; |
207 | | |
208 | | static const char eval_attr_set_source[] = R"( |
209 | | function(x, which, value) { |
210 | | if (is.environment(x)) |
211 | | .Internal(stop(TRUE, "attributes of environments cannot be set in the eval target")) |
212 | | if (is.character(which) && length(which) == 1L && !is.na(which) && |
213 | | which == "class") |
214 | | .Internal(stop(TRUE, "the class attribute is not available in the eval target")) |
215 | | .attr_set(x, which, value = value) |
216 | | } |
217 | | )"; |
218 | | |
219 | | static const char eval_attributes_set_source[] = R"( |
220 | | function(x, value) { |
221 | | if (is.environment(x)) |
222 | | .Internal(stop(TRUE, "attributes of environments cannot be set in the eval target")) |
223 | | if (any(names(value) == "class")) |
224 | | .Internal(stop(TRUE, "the class attribute is not available in the eval target")) |
225 | | .attributes_set(x, value) |
226 | | } |
227 | | )"; |
228 | | |
229 | | typedef struct { |
230 | | const char *name; /* bound in eval_wrappers */ |
231 | | const char *primitive; /* the primitive, bound in the private enclosure */ |
232 | | const char *source; |
233 | | } eval_wrapper_t; |
234 | | |
235 | | static const eval_wrapper_t eval_wrapper_table[] = { |
236 | | { ":", ".colon", eval_colon_source }, |
237 | | { "seq_len", ".seq_len", eval_seq_len_source }, |
238 | | { "seq.int", ".seq_int", eval_seq_int_source }, |
239 | | { "attr<-", ".attr_set", eval_attr_set_source }, |
240 | | { "attributes<-", ".attributes_set", eval_attributes_set_source }, |
241 | | }; |
242 | | |
243 | | typedef struct { |
244 | | const uint8_t *data; |
245 | | size_t size; |
246 | | } eval_input_t; |
247 | | |
248 | | /* |
249 | | * Execution budget, counted in interrupt checks. |
250 | | * |
251 | | * R_CheckUserInterrupt() -> R_ProcessEvents() -> R_PolledEvents() is the |
252 | | * hook R offers for event loops, and it is reached from the same places |
253 | | * that honour setTimeLimit(): every 10th eval() of the AST interpreter |
254 | | * (every 1000th in stock R; instrumentation/0001 lowers it), |
255 | | * the byte-code loop back-edges, and the long-running C loops that poll |
256 | | * for interrupts. Counting those calls instead of CPU time gives every |
257 | | * input the same budget on every machine, so an input that is cut off |
258 | | * under ASAN on a slow bot is cut off the same way in a local reproduction, |
259 | | * and libFuzzer's coverage feedback stops depending on timing. |
260 | | * |
261 | | * Exactness is to within one check interval: eval()'s counter is static |
262 | | * and carries over between inputs. |
263 | | * |
264 | | * The unit is an evaluation, and an evaluation can be `!x` over the whole |
265 | | * heap: with a 64 MiB heap and a check every 1000 evaluations, |
266 | | * `x <- !1:4e4; repeat !x` ran 15 s under ASAN before the budget was |
267 | | * spent, and would have been filed as a timeout. Three things bound that. |
268 | | * The heap is small (8 MiB), which caps the work of any one evaluation. |
269 | | * The check interval is short (instrumentation/0001), which caps the number of |
270 | | * evaluations between two checks. And a CPU backstop ends the input at |
271 | | * the first check after FUZZ_EVAL_CPU_LIMIT seconds, whatever the budget |
272 | | * says. The backstop is the one timing-dependent limit left, and it only |
273 | | * decides whether a vector-heavy input completes or errors, never whether |
274 | | * it crashes; it sits far below ClusterFuzz's timeout threshold so that |
275 | | * difference stays out of the tracker. |
276 | | * |
277 | | * The error unwinds to R_tryEvalSilent like any other R error. Raising it |
278 | | * from inside R_ProcessEvents is what R_CheckTimeLimits does, so the |
279 | | * interpreter is prepared for a longjmp at this point. The budget is |
280 | | * zero by the time either error is raised, which switches the check off, |
281 | | * so nothing on the error path can re-enter it. No input code runs once |
282 | | * the error is raised: there are no handlers or on.exit in the allowlist, |
283 | | * and that is a condition of this design (see eval_primitives). |
284 | | */ |
285 | | static void eval_poll_budget(void) |
286 | 14.1M | { |
287 | 14.1M | if (eval_budget <= 0) |
288 | 34.7k | return; |
289 | | |
290 | 14.0M | if (--eval_budget == 0) |
291 | 602 | Rf_error("evaluation budget exhausted"); |
292 | | |
293 | 14.0M | if ((double)(clock() - eval_cpu_start) / CLOCKS_PER_SEC > FUZZ_EVAL_CPU_LIMIT) { |
294 | 286 | eval_budget = 0; |
295 | 286 | Rf_error("evaluation CPU limit exhausted"); |
296 | 286 | } |
297 | 14.0M | } |
298 | | |
299 | | /* UseMethod() binds .GenericDefEnv in the method's frame to the top |
300 | | * environment of the generic's enclosure, which here is the allowlist frame |
301 | | * itself. Its bindings are locked, but attributes are not bindings. Two |
302 | | * things keep that harmless. The wrappers for attr<- and attributes<- |
303 | | * refuse environments, so the input cannot take away the frame's name, |
304 | | * which topenv() would otherwise stop recognising -- it then falls back to |
305 | | * R_GlobalEnv, and UseMethod's method lookup from there reaches base's own |
306 | | * S3 methods (with.default evaluates its argument with the whole of base |
307 | | * in scope). And the frame carries a locked .packageName binding, which |
308 | | * topenv() accepts on its own, so recognition never rests on an attribute |
309 | | * at all. What is left is levels<-, which can hang a heap-sized attribute |
310 | | * on the frame that would outlive the input; so the attributes are put |
311 | | * back after every input. (.GenericCallEnv is the caller's frame, the |
312 | | * input's own.) Through R, since the attribute list is not reachable from |
313 | | * the public API; in two steps with a preserved value, so that nothing is |
314 | | * allocated while an attribute the input left may be filling the heap. */ |
315 | | static const char eval_reset_builtins_source[] = R"( |
316 | | function(env, value) { |
317 | | attributes(env) <- NULL |
318 | | attributes(env) <- value |
319 | | } |
320 | | )"; |
321 | | |
322 | | static void eval_reset_builtins(void) |
323 | 16.7k | { |
324 | 16.7k | SEXP call; |
325 | 16.7k | Rf_protect(call = Rf_lang3(eval_reset_builtins_fn, eval_builtins, |
326 | 16.7k | eval_builtins_attributes)); |
327 | 16.7k | Rf_eval(call, R_BaseEnv); |
328 | 16.7k | Rf_unprotect(1); |
329 | 16.7k | } |
330 | | |
331 | | static void eval_reset_builtins_exec(void *unused) |
332 | 268 | { |
333 | 268 | (void)unused; |
334 | 268 | eval_reset_builtins(); |
335 | 268 | } |
336 | | |
337 | | /* The allowlist is only ever primitives (see eval_primitives): a name that |
338 | | * stops being one would silently import a closure and its namespace. */ |
339 | | static SEXP eval_primitive(const char *name) |
340 | 384 | { |
341 | 384 | SEXP value = Rf_findFun(Rf_install(name), R_BaseEnv); |
342 | 384 | if (TYPEOF(value) != BUILTINSXP && TYPEOF(value) != SPECIALSXP) { |
343 | 0 | fprintf(stderr, "eval: %s is no longer a primitive\n", name); |
344 | 0 | abort(); |
345 | 0 | } |
346 | 384 | return value; |
347 | 384 | } |
348 | | |
349 | | static void eval_import_primitives(SEXP env, const char *const *names, size_t n) |
350 | 4 | { |
351 | 378 | for (size_t i = 0; i < n; i++) |
352 | 374 | Rf_defineVar(Rf_install(names[i]), eval_primitive(names[i]), env); |
353 | 4 | } |
354 | | |
355 | | /* Parse and evaluate one expression of set-up code. A failure here is a |
356 | | * harness bug, so it stops the process rather than becoming an R error. */ |
357 | | static SEXP eval_run_init(const char *source, SEXP env) |
358 | 16 | { |
359 | 16 | ParseStatus status; |
360 | 16 | SEXP text, parsed, value; |
361 | 16 | int error = 0; |
362 | | |
363 | 16 | Rf_protect(text = Rf_mkString(source)); |
364 | 16 | Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue)); |
365 | 16 | if (status != PARSE_OK || XLENGTH(parsed) != 1) |
366 | 0 | abort(); |
367 | | |
368 | 16 | value = R_tryEvalSilent(VECTOR_ELT(parsed, 0), env, &error); |
369 | 16 | if (error) { |
370 | 0 | fprintf(stderr, "eval: set-up failed: %s", R_curErrorBuf()); |
371 | 0 | abort(); |
372 | 0 | } |
373 | | |
374 | 16 | Rf_unprotect(2); |
375 | 16 | return value; |
376 | 16 | } |
377 | | |
378 | | static int eval_valid_utf8(const uint8_t *data, size_t size) |
379 | 18.7k | { |
380 | 18.7k | size_t i = 0; |
381 | 2.96M | while (i < size) { |
382 | 2.94M | uint8_t c = data[i++]; |
383 | 2.94M | if (c < 0x80) |
384 | 2.91M | continue; |
385 | 26.3k | if (c >= 0xc2 && c <= 0xdf) { |
386 | 12.0k | if (i >= size || (data[i++] & 0xc0) != 0x80) |
387 | 5 | return 0; |
388 | 12.0k | continue; |
389 | 12.0k | } |
390 | 14.3k | if (c >= 0xe0 && c <= 0xef) { |
391 | 5.33k | if (i + 1 >= size || (data[i] & 0xc0) != 0x80 || |
392 | 5.33k | (data[i + 1] & 0xc0) != 0x80 || |
393 | 5.33k | (c == 0xe0 && data[i] < 0xa0) || |
394 | 5.32k | (c == 0xed && data[i] >= 0xa0)) |
395 | 10 | return 0; |
396 | 5.32k | i += 2; |
397 | 5.32k | continue; |
398 | 5.33k | } |
399 | 9.01k | if (c >= 0xf0 && c <= 0xf4) { |
400 | 9.00k | if (i + 2 >= size || (data[i] & 0xc0) != 0x80 || |
401 | 8.99k | (data[i + 1] & 0xc0) != 0x80 || |
402 | 8.98k | (data[i + 2] & 0xc0) != 0x80 || |
403 | 8.98k | (c == 0xf0 && data[i] < 0x90) || |
404 | 8.98k | (c == 0xf4 && data[i] >= 0x90)) |
405 | 19 | return 0; |
406 | 8.98k | i += 3; |
407 | 8.98k | continue; |
408 | 9.00k | } |
409 | 19 | return 0; |
410 | 9.01k | } |
411 | 18.7k | return 1; |
412 | 18.7k | } |
413 | | |
414 | | /* Bound the post-parse walk, including wide argument lists. This limits test |
415 | | * complexity, not execution time: even a tiny expression can loop forever. |
416 | | */ |
417 | | static int eval_tree_within_budget(SEXP x, unsigned depth, unsigned *nodes) |
418 | 675k | { |
419 | 675k | if (depth > FUZZ_MAX_DEPTH || ++*nodes > FUZZ_MAX_NODES) |
420 | 58 | return 0; |
421 | | |
422 | 675k | switch (TYPEOF(x)) { |
423 | 225k | case LANGSXP: |
424 | 226k | case LISTSXP: |
425 | 846k | for (SEXP p = x; p != R_NilValue; p = CDR(p)) { |
426 | 624k | if (++*nodes > FUZZ_MAX_NODES || |
427 | 624k | !eval_tree_within_budget(CAR(p), depth + 1, nodes)) |
428 | 3.61k | return 0; |
429 | 624k | } |
430 | 222k | return 1; |
431 | 16.5k | case EXPRSXP: |
432 | 51.6k | for (R_xlen_t i = 0; i < XLENGTH(x); i++) { |
433 | 35.1k | if (!eval_tree_within_budget(VECTOR_ELT(x, i), depth + 1, nodes)) |
434 | 83 | return 0; |
435 | 35.1k | } |
436 | 16.4k | return 1; |
437 | 432k | default: |
438 | 432k | return 1; |
439 | 675k | } |
440 | 675k | } |
441 | | |
442 | | /* |
443 | | * Byte-code. |
444 | | * |
445 | | * Nearly all R code that runs in a session is byte-compiled: packages at |
446 | | * install time, everything else by the JIT after a call or two. The JIT |
447 | | * is not used here (R_ENABLE_JIT=0): it compiles on its own schedule, |
448 | | * keeps a cache across inputs, and catches errors inside the compiler, |
449 | | * where a budget error would be swallowed and the budget left switched |
450 | | * off. Instead the harness compiles each top-level expression itself |
451 | | * and evaluates the result. Closures the input defines are created with |
452 | | * compiled bodies (MAKECLOSURE), top-level loops are compiled too, and |
453 | | * anything the compiler declines runs through the AST interpreter, which |
454 | | * is what the JIT falls back to as well. Constant folding evaluates base |
455 | | * functions on literals only. |
456 | | * |
457 | | * The compiler (compiler:::cmp.R, or bccompile.c where features/0001 is |
458 | | * applied; both emit the same code) needs two things from the sandbox. It |
459 | | * refuses an environment whose chain does not end in a frame topenv() |
460 | | * recognises, and it inlines base syntax and arithmetic only for names it |
461 | | * finds bound in a frame it classifies as base, by the frame's "name" |
462 | | * attribute. So eval_builtins carries the name of base's package frame. |
463 | | * Its bindings are base's own primitives, so the BASEGUARD check that |
464 | | * compiled code makes before an inlined builtin call passes, and a name |
465 | | * the input rebinds is looked up like any other. isBaseVar, which gates |
466 | | * whether break/next compile to a jump or to a loop context, compares |
467 | | * frames by identity instead, so it is rebound to accept the named frame; |
468 | | * without that every loop with a conditional break would compile with a |
469 | | * context, which a session's would not. The rebinding cannot reach |
470 | | * bccompile.c's twin of isBaseVar; instrumentation/0007 changes that one. |
471 | | */ |
472 | | static const char eval_compiler_setup[] = R"( |
473 | | local({ |
474 | | ns <- asNamespace("compiler") |
475 | | isBaseVar <- function(var, cntxt) { |
476 | | info <- getInlineInfo(var, cntxt) |
477 | | !is.null(info) && |
478 | | (identical(info$frame, .BaseNamespaceEnv) || |
479 | | identical(info$frame, baseenv()) || |
480 | | packFrameName(info$frame) == "base") |
481 | | } |
482 | | environment(isBaseVar) <- ns |
483 | | unlockBinding("isBaseVar", ns) |
484 | | assign("isBaseVar", isBaseVar, envir = ns) |
485 | | lockBinding("isBaseVar", ns) |
486 | | compiler::compile |
487 | | }) |
488 | | )"; |
489 | | |
490 | | /* Run once at start-up, so the compiler's lazily loaded internals are in |
491 | | * memory before the first input and every input sees the same R. */ |
492 | | static const char eval_warmup_source[] = R"( |
493 | | f <- function(n) { |
494 | | s <- 0 |
495 | | for (i in 1:n) if (i %% 2 == 0) s <- s + i else next |
496 | | s |
497 | | } |
498 | | x <- c(f(10), 1) |
499 | | x[[2]] <- x[1] |
500 | | g <- function(...) list(...) |
501 | | g(x, repeat break) |
502 | | h <- function(x) UseMethod("h") |
503 | | h.default <- function(x) switch(class(x), numeric = nargs(), 2) |
504 | | h.function <- function(x) attr(unclass(x), "srcref") |
505 | | h(x); h(g) |
506 | | y <- seq_len(3); names(y) <- c("a", "b", "c"); dim(y) <- 3L; y[[2L]] |
507 | | )"; |
508 | | |
509 | | /* Byte-code for expr, or expr itself if the compiler declined it. |
510 | | * |
511 | | * cmp.R is R code and runs under the input's budget like the code it |
512 | | * produces. It used to run with the budget paused, bounded only by |
513 | | * the parsed-tree limits, but its cost is not linear in the tree: constant |
514 | | * folding re-walks every subtree at each level of nesting, so an |
515 | | * expression nested 62 calls deep compiles in about a second under ASAN |
516 | | * and four of them (270 bytes, within the tree limits) in over four, |
517 | | * which on the bots was the 25 s libFuzzer timeout. A compile the |
518 | | * budget cuts off leaves eval_budget at zero; the caller stops the input |
519 | | * there rather than running the expression uncompiled. bccompile.c |
520 | | * (features/0001) never polls, so only the parsed-tree limits bound it, |
521 | | * which keeps those four expressions to about 15 ms without sanitizers. |
522 | | */ |
523 | | static SEXP eval_compile(SEXP expr, SEXP env) |
524 | 31.2k | { |
525 | 31.2k | SEXP quoted, call, code; |
526 | 31.2k | int error = 0; |
527 | | |
528 | 31.2k | Rf_protect(quoted = Rf_lang2(R_QuoteSymbol, expr)); |
529 | 31.2k | Rf_protect(call = Rf_lang3(eval_compile_fn, quoted, env)); |
530 | 31.2k | code = R_tryEvalSilent(call, R_BaseEnv, &error); |
531 | 31.2k | Rf_unprotect(2); |
532 | | |
533 | 31.2k | return error ? expr : code; |
534 | 31.2k | } |
535 | | |
536 | | /* Caller protects the returned object immediately if it needs the result. |
537 | | * All errors (including parsing/allocation) must be under R_ToplevelExec. |
538 | | */ |
539 | | static SEXP eval_source(const eval_input_t *input, int *error) |
540 | 18.7k | { |
541 | 18.7k | ParseStatus status; |
542 | 18.7k | SEXP text, parsed, env, result = R_NilValue; |
543 | 18.7k | Rf_protect(text = Rf_allocVector(STRSXP, 1)); |
544 | 18.7k | SET_STRING_ELT(text, 0, |
545 | 18.7k | Rf_mkCharLenCE((const char *)input->data, (int)input->size, |
546 | 18.7k | CE_UTF8)); |
547 | 18.7k | Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue)); |
548 | 18.7k | unsigned nodes = 0; |
549 | 18.7k | if (status != PARSE_OK || !eval_tree_within_budget(parsed, 0, &nodes)) { |
550 | 2.01k | *error = 1; |
551 | 2.01k | Rf_unprotect(2); |
552 | 2.01k | return R_NilValue; |
553 | 2.01k | } |
554 | | |
555 | | /* One budget covers all top-level expressions of an input. */ |
556 | 16.7k | Rf_protect(env = R_NewEnv(eval_wrappers, TRUE, 29)); |
557 | 16.7k | eval_cpu_start = clock(); |
558 | 16.7k | eval_budget = FUZZ_EVAL_BUDGET; |
559 | 39.1k | for (R_xlen_t i = 0; i < XLENGTH(parsed); i++) { |
560 | 31.2k | SEXP code; |
561 | 31.2k | Rf_protect(code = eval_compile(VECTOR_ELT(parsed, i), env)); |
562 | 31.2k | if (eval_budget == 0) { |
563 | | /* The compiler used up the budget or the CPU limit. */ |
564 | 5 | *error = 1; |
565 | 5 | Rf_unprotect(1); |
566 | 5 | break; |
567 | 5 | } |
568 | 31.2k | result = R_tryEvalSilent(code, env, error); |
569 | 31.2k | Rf_unprotect(1); |
570 | 31.2k | if (*error) |
571 | 8.80k | break; |
572 | 31.2k | } |
573 | 16.7k | eval_budget = 0; |
574 | 16.7k | eval_reset_builtins(); |
575 | | |
576 | 16.7k | Rf_unprotect(3); |
577 | 16.7k | return *error ? R_NilValue : result; |
578 | 18.7k | } |
579 | | |
580 | | static void eval_one(void *data) |
581 | 18.7k | { |
582 | 18.7k | int error = 0; |
583 | 18.7k | eval_source((const eval_input_t *)data, &error); |
584 | 18.7k | } |
585 | | |
586 | | static void eval_run(const uint8_t *data, size_t size) |
587 | 18.7k | { |
588 | 18.7k | eval_input_t input = { data, size }; |
589 | | /* A jump past eval_source (an interrupt, not an error) skips its resets. */ |
590 | 18.7k | if (!R_ToplevelExec(eval_one, &input)) { |
591 | 268 | eval_budget = 0; |
592 | 268 | R_ToplevelExec(eval_reset_builtins_exec, NULL); |
593 | 268 | } |
594 | 18.7k | } |
595 | | |
596 | | int fuzz_target_init(int *argc, char ***argv) |
597 | 2 | { |
598 | 2 | (void)argc; |
599 | 2 | (void)argv; |
600 | | /* The harness compiles explicitly (eval_compile); nothing is attached |
601 | | * that a method lookup could reach. */ |
602 | 2 | setenv("R_ENABLE_JIT", "0", 1); |
603 | 2 | setenv("R_DEFAULT_PACKAGES", "NULL", 1); |
604 | 2 | if (getenv("R_VSIZE") == NULL) |
605 | 1 | setenv("R_VSIZE", FUZZ_R_MAX_VSIZE, 1); |
606 | 2 | fuzz_init_r(); |
607 | | |
608 | 2 | eval_reset_builtins_fn = eval_run_init(eval_reset_builtins_source, R_BaseEnv); |
609 | 2 | R_PreserveObject(eval_reset_builtins_fn); |
610 | 2 | eval_builtins_attributes = eval_run_init("list(name = \"package:base\")", R_BaseEnv); |
611 | 2 | R_PreserveObject(eval_builtins_attributes); |
612 | 2 | Rf_protect(eval_builtins = R_NewEnv(R_EmptyEnv, TRUE, 97)); |
613 | 2 | eval_reset_builtins(); |
614 | 2 | eval_import_primitives(eval_builtins, eval_primitives, |
615 | 2 | sizeof(eval_primitives) / sizeof(*eval_primitives)); |
616 | | /* topenv() recognises a frame by this binding as well as by its name |
617 | | * attribute; the binding is the one the input cannot touch. */ |
618 | 2 | Rf_defineVar(Rf_install(".packageName"), Rf_mkString("base"), eval_builtins); |
619 | 2 | R_LockEnvironment(eval_builtins, TRUE); |
620 | | |
621 | 2 | Rf_protect(eval_wrappers = R_NewEnv(eval_builtins, TRUE, 29)); |
622 | 2 | SEXP private_env; |
623 | 2 | size_t n_wrappers = sizeof(eval_wrapper_table) / sizeof(*eval_wrapper_table); |
624 | 2 | Rf_protect(private_env = R_NewEnv(R_EmptyEnv, TRUE, 29)); |
625 | 2 | eval_import_primitives(private_env, eval_wrapper_primitives, |
626 | 2 | sizeof(eval_wrapper_primitives) / sizeof(*eval_wrapper_primitives)); |
627 | 12 | for (size_t i = 0; i < n_wrappers; i++) |
628 | 10 | Rf_defineVar(Rf_install(eval_wrapper_table[i].primitive), |
629 | 10 | eval_primitive(eval_wrapper_table[i].name), private_env); |
630 | 2 | R_LockEnvironment(private_env, TRUE); |
631 | 12 | for (size_t i = 0; i < n_wrappers; i++) { |
632 | 10 | SEXP wrapper; |
633 | 10 | Rf_protect(wrapper = eval_run_init(eval_wrapper_table[i].source, private_env)); |
634 | 10 | Rf_defineVar(Rf_install(eval_wrapper_table[i].name), wrapper, eval_wrappers); |
635 | 10 | Rf_unprotect(1); |
636 | 10 | } |
637 | 2 | Rf_unprotect(1); |
638 | 2 | R_LockEnvironment(eval_wrappers, TRUE); |
639 | | |
640 | 2 | eval_compile_fn = eval_run_init(eval_compiler_setup, R_BaseEnv); |
641 | 2 | R_PreserveObject(eval_compile_fn); |
642 | | |
643 | 2 | R_PolledEvents = eval_poll_budget; |
644 | 2 | eval_run((const uint8_t *)eval_warmup_source, strlen(eval_warmup_source)); |
645 | 2 | return 0; |
646 | 2 | } |
647 | | |
648 | | int fuzz_target_run(const uint8_t *data, size_t size) |
649 | 18.7k | { |
650 | 18.7k | if (size == 0 || size > FUZZ_MAX_INPUT || memchr(data, '\0', size) || |
651 | 18.7k | !eval_valid_utf8(data, size)) |
652 | 54 | return 0; |
653 | | |
654 | 18.7k | eval_run(data, size); |
655 | 18.7k | return 0; |
656 | 18.7k | } |