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