Coverage Report

Created: 2026-11-30 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-oss-fuzz/harnesses/common.h
Line
Count
Source
1
/*
2
 * Shared helpers for R fuzzing harnesses (libFuzzer).
3
 *
4
 * Provides:
5
 *   fuzz_suppress_warnings() - Suppress R warnings to avoid buffer overflow
6
 *   fuzz_run_on_r_thread()   - Run a function on the R thread (1 GiB stack)
7
 *   fuzz_init_r()            - Full R initialization sequence
8
 *   fuzz_set_string()        - Stage a string input under a toplevel context
9
 *   fuzz_set_string_ce()     - Stage a string with an explicit encoding mark
10
 *   fuzz_set_raw_arg()       - Stage a raw-vector input likewise
11
 *   fuzz_make_wrapper()      - Parse an R closure that implements a call slot
12
 *   fuzz_label_calls()       - Name a target's call slots in timeout dumps
13
 *   fuzz_scratch_file()      - Per-process temp file for path-only entry points
14
 *   fuzz_write_scratch()     - Rewrite that file with the current input
15
 *   fuzz_repeat_product_excessive() - Guard against TRE repeat blowup
16
 *   LLVMFuzzerInitialize / LLVMFuzzerTestOneInput - forward to the
17
 *       harness's fuzz_target_init / fuzz_target_run on the R thread
18
 *
19
 * Adapted from r-afl's fuzz.h for use with libFuzzer instead of AFL++.
20
 */
21
22
#ifndef FUZZ_COMMON_H
23
#define FUZZ_COMMON_H
24
25
#include <limits.h>
26
#include <pthread.h>
27
#include <signal.h>
28
#include <stdatomic.h>
29
#include <stdint.h>
30
#include <stdio.h>
31
#include <stdlib.h>
32
#include <string.h>
33
#include <time.h>
34
#include <unistd.h>
35
36
#define R_NO_REMAP 1
37
#include <Rembedded.h>
38
#include <Rinternals.h>
39
#define CSTACK_DEFNS 1    /* R_CStackStart, R_CStackLimit */
40
#define HAVE_UINTPTR_T 1
41
#include <Rinterface.h>   /* R_SignalHandlers */
42
#include <R_ext/Parse.h>
43
44
/*
45
 * Suppress R warnings globally.
46
 *
47
 * Many R functions emit warnings on invalid input (e.g., "NAs introduced
48
 * by coercion").  In persistent fuzzing, these accumulate and can overflow
49
 * R's warning buffer, triggering fatal errors.  Setting warn = -1
50
 * suppresses all warnings.
51
 */
52
static void fuzz_suppress_warnings(void)
53
2
{
54
2
    int error = 0;
55
2
    SEXP warn_call;
56
2
    Rf_protect(warn_call = Rf_lang2(Rf_install("options"),
57
2
                                    Rf_ScalarInteger(-1)));
58
2
    SET_TAG(CDR(warn_call), Rf_install("warn"));
59
2
    R_tryEval(warn_call, R_GlobalEnv, &error);
60
2
    Rf_unprotect(1);
61
2
}
62
63
/*
64
 * Set R_HOME based on the fuzzer binary's location.
65
 *
66
 * OSS-Fuzz places everything in $OUT.  The build.sh installs R to
67
 * $OUT/r-install, so R_HOME is at $OUT/r-install/lib/R.  We derive
68
 * this from /proc/self/exe so it works regardless of the mount path.
69
 */
70
static void fuzz_set_r_home(void)
71
2
{
72
    /* Skip if R_HOME is already set (e.g., for local testing) */
73
2
    if (getenv("R_HOME") != NULL)
74
1
        return;
75
76
1
    char exe[PATH_MAX];
77
1
    ssize_t len = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
78
1
    if (len <= 0)
79
0
        return;
80
1
    exe[len] = '\0';
81
82
    /* Find the directory containing the binary */
83
1
    char *slash = strrchr(exe, '/');
84
1
    if (slash == NULL)
85
0
        return;
86
1
    *slash = '\0';
87
88
1
    char r_home[PATH_MAX];
89
1
    snprintf(r_home, sizeof(r_home), "%s/r-install/lib/R", exe);
90
1
    setenv("R_HOME", r_home, 1);
91
1
}
92
93
/*
94
 * Cap R's vector heap.
95
 *
96
 * Hostile input reaches R's allocator directly -- a serialized vector can
97
 * declare any length it likes, and coercion or scanning can be talked into
98
 * asking for one -- so a 64KB input can request gigabytes.
99
 *
100
 * R enforces R_MAX_VSIZE in allocVector and signals an ordinary R error
101
 * ("vector memory limit of N reached").  When it fires inside R_ToplevelExec
102
 * the iteration is discarded and fuzzing carries on; every per-iteration
103
 * allocation must therefore go through fuzz_set_string / fuzz_set_raw_arg
104
 * below, which run under such a context.  That catchability is the reason
105
 * to prefer this over a sanitizer-level RSS limit: ASAN's soft_rss_limit_mb
106
 * either aborts the process or starts handing NULL back to allocators that
107
 * never expected it, and both look like crashes.
108
 *
109
 * Caveats:
110
 *   - The cap bounds R's cumulative LIVE vector heap, not one input's
111
 *     allocations.  Interned symbols are never collected, so the parse and
112
 *     unserialize targets ratchet toward the cap over a long run.
113
 *   - It bounds R's vector heap ONLY.  malloc-based allocations, like TRE
114
 *     compiling a pattern, bypass it entirely; see
115
 *     fuzz_repeat_product_excessive for that guard.
116
 *   - It does cost coverage of code paths that need larger results.
117
 *     A target can change the default by defining FUZZ_R_MAX_VSIZE
118
 *     before including this header (eval, load and unserialize lower it).
119
 *     Raising it past ClusterFuzz's -rss_limit_mb=2560 is pointless:
120
 *     libFuzzer kills the process as out-of-memory before R's limit
121
 *     can turn the allocation into an error (decompress, Nov 2026).
122
 *   - R's suffix parsing is case-sensitive: "4Gb" works, "4gb" silently
123
 *     leaves the heap uncapped (R only warns on stderr at startup).  The
124
 *     env override is for local runs; the CI runner does not forward
125
 *     arbitrary environment variables.
126
 *
127
 * Local reproduction of vector-limit findings under plain Rscript needs
128
 * the same value exported; see README.md.
129
 */
130
#ifndef FUZZ_R_MAX_VSIZE
131
# define FUZZ_R_MAX_VSIZE "1Gb"
132
#endif
133
134
static void fuzz_set_vsize_limit(void)
135
2
{
136
2
    if (getenv("R_MAX_VSIZE") == NULL)
137
1
        setenv("R_MAX_VSIZE", FUZZ_R_MAX_VSIZE, 1);
138
2
}
139
140
/*
141
 * Run R on its own thread with a large stack.
142
 *
143
 * Several of R's recursive C walkers never call R_CheckStack(): bind.c's
144
 * AnswerType behind c(recursive = TRUE), deparse.c behind
145
 * as.character(<list>), and the coerce, duplicate, identical and subassign
146
 * walkers.  A list some tens of thousands deep, which an input can build
147
 * at run time, overflows the 8 MiB main-thread stack in them.  Plain R
148
 * reports "segfault from C stack overflow" and recovers, long-standing
149
 * behaviour rather than a defect to report; under the sanitizers it is a
150
 * stack-overflow crash that every target walking a nested value would
151
 * keep rediscovering.
152
 *
153
 * The main thread's stack is fixed before the process starts, so R runs
154
 * on a worker thread created with FUZZ_R_STACK_SIZE of stack instead:
155
 * deep enough that any recursion an input can afford within the per-input
156
 * limits completes, and virtual until touched, so it costs an idle target
157
 * nothing.
158
 *
159
 * Everything that touches R -- initialization, every input, the checks
160
 * under tests/ -- must run on that thread: R records its stack bounds
161
 * once, and R_CheckStack() measures against them.  The libFuzzer entry
162
 * points at the end of this header forward to fuzz_target_init and
163
 * fuzz_target_run there, and fuzz_init_r() refuses to run anywhere else.
164
 *
165
 * The thread does not survive a fork, and AFL++'s driver forks: its
166
 * forkserver starts after LLVMFuzzerInitialize, so every input runs in a
167
 * child that inherited the initialized R but no thread to run it on.
168
 * An atfork handler forgets the thread in the child, and the next job
169
 * starts a fresh one, which points R's stack check at its own stack.
170
 * Strict barrier's thread check would reject that new thread wherever
171
 * it gets a new pthread_t; instrumentation/0008 lets it in.
172
 */
173
#ifndef FUZZ_R_STACK_SIZE
174
2
# define FUZZ_R_STACK_SIZE ((size_t)1 << 30)
175
#endif
176
177
/*
178
 * R_CheckStack()'s limit, far below the stack it guards.  When an R error
179
 * longjmps out of more than 64 MiB of stack, ASAN does not unpoison the
180
 * frames it abandons -- a fixed cap in __asan_handle_no_return, which
181
 * says "ASan is ignoring requested __asan_handle_no_return" -- and the
182
 * next code to reuse that stack trips over their stale redzones: a
183
 * stack-buffer-overflow in whatever runs after the error, with no bug
184
 * behind it.  R's check is what ends recursion that goes through C
185
 * (UseMethod dispatch, the AST interpreter, deparse through the poll of
186
 * instrumentation/0005), and R handles the overflow error with another
187
 * 5% of stack, so a limit of 48 MiB keeps those errors inside ASAN's
188
 * cleanup.  The walkers that never check still have the whole stack.
189
 */
190
#ifndef FUZZ_R_CSTACK_LIMIT
191
2
# define FUZZ_R_CSTACK_LIMIT ((uintptr_t)48 << 20)
192
#endif
193
194
typedef struct {
195
    void (*fn)(void *);
196
    void *arg;
197
} fuzz_job_t;
198
199
static struct {
200
    pthread_t thread;
201
    int started;
202
    pthread_mutex_t mutex;
203
    pthread_cond_t cond;
204
    fuzz_job_t *job;        /* set by the caller, cleared by the thread */
205
    uintptr_t stack_top;    /* where the thread's frames begin */
206
} fuzz_r_thread = {
207
    .mutex = PTHREAD_MUTEX_INITIALIZER,
208
    .cond = PTHREAD_COND_INITIALIZER
209
};
210
211
/*
212
 * Timeout diagnostics.
213
 *
214
 * With the alarm confined to the main thread, libFuzzer's timeout report
215
 * would show that thread waiting in fuzz_run_on_r_thread and nothing of
216
 * where R is.  So once libFuzzer has installed its SIGALRM handler, a
217
 * wrapper takes its place: on a tick where libFuzzer may time the input
218
 * out, it first signals the R thread, which prints its own stack, and
219
 * then hands the alarm on to libFuzzer, which prints its report and
220
 * exits.  The wrapper goes in after libFuzzer's startup because libFuzzer
221
 * leaves an already-installed SIGALRM handler alone.
222
 *
223
 * libFuzzer's clock for the input is not visible, but it is bracketed:
224
 * it starts after the main thread last went idle (armed) and before the
225
 * R thread took the input (started).  Every tick (timeout/2+1 s apart)
226
 * comes through here.  One that finds the input within a second of the
227
 * timeout by the armed clock, so possibly out of time by libFuzzer's
228
 * after whatever delays this handler, holds until the input is out of
229
 * time by the started clock too, which means by libFuzzer's as well;
230
 * then the dump is requested and waited for, and the tick goes on to
231
 * libFuzzer, which reports the timeout.  A tick that finds the input
232
 * younger goes straight on, and only one delayed by over a second
233
 * between reading the armed clock and libFuzzer reading its own can
234
 * still leave a timeout without its dump.  The dump pauses the R
235
 * thread, so it is taken only for an input already out of time, never
236
 * for one that may still finish.
237
 *
238
 * An input that finishes while a tick is held is not handed to libFuzzer
239
 * at all, nor is any tick that queued up meanwhile: it finished within
240
 * its time by its own clock, and the hold would be blamed for it.  Inputs
241
 * are numbered so a dump outstanding from one cannot stand in for the
242
 * next's, and the R thread itself announces when an input is running, so
243
 * a tick during the handoff finds nothing to dump.
244
 */
245
#ifdef SIGRTMIN
246
1
# define FUZZ_DUMP_SIGNAL SIGRTMIN   /* untouched by libFuzzer, glibc and R */
247
#else
248
# define FUZZ_DUMP_SIGNAL SIGUSR2    /* macOS: displaces libFuzzer's graceful exit */
249
#endif
250
251
extern void __sanitizer_print_stack_trace(void) __attribute__((weak));
252
253
static struct {
254
    int timeout;                 /* -timeout=N, seconds */
255
    long poll_ns;                /* between looks while holding or waiting */
256
    int wrapped;
257
    struct sigaction chain;      /* libFuzzer's SIGALRM action */
258
    struct timespec armed;       /* main thread idle; libFuzzer's clock starts later */
259
    struct timespec started;     /* the R thread took the input; libFuzzer's clock started earlier */
260
    atomic_int running;          /* the R thread is inside an input */
261
    atomic_int finishing;        /* a held tick saw the input finish */
262
    atomic_uint input;           /* numbers the inputs from 1; 0 is none */
263
    atomic_uint requested;       /* input whose dump was requested */
264
    atomic_uint done;            /* input whose dump has been printed */
265
} fuzz_alarm = { .timeout = 1200, .poll_ns = 1000 * 1000 };  /* libFuzzer's default */
266
267
static void fuzz_write_stderr(const char *s)
268
0
{
269
0
    ssize_t rc = write(STDERR_FILENO, s, strlen(s));
270
0
    (void)rc;
271
0
}
272
273
/*
274
 * Slot labels for the timeout dump.
275
 *
276
 * The R thread's stack is mostly the byte-code interpreter, which says
277
 * little about which of a target's calls was running.  A harness
278
 * registers its calls once with fuzz_label_calls(), which deparses each
279
 * while its placeholders still hold their initial values, and the dump
280
 * prints the one last entered by fuzz_eval_silent() or fuzz_do_eval() in
281
 * the current input.  Harnesses that evaluate a registered call another
282
 * way note it with fuzz_label_enter().  The text is formatted up front,
283
 * so the dump handler only writes it.
284
 */
285
8
#define FUZZ_MAX_LABELS 128
286
56
#define FUZZ_LABEL_MAX 4096
287
288
static struct {
289
    SEXP call;
290
    char *text;
291
} fuzz_labels[FUZZ_MAX_LABELS];
292
static int fuzz_n_labels;
293
static atomic_int fuzz_label_current = -1;  /* index into fuzz_labels */
294
295
typedef struct {
296
    SEXP call;
297
    char *buf;      /* FUZZ_LABEL_MAX bytes, holding the header */
298
    size_t len;
299
} fuzz_deparse_job_t;
300
301
/* Append one deparsed line, indented; false if it does not fit with
302
 * room left for the closing "...". */
303
static int fuzz_label_append_line(fuzz_deparse_job_t *job, const char *line)
304
40
{
305
40
    size_t n = strlen(line);
306
40
    if (job->len + 4 + n + 1 >= FUZZ_LABEL_MAX - sizeof "    ...\n")
307
0
        return 0;
308
40
    memcpy(job->buf + job->len, "    ", 4);
309
40
    memcpy(job->buf + job->len + 4, line, n);
310
40
    job->buf[job->len + 4 + n] = '\n';
311
40
    job->len += 4 + n + 1;
312
40
    job->buf[job->len] = '\0';
313
40
    return 1;
314
40
}
315
316
static void fuzz_do_deparse(void *data)
317
8
{
318
8
    fuzz_deparse_job_t *job = data;
319
8
    SEXP quoted, expr, lines;
320
8
    Rf_protect(quoted = Rf_lang2(R_QuoteSymbol, job->call));
321
8
    Rf_protect(expr = Rf_lang2(Rf_install("deparse"), quoted));
322
8
    Rf_protect(lines = Rf_eval(expr, R_BaseEnv));
323
48
    for (R_xlen_t i = 0; i < XLENGTH(lines); i++) {
324
40
        if (!fuzz_label_append_line(job, CHAR(STRING_ELT(lines, i)))) {
325
0
            memcpy(job->buf + job->len, "    ...\n", sizeof "    ...\n");
326
0
            break;
327
0
        }
328
40
    }
329
8
    Rf_unprotect(3);
330
8
}
331
332
static void fuzz_label_call(SEXP call, int slot, int n_slots)
333
8
{
334
8
    if (call == NULL || call == R_NilValue)
335
0
        return;
336
337
    /* A call shared by several slots (run under different settings, say)
338
     * keeps one label naming them all. */
339
20
    for (int i = 0; i < fuzz_n_labels; i++) {
340
12
        if (fuzz_labels[i].call != call)
341
12
            continue;
342
0
        char *old = fuzz_labels[i].text;
343
0
        char *of = strstr(old, " of ");  /* "==fuzz== slot 7 of 9:" */
344
0
        size_t size = strlen(old) + 32;
345
0
        char *buf = malloc(size);
346
0
        if (of == NULL || buf == NULL) {
347
0
            free(buf);
348
0
            return;
349
0
        }
350
0
        snprintf(buf, size, "%.*s, %d%s", (int)(of - old), old, slot, of);
351
0
        fuzz_labels[i].text = buf;
352
0
        free(old);
353
0
        return;
354
0
    }
355
8
    if (fuzz_n_labels == FUZZ_MAX_LABELS)
356
0
        return;
357
358
8
    char *buf = malloc(FUZZ_LABEL_MAX);
359
8
    if (buf == NULL)
360
0
        return;
361
8
    int n = snprintf(buf, FUZZ_LABEL_MAX, "==fuzz== slot %d of %d:\n", slot, n_slots);
362
363
    /* A failed deparse leaves the header alone. */
364
8
    fuzz_deparse_job_t job = { call, buf, (size_t)n };
365
8
    R_ToplevelExec(fuzz_do_deparse, &job);
366
367
8
    fuzz_labels[fuzz_n_labels].call = call;
368
8
    fuzz_labels[fuzz_n_labels].text = buf;
369
8
    fuzz_n_labels++;
370
8
}
371
372
/* Label calls[0..n-1] as slots 0..n-1; NULL entries (slots run in C)
373
 * are skipped. */
374
static void fuzz_label_calls(const SEXP *calls, int n)
375
2
{
376
10
    for (int i = 0; i < n; i++)
377
8
        fuzz_label_call(calls[i], i, n);
378
2
}
379
380
/* Note the call about to be evaluated; an unregistered one clears it. */
381
static void fuzz_label_enter(SEXP call)
382
5.70k
{
383
5.70k
    int found = -1;
384
13.6k
    for (int i = 0; i < fuzz_n_labels; i++) {
385
13.6k
        if (fuzz_labels[i].call == call) {
386
5.70k
            found = i;
387
5.70k
            break;
388
5.70k
        }
389
13.6k
    }
390
5.70k
    atomic_store(&fuzz_label_current, found);
391
5.70k
}
392
393
/* Runs on the R thread, interrupting whatever the input is doing. */
394
static void fuzz_dump_handler(int sig, siginfo_t *info, void *context)
395
0
{
396
0
    (void)sig;
397
0
    (void)info;
398
0
    (void)context;
399
0
    unsigned input = atomic_load(&fuzz_alarm.requested);
400
0
    int label = atomic_load(&fuzz_label_current);
401
0
    if (label >= 0)
402
0
        fuzz_write_stderr(fuzz_labels[label].text);
403
0
    if (__sanitizer_print_stack_trace)
404
0
        __sanitizer_print_stack_trace();
405
0
    else
406
0
        fuzz_write_stderr("    (no sanitizer runtime to print it)\n");
407
0
    atomic_store(&fuzz_alarm.done, input);
408
0
}
409
410
/* Whole seconds since a moment. */
411
static long fuzz_seconds_since(const struct timespec *then)
412
5
{
413
5
    struct timespec now;
414
5
    clock_gettime(CLOCK_REALTIME, &now);
415
416
5
    long seconds = now.tv_sec - then->tv_sec;
417
5
    if (now.tv_nsec < then->tv_nsec)
418
1
        seconds--;
419
5
    return seconds;
420
5
}
421
422
/* Runs on the main thread, where libFuzzer's alarm lands. */
423
static void fuzz_alarm_handler(int sig, siginfo_t *info, void *context)
424
5
{
425
5
    if (atomic_load(&fuzz_alarm.finishing))
426
0
        return;
427
428
5
    if (atomic_load(&fuzz_alarm.running) &&
429
5
        fuzz_seconds_since(&fuzz_alarm.armed) >= fuzz_alarm.timeout - 1) {
430
0
        struct timespec tick = { 0, fuzz_alarm.poll_ns };
431
432
        /* Hold until the input is out of time by its own clock as well;
433
         * one that finishes first, even in the last sleep, was within
434
         * its time.  The clock is read before the input is looked at, so
435
         * an input seen running was running at a moment past the
436
         * timeout, whatever delay falls between the two. */
437
0
        for (;;) {
438
0
            long age = fuzz_seconds_since(&fuzz_alarm.started);
439
0
            if (!atomic_load(&fuzz_alarm.running)) {
440
0
                atomic_store(&fuzz_alarm.finishing, 1);
441
0
                return;
442
0
            }
443
0
            if (age >= fuzz_alarm.timeout)
444
0
                break;
445
0
            nanosleep(&tick, NULL);
446
0
        }
447
448
0
        unsigned input = atomic_load(&fuzz_alarm.input);
449
0
        if (atomic_load(&fuzz_alarm.requested) != input) {
450
0
            atomic_store(&fuzz_alarm.requested, input);
451
0
            fuzz_write_stderr("==fuzz== R thread, where the input is running:\n");
452
0
            if (pthread_kill(fuzz_r_thread.thread, FUZZ_DUMP_SIGNAL) != 0)
453
0
                atomic_store(&fuzz_alarm.done, input);
454
0
        }
455
456
        /* Symbolizing takes a moment; a thread that never answers (stuck
457
         * in the allocator, say) must not hold up the report, and an
458
         * input finishing now is reported all the same: it was out of
459
         * time already. */
460
0
        for (int i = 0; i < 5000; i++) {
461
0
            if (atomic_load(&fuzz_alarm.done) == input ||
462
0
                !atomic_load(&fuzz_alarm.running))
463
0
                break;
464
0
            nanosleep(&tick, NULL);
465
0
        }
466
0
    }
467
5
    fuzz_alarm.chain.sa_sigaction(sig, info, context);
468
5
}
469
470
/* Wrap libFuzzer's SIGALRM handler, once it exists.  Called before each
471
 * input; the first call after libFuzzer's startup sees the handler. */
472
static void fuzz_alarm_wrap(void)
473
5.70k
{
474
5.70k
    if (fuzz_alarm.wrapped)
475
5.70k
        return;
476
1
    fuzz_alarm.wrapped = 1;
477
478
1
    struct sigaction current;
479
1
    if (sigaction(SIGALRM, NULL, &current) != 0 ||
480
1
        !(current.sa_flags & SA_SIGINFO) || current.sa_sigaction == NULL)
481
0
        return;  /* no alarm: AFL++'s driver, -timeout=0, tests */
482
483
1
    struct sigaction dump;
484
1
    memset(&dump, 0, sizeof dump);
485
1
    dump.sa_sigaction = fuzz_dump_handler;
486
1
    dump.sa_flags = SA_SIGINFO;
487
1
    sigemptyset(&dump.sa_mask);
488
1
    if (sigaction(FUZZ_DUMP_SIGNAL, &dump, NULL) != 0)
489
0
        return;
490
491
1
    fuzz_alarm.chain = current;
492
1
    struct sigaction wrapper = current;
493
1
    wrapper.sa_sigaction = fuzz_alarm_handler;
494
1
    if (sigaction(SIGALRM, &wrapper, NULL) != 0)
495
0
        sigaction(FUZZ_DUMP_SIGNAL, &(struct sigaction){ .sa_handler = SIG_DFL }, NULL);
496
1
}
497
498
static void *fuzz_r_thread_main(void *unused)
499
2
{
500
2
    (void)unused;
501
    /* The frame address rather than a local's: under ASAN an address-taken
502
     * local may sit on the fake stack, nowhere near this thread's stack.
503
     * R_CStackStart matters only once R is initialized; fuzz_init_r()
504
     * sets it again after Rf_initialize_R has overwritten it. */
505
2
    fuzz_r_thread.stack_top = (uintptr_t)__builtin_frame_address(0);
506
2
    R_CStackStart = fuzz_r_thread.stack_top;
507
508
    /* libFuzzer's -timeout alarm is acted on only by the thread running
509
     * its loop (the main thread); delivered here it would be ignored and
510
     * the input would run on.  Block it so the kernel cannot pick this
511
     * thread; fuzz_alarm_handler below gets this thread's stack into the
512
     * timeout report instead. */
513
2
    sigset_t alarm;
514
2
    sigemptyset(&alarm);
515
2
    sigaddset(&alarm, SIGALRM);
516
2
    pthread_sigmask(SIG_BLOCK, &alarm, NULL);
517
518
2
    pthread_mutex_lock(&fuzz_r_thread.mutex);
519
5.70k
    for (;;) {
520
11.4k
        while (fuzz_r_thread.job == NULL)
521
5.70k
            pthread_cond_wait(&fuzz_r_thread.cond, &fuzz_r_thread.mutex);
522
5.70k
        fuzz_job_t *job = fuzz_r_thread.job;
523
5.70k
        pthread_mutex_unlock(&fuzz_r_thread.mutex);
524
525
5.70k
        clock_gettime(CLOCK_REALTIME, &fuzz_alarm.started);
526
5.70k
        atomic_store(&fuzz_alarm.running, 1);
527
5.70k
        job->fn(job->arg);
528
5.70k
        atomic_store(&fuzz_alarm.running, 0);
529
530
5.70k
        pthread_mutex_lock(&fuzz_r_thread.mutex);
531
5.70k
        fuzz_r_thread.job = NULL;
532
5.70k
        pthread_cond_broadcast(&fuzz_r_thread.cond);
533
5.70k
    }
534
2
    return NULL;
535
2
}
536
537
static int fuzz_on_r_thread(void)
538
5.70k
{
539
5.70k
    return fuzz_r_thread.started &&
540
5.70k
           pthread_equal(pthread_self(), fuzz_r_thread.thread);
541
5.70k
}
542
543
/* Child side of fork: only the forking thread survives, so the R thread
544
 * is gone, and if it was the one waiting in pthread_cond_wait the
545
 * condition variable still counts it.  Nothing holds the mutex during a
546
 * fork from either side of the handoff, so resetting both is safe;
547
 * pthread_cond_destroy would wait for the phantom waiter instead. */
548
static void fuzz_r_thread_forget(void)
549
0
{
550
0
    fuzz_r_thread.started = 0;
551
0
    fuzz_r_thread.job = NULL;
552
0
    fuzz_r_thread.mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
553
0
    fuzz_r_thread.cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
554
0
}
555
556
/* Run fn(arg) on the R thread and wait for it to return, starting the
557
 * thread on first use.  From the R thread itself this is a plain call. */
558
static void fuzz_run_on_r_thread(void (*fn)(void *), void *arg)
559
5.70k
{
560
5.70k
    if (!fuzz_r_thread.started) {
561
2
        static int atfork_registered = 0;
562
2
        if (!atfork_registered) {
563
2
            if (pthread_atfork(NULL, NULL, fuzz_r_thread_forget) != 0) {
564
0
                fprintf(stderr, "fuzz: cannot register the fork handler\n");
565
0
                abort();
566
0
            }
567
2
            atfork_registered = 1;
568
2
        }
569
570
2
        pthread_attr_t attr;
571
2
        if (pthread_attr_init(&attr) != 0 ||
572
2
            pthread_attr_setstacksize(&attr, FUZZ_R_STACK_SIZE) != 0 ||
573
2
            pthread_create(&fuzz_r_thread.thread, &attr,
574
2
                           fuzz_r_thread_main, NULL) != 0) {
575
0
            fprintf(stderr, "fuzz: cannot start the R thread\n");
576
0
            abort();
577
0
        }
578
2
        pthread_attr_destroy(&attr);
579
2
        fuzz_r_thread.started = 1;
580
2
    }
581
582
5.70k
    if (fuzz_on_r_thread()) {
583
0
        fn(arg);
584
0
        return;
585
0
    }
586
587
5.70k
    fuzz_job_t job = { fn, arg };
588
5.70k
    if (atomic_fetch_add(&fuzz_alarm.input, 1) + 1 == 0)
589
5.70k
        atomic_fetch_add(&fuzz_alarm.input, 1);  /* wrapped past 0, which is none */
590
591
5.70k
    pthread_mutex_lock(&fuzz_r_thread.mutex);
592
5.70k
    fuzz_r_thread.job = &job;
593
5.70k
    pthread_cond_broadcast(&fuzz_r_thread.cond);
594
11.4k
    while (fuzz_r_thread.job != NULL)
595
5.70k
        pthread_cond_wait(&fuzz_r_thread.cond, &fuzz_r_thread.mutex);
596
5.70k
    pthread_mutex_unlock(&fuzz_r_thread.mutex);
597
598
    /* Idle again: ticks count, and libFuzzer's clock for the next input
599
     * starts after this. */
600
5.70k
    atomic_store(&fuzz_alarm.finishing, 0);
601
5.70k
    clock_gettime(CLOCK_REALTIME, &fuzz_alarm.armed);
602
5.70k
}
603
604
/*
605
 * Initialize R for fuzzing.  Call once from fuzz_target_init.
606
 *
607
 * Performs:
608
 *   1. Set R_HOME from binary location
609
 *   2. Cap the vector heap (must precede R's startup, which reads it)
610
 *   3. Initialize embedded R, without R's signal handlers
611
 *   4. Point R's C stack check at the R thread's stack
612
 *   5. Suppress warnings
613
 */
614
static void fuzz_init_r(void)
615
2
{
616
2
    if (!fuzz_on_r_thread()) {
617
0
        fprintf(stderr, "fuzz_init_r: must run on the R thread "
618
0
                        "(define fuzz_target_init, not LLVMFuzzerInitialize)\n");
619
0
        abort();
620
0
    }
621
622
2
    fuzz_set_r_home();
623
2
    fuzz_set_vsize_limit();
624
625
    /* GC consistency failures ("untraced old-to-new reference", a node
626
     * with a bad type) are memory corruption, not input errors.  R's
627
     * default is to report and carry on; this makes gc_error() fatal
628
     * (through R_Suicide, which instrumentation/0004 turns into abort)
629
     * so they surface as crashes at the collection that found them. */
630
2
    if (getenv("_R_GC_FAIL_ON_ERROR_") == NULL)
631
1
        setenv("_R_GC_FAIL_ON_ERROR_", "yes", 1);
632
633
    /* R's SIGSEGV/SIGILL/etc. handlers enter an interactive recovery
634
     * prompt instead of crashing, which would hang the fuzzer.  Telling
635
     * R not to install them (rather than resetting to SIG_DFL after
636
     * init) keeps the sanitizers' own handlers in place, so wild-pointer
637
     * faults still get full ASAN reports and clean deduplication. */
638
2
    R_SignalHandlers = 0;
639
640
    /* The two halves of Rf_initEmbeddedR, with the C stack check fixed
641
     * up in between.  On Linux Rf_initialize_R takes R_CStackStart from
642
     * __libc_stack_end, the main thread's stack, so from this thread
643
     * every R_CheckStack() while setup_Rmainloop loads base would see
644
     * terabytes of usage and R would abort ("unable to initialize the
645
     * JIT").  macOS never sets it when embedded, which hides this
646
     * locally.  Switch the check off for startup, then measure against
647
     * this thread: R_CheckStack() fires as an ordinary R error at
648
     * FUZZ_R_CSTACK_LIMIT (see there for why it is not the whole stack).
649
     * setup_Rmainloop itself would turn any limit above 100 MB into
650
     * "unlimited", hence setting it after. */
651
2
    char *r_argv[] = {"R", "--vanilla", "--no-echo", "--no-restore"};
652
2
    int r_argc = sizeof(r_argv) / sizeof(r_argv[0]);
653
2
    Rf_initialize_R(r_argc, r_argv);
654
2
    R_CStackStart = fuzz_r_thread.stack_top;
655
2
    R_CStackLimit = (uintptr_t)-1;
656
2
    R_Interactive = TRUE;   /* as Rf_initEmbeddedR */
657
2
    setup_Rmainloop();
658
2
    R_CStackLimit = FUZZ_R_CSTACK_LIMIT;
659
660
2
    fuzz_suppress_warnings();
661
2
}
662
663
/*
664
 * Helper for protected evaluation via R_ToplevelExec.
665
 *
666
 * R API calls that touch R objects can longjmp on error.  Without a
667
 * top-level context, R's error handler crashes.  Wrapping calls in
668
 * R_ToplevelExec catches the longjmp cleanly.
669
 */
670
typedef struct {
671
    SEXP call;
672
    SEXP env;
673
} fuzz_eval_data_t;
674
675
static void fuzz_do_eval(void *data)
676
0
{
677
0
    fuzz_eval_data_t *ed = (fuzz_eval_data_t *)data;
678
0
    fuzz_label_enter(ed->call);
679
0
    Rf_eval(ed->call, ed->env);
680
0
}
681
682
/* Evaluate malformed-input-heavy targets without printing each expected
683
 * R error. R_tryEvalSilent installs its own top-level error context.
684
 * FUZZ_PRINT_ERRORS prints them instead, for scripts/check-wrappers.sh. */
685
static void fuzz_eval_silent(SEXP call, SEXP env)
686
5.70k
{
687
5.70k
    int error = 0;
688
5.70k
    fuzz_label_enter(call);
689
#ifdef FUZZ_PRINT_ERRORS
690
    R_tryEval(call, env, &error);
691
#else
692
5.70k
    R_tryEvalSilent(call, env, &error);
693
5.70k
#endif
694
5.70k
}
695
696
/*
697
 * Stage per-iteration inputs under a toplevel context.
698
 *
699
 * Rf_mkChar and Rf_allocVector can themselves signal the vector-limit
700
 * error.  Outside a toplevel context that error longjmps into a stack
701
 * frame that returned during Rf_initEmbeddedR -- undefined behaviour --
702
 * so input staging must be wrapped just like evaluation.  Both helpers
703
 * return FALSE when the allocation failed; skip the iteration then.
704
 */
705
typedef struct {
706
    SEXP vec;
707
    const char *str;
708
} fuzz_string_data_t;
709
710
static void fuzz_do_set_string(void *data)
711
0
{
712
0
    fuzz_string_data_t *sd = (fuzz_string_data_t *)data;
713
0
    SET_STRING_ELT(sd->vec, 0, Rf_mkChar(sd->str));
714
0
}
715
716
static Rboolean fuzz_set_string(SEXP vec, const char *str)
717
0
{
718
0
    fuzz_string_data_t sd = { vec, str };
719
0
    return R_ToplevelExec(fuzz_do_set_string, &sd);
720
0
}
721
722
/*
723
 * Parse and evaluate one R function literal, once, at initialization.
724
 *
725
 * Harnesses whose calls need named arguments, on.exit(close(con)) or a
726
 * few R-level steps around the entry point express each slot as an R
727
 * closure and call it with Rf_lang*; that keeps the C side free of
728
 * argument plumbing.  The source is harness-authored (never fuzz
729
 * input), so a parse or evaluation failure is a harness bug: abort.
730
 *
731
 * The closure is created in the global environment so its body sees
732
 * the attached packages.  Created in base it would not: base's enclosure
733
 * is the empty environment, so every call to a grDevices, utils or
734
 * stats function fails with "could not find function", silently under
735
 * fuzz_eval_silent.  scripts/check-wrappers.sh checks for that.
736
 */
737
static SEXP fuzz_make_wrapper(const char *source)
738
8
{
739
8
    ParseStatus status;
740
8
    SEXP text, parsed, wrapper;
741
8
    Rf_protect(text = Rf_mkString(source));
742
8
    Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue));
743
8
    if (status != PARSE_OK || XLENGTH(parsed) != 1)
744
0
        abort();
745
746
8
    wrapper = Rf_eval(VECTOR_ELT(parsed, 0), R_GlobalEnv);
747
8
    Rf_unprotect(2);
748
8
    return wrapper;
749
8
}
750
751
/*
752
 * fuzz_set_string with an explicit encoding mark.
753
 *
754
 * R does not validate the mark (Encoding<- lets users set it on any
755
 * bytes), so handing the same payload over as UTF-8 or latin1 reaches
756
 * the multibyte branches and their handling of invalid sequences
757
 * without touching the process locale.
758
 */
759
typedef struct {
760
    SEXP vec;
761
    const char *str;
762
    cetype_t ce;
763
} fuzz_ce_string_data_t;
764
765
static void fuzz_do_set_string_ce(void *data)
766
0
{
767
0
    fuzz_ce_string_data_t *sd = (fuzz_ce_string_data_t *)data;
768
0
    SET_STRING_ELT(sd->vec, 0, Rf_mkCharCE(sd->str, sd->ce));
769
0
}
770
771
static Rboolean fuzz_set_string_ce(SEXP vec, const char *str, cetype_t ce)
772
0
{
773
0
    fuzz_ce_string_data_t sd = { vec, str, ce };
774
0
    return R_ToplevelExec(fuzz_do_set_string_ce, &sd);
775
0
}
776
777
typedef struct {
778
    SEXP call;
779
    const uint8_t *data;
780
    size_t size;
781
} fuzz_raw_data_t;
782
783
static void fuzz_do_set_raw(void *data)
784
5.69k
{
785
5.69k
    fuzz_raw_data_t *rd = (fuzz_raw_data_t *)data;
786
787
    /* The raw vector is reachable from the (protected) call as soon as
788
     * SETCADR runs, and nothing allocates before the memcpy completes,
789
     * so no extra protection is needed. */
790
5.69k
    SEXP raw = Rf_allocVector(RAWSXP, (R_xlen_t)rd->size);
791
5.69k
    SETCADR(rd->call, raw);
792
5.69k
    memcpy(RAW(raw), rd->data, rd->size);
793
5.69k
}
794
795
static Rboolean fuzz_set_raw_arg(SEXP call, const uint8_t *data, size_t size)
796
5.69k
{
797
5.69k
    fuzz_raw_data_t rd = { call, data, size };
798
5.69k
    return R_ToplevelExec(fuzz_do_set_raw, &rd);
799
5.69k
}
800
801
/*
802
 * Stage the input in a scratch file.
803
 *
804
 * Some R entry points only take a path (load() of a pre-1.4 save file,
805
 * unzip(), file(encoding=)), so those targets rewrite one per-process
806
 * file each iteration instead of handing R a raw vector.  The file lives
807
 * in the system temp directory, which OSS-Fuzz runners allow writes to,
808
 * and is created once in fuzz_target_init so fuzzing never pays a
809
 * mkstemp per input.  Returns a malloc'd path, or NULL on failure.
810
 */
811
static char *fuzz_scratch_file(const char *name)
812
0
{
813
0
    const char *tmpdir = getenv("TMPDIR");
814
0
    if (tmpdir == NULL || *tmpdir == '\0')
815
0
        tmpdir = "/tmp";
816
0
817
0
    char *path = malloc(PATH_MAX);
818
0
    if (path == NULL)
819
0
        return NULL;
820
0
    snprintf(path, PATH_MAX, "%s/fuzz-%s-XXXXXX", tmpdir, name);
821
0
822
0
    int fd = mkstemp(path);
823
0
    if (fd < 0) {
824
0
        free(path);
825
0
        return NULL;
826
0
    }
827
0
    close(fd);
828
0
    return path;
829
0
}
830
831
/* Replace the scratch file's contents.  Returns FALSE on any I/O error so
832
 * the iteration can be skipped rather than fuzzing a stale file. */
833
static Rboolean fuzz_write_scratch(const char *path, const uint8_t *data,
834
                                   size_t size)
835
0
{
836
0
    FILE *fp = fopen(path, "wb");
837
0
    if (fp == NULL)
838
0
        return FALSE;
839
0
840
0
    size_t written = size > 0 ? fwrite(data, 1, size, fp) : 0;
841
0
    int rc = fclose(fp);
842
0
    return written == size && rc == 0;
843
0
}
844
845
/*
846
 * Guard against TRE's bounded-repeat blowup.
847
 *
848
 * TRE compiles bounded repeats by duplicating the pattern AST, so nested
849
 * counted repeats multiply: a 36-byte pattern like
850
 * (?:a{2,101,})(?:a{2,101,}){100}{100} expands to ~10^8 nodes and >8GB of
851
 * allocations at compile time.  Those allocations are malloc, not R's
852
 * vector heap, so R_MAX_VSIZE cannot bound them; reject the pattern
853
 * before it reaches R instead.
854
 *
855
 * The product of all repeat bounds is a deliberate over-estimate --
856
 * sequential (non-nested) repeats add rather than multiply -- trading a
857
 * little coverage of repeat-heavy patterns for a hard bound on compile
858
 * cost.
859
 */
860
#define FUZZ_MAX_REPEAT_PRODUCT 1000000.0
861
862
static int fuzz_repeat_product_excessive(const char *pattern)
863
0
{
864
0
    double product = 1.0;
865
0
866
0
    for (const char *p = pattern; *p != '\0'; p++) {
867
0
        if (*p != '{')
868
0
            continue;
869
0
870
0
        /* The largest number inside the braces bounds this repeat. */
871
0
        unsigned long bound = 0, cur = 0;
872
0
        int counted = 0;
873
0
        const char *q = p + 1;
874
0
        for (; *q != '\0' && *q != '}'; q++) {
875
0
            if (*q >= '0' && *q <= '9') {
876
0
                cur = cur * 10 + (unsigned long)(*q - '0');
877
0
                if (cur > 10000000)
878
0
                    cur = 10000000;  /* saturate; already over any budget */
879
0
                counted = 1;
880
0
            } else if (*q == ',') {
881
0
                if (cur > bound)
882
0
                    bound = cur;
883
0
                cur = 0;
884
0
            } else {
885
0
                counted = 0;  /* not a counted repeat, e.g. "{a}" */
886
0
                break;
887
0
            }
888
0
        }
889
0
        if (!counted || *q != '}')
890
0
            continue;
891
0
892
0
        if (cur > bound)
893
0
            bound = cur;
894
0
        if (bound > 1)
895
0
            product *= (double)bound;
896
0
        if (product > FUZZ_MAX_REPEAT_PRODUCT)
897
0
            return 1;
898
0
899
0
        p = q;
900
0
    }
901
0
902
0
    return 0;
903
0
}
904
905
/*
906
 * libFuzzer entry points.
907
 *
908
 * A harness defines fuzz_target_init and fuzz_target_run with the
909
 * LLVMFuzzerInitialize / LLVMFuzzerTestOneInput signatures; these run
910
 * them on the R thread, one condition-variable handoff each way per input.
911
 */
912
int fuzz_target_init(int *argc, char ***argv);
913
int fuzz_target_run(const uint8_t *data, size_t size);
914
915
typedef struct {
916
    int *argc;
917
    char ***argv;
918
    int result;
919
} fuzz_init_job_t;
920
921
static void fuzz_do_target_init(void *data)
922
2
{
923
2
    fuzz_init_job_t *job = data;
924
2
    job->result = fuzz_target_init(job->argc, job->argv);
925
2
}
926
927
typedef struct {
928
    const uint8_t *data;
929
    size_t size;
930
    int result;
931
} fuzz_run_job_t;
932
933
static void fuzz_do_target_run(void *data)
934
5.70k
{
935
5.70k
    fuzz_run_job_t *job = data;
936
5.70k
    atomic_store(&fuzz_label_current, -1);
937
5.70k
    job->result = fuzz_target_run(job->data, job->size);
938
5.70k
    atomic_store(&fuzz_label_current, -1);
939
5.70k
}
940
941
#ifdef FUZZ_ENGINE_LIBFUZZER
942
/*
943
 * Split the libFuzzer sessions on entropic exec-time scaling (README.md,
944
 * "Engine options").  Not `random(0, 1)` in the .options files: ClusterFuzz
945
 * expands it, but OSS-Fuzz's build check pastes option values into
946
 * `bash -c` unquoted, the parentheses are a syntax error, and every target
947
 * counts as broken.  libFuzzer parses its flags only after
948
 * LLVMFuzzerInitialize returns, so the flag is appended to argv here.  One
949
 * already on the command line wins; that also keeps a fork-mode parent's
950
 * choice in its children, which inherit its flags.
951
 */
952
17
#define FUZZ_EXEC_TIME_FLAG "-entropic_scale_per_exec_time="
953
954
/* Static so LeakSanitizer counts the array as reachable. */
955
static char **fuzz_split_argv;
956
957
static void fuzz_split_exec_time_scaling(int *argc, char ***argv)
958
2
{
959
9
    for (int i = 1; i < *argc; i++) {
960
8
        if (strncmp((*argv)[i], FUZZ_EXEC_TIME_FLAG,
961
8
                    strlen(FUZZ_EXEC_TIME_FLAG)) == 0)
962
1
            return;
963
8
    }
964
965
    /* Not rand(): unseeded, it gives every session the same answer. */
966
1
    unsigned char coin;
967
1
    FILE *urandom = fopen("/dev/urandom", "rb");
968
1
    if (urandom == NULL || fread(&coin, 1, 1, urandom) != 1)
969
0
        coin = (unsigned char)getpid();
970
1
    if (urandom != NULL)
971
1
        fclose(urandom);
972
973
1
    fuzz_split_argv = malloc((*argc + 2) * sizeof(char *));
974
1
    if (fuzz_split_argv == NULL)
975
0
        return;
976
1
    memcpy(fuzz_split_argv, *argv, *argc * sizeof(char *));
977
1
    fuzz_split_argv[*argc] = (coin & 1) ? FUZZ_EXEC_TIME_FLAG "1"
978
1
                                        : FUZZ_EXEC_TIME_FLAG "0";
979
1
    fuzz_split_argv[*argc + 1] = NULL;
980
981
1
    fprintf(stderr, "fuzz: this session runs with %s\n",
982
1
            fuzz_split_argv[*argc]);
983
1
    *argv = fuzz_split_argv;
984
1
    (*argc)++;
985
1
}
986
#endif
987
988
int LLVMFuzzerInitialize(int *argc, char ***argv)
989
2
{
990
2
#ifdef FUZZ_ENGINE_LIBFUZZER
991
2
    fuzz_split_exec_time_scaling(argc, argv);
992
2
#endif
993
994
    /* libFuzzer parses this itself; the alarm wrapper needs the value. */
995
13
    for (int i = 1; i < *argc; i++) {
996
11
        const char *arg = (*argv)[i];
997
11
        if (strncmp(arg, "-timeout=", 9) == 0)
998
2
            fuzz_alarm.timeout = atoi(arg + 9);
999
11
    }
1000
1001
2
    fuzz_init_job_t job = { argc, argv, 0 };
1002
2
    fuzz_run_on_r_thread(fuzz_do_target_init, &job);
1003
2
    return job.result;
1004
2
}
1005
1006
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1007
5.70k
{
1008
5.70k
    fuzz_alarm_wrap();
1009
1010
5.70k
    fuzz_run_job_t job = { data, size, 0 };
1011
5.70k
    fuzz_run_on_r_thread(fuzz_do_target_run, &job);
1012
5.70k
    return job.result;
1013
5.70k
}
1014
1015
#endif /* FUZZ_COMMON_H */