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