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