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