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