10 #include "nodestack.h"
12 #include "snapshot-interface.h"
15 #include "threads-model.h"
17 #include "traceanalysis.h"
18 #include "execution.h"
19 #include "bugmessage.h"
22 ModelChecker *model = NULL;
23 bool modelchecker_started = false;
25 /** Wrapper to run the user's main function, with appropriate arguments */
26 void user_main_wrapper(void *)
28 user_main(model->params.argc, model->params.argv);
31 /** @brief Constructor */
32 ModelChecker::ModelChecker() :
33 /* Initialize default scheduler */
36 scheduler(new Scheduler()),
37 node_stack(new NodeStack()),
38 execution(new ModelExecution(this, scheduler, node_stack)),
43 memset(&stats,0,sizeof(struct execution_stats));
44 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
45 execution->add_thread(init_thread);
46 scheduler->set_current_thread(init_thread);
47 execution->setParams(¶ms);
48 param_defaults(¶ms);
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
58 /** Method to set parameters */
59 model_params * ModelChecker::getParams() {
64 * Restores user program to initial state and resets all model-checker data
67 void ModelChecker::reset_to_initial_state()
71 * FIXME: if we utilize partial rollback, we will need to free only
72 * those pending actions which were NOT pending before the rollback
75 for (unsigned int i = 0;i < get_num_threads();i++)
76 delete get_thread(int_to_id(i))->get_pending();
78 snapshot_backtrack_before(0);
81 /** @return the number of user threads created during this execution */
82 unsigned int ModelChecker::get_num_threads() const
84 return execution->get_num_threads();
88 * Must be called from user-thread context (e.g., through the global
89 * thread_current() interface)
91 * @return The currently executing Thread.
93 Thread * ModelChecker::get_current_thread() const
95 return scheduler->get_current_thread();
99 * @brief Choose the next thread to execute.
101 * This function chooses the next thread that should execute. It can enforce
102 * execution replay/backtracking or, if the model-checker has no preference
103 * regarding the next thread (i.e., when exploring a new execution ordering),
104 * we defer to the scheduler.
106 * @return The next chosen thread to run, if any exist. Or else if the current
107 * execution should terminate, return NULL.
109 Thread * ModelChecker::get_next_thread()
113 * Have we completed exploring the preselected path? Then let the
116 return scheduler->select_next_thread(node_stack->get_head());
120 * @brief Assert a bug in the executing program.
122 * Use this function to assert any sort of bug in the user program. If the
123 * current trace is feasible (actually, a prefix of some feasible execution),
124 * then this execution will be aborted, printing the appropriate message. If
125 * the current trace is not yet feasible, the error message will be stashed and
126 * printed if the execution ever becomes feasible.
128 * @param msg Descriptive message for the bug (do not include newline char)
129 * @return True if bug is immediately-feasible
131 bool ModelChecker::assert_bug(const char *msg, ...)
137 vsnprintf(str, sizeof(str), msg, ap);
140 return execution->assert_bug(str);
144 * @brief Assert a bug in the executing program, asserted by a user thread
145 * @see ModelChecker::assert_bug
146 * @param msg Descriptive message for the bug (do not include newline char)
148 void ModelChecker::assert_user_bug(const char *msg)
150 /* If feasible bug, bail out now */
152 switch_to_master(NULL);
155 /** @brief Print bug report listing for this execution (if any bugs exist) */
156 void ModelChecker::print_bugs() const
158 SnapVector<bug_message *> *bugs = execution->get_bugs();
160 model_print("Bug report: %zu bug%s detected\n",
162 bugs->size() > 1 ? "s" : "");
163 for (unsigned int i = 0;i < bugs->size();i++)
168 * @brief Record end-of-execution stats
170 * Must be run when exiting an execution. Records various stats.
171 * @see struct execution_stats
173 void ModelChecker::record_stats()
176 if (!execution->isfeasibleprefix())
177 stats.num_infeasible++;
178 else if (execution->have_bug_reports())
179 stats.num_buggy_executions++;
180 else if (execution->is_complete_execution())
181 stats.num_complete++;
183 stats.num_redundant++;
186 * @todo We can violate this ASSERT() when fairness/sleep sets
187 * conflict to cause an execution to terminate, e.g. with:
188 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
190 //ASSERT(scheduler->all_threads_sleeping());
194 /** @brief Print execution stats */
195 void ModelChecker::print_stats() const
197 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
198 model_print("Number of redundant executions: %d\n", stats.num_redundant);
199 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
200 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
201 model_print("Total executions: %d\n", stats.num_total);
205 * @brief End-of-exeuction print
206 * @param printbugs Should any existing bugs be printed?
208 void ModelChecker::print_execution(bool printbugs) const
210 model_print("Program output from execution %d:\n",
211 get_execution_number());
212 print_program_output();
214 if (params.verbose >= 3) {
218 /* Don't print invalid bugs */
219 if (printbugs && execution->have_bug_reports()) {
225 execution->print_summary();
229 * Queries the model-checker for more executions to explore and, if one
230 * exists, resets the model-checker state to execute a new execution.
232 * @return If there are more executions to explore, return true. Otherwise,
235 bool ModelChecker::next_execution()
238 /* Is this execution a feasible execution that's worth bug-checking? */
239 bool complete = execution->isfeasibleprefix() &&
240 (execution->is_complete_execution() ||
241 execution->have_bug_reports());
243 /* End-of-execution bug checks */
245 if (execution->is_deadlocked())
246 assert_bug("Deadlock detected");
249 run_trace_analyses();
254 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
255 print_execution(complete);
257 clear_program_output();
265 reset_to_initial_state();
269 /** @brief Run trace analyses on complete trace */
270 void ModelChecker::run_trace_analyses() {
271 for (unsigned int i = 0;i < trace_analyses.size();i++)
272 trace_analyses[i]->analyze(execution->get_action_trace());
276 * @brief Get a Thread reference by its ID
277 * @param tid The Thread's ID
278 * @return A Thread reference
280 Thread * ModelChecker::get_thread(thread_id_t tid) const
282 return execution->get_thread(tid);
286 * @brief Get a reference to the Thread in which a ModelAction was executed
287 * @param act The ModelAction
288 * @return A Thread reference
290 Thread * ModelChecker::get_thread(const ModelAction *act) const
292 return execution->get_thread(act);
296 * Switch from a model-checker context to a user-thread context. This is the
297 * complement of ModelChecker::switch_to_master and must be called from the
298 * model-checker context
300 * @param thread The user-thread to switch to
302 void ModelChecker::switch_from_master(Thread *thread)
304 scheduler->set_current_thread(thread);
305 Thread::swap(&system_context, thread);
309 * Switch from a user-context to the "master thread" context (a.k.a. system
310 * context). This switch is made with the intention of exploring a particular
311 * model-checking action (described by a ModelAction object). Must be called
312 * from a user-thread context.
314 * @param act The current action that will be explored. May be NULL only if
315 * trace is exiting via an assertion (see ModelExecution::set_assert and
316 * ModelExecution::has_asserted).
317 * @return Return the value returned by the current action
319 uint64_t ModelChecker::switch_to_master(ModelAction *act)
322 Thread *old = thread_current();
323 scheduler->set_current_thread(NULL);
324 ASSERT(!old->get_pending());
326 if (inspect_plugin != NULL) {
327 inspect_plugin->inspectModelAction(act);
330 old->set_pending(act);
331 if (Thread::swap(old, &system_context) < 0) {
332 perror("swap threads");
335 return old->get_return_value();
338 bool ModelChecker::should_terminate_execution()
340 /* Infeasible -> don't take any more steps */
341 if (execution->is_infeasible())
343 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
344 execution->set_assert();
350 /** @brief Restart ModelChecker upon returning to the run loop of the
352 void ModelChecker::restart()
357 void ModelChecker::do_restart()
359 restart_flag = false;
360 reset_to_initial_state();
361 memset(&stats,0,sizeof(struct execution_stats));
362 execution_number = 1;
365 /** @brief Run ModelChecker for the user program */
366 void ModelChecker::run()
368 //Need to initial random number generator state to avoid resets on rollback
369 char random_state[256];
370 initstate(423121, random_state, sizeof(random_state));
372 for(int exec = 0;exec < params.maxexecutions;exec++) {
373 Thread * t = init_thread;
377 * Stash next pending action(s) for thread(s). There
378 * should only need to stash one thread's action--the
379 * thread which just took a step--plus the first step
380 * for any newly-created thread
383 for (unsigned int i = 0;i < get_num_threads();i++) {
384 thread_id_t tid = int_to_id(i);
385 Thread *thr = get_thread(tid);
386 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
387 switch_from_master(thr); // L: context swapped, and action type of thr changed.
388 if (thr->is_waiting_on(thr))
389 assert_bug("Deadlock detected (thread %u)", i);
393 /* Don't schedule threads which should be disabled */
394 for (unsigned int i = 0;i < get_num_threads();i++) {
395 Thread *th = get_thread(int_to_id(i));
396 ModelAction *act = th->get_pending();
397 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
398 scheduler->sleep(th);
402 for (unsigned int i = 1;i < get_num_threads();i++) {
403 Thread *th = get_thread(int_to_id(i));
404 ModelAction *act = th->get_pending();
405 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
406 if (act->is_write()) {
407 std::memory_order order = act->get_mo();
408 if (order == std::memory_order_relaxed || \
409 order == std::memory_order_release) {
413 } else if (act->get_type() == THREAD_CREATE || \
414 act->get_type() == PTHREAD_CREATE || \
415 act->get_type() == THREAD_START || \
416 act->get_type() == THREAD_FINISH) {
423 /* Catch assertions from prior take_step or from
424 * between-ModelAction bugs (e.g., data races) */
426 if (execution->has_asserted())
429 t = get_next_thread();
430 if (!t || t->is_model_thread())
433 /* Consume the next action for a Thread */
434 ModelAction *curr = t->get_pending();
435 t->set_pending(NULL);
436 t = execution->take_step(curr);
437 } while (!should_terminate_execution());
439 //restore random number generator state after rollback
440 setstate(random_state);
443 model_print("******* Model-checking complete: *******\n");
446 /* Have the trace analyses dump their output. */
447 for (unsigned int i = 0;i < trace_analyses.size();i++)
448 trace_analyses[i]->finish();