10 #include "nodestack.h"
12 #include "snapshot-interface.h"
15 #include "threads-model.h"
17 #include "traceanalysis.h"
18 #include "execution.h"
20 #include "bugmessage.h"
24 /** @brief Constructor */
25 ModelChecker::ModelChecker() :
26 /* Initialize default scheduler */
29 scheduler(new Scheduler()),
30 node_stack(new NodeStack()),
31 execution(new ModelExecution(this, scheduler, node_stack)),
32 history(new ModelHistory()),
37 memset(&stats,0,sizeof(struct execution_stats));
40 /** @brief Destructor */
41 ModelChecker::~ModelChecker()
47 /** Method to set parameters */
48 void ModelChecker::setParams(struct model_params params) {
49 this->params = params;
50 execution->setParams(¶ms);
54 * Restores user program to initial state and resets all model-checker data
57 void ModelChecker::reset_to_initial_state()
59 DEBUG("+++ Resetting to initial state +++\n");
60 node_stack->reset_execution();
63 * FIXME: if we utilize partial rollback, we will need to free only
64 * those pending actions which were NOT pending before the rollback
67 for (unsigned int i = 0;i < get_num_threads();i++)
68 delete get_thread(int_to_id(i))->get_pending();
70 snapshot_backtrack_before(0);
73 /** @return the number of user threads created during this execution */
74 unsigned int ModelChecker::get_num_threads() const
76 return execution->get_num_threads();
80 * Must be called from user-thread context (e.g., through the global
81 * thread_current() interface)
83 * @return The currently executing Thread.
85 Thread * ModelChecker::get_current_thread() const
87 return scheduler->get_current_thread();
91 * @brief Choose the next thread to execute.
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.
98 * @return The next chosen thread to run, if any exist. Or else if the current
99 * execution should terminate, return NULL.
101 Thread * ModelChecker::get_next_thread()
105 * Have we completed exploring the preselected path? Then let the
108 return scheduler->select_next_thread(node_stack->get_head());
112 * @brief Assert a bug in the executing program.
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.
120 * @param msg Descriptive message for the bug (do not include newline char)
121 * @return True if bug is immediately-feasible
123 bool ModelChecker::assert_bug(const char *msg, ...)
129 vsnprintf(str, sizeof(str), msg, ap);
132 return execution->assert_bug(str);
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)
140 void ModelChecker::assert_user_bug(const char *msg)
142 /* If feasible bug, bail out now */
144 switch_to_master(NULL);
147 /** @brief Print bug report listing for this execution (if any bugs exist) */
148 void ModelChecker::print_bugs() const
150 SnapVector<bug_message *> *bugs = execution->get_bugs();
152 model_print("Bug report: %zu bug%s detected\n",
154 bugs->size() > 1 ? "s" : "");
155 for (unsigned int i = 0;i < bugs->size();i++)
160 * @brief Record end-of-execution stats
162 * Must be run when exiting an execution. Records various stats.
163 * @see struct execution_stats
165 void ModelChecker::record_stats()
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++;
175 stats.num_redundant++;
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]
182 //ASSERT(scheduler->all_threads_sleeping());
186 /** @brief Print execution stats */
187 void ModelChecker::print_stats() const
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);
197 * @brief End-of-exeuction print
198 * @param printbugs Should any existing bugs be printed?
200 void ModelChecker::print_execution(bool printbugs) const
202 model_print("Program output from execution %d:\n",
203 get_execution_number());
204 print_program_output();
206 if (params.verbose >= 3) {
210 /* Don't print invalid bugs */
211 if (printbugs && execution->have_bug_reports()) {
217 execution->print_summary();
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.
224 * @return If there are more executions to explore, return true. Otherwise,
227 bool ModelChecker::next_execution()
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());
235 /* End-of-execution bug checks */
237 if (execution->is_deadlocked())
238 assert_bug("Deadlock detected");
241 run_trace_analyses();
246 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
247 print_execution(complete);
249 clear_program_output();
257 reset_to_initial_state();
258 node_stack->full_reset();
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());
269 * @brief Get a Thread reference by its ID
270 * @param tid The Thread's ID
271 * @return A Thread reference
273 Thread * ModelChecker::get_thread(thread_id_t tid) const
275 return execution->get_thread(tid);
279 * @brief Get a reference to the Thread in which a ModelAction was executed
280 * @param act The ModelAction
281 * @return A Thread reference
283 Thread * ModelChecker::get_thread(const ModelAction *act) const
285 return execution->get_thread(act);
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
293 * @param thread The user-thread to switch to
295 void ModelChecker::switch_from_master(Thread *thread)
297 scheduler->set_current_thread(thread);
298 Thread::swap(&system_context, thread);
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.
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
312 uint64_t ModelChecker::switch_to_master(ModelAction *act)
315 Thread *old = thread_current();
316 scheduler->set_current_thread(NULL);
317 ASSERT(!old->get_pending());
319 if (inspect_plugin != NULL) {
320 inspect_plugin->inspectModelAction(act);
322 old->set_pending(act);
323 if (Thread::swap(old, &system_context) < 0) {
324 perror("swap threads");
327 return old->get_return_value();
330 /** Wrapper to run the user's main function, with appropriate arguments */
331 void user_main_wrapper(void *)
333 user_main(model->params.argc, model->params.argv);
336 bool ModelChecker::should_terminate_execution()
338 /* Infeasible -> don't take any more steps */
339 if (execution->is_infeasible())
341 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
342 execution->set_assert();
348 /** @brief Restart ModelChecker upon returning to the run loop of the
350 void ModelChecker::restart()
355 void ModelChecker::do_restart()
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;
364 /** @brief Run ModelChecker for the user program */
365 void ModelChecker::run()
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));
371 for(int exec = 0;exec < params.maxexecutions;exec++) {
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
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
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);
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);
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) {
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) {
424 /* Catch assertions from prior take_step or from
425 * between-ModelAction bugs (e.g., data races) */
427 if (execution->has_asserted())
430 t = get_next_thread();
431 if (!t || t->is_model_thread())
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());
440 //restore random number generator state after rollback
441 setstate(random_state);
444 model_print("******* Model-checking complete: *******\n");
447 /* Have the trace analyses dump their output. */
448 for (unsigned int i = 0;i < trace_analyses.size();i++)
449 trace_analyses[i]->finish();