xref: /qemu/tests/qtest/fuzz/fuzz.c (revision 138ca49a)
1 /*
2  * fuzzing driver
3  *
4  * Copyright Red Hat Inc., 2019
5  *
6  * Authors:
7  *  Alexander Bulekov   <alxndr@bu.edu>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 
16 #include <wordexp.h>
17 
18 #include "qemu/datadir.h"
19 #include "sysemu/qtest.h"
20 #include "sysemu/runstate.h"
21 #include "sysemu/sysemu.h"
22 #include "qemu/main-loop.h"
23 #include "qemu/rcu.h"
24 #include "tests/qtest/libqos/libqtest.h"
25 #include "tests/qtest/libqos/qgraph.h"
26 #include "fuzz.h"
27 
28 #define MAX_EVENT_LOOPS 10
29 
30 typedef struct FuzzTargetState {
31         FuzzTarget *target;
32         QSLIST_ENTRY(FuzzTargetState) target_list;
33 } FuzzTargetState;
34 
35 typedef QSLIST_HEAD(, FuzzTargetState) FuzzTargetList;
36 
37 static const char *fuzz_arch = TARGET_NAME;
38 
39 static FuzzTargetList *fuzz_target_list;
40 static FuzzTarget *fuzz_target;
41 static QTestState *fuzz_qts;
42 
43 
44 
45 void flush_events(QTestState *s)
46 {
47     int i = MAX_EVENT_LOOPS;
48     while (g_main_context_pending(NULL) && i-- > 0) {
49         main_loop_wait(false);
50     }
51 }
52 
53 static QTestState *qtest_setup(void)
54 {
55     qtest_server_set_send_handler(&qtest_client_inproc_recv, &fuzz_qts);
56     return qtest_inproc_init(&fuzz_qts, false, fuzz_arch,
57             &qtest_server_inproc_recv);
58 }
59 
60 void fuzz_add_target(const FuzzTarget *target)
61 {
62     FuzzTargetState *tmp;
63     FuzzTargetState *target_state;
64     if (!fuzz_target_list) {
65         fuzz_target_list = g_new0(FuzzTargetList, 1);
66     }
67 
68     QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
69         if (g_strcmp0(tmp->target->name, target->name) == 0) {
70             fprintf(stderr, "Error: Fuzz target name %s already in use\n",
71                     target->name);
72             abort();
73         }
74     }
75     target_state = g_new0(FuzzTargetState, 1);
76     target_state->target = g_new0(FuzzTarget, 1);
77     *(target_state->target) = *target;
78     QSLIST_INSERT_HEAD(fuzz_target_list, target_state, target_list);
79 }
80 
81 
82 
83 static void usage(char *path)
84 {
85     printf("Usage: %s --fuzz-target=FUZZ_TARGET [LIBFUZZER ARGUMENTS]\n", path);
86     printf("where FUZZ_TARGET is one of:\n");
87     FuzzTargetState *tmp;
88     if (!fuzz_target_list) {
89         fprintf(stderr, "Fuzz target list not initialized\n");
90         abort();
91     }
92     QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
93         printf(" * %s  : %s\n", tmp->target->name,
94                 tmp->target->description);
95     }
96     printf("Alternatively, add -target-FUZZ_TARGET to the executable name\n\n"
97            "Set the environment variable FUZZ_SERIALIZE_QTEST=1 to serialize\n"
98            "QTest commands into an ASCII protocol. Useful for building crash\n"
99            "reproducers, but slows down execution.\n\n"
100            "Set the environment variable QTEST_LOG=1 to log all qtest commands"
101            "\n");
102     exit(0);
103 }
104 
105 static FuzzTarget *fuzz_get_target(char* name)
106 {
107     FuzzTargetState *tmp;
108     if (!fuzz_target_list) {
109         fprintf(stderr, "Fuzz target list not initialized\n");
110         abort();
111     }
112 
113     QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
114         if (strcmp(tmp->target->name, name) == 0) {
115             return tmp->target;
116         }
117     }
118     return NULL;
119 }
120 
121 
122 /* Sometimes called by libfuzzer to mutate two inputs into one */
123 size_t LLVMFuzzerCustomCrossOver(const uint8_t *data1, size_t size1,
124                                  const uint8_t *data2, size_t size2,
125                                  uint8_t *out, size_t max_out_size,
126                                  unsigned int seed)
127 {
128     if (fuzz_target->crossover) {
129         return fuzz_target->crossover(data1, size1, data2, size2, out,
130                                       max_out_size, seed);
131     }
132     return 0;
133 }
134 
135 /* Executed for each fuzzing-input */
136 int LLVMFuzzerTestOneInput(const unsigned char *Data, size_t Size)
137 {
138     /*
139      * Do the pre-fuzz-initialization before the first fuzzing iteration,
140      * instead of before the actual fuzz loop. This is needed since libfuzzer
141      * may fork off additional workers, prior to the fuzzing loop, and if
142      * pre_fuzz() sets up e.g. shared memory, this should be done for the
143      * individual worker processes
144      */
145     static int pre_fuzz_done;
146     if (!pre_fuzz_done && fuzz_target->pre_fuzz) {
147         fuzz_target->pre_fuzz(fuzz_qts);
148         pre_fuzz_done = true;
149     }
150 
151     fuzz_target->fuzz(fuzz_qts, Data, Size);
152     return 0;
153 }
154 
155 /* Executed once, prior to fuzzing */
156 int LLVMFuzzerInitialize(int *argc, char ***argv, char ***envp)
157 {
158 
159     char *target_name;
160     const char *bindir;
161     char *datadir;
162     bool serialize = false;
163 
164     /* Initialize qgraph and modules */
165     qos_graph_init();
166     module_call_init(MODULE_INIT_FUZZ_TARGET);
167     module_call_init(MODULE_INIT_QOM);
168     module_call_init(MODULE_INIT_LIBQOS);
169 
170     qemu_init_exec_dir(**argv);
171     target_name = strstr(**argv, "-target-");
172     if (target_name) {        /* The binary name specifies the target */
173         target_name += strlen("-target-");
174         /*
175          * With oss-fuzz, the executable is kept in the root of a directory (we
176          * cannot assume the path). All data (including bios binaries) must be
177          * in the same dir, or a subdir. Thus, we cannot place the pc-bios so
178          * that it would be in exec_dir/../pc-bios.
179          * As a workaround, oss-fuzz allows us to use argv[0] to get the
180          * location of the executable. Using this we add exec_dir/pc-bios to
181          * the datadirs.
182          */
183         bindir = qemu_get_exec_dir();
184         datadir = g_build_filename(bindir, "pc-bios", NULL);
185         if (g_file_test(datadir, G_FILE_TEST_IS_DIR)) {
186             qemu_add_data_dir(datadir);
187         } else {
188             g_free(datadir);
189 	}
190     } else if (*argc > 1) {  /* The target is specified as an argument */
191         target_name = (*argv)[1];
192         if (!strstr(target_name, "--fuzz-target=")) {
193             usage(**argv);
194         }
195         target_name += strlen("--fuzz-target=");
196     } else {
197         usage(**argv);
198     }
199 
200     /* Should we always serialize qtest commands? */
201     if (getenv("FUZZ_SERIALIZE_QTEST")) {
202         serialize = true;
203     }
204 
205     fuzz_qtest_set_serialize(serialize);
206 
207     /* Identify the fuzz target */
208     fuzz_target = fuzz_get_target(target_name);
209     if (!fuzz_target) {
210         usage(**argv);
211     }
212 
213     fuzz_qts = qtest_setup();
214 
215     if (fuzz_target->pre_vm_init) {
216         fuzz_target->pre_vm_init();
217     }
218 
219     /* Run QEMU's softmmu main with the fuzz-target dependent arguments */
220     GString *cmd_line = fuzz_target->get_init_cmdline(fuzz_target);
221     g_string_append_printf(cmd_line, " %s -qtest /dev/null ",
222                            getenv("QTEST_LOG") ? "" : "-qtest-log none");
223 
224     /* Split the runcmd into an argv and argc */
225     wordexp_t result;
226     wordexp(cmd_line->str, &result, 0);
227     g_string_free(cmd_line, true);
228 
229     qemu_init(result.we_wordc, result.we_wordv, NULL);
230 
231     /* re-enable the rcu atfork, which was previously disabled in qemu_init */
232     rcu_enable_atfork();
233 
234     /*
235      * Disable QEMU's signal handlers, since we manually control the main_loop,
236      * and don't check for main_loop_should_exit
237      */
238     signal(SIGINT, SIG_DFL);
239     signal(SIGHUP, SIG_DFL);
240     signal(SIGTERM, SIG_DFL);
241 
242     return 0;
243 }
244