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