Debian Codegraph @

src/libsystemd/sd-bus/fuzz-bus-match.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-bus.h"
4
5 #include "alloc-util.h"
6 #include "bus-internal.h"
7 #include "bus-match.h"
8 #include "env-util.h"
9 #include "fuzz.h"
10 #include "memstream-util.h"
11
12 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
13 _cleanup_(memstream_done) MemStream m = {};
14 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
15 FILE *g = NULL;
16 int r;
17
18 if (outside_size_range(size, 0, 65536))
19 return 0;
20
21 fuzz_setup_logging();
22
23 r = sd_bus_new(&bus);
24 assert_se(r >= 0);
25
26 _cleanup_(bus_match_free) BusMatchNode root = {
27 .type = BUS_MATCH_ROOT,
28 };
29
30 /* Note that we use the pointer to match_callback substructure, but the code
31 * uses container_of() to access outside of the passed-in type. */
32 sd_bus_slot slot = {
33 .type = BUS_MATCH_CALLBACK,
34 .match_callback = {},
35 };
36
37 if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0)
38 assert_se(g = memstream_init(&m));
39
40 for (size_t offset = 0; offset < size; ) {
41 _cleanup_free_ char *line = NULL;
42 char *end;
43
44 end = memchr((char*) data + offset, '\n', size - offset);
45
46 line = memdup_suffix0((char*) data + offset,
47 end ? end - (char*) data - offset : size - offset);
48 if (!line)
49 return log_oom_debug();
50
51 offset = end ? (size_t) (end - (char*) data + 1) : size;
52
53 BusMatchComponent *components;
54 size_t n_components;
55 r = bus_match_parse(line, &components, &n_components);
56 if (IN_SET(r, -EINVAL, -ENOMEM)) {
57 log_debug_errno(r, "Failed to parse line: %m");
58 continue;
59 }
60 assert_se(r >= 0); /* We only expect EINVAL and ENOMEM errors, or success. */
61
62 CLEANUP_ARRAY(components, n_components, bus_match_parse_free);
63
64 log_debug("Parsed %zu components.", n_components);
65
66 _cleanup_free_ char *again = bus_match_to_string(components, n_components);
67 if (!again) {
68 log_oom();
69 break;
70 }
71
72 if (g)
73 fprintf(g, "%s\n", again);
74
75 r = bus_match_add(&root, components, n_components, &slot.match_callback);
76 if (r < 0) {
77 log_error_errno(r, "Failed to add match: %m");
78 break;
79 }
80 }
81
82 bus_match_dump(g ?: stdout, &root, 0); /* We do this even on failure, to check consistency after error. */
83 bus_match_free(&root);
84
85 return 0;
86 }