Tabbing
[c11tester.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3 #include <new>
4 #include <stdarg.h>
5 #include <string.h>
6 #include <cstdlib>
7
8 #include "model.h"
9 #include "action.h"
10 #include "schedule.h"
11 #include "snapshot-interface.h"
12 #include "common.h"
13 #include "datarace.h"
14 #include "threads-model.h"
15 #include "output.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
18 #include "history.h"
19 #include "bugmessage.h"
20 #include "params.h"
21
22 ModelChecker *model = NULL;
23
24 /** Wrapper to run the user's main function, with appropriate arguments */
25 void user_main_wrapper(void *)
26 {
27         user_main(model->params.argc, model->params.argv);
28 }
29
30 /** @brief Constructor */
31 ModelChecker::ModelChecker() :
32         /* Initialize default scheduler */
33         params(),
34         restart_flag(false),
35         scheduler(new Scheduler()),
36         history(new ModelHistory()),
37         execution(new ModelExecution(this, scheduler)),
38         execution_number(1),
39         trace_analyses(),
40         inspect_plugin(NULL)
41 {
42         memset(&stats,0,sizeof(struct execution_stats));
43         init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &user_main_wrapper, NULL, NULL);
44 #ifdef TLS
45         init_thread->setTLS((char *)get_tls_addr());
46 #endif
47         execution->add_thread(init_thread);
48         scheduler->set_current_thread(init_thread);
49         execution->setParams(&params);
50         param_defaults(&params);
51         initRaceDetector();
52 }
53
54 /** @brief Destructor */
55 ModelChecker::~ModelChecker()
56 {
57         delete scheduler;
58 }
59
60 /** Method to set parameters */
61 model_params * ModelChecker::getParams() {
62         return &params;
63 }
64
65 /**
66  * Restores user program to initial state and resets all model-checker data
67  * structures.
68  */
69 void ModelChecker::reset_to_initial_state()
70 {
71
72         /**
73          * FIXME: if we utilize partial rollback, we will need to free only
74          * those pending actions which were NOT pending before the rollback
75          * point
76          */
77         for (unsigned int i = 0;i < get_num_threads();i++)
78                 delete get_thread(int_to_id(i))->get_pending();
79
80         snapshot_backtrack_before(0);
81 }
82
83 /** @return the number of user threads created during this execution */
84 unsigned int ModelChecker::get_num_threads() const
85 {
86         return execution->get_num_threads();
87 }
88
89 /**
90  * Must be called from user-thread context (e.g., through the global
91  * thread_current() interface)
92  *
93  * @return The currently executing Thread.
94  */
95 Thread * ModelChecker::get_current_thread() const
96 {
97         return scheduler->get_current_thread();
98 }
99
100 /**
101  * @brief Choose the next thread to execute.
102  *
103  * This function chooses the next thread that should execute. It can enforce
104  * execution replay/backtracking or, if the model-checker has no preference
105  * regarding the next thread (i.e., when exploring a new execution ordering),
106  * we defer to the scheduler.
107  *
108  * @return The next chosen thread to run, if any exist. Or else if the current
109  * execution should terminate, return NULL.
110  */
111 Thread * ModelChecker::get_next_thread()
112 {
113
114         /*
115          * Have we completed exploring the preselected path? Then let the
116          * scheduler decide
117          */
118         return scheduler->select_next_thread();
119 }
120
121 /**
122  * @brief Assert a bug in the executing program.
123  *
124  * Use this function to assert any sort of bug in the user program. If the
125  * current trace is feasible (actually, a prefix of some feasible execution),
126  * then this execution will be aborted, printing the appropriate message. If
127  * the current trace is not yet feasible, the error message will be stashed and
128  * printed if the execution ever becomes feasible.
129  *
130  * @param msg Descriptive message for the bug (do not include newline char)
131  * @return True if bug is immediately-feasible
132  */
133 void ModelChecker::assert_bug(const char *msg, ...)
134 {
135         char str[800];
136
137         va_list ap;
138         va_start(ap, msg);
139         vsnprintf(str, sizeof(str), msg, ap);
140         va_end(ap);
141
142         execution->assert_bug(str);
143 }
144
145 /**
146  * @brief Assert a bug in the executing program, asserted by a user thread
147  * @see ModelChecker::assert_bug
148  * @param msg Descriptive message for the bug (do not include newline char)
149  */
150 void ModelChecker::assert_user_bug(const char *msg)
151 {
152         /* If feasible bug, bail out now */
153         assert_bug(msg);
154         switch_to_master(NULL);
155 }
156
157 /** @brief Print bug report listing for this execution (if any bugs exist) */
158 void ModelChecker::print_bugs() const
159 {
160         SnapVector<bug_message *> *bugs = execution->get_bugs();
161
162         model_print("Bug report: %zu bug%s detected\n",
163                                                         bugs->size(),
164                                                         bugs->size() > 1 ? "s" : "");
165         for (unsigned int i = 0;i < bugs->size();i++)
166                 (*bugs)[i] -> print();
167 }
168
169 /**
170  * @brief Record end-of-execution stats
171  *
172  * Must be run when exiting an execution. Records various stats.
173  * @see struct execution_stats
174  */
175 void ModelChecker::record_stats()
176 {
177         stats.num_total ++;
178         if (execution->have_bug_reports())
179                 stats.num_buggy_executions ++;
180         else if (execution->is_complete_execution())
181                 stats.num_complete ++;
182         else {
183                 //All threads are sleeping
184                 /**
185                  * @todo We can violate this ASSERT() when fairness/sleep sets
186                  * conflict to cause an execution to terminate, e.g. with:
187                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
188                  */
189                 //ASSERT(scheduler->all_threads_sleeping());
190         }
191 }
192
193 /** @brief Print execution stats */
194 void ModelChecker::print_stats() const
195 {
196         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
197         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
198         model_print("Total executions: %d\n", stats.num_total);
199 }
200
201 /**
202  * @brief End-of-exeuction print
203  * @param printbugs Should any existing bugs be printed?
204  */
205 void ModelChecker::print_execution(bool printbugs) const
206 {
207         model_print("Program output from execution %d:\n",
208                                                         get_execution_number());
209         print_program_output();
210
211         if (params.verbose >= 3) {
212                 print_stats();
213         }
214
215         /* Don't print invalid bugs */
216         if (printbugs && execution->have_bug_reports()) {
217                 model_print("\n");
218                 print_bugs();
219         }
220
221         model_print("\n");
222         execution->print_summary();
223 }
224
225 /**
226  * Queries the model-checker for more executions to explore and, if one
227  * exists, resets the model-checker state to execute a new execution.
228  *
229  * @return If there are more executions to explore, return true. Otherwise,
230  * return false.
231  */
232 bool ModelChecker::next_execution()
233 {
234         DBG();
235         /* Is this execution a feasible execution that's worth bug-checking? */
236         bool complete = (execution->is_complete_execution() ||
237                                                                          execution->have_bug_reports());
238
239         /* End-of-execution bug checks */
240         if (complete) {
241                 if (execution->is_deadlocked())
242                         assert_bug("Deadlock detected");
243
244                 run_trace_analyses();
245         }
246
247         record_stats();
248         /* Output */
249         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
250                 print_execution(complete);
251         else
252                 clear_program_output();
253
254         if (restart_flag) {
255                 do_restart();
256                 return true;
257         }
258 // test code
259         execution_number ++;
260         reset_to_initial_state();
261         history->set_new_exec_flag();
262         return false;
263 }
264
265 /** @brief Run trace analyses on complete trace */
266 void ModelChecker::run_trace_analyses() {
267         for (unsigned int i = 0;i < trace_analyses.size();i ++)
268                 trace_analyses[i] -> analyze(execution->get_action_trace());
269 }
270
271 /**
272  * @brief Get a Thread reference by its ID
273  * @param tid The Thread's ID
274  * @return A Thread reference
275  */
276 Thread * ModelChecker::get_thread(thread_id_t tid) const
277 {
278         return execution->get_thread(tid);
279 }
280
281 /**
282  * @brief Get a reference to the Thread in which a ModelAction was executed
283  * @param act The ModelAction
284  * @return A Thread reference
285  */
286 Thread * ModelChecker::get_thread(const ModelAction *act) const
287 {
288         return execution->get_thread(act);
289 }
290
291 /**
292  * Switch from a model-checker context to a user-thread context. This is the
293  * complement of ModelChecker::switch_to_master and must be called from the
294  * model-checker context
295  *
296  * @param thread The user-thread to switch to
297  */
298 void ModelChecker::switch_from_master(Thread *thread)
299 {
300         scheduler->set_current_thread(thread);
301         Thread::swap(&system_context, thread);
302 }
303
304 /**
305  * Switch from a user-context to the "master thread" context (a.k.a. system
306  * context). This switch is made with the intention of exploring a particular
307  * model-checking action (described by a ModelAction object). Must be called
308  * from a user-thread context.
309  *
310  * @param act The current action that will be explored. May be NULL only if
311  * trace is exiting via an assertion (see ModelExecution::set_assert and
312  * ModelExecution::has_asserted).
313  * @return Return the value returned by the current action
314  */
315 uint64_t ModelChecker::switch_to_master(ModelAction *act)
316 {
317         if (modellock) {
318                 static bool fork_message_printed = false;
319
320                 if (!fork_message_printed) {
321                         model_print("Fork handler or dead thread trying to call into model checker...\n");
322                         fork_message_printed = true;
323                 }
324                 delete act;
325                 return 0;
326         }
327         DBG();
328         Thread *old = thread_current();
329         scheduler->set_current_thread(NULL);
330         ASSERT(!old->get_pending());
331
332         if (inspect_plugin != NULL) {
333                 inspect_plugin->inspectModelAction(act);
334         }
335
336         old->set_pending(act);
337         if (Thread::swap(old, &system_context) < 0) {
338                 perror("swap threads");
339                 exit(EXIT_FAILURE);
340         }
341         return old->get_return_value();
342 }
343
344 static void runChecker() {
345         model->run();
346         delete model;
347 }
348
349 void ModelChecker::startChecker() {
350         startExecution(get_system_context(), runChecker);
351         snapshot_stack_init();
352         snapshot_record(0);
353 }
354
355 bool ModelChecker::should_terminate_execution()
356 {
357         if (execution->have_bug_reports()) {
358                 execution->set_assert();
359                 return true;
360         } else if (execution->isFinished()) {
361                 return true;
362         }
363         return false;
364 }
365
366 /** @brief Restart ModelChecker upon returning to the run loop of the
367  *      model checker. */
368 void ModelChecker::restart()
369 {
370         restart_flag = true;
371 }
372
373 void ModelChecker::do_restart()
374 {
375         restart_flag = false;
376         reset_to_initial_state();
377         memset(&stats,0,sizeof(struct execution_stats));
378         execution_number = 1;
379 }
380
381 void ModelChecker::startMainThread() {
382         init_thread->set_state(THREAD_RUNNING);
383         scheduler->set_current_thread(init_thread);
384         main_thread_startup();
385 }
386
387 /** @brief Run ModelChecker for the user program */
388 void ModelChecker::run()
389 {
390         //Need to initial random number generator state to avoid resets on rollback
391         char random_state[256];
392         initstate(423121, random_state, sizeof(random_state));
393
394         for(int exec = 0;exec < params.maxexecutions;exec++) {
395                 Thread * t = init_thread;
396
397                 do {
398                         /*
399                          * Stash next pending action(s) for thread(s). There
400                          * should only need to stash one thread's action--the
401                          * thread which just took a step--plus the first step
402                          * for any newly-created thread
403                          */
404                         for (unsigned int i = 0;i < get_num_threads();i++) {
405                                 thread_id_t tid = int_to_id(i);
406                                 Thread *thr = get_thread(tid);
407                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
408                                         switch_from_master(thr);
409                                         if (thr->is_waiting_on(thr))
410                                                 assert_bug("Deadlock detected (thread %u)", i);
411                                 }
412                         }
413
414                         /* Don't schedule threads which should be disabled */
415                         for (unsigned int i = 0;i < get_num_threads();i++) {
416                                 Thread *th = get_thread(int_to_id(i));
417                                 ModelAction *act = th->get_pending();
418                                 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
419                                         scheduler->sleep(th);
420                                 }
421                         }
422
423                         for (unsigned int i = 1;i < get_num_threads();i++) {
424                                 Thread *th = get_thread(int_to_id(i));
425                                 ModelAction *act = th->get_pending();
426                                 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
427                                         if (act->is_write()) {
428                                                 std::memory_order order = act->get_mo();
429                                                 if (order == std::memory_order_relaxed || \
430                                                                 order == std::memory_order_release) {
431                                                         t = th;
432                                                         break;
433                                                 }
434                                         } else if (act->get_type() == THREAD_CREATE || \
435                                                                                  act->get_type() == PTHREAD_CREATE || \
436                                                                                  act->get_type() == THREAD_START || \
437                                                                                  act->get_type() == THREAD_FINISH) {
438                                                 t = th;
439                                                 break;
440                                         }
441                                 }
442                         }
443
444                         /* Catch assertions from prior take_step or from
445                         * between-ModelAction bugs (e.g., data races) */
446
447                         if (execution->has_asserted())
448                                 break;
449                         if (!t)
450                                 t = get_next_thread();
451                         if (!t || t->is_model_thread())
452                                 break;
453                         if (t->just_woken_up()) {
454                                 t->set_wakeup_state(false);
455                                 t->set_pending(NULL);
456                                 t = NULL;
457                                 continue;       // Allow this thread to stash the next pending action
458                         }
459
460                         /* Consume the next action for a Thread */
461                         ModelAction *curr = t->get_pending();
462                         t->set_pending(NULL);
463                         t = execution->take_step(curr);
464                 } while (!should_terminate_execution());
465                 next_execution();
466                 //restore random number generator state after rollback
467                 setstate(random_state);
468         }
469
470         model_print("******* Model-checking complete: *******\n");
471         print_stats();
472
473         /* Have the trace analyses dump their output. */
474         for (unsigned int i = 0;i < trace_analyses.size();i++)
475                 trace_analyses[i]->finish();
476
477         /* unlink tmp file created by last child process */
478         char filename[256];
479         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
480         unlink(filename);
481 }