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