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"
23 ModelChecker *model = NULL;
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)),
39 history(new ModelHistory()),
44 memset(&stats,0,sizeof(struct execution_stats));
45 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
46 execution->add_thread(init_thread);
47 scheduler->set_current_thread(init_thread);
48 execution->setParams(¶ms);
49 param_defaults(¶ms);
52 /** @brief Destructor */
53 ModelChecker::~ModelChecker()
59 /** Method to set parameters */
60 model_params * ModelChecker::getParams() {
65 * Restores user program to initial state and resets all model-checker data
68 void ModelChecker::reset_to_initial_state()
72 * FIXME: if we utilize partial rollback, we will need to free only
73 * those pending actions which were NOT pending before the rollback
76 for (unsigned int i = 0;i < get_num_threads();i++)
77 delete get_thread(int_to_id(i))->get_pending();
79 snapshot_backtrack_before(0);
82 /** @return the number of user threads created during this execution */
83 unsigned int ModelChecker::get_num_threads() const
85 return execution->get_num_threads();
89 * Must be called from user-thread context (e.g., through the global
90 * thread_current() interface)
92 * @return The currently executing Thread.
94 Thread * ModelChecker::get_current_thread() const
96 return scheduler->get_current_thread();
100 * @brief Choose the next thread to execute.
102 * This function chooses the next thread that should execute. It can enforce
103 * execution replay/backtracking or, if the model-checker has no preference
104 * regarding the next thread (i.e., when exploring a new execution ordering),
105 * we defer to the scheduler.
107 * @return The next chosen thread to run, if any exist. Or else if the current
108 * execution should terminate, return NULL.
110 Thread * ModelChecker::get_next_thread()
114 * Have we completed exploring the preselected path? Then let the
117 return scheduler->select_next_thread(node_stack->get_head());
121 * @brief Assert a bug in the executing program.
123 * Use this function to assert any sort of bug in the user program. If the
124 * current trace is feasible (actually, a prefix of some feasible execution),
125 * then this execution will be aborted, printing the appropriate message. If
126 * the current trace is not yet feasible, the error message will be stashed and
127 * printed if the execution ever becomes feasible.
129 * @param msg Descriptive message for the bug (do not include newline char)
130 * @return True if bug is immediately-feasible
132 bool ModelChecker::assert_bug(const char *msg, ...)
138 vsnprintf(str, sizeof(str), msg, ap);
141 return execution->assert_bug(str);
145 * @brief Assert a bug in the executing program, asserted by a user thread
146 * @see ModelChecker::assert_bug
147 * @param msg Descriptive message for the bug (do not include newline char)
149 void ModelChecker::assert_user_bug(const char *msg)
151 /* If feasible bug, bail out now */
153 switch_to_master(NULL);
156 /** @brief Print bug report listing for this execution (if any bugs exist) */
157 void ModelChecker::print_bugs() const
159 SnapVector<bug_message *> *bugs = execution->get_bugs();
161 model_print("Bug report: %zu bug%s detected\n",
163 bugs->size() > 1 ? "s" : "");
164 for (unsigned int i = 0;i < bugs->size();i++)
169 * @brief Record end-of-execution stats
171 * Must be run when exiting an execution. Records various stats.
172 * @see struct execution_stats
174 void ModelChecker::record_stats()
177 if (!execution->isfeasibleprefix())
178 stats.num_infeasible++;
179 else if (execution->have_bug_reports())
180 stats.num_buggy_executions++;
181 else if (execution->is_complete_execution())
182 stats.num_complete++;
184 stats.num_redundant++;
187 * @todo We can violate this ASSERT() when fairness/sleep sets
188 * conflict to cause an execution to terminate, e.g. with:
189 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
191 //ASSERT(scheduler->all_threads_sleeping());
195 /** @brief Print execution stats */
196 void ModelChecker::print_stats() const
198 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
199 model_print("Number of redundant executions: %d\n", stats.num_redundant);
200 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
201 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
202 model_print("Total executions: %d\n", stats.num_total);
206 * @brief End-of-exeuction print
207 * @param printbugs Should any existing bugs be printed?
209 void ModelChecker::print_execution(bool printbugs) const
211 model_print("Program output from execution %d:\n",
212 get_execution_number());
213 print_program_output();
215 if (params.verbose >= 3) {
219 /* Don't print invalid bugs */
220 if (printbugs && execution->have_bug_reports()) {
226 execution->print_summary();
230 * Queries the model-checker for more executions to explore and, if one
231 * exists, resets the model-checker state to execute a new execution.
233 * @return If there are more executions to explore, return true. Otherwise,
236 bool ModelChecker::next_execution()
239 /* Is this execution a feasible execution that's worth bug-checking? */
240 bool complete = execution->isfeasibleprefix() &&
241 (execution->is_complete_execution() ||
242 execution->have_bug_reports());
244 /* End-of-execution bug checks */
246 if (execution->is_deadlocked())
247 assert_bug("Deadlock detected");
250 run_trace_analyses();
255 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
256 print_execution(complete);
258 clear_program_output();
266 reset_to_initial_state();
270 /** @brief Run trace analyses on complete trace */
271 void ModelChecker::run_trace_analyses() {
272 for (unsigned int i = 0;i < trace_analyses.size();i++)
273 trace_analyses[i]->analyze(execution->get_action_trace());
277 * @brief Get a Thread reference by its ID
278 * @param tid The Thread's ID
279 * @return A Thread reference
281 Thread * ModelChecker::get_thread(thread_id_t tid) const
283 return execution->get_thread(tid);
287 * @brief Get a reference to the Thread in which a ModelAction was executed
288 * @param act The ModelAction
289 * @return A Thread reference
291 Thread * ModelChecker::get_thread(const ModelAction *act) const
293 return execution->get_thread(act);
297 * Switch from a model-checker context to a user-thread context. This is the
298 * complement of ModelChecker::switch_to_master and must be called from the
299 * model-checker context
301 * @param thread The user-thread to switch to
303 void ModelChecker::switch_from_master(Thread *thread)
305 scheduler->set_current_thread(thread);
306 Thread::swap(&system_context, thread);
310 * Switch from a user-context to the "master thread" context (a.k.a. system
311 * context). This switch is made with the intention of exploring a particular
312 * model-checking action (described by a ModelAction object). Must be called
313 * from a user-thread context.
315 * @param act The current action that will be explored. May be NULL only if
316 * trace is exiting via an assertion (see ModelExecution::set_assert and
317 * ModelExecution::has_asserted).
318 * @return Return the value returned by the current action
320 uint64_t ModelChecker::switch_to_master(ModelAction *act)
323 Thread *old = thread_current();
324 scheduler->set_current_thread(NULL);
325 ASSERT(!old->get_pending());
327 if (inspect_plugin != NULL) {
328 inspect_plugin->inspectModelAction(act);
331 old->set_pending(act);
332 if (Thread::swap(old, &system_context) < 0) {
333 perror("swap threads");
336 return old->get_return_value();
339 static void runChecker() {
344 void ModelChecker::startChecker() {
345 startExecution(get_system_context(), runChecker);
348 bool ModelChecker::should_terminate_execution()
350 /* Infeasible -> don't take any more steps */
351 if (execution->is_infeasible())
353 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
354 execution->set_assert();
360 /** @brief Restart ModelChecker upon returning to the run loop of the
362 void ModelChecker::restart()
367 void ModelChecker::do_restart()
369 restart_flag = false;
370 reset_to_initial_state();
371 memset(&stats,0,sizeof(struct execution_stats));
372 execution_number = 1;
375 void ModelChecker::startMainThread() {
376 init_thread->set_state(THREAD_RUNNING);
377 scheduler->set_current_thread(init_thread);
381 static bool is_nonsc_write(const ModelAction *act) {
382 if (act->get_type() == ATOMIC_WRITE) {
383 std::memory_order order = act->get_mo();
385 case std::memory_order_relaxed:
386 case std::memory_order_release:
395 /** @brief Run ModelChecker for the user program */
396 void ModelChecker::run()
398 //Need to initial random number generator state to avoid resets on rollback
399 char random_state[256];
400 initstate(423121, random_state, sizeof(random_state));
402 for(int exec = 0;exec < params.maxexecutions;exec++) {
403 Thread * t = init_thread;
407 * Stash next pending action(s) for thread(s). There
408 * should only need to stash one thread's action--the
409 * thread which just took a step--plus the first step
410 * for any newly-created thread
412 ModelAction * pending;
413 for (unsigned int i = 0;i < get_num_threads();i++) {
414 thread_id_t tid = int_to_id(i);
415 Thread *thr = get_thread(tid);
416 if (!thr->is_model_thread() && !thr->is_complete() && ((!(pending=thr->get_pending())) || is_nonsc_write(pending)) ) {
417 switch_from_master(thr); // L: context swapped, and action type of thr changed.
418 if (thr->is_waiting_on(thr))
419 assert_bug("Deadlock detected (thread %u)", i);
423 /* Don't schedule threads which should be disabled */
424 for (unsigned int i = 0;i < get_num_threads();i++) {
425 Thread *th = get_thread(int_to_id(i));
426 ModelAction *act = th->get_pending();
427 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
428 scheduler->sleep(th);
432 for (unsigned int i = 1;i < get_num_threads();i++) {
433 Thread *th = get_thread(int_to_id(i));
434 ModelAction *act = th->get_pending();
435 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
436 if (act->is_write()) {
437 std::memory_order order = act->get_mo();
438 if (order == std::memory_order_relaxed || \
439 order == std::memory_order_release) {
443 } else if (act->get_type() == THREAD_CREATE || \
444 act->get_type() == PTHREAD_CREATE || \
445 act->get_type() == THREAD_START || \
446 act->get_type() == THREAD_FINISH) {
453 /* Catch assertions from prior take_step or from
454 * between-ModelAction bugs (e.g., data races) */
456 if (execution->has_asserted())
459 t = get_next_thread();
460 if (!t || t->is_model_thread())
463 /* Consume the next action for a Thread */
464 ModelAction *curr = t->get_pending();
465 t->set_pending(NULL);
466 t = execution->take_step(curr);
467 } while (!should_terminate_execution());
469 //restore random number generator state after rollback
470 setstate(random_state);
473 model_print("******* Model-checking complete: *******\n");
476 /* Have the trace analyses dump their output. */
477 for (unsigned int i = 0;i < trace_analyses.size();i++)
478 trace_analyses[i]->finish();