Redo params
[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 #include "params.h"
21
22 ModelChecker *model = NULL;
23 bool modelchecker_started = false;
24
25 /** Wrapper to run the user's main function, with appropriate arguments */
26 void user_main_wrapper(void *)
27 {
28         user_main(model->params.argc, model->params.argv);
29 }
30
31 /** @brief Constructor */
32 ModelChecker::ModelChecker() :
33         /* Initialize default scheduler */
34         params(),
35         restart_flag(false),
36         scheduler(new Scheduler()),
37         node_stack(new NodeStack()),
38         execution(new ModelExecution(this, scheduler, node_stack)),
39         execution_number(1),
40         trace_analyses(),
41         inspect_plugin(NULL)
42 {
43         memset(&stats,0,sizeof(struct execution_stats));
44         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
45         execution->add_thread(init_thread);
46         scheduler->set_current_thread(init_thread);
47         execution->setParams(&params);
48         param_defaults(&params);
49 }
50
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
53 {
54         delete node_stack;
55         delete scheduler;
56 }
57
58 /** Method to set parameters */
59 model_params * ModelChecker::getParams() {
60         return &params;
61 }
62
63 /**
64  * Restores user program to initial state and resets all model-checker data
65  * structures.
66  */
67 void ModelChecker::reset_to_initial_state()
68 {
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         return false;
267 }
268
269 /** @brief Run trace analyses on complete trace */
270 void ModelChecker::run_trace_analyses() {
271         for (unsigned int i = 0;i < trace_analyses.size();i++)
272                 trace_analyses[i]->analyze(execution->get_action_trace());
273 }
274
275 /**
276  * @brief Get a Thread reference by its ID
277  * @param tid The Thread's ID
278  * @return A Thread reference
279  */
280 Thread * ModelChecker::get_thread(thread_id_t tid) const
281 {
282         return execution->get_thread(tid);
283 }
284
285 /**
286  * @brief Get a reference to the Thread in which a ModelAction was executed
287  * @param act The ModelAction
288  * @return A Thread reference
289  */
290 Thread * ModelChecker::get_thread(const ModelAction *act) const
291 {
292         return execution->get_thread(act);
293 }
294
295 /**
296  * Switch from a model-checker context to a user-thread context. This is the
297  * complement of ModelChecker::switch_to_master and must be called from the
298  * model-checker context
299  *
300  * @param thread The user-thread to switch to
301  */
302 void ModelChecker::switch_from_master(Thread *thread)
303 {
304         scheduler->set_current_thread(thread);
305         Thread::swap(&system_context, thread);
306 }
307
308 /**
309  * Switch from a user-context to the "master thread" context (a.k.a. system
310  * context). This switch is made with the intention of exploring a particular
311  * model-checking action (described by a ModelAction object). Must be called
312  * from a user-thread context.
313  *
314  * @param act The current action that will be explored. May be NULL only if
315  * trace is exiting via an assertion (see ModelExecution::set_assert and
316  * ModelExecution::has_asserted).
317  * @return Return the value returned by the current action
318  */
319 uint64_t ModelChecker::switch_to_master(ModelAction *act)
320 {
321         DBG();
322         Thread *old = thread_current();
323         scheduler->set_current_thread(NULL);
324         ASSERT(!old->get_pending());
325
326         if (inspect_plugin != NULL) {
327                 inspect_plugin->inspectModelAction(act);
328         }
329
330         old->set_pending(act);
331         if (Thread::swap(old, &system_context) < 0) {
332                 perror("swap threads");
333                 exit(EXIT_FAILURE);
334         }
335         return old->get_return_value();
336 }
337
338 bool ModelChecker::should_terminate_execution()
339 {
340         /* Infeasible -> don't take any more steps */
341         if (execution->is_infeasible())
342                 return true;
343         else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
344                 execution->set_assert();
345                 return true;
346         }
347         return false;
348 }
349
350 /** @brief Restart ModelChecker upon returning to the run loop of the
351  *      model checker. */
352 void ModelChecker::restart()
353 {
354         restart_flag = true;
355 }
356
357 void ModelChecker::do_restart()
358 {
359         restart_flag = false;
360         reset_to_initial_state();
361         memset(&stats,0,sizeof(struct execution_stats));
362         execution_number = 1;
363 }
364
365 /** @brief Run ModelChecker for the user program */
366 void ModelChecker::run()
367 {
368         //Need to initial random number generator state to avoid resets on rollback
369         char random_state[256];
370         initstate(423121, random_state, sizeof(random_state));
371
372         for(int exec = 0;exec < params.maxexecutions;exec++) {
373                 Thread * t = init_thread;
374
375                 do {
376                         /*
377                          * Stash next pending action(s) for thread(s). There
378                          * should only need to stash one thread's action--the
379                          * thread which just took a step--plus the first step
380                          * for any newly-created thread
381                          */
382
383                         for (unsigned int i = 0;i < get_num_threads();i++) {
384                                 thread_id_t tid = int_to_id(i);
385                                 Thread *thr = get_thread(tid);
386                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
387                                         switch_from_master(thr);        // L: context swapped, and action type of thr changed.
388                                         if (thr->is_waiting_on(thr))
389                                                 assert_bug("Deadlock detected (thread %u)", i);
390                                 }
391                         }
392
393                         /* Don't schedule threads which should be disabled */
394                         for (unsigned int i = 0;i < get_num_threads();i++) {
395                                 Thread *th = get_thread(int_to_id(i));
396                                 ModelAction *act = th->get_pending();
397                                 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
398                                         scheduler->sleep(th);
399                                 }
400                         }
401
402                         for (unsigned int i = 1;i < get_num_threads();i++) {
403                                 Thread *th = get_thread(int_to_id(i));
404                                 ModelAction *act = th->get_pending();
405                                 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
406                                         if (act->is_write()) {
407                                                 std::memory_order order = act->get_mo();
408                                                 if (order == std::memory_order_relaxed || \
409                                                                 order == std::memory_order_release) {
410                                                         t = th;
411                                                         break;
412                                                 }
413                                         } else if (act->get_type() == THREAD_CREATE || \
414                                                                                  act->get_type() == PTHREAD_CREATE || \
415                                                                                  act->get_type() == THREAD_START || \
416                                                                                  act->get_type() == THREAD_FINISH) {
417                                                 t = th;
418                                                 break;
419                                         }
420                                 }
421                         }
422
423                         /* Catch assertions from prior take_step or from
424                         * between-ModelAction bugs (e.g., data races) */
425
426                         if (execution->has_asserted())
427                                 break;
428                         if (!t)
429                                 t = get_next_thread();
430                         if (!t || t->is_model_thread())
431                                 break;
432
433                         /* Consume the next action for a Thread */
434                         ModelAction *curr = t->get_pending();
435                         t->set_pending(NULL);
436                         t = execution->take_step(curr);
437                 } while (!should_terminate_execution());
438                 next_execution();
439                 //restore random number generator state after rollback
440                 setstate(random_state);
441         }
442
443         model_print("******* Model-checking complete: *******\n");
444         print_stats();
445
446         /* Have the trace analyses dump their output. */
447         for (unsigned int i = 0;i < trace_analyses.size();i++)
448                 trace_analyses[i]->finish();
449 }