Coverage Report

Created: 2026-11-20 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Modules/_xxtestfuzz/fuzzer.c
Line
Count
Source
1
/* A fuzz test for CPython.
2
3
  The only exposed function is LLVMFuzzerTestOneInput, which is called by
4
  fuzzers and by the _fuzz module for smoke tests.
5
6
  To build exactly one fuzz test, as when running in oss-fuzz etc.,
7
  build with -D _Py_FUZZ_ONE and -D _Py_FUZZ_<test_name>. e.g. to build
8
  LLVMFuzzerTestOneInput to only run "fuzz_builtin_float", build this file with
9
      -D _Py_FUZZ_ONE -D _Py_FUZZ_fuzz_builtin_float.
10
11
  See the source code for LLVMFuzzerTestOneInput for details. */
12
13
#ifndef Py_BUILD_CORE_MODULE
14
#  define Py_BUILD_CORE_MODULE 1
15
#endif
16
17
#include <Python.h>
18
#include <stdlib.h>
19
#include <inttypes.h>
20
21
/*  Fuzz PyFloat_FromString as a proxy for float(str). */
22
4.01k
static int fuzz_builtin_float(const char* data, size_t size) {
23
4.01k
    PyObject* s = PyBytes_FromStringAndSize(data, size);
24
4.01k
    if (s == NULL) return 0;
25
4.01k
    PyObject* f = PyFloat_FromString(s);
26
4.01k
    if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ValueError)) {
27
2.08k
        PyErr_Clear();
28
2.08k
    }
29
30
4.01k
    Py_XDECREF(f);
31
4.01k
    Py_DECREF(s);
32
4.01k
    return 0;
33
4.01k
}
34
35
3.50k
#define MAX_INT_TEST_SIZE 0x10000
36
37
/* Fuzz PyLong_FromUnicodeObject as a proxy for int(str). */
38
3.50k
static int fuzz_builtin_int(const char* data, size_t size) {
39
    /* Ignore test cases with very long ints to avoid timeouts
40
       int("9" * 1000000) is not a very interesting test caase */
41
3.50k
    if (size < 1 || size > MAX_INT_TEST_SIZE) {
42
5
        return 0;
43
5
    }
44
    // Use the first byte to pick a base
45
3.49k
    int base = ((unsigned char) data[0]) % 37;
46
3.49k
    if (base == 1) {
47
        // 1 is the only number between 0 and 36 that is not a valid base.
48
208
        base = 0;
49
208
    }
50
51
3.49k
    data += 1;
52
3.49k
    size -= 1;
53
54
3.49k
    PyObject* s = PyUnicode_FromStringAndSize(data, size);
55
3.49k
    if (s == NULL) {
56
702
        if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
57
702
            PyErr_Clear();
58
702
        }
59
702
        return 0;
60
702
    }
61
2.79k
    PyObject* l = PyLong_FromUnicodeObject(s, base);
62
2.79k
    if (l == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
63
2.36k
        PyErr_Clear();
64
2.36k
    }
65
2.79k
    PyErr_Clear();
66
2.79k
    Py_XDECREF(l);
67
2.79k
    Py_DECREF(s);
68
2.79k
    return 0;
69
3.49k
}
70
71
/* Fuzz PyUnicode_FromStringAndSize as a proxy for unicode(str). */
72
1.44k
static int fuzz_builtin_unicode(const char* data, size_t size) {
73
1.44k
    PyObject* s = PyUnicode_FromStringAndSize(data, size);
74
1.44k
    if (s == NULL && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
75
874
        PyErr_Clear();
76
874
    }
77
1.44k
    Py_XDECREF(s);
78
1.44k
    return 0;
79
1.44k
}
80
81
82
PyObject* struct_unpack_method = NULL;
83
PyObject* struct_error = NULL;
84
/* Called by LLVMFuzzerTestOneInput for initialization */
85
1
static int init_struct_unpack(void) {
86
    /* Import struct.unpack */
87
1
    PyObject* struct_module = PyImport_ImportModule("struct");
88
1
    if (struct_module == NULL) {
89
0
        return 0;
90
0
    }
91
1
    struct_error = PyObject_GetAttrString(struct_module, "error");
92
1
    if (struct_error == NULL) {
93
0
        return 0;
94
0
    }
95
1
    struct_unpack_method = PyObject_GetAttrString(struct_module, "unpack");
96
1
    return struct_unpack_method != NULL;
97
1
}
98
/* Fuzz struct.unpack(x, y) */
99
3.16k
static int fuzz_struct_unpack(const char* data, size_t size) {
100
    /* Everything up to the first null byte is considered the
101
       format. Everything after is the buffer */
102
3.16k
    const char* first_null = memchr(data, '\0', size);
103
3.16k
    if (first_null == NULL) {
104
9
        return 0;
105
9
    }
106
107
3.15k
    size_t format_length = first_null - data;
108
3.15k
    size_t buffer_length = size - format_length - 1;
109
110
3.15k
    PyObject* pattern = PyBytes_FromStringAndSize(data, format_length);
111
3.15k
    if (pattern == NULL) {
112
0
        return 0;
113
0
    }
114
3.15k
    PyObject* buffer = PyBytes_FromStringAndSize(first_null + 1, buffer_length);
115
3.15k
    if (buffer == NULL) {
116
0
        Py_DECREF(pattern);
117
0
        return 0;
118
0
    }
119
120
3.15k
    PyObject* unpacked = PyObject_CallFunctionObjArgs(
121
3.15k
        struct_unpack_method, pattern, buffer, NULL);
122
    /* Ignore any overflow errors, these are easily triggered accidentally */
123
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_OverflowError)) {
124
0
        PyErr_Clear();
125
0
    }
126
    /* The pascal format string will throw a negative size when passing 0
127
       like: struct.unpack('0p', b'') */
128
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_SystemError)) {
129
0
        PyErr_Clear();
130
0
    }
131
    /* Ignore any ValueError, these are triggered by non-ASCII format. */
132
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
133
172
        PyErr_Clear();
134
172
    }
135
    /* Ignore any struct.error exceptions, these can be caused by invalid
136
       formats or incomplete buffers both of which are common. */
137
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(struct_error)) {
138
747
        PyErr_Clear();
139
747
    }
140
141
3.15k
    Py_XDECREF(unpacked);
142
3.15k
    Py_DECREF(pattern);
143
3.15k
    Py_DECREF(buffer);
144
3.15k
    return 0;
145
3.15k
}
Unexecuted instantiation: fuzzer.c:fuzz_struct_unpack
fuzzer.c:fuzz_struct_unpack
Line
Count
Source
99
3.16k
static int fuzz_struct_unpack(const char* data, size_t size) {
100
    /* Everything up to the first null byte is considered the
101
       format. Everything after is the buffer */
102
3.16k
    const char* first_null = memchr(data, '\0', size);
103
3.16k
    if (first_null == NULL) {
104
9
        return 0;
105
9
    }
106
107
3.15k
    size_t format_length = first_null - data;
108
3.15k
    size_t buffer_length = size - format_length - 1;
109
110
3.15k
    PyObject* pattern = PyBytes_FromStringAndSize(data, format_length);
111
3.15k
    if (pattern == NULL) {
112
0
        return 0;
113
0
    }
114
3.15k
    PyObject* buffer = PyBytes_FromStringAndSize(first_null + 1, buffer_length);
115
3.15k
    if (buffer == NULL) {
116
0
        Py_DECREF(pattern);
117
0
        return 0;
118
0
    }
119
120
3.15k
    PyObject* unpacked = PyObject_CallFunctionObjArgs(
121
3.15k
        struct_unpack_method, pattern, buffer, NULL);
122
    /* Ignore any overflow errors, these are easily triggered accidentally */
123
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_OverflowError)) {
124
0
        PyErr_Clear();
125
0
    }
126
    /* The pascal format string will throw a negative size when passing 0
127
       like: struct.unpack('0p', b'') */
128
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_SystemError)) {
129
0
        PyErr_Clear();
130
0
    }
131
    /* Ignore any ValueError, these are triggered by non-ASCII format. */
132
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
133
172
        PyErr_Clear();
134
172
    }
135
    /* Ignore any struct.error exceptions, these can be caused by invalid
136
       formats or incomplete buffers both of which are common. */
137
3.15k
    if (unpacked == NULL && PyErr_ExceptionMatches(struct_error)) {
138
747
        PyErr_Clear();
139
747
    }
140
141
3.15k
    Py_XDECREF(unpacked);
142
3.15k
    Py_DECREF(pattern);
143
3.15k
    Py_DECREF(buffer);
144
3.15k
    return 0;
145
3.15k
}
146
147
148
8.44k
#define MAX_JSON_TEST_SIZE 0x100000
149
150
PyObject* json_loads_method = NULL;
151
/* Called by LLVMFuzzerTestOneInput for initialization */
152
1
static int init_json_loads(void) {
153
    /* Import json.loads */
154
1
    PyObject* json_module = PyImport_ImportModule("json");
155
1
    if (json_module == NULL) {
156
0
        return 0;
157
0
    }
158
1
    json_loads_method = PyObject_GetAttrString(json_module, "loads");
159
1
    return json_loads_method != NULL;
160
1
}
161
/* Fuzz json.loads(x) */
162
8.44k
static int fuzz_json_loads(const char* data, size_t size) {
163
    /* Since python supports arbitrarily large ints in JSON,
164
       long inputs can lead to timeouts on boring inputs like
165
       `json.loads("9" * 100000)` */
166
8.44k
    if (size > MAX_JSON_TEST_SIZE) {
167
0
        return 0;
168
0
    }
169
8.44k
    PyObject* input_bytes = PyBytes_FromStringAndSize(data, size);
170
8.44k
    if (input_bytes == NULL) {
171
0
        return 0;
172
0
    }
173
8.44k
    PyObject* parsed = PyObject_CallOneArg(json_loads_method, input_bytes);
174
8.44k
    if (parsed == NULL) {
175
        /* Ignore ValueError as the fuzzer will more than likely
176
           generate some invalid json and values */
177
7.23k
        if (PyErr_ExceptionMatches(PyExc_ValueError) ||
178
        /* Ignore RecursionError as the fuzzer generates long sequences of
179
           arrays such as `[[[...` */
180
127
            PyErr_ExceptionMatches(PyExc_RecursionError) ||
181
        /* Ignore unicode errors, invalid byte sequences are common */
182
0
            PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)
183
7.23k
        ) {
184
7.23k
            PyErr_Clear();
185
7.23k
        }
186
7.23k
    }
187
8.44k
    Py_DECREF(input_bytes);
188
8.44k
    Py_XDECREF(parsed);
189
8.44k
    return 0;
190
8.44k
}
Unexecuted instantiation: fuzzer.c:fuzz_json_loads
fuzzer.c:fuzz_json_loads
Line
Count
Source
162
8.44k
static int fuzz_json_loads(const char* data, size_t size) {
163
    /* Since python supports arbitrarily large ints in JSON,
164
       long inputs can lead to timeouts on boring inputs like
165
       `json.loads("9" * 100000)` */
166
8.44k
    if (size > MAX_JSON_TEST_SIZE) {
167
0
        return 0;
168
0
    }
169
8.44k
    PyObject* input_bytes = PyBytes_FromStringAndSize(data, size);
170
8.44k
    if (input_bytes == NULL) {
171
0
        return 0;
172
0
    }
173
8.44k
    PyObject* parsed = PyObject_CallOneArg(json_loads_method, input_bytes);
174
8.44k
    if (parsed == NULL) {
175
        /* Ignore ValueError as the fuzzer will more than likely
176
           generate some invalid json and values */
177
7.23k
        if (PyErr_ExceptionMatches(PyExc_ValueError) ||
178
        /* Ignore RecursionError as the fuzzer generates long sequences of
179
           arrays such as `[[[...` */
180
127
            PyErr_ExceptionMatches(PyExc_RecursionError) ||
181
        /* Ignore unicode errors, invalid byte sequences are common */
182
0
            PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)
183
7.23k
        ) {
184
7.23k
            PyErr_Clear();
185
7.23k
        }
186
7.23k
    }
187
8.44k
    Py_DECREF(input_bytes);
188
8.44k
    Py_XDECREF(parsed);
189
8.44k
    return 0;
190
8.44k
}
191
192
5.81k
#define MAX_RE_TEST_SIZE 0x10000
193
194
PyObject* re_compile_method = NULL;
195
PyObject* re_error_exception = NULL;
196
int RE_FLAG_DEBUG = 0;
197
/* Called by LLVMFuzzerTestOneInput for initialization */
198
1
static int init_sre_compile(void) {
199
    /* Import sre_compile.compile and sre.error */
200
1
    PyObject* re_module = PyImport_ImportModule("re");
201
1
    if (re_module == NULL) {
202
0
        return 0;
203
0
    }
204
1
    re_compile_method = PyObject_GetAttrString(re_module, "compile");
205
1
    if (re_compile_method == NULL) {
206
0
        return 0;
207
0
    }
208
209
1
    re_error_exception = PyObject_GetAttrString(re_module, "error");
210
1
    if (re_error_exception == NULL) {
211
0
        return 0;
212
0
    }
213
1
    PyObject* debug_flag = PyObject_GetAttrString(re_module, "DEBUG");
214
1
    if (debug_flag == NULL) {
215
0
        return 0;
216
0
    }
217
1
    RE_FLAG_DEBUG = PyLong_AsLong(debug_flag);
218
1
    return 1;
219
1
}
220
/* Fuzz re.compile(x) */
221
5.37k
static int fuzz_sre_compile(const char* data, size_t size) {
222
    /* Ignore really long regex patterns that will timeout the fuzzer */
223
5.37k
    if (size > MAX_RE_TEST_SIZE) {
224
1
        return 0;
225
1
    }
226
    /* We treat the first 2 bytes of the input as a number for the flags */
227
5.37k
    if (size < 2) {
228
2
        return 0;
229
2
    }
230
5.37k
    uint16_t flags = ((uint16_t*) data)[0];
231
    /* We remove the SRE_FLAG_DEBUG if present. This is because it
232
       prints to stdout which greatly decreases fuzzing speed */
233
5.37k
    flags &= ~RE_FLAG_DEBUG;
234
235
    /* Pull the pattern from the remaining bytes */
236
5.37k
    PyObject* pattern_bytes = PyBytes_FromStringAndSize(data + 2, size - 2);
237
5.37k
    if (pattern_bytes == NULL) {
238
0
        return 0;
239
0
    }
240
5.37k
    PyObject* flags_obj = PyLong_FromUnsignedLong(flags);
241
5.37k
    if (flags_obj == NULL) {
242
0
        Py_DECREF(pattern_bytes);
243
0
        return 0;
244
0
    }
245
246
    /* compiled = re.compile(data[2:], data[0:2] */
247
5.37k
    PyObject* compiled = PyObject_CallFunctionObjArgs(
248
5.37k
        re_compile_method, pattern_bytes, flags_obj, NULL);
249
    /* Ignore ValueError as the fuzzer will more than likely
250
       generate some invalid combination of flags */
251
5.37k
    if (compiled == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
252
199
        PyErr_Clear();
253
199
    }
254
    /* Ignore some common errors thrown by sre_parse:
255
       Overflow, Assertion, Recursion and Index */
256
5.37k
    if (compiled == NULL && (PyErr_ExceptionMatches(PyExc_OverflowError) ||
257
2.61k
                             PyErr_ExceptionMatches(PyExc_AssertionError) ||
258
2.61k
                             PyErr_ExceptionMatches(PyExc_RecursionError) ||
259
2.52k
                             PyErr_ExceptionMatches(PyExc_IndexError))
260
5.37k
    ) {
261
197
        PyErr_Clear();
262
197
    }
263
    /* Ignore re.error */
264
5.37k
    if (compiled == NULL && PyErr_ExceptionMatches(re_error_exception)) {
265
2.32k
        PyErr_Clear();
266
2.32k
    }
267
268
5.37k
    Py_DECREF(pattern_bytes);
269
5.37k
    Py_DECREF(flags_obj);
270
5.37k
    Py_XDECREF(compiled);
271
5.37k
    return 0;
272
5.37k
}
273
274
/* Some random patterns used to test re.match.
275
   Be careful not to add catostraphically slow regexes here, we want to
276
   exercise the matching code without causing timeouts.*/
277
static const char* regex_patterns[] = {
278
    ".", "^", "abc", "abc|def", "^xxx$", "\\b", "()", "[a-zA-Z0-9]",
279
    "abc+", "[^A-Z]", "[x]", "(?=)", "a{z}", "a+b", "a*?", "a??", "a+?",
280
    "{}", "a{,}", "{", "}", "^\\(*\\d{3}\\)*( |-)*\\d{3}( |-)*\\d{4}$",
281
    "(?:a*)*", "a{1,2}?"
282
};
283
const size_t NUM_PATTERNS = sizeof(regex_patterns) / sizeof(regex_patterns[0]);
284
PyObject** compiled_patterns = NULL;
285
/* Called by LLVMFuzzerTestOneInput for initialization */
286
0
static int init_sre_match(void) {
287
0
    PyObject* re_module = PyImport_ImportModule("re");
288
0
    if (re_module == NULL) {
289
0
        return 0;
290
0
    }
291
0
    compiled_patterns = (PyObject**) PyMem_RawMalloc(
292
0
        sizeof(PyObject*) * NUM_PATTERNS);
293
0
    if (compiled_patterns == NULL) {
294
0
        PyErr_NoMemory();
295
0
        return 0;
296
0
    }
297
0
298
0
    /* Precompile all the regex patterns on the first run for faster fuzzing */
299
0
    for (size_t i = 0; i < NUM_PATTERNS; i++) {
300
0
        PyObject* compiled = PyObject_CallMethod(
301
0
            re_module, "compile", "y", regex_patterns[i]);
302
0
        /* Bail if any of the patterns fail to compile */
303
0
        if (compiled == NULL) {
304
0
            return 0;
305
0
        }
306
0
        compiled_patterns[i] = compiled;
307
0
    }
308
0
    return 1;
309
0
}
310
/* Fuzz re.match(x) */
311
437
static int fuzz_sre_match(const char* data, size_t size) {
312
437
    if (size < 1 || size > MAX_RE_TEST_SIZE) {
313
5
        return 0;
314
5
    }
315
    /* Use the first byte as a uint8_t specifying the index of the
316
       regex to use */
317
432
    unsigned char idx = (unsigned char) data[0];
318
432
    idx = idx % NUM_PATTERNS;
319
320
    /* Pull the string to match from the remaining bytes */
321
432
    PyObject* to_match = PyBytes_FromStringAndSize(data + 1, size - 1);
322
432
    if (to_match == NULL) {
323
0
        return 0;
324
0
    }
325
326
432
    PyObject* pattern = compiled_patterns[idx];
327
432
    PyObject* match_callable = PyObject_GetAttrString(pattern, "match");
328
432
    if (match_callable == NULL) {
329
0
        Py_DECREF(to_match);
330
0
        return 0;
331
0
    }
332
333
432
    PyObject* matches = PyObject_CallOneArg(match_callable, to_match);
334
335
432
    Py_XDECREF(matches);
336
432
    Py_DECREF(match_callable);
337
432
    Py_DECREF(to_match);
338
432
    return 0;
339
432
}
340
341
2.34k
#define MAX_CSV_TEST_SIZE 0x100000
342
PyObject* csv_module = NULL;
343
PyObject* csv_error = NULL;
344
/* Called by LLVMFuzzerTestOneInput for initialization */
345
1
static int init_csv_reader(void) {
346
    /* Import csv and csv.Error */
347
1
    csv_module = PyImport_ImportModule("csv");
348
1
    if (csv_module == NULL) {
349
0
        return 0;
350
0
    }
351
1
    csv_error = PyObject_GetAttrString(csv_module, "Error");
352
1
    return csv_error != NULL;
353
1
}
354
/* Fuzz csv.reader([x]) */
355
2.34k
static int fuzz_csv_reader(const char* data, size_t size) {
356
2.34k
    if (size < 1 || size > MAX_CSV_TEST_SIZE) {
357
0
        return 0;
358
0
    }
359
    /* Ignore non null-terminated strings since _csv can't handle
360
       embedded nulls */
361
2.34k
    if (memchr(data, '\0', size) == NULL) {
362
4
        return 0;
363
4
    }
364
365
2.34k
    PyObject* s = PyUnicode_FromString(data);
366
    /* Ignore exceptions until we have a valid string */
367
2.34k
    if (s == NULL) {
368
472
        PyErr_Clear();
369
472
        return 0;
370
472
    }
371
372
    /* Split on \n so we can test multiple lines */
373
1.87k
    PyObject* lines = PyObject_CallMethod(s, "split", "s", "\n");
374
1.87k
    if (lines == NULL) {
375
0
        Py_DECREF(s);
376
0
        return 0;
377
0
    }
378
379
1.87k
    PyObject* reader = PyObject_CallMethod(csv_module, "reader", "N", lines);
380
1.87k
    if (reader) {
381
        /* Consume all of the reader as an iterator */
382
1.87k
        PyObject* parsed_line;
383
28.7M
        while ((parsed_line = PyIter_Next(reader))) {
384
28.7M
            Py_DECREF(parsed_line);
385
28.7M
        }
386
1.87k
    }
387
388
    /* Ignore csv.Error because we're probably going to generate
389
       some bad files (embedded new-lines, unterminated quotes etc) */
390
1.87k
    if (PyErr_ExceptionMatches(csv_error)) {
391
201
        PyErr_Clear();
392
201
    }
393
394
1.87k
    Py_XDECREF(reader);
395
1.87k
    Py_DECREF(s);
396
1.87k
    return 0;
397
1.87k
}
398
399
37
#define MAX_AST_LITERAL_EVAL_TEST_SIZE 0x100000
400
PyObject* ast_literal_eval_method = NULL;
401
/* Called by LLVMFuzzerTestOneInput for initialization */
402
1
static int init_ast_literal_eval(void) {
403
1
    PyObject* ast_module = PyImport_ImportModule("ast");
404
1
    if (ast_module == NULL) {
405
0
        return 0;
406
0
    }
407
1
    ast_literal_eval_method = PyObject_GetAttrString(ast_module, "literal_eval");
408
1
    return ast_literal_eval_method != NULL;
409
1
}
410
/* Fuzz ast.literal_eval(x) */
411
37
static int fuzz_ast_literal_eval(const char* data, size_t size) {
412
37
    if (size > MAX_AST_LITERAL_EVAL_TEST_SIZE) {
413
0
        return 0;
414
0
    }
415
    /* Ignore non null-terminated strings since ast can't handle
416
       embedded nulls */
417
37
    if (memchr(data, '\0', size) == NULL) {
418
0
        return 0;
419
0
    }
420
421
37
    PyObject* s = PyUnicode_FromString(data);
422
    /* Ignore exceptions until we have a valid string */
423
37
    if (s == NULL) {
424
4
        PyErr_Clear();
425
4
        return 0;
426
4
    }
427
428
33
    PyObject* literal = PyObject_CallOneArg(ast_literal_eval_method, s);
429
    /* Ignore some common errors thrown by ast.literal_eval */
430
33
    if (literal == NULL && (PyErr_ExceptionMatches(PyExc_ValueError) ||
431
24
                            PyErr_ExceptionMatches(PyExc_TypeError) ||
432
24
                            PyErr_ExceptionMatches(PyExc_SyntaxError) ||
433
0
                            PyErr_ExceptionMatches(PyExc_MemoryError) ||
434
0
                            PyErr_ExceptionMatches(PyExc_OverflowError) ||
435
0
                            PyErr_ExceptionMatches(PyExc_RecursionError))
436
33
    ) {
437
32
        PyErr_Clear();
438
32
    }
439
440
33
    Py_XDECREF(literal);
441
33
    Py_DECREF(s);
442
33
    return 0;
443
37
}
444
445
16.8k
#define MAX_ELEMENTTREE_PARSEWHOLE_TEST_SIZE 0x100000
446
PyObject* xmlparser_type = NULL;
447
PyObject* bytesio_type = NULL;
448
/* Called by LLVMFuzzerTestOneInput for initialization */
449
1
static int init_elementtree_parsewhole(void) {
450
1
    PyObject* elementtree_module = PyImport_ImportModule("_elementtree");
451
1
    if (elementtree_module == NULL) {
452
0
        return 0;
453
0
    }
454
1
    xmlparser_type = PyObject_GetAttrString(elementtree_module, "XMLParser");
455
1
    Py_DECREF(elementtree_module);
456
1
    if (xmlparser_type == NULL) {
457
0
        return 0;
458
0
    }
459
460
461
1
    PyObject* io_module = PyImport_ImportModule("io");
462
1
    if (io_module == NULL) {
463
0
        return 0;
464
0
    }
465
1
    bytesio_type = PyObject_GetAttrString(io_module, "BytesIO");
466
1
    Py_DECREF(io_module);
467
1
    if (bytesio_type == NULL) {
468
0
        return 0;
469
0
    }
470
471
1
    return 1;
472
1
}
473
/* Fuzz _elementtree.XMLParser._parse_whole(x) */
474
16.8k
static int fuzz_elementtree_parsewhole(const char* data, size_t size) {
475
16.8k
    if (size > MAX_ELEMENTTREE_PARSEWHOLE_TEST_SIZE) {
476
0
        return 0;
477
0
    }
478
479
16.8k
    PyObject *input = PyObject_CallFunction(bytesio_type, "y#", data, (Py_ssize_t)size);
480
16.8k
    if (input == NULL) {
481
0
        assert(PyErr_Occurred());
482
0
        PyErr_Print();
483
0
        abort();
484
0
    }
485
486
16.8k
    PyObject *xmlparser_instance = PyObject_CallObject(xmlparser_type, NULL);
487
16.8k
    if (xmlparser_instance == NULL) {
488
0
        assert(PyErr_Occurred());
489
0
        PyErr_Print();
490
0
        abort();
491
0
    }
492
493
16.8k
    PyObject *result = PyObject_CallMethod(xmlparser_instance, "_parse_whole", "O", input);
494
16.8k
    if (result == NULL) {
495
        /* Ignore exception here, which can be caused by invalid XML input */
496
16.7k
        PyErr_Clear();
497
16.7k
    } else {
498
78
        Py_DECREF(result);
499
78
    }
500
501
16.8k
    Py_DECREF(xmlparser_instance);
502
16.8k
    Py_DECREF(input);
503
504
16.8k
    return 0;
505
16.8k
}
Unexecuted instantiation: fuzzer.c:fuzz_elementtree_parsewhole
fuzzer.c:fuzz_elementtree_parsewhole
Line
Count
Source
474
16.8k
static int fuzz_elementtree_parsewhole(const char* data, size_t size) {
475
16.8k
    if (size > MAX_ELEMENTTREE_PARSEWHOLE_TEST_SIZE) {
476
0
        return 0;
477
0
    }
478
479
16.8k
    PyObject *input = PyObject_CallFunction(bytesio_type, "y#", data, (Py_ssize_t)size);
480
16.8k
    if (input == NULL) {
481
0
        assert(PyErr_Occurred());
482
0
        PyErr_Print();
483
0
        abort();
484
0
    }
485
486
16.8k
    PyObject *xmlparser_instance = PyObject_CallObject(xmlparser_type, NULL);
487
16.8k
    if (xmlparser_instance == NULL) {
488
0
        assert(PyErr_Occurred());
489
0
        PyErr_Print();
490
0
        abort();
491
0
    }
492
493
16.8k
    PyObject *result = PyObject_CallMethod(xmlparser_instance, "_parse_whole", "O", input);
494
16.8k
    if (result == NULL) {
495
        /* Ignore exception here, which can be caused by invalid XML input */
496
16.7k
        PyErr_Clear();
497
16.7k
    } else {
498
78
        Py_DECREF(result);
499
78
    }
500
501
16.8k
    Py_DECREF(xmlparser_instance);
502
16.8k
    Py_DECREF(input);
503
504
16.8k
    return 0;
505
16.8k
}
506
507
26.3k
#define MAX_PYCOMPILE_TEST_SIZE 16384
508
509
static const int start_vals[] = {Py_eval_input, Py_single_input, Py_file_input};
510
const size_t NUM_START_VALS = sizeof(start_vals) / sizeof(start_vals[0]);
511
512
static const int optimize_vals[] = {-1, 0, 1, 2};
513
const size_t NUM_OPTIMIZE_VALS = sizeof(optimize_vals) / sizeof(optimize_vals[0]);
514
515
/* Fuzz `PyCompileStringExFlags` using a variety of input parameters.
516
 * That function is essentially behind the `compile` builtin */
517
26.3k
static int fuzz_pycompile(const char* data, size_t size) {
518
    // Ignore overly-large inputs, and account for a NUL terminator
519
26.3k
    if (size > MAX_PYCOMPILE_TEST_SIZE - 1) {
520
1
        return 0;
521
1
    }
522
523
    // Need 3 bytes for parameter selection
524
26.3k
    if (size < 3) {
525
2
        return 0;
526
2
    }
527
528
    // Use first byte to determine element of `start_vals` to use
529
26.3k
    unsigned char start_idx = (unsigned char) data[0];
530
26.3k
    int start = start_vals[start_idx % NUM_START_VALS];
531
532
    // Use second byte to determine element of `optimize_vals` to use
533
26.3k
    unsigned char optimize_idx = (unsigned char) data[1];
534
26.3k
    int optimize = optimize_vals[optimize_idx % NUM_OPTIMIZE_VALS];
535
536
    // Use third byte to determine compiler flags to use.
537
26.3k
    unsigned char flags_byte = (unsigned char) data[2];
538
26.3k
    PyCompilerFlags flags = _PyCompilerFlags_INIT;
539
26.3k
    if (flags_byte & 0x01) {
540
12.3k
        flags.cf_flags |= PyCF_DONT_IMPLY_DEDENT;
541
12.3k
    }
542
26.3k
    if (flags_byte & 0x02) {
543
6.59k
        flags.cf_flags |= PyCF_ONLY_AST;
544
6.59k
    }
545
26.3k
    if (flags_byte & 0x04) {
546
11.6k
        flags.cf_flags |= PyCF_IGNORE_COOKIE;
547
11.6k
    }
548
26.3k
    if (flags_byte & 0x08) {
549
11.6k
        flags.cf_flags |= PyCF_TYPE_COMMENTS;
550
11.6k
    }
551
26.3k
    if (flags_byte & 0x10) {
552
7.66k
        flags.cf_flags |= PyCF_ALLOW_TOP_LEVEL_AWAIT;
553
7.66k
    }
554
26.3k
    if (flags_byte & 0x20) {
555
18.6k
        flags.cf_flags |= PyCF_ALLOW_INCOMPLETE_INPUT;
556
18.6k
    }
557
26.3k
    if (flags_byte & 0x40) {
558
4.96k
        flags.cf_flags |= PyCF_OPTIMIZED_AST;
559
4.96k
    }
560
561
26.3k
    char pycompile_scratch[MAX_PYCOMPILE_TEST_SIZE];
562
563
    // Create a NUL-terminated C string from the remaining input
564
26.3k
    memcpy(pycompile_scratch, data + 3, size - 3);
565
    // Put a NUL terminator just after the copied data. (Space was reserved already.)
566
26.3k
    pycompile_scratch[size - 3] = '\0';
567
568
26.3k
    PyObject *result = Py_CompileStringExFlags(pycompile_scratch, "<fuzz input>", start, &flags, optimize);
569
26.3k
    if (result == NULL) {
570
        /* Compilation failed, most likely from a syntax error. If it was a
571
           SystemError we abort. There's no non-bug reason to raise a
572
           SystemError. */
573
12.7k
        if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemError)) {
574
0
            PyErr_Print();
575
0
            abort();
576
0
        }
577
12.7k
        PyErr_Clear();
578
13.5k
    } else {
579
13.5k
        Py_DECREF(result);
580
13.5k
    }
581
582
26.3k
    return 0;
583
26.3k
}
584
585
/* Run fuzzer and abort on failure. */
586
72.0k
static int _run_fuzz(const uint8_t *data, size_t size, int(*fuzzer)(const char* , size_t)) {
587
72.0k
    int rv = fuzzer((const char*) data, size);
588
72.0k
    if (PyErr_Occurred()) {
589
        /* Fuzz tests should handle expected errors for themselves.
590
           This is last-ditch check in case they didn't. */
591
0
        PyErr_Print();
592
0
        abort();
593
0
    }
594
    /* Someday the return value might mean something, propagate it. */
595
72.0k
    return rv;
596
72.0k
}
597
598
/* CPython generates a lot of leak warnings for whatever reason. */
599
0
int __lsan_is_turned_off(void) { return 1; }
600
601
602
22
int LLVMFuzzerInitialize(int *argc, char ***argv) {
603
22
    PyConfig config;
604
22
    PyConfig_InitPythonConfig(&config);
605
22
    config.install_signal_handlers = 0;
606
    /* Raise the limit above the default allows exercising larger things
607
     * now that we fall back to the _pylong module for large values. */
608
22
    config.int_max_str_digits = 8086;
609
22
    PyStatus status;
610
22
    status = PyConfig_SetBytesString(&config, &config.program_name, *argv[0]);
611
22
    if (PyStatus_Exception(status)) {
612
0
        goto fail;
613
0
    }
614
615
22
    status = Py_InitializeFromConfig(&config);
616
22
    if (PyStatus_Exception(status)) {
617
0
        goto fail;
618
0
    }
619
22
    PyConfig_Clear(&config);
620
621
22
    return 0;
622
623
0
fail:
624
0
    PyConfig_Clear(&config);
625
0
    Py_ExitStatusException(status);
626
22
}
627
628
/* Fuzz test interface.
629
   This returns the bitwise or of all fuzz test's return values.
630
631
   All fuzz tests must return 0, as all nonzero return codes are reserved for
632
   future use -- we propagate the return values for that future case.
633
   (And we bitwise or when running multiple tests to verify that normally we
634
   only return 0.) */
635
35.3k
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
636
35.3k
    assert(Py_IsInitialized());
637
638
35.3k
    int rv = 0;
639
640
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_builtin_float)
641
    rv |= _run_fuzz(data, size, fuzz_builtin_float);
642
#endif
643
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_builtin_int)
644
    rv |= _run_fuzz(data, size, fuzz_builtin_int);
645
#endif
646
35.3k
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_builtin_unicode)
647
35.3k
    rv |= _run_fuzz(data, size, fuzz_builtin_unicode);
648
35.3k
#endif
649
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_struct_unpack)
650
    static int STRUCT_UNPACK_INITIALIZED = 0;
651
    if (!STRUCT_UNPACK_INITIALIZED && !init_struct_unpack()) {
652
        PyErr_Print();
653
        abort();
654
    } else {
655
        STRUCT_UNPACK_INITIALIZED = 1;
656
    }
657
    rv |= _run_fuzz(data, size, fuzz_struct_unpack);
658
#endif
659
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_json_loads)
660
    static int JSON_LOADS_INITIALIZED = 0;
661
    if (!JSON_LOADS_INITIALIZED && !init_json_loads()) {
662
        PyErr_Print();
663
        abort();
664
    } else {
665
        JSON_LOADS_INITIALIZED = 1;
666
    }
667
668
    rv |= _run_fuzz(data, size, fuzz_json_loads);
669
#endif
670
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_sre_compile)
671
    static int SRE_COMPILE_INITIALIZED = 0;
672
    if (!SRE_COMPILE_INITIALIZED && !init_sre_compile()) {
673
        PyErr_Print();
674
        abort();
675
    } else {
676
        SRE_COMPILE_INITIALIZED = 1;
677
    }
678
679
    if (SRE_COMPILE_INITIALIZED) {
680
        rv |= _run_fuzz(data, size, fuzz_sre_compile);
681
    }
682
#endif
683
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_sre_match)
684
    static int SRE_MATCH_INITIALIZED = 0;
685
    if (!SRE_MATCH_INITIALIZED && !init_sre_match()) {
686
        PyErr_Print();
687
        abort();
688
    } else {
689
        SRE_MATCH_INITIALIZED = 1;
690
    }
691
692
    rv |= _run_fuzz(data, size, fuzz_sre_match);
693
#endif
694
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_csv_reader)
695
    static int CSV_READER_INITIALIZED = 0;
696
    if (!CSV_READER_INITIALIZED && !init_csv_reader()) {
697
        PyErr_Print();
698
        abort();
699
    } else {
700
        CSV_READER_INITIALIZED = 1;
701
    }
702
703
    rv |= _run_fuzz(data, size, fuzz_csv_reader);
704
#endif
705
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_ast_literal_eval)
706
    static int AST_LITERAL_EVAL_INITIALIZED = 0;
707
    if (!AST_LITERAL_EVAL_INITIALIZED && !init_ast_literal_eval()) {
708
        PyErr_Print();
709
        abort();
710
    } else {
711
        AST_LITERAL_EVAL_INITIALIZED = 1;
712
    }
713
714
    rv |= _run_fuzz(data, size, fuzz_ast_literal_eval);
715
#endif
716
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_elementtree_parsewhole)
717
    static int ELEMENTTREE_PARSEWHOLE_INITIALIZED = 0;
718
    if (!ELEMENTTREE_PARSEWHOLE_INITIALIZED && !init_elementtree_parsewhole()) {
719
        PyErr_Print();
720
        abort();
721
    } else {
722
        ELEMENTTREE_PARSEWHOLE_INITIALIZED = 1;
723
    }
724
725
    rv |= _run_fuzz(data, size, fuzz_elementtree_parsewhole);
726
#endif
727
#if !defined(_Py_FUZZ_ONE) || defined(_Py_FUZZ_fuzz_pycompile)
728
    rv |= _run_fuzz(data, size, fuzz_pycompile);
729
#endif
730
35.3k
  return rv;
731
35.3k
}