Coverage Report

Created: 2026-11-13 07:19

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 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
1
# 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
 */
171
#ifndef FUZZ_R_STACK_SIZE
172
4
# define FUZZ_R_STACK_SIZE ((size_t)1 << 30)
173
#endif
174
175
typedef struct {
176
    void (*fn)(void *);
177
    void *arg;
178
} fuzz_job_t;
179
180
static struct {
181
    pthread_t thread;
182
    int started;
183
    pthread_mutex_t mutex;
184
    pthread_cond_t cond;
185
    fuzz_job_t *job;        /* set by the caller, cleared by the thread */
186
    uintptr_t stack_top;    /* where the thread's frames begin */
187
} fuzz_r_thread = {
188
    .mutex = PTHREAD_MUTEX_INITIALIZER,
189
    .cond = PTHREAD_COND_INITIALIZER
190
};
191
192
/*
193
 * Timeout diagnostics.
194
 *
195
 * With the alarm confined to the main thread, libFuzzer's timeout report
196
 * would show that thread waiting in fuzz_run_on_r_thread and nothing of
197
 * where R is.  So once libFuzzer has installed its SIGALRM handler, a
198
 * wrapper takes its place: on a tick where libFuzzer may time the input
199
 * out, it first signals the R thread, which prints its own stack, and
200
 * then hands the alarm on to libFuzzer, which prints its report and
201
 * exits.  The wrapper goes in after libFuzzer's startup because libFuzzer
202
 * leaves an already-installed SIGALRM handler alone.
203
 *
204
 * libFuzzer's clock for the input is not visible, but it is bracketed:
205
 * it starts after the main thread last went idle (armed) and before the
206
 * R thread took the input (started).  Every tick (timeout/2+1 s apart)
207
 * comes through here.  One that finds the input within a second of the
208
 * timeout by the armed clock, so possibly out of time by libFuzzer's
209
 * after whatever delays this handler, holds until the input is out of
210
 * time by the started clock too, which means by libFuzzer's as well;
211
 * then the dump is requested and waited for, and the tick goes on to
212
 * libFuzzer, which reports the timeout.  A tick that finds the input
213
 * younger goes straight on, and only one delayed by over a second
214
 * between reading the armed clock and libFuzzer reading its own can
215
 * still leave a timeout without its dump.  The dump pauses the R
216
 * thread, so it is taken only for an input already out of time, never
217
 * for one that may still finish.
218
 *
219
 * An input that finishes while a tick is held is not handed to libFuzzer
220
 * at all, nor is any tick that queued up meanwhile: it finished within
221
 * its time by its own clock, and the hold would be blamed for it.  Inputs
222
 * are numbered so a dump outstanding from one cannot stand in for the
223
 * next's, and the R thread itself announces when an input is running, so
224
 * a tick during the handoff finds nothing to dump.
225
 */
226
#ifdef SIGRTMIN
227
1
# define FUZZ_DUMP_SIGNAL SIGRTMIN   /* untouched by libFuzzer, glibc and R */
228
#else
229
# define FUZZ_DUMP_SIGNAL SIGUSR2    /* macOS: displaces libFuzzer's graceful exit */
230
#endif
231
232
extern void __sanitizer_print_stack_trace(void) __attribute__((weak));
233
234
static struct {
235
    int timeout;                 /* -timeout=N, seconds */
236
    long poll_ns;                /* between looks while holding or waiting */
237
    int wrapped;
238
    struct sigaction chain;      /* libFuzzer's SIGALRM action */
239
    struct timespec armed;       /* main thread idle; libFuzzer's clock starts later */
240
    struct timespec started;     /* the R thread took the input; libFuzzer's clock started earlier */
241
    atomic_int running;          /* the R thread is inside an input */
242
    atomic_int finishing;        /* a held tick saw the input finish */
243
    atomic_uint input;           /* numbers the inputs from 1; 0 is none */
244
    atomic_uint requested;       /* input whose dump was requested */
245
    atomic_uint done;            /* input whose dump has been printed */
246
} fuzz_alarm = { .timeout = 1200, .poll_ns = 1000 * 1000 };  /* libFuzzer's default */
247
248
static void fuzz_write_stderr(const char *s)
249
0
{
250
0
    ssize_t rc = write(STDERR_FILENO, s, strlen(s));
251
0
    (void)rc;
252
0
}
253
254
/*
255
 * Slot labels for the timeout dump.
256
 *
257
 * The R thread's stack is mostly the byte-code interpreter, which says
258
 * little about which of a target's calls was running.  A harness
259
 * registers its calls once with fuzz_label_calls(), which deparses each
260
 * while its placeholders still hold their initial values, and the dump
261
 * prints the one last entered by fuzz_eval_silent() or fuzz_do_eval() in
262
 * the current input.  Harnesses that evaluate a registered call another
263
 * way note it with fuzz_label_enter().  The text is formatted up front,
264
 * so the dump handler only writes it.
265
 */
266
52
#define FUZZ_MAX_LABELS 128
267
234
#define FUZZ_LABEL_MAX 4096
268
269
static struct {
270
    SEXP call;
271
    char *text;
272
} fuzz_labels[FUZZ_MAX_LABELS];
273
static int fuzz_n_labels;
274
static atomic_int fuzz_label_current = -1;  /* index into fuzz_labels */
275
276
typedef struct {
277
    SEXP call;
278
    char *buf;      /* FUZZ_LABEL_MAX bytes, holding the header */
279
    size_t len;
280
} fuzz_deparse_job_t;
281
282
/* Append one deparsed line, indented; false if it does not fit with
283
 * room left for the closing "...". */
284
static int fuzz_label_append_line(fuzz_deparse_job_t *job, const char *line)
285
130
{
286
130
    size_t n = strlen(line);
287
130
    if (job->len + 4 + n + 1 >= FUZZ_LABEL_MAX - sizeof "    ...\n")
288
0
        return 0;
289
130
    memcpy(job->buf + job->len, "    ", 4);
290
130
    memcpy(job->buf + job->len + 4, line, n);
291
130
    job->buf[job->len + 4 + n] = '\n';
292
130
    job->len += 4 + n + 1;
293
130
    job->buf[job->len] = '\0';
294
130
    return 1;
295
130
}
296
297
static void fuzz_do_deparse(void *data)
298
52
{
299
52
    fuzz_deparse_job_t *job = data;
300
52
    SEXP quoted, expr, lines;
301
52
    Rf_protect(quoted = Rf_lang2(R_QuoteSymbol, job->call));
302
52
    Rf_protect(expr = Rf_lang2(Rf_install("deparse"), quoted));
303
52
    Rf_protect(lines = Rf_eval(expr, R_BaseEnv));
304
182
    for (R_xlen_t i = 0; i < XLENGTH(lines); i++) {
305
130
        if (!fuzz_label_append_line(job, CHAR(STRING_ELT(lines, i)))) {
306
0
            memcpy(job->buf + job->len, "    ...\n", sizeof "    ...\n");
307
0
            break;
308
0
        }
309
130
    }
310
52
    Rf_unprotect(3);
311
52
}
312
313
static void fuzz_label_call(SEXP call, int slot, int n_slots)
314
52
{
315
52
    if (call == NULL || call == R_NilValue)
316
0
        return;
317
318
    /* A call shared by several slots (run under different settings, say)
319
     * keeps one label naming them all. */
320
702
    for (int i = 0; i < fuzz_n_labels; i++) {
321
650
        if (fuzz_labels[i].call != call)
322
650
            continue;
323
0
        char *old = fuzz_labels[i].text;
324
0
        char *of = strstr(old, " of ");  /* "==fuzz== slot 7 of 9:" */
325
0
        size_t size = strlen(old) + 32;
326
0
        char *buf = malloc(size);
327
0
        if (of == NULL || buf == NULL) {
328
0
            free(buf);
329
0
            return;
330
0
        }
331
0
        snprintf(buf, size, "%.*s, %d%s", (int)(of - old), old, slot, of);
332
0
        fuzz_labels[i].text = buf;
333
0
        free(old);
334
0
        return;
335
0
    }
336
52
    if (fuzz_n_labels == FUZZ_MAX_LABELS)
337
0
        return;
338
339
52
    char *buf = malloc(FUZZ_LABEL_MAX);
340
52
    if (buf == NULL)
341
0
        return;
342
52
    int n = snprintf(buf, FUZZ_LABEL_MAX, "==fuzz== slot %d of %d:\n", slot, n_slots);
343
344
    /* A failed deparse leaves the header alone. */
345
52
    fuzz_deparse_job_t job = { call, buf, (size_t)n };
346
52
    R_ToplevelExec(fuzz_do_deparse, &job);
347
348
52
    fuzz_labels[fuzz_n_labels].call = call;
349
52
    fuzz_labels[fuzz_n_labels].text = buf;
350
52
    fuzz_n_labels++;
351
52
}
352
353
/* Label calls[0..n-1] as slots 0..n-1; NULL entries (slots run in C)
354
 * are skipped. */
355
static void fuzz_label_calls(const SEXP *calls, int n)
356
0
{
357
0
    for (int i = 0; i < n; i++)
358
0
        fuzz_label_call(calls[i], i, n);
359
0
}
360
361
/* Note the call about to be evaluated; an unregistered one clears it. */
362
static void fuzz_label_enter(SEXP call)
363
2.20k
{
364
2.20k
    int found = -1;
365
33.6k
    for (int i = 0; i < fuzz_n_labels; i++) {
366
33.6k
        if (fuzz_labels[i].call == call) {
367
2.20k
            found = i;
368
2.20k
            break;
369
2.20k
        }
370
33.6k
    }
371
2.20k
    atomic_store(&fuzz_label_current, found);
372
2.20k
}
373
374
/* Runs on the R thread, interrupting whatever the input is doing. */
375
static void fuzz_dump_handler(int sig, siginfo_t *info, void *context)
376
0
{
377
0
    (void)sig;
378
0
    (void)info;
379
0
    (void)context;
380
0
    unsigned input = atomic_load(&fuzz_alarm.requested);
381
0
    int label = atomic_load(&fuzz_label_current);
382
0
    if (label >= 0)
383
0
        fuzz_write_stderr(fuzz_labels[label].text);
384
0
    if (__sanitizer_print_stack_trace)
385
0
        __sanitizer_print_stack_trace();
386
0
    else
387
0
        fuzz_write_stderr("    (no sanitizer runtime to print it)\n");
388
0
    atomic_store(&fuzz_alarm.done, input);
389
0
}
390
391
/* Whole seconds since a moment. */
392
static long fuzz_seconds_since(const struct timespec *then)
393
0
{
394
0
    struct timespec now;
395
0
    clock_gettime(CLOCK_REALTIME, &now);
396
397
0
    long seconds = now.tv_sec - then->tv_sec;
398
0
    if (now.tv_nsec < then->tv_nsec)
399
0
        seconds--;
400
0
    return seconds;
401
0
}
402
403
/* Runs on the main thread, where libFuzzer's alarm lands. */
404
static void fuzz_alarm_handler(int sig, siginfo_t *info, void *context)
405
0
{
406
0
    if (atomic_load(&fuzz_alarm.finishing))
407
0
        return;
408
409
0
    if (atomic_load(&fuzz_alarm.running) &&
410
0
        fuzz_seconds_since(&fuzz_alarm.armed) >= fuzz_alarm.timeout - 1) {
411
0
        struct timespec tick = { 0, fuzz_alarm.poll_ns };
412
413
        /* Hold until the input is out of time by its own clock as well;
414
         * one that finishes first, even in the last sleep, was within
415
         * its time.  The clock is read before the input is looked at, so
416
         * an input seen running was running at a moment past the
417
         * timeout, whatever delay falls between the two. */
418
0
        for (;;) {
419
0
            long age = fuzz_seconds_since(&fuzz_alarm.started);
420
0
            if (!atomic_load(&fuzz_alarm.running)) {
421
0
                atomic_store(&fuzz_alarm.finishing, 1);
422
0
                return;
423
0
            }
424
0
            if (age >= fuzz_alarm.timeout)
425
0
                break;
426
0
            nanosleep(&tick, NULL);
427
0
        }
428
429
0
        unsigned input = atomic_load(&fuzz_alarm.input);
430
0
        if (atomic_load(&fuzz_alarm.requested) != input) {
431
0
            atomic_store(&fuzz_alarm.requested, input);
432
0
            fuzz_write_stderr("==fuzz== R thread, where the input is running:\n");
433
0
            if (pthread_kill(fuzz_r_thread.thread, FUZZ_DUMP_SIGNAL) != 0)
434
0
                atomic_store(&fuzz_alarm.done, input);
435
0
        }
436
437
        /* Symbolizing takes a moment; a thread that never answers (stuck
438
         * in the allocator, say) must not hold up the report, and an
439
         * input finishing now is reported all the same: it was out of
440
         * time already. */
441
0
        for (int i = 0; i < 5000; i++) {
442
0
            if (atomic_load(&fuzz_alarm.done) == input ||
443
0
                !atomic_load(&fuzz_alarm.running))
444
0
                break;
445
0
            nanosleep(&tick, NULL);
446
0
        }
447
0
    }
448
0
    fuzz_alarm.chain.sa_sigaction(sig, info, context);
449
0
}
450
451
/* Wrap libFuzzer's SIGALRM handler, once it exists.  Called before each
452
 * input; the first call after libFuzzer's startup sees the handler. */
453
static void fuzz_alarm_wrap(void)
454
1.50k
{
455
1.50k
    if (fuzz_alarm.wrapped)
456
1.50k
        return;
457
1
    fuzz_alarm.wrapped = 1;
458
459
1
    struct sigaction current;
460
1
    if (sigaction(SIGALRM, NULL, &current) != 0 ||
461
1
        !(current.sa_flags & SA_SIGINFO) || current.sa_sigaction == NULL)
462
0
        return;  /* no alarm: AFL++'s driver, -timeout=0, tests */
463
464
1
    struct sigaction dump;
465
1
    memset(&dump, 0, sizeof dump);
466
1
    dump.sa_sigaction = fuzz_dump_handler;
467
1
    dump.sa_flags = SA_SIGINFO;
468
1
    sigemptyset(&dump.sa_mask);
469
1
    if (sigaction(FUZZ_DUMP_SIGNAL, &dump, NULL) != 0)
470
0
        return;
471
472
1
    fuzz_alarm.chain = current;
473
1
    struct sigaction wrapper = current;
474
1
    wrapper.sa_sigaction = fuzz_alarm_handler;
475
1
    if (sigaction(SIGALRM, &wrapper, NULL) != 0)
476
0
        sigaction(FUZZ_DUMP_SIGNAL, &(struct sigaction){ .sa_handler = SIG_DFL }, NULL);
477
1
}
478
479
static void *fuzz_r_thread_main(void *unused)
480
2
{
481
2
    (void)unused;
482
    /* The frame address rather than a local's: under ASAN an address-taken
483
     * local may sit on the fake stack, nowhere near this thread's stack.
484
     * R_CStackStart matters only once R is initialized; fuzz_init_r()
485
     * sets it again after Rf_initialize_R has overwritten it. */
486
2
    fuzz_r_thread.stack_top = (uintptr_t)__builtin_frame_address(0);
487
2
    R_CStackStart = fuzz_r_thread.stack_top;
488
489
    /* libFuzzer's -timeout alarm is acted on only by the thread running
490
     * its loop (the main thread); delivered here it would be ignored and
491
     * the input would run on.  Block it so the kernel cannot pick this
492
     * thread; fuzz_alarm_handler below gets this thread's stack into the
493
     * timeout report instead. */
494
2
    sigset_t alarm;
495
2
    sigemptyset(&alarm);
496
2
    sigaddset(&alarm, SIGALRM);
497
2
    pthread_sigmask(SIG_BLOCK, &alarm, NULL);
498
499
2
    pthread_mutex_lock(&fuzz_r_thread.mutex);
500
1.50k
    for (;;) {
501
3.01k
        while (fuzz_r_thread.job == NULL)
502
1.50k
            pthread_cond_wait(&fuzz_r_thread.cond, &fuzz_r_thread.mutex);
503
1.50k
        fuzz_job_t *job = fuzz_r_thread.job;
504
1.50k
        pthread_mutex_unlock(&fuzz_r_thread.mutex);
505
506
1.50k
        clock_gettime(CLOCK_REALTIME, &fuzz_alarm.started);
507
1.50k
        atomic_store(&fuzz_alarm.running, 1);
508
1.50k
        job->fn(job->arg);
509
1.50k
        atomic_store(&fuzz_alarm.running, 0);
510
511
1.50k
        pthread_mutex_lock(&fuzz_r_thread.mutex);
512
1.50k
        fuzz_r_thread.job = NULL;
513
1.50k
        pthread_cond_broadcast(&fuzz_r_thread.cond);
514
1.50k
    }
515
2
    return NULL;
516
2
}
517
518
static int fuzz_on_r_thread(void)
519
1.50k
{
520
1.50k
    return fuzz_r_thread.started &&
521
1.50k
           pthread_equal(pthread_self(), fuzz_r_thread.thread);
522
1.50k
}
523
524
/* Child side of fork: only the forking thread survives, so the R thread
525
 * is gone, and if it was the one waiting in pthread_cond_wait the
526
 * condition variable still counts it.  Nothing holds the mutex during a
527
 * fork from either side of the handoff, so resetting both is safe;
528
 * pthread_cond_destroy would wait for the phantom waiter instead. */
529
static void fuzz_r_thread_forget(void)
530
0
{
531
0
    fuzz_r_thread.started = 0;
532
0
    fuzz_r_thread.job = NULL;
533
0
    fuzz_r_thread.mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
534
0
    fuzz_r_thread.cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
535
0
}
536
537
/* Run fn(arg) on the R thread and wait for it to return, starting the
538
 * thread on first use.  From the R thread itself this is a plain call. */
539
static void fuzz_run_on_r_thread(void (*fn)(void *), void *arg)
540
1.50k
{
541
1.50k
    if (!fuzz_r_thread.started) {
542
2
        static int atfork_registered = 0;
543
2
        if (!atfork_registered) {
544
2
            if (pthread_atfork(NULL, NULL, fuzz_r_thread_forget) != 0) {
545
0
                fprintf(stderr, "fuzz: cannot register the fork handler\n");
546
0
                abort();
547
0
            }
548
2
            atfork_registered = 1;
549
2
        }
550
551
2
        pthread_attr_t attr;
552
2
        if (pthread_attr_init(&attr) != 0 ||
553
2
            pthread_attr_setstacksize(&attr, FUZZ_R_STACK_SIZE) != 0 ||
554
2
            pthread_create(&fuzz_r_thread.thread, &attr,
555
2
                           fuzz_r_thread_main, NULL) != 0) {
556
0
            fprintf(stderr, "fuzz: cannot start the R thread\n");
557
0
            abort();
558
0
        }
559
2
        pthread_attr_destroy(&attr);
560
2
        fuzz_r_thread.started = 1;
561
2
    }
562
563
1.50k
    if (fuzz_on_r_thread()) {
564
0
        fn(arg);
565
0
        return;
566
0
    }
567
568
1.50k
    fuzz_job_t job = { fn, arg };
569
1.50k
    if (atomic_fetch_add(&fuzz_alarm.input, 1) + 1 == 0)
570
1.50k
        atomic_fetch_add(&fuzz_alarm.input, 1);  /* wrapped past 0, which is none */
571
572
1.50k
    pthread_mutex_lock(&fuzz_r_thread.mutex);
573
1.50k
    fuzz_r_thread.job = &job;
574
1.50k
    pthread_cond_broadcast(&fuzz_r_thread.cond);
575
3.01k
    while (fuzz_r_thread.job != NULL)
576
1.50k
        pthread_cond_wait(&fuzz_r_thread.cond, &fuzz_r_thread.mutex);
577
1.50k
    pthread_mutex_unlock(&fuzz_r_thread.mutex);
578
579
    /* Idle again: ticks count, and libFuzzer's clock for the next input
580
     * starts after this. */
581
1.50k
    atomic_store(&fuzz_alarm.finishing, 0);
582
1.50k
    clock_gettime(CLOCK_REALTIME, &fuzz_alarm.armed);
583
1.50k
}
584
585
/*
586
 * Initialize R for fuzzing.  Call once from fuzz_target_init.
587
 *
588
 * Performs:
589
 *   1. Set R_HOME from binary location
590
 *   2. Cap the vector heap (must precede R's startup, which reads it)
591
 *   3. Initialize embedded R, without R's signal handlers
592
 *   4. Point R's C stack check at the R thread's stack
593
 *   5. Suppress warnings
594
 */
595
static void fuzz_init_r(void)
596
2
{
597
2
    if (!fuzz_on_r_thread()) {
598
0
        fprintf(stderr, "fuzz_init_r: must run on the R thread "
599
0
                        "(define fuzz_target_init, not LLVMFuzzerInitialize)\n");
600
0
        abort();
601
0
    }
602
603
2
    fuzz_set_r_home();
604
2
    fuzz_set_vsize_limit();
605
606
    /* GC consistency failures ("untraced old-to-new reference", a node
607
     * with a bad type) are memory corruption, not input errors.  R's
608
     * default is to report and carry on; this makes gc_error() fatal
609
     * (through R_Suicide, which instrumentation/0004 turns into abort)
610
     * so they surface as crashes at the collection that found them. */
611
2
    if (getenv("_R_GC_FAIL_ON_ERROR_") == NULL)
612
1
        setenv("_R_GC_FAIL_ON_ERROR_", "yes", 1);
613
614
    /* R's SIGSEGV/SIGILL/etc. handlers enter an interactive recovery
615
     * prompt instead of crashing, which would hang the fuzzer.  Telling
616
     * R not to install them (rather than resetting to SIG_DFL after
617
     * init) keeps the sanitizers' own handlers in place, so wild-pointer
618
     * faults still get full ASAN reports and clean deduplication. */
619
2
    R_SignalHandlers = 0;
620
621
    /* The two halves of Rf_initEmbeddedR, with the C stack check fixed
622
     * up in between.  On Linux Rf_initialize_R takes R_CStackStart from
623
     * __libc_stack_end, the main thread's stack, so from this thread
624
     * every R_CheckStack() while setup_Rmainloop loads base would see
625
     * terabytes of usage and R would abort ("unable to initialize the
626
     * JIT").  macOS never sets it when embedded, which hides this
627
     * locally.  Switch the check off for startup, then measure against
628
     * this thread with R's own 5% of headroom for handling the overflow
629
     * error: R_CheckStack() fires as an ordinary R error at
630
     * 0.95 * FUZZ_R_STACK_SIZE rather than the sanitizer catching a fault.
631
     * setup_Rmainloop itself would turn any limit above 100 MB into
632
     * "unlimited", hence setting it after. */
633
2
    char *r_argv[] = {"R", "--vanilla", "--no-echo", "--no-restore"};
634
2
    int r_argc = sizeof(r_argv) / sizeof(r_argv[0]);
635
2
    Rf_initialize_R(r_argc, r_argv);
636
2
    R_CStackStart = fuzz_r_thread.stack_top;
637
2
    R_CStackLimit = (uintptr_t)-1;
638
2
    R_Interactive = TRUE;   /* as Rf_initEmbeddedR */
639
2
    setup_Rmainloop();
640
2
    R_CStackLimit = (uintptr_t)(0.95 * FUZZ_R_STACK_SIZE);
641
642
2
    fuzz_suppress_warnings();
643
2
}
644
645
/*
646
 * Helper for protected evaluation via R_ToplevelExec.
647
 *
648
 * R API calls that touch R objects can longjmp on error.  Without a
649
 * top-level context, R's error handler crashes.  Wrapping calls in
650
 * R_ToplevelExec catches the longjmp cleanly.
651
 */
652
typedef struct {
653
    SEXP call;
654
    SEXP env;
655
} fuzz_eval_data_t;
656
657
static void fuzz_do_eval(void *data)
658
0
{
659
0
    fuzz_eval_data_t *ed = (fuzz_eval_data_t *)data;
660
0
    fuzz_label_enter(ed->call);
661
0
    Rf_eval(ed->call, ed->env);
662
0
}
663
664
/* Evaluate malformed-input-heavy targets without printing each expected
665
 * R error. R_tryEvalSilent installs its own top-level error context. */
666
static void fuzz_eval_silent(SEXP call, SEXP env)
667
1.13k
{
668
1.13k
    int error = 0;
669
1.13k
    fuzz_label_enter(call);
670
1.13k
    R_tryEvalSilent(call, env, &error);
671
1.13k
}
672
673
/*
674
 * Stage per-iteration inputs under a toplevel context.
675
 *
676
 * Rf_mkChar and Rf_allocVector can themselves signal the vector-limit
677
 * error.  Outside a toplevel context that error longjmps into a stack
678
 * frame that returned during Rf_initEmbeddedR -- undefined behaviour --
679
 * so input staging must be wrapped just like evaluation.  Both helpers
680
 * return FALSE when the allocation failed; skip the iteration then.
681
 */
682
typedef struct {
683
    SEXP vec;
684
    const char *str;
685
} fuzz_string_data_t;
686
687
static void fuzz_do_set_string(void *data)
688
0
{
689
0
    fuzz_string_data_t *sd = (fuzz_string_data_t *)data;
690
0
    SET_STRING_ELT(sd->vec, 0, Rf_mkChar(sd->str));
691
0
}
692
693
static Rboolean fuzz_set_string(SEXP vec, const char *str)
694
0
{
695
0
    fuzz_string_data_t sd = { vec, str };
696
0
    return R_ToplevelExec(fuzz_do_set_string, &sd);
697
0
}
698
699
/*
700
 * Parse and evaluate one R function literal, once, at initialization.
701
 *
702
 * Harnesses whose calls need named arguments, on.exit(close(con)) or a
703
 * few R-level steps around the entry point express each slot as an R
704
 * closure and call it with Rf_lang*; that keeps the C side free of
705
 * argument plumbing.  The source is harness-authored (never fuzz
706
 * input), so a parse or evaluation failure is a harness bug: abort.
707
 */
708
static SEXP fuzz_make_wrapper(const char *source)
709
20
{
710
20
    ParseStatus status;
711
20
    SEXP text, parsed, wrapper;
712
20
    Rf_protect(text = Rf_mkString(source));
713
20
    Rf_protect(parsed = R_ParseVector(text, -1, &status, R_NilValue));
714
20
    if (status != PARSE_OK || XLENGTH(parsed) != 1)
715
0
        abort();
716
717
20
    wrapper = Rf_eval(VECTOR_ELT(parsed, 0), R_BaseEnv);
718
20
    Rf_unprotect(2);
719
20
    return wrapper;
720
20
}
721
722
/*
723
 * fuzz_set_string with an explicit encoding mark.
724
 *
725
 * R does not validate the mark (Encoding<- lets users set it on any
726
 * bytes), so handing the same payload over as UTF-8 or latin1 reaches
727
 * the multibyte branches and their handling of invalid sequences
728
 * without touching the process locale.
729
 */
730
typedef struct {
731
    SEXP vec;
732
    const char *str;
733
    cetype_t ce;
734
} fuzz_ce_string_data_t;
735
736
static void fuzz_do_set_string_ce(void *data)
737
0
{
738
0
    fuzz_ce_string_data_t *sd = (fuzz_ce_string_data_t *)data;
739
0
    SET_STRING_ELT(sd->vec, 0, Rf_mkCharCE(sd->str, sd->ce));
740
0
}
741
742
static Rboolean fuzz_set_string_ce(SEXP vec, const char *str, cetype_t ce)
743
0
{
744
0
    fuzz_ce_string_data_t sd = { vec, str, ce };
745
0
    return R_ToplevelExec(fuzz_do_set_string_ce, &sd);
746
0
}
747
748
typedef struct {
749
    SEXP call;
750
    const uint8_t *data;
751
    size_t size;
752
} fuzz_raw_data_t;
753
754
static void fuzz_do_set_raw(void *data)
755
1.13k
{
756
1.13k
    fuzz_raw_data_t *rd = (fuzz_raw_data_t *)data;
757
758
    /* The raw vector is reachable from the (protected) call as soon as
759
     * SETCADR runs, and nothing allocates before the memcpy completes,
760
     * so no extra protection is needed. */
761
1.13k
    SEXP raw = Rf_allocVector(RAWSXP, (R_xlen_t)rd->size);
762
1.13k
    SETCADR(rd->call, raw);
763
1.13k
    memcpy(RAW(raw), rd->data, rd->size);
764
1.13k
}
765
766
static Rboolean fuzz_set_raw_arg(SEXP call, const uint8_t *data, size_t size)
767
1.13k
{
768
1.13k
    fuzz_raw_data_t rd = { call, data, size };
769
1.13k
    return R_ToplevelExec(fuzz_do_set_raw, &rd);
770
1.13k
}
771
772
/*
773
 * Stage the input in a scratch file.
774
 *
775
 * Some R entry points only take a path (load() of a pre-1.4 save file,
776
 * unzip(), file(encoding=)), so those targets rewrite one per-process
777
 * file each iteration instead of handing R a raw vector.  The file lives
778
 * in the system temp directory, which OSS-Fuzz runners allow writes to,
779
 * and is created once in fuzz_target_init so fuzzing never pays a
780
 * mkstemp per input.  Returns a malloc'd path, or NULL on failure.
781
 */
782
static char *fuzz_scratch_file(const char *name)
783
0
{
784
0
    const char *tmpdir = getenv("TMPDIR");
785
0
    if (tmpdir == NULL || *tmpdir == '\0')
786
0
        tmpdir = "/tmp";
787
0
788
0
    char *path = malloc(PATH_MAX);
789
0
    if (path == NULL)
790
0
        return NULL;
791
0
    snprintf(path, PATH_MAX, "%s/fuzz-%s-XXXXXX", tmpdir, name);
792
0
793
0
    int fd = mkstemp(path);
794
0
    if (fd < 0) {
795
0
        free(path);
796
0
        return NULL;
797
0
    }
798
0
    close(fd);
799
0
    return path;
800
0
}
801
802
/* Replace the scratch file's contents.  Returns FALSE on any I/O error so
803
 * the iteration can be skipped rather than fuzzing a stale file. */
804
static Rboolean fuzz_write_scratch(const char *path, const uint8_t *data,
805
                                   size_t size)
806
0
{
807
0
    FILE *fp = fopen(path, "wb");
808
0
    if (fp == NULL)
809
0
        return FALSE;
810
0
811
0
    size_t written = size > 0 ? fwrite(data, 1, size, fp) : 0;
812
0
    int rc = fclose(fp);
813
0
    return written == size && rc == 0;
814
0
}
815
816
/*
817
 * Guard against TRE's bounded-repeat blowup.
818
 *
819
 * TRE compiles bounded repeats by duplicating the pattern AST, so nested
820
 * counted repeats multiply: a 36-byte pattern like
821
 * (?:a{2,101,})(?:a{2,101,}){100}{100} expands to ~10^8 nodes and >8GB of
822
 * allocations at compile time.  Those allocations are malloc, not R's
823
 * vector heap, so R_MAX_VSIZE cannot bound them; reject the pattern
824
 * before it reaches R instead.
825
 *
826
 * The product of all repeat bounds is a deliberate over-estimate --
827
 * sequential (non-nested) repeats add rather than multiply -- trading a
828
 * little coverage of repeat-heavy patterns for a hard bound on compile
829
 * cost.
830
 */
831
#define FUZZ_MAX_REPEAT_PRODUCT 1000000.0
832
833
static int fuzz_repeat_product_excessive(const char *pattern)
834
0
{
835
0
    double product = 1.0;
836
0
837
0
    for (const char *p = pattern; *p != '\0'; p++) {
838
0
        if (*p != '{')
839
0
            continue;
840
0
841
0
        /* The largest number inside the braces bounds this repeat. */
842
0
        unsigned long bound = 0, cur = 0;
843
0
        int counted = 0;
844
0
        const char *q = p + 1;
845
0
        for (; *q != '\0' && *q != '}'; q++) {
846
0
            if (*q >= '0' && *q <= '9') {
847
0
                cur = cur * 10 + (unsigned long)(*q - '0');
848
0
                if (cur > 10000000)
849
0
                    cur = 10000000;  /* saturate; already over any budget */
850
0
                counted = 1;
851
0
            } else if (*q == ',') {
852
0
                if (cur > bound)
853
0
                    bound = cur;
854
0
                cur = 0;
855
0
            } else {
856
0
                counted = 0;  /* not a counted repeat, e.g. "{a}" */
857
0
                break;
858
0
            }
859
0
        }
860
0
        if (!counted || *q != '}')
861
0
            continue;
862
0
863
0
        if (cur > bound)
864
0
            bound = cur;
865
0
        if (bound > 1)
866
0
            product *= (double)bound;
867
0
        if (product > FUZZ_MAX_REPEAT_PRODUCT)
868
0
            return 1;
869
0
870
0
        p = q;
871
0
    }
872
0
873
0
    return 0;
874
0
}
875
876
/*
877
 * libFuzzer entry points.
878
 *
879
 * A harness defines fuzz_target_init and fuzz_target_run with the
880
 * LLVMFuzzerInitialize / LLVMFuzzerTestOneInput signatures; these run
881
 * them on the R thread, one condition-variable handoff each way per input.
882
 */
883
int fuzz_target_init(int *argc, char ***argv);
884
int fuzz_target_run(const uint8_t *data, size_t size);
885
886
typedef struct {
887
    int *argc;
888
    char ***argv;
889
    int result;
890
} fuzz_init_job_t;
891
892
static void fuzz_do_target_init(void *data)
893
2
{
894
2
    fuzz_init_job_t *job = data;
895
2
    job->result = fuzz_target_init(job->argc, job->argv);
896
2
}
897
898
typedef struct {
899
    const uint8_t *data;
900
    size_t size;
901
    int result;
902
} fuzz_run_job_t;
903
904
static void fuzz_do_target_run(void *data)
905
1.50k
{
906
1.50k
    fuzz_run_job_t *job = data;
907
1.50k
    atomic_store(&fuzz_label_current, -1);
908
1.50k
    job->result = fuzz_target_run(job->data, job->size);
909
1.50k
    atomic_store(&fuzz_label_current, -1);
910
1.50k
}
911
912
int LLVMFuzzerInitialize(int *argc, char ***argv)
913
2
{
914
    /* libFuzzer parses this itself; the alarm wrapper needs the value. */
915
11
    for (int i = 1; i < *argc; i++) {
916
9
        const char *arg = (*argv)[i];
917
9
        if (strncmp(arg, "-timeout=", 9) == 0)
918
2
            fuzz_alarm.timeout = atoi(arg + 9);
919
9
    }
920
921
2
    fuzz_init_job_t job = { argc, argv, 0 };
922
2
    fuzz_run_on_r_thread(fuzz_do_target_init, &job);
923
2
    return job.result;
924
2
}
925
926
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
927
1.50k
{
928
1.50k
    fuzz_alarm_wrap();
929
930
1.50k
    fuzz_run_job_t job = { data, size, 0 };
931
1.50k
    fuzz_run_on_r_thread(fuzz_do_target_run, &job);
932
1.50k
    return job.result;
933
1.50k
}
934
935
#endif /* FUZZ_COMMON_H */