11 #include "snapshot-interface.h"
14 #include "threads-model.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
19 #include "bugmessage.h"
22 ModelChecker *model = NULL;
24 /** Wrapper to run the user's main function, with appropriate arguments */
25 void user_main_wrapper(void *)
27 user_main(model->params.argc, model->params.argv);
30 /** @brief Constructor */
31 ModelChecker::ModelChecker() :
32 /* Initialize default scheduler */
35 scheduler(new Scheduler()),
36 history(new ModelHistory()),
37 execution(new ModelExecution(this, scheduler)),
42 memset(&stats,0,sizeof(struct execution_stats));
43 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &user_main_wrapper, NULL, NULL);
45 init_thread->setTLS((char *)get_tls_addr());
47 execution->add_thread(init_thread);
48 scheduler->set_current_thread(init_thread);
49 execution->setParams(¶ms);
50 param_defaults(¶ms);
54 /** @brief Destructor */
55 ModelChecker::~ModelChecker()
60 /** Method to set parameters */
61 model_params * ModelChecker::getParams() {
66 * Restores user program to initial state and resets all model-checker data
69 void ModelChecker::reset_to_initial_state()
73 * FIXME: if we utilize partial rollback, we will need to free only
74 * those pending actions which were NOT pending before the rollback
77 for (unsigned int i = 0;i < get_num_threads();i++)
78 delete get_thread(int_to_id(i))->get_pending();
80 snapshot_backtrack_before(0);
83 /** @return the number of user threads created during this execution */
84 unsigned int ModelChecker::get_num_threads() const
86 return execution->get_num_threads();
90 * Must be called from user-thread context (e.g., through the global
91 * thread_current() interface)
93 * @return The currently executing Thread.
95 Thread * ModelChecker::get_current_thread() const
97 return scheduler->get_current_thread();
101 * @brief Choose the next thread to execute.
103 * This function chooses the next thread that should execute. It can enforce
104 * execution replay/backtracking or, if the model-checker has no preference
105 * regarding the next thread (i.e., when exploring a new execution ordering),
106 * we defer to the scheduler.
108 * @return The next chosen thread to run, if any exist. Or else if the current
109 * execution should terminate, return NULL.
111 Thread * ModelChecker::get_next_thread()
115 * Have we completed exploring the preselected path? Then let the
118 return scheduler->select_next_thread();
122 * @brief Assert a bug in the executing program.
124 * Use this function to assert any sort of bug in the user program. If the
125 * current trace is feasible (actually, a prefix of some feasible execution),
126 * then this execution will be aborted, printing the appropriate message. If
127 * the current trace is not yet feasible, the error message will be stashed and
128 * printed if the execution ever becomes feasible.
130 * @param msg Descriptive message for the bug (do not include newline char)
131 * @return True if bug is immediately-feasible
133 bool ModelChecker::assert_bug(const char *msg, ...)
139 vsnprintf(str, sizeof(str), msg, ap);
142 return execution->assert_bug(str);
146 * @brief Assert a bug in the executing program, asserted by a user thread
147 * @see ModelChecker::assert_bug
148 * @param msg Descriptive message for the bug (do not include newline char)
150 void ModelChecker::assert_user_bug(const char *msg)
152 /* If feasible bug, bail out now */
154 switch_to_master(NULL);
157 /** @brief Print bug report listing for this execution (if any bugs exist) */
158 void ModelChecker::print_bugs() const
160 SnapVector<bug_message *> *bugs = execution->get_bugs();
162 model_print("Bug report: %zu bug%s detected\n",
164 bugs->size() > 1 ? "s" : "");
165 for (unsigned int i = 0;i < bugs->size();i++)
166 (*bugs)[i] -> print();
170 * @brief Record end-of-execution stats
172 * Must be run when exiting an execution. Records various stats.
173 * @see struct execution_stats
175 void ModelChecker::record_stats()
178 if (!execution->isfeasibleprefix())
179 stats.num_infeasible ++;
180 else if (execution->have_bug_reports())
181 stats.num_buggy_executions ++;
182 else if (execution->is_complete_execution())
183 stats.num_complete ++;
185 stats.num_redundant ++;
188 * @todo We can violate this ASSERT() when fairness/sleep sets
189 * conflict to cause an execution to terminate, e.g. with:
190 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
192 //ASSERT(scheduler->all_threads_sleeping());
196 /** @brief Print execution stats */
197 void ModelChecker::print_stats() const
199 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
200 model_print("Number of redundant executions: %d\n", stats.num_redundant);
201 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
202 model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
203 model_print("Total executions: %d\n", stats.num_total);
207 * @brief End-of-exeuction print
208 * @param printbugs Should any existing bugs be printed?
210 void ModelChecker::print_execution(bool printbugs) const
212 model_print("Program output from execution %d:\n",
213 get_execution_number());
214 print_program_output();
216 if (params.verbose >= 3) {
220 /* Don't print invalid bugs */
221 if (printbugs && execution->have_bug_reports()) {
227 execution->print_summary();
231 * Queries the model-checker for more executions to explore and, if one
232 * exists, resets the model-checker state to execute a new execution.
234 * @return If there are more executions to explore, return true. Otherwise,
237 bool ModelChecker::next_execution()
240 /* Is this execution a feasible execution that's worth bug-checking? */
241 bool complete = execution->isfeasibleprefix() &&
242 (execution->is_complete_execution() ||
243 execution->have_bug_reports());
245 /* End-of-execution bug checks */
247 if (execution->is_deadlocked())
248 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();
267 history->set_new_exec_flag();
271 /** @brief Run trace analyses on complete trace */
272 void ModelChecker::run_trace_analyses() {
273 for (unsigned int i = 0;i < trace_analyses.size();i ++)
274 trace_analyses[i] -> analyze(execution->get_action_trace());
278 * @brief Get a Thread reference by its ID
279 * @param tid The Thread's ID
280 * @return A Thread reference
282 Thread * ModelChecker::get_thread(thread_id_t tid) const
284 return execution->get_thread(tid);
288 * @brief Get a reference to the Thread in which a ModelAction was executed
289 * @param act The ModelAction
290 * @return A Thread reference
292 Thread * ModelChecker::get_thread(const ModelAction *act) const
294 return execution->get_thread(act);
298 * Switch from a model-checker context to a user-thread context. This is the
299 * complement of ModelChecker::switch_to_master and must be called from the
300 * model-checker context
302 * @param thread The user-thread to switch to
304 void ModelChecker::switch_from_master(Thread *thread)
306 scheduler->set_current_thread(thread);
307 Thread::swap(&system_context, thread);
311 * Switch from a user-context to the "master thread" context (a.k.a. system
312 * context). This switch is made with the intention of exploring a particular
313 * model-checking action (described by a ModelAction object). Must be called
314 * from a user-thread context.
316 * @param act The current action that will be explored. May be NULL only if
317 * trace is exiting via an assertion (see ModelExecution::set_assert and
318 * ModelExecution::has_asserted).
319 * @return Return the value returned by the current action
321 uint64_t ModelChecker::switch_to_master(ModelAction *act)
324 static bool fork_message_printed = false;
326 if (!fork_message_printed) {
327 model_print("Fork handler or dead thread trying to call into model checker...\n");
328 fork_message_printed = true;
334 Thread *old = thread_current();
335 scheduler->set_current_thread(NULL);
336 ASSERT(!old->get_pending());
338 if (inspect_plugin != NULL) {
339 inspect_plugin->inspectModelAction(act);
342 old->set_pending(act);
343 if (Thread::swap(old, &system_context) < 0) {
344 perror("swap threads");
347 return old->get_return_value();
350 static void runChecker() {
355 void ModelChecker::startChecker() {
356 startExecution(get_system_context(), runChecker);
357 snapshot_stack_init();
361 bool ModelChecker::should_terminate_execution()
363 /* Infeasible -> don't take any more steps */
364 if (execution->is_infeasible())
366 else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
367 execution->set_assert();
369 } else if (execution->isFinished()) {
375 /** @brief Restart ModelChecker upon returning to the run loop of the
377 void ModelChecker::restart()
382 void ModelChecker::do_restart()
384 restart_flag = false;
385 reset_to_initial_state();
386 memset(&stats,0,sizeof(struct execution_stats));
387 execution_number = 1;
390 void ModelChecker::startMainThread() {
391 init_thread->set_state(THREAD_RUNNING);
392 scheduler->set_current_thread(init_thread);
393 main_thread_startup();
396 /** @brief Run ModelChecker for the user program */
397 void ModelChecker::run()
399 //Need to initial random number generator state to avoid resets on rollback
400 char random_state[256];
401 initstate(423121, random_state, sizeof(random_state));
403 for(int exec = 0;exec < params.maxexecutions;exec++) {
404 Thread * t = init_thread;
408 * Stash next pending action(s) for thread(s). There
409 * should only need to stash one thread's action--the
410 * thread which just took a step--plus the first step
411 * for any newly-created thread
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() && !thr->get_pending()) {
417 switch_from_master(thr);
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())
462 if (t->just_woken_up()) {
463 t->set_wakeup_state(false);
464 t->set_pending(NULL);
466 continue; // Allow this thread to stash the next pending action
469 /* Consume the next action for a Thread */
470 ModelAction *curr = t->get_pending();
471 t->set_pending(NULL);
472 t = execution->take_step(curr);
473 } while (!should_terminate_execution());
475 //restore random number generator state after rollback
476 setstate(random_state);
479 model_print("******* Model-checking complete: *******\n");
482 /* Have the trace analyses dump their output. */
483 for (unsigned int i = 0;i < trace_analyses.size();i++)
484 trace_analyses[i]->finish();
486 /* unlink tmp file created by last child process */
488 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());