11 #include "snapshot-interface.h"
14 #include "threads-model.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
18 #include "bugmessage.h"
22 /** @brief Constructor */
23 ModelChecker::ModelChecker(struct model_params params) :
24 /* Initialize default scheduler */
28 scheduler(new Scheduler()),
29 node_stack(new NodeStack()),
30 execution(new ModelExecution(this, &this->params, scheduler, node_stack)),
33 earliest_diverge(NULL),
37 memset(&stats,0,sizeof(struct execution_stats));
40 /** @brief Destructor */
41 ModelChecker::~ModelChecker()
48 * Restores user program to initial state and resets all model-checker data
51 void ModelChecker::reset_to_initial_state()
53 DEBUG("+++ Resetting to initial state +++\n");
54 node_stack->reset_execution();
57 * FIXME: if we utilize partial rollback, we will need to free only
58 * those pending actions which were NOT pending before the rollback
61 for (unsigned int i = 0; i < get_num_threads(); i++)
62 delete get_thread(int_to_id(i))->get_pending();
64 snapshot_backtrack_before(0);
67 /** @return the number of user threads created during this execution */
68 unsigned int ModelChecker::get_num_threads() const
70 return execution->get_num_threads();
74 * Must be called from user-thread context (e.g., through the global
75 * thread_current() interface)
77 * @return The currently executing Thread.
79 Thread * ModelChecker::get_current_thread() const
81 return scheduler->get_current_thread();
85 * @brief Choose the next thread to execute.
87 * This function chooses the next thread that should execute. It can enforce
88 * execution replay/backtracking or, if the model-checker has no preference
89 * regarding the next thread (i.e., when exploring a new execution ordering),
90 * we defer to the scheduler.
92 * @return The next chosen thread to run, if any exist. Or else if the current
93 * execution should terminate, return NULL.
95 Thread * ModelChecker::get_next_thread()
100 * Have we completed exploring the preselected path? Then let the
104 return scheduler->select_next_thread(node_stack->get_head());
107 /* Else, we are trying to replay an execution */
108 ModelAction *next = node_stack->get_next()->get_action();
110 if (next == diverge) {
111 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
112 earliest_diverge = diverge;
114 Node *nextnode = next->get_node();
115 Node *prevnode = nextnode->get_parent();
116 scheduler->update_sleep_set(prevnode);
118 /* Reached divergence point */
119 if (nextnode->increment_behaviors()) {
120 /* Execute the same thread with a new behavior */
121 tid = next->get_tid();
122 node_stack->pop_restofstack(2);
125 /* Make a different thread execute for next step */
126 scheduler->add_sleep(get_thread(next->get_tid()));
127 tid = prevnode->get_next_backtrack();
128 /* Make sure the backtracked thread isn't sleeping. */
129 node_stack->pop_restofstack(1);
130 if (diverge == earliest_diverge) {
131 earliest_diverge = prevnode->get_action();
134 /* Start the round robin scheduler from this thread id */
135 scheduler->set_scheduler_thread(tid);
136 /* The correct sleep set is in the parent node. */
139 DEBUG("*** Divergence point ***\n");
143 tid = next->get_tid();
145 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
146 ASSERT(tid != THREAD_ID_T_NONE);
147 return get_thread(id_to_int(tid));
151 * We need to know what the next actions of all threads in the sleep
152 * set will be. This method computes them and stores the actions at
153 * the corresponding thread object's pending action.
155 void ModelChecker::execute_sleep_set()
157 for (unsigned int i = 0; i < get_num_threads(); i++) {
158 thread_id_t tid = int_to_id(i);
159 Thread *thr = get_thread(tid);
160 if (scheduler->is_sleep_set(thr) && thr->get_pending()) {
161 thr->get_pending()->set_sleep_flag();
167 * @brief Assert a bug in the executing program.
169 * Use this function to assert any sort of bug in the user program. If the
170 * current trace is feasible (actually, a prefix of some feasible execution),
171 * then this execution will be aborted, printing the appropriate message. If
172 * the current trace is not yet feasible, the error message will be stashed and
173 * printed if the execution ever becomes feasible.
175 * @param msg Descriptive message for the bug (do not include newline char)
176 * @return True if bug is immediately-feasible
178 bool ModelChecker::assert_bug(const char *msg, ...)
184 vsnprintf(str, sizeof(str), msg, ap);
187 return execution->assert_bug(str);
191 * @brief Assert a bug in the executing program, asserted by a user thread
192 * @see ModelChecker::assert_bug
193 * @param msg Descriptive message for the bug (do not include newline char)
195 void ModelChecker::assert_user_bug(const char *msg)
197 /* If feasible bug, bail out now */
199 switch_to_master(NULL);
202 /** @brief Print bug report listing for this execution (if any bugs exist) */
203 void ModelChecker::print_bugs() const
205 SnapVector<bug_message *> *bugs = execution->get_bugs();
207 model_print("Bug report: %zu bug%s detected\n",
209 bugs->size() > 1 ? "s" : "");
210 for (unsigned int i = 0; i < bugs->size(); i++)
215 * @brief Record end-of-execution stats
217 * Must be run when exiting an execution. Records various stats.
218 * @see struct execution_stats
220 void ModelChecker::record_stats()
223 if (!execution->isfeasibleprefix())
224 stats.num_infeasible++;
225 else if (execution->have_bug_reports())
226 stats.num_buggy_executions++;
227 else if (execution->is_complete_execution())
228 stats.num_complete++;
230 stats.num_redundant++;
233 * @todo We can violate this ASSERT() when fairness/sleep sets
234 * conflict to cause an execution to terminate, e.g. with:
235 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
237 //ASSERT(scheduler->all_threads_sleeping());
241 /** @brief Print execution stats */
242 void ModelChecker::print_stats() const
244 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
245 model_print("Number of redundant executions: %d\n", stats.num_redundant);
246 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
247 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
248 model_print("Total executions: %d\n", stats.num_total);
250 model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
254 * @brief End-of-exeuction print
255 * @param printbugs Should any existing bugs be printed?
257 void ModelChecker::print_execution(bool printbugs) const
259 model_print("Program output from execution %d:\n",
260 get_execution_number());
261 print_program_output();
263 if (params.verbose >= 3) {
264 model_print("\nEarliest divergence point since last feasible execution:\n");
265 if (earliest_diverge)
266 earliest_diverge->print();
268 model_print("(Not set)\n");
274 /* Don't print invalid bugs */
275 if (printbugs && execution->have_bug_reports()) {
281 execution->print_summary();
285 * Queries the model-checker for more executions to explore and, if one
286 * exists, resets the model-checker state to execute a new execution.
288 * @return If there are more executions to explore, return true. Otherwise,
291 bool ModelChecker::next_execution()
294 /* Is this execution a feasible execution that's worth bug-checking? */
295 bool complete = execution->isfeasibleprefix() &&
296 (execution->is_complete_execution() ||
297 execution->have_bug_reports());
299 /* End-of-execution bug checks */
301 if (execution->is_deadlocked())
302 assert_bug("Deadlock detected");
305 run_trace_analyses();
306 } else if (inspect_plugin && !execution->is_complete_execution() &&
307 (execution->too_many_steps())) {
308 inspect_plugin->analyze(execution->get_action_trace());
314 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
315 print_execution(complete);
317 clear_program_output();
320 earliest_diverge = NULL;
330 if ((diverge = execution->get_next_backtrack()) == NULL)
334 model_print("Next execution will diverge at:\n");
340 if (params.maxexecutions != 0 && stats.num_complete >= params.maxexecutions)
343 reset_to_initial_state();
347 /** @brief Run trace analyses on complete trace */
348 void ModelChecker::run_trace_analyses() {
349 for (unsigned int i = 0; i < trace_analyses.size(); i++)
350 trace_analyses[i]->analyze(execution->get_action_trace());
354 * @brief Get a Thread reference by its ID
355 * @param tid The Thread's ID
356 * @return A Thread reference
358 Thread * ModelChecker::get_thread(thread_id_t tid) const
360 return execution->get_thread(tid);
364 * @brief Get a reference to the Thread in which a ModelAction was executed
365 * @param act The ModelAction
366 * @return A Thread reference
368 Thread * ModelChecker::get_thread(const ModelAction *act) const
370 return execution->get_thread(act);
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 if (inspect_plugin != NULL) {
404 inspect_plugin->inspectModelAction(act);
406 old->set_pending(act);
407 if (Thread::swap(old, &system_context) < 0) {
408 perror("swap threads");
411 return old->get_return_value();
414 /** Wrapper to run the user's main function, with appropriate arguments */
415 void user_main_wrapper(void *)
417 user_main(model->params.argc, model->params.argv);
420 bool ModelChecker::should_terminate_execution()
422 /* Infeasible -> don't take any more steps */
423 if (execution->is_infeasible())
425 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
426 execution->set_assert();
430 if (execution->too_many_steps())
435 /** @brief Exit ModelChecker upon returning to the run loop of the
437 void ModelChecker::exit_model_checker()
442 /** @brief Restart ModelChecker upon returning to the run loop of the
444 void ModelChecker::restart()
449 void ModelChecker::do_restart()
451 restart_flag = false;
453 earliest_diverge = NULL;
454 reset_to_initial_state();
455 node_stack->full_reset();
456 memset(&stats,0,sizeof(struct execution_stats));
457 execution_number = 1;
460 /** @brief Run ModelChecker for the user program */
461 void ModelChecker::run()
466 Thread *t = new Thread(execution->get_next_id(), &user_thread, &user_main_wrapper, NULL, NULL);
467 execution->add_thread(t);
471 * Stash next pending action(s) for thread(s). There
472 * should only need to stash one thread's action--the
473 * thread which just took a step--plus the first step
474 * for any newly-created thread
476 for (unsigned int i = 0; i < get_num_threads(); i++) {
477 thread_id_t tid = int_to_id(i);
478 Thread *thr = get_thread(tid);
479 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
480 switch_from_master(thr);
481 if (thr->is_waiting_on(thr))
482 assert_bug("Deadlock detected (thread %u)", i);
486 /* Don't schedule threads which should be disabled */
487 for (unsigned int i = 0; i < get_num_threads(); i++) {
488 Thread *th = get_thread(int_to_id(i));
489 ModelAction *act = th->get_pending();
490 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
491 scheduler->sleep(th);
495 /* Catch assertions from prior take_step or from
496 * between-ModelAction bugs (e.g., data races) */
497 if (execution->has_asserted())
501 t = get_next_thread();
502 if (!t || t->is_model_thread())
505 /* Consume the next action for a Thread */
506 ModelAction *curr = t->get_pending();
507 t->set_pending(NULL);
508 t = execution->take_step(curr);
509 } while (!should_terminate_execution());
511 has_next = next_execution();
512 if (inspect_plugin != NULL && !has_next) {
513 inspect_plugin->actionAtModelCheckingFinish();
514 // Check if the inpect plugin set the restart flag
516 model_print("******* Model-checking RESTART: *******\n");
523 execution->fixup_release_sequences();
525 model_print("******* Model-checking complete: *******\n");
528 /* Have the trace analyses dump their output. */
529 for (unsigned int i = 0; i < trace_analyses.size(); i++)
530 trace_analyses[i]->finish();