17ea5427d70bd19d8a0cd9856a9a997e077f3162
[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 "nodestack.h"
11 #include "schedule.h"
12 #include "snapshot-interface.h"
13 #include "common.h"
14 #include "datarace.h"
15 #include "threads-model.h"
16 #include "output.h"
17 #include "traceanalysis.h"
18 #include "execution.h"
19 #include "bugmessage.h"
20
21 ModelChecker *model = NULL;
22 bool modelchecker_started = false;
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         node_stack(new NodeStack()),
37         execution(new ModelExecution(this, scheduler, node_stack)),
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 *) malloc(sizeof(thrd_t)), &user_main_wrapper, NULL, NULL);  // L: user_main_wrapper passes the user program
44         execution->add_thread(init_thread);
45         scheduler->set_current_thread(init_thread);
46 }
47
48 /** @brief Destructor */
49 ModelChecker::~ModelChecker()
50 {
51         delete node_stack;
52         delete scheduler;
53 }
54
55 /** Method to set parameters */
56 void ModelChecker::setParams(struct model_params params) {
57         this->params = params;
58         execution->setParams(&params);
59 }
60
61 /**
62  * Restores user program to initial state and resets all model-checker data
63  * structures.
64  */
65 void ModelChecker::reset_to_initial_state()
66 {
67
68         /**
69          * FIXME: if we utilize partial rollback, we will need to free only
70          * those pending actions which were NOT pending before the rollback
71          * point
72          */
73         for (unsigned int i = 0;i < get_num_threads();i++)
74                 delete get_thread(int_to_id(i))->get_pending();
75
76         snapshot_backtrack_before(0);
77 }
78
79 /** @return the number of user threads created during this execution */
80 unsigned int ModelChecker::get_num_threads() const
81 {
82         return execution->get_num_threads();
83 }
84
85 /**
86  * Must be called from user-thread context (e.g., through the global
87  * thread_current() interface)
88  *
89  * @return The currently executing Thread.
90  */
91 Thread * ModelChecker::get_current_thread() const
92 {
93         return scheduler->get_current_thread();
94 }
95
96 /**
97  * @brief Choose the next thread to execute.
98  *
99  * This function chooses the next thread that should execute. It can enforce
100  * execution replay/backtracking or, if the model-checker has no preference
101  * regarding the next thread (i.e., when exploring a new execution ordering),
102  * we defer to the scheduler.
103  *
104  * @return The next chosen thread to run, if any exist. Or else if the current
105  * execution should terminate, return NULL.
106  */
107 Thread * ModelChecker::get_next_thread()
108 {
109
110         /*
111          * Have we completed exploring the preselected path? Then let the
112          * scheduler decide
113          */
114         return scheduler->select_next_thread(node_stack->get_head());
115 }
116
117 /**
118  * @brief Assert a bug in the executing program.
119  *
120  * Use this function to assert any sort of bug in the user program. If the
121  * current trace is feasible (actually, a prefix of some feasible execution),
122  * then this execution will be aborted, printing the appropriate message. If
123  * the current trace is not yet feasible, the error message will be stashed and
124  * printed if the execution ever becomes feasible.
125  *
126  * @param msg Descriptive message for the bug (do not include newline char)
127  * @return True if bug is immediately-feasible
128  */
129 bool ModelChecker::assert_bug(const char *msg, ...)
130 {
131         char str[800];
132
133         va_list ap;
134         va_start(ap, msg);
135         vsnprintf(str, sizeof(str), msg, ap);
136         va_end(ap);
137
138         return execution->assert_bug(str);
139 }
140
141 /**
142  * @brief Assert a bug in the executing program, asserted by a user thread
143  * @see ModelChecker::assert_bug
144  * @param msg Descriptive message for the bug (do not include newline char)
145  */
146 void ModelChecker::assert_user_bug(const char *msg)
147 {
148         /* If feasible bug, bail out now */
149         if (assert_bug(msg))
150                 switch_to_master(NULL);
151 }
152
153 /** @brief Print bug report listing for this execution (if any bugs exist) */
154 void ModelChecker::print_bugs() const
155 {
156         SnapVector<bug_message *> *bugs = execution->get_bugs();
157
158         model_print("Bug report: %zu bug%s detected\n",
159                                                         bugs->size(),
160                                                         bugs->size() > 1 ? "s" : "");
161         for (unsigned int i = 0;i < bugs->size();i++)
162                 (*bugs)[i]->print();
163 }
164
165 /**
166  * @brief Record end-of-execution stats
167  *
168  * Must be run when exiting an execution. Records various stats.
169  * @see struct execution_stats
170  */
171 void ModelChecker::record_stats()
172 {
173         stats.num_total++;
174         if (!execution->isfeasibleprefix())
175                 stats.num_infeasible++;
176         else if (execution->have_bug_reports())
177                 stats.num_buggy_executions++;
178         else if (execution->is_complete_execution())
179                 stats.num_complete++;
180         else {
181                 stats.num_redundant++;
182
183                 /**
184                  * @todo We can violate this ASSERT() when fairness/sleep sets
185                  * conflict to cause an execution to terminate, e.g. with:
186                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
187                  */
188                 //ASSERT(scheduler->all_threads_sleeping());
189         }
190 }
191
192 /** @brief Print execution stats */
193 void ModelChecker::print_stats() const
194 {
195         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
196         model_print("Number of redundant executions: %d\n", stats.num_redundant);
197         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
198         model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
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->isfeasibleprefix() &&
238                                                                         (execution->is_complete_execution() ||
239                                                                          execution->have_bug_reports());
240
241         /* End-of-execution bug checks */
242         if (complete) {
243                 if (execution->is_deadlocked())
244                         assert_bug("Deadlock detected");
245
246                 checkDataRaces();
247                 run_trace_analyses();
248         }
249
250         record_stats();
251         /* Output */
252         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
253                 print_execution(complete);
254         else
255                 clear_program_output();
256
257         if (restart_flag) {
258                 do_restart();
259                 return true;
260         }
261 // test code
262         execution_number++;
263         reset_to_initial_state();
264         return false;
265 }
266
267 /** @brief Run trace analyses on complete trace */
268 void ModelChecker::run_trace_analyses() {
269         for (unsigned int i = 0;i < trace_analyses.size();i++)
270                 trace_analyses[i]->analyze(execution->get_action_trace());
271 }
272
273 /**
274  * @brief Get a Thread reference by its ID
275  * @param tid The Thread's ID
276  * @return A Thread reference
277  */
278 Thread * ModelChecker::get_thread(thread_id_t tid) const
279 {
280         return execution->get_thread(tid);
281 }
282
283 /**
284  * @brief Get a reference to the Thread in which a ModelAction was executed
285  * @param act The ModelAction
286  * @return A Thread reference
287  */
288 Thread * ModelChecker::get_thread(const ModelAction *act) const
289 {
290         return execution->get_thread(act);
291 }
292
293 /**
294  * Switch from a model-checker context to a user-thread context. This is the
295  * complement of ModelChecker::switch_to_master and must be called from the
296  * model-checker context
297  *
298  * @param thread The user-thread to switch to
299  */
300 void ModelChecker::switch_from_master(Thread *thread)
301 {
302         scheduler->set_current_thread(thread);
303         Thread::swap(&system_context, thread);
304 }
305
306 /**
307  * Switch from a user-context to the "master thread" context (a.k.a. system
308  * context). This switch is made with the intention of exploring a particular
309  * model-checking action (described by a ModelAction object). Must be called
310  * from a user-thread context.
311  *
312  * @param act The current action that will be explored. May be NULL only if
313  * trace is exiting via an assertion (see ModelExecution::set_assert and
314  * ModelExecution::has_asserted).
315  * @return Return the value returned by the current action
316  */
317 uint64_t ModelChecker::switch_to_master(ModelAction *act)
318 {
319         DBG();
320         Thread *old = thread_current();
321         scheduler->set_current_thread(NULL);
322         ASSERT(!old->get_pending());
323
324         if (inspect_plugin != NULL) {
325                 inspect_plugin->inspectModelAction(act);
326         }
327
328         old->set_pending(act);
329         if (Thread::swap(old, &system_context) < 0) {
330                 perror("swap threads");
331                 exit(EXIT_FAILURE);
332         }
333         return old->get_return_value();
334 }
335
336 bool ModelChecker::should_terminate_execution()
337 {
338         /* Infeasible -> don't take any more steps */
339         if (execution->is_infeasible())
340                 return true;
341         else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
342                 execution->set_assert();
343                 return true;
344         }
345         return false;
346 }
347
348 /** @brief Restart ModelChecker upon returning to the run loop of the
349  *      model checker. */
350 void ModelChecker::restart()
351 {
352         restart_flag = true;
353 }
354
355 void ModelChecker::do_restart()
356 {
357         restart_flag = false;
358         reset_to_initial_state();
359         memset(&stats,0,sizeof(struct execution_stats));
360         execution_number = 1;
361 }
362
363 /** @brief Run ModelChecker for the user program */
364 void ModelChecker::run()
365 {
366         //Need to initial random number generator state to avoid resets on rollback
367         char random_state[256];
368         initstate(423121, random_state, sizeof(random_state));
369
370         for(int exec = 0;exec < params.maxexecutions;exec++) {
371                 Thread * t = init_thread;
372
373                 do {
374                         /*
375                          * Stash next pending action(s) for thread(s). There
376                          * should only need to stash one thread's action--the
377                          * thread which just took a step--plus the first step
378                          * for any newly-created thread
379                          */
380
381                         for (unsigned int i = 0;i < get_num_threads();i++) {
382                                 thread_id_t tid = int_to_id(i);
383                                 Thread *thr = get_thread(tid);
384                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
385                                         switch_from_master(thr);        // L: context swapped, and action type of thr changed.
386                                         if (thr->is_waiting_on(thr))
387                                                 assert_bug("Deadlock detected (thread %u)", i);
388                                 }
389                         }
390
391                         /* Don't schedule threads which should be disabled */
392                         for (unsigned int i = 0;i < get_num_threads();i++) {
393                                 Thread *th = get_thread(int_to_id(i));
394                                 ModelAction *act = th->get_pending();
395                                 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
396                                         scheduler->sleep(th);
397                                 }
398                         }
399
400                         for (unsigned int i = 1;i < get_num_threads();i++) {
401                                 Thread *th = get_thread(int_to_id(i));
402                                 ModelAction *act = th->get_pending();
403                                 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
404                                         if (act->is_write()) {
405                                                 std::memory_order order = act->get_mo();
406                                                 if (order == std::memory_order_relaxed || \
407                                                                 order == std::memory_order_release) {
408                                                         t = th;
409                                                         break;
410                                                 }
411                                         } else if (act->get_type() == THREAD_CREATE || \
412                                                                                  act->get_type() == PTHREAD_CREATE || \
413                                                                                  act->get_type() == THREAD_START || \
414                                                                                  act->get_type() == THREAD_FINISH) {
415                                                 t = th;
416                                                 break;
417                                         }
418                                 }
419                         }
420
421                         /* Catch assertions from prior take_step or from
422                         * between-ModelAction bugs (e.g., data races) */
423
424                         if (execution->has_asserted())
425                                 break;
426                         if (!t)
427                                 t = get_next_thread();
428                         if (!t || t->is_model_thread())
429                                 break;
430
431                         /* Consume the next action for a Thread */
432                         ModelAction *curr = t->get_pending();
433                         t->set_pending(NULL);
434                         t = execution->take_step(curr);
435                 } while (!should_terminate_execution());
436                 next_execution();
437                 //restore random number generator state after rollback
438                 setstate(random_state);
439         }
440
441         model_print("******* Model-checking complete: *******\n");
442         print_stats();
443
444         /* Have the trace analyses dump their output. */
445         for (unsigned int i = 0;i < trace_analyses.size();i++)
446                 trace_analyses[i]->finish();
447 }