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