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()
43 * Restores user program to initial state and resets all model-checker data
46 void ModelChecker::reset_to_initial_state()
48 DEBUG("+++ Resetting to initial state +++\n");
49 node_stack->reset_execution();
52 * FIXME: if we utilize partial rollback, we will need to free only
53 * those pending actions which were NOT pending before the rollback
56 for (unsigned int i = 0; i < get_num_threads(); i++)
57 delete get_thread(int_to_id(i))->get_pending();
59 snapshot_backtrack_before(0);
62 /** @return the number of user threads created during this execution */
63 unsigned int ModelChecker::get_num_threads() const
65 return execution->get_num_threads();
69 * Must be called from user-thread context (e.g., through the global
70 * thread_current() interface)
72 * @return The currently executing Thread.
74 Thread * ModelChecker::get_current_thread() const
76 return scheduler->get_current_thread();
80 * @brief Choose the next thread to execute.
82 * This function chooses the next thread that should execute. It can enforce
83 * execution replay/backtracking or, if the model-checker has no preference
84 * regarding the next thread (i.e., when exploring a new execution ordering),
85 * we defer to the scheduler.
87 * @return The next chosen thread to run, if any exist. Or else if the current
88 * execution should terminate, return NULL.
90 Thread * ModelChecker::get_next_thread()
95 * Have we completed exploring the preselected path? Then let the
99 return scheduler->select_next_thread(node_stack->get_head());
102 /* Else, we are trying to replay an execution */
103 ModelAction *next = node_stack->get_next()->get_action();
105 if (next == diverge) {
106 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
107 earliest_diverge = diverge;
109 Node *nextnode = next->get_node();
110 Node *prevnode = nextnode->get_parent();
111 scheduler->update_sleep_set(prevnode);
113 /* Reached divergence point */
114 if (nextnode->increment_behaviors()) {
115 /* Execute the same thread with a new behavior */
116 tid = next->get_tid();
117 node_stack->pop_restofstack(2);
120 /* Make a different thread execute for next step */
121 scheduler->add_sleep(get_thread(next->get_tid()));
122 tid = prevnode->get_next_backtrack();
123 /* Make sure the backtracked thread isn't sleeping. */
124 node_stack->pop_restofstack(1);
125 if (diverge == earliest_diverge) {
126 earliest_diverge = prevnode->get_action();
129 /* Start the round robin scheduler from this thread id */
130 scheduler->set_scheduler_thread(tid);
131 /* The correct sleep set is in the parent node. */
134 DEBUG("*** Divergence point ***\n");
138 tid = next->get_tid();
140 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
141 ASSERT(tid != THREAD_ID_T_NONE);
142 return get_thread(id_to_int(tid));
146 * We need to know what the next actions of all threads in the sleep
147 * set will be. This method computes them and stores the actions at
148 * the corresponding thread object's pending action.
150 void ModelChecker::execute_sleep_set()
152 for (unsigned int i = 0; i < get_num_threads(); i++) {
153 thread_id_t tid = int_to_id(i);
154 Thread *thr = get_thread(tid);
155 if (scheduler->is_sleep_set(thr) && thr->get_pending()) {
156 thr->get_pending()->set_sleep_flag();
162 * @brief Assert a bug in the executing program.
164 * Use this function to assert any sort of bug in the user program. If the
165 * current trace is feasible (actually, a prefix of some feasible execution),
166 * then this execution will be aborted, printing the appropriate message. If
167 * the current trace is not yet feasible, the error message will be stashed and
168 * printed if the execution ever becomes feasible.
170 * @param msg Descriptive message for the bug (do not include newline char)
171 * @return True if bug is immediately-feasible
173 bool ModelChecker::assert_bug(const char *msg, ...)
179 vsnprintf(str, sizeof(str), msg, ap);
182 return execution->assert_bug(str);
186 * @brief Assert a bug in the executing program, asserted by a user thread
187 * @see ModelChecker::assert_bug
188 * @param msg Descriptive message for the bug (do not include newline char)
190 void ModelChecker::assert_user_bug(const char *msg)
192 /* If feasible bug, bail out now */
194 switch_to_master(NULL);
197 /** @brief Print bug report listing for this execution (if any bugs exist) */
198 void ModelChecker::print_bugs() const
200 SnapVector<bug_message *> *bugs = execution->get_bugs();
202 model_print("Bug report: %zu bug%s detected\n",
204 bugs->size() > 1 ? "s" : "");
205 for (unsigned int i = 0; i < bugs->size(); i++)
210 * @brief Record end-of-execution stats
212 * Must be run when exiting an execution. Records various stats.
213 * @see struct execution_stats
215 void ModelChecker::record_stats()
218 if (!execution->isfeasibleprefix())
219 stats.num_infeasible++;
220 else if (execution->have_bug_reports())
221 stats.num_buggy_executions++;
222 else if (execution->is_complete_execution())
223 stats.num_complete++;
225 stats.num_redundant++;
228 * @todo We can violate this ASSERT() when fairness/sleep sets
229 * conflict to cause an execution to terminate, e.g. with:
230 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
232 //ASSERT(scheduler->all_threads_sleeping());
236 /** @brief Print execution stats */
237 void ModelChecker::print_stats() const
239 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
240 model_print("Number of redundant executions: %d\n", stats.num_redundant);
241 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
242 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
243 model_print("Total executions: %d\n", stats.num_total);
244 model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
248 * @brief End-of-exeuction print
249 * @param printbugs Should any existing bugs be printed?
251 void ModelChecker::print_execution(bool printbugs) const
253 model_print("Program output from execution %d:\n",
254 get_execution_number());
255 print_program_output();
257 if (params.verbose >= 2) {
258 model_print("\nEarliest divergence point since last feasible execution:\n");
259 if (earliest_diverge)
260 earliest_diverge->print();
262 model_print("(Not set)\n");
268 /* Don't print invalid bugs */
269 if (printbugs && execution->have_bug_reports()) {
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 * Switch from a model-checker context to a user-thread context. This is the
355 * complement of ModelChecker::switch_to_master and must be called from the
356 * model-checker context
358 * @param thread The user-thread to switch to
360 void ModelChecker::switch_from_master(Thread *thread)
362 scheduler->set_current_thread(thread);
363 Thread::swap(&system_context, thread);
367 * Switch from a user-context to the "master thread" context (a.k.a. system
368 * context). This switch is made with the intention of exploring a particular
369 * model-checking action (described by a ModelAction object). Must be called
370 * from a user-thread context.
372 * @param act The current action that will be explored. May be NULL only if
373 * trace is exiting via an assertion (see ModelExecution::set_assert and
374 * ModelExecution::has_asserted).
375 * @return Return the value returned by the current action
377 uint64_t ModelChecker::switch_to_master(ModelAction *act)
380 Thread *old = thread_current();
381 scheduler->set_current_thread(NULL);
382 ASSERT(!old->get_pending());
383 old->set_pending(act);
384 if (Thread::swap(old, &system_context) < 0) {
385 perror("swap threads");
388 return old->get_return_value();
391 /** Wrapper to run the user's main function, with appropriate arguments */
392 void user_main_wrapper(void *)
394 user_main(model->params.argc, model->params.argv);
397 bool ModelChecker::should_terminate_execution()
399 /* Infeasible -> don't take any more steps */
400 if (execution->is_infeasible())
402 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
403 execution->set_assert();
407 if (execution->too_many_steps())
412 /** @brief Run ModelChecker for the user program */
413 void ModelChecker::run()
417 Thread *t = new Thread(execution->get_next_id(), &user_thread, &user_main_wrapper, NULL, NULL);
418 execution->add_thread(t);
422 * Stash next pending action(s) for thread(s). There
423 * should only need to stash one thread's action--the
424 * thread which just took a step--plus the first step
425 * for any newly-created thread
427 for (unsigned int i = 0; i < get_num_threads(); i++) {
428 thread_id_t tid = int_to_id(i);
429 Thread *thr = get_thread(tid);
430 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
431 switch_from_master(thr);
432 if (thr->is_waiting_on(thr))
433 assert_bug("Deadlock detected (thread %u)", i);
437 /* Don't schedule threads which should be disabled */
438 for (unsigned int i = 0; i < get_num_threads(); i++) {
439 Thread *th = get_thread(int_to_id(i));
440 ModelAction *act = th->get_pending();
441 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
442 scheduler->sleep(th);
446 /* Catch assertions from prior take_step or from
447 * between-ModelAction bugs (e.g., data races) */
448 if (execution->has_asserted())
452 t = get_next_thread();
453 if (!t || t->is_model_thread())
456 /* Consume the next action for a Thread */
457 ModelAction *curr = t->get_pending();
458 t->set_pending(NULL);
459 t = execution->take_step(curr);
460 } while (!should_terminate_execution());
462 } while (next_execution());
464 execution->fixup_release_sequences();
466 model_print("******* Model-checking complete: *******\n");
469 /* Have the trace analyses dump their output. */
470 for (unsigned int i = 0; i < trace_analyses.size(); i++)
471 trace_analyses[i]->finish();