10 #include "snapshot-interface.h"
13 #include "threads-model.h"
15 #include "traceanalysis.h"
16 #include "execution.h"
17 #include "bugmessage.h"
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23 /* Initialize default scheduler */
25 scheduler(new Scheduler()),
26 node_stack(new NodeStack()),
27 execution(new ModelExecution(this, &this->params, scheduler, node_stack)),
30 earliest_diverge(NULL),
35 /** @brief Destructor */
36 ModelChecker::~ModelChecker()
39 for (unsigned int i = 0; i < trace_analyses.size(); i++)
40 delete trace_analyses[i];
45 * Restores user program to initial state and resets all model-checker data
48 void ModelChecker::reset_to_initial_state()
50 DEBUG("+++ Resetting to initial state +++\n");
51 node_stack->reset_execution();
54 * FIXME: if we utilize partial rollback, we will need to free only
55 * those pending actions which were NOT pending before the rollback
58 for (unsigned int i = 0; i < get_num_threads(); i++)
59 delete get_thread(int_to_id(i))->get_pending();
61 snapshot_backtrack_before(0);
64 /** @return the number of user threads created during this execution */
65 unsigned int ModelChecker::get_num_threads() const
67 return execution->get_num_threads();
71 * Must be called from user-thread context (e.g., through the global
72 * thread_current() interface)
74 * @return The currently executing Thread.
76 Thread * ModelChecker::get_current_thread() const
78 return scheduler->get_current_thread();
82 * @brief Choose the next thread to execute.
84 * This function chooses the next thread that should execute. It can enforce
85 * execution replay/backtracking or, if the model-checker has no preference
86 * regarding the next thread (i.e., when exploring a new execution ordering),
87 * we defer to the scheduler.
89 * @return The next chosen thread to run, if any exist. Or else if the current
90 * execution should terminate, return NULL.
92 Thread * ModelChecker::get_next_thread()
97 * Have we completed exploring the preselected path? Then let the
101 return scheduler->select_next_thread(node_stack->get_head());
104 /* Else, we are trying to replay an execution */
105 ModelAction *next = node_stack->get_next()->get_action();
107 if (next == diverge) {
108 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
109 earliest_diverge = diverge;
111 Node *nextnode = next->get_node();
112 Node *prevnode = nextnode->get_parent();
113 scheduler->update_sleep_set(prevnode);
115 /* Reached divergence point */
116 if (nextnode->increment_behaviors()) {
117 /* Execute the same thread with a new behavior */
118 tid = next->get_tid();
119 node_stack->pop_restofstack(2);
122 /* Make a different thread execute for next step */
123 scheduler->add_sleep(get_thread(next->get_tid()));
124 tid = prevnode->get_next_backtrack();
125 /* Make sure the backtracked thread isn't sleeping. */
126 node_stack->pop_restofstack(1);
127 if (diverge == earliest_diverge) {
128 earliest_diverge = prevnode->get_action();
131 /* Start the round robin scheduler from this thread id */
132 scheduler->set_scheduler_thread(tid);
133 /* The correct sleep set is in the parent node. */
136 DEBUG("*** Divergence point ***\n");
140 tid = next->get_tid();
142 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
143 ASSERT(tid != THREAD_ID_T_NONE);
144 return get_thread(id_to_int(tid));
148 * We need to know what the next actions of all threads in the sleep
149 * set will be. This method computes them and stores the actions at
150 * the corresponding thread object's pending action.
152 void ModelChecker::execute_sleep_set()
154 for (unsigned int i = 0; i < get_num_threads(); i++) {
155 thread_id_t tid = int_to_id(i);
156 Thread *thr = get_thread(tid);
157 if (scheduler->is_sleep_set(thr) && thr->get_pending()) {
158 thr->get_pending()->set_sleep_flag();
164 * @brief Assert a bug in the executing program.
166 * Use this function to assert any sort of bug in the user program. If the
167 * current trace is feasible (actually, a prefix of some feasible execution),
168 * then this execution will be aborted, printing the appropriate message. If
169 * the current trace is not yet feasible, the error message will be stashed and
170 * printed if the execution ever becomes feasible.
172 * @param msg Descriptive message for the bug (do not include newline char)
173 * @return True if bug is immediately-feasible
175 bool ModelChecker::assert_bug(const char *msg, ...)
181 vsnprintf(str, sizeof(str), msg, ap);
184 return execution->assert_bug(str);
188 * @brief Assert a bug in the executing program, asserted by a user thread
189 * @see ModelChecker::assert_bug
190 * @param msg Descriptive message for the bug (do not include newline char)
192 void ModelChecker::assert_user_bug(const char *msg)
194 /* If feasible bug, bail out now */
196 switch_to_master(NULL);
199 /** @brief Print bug report listing for this execution (if any bugs exist) */
200 void ModelChecker::print_bugs() const
202 if (execution->have_bug_reports()) {
203 SnapVector<bug_message *> *bugs = execution->get_bugs();
205 model_print("Bug report: %zu bug%s detected\n",
207 bugs->size() > 1 ? "s" : "");
208 for (unsigned int i = 0; i < bugs->size(); i++)
214 * @brief Record end-of-execution stats
216 * Must be run when exiting an execution. Records various stats.
217 * @see struct execution_stats
219 void ModelChecker::record_stats()
222 if (!execution->isfeasibleprefix())
223 stats.num_infeasible++;
224 else if (execution->have_bug_reports())
225 stats.num_buggy_executions++;
226 else if (execution->is_complete_execution())
227 stats.num_complete++;
229 stats.num_redundant++;
232 * @todo We can violate this ASSERT() when fairness/sleep sets
233 * conflict to cause an execution to terminate, e.g. with:
234 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
236 //ASSERT(scheduler->all_threads_sleeping());
240 /** @brief Print execution stats */
241 void ModelChecker::print_stats() const
243 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
244 model_print("Number of redundant executions: %d\n", stats.num_redundant);
245 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
246 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
247 model_print("Total executions: %d\n", stats.num_total);
248 model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
252 * @brief End-of-exeuction print
253 * @param printbugs Should any existing bugs be printed?
255 void ModelChecker::print_execution(bool printbugs) const
257 print_program_output();
259 if (params.verbose) {
260 model_print("Earliest divergence point since last feasible execution:\n");
261 if (earliest_diverge)
262 earliest_diverge->print();
264 model_print("(Not set)\n");
270 /* Don't print invalid bugs */
275 execution->print_summary();
279 * Queries the model-checker for more executions to explore and, if one
280 * exists, resets the model-checker state to execute a new execution.
282 * @return If there are more executions to explore, return true. Otherwise,
285 bool ModelChecker::next_execution()
288 /* Is this execution a feasible execution that's worth bug-checking? */
289 bool complete = execution->isfeasibleprefix() &&
290 (execution->is_complete_execution() ||
291 execution->have_bug_reports());
293 /* End-of-execution bug checks */
295 if (execution->is_deadlocked())
296 assert_bug("Deadlock detected");
299 run_trace_analyses();
305 if (params.verbose || (complete && execution->have_bug_reports()))
306 print_execution(complete);
308 clear_program_output();
311 earliest_diverge = NULL;
313 if ((diverge = execution->get_next_backtrack()) == NULL)
317 model_print("Next execution will diverge at:\n");
323 reset_to_initial_state();
327 /** @brief Run trace analyses on complete trace */
328 void ModelChecker::run_trace_analyses() {
329 for (unsigned int i = 0; i < trace_analyses.size(); i++)
330 trace_analyses[i]->analyze(execution->get_action_trace());
334 * @brief Get a Thread reference by its ID
335 * @param tid The Thread's ID
336 * @return A Thread reference
338 Thread * ModelChecker::get_thread(thread_id_t tid) const
340 return execution->get_thread(tid);
344 * @brief Get a reference to the Thread in which a ModelAction was executed
345 * @param act The ModelAction
346 * @return A Thread reference
348 Thread * ModelChecker::get_thread(const ModelAction *act) const
350 return execution->get_thread(act);
354 * @brief Check if a Thread is currently enabled
355 * @param t The Thread to check
356 * @return True if the Thread is currently enabled
358 bool ModelChecker::is_enabled(Thread *t) const
360 return scheduler->is_enabled(t);
364 * @brief Check if a Thread is currently enabled
365 * @param tid The ID of the Thread to check
366 * @return True if the Thread is currently enabled
368 bool ModelChecker::is_enabled(thread_id_t tid) const
370 return scheduler->is_enabled(tid);
374 * Switch from a model-checker context to a user-thread context. This is the
375 * complement of ModelChecker::switch_to_master and must be called from the
376 * model-checker context
378 * @param thread The user-thread to switch to
380 void ModelChecker::switch_from_master(Thread *thread)
382 scheduler->set_current_thread(thread);
383 Thread::swap(&system_context, thread);
387 * Switch from a user-context to the "master thread" context (a.k.a. system
388 * context). This switch is made with the intention of exploring a particular
389 * model-checking action (described by a ModelAction object). Must be called
390 * from a user-thread context.
392 * @param act The current action that will be explored. May be NULL only if
393 * trace is exiting via an assertion (see ModelExecution::set_assert and
394 * ModelExecution::has_asserted).
395 * @return Return the value returned by the current action
397 uint64_t ModelChecker::switch_to_master(ModelAction *act)
400 Thread *old = thread_current();
401 scheduler->set_current_thread(NULL);
402 ASSERT(!old->get_pending());
403 old->set_pending(act);
404 if (Thread::swap(old, &system_context) < 0) {
405 perror("swap threads");
408 return old->get_return_value();
411 /** Wrapper to run the user's main function, with appropriate arguments */
412 void user_main_wrapper(void *)
414 user_main(model->params.argc, model->params.argv);
417 bool ModelChecker::should_terminate_execution()
419 /* Infeasible -> don't take any more steps */
420 if (execution->is_infeasible())
422 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
423 execution->set_assert();
427 if (execution->too_many_steps())
432 /** @brief Run ModelChecker for the user program */
433 void ModelChecker::run()
437 Thread *t = new Thread(execution->get_next_id(), &user_thread, &user_main_wrapper, NULL, NULL);
438 execution->add_thread(t);
442 * Stash next pending action(s) for thread(s). There
443 * should only need to stash one thread's action--the
444 * thread which just took a step--plus the first step
445 * for any newly-created thread
447 for (unsigned int i = 0; i < get_num_threads(); i++) {
448 thread_id_t tid = int_to_id(i);
449 Thread *thr = get_thread(tid);
450 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
451 switch_from_master(thr);
452 if (thr->is_waiting_on(thr))
453 assert_bug("Deadlock detected (thread %u)", i);
457 /* Don't schedule threads which should be disabled */
458 for (unsigned int i = 0; i < get_num_threads(); i++) {
459 Thread *th = get_thread(int_to_id(i));
460 ModelAction *act = th->get_pending();
461 if (act && is_enabled(th) && !execution->check_action_enabled(act)) {
462 scheduler->sleep(th);
466 /* Catch assertions from prior take_step or from
467 * between-ModelAction bugs (e.g., data races) */
468 if (execution->has_asserted())
472 t = get_next_thread();
473 if (!t || t->is_model_thread())
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());
482 } while (next_execution());
484 execution->fixup_release_sequences();
486 model_print("******* Model-checking complete: *******\n");