/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 | 24.3k | #define FUZZ_MAX_INPUT 8192 |
37 | 1.00M | #define FUZZ_MAX_DEPTH 64 |
38 | 1.44M | #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 | 10.5k | #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 | 13.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 | | }; |
101 | | |
102 | | /* |
103 | | * Wrappers: closures standing in for primitives whose plain form would |
104 | | * get past a limit. Each is bound in eval_wrappers, a frame of its own |
105 | | * below the allowlist, because the compiler inlines and constant-folds |
106 | | * calls to names it finds in the base-like frame (the COLON and SEQLEN |
107 | | * instructions; `:`, seq_len, seq.int and rep are in its foldFuns), and |
108 | | * an inlined call would bypass the wrapper (see eval_compile). The |
109 | | * wrappers share one private enclosure holding only the primitives their |
110 | | * bodies name (`function` included: it is a primitive looked up like any |
111 | | * other), the wrapped primitives under dotted names, and .Internal, bound |
112 | | * there to raise the errors and nowhere the input can see. So they add |
113 | | * no capability. |
114 | | * |
115 | | * `:`, seq_len and seq.int build compact ALTREP sequences, which cost |
116 | | * nothing to create whatever their length; the reductions without an |
117 | | * ALTREP shortcut (prod, or min/max/sum with two arguments) then walk 1e9 |
118 | | * elements in C without an interrupt check: 8-18 s under ASAN, which the |
119 | | * budget cannot see and ClusterFuzz would file as a timeout. Nothing |
120 | | * else in the allowlist builds a long vector without allocating it, and |
121 | | * allocation is bounded by the vector heap. `:` is capped on what it |
122 | | * uses: the first element of each argument, as a double, so a longer |
123 | | * vector or a character argument (`c(1e12, 1):5`, `"1":"1e9"`) is bounded |
124 | | * like a scalar. seq_len and seq.int have more argument forms, so they |
125 | | * are capped on the result instead: building it is free, and its length |
126 | | * is known before anything walks it. |
127 | | * |
128 | | * `attr<-` and `attributes<-` refuse two things. The class attribute: an |
129 | | * object with one dispatches every internal generic in the allowlist |
130 | | * (`[`, `+`, `length`, `c`, ...) to the S3 methods base registers for its |
131 | | * classes -- `[.data.frame`, `Ops.Date`, `$.DLLInfo` -- which are closures |
132 | | * over the base namespace running on input-shaped data, and a crash in |
133 | | * one of them on `class(x) <- "DLLInfo"` is the "you asked for it" report |
134 | | * this target is meant not to produce. UseMethod dispatches on the |
135 | | * implicit class (matrix, integer, function, ...) to methods the input |
136 | | * defines, which is the dispatch code this allowlist is for. And |
137 | | * environments: UseMethod hands the method .GenericDefEnv, which is the |
138 | | * allowlist frame itself, whose bindings are locked but whose attributes |
139 | | * are not (see eval_reset_builtins). The other setters in the allowlist |
140 | | * either reject environments (names<-, dim<-, dimnames<-) or set only |
141 | | * their own attribute (levels<-). |
142 | | */ |
143 | | static const char *const eval_wrapper_primitives[] = { |
144 | | "function", "{", "if", "&&", "||", ">=", ">", "==", "-", "<-", "length", |
145 | | "[[", "as.double", "is.finite", "abs", "is.character", "is.na", "!", |
146 | | "any", "names", "is.environment", ".Internal" |
147 | | }; |
148 | | |
149 | | static const char eval_colon_source[] = R"( |
150 | | function(from, to) { |
151 | | if (length(from) >= 1L && length(to) >= 1L) { |
152 | | f <- as.double(from[[1L]]) |
153 | | t <- as.double(to[[1L]]) |
154 | | if (is.finite(f) && is.finite(t) && abs(t - f) >= 1e6) |
155 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
156 | | } |
157 | | .colon(from, to) |
158 | | } |
159 | | )"; |
160 | | |
161 | | static const char eval_seq_len_source[] = R"( |
162 | | function(length.out) { |
163 | | x <- .seq_len(length.out) |
164 | | if (length(x) > 1e6) |
165 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
166 | | x |
167 | | } |
168 | | )"; |
169 | | |
170 | | static const char eval_seq_int_source[] = R"( |
171 | | function(...) { |
172 | | x <- .seq_int(...) |
173 | | if (length(x) > 1e6) |
174 | | .Internal(stop(TRUE, "sequence too long for the eval target")) |
175 | | x |
176 | | } |
177 | | )"; |
178 | | |
179 | | static const char eval_attr_set_source[] = R"( |
180 | | function(x, which, value) { |
181 | | if (is.environment(x)) |
182 | | .Internal(stop(TRUE, "attributes of environments cannot be set in the eval target")) |
183 | | if (is.character(which) && length(which) == 1L && !is.na(which) && |
184 | | which == "class") |
185 | | .Internal(stop(TRUE, "the class attribute is not available in the eval target")) |
186 | | .attr_set(x, which, value = value) |
187 | | } |
188 | | )"; |
189 | | |
190 | | static const char eval_attributes_set_source[] = R"( |
191 | | function(x, value) { |
192 | | if (is.environment(x)) |
193 | | .Internal(stop(TRUE, "attributes of environments cannot be set in the eval target")) |
194 | | if (any(names(value) == "class")) |
195 | | .Internal(stop(TRUE, "the class attribute is not available in the eval target")) |
196 | | .attributes_set(x, value) |
197 | | } |
198 | | )"; |
199 | | |
200 | | typedef struct { |
201 | | const char *name; /* bound in eval_wrappers */ |
202 | | const char *primitive; /* the primitive, bound in the private enclosure */ |
203 | | const char *source; |
204 | | } eval_wrapper_t; |
205 | | |
206 | | static const eval_wrapper_t eval_wrapper_table[] = { |
207 | | { ":", ".colon", eval_colon_source }, |
208 | | { "seq_len", ".seq_len", eval_seq_len_source }, |
209 | | { "seq.int", ".seq_int", eval_seq_int_source }, |
210 | | { "attr<-", ".attr_set", eval_attr_set_source }, |
211 | | { "attributes<-", ".attributes_set", eval_attributes_set_source }, |
212 | | }; |
213 | | |
214 | | typedef struct { |
215 | | const uint8_t *data; |
216 | | size_t size; |
217 | | } eval_input_t; |
218 | | |
219 | | /* |
220 | | * Execution budget, counted in interrupt checks. |
221 | | * |
222 | | * R_CheckUserInterrupt() -> R_ProcessEvents() -> R_PolledEvents() is the |
223 | | * hook R offers for event loops, and it is reached from the same places |
224 | | * that honour setTimeLimit(): every 10th eval() of the AST interpreter |
225 | | * (every 1000th in stock R; instrumentation/0001 lowers it), |
226 | | * the byte-code loop back-edges, and the long-running C loops that poll |
227 | | * for interrupts. Counting those calls instead of CPU time gives every |
228 | | * input the same budget on every machine, so an input that is cut off |
229 | | * under ASAN on a slow bot is cut off the same way in a local reproduction, |
230 | | * and libFuzzer's coverage feedback stops depending on timing. |
231 | | * |
232 | | * Exactness is to within one check interval: eval()'s counter is static |
233 | | * and carries over between inputs. |
234 | | * |
235 | | * The unit is an evaluation, and an evaluation can be `!x` over the whole |
236 | | * heap: with a 64 MiB heap and a check every 1000 evaluations, |
237 | | * `x <- !1:4e4; repeat !x` ran 15 s under ASAN before the budget was |
238 | | * spent, and would have been filed as a timeout. Three things bound that. |
239 | | * The heap is small (8 MiB), which caps the work of any one evaluation. |
240 | | * The check interval is short (instrumentation/0001), which caps the number of |
241 | | * evaluations between two checks. And a CPU backstop ends the input at |
242 | | * the first check after FUZZ_EVAL_CPU_LIMIT seconds, whatever the budget |
243 | | * says. The backstop is the one timing-dependent limit left, and it only |
244 | | * decides whether a vector-heavy input completes or errors, never whether |
245 | | * it crashes; it sits far below ClusterFuzz's timeout threshold so that |
246 | | * difference stays out of the tracker. |
247 | | * |
248 | | * The error unwinds to R_tryEvalSilent like any other R error. Raising it |
249 | | * from inside R_ProcessEvents is what R_CheckTimeLimits does, so the |
250 | | * interpreter is prepared for a longjmp at this point. The budget is |
251 | | * zero by the time either error is raised, which switches the check off, |
252 | | * so nothing on the error path can re-enter it. No input code runs once |
253 | | * the error is raised: there are no handlers or on.exit in the allowlist, |
254 | | * and that is a condition of this design (see eval_primitives). |
255 | | */ |
256 | | static void eval_poll_budget(void) |
257 | 13.0M | { |
258 | 13.0M | if (eval_budget <= 0) |
259 | 24.2k | return; |
260 | | |
261 | 13.0M | if (--eval_budget == 0) |
262 | 365 | Rf_error("evaluation budget exhausted"); |
263 | | |
264 | 13.0M | if ((double)(clock() - eval_cpu_start) / CLOCKS_PER_SEC > FUZZ_EVAL_CPU_LIMIT) { |
265 | 99 | eval_budget = 0; |
266 | 99 | Rf_error("evaluation CPU limit exhausted"); |
267 | 99 | } |
268 | 13.0M | } |
269 | | |
270 | | /* UseMethod() binds .GenericDefEnv in the method's frame to the top |
271 | | * environment of the generic's enclosure, which here is the allowlist frame |
272 | | * itself. Its bindings are locked, but attributes are not bindings. Two |
273 | | * things keep that harmless. The wrappers for attr<- and attributes<- |
274 | | * refuse environments, so the input cannot take away the frame's name, |
275 | | * which topenv() would otherwise stop recognising -- it then falls back to |
276 | | * R_GlobalEnv, and UseMethod's method lookup from there reaches base's own |
277 | | * S3 methods (with.default evaluates its argument with the whole of base |
278 | | * in scope). And the frame carries a locked .packageName binding, which |
279 | | * topenv() accepts on its own, so recognition never rests on an attribute |
280 | | * at all. What is left is levels<-, which can hang a heap-sized attribute |
281 | | * on the frame that would outlive the input; so the attributes are put |
282 | | * back after every input. (.GenericCallEnv is the caller's frame, the |
283 | | * input's own.) Through R, since the attribute list is not reachable from |
284 | | * the public API; in two steps with a preserved value, so that nothing is |
285 | | * allocated while an attribute the input left may be filling the heap. */ |
286 | | static const char eval_reset_builtins_source[] = R"( |
287 | | function(env, value) { |
288 | | attributes(env) <- NULL |
289 | | attributes(env) <- value |
290 | | } |
291 | | )"; |
292 | | |
293 | | static void eval_reset_builtins(void) |
294 | 10.5k | { |
295 | 10.5k | SEXP call; |
296 | 10.5k | Rf_protect(call = Rf_lang3(eval_reset_builtins_fn, eval_builtins, |
297 | 10.5k | eval_builtins_attributes)); |
298 | 10.5k | Rf_eval(call, R_BaseEnv); |
299 | 10.5k | Rf_unprotect(1); |
300 | 10.5k | } |
301 | | |
302 | | static void eval_reset_builtins_exec(void *unused) |
303 | 170 | { |
304 | 170 | (void)unused; |
305 | 170 | eval_reset_builtins(); |
306 | 170 | } |
307 | | |
308 | | /* The allowlist is only ever primitives (see eval_primitives): a name that |
309 | | * stops being one would silently import a closure and its namespace. */ |
310 | | static SEXP eval_primitive(const char *name) |
311 | 230 | { |
312 | 230 | SEXP value = Rf_findFun(Rf_install(name), R_BaseEnv); |
313 | 230 | if (TYPEOF(value) != BUILTINSXP && TYPEOF(value) != SPECIALSXP) { |
314 | 0 | fprintf(stderr, "eval: %s is no longer a primitive\n", name); |
315 | 0 | abort(); |
316 | 0 | } |
317 | 230 | return value; |
318 | 230 | } |
319 | | |
320 | | static void eval_import_primitives(SEXP env, const char *const *names, size_t n) |
321 | 4 | { |
322 | 224 | for (size_t i = 0; i < n; i++) |
323 | 220 | Rf_defineVar(Rf_install(names[i]), eval_primitive(names[i]), env); |
324 | 4 | } |
325 | | |
326 | | /* Parse and evaluate one expression of set-up code. A failure here is a |
327 | | * harness bug, so it stops the process rather than becoming an R error. */ |
328 | | static SEXP eval_run_init(const char *source, SEXP env) |
329 | 16 | { |
330 | 16 | ParseStatus status; |
331 | 16 | SEXP text, parsed, value; |
332 | 16 | int error = 0; |
333 | | |
334 | 16 | Rf_protect(text = Rf_mkString(source)); |
335 | 16 | Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue)); |
336 | 16 | if (status != PARSE_OK || XLENGTH(parsed) != 1) |
337 | 0 | abort(); |
338 | | |
339 | 16 | value = R_tryEvalSilent(VECTOR_ELT(parsed, 0), env, &error); |
340 | 16 | if (error) { |
341 | 0 | fprintf(stderr, "eval: set-up failed: %s", R_curErrorBuf()); |
342 | 0 | abort(); |
343 | 0 | } |
344 | | |
345 | 16 | Rf_unprotect(2); |
346 | 16 | return value; |
347 | 16 | } |
348 | | |
349 | | static int eval_valid_utf8(const uint8_t *data, size_t size) |
350 | 12.1k | { |
351 | 12.1k | size_t i = 0; |
352 | 2.58M | while (i < size) { |
353 | 2.57M | uint8_t c = data[i++]; |
354 | 2.57M | if (c < 0x80) |
355 | 2.55M | continue; |
356 | 26.4k | if (c >= 0xc2 && c <= 0xdf) { |
357 | 17.4k | if (i >= size || (data[i++] & 0xc0) != 0x80) |
358 | 4 | return 0; |
359 | 17.4k | continue; |
360 | 17.4k | } |
361 | 9.02k | if (c >= 0xe0 && c <= 0xef) { |
362 | 5.57k | if (i + 1 >= size || (data[i] & 0xc0) != 0x80 || |
363 | 5.56k | (data[i + 1] & 0xc0) != 0x80 || |
364 | 5.56k | (c == 0xe0 && data[i] < 0xa0) || |
365 | 5.56k | (c == 0xed && data[i] >= 0xa0)) |
366 | 11 | return 0; |
367 | 5.56k | i += 2; |
368 | 5.56k | continue; |
369 | 5.57k | } |
370 | 3.45k | if (c >= 0xf0 && c <= 0xf4) { |
371 | 3.43k | if (i + 2 >= size || (data[i] & 0xc0) != 0x80 || |
372 | 3.42k | (data[i + 1] & 0xc0) != 0x80 || |
373 | 3.42k | (data[i + 2] & 0xc0) != 0x80 || |
374 | 3.42k | (c == 0xf0 && data[i] < 0x90) || |
375 | 3.42k | (c == 0xf4 && data[i] >= 0x90)) |
376 | 12 | return 0; |
377 | 3.41k | i += 3; |
378 | 3.41k | continue; |
379 | 3.43k | } |
380 | 20 | return 0; |
381 | 3.45k | } |
382 | 12.1k | return 1; |
383 | 12.1k | } |
384 | | |
385 | | /* Bound the post-parse walk, including wide argument lists. This limits test |
386 | | * complexity, not execution time: even a tiny expression can loop forever. |
387 | | */ |
388 | | static int eval_tree_within_budget(SEXP x, unsigned depth, unsigned *nodes) |
389 | 503k | { |
390 | 503k | if (depth > FUZZ_MAX_DEPTH || ++*nodes > FUZZ_MAX_NODES) |
391 | 53 | return 0; |
392 | | |
393 | 503k | switch (TYPEOF(x)) { |
394 | 176k | case LANGSXP: |
395 | 176k | case LISTSXP: |
396 | 645k | for (SEXP p = x; p != R_NilValue; p = CDR(p)) { |
397 | 472k | if (++*nodes > FUZZ_MAX_NODES || |
398 | 472k | !eval_tree_within_budget(CAR(p), depth + 1, nodes)) |
399 | 3.70k | return 0; |
400 | 472k | } |
401 | 172k | return 1; |
402 | 10.4k | case EXPRSXP: |
403 | 30.7k | for (R_xlen_t i = 0; i < XLENGTH(x); i++) { |
404 | 20.3k | if (!eval_tree_within_budget(VECTOR_ELT(x, i), depth + 1, nodes)) |
405 | 85 | return 0; |
406 | 20.3k | } |
407 | 10.3k | return 1; |
408 | 316k | default: |
409 | 316k | return 1; |
410 | 503k | } |
411 | 503k | } |
412 | | |
413 | | /* |
414 | | * Byte-code. |
415 | | * |
416 | | * Nearly all R code that runs in a session is byte-compiled: packages at |
417 | | * install time, everything else by the JIT after a call or two. The JIT |
418 | | * is not used here (R_ENABLE_JIT=0): it compiles on its own schedule, |
419 | | * keeps a cache across inputs, and catches errors inside the compiler, |
420 | | * where a budget error would be swallowed and the budget left switched |
421 | | * off. Instead the harness compiles each top-level expression itself, |
422 | | * with the budget paused, and evaluates the result. Closures the input |
423 | | * defines are created with compiled bodies (MAKECLOSURE), top-level loops |
424 | | * are compiled too, and anything the compiler declines runs through the |
425 | | * AST interpreter, which is what the JIT falls back to as well. Compile |
426 | | * time is bounded by the parsed-tree limits; constant folding evaluates |
427 | | * base functions on literals only. |
428 | | * |
429 | | * The compiler (compiler:::cmp.R) needs two things from the sandbox. It |
430 | | * refuses an environment whose chain does not end in a frame topenv() |
431 | | * recognises, and it inlines base syntax and arithmetic only for names it |
432 | | * finds bound in a frame it classifies as base, by the frame's "name" |
433 | | * attribute. So eval_builtins carries the name of base's package frame. |
434 | | * Its bindings are base's own primitives, so the BASEGUARD check that |
435 | | * compiled code makes before an inlined builtin call passes, and a name |
436 | | * the input rebinds is looked up like any other. isBaseVar, which gates |
437 | | * whether break/next compile to a jump or to a loop context, compares |
438 | | * frames by identity instead, so it is rebound to accept the named frame; |
439 | | * without that every loop with a conditional break would compile with a |
440 | | * context, which a session's would not. |
441 | | */ |
442 | | static const char eval_compiler_setup[] = R"( |
443 | | local({ |
444 | | ns <- asNamespace("compiler") |
445 | | isBaseVar <- function(var, cntxt) { |
446 | | info <- getInlineInfo(var, cntxt) |
447 | | !is.null(info) && |
448 | | (identical(info$frame, .BaseNamespaceEnv) || |
449 | | identical(info$frame, baseenv()) || |
450 | | packFrameName(info$frame) == "base") |
451 | | } |
452 | | environment(isBaseVar) <- ns |
453 | | unlockBinding("isBaseVar", ns) |
454 | | assign("isBaseVar", isBaseVar, envir = ns) |
455 | | lockBinding("isBaseVar", ns) |
456 | | compiler::compile |
457 | | }) |
458 | | )"; |
459 | | |
460 | | /* Run once at start-up, so the compiler's lazily loaded internals are in |
461 | | * memory before the first input and every input sees the same R. */ |
462 | | static const char eval_warmup_source[] = R"( |
463 | | f <- function(n) { |
464 | | s <- 0 |
465 | | for (i in 1:n) if (i %% 2 == 0) s <- s + i else next |
466 | | s |
467 | | } |
468 | | x <- c(f(10), 1) |
469 | | x[[2]] <- x[1] |
470 | | g <- function(...) list(...) |
471 | | g(x, repeat break) |
472 | | h <- function(x) UseMethod("h") |
473 | | h.default <- function(x) switch(class(x), numeric = nargs(), 2) |
474 | | h.function <- function(x) attr(unclass(x), "srcref") |
475 | | h(x); h(g) |
476 | | y <- seq_len(3); names(y) <- c("a", "b", "c"); dim(y) <- 3L; y[[2L]] |
477 | | )"; |
478 | | |
479 | | /* Byte-code for expr, or expr itself if the compiler declined it. |
480 | | * |
481 | | * The compiler is R code and runs under the input's budget like the code |
482 | | * it produces. It used to run with the budget paused, bounded only by |
483 | | * the parsed-tree limits, but its cost is not linear in the tree: constant |
484 | | * folding re-walks every subtree at each level of nesting, so an |
485 | | * expression nested 62 calls deep compiles in about a second under ASAN |
486 | | * and four of them (270 bytes, within the tree limits) in over four, |
487 | | * which on the bots was the 25 s libFuzzer timeout. A compile the |
488 | | * budget cuts off leaves eval_budget at zero; the caller stops the input |
489 | | * there rather than running the expression uncompiled. |
490 | | */ |
491 | | static SEXP eval_compile(SEXP expr, SEXP env) |
492 | 17.6k | { |
493 | 17.6k | SEXP quoted, call, code; |
494 | 17.6k | int error = 0; |
495 | | |
496 | 17.6k | Rf_protect(quoted = Rf_lang2(R_QuoteSymbol, expr)); |
497 | 17.6k | Rf_protect(call = Rf_lang3(eval_compile_fn, quoted, env)); |
498 | 17.6k | code = R_tryEvalSilent(call, R_BaseEnv, &error); |
499 | 17.6k | Rf_unprotect(2); |
500 | | |
501 | 17.6k | return error ? expr : code; |
502 | 17.6k | } |
503 | | |
504 | | /* Caller protects the returned object immediately if it needs the result. |
505 | | * All errors (including parsing/allocation) must be under R_ToplevelExec. |
506 | | */ |
507 | | static SEXP eval_source(const eval_input_t *input, int *error) |
508 | 12.1k | { |
509 | 12.1k | ParseStatus status; |
510 | 12.1k | SEXP text, parsed, env, result = R_NilValue; |
511 | 12.1k | Rf_protect(text = Rf_allocVector(STRSXP, 1)); |
512 | 12.1k | SET_STRING_ELT(text, 0, |
513 | 12.1k | Rf_mkCharLenCE((const char *)input->data, (int)input->size, |
514 | 12.1k | CE_UTF8)); |
515 | 12.1k | Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue)); |
516 | 12.1k | unsigned nodes = 0; |
517 | 12.1k | if (status != PARSE_OK || !eval_tree_within_budget(parsed, 0, &nodes)) { |
518 | 1.57k | *error = 1; |
519 | 1.57k | Rf_unprotect(2); |
520 | 1.57k | return R_NilValue; |
521 | 1.57k | } |
522 | | |
523 | | /* One budget covers all top-level expressions of an input. */ |
524 | 10.5k | Rf_protect(env = R_NewEnv(eval_wrappers, TRUE, 29)); |
525 | 10.5k | eval_cpu_start = clock(); |
526 | 10.5k | eval_budget = FUZZ_EVAL_BUDGET; |
527 | 21.2k | for (R_xlen_t i = 0; i < XLENGTH(parsed); i++) { |
528 | 17.6k | SEXP code; |
529 | 17.6k | Rf_protect(code = eval_compile(VECTOR_ELT(parsed, i), env)); |
530 | 17.6k | if (eval_budget == 0) { |
531 | | /* The compiler used up the budget or the CPU limit. */ |
532 | 11 | *error = 1; |
533 | 11 | Rf_unprotect(1); |
534 | 11 | break; |
535 | 11 | } |
536 | 17.6k | result = R_tryEvalSilent(code, env, error); |
537 | 17.6k | Rf_unprotect(1); |
538 | 17.6k | if (*error) |
539 | 6.93k | break; |
540 | 17.6k | } |
541 | 10.5k | eval_budget = 0; |
542 | 10.5k | eval_reset_builtins(); |
543 | | |
544 | 10.5k | Rf_unprotect(3); |
545 | 10.5k | return *error ? R_NilValue : result; |
546 | 12.1k | } |
547 | | |
548 | | static void eval_one(void *data) |
549 | 12.1k | { |
550 | 12.1k | int error = 0; |
551 | 12.1k | eval_source((const eval_input_t *)data, &error); |
552 | 12.1k | } |
553 | | |
554 | | static void eval_run(const uint8_t *data, size_t size) |
555 | 12.1k | { |
556 | 12.1k | eval_input_t input = { data, size }; |
557 | | /* A jump past eval_source (an interrupt, not an error) skips its resets. */ |
558 | 12.1k | if (!R_ToplevelExec(eval_one, &input)) { |
559 | 170 | eval_budget = 0; |
560 | 170 | R_ToplevelExec(eval_reset_builtins_exec, NULL); |
561 | 170 | } |
562 | 12.1k | } |
563 | | |
564 | | int fuzz_target_init(int *argc, char ***argv) |
565 | 2 | { |
566 | 2 | (void)argc; |
567 | 2 | (void)argv; |
568 | | /* The harness compiles explicitly (eval_compile); nothing is attached |
569 | | * that a method lookup could reach. */ |
570 | 2 | setenv("R_ENABLE_JIT", "0", 1); |
571 | 2 | setenv("R_DEFAULT_PACKAGES", "NULL", 1); |
572 | 2 | if (getenv("R_VSIZE") == NULL) |
573 | 1 | setenv("R_VSIZE", FUZZ_R_MAX_VSIZE, 1); |
574 | 2 | fuzz_init_r(); |
575 | | |
576 | 2 | eval_reset_builtins_fn = eval_run_init(eval_reset_builtins_source, R_BaseEnv); |
577 | 2 | R_PreserveObject(eval_reset_builtins_fn); |
578 | 2 | eval_builtins_attributes = eval_run_init("list(name = \"package:base\")", R_BaseEnv); |
579 | 2 | R_PreserveObject(eval_builtins_attributes); |
580 | 2 | Rf_protect(eval_builtins = R_NewEnv(R_EmptyEnv, TRUE, 97)); |
581 | 2 | eval_reset_builtins(); |
582 | 2 | eval_import_primitives(eval_builtins, eval_primitives, |
583 | 2 | sizeof(eval_primitives) / sizeof(*eval_primitives)); |
584 | | /* topenv() recognises a frame by this binding as well as by its name |
585 | | * attribute; the binding is the one the input cannot touch. */ |
586 | 2 | Rf_defineVar(Rf_install(".packageName"), Rf_mkString("base"), eval_builtins); |
587 | 2 | R_LockEnvironment(eval_builtins, TRUE); |
588 | | |
589 | 2 | Rf_protect(eval_wrappers = R_NewEnv(eval_builtins, TRUE, 29)); |
590 | 2 | SEXP private_env; |
591 | 2 | size_t n_wrappers = sizeof(eval_wrapper_table) / sizeof(*eval_wrapper_table); |
592 | 2 | Rf_protect(private_env = R_NewEnv(R_EmptyEnv, TRUE, 29)); |
593 | 2 | eval_import_primitives(private_env, eval_wrapper_primitives, |
594 | 2 | sizeof(eval_wrapper_primitives) / sizeof(*eval_wrapper_primitives)); |
595 | 12 | for (size_t i = 0; i < n_wrappers; i++) |
596 | 10 | Rf_defineVar(Rf_install(eval_wrapper_table[i].primitive), |
597 | 10 | eval_primitive(eval_wrapper_table[i].name), private_env); |
598 | 2 | R_LockEnvironment(private_env, TRUE); |
599 | 12 | for (size_t i = 0; i < n_wrappers; i++) { |
600 | 10 | SEXP wrapper; |
601 | 10 | Rf_protect(wrapper = eval_run_init(eval_wrapper_table[i].source, private_env)); |
602 | 10 | Rf_defineVar(Rf_install(eval_wrapper_table[i].name), wrapper, eval_wrappers); |
603 | 10 | Rf_unprotect(1); |
604 | 10 | } |
605 | 2 | Rf_unprotect(1); |
606 | 2 | R_LockEnvironment(eval_wrappers, TRUE); |
607 | | |
608 | 2 | eval_compile_fn = eval_run_init(eval_compiler_setup, R_BaseEnv); |
609 | 2 | R_PreserveObject(eval_compile_fn); |
610 | | |
611 | 2 | R_PolledEvents = eval_poll_budget; |
612 | 2 | eval_run((const uint8_t *)eval_warmup_source, strlen(eval_warmup_source)); |
613 | 2 | return 0; |
614 | 2 | } |
615 | | |
616 | | int fuzz_target_run(const uint8_t *data, size_t size) |
617 | 12.1k | { |
618 | 12.1k | if (size == 0 || size > FUZZ_MAX_INPUT || memchr(data, '\0', size) || |
619 | 12.1k | !eval_valid_utf8(data, size)) |
620 | 48 | return 0; |
621 | | |
622 | 12.1k | eval_run(data, size); |
623 | 12.1k | return 0; |
624 | 12.1k | } |