Coverage Report

Created: 2026-11-13 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-oss-fuzz/harnesses/datetime.c
Line
Count
Source
1
/*
2
 * libFuzzer harness for R's date/time parsing and formatting.
3
 *
4
 * Passes fuzzed input through strptime, as.Date, as.POSIXct, as.POSIXlt,
5
 * format.POSIXlt and balancePOSIXlt -- exercising R_strptime (Rstrptime.h)
6
 * and src/main/datetime.c: ~2000 lines of locale-dependent parsing,
7
 * timezone handling, leap seconds, and DST transitions.
8
 *
9
 * Input layout: the first byte selects a call slot, the rest is the
10
 * payload.  Slots 0-8 take the whole payload as the datetime string and
11
 * use fixed format strings (the original shape of this target, so the
12
 * stored corpus keeps its meaning).  Slots 9 and up split the payload at
13
 * its first newline: the format string comes before it and the datetime
14
 * string after, so strptime directives and strftime output are fuzzed
15
 * too.  Without a newline the payload is the datetime string and a
16
 * default format is used.
17
 *
18
 * Adapted from r-afl's datetime harness.
19
 */
20
21
#include <locale.h>
22
#include <stdint.h>
23
#include <string.h>
24
25
#include "common.h"
26
27
13.9k
#define FUZZ_MAX_INPUT (1024 * 64)
28
29
/*
30
 * strptime format strings, each exercising a different path in
31
 * Rstrptime.h's strptime_internal (numeric fields, locale month/weekday
32
 * names, ISO 8601 zone offset, locale preferred representations).
33
 */
34
20.9k
#define N_FORMATS 6
35
static const char *strptime_formats[N_FORMATS] = {
36
    "%Y-%m-%d %H:%M:%S",
37
    "%d/%b/%Y",
38
    "%Y-%m-%dT%H:%M:%S%z",
39
    "%c",
40
    "%x %X",
41
    "%a %d %b %Y",
42
};
43
44
20.9k
#define N_FIXED_CALLS (N_FORMATS + 3)
45
13.9k
#define N_FMT_CALLS 8
46
13.9k
#define N_CALLS (N_FIXED_CALLS + N_FMT_CALLS)
47
48
/* Slots from this index on run with a UTF-8 LC_CTYPE and the others with
49
 * C, whatever locale the runner starts in, so R_strptime takes its
50
 * wide-character path (w_strptime_internal) here and its narrow one
51
 * (strptime_internal) everywhere else. */
52
6.97k
#define FIRST_UTF8_CALL (N_CALLS - 2)
53
54
6.94k
#define DEFAULT_FORMAT "%Y-%m-%d %H:%M:%OS"
55
56
static SEXP x_str;
57
static SEXP fmt_str;
58
static SEXP calls[N_CALLS];
59
60
static SEXP call_ctype_utf8;
61
static SEXP call_ctype_c;
62
63
/* -1 until set_ctype first runs: R starts in the runner's own locale
64
 * (UTF-8 on the OSS-Fuzz bots), which may match neither setting. */
65
static int ctype_is_utf8 = -1;
66
67
/* Pick a UTF-8 locale this runner has.  Returns NULL when none exists,
68
 * in which case the UTF-8 slots simply run in the C locale.  The probe
69
 * puts LC_CTYPE back as it found it: R picks the strptime path from its
70
 * own cached view of the locale, which only Sys.setlocale updates. */
71
static const char *find_utf8_locale(void)
72
2
{
73
2
    static const char *const candidates[] = { "C.UTF-8", "en_US.UTF-8", NULL };
74
2
    const char *found = NULL;
75
2
    char *saved = strdup(setlocale(LC_CTYPE, NULL));
76
77
2
    for (int i = 0; candidates[i] != NULL; i++) {
78
2
        if (setlocale(LC_CTYPE, candidates[i]) != NULL) {
79
2
            found = candidates[i];
80
2
            break;
81
2
        }
82
2
    }
83
84
2
    setlocale(LC_CTYPE, saved);
85
2
    free(saved);
86
2
    return found;
87
2
}
88
89
static SEXP make_setlocale_call(const char *name)
90
4
{
91
4
    SEXP call;
92
4
    Rf_protect(call = Rf_lang3(Rf_install("Sys.setlocale"),
93
4
                               Rf_mkString("LC_CTYPE"), Rf_mkString(name)));
94
4
    return call;
95
4
}
96
97
/* Switch LC_CTYPE only when a slot needs the other setting; Sys.setlocale
98
 * is cheap but not free, and consecutive inputs usually share a slot. */
99
static void set_ctype(int want_utf8)
100
6.97k
{
101
6.97k
    if (call_ctype_utf8 == NULL)
102
0
        want_utf8 = 0;
103
6.97k
    if (want_utf8 == ctype_is_utf8)
104
3.86k
        return;
105
106
3.11k
    fuzz_eval_silent(want_utf8 ? call_ctype_utf8 : call_ctype_c, R_GlobalEnv);
107
3.11k
    ctype_is_utf8 = want_utf8;
108
3.11k
}
109
110
int fuzz_target_init(int *argc, char ***argv)
111
2
{
112
2
    fuzz_init_r();
113
114
2
    SEXP sym_strptime   = Rf_install("strptime");
115
2
    SEXP sym_as_Date    = Rf_install("as.Date");
116
2
    SEXP sym_as_POSIXct = Rf_install("as.POSIXct");
117
2
    SEXP sym_as_POSIXlt = Rf_install("as.POSIXlt");
118
2
    SEXP sym_format     = Rf_install("format");
119
2
    SEXP sym_tz         = Rf_install("tz");
120
121
    /* Reusable input containers -- each iteration swaps their CHARSXPs. */
122
2
    Rf_protect(x_str = Rf_allocVector(STRSXP, 1));
123
2
    Rf_protect(fmt_str = Rf_allocVector(STRSXP, 1));
124
125
2
    SEXP tz_utc, tz_london, true_val;
126
2
    Rf_protect(tz_utc = Rf_mkString("UTC"));
127
2
    Rf_protect(tz_london = Rf_mkString("Europe/London"));
128
2
    Rf_protect(true_val = Rf_ScalarLogical(TRUE));
129
130
    /* strptime(x, format=fmt, tz="UTC") for each fixed format */
131
14
    for (int i = 0; i < N_FORMATS; i++) {
132
12
        SEXP fmt;
133
12
        Rf_protect(fmt = Rf_mkString(strptime_formats[i]));
134
12
        Rf_protect(calls[i] = Rf_lang4(sym_strptime, x_str, fmt, tz_utc));
135
12
        SET_TAG(CDDR(calls[i]), sym_format);
136
12
        SET_TAG(CDR(CDDR(calls[i])), sym_tz);
137
12
    }
138
139
    /* as.Date(x, format="%Y-%m-%d") */
140
2
    {
141
2
        SEXP date_fmt;
142
2
        Rf_protect(date_fmt = Rf_mkString("%Y-%m-%d"));
143
2
        Rf_protect(calls[N_FORMATS] = Rf_lang3(sym_as_Date, x_str, date_fmt));
144
2
        SET_TAG(CDDR(calls[N_FORMATS]), sym_format);
145
2
    }
146
147
    /* as.POSIXct(x, tz="UTC") */
148
2
    Rf_protect(calls[N_FORMATS + 1] = Rf_lang3(sym_as_POSIXct, x_str, tz_utc));
149
2
    SET_TAG(CDDR(calls[N_FORMATS + 1]), sym_tz);
150
151
    /* as.POSIXlt(x, tz="UTC") */
152
2
    Rf_protect(calls[N_FORMATS + 2] = Rf_lang3(sym_as_POSIXlt, x_str, tz_utc));
153
2
    SET_TAG(CDDR(calls[N_FORMATS + 2]), sym_tz);
154
155
    /* The fuzzed-format slots.  strptime(x, fmt, tz="UTC") is shared by
156
     * several of them as the inner call. */
157
2
    SEXP strptime_fmt;
158
2
    Rf_protect(strptime_fmt = Rf_lang4(sym_strptime, x_str, fmt_str, tz_utc));
159
2
    SET_TAG(CDDR(strptime_fmt), sym_format);
160
2
    SET_TAG(CDR(CDDR(strptime_fmt)), sym_tz);
161
162
2
    int k = N_FIXED_CALLS;
163
164
    /* [9] strptime(x, fmt, tz="UTC") */
165
2
    calls[k++] = strptime_fmt;
166
167
    /* [10] format(strptime(x, fmt, tz="UTC"), format=fmt, usetz=TRUE)
168
     * -- do_formatPOSIXlt with a fuzzed strftime format */
169
2
    Rf_protect(calls[k] = Rf_lang4(sym_format, strptime_fmt, fmt_str, true_val));
170
2
    SET_TAG(CDDR(calls[k]), sym_format);
171
2
    SET_TAG(CDR(CDDR(calls[k])), Rf_install("usetz"));
172
2
    k++;
173
174
    /* [11] as.POSIXlt(as.Date(x, format=fmt)) -- do_D2POSIXlt */
175
2
    {
176
2
        SEXP as_date;
177
2
        Rf_protect(as_date = Rf_lang3(sym_as_Date, x_str, fmt_str));
178
2
        SET_TAG(CDDR(as_date), sym_format);
179
2
        Rf_protect(calls[k] = Rf_lang2(sym_as_POSIXlt, as_date));
180
2
        k++;
181
2
    }
182
183
    /* [12] format(as.POSIXct(x, format=fmt, tz="UTC"), format=fmt) */
184
2
    {
185
2
        SEXP as_ct;
186
2
        Rf_protect(as_ct = Rf_lang4(sym_as_POSIXct, x_str, fmt_str, tz_utc));
187
2
        SET_TAG(CDDR(as_ct), sym_format);
188
2
        SET_TAG(CDR(CDDR(as_ct)), sym_tz);
189
2
        Rf_protect(calls[k] = Rf_lang3(sym_format, as_ct, fmt_str));
190
2
        SET_TAG(CDDR(calls[k]), sym_format);
191
2
        k++;
192
2
    }
193
194
    /* [13], [14] Perturb the parsed fields by amounts taken from the
195
     * input bytes, then balance, convert and format the result.  A
196
     * strptime result carries a "balanced" attribute that short-circuits
197
     * balancePOSIXlt, so dropping it is what reaches the normalisation
198
     * code in balancePOSIXlt, mktime0 and localtime0; the second slot
199
     * uses a DST-observing zone so the local-time paths run. */
200
2
    {
201
2
        static const char *const source =
202
2
            "function(x, fmt, tz) {\n"
203
2
            "    lt <- unclass(strptime(x, fmt, tz = tz))\n"
204
2
            "    attr(lt, \"balanced\") <- NULL\n"
205
2
            "    b <- as.integer(charToRaw(x))\n"
206
2
            "    fields <- c(\"sec\", \"min\", \"hour\", \"mday\", \"mon\", \"year\")\n"
207
2
            "    for (i in seq_len(min(length(b), length(fields))))\n"
208
2
            "        lt[[fields[i]]] <- lt[[fields[i]]] + (b[i] - 128L) * 7L\n"
209
2
            "    class(lt) <- c(\"POSIXlt\", \"POSIXt\")\n"
210
2
            "    bal <- balancePOSIXlt(lt)\n"
211
2
            "    ct <- as.POSIXct(lt)\n"
212
2
            "    invisible(list(as.POSIXlt(ct, tz = tz), as.Date(lt),\n"
213
2
            "                   format(bal, fmt, usetz = TRUE), format(ct)))\n"
214
2
            "}";
215
2
        SEXP wrapper;
216
2
        Rf_protect(wrapper = fuzz_make_wrapper(source));
217
2
        Rf_protect(calls[k] = Rf_lang4(wrapper, x_str, fmt_str, tz_utc));
218
2
        k++;
219
2
        Rf_protect(calls[k] = Rf_lang4(wrapper, x_str, fmt_str, tz_london));
220
2
        k++;
221
2
    }
222
223
    /* [15], [16] The same strptime and format calls, run under a UTF-8
224
     * LC_CTYPE (see set_ctype). */
225
2
    calls[k++] = calls[N_FIXED_CALLS];
226
2
    calls[k++] = calls[N_FIXED_CALLS + 1];
227
228
2
    if (k != N_CALLS)
229
0
        abort();
230
2
    fuzz_label_calls(calls, N_CALLS);
231
232
2
    const char *utf8_locale = find_utf8_locale();
233
2
    if (utf8_locale != NULL)
234
2
        call_ctype_utf8 = make_setlocale_call(utf8_locale);
235
2
    call_ctype_c = make_setlocale_call("C");
236
237
    /* Warmup: prime datetime internals, each slot in its own locale. */
238
2
    {
239
2
        int error = 0;
240
2
        SET_STRING_ELT(x_str, 0, Rf_mkChar("2024-01-15 12:30:00"));
241
2
        SET_STRING_ELT(fmt_str, 0, Rf_mkChar(DEFAULT_FORMAT));
242
36
        for (int i = 0; i < N_CALLS; i++) {
243
34
            set_ctype(i >= FIRST_UTF8_CALL);
244
34
            R_tryEval(calls[i], R_GlobalEnv, &error);
245
34
            error = 0;
246
34
        }
247
2
    }
248
249
2
    return 0;
250
2
}
251
252
int fuzz_target_run(const uint8_t *data, size_t size)
253
6.95k
{
254
6.95k
    if (size < 2 || size > FUZZ_MAX_INPUT || memchr(data + 1, '\0', size - 1))
255
14
        return 0;
256
257
6.94k
    int selected = data[0] % N_CALLS;
258
6.94k
    const uint8_t *payload = data + 1;
259
6.94k
    size_t payload_size = size - 1;
260
261
6.94k
    char buf[FUZZ_MAX_INPUT + 1];
262
6.94k
    const char *fmt = DEFAULT_FORMAT;
263
6.94k
    const char *value = buf;
264
265
6.94k
    if (selected < N_FIXED_CALLS) {
266
695
        memcpy(buf, payload, payload_size);
267
695
        buf[payload_size] = '\0';
268
6.24k
    } else {
269
        /* "<format>\n<datetime>"; the NUL replacing the newline splits
270
         * the one buffer into both strings. */
271
6.24k
        memcpy(buf, payload, payload_size);
272
6.24k
        buf[payload_size] = '\0';
273
6.24k
        char *nl = memchr(buf, '\n', payload_size);
274
6.24k
        if (nl != NULL) {
275
5.46k
            *nl = '\0';
276
5.46k
            fmt = buf;
277
5.46k
            value = nl + 1;
278
5.46k
        }
279
6.24k
    }
280
281
6.94k
    if (!fuzz_set_string(x_str, value))
282
0
        return 0;
283
6.94k
    if (!fuzz_set_string(fmt_str, fmt))
284
0
        return 0;
285
286
6.94k
    set_ctype(selected >= FIRST_UTF8_CALL);
287
288
6.94k
    fuzz_eval_data_t ed = { .call = calls[selected], .env = R_GlobalEnv };
289
6.94k
    R_ToplevelExec(fuzz_do_eval, &ed);
290
291
6.94k
    return 0;
292
6.94k
}