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);
51 parse_options(¶ms);
55 /** @brief Destructor */
56 ModelChecker::~ModelChecker()
61 /** Method to set parameters */
62 model_params * ModelChecker::getParams() {
67 * Restores user program to initial state and resets all model-checker data
70 void ModelChecker::reset_to_initial_state()
74 * FIXME: if we utilize partial rollback, we will need to free only
75 * those pending actions which were NOT pending before the rollback
78 for (unsigned int i = 0;i < get_num_threads();i++)
79 delete get_thread(int_to_id(i))->get_pending();
81 snapshot_backtrack_before(0);
84 /** @return the number of user threads created during this execution */
85 unsigned int ModelChecker::get_num_threads() const
87 return execution->get_num_threads();
91 * Must be called from user-thread context (e.g., through the global
92 * thread_current() interface)
94 * @return The currently executing Thread.
96 Thread * ModelChecker::get_current_thread() const
98 return scheduler->get_current_thread();
102 * @brief Choose the next thread to execute.
104 * This function chooses the next thread that should execute. It can enforce
105 * execution replay/backtracking or, if the model-checker has no preference
106 * regarding the next thread (i.e., when exploring a new execution ordering),
107 * we defer to the scheduler.
109 * @return The next chosen thread to run, if any exist. Or else if the current
110 * execution should terminate, return NULL.
112 Thread * ModelChecker::get_next_thread()
116 * Have we completed exploring the preselected path? Then let the
119 return scheduler->select_next_thread();
123 * @brief Assert a bug in the executing program.
125 * Use this function to assert any sort of bug in the user program. If the
126 * current trace is feasible (actually, a prefix of some feasible execution),
127 * then this execution will be aborted, printing the appropriate message. If
128 * the current trace is not yet feasible, the error message will be stashed and
129 * printed if the execution ever becomes feasible.
131 * @param msg Descriptive message for the bug (do not include newline char)
132 * @return True if bug is immediately-feasible
134 void ModelChecker::assert_bug(const char *msg, ...)
140 vsnprintf(str, sizeof(str), msg, ap);
143 execution->assert_bug(str);
147 * @brief Assert a bug in the executing program, asserted by a user thread
148 * @see ModelChecker::assert_bug
149 * @param msg Descriptive message for the bug (do not include newline char)
151 void ModelChecker::assert_user_bug(const char *msg)
153 /* If feasible bug, bail out now */
155 switch_to_master(NULL);
158 /** @brief Print bug report listing for this execution (if any bugs exist) */
159 void ModelChecker::print_bugs() const
161 SnapVector<bug_message *> *bugs = execution->get_bugs();
163 model_print("Bug report: %zu bug%s detected\n",
165 bugs->size() > 1 ? "s" : "");
166 for (unsigned int i = 0;i < bugs->size();i++)
167 (*bugs)[i] -> print();
171 * @brief Record end-of-execution stats
173 * Must be run when exiting an execution. Records various stats.
174 * @see struct execution_stats
176 void ModelChecker::record_stats()
179 if (execution->have_bug_reports())
180 stats.num_buggy_executions ++;
181 else if (execution->is_complete_execution())
182 stats.num_complete ++;
184 //All threads are sleeping
186 * @todo We can violate this ASSERT() when fairness/sleep sets
187 * conflict to cause an execution to terminate, e.g. with:
188 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
190 //ASSERT(scheduler->all_threads_sleeping());
194 /** @brief Print execution stats */
195 void ModelChecker::print_stats() const
197 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
198 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
199 model_print("Total executions: %d\n", stats.num_total);
203 * @brief End-of-exeuction print
204 * @param printbugs Should any existing bugs be printed?
206 void ModelChecker::print_execution(bool printbugs) const
208 model_print("Program output from execution %d:\n",
209 get_execution_number());
210 print_program_output();
212 if (params.verbose >= 3) {
216 /* Don't print invalid bugs */
217 if (printbugs && execution->have_bug_reports()) {
223 execution->print_summary();
227 * Queries the model-checker for more executions to explore and, if one
228 * exists, resets the model-checker state to execute a new execution.
230 * @return If there are more executions to explore, return true. Otherwise,
233 bool ModelChecker::next_execution()
236 /* Is this execution a feasible execution that's worth bug-checking? */
237 bool complete = (execution->is_complete_execution() ||
238 execution->have_bug_reports());
240 /* End-of-execution bug checks */
242 if (execution->is_deadlocked())
243 assert_bug("Deadlock detected");
245 run_trace_analyses();
250 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
251 print_execution(complete);
253 clear_program_output();
261 reset_to_initial_state();
262 history->set_new_exec_flag();
266 /** @brief Run trace analyses on complete trace */
267 void ModelChecker::run_trace_analyses() {
268 for (unsigned int i = 0;i < trace_analyses.size();i ++)
269 trace_analyses[i] -> analyze(execution->get_action_trace());
273 * @brief Get a Thread reference by its ID
274 * @param tid The Thread's ID
275 * @return A Thread reference
277 Thread * ModelChecker::get_thread(thread_id_t tid) const
279 return execution->get_thread(tid);
283 * @brief Get a reference to the Thread in which a ModelAction was executed
284 * @param act The ModelAction
285 * @return A Thread reference
287 Thread * ModelChecker::get_thread(const ModelAction *act) const
289 return execution->get_thread(act);
293 * Switch from a model-checker context to a user-thread context. This is the
294 * complement of ModelChecker::switch_to_master and must be called from the
295 * model-checker context
297 * @param thread The user-thread to switch to
299 void ModelChecker::switch_from_master(Thread *thread)
301 scheduler->set_current_thread(thread);
302 Thread::swap(&system_context, thread);
306 * Switch from a user-context to the "master thread" context (a.k.a. system
307 * context). This switch is made with the intention of exploring a particular
308 * model-checking action (described by a ModelAction object). Must be called
309 * from a user-thread context.
311 * @param act The current action that will be explored. May be NULL only if
312 * trace is exiting via an assertion (see ModelExecution::set_assert and
313 * ModelExecution::has_asserted).
314 * @return Return the value returned by the current action
316 uint64_t ModelChecker::switch_to_master(ModelAction *act)
319 static bool fork_message_printed = false;
321 if (!fork_message_printed) {
322 model_print("Fork handler or dead thread trying to call into model checker...\n");
323 fork_message_printed = true;
329 Thread *old = thread_current();
330 scheduler->set_current_thread(NULL);
331 ASSERT(!old->get_pending());
333 if (inspect_plugin != NULL) {
334 inspect_plugin->inspectModelAction(act);
337 old->set_pending(act);
338 if (Thread::swap(old, &system_context) < 0) {
339 perror("swap threads");
342 return old->get_return_value();
345 static void runChecker() {
350 void ModelChecker::startChecker() {
351 startExecution(get_system_context(), runChecker);
352 snapshot_stack_init();
356 bool ModelChecker::should_terminate_execution()
358 if (execution->have_bug_reports()) {
359 execution->set_assert();
361 } else if (execution->isFinished()) {
367 /** @brief Restart ModelChecker upon returning to the run loop of the
369 void ModelChecker::restart()
374 void ModelChecker::do_restart()
376 restart_flag = false;
377 reset_to_initial_state();
378 memset(&stats,0,sizeof(struct execution_stats));
379 execution_number = 1;
382 void ModelChecker::startMainThread() {
383 init_thread->set_state(THREAD_RUNNING);
384 scheduler->set_current_thread(init_thread);
385 main_thread_startup();
388 /** @brief Run ModelChecker for the user program */
389 void ModelChecker::run()
391 //Need to initial random number generator state to avoid resets on rollback
392 char random_state[256];
393 initstate(423121, random_state, sizeof(random_state));
395 for(int exec = 0;exec < params.maxexecutions;exec++) {
396 Thread * t = init_thread;
400 * Stash next pending action(s) for thread(s). There
401 * should only need to stash one thread's action--the
402 * thread which just took a step--plus the first step
403 * for any newly-created thread
405 for (unsigned int i = 0;i < get_num_threads();i++) {
406 thread_id_t tid = int_to_id(i);
407 Thread *thr = get_thread(tid);
408 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
409 switch_from_master(thr);
410 if (thr->is_waiting_on(thr))
411 assert_bug("Deadlock detected (thread %u)", i);
415 /* Don't schedule threads which should be disabled */
416 for (unsigned int i = 0;i < get_num_threads();i++) {
417 Thread *th = get_thread(int_to_id(i));
418 ModelAction *act = th->get_pending();
419 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
420 scheduler->sleep(th);
424 for (unsigned int i = 1;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) && (th->get_state() != THREAD_BLOCKED) ) {
428 if (act->is_write()) {
429 std::memory_order order = act->get_mo();
430 if (order == std::memory_order_relaxed || \
431 order == std::memory_order_release) {
435 } else if (act->get_type() == THREAD_CREATE || \
436 act->get_type() == PTHREAD_CREATE || \
437 act->get_type() == THREAD_START || \
438 act->get_type() == THREAD_FINISH) {
445 /* Catch assertions from prior take_step or from
446 * between-ModelAction bugs (e.g., data races) */
448 if (execution->has_asserted())
451 t = get_next_thread();
452 if (!t || t->is_model_thread())
454 if (t->just_woken_up()) {
455 t->set_wakeup_state(false);
456 t->set_pending(NULL);
458 continue; // Allow this thread to stash the next pending action
461 /* Consume the next action for a Thread */
462 ModelAction *curr = t->get_pending();
463 t->set_pending(NULL);
464 t = execution->take_step(curr);
465 } while (!should_terminate_execution());
467 //restore random number generator state after rollback
468 setstate(random_state);
471 model_print("******* Model-checking complete: *******\n");
474 /* Have the trace analyses dump their output. */
475 for (unsigned int i = 0;i < trace_analyses.size();i++)
476 trace_analyses[i]->finish();
478 /* unlink tmp file created by last child process */
480 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());