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