11 #include "snapshot-interface.h"
14 #include "threads-model.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
19 #include "bugmessage.h"
23 ModelChecker *model = NULL;
25 void placeholder(void *) {
31 #define SIGSTACKSIZE 65536
32 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
34 model_print("Segmentation fault at %p\n", si->si_addr);
35 model_print("For debugging, place breakpoint at: %s:%d\n",
37 print_trace(); // Trace printing may cause dynamic memory allocation
42 void install_handler() {
44 ss.ss_sp = model_malloc(SIGSTACKSIZE);
45 ss.ss_size = SIGSTACKSIZE;
47 sigaltstack(&ss, NULL);
49 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
50 sigemptyset(&sa.sa_mask);
51 sa.sa_sigaction = mprot_handle_pf;
53 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
54 perror("sigaction(SIGSEGV)");
60 /** @brief Constructor */
61 ModelChecker::ModelChecker() :
62 /* Initialize default scheduler */
64 scheduler(new Scheduler()),
65 history(new ModelHistory()),
66 execution(new ModelExecution(this, scheduler)),
71 model_print("C11Tester\n"
72 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
73 "Distributed under the GPLv2\n"
74 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
75 memset(&stats,0,sizeof(struct execution_stats));
76 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
78 init_thread->setTLS((char *)get_tls_addr());
80 execution->add_thread(init_thread);
81 scheduler->set_current_thread(init_thread);
83 execution->setParams(¶ms);
84 param_defaults(¶ms);
85 parse_options(¶ms);
87 /* Configure output redirection for the model-checker */
88 install_trace_analyses(get_execution());
92 /** @brief Destructor */
93 ModelChecker::~ModelChecker()
98 /** Method to set parameters */
99 model_params * ModelChecker::getParams() {
104 * Restores user program to initial state and resets all model-checker data
107 void ModelChecker::reset_to_initial_state()
111 * FIXME: if we utilize partial rollback, we will need to free only
112 * those pending actions which were NOT pending before the rollback
115 for (unsigned int i = 0;i < get_num_threads();i++)
116 delete get_thread(int_to_id(i))->get_pending();
118 snapshot_roll_back(snapshot);
121 /** @return the number of user threads created during this execution */
122 unsigned int ModelChecker::get_num_threads() const
124 return execution->get_num_threads();
128 * Must be called from user-thread context (e.g., through the global
129 * thread_current() interface)
131 * @return The currently executing Thread.
133 Thread * ModelChecker::get_current_thread() const
135 return scheduler->get_current_thread();
139 * @brief Choose the next thread to execute.
141 * This function chooses the next thread that should execute. It can enforce
142 * execution replay/backtracking or, if the model-checker has no preference
143 * regarding the next thread (i.e., when exploring a new execution ordering),
144 * we defer to the scheduler.
146 * @return The next chosen thread to run, if any exist. Or else if the current
147 * execution should terminate, return NULL.
149 Thread * ModelChecker::get_next_thread()
153 * Have we completed exploring the preselected path? Then let the
156 return scheduler->select_next_thread();
160 * @brief Assert a bug in the executing program.
162 * Use this function to assert any sort of bug in the user program. If the
163 * current trace is feasible (actually, a prefix of some feasible execution),
164 * then this execution will be aborted, printing the appropriate message. If
165 * the current trace is not yet feasible, the error message will be stashed and
166 * printed if the execution ever becomes feasible.
168 * @param msg Descriptive message for the bug (do not include newline char)
169 * @return True if bug is immediately-feasible
171 void ModelChecker::assert_bug(const char *msg, ...)
177 vsnprintf(str, sizeof(str), msg, ap);
180 execution->assert_bug(str);
184 * @brief Assert a bug in the executing program, asserted by a user thread
185 * @see ModelChecker::assert_bug
186 * @param msg Descriptive message for the bug (do not include newline char)
188 void ModelChecker::assert_user_bug(const char *msg)
190 /* If feasible bug, bail out now */
192 switch_to_master(NULL);
195 /** @brief Print bug report listing for this execution (if any bugs exist) */
196 void ModelChecker::print_bugs() const
198 SnapVector<bug_message *> *bugs = execution->get_bugs();
200 model_print("Bug report: %zu bug%s detected\n",
202 bugs->size() > 1 ? "s" : "");
203 for (unsigned int i = 0;i < bugs->size();i++)
204 (*bugs)[i] -> print();
208 * @brief Record end-of-execution stats
210 * Must be run when exiting an execution. Records various stats.
211 * @see struct execution_stats
213 void ModelChecker::record_stats()
216 if (execution->have_bug_reports())
217 stats.num_buggy_executions ++;
218 else if (execution->is_complete_execution())
219 stats.num_complete ++;
221 //All threads are sleeping
223 * @todo We can violate this ASSERT() when fairness/sleep sets
224 * conflict to cause an execution to terminate, e.g. with:
225 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
227 //ASSERT(scheduler->all_threads_sleeping());
231 /** @brief Print execution stats */
232 void ModelChecker::print_stats() const
234 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
235 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
236 model_print("Total executions: %d\n", stats.num_total);
240 * @brief End-of-exeuction print
241 * @param printbugs Should any existing bugs be printed?
243 void ModelChecker::print_execution(bool printbugs) const
245 model_print("Program output from execution %d:\n",
246 get_execution_number());
247 print_program_output();
249 if (params.verbose >= 3) {
253 /* Don't print invalid bugs */
254 if (printbugs && execution->have_bug_reports()) {
260 execution->print_summary();
264 * Queries the model-checker for more executions to explore and, if one
265 * exists, resets the model-checker state to execute a new execution.
267 * @return If there are more executions to explore, return true. Otherwise,
270 void ModelChecker::finish_execution(bool more_executions)
273 /* Is this execution a feasible execution that's worth bug-checking? */
274 bool complete = (execution->is_complete_execution() ||
275 execution->have_bug_reports());
277 /* End-of-execution bug checks */
279 if (execution->is_deadlocked())
280 assert_bug("Deadlock detected");
282 run_trace_analyses();
287 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
288 print_execution(complete);
290 clear_program_output();
295 reset_to_initial_state();
297 history->set_new_exec_flag();
300 /** @brief Run trace analyses on complete trace */
301 void ModelChecker::run_trace_analyses() {
302 for (unsigned int i = 0;i < trace_analyses.size();i ++)
303 trace_analyses[i] -> analyze(execution->get_action_trace());
307 * @brief Get a Thread reference by its ID
308 * @param tid The Thread's ID
309 * @return A Thread reference
311 Thread * ModelChecker::get_thread(thread_id_t tid) const
313 return execution->get_thread(tid);
317 * @brief Get a reference to the Thread in which a ModelAction was executed
318 * @param act The ModelAction
319 * @return A Thread reference
321 Thread * ModelChecker::get_thread(const ModelAction *act) const
323 return execution->get_thread(act);
327 * Switch from a model-checker context to a user-thread context. This is the
328 * complement of ModelChecker::switch_to_master and must be called from the
329 * model-checker context
331 * @param thread The user-thread to switch to
333 void ModelChecker::switch_from_master(Thread *thread)
335 scheduler->set_current_thread(thread);
336 Thread::swap(&system_context, thread);
340 * Switch from a user-context to the "master thread" context (a.k.a. system
341 * context). This switch is made with the intention of exploring a particular
342 * model-checking action (described by a ModelAction object). Must be called
343 * from a user-thread context.
345 * @param act The current action that will be explored. May be NULL only if
346 * trace is exiting via an assertion (see ModelExecution::set_assert and
347 * ModelExecution::has_asserted).
348 * @return Return the value returned by the current action
350 uint64_t ModelChecker::switch_to_master(ModelAction *act)
353 static bool fork_message_printed = false;
355 if (!fork_message_printed) {
356 model_print("Fork handler or dead thread trying to call into model checker...\n");
357 fork_message_printed = true;
363 Thread *old = thread_current();
364 scheduler->set_current_thread(NULL);
365 ASSERT(!old->get_pending());
367 if (inspect_plugin != NULL) {
368 inspect_plugin->inspectModelAction(act);
371 old->set_pending(act);
372 if (Thread::swap(old, &system_context) < 0) {
373 perror("swap threads");
376 return old->get_return_value();
379 static void runChecker() {
384 void ModelChecker::startChecker() {
385 startExecution(get_system_context(), runChecker);
386 snapshot = take_snapshot();
392 bool ModelChecker::should_terminate_execution()
394 if (execution->have_bug_reports()) {
395 execution->set_assert();
397 } else if (execution->isFinished()) {
403 /** @brief Run ModelChecker for the user program */
404 void ModelChecker::run()
406 //Need to initial random number generator state to avoid resets on rollback
407 char random_state[256];
408 initstate(423121, random_state, sizeof(random_state));
409 modelclock_t checkfree = params.checkthreshold;
410 for(int exec = 0;exec < params.maxexecutions;exec++) {
411 Thread * t = init_thread;
414 /* Check whether we need to free model actions. */
416 if (params.traceminsize != 0 &&
417 execution->get_curr_seq_num() > checkfree) {
418 checkfree += params.checkthreshold;
419 execution->collectActions();
423 * Stash next pending action(s) for thread(s). There
424 * should only need to stash one thread's action--the
425 * thread which just took a step--plus the first step
426 * for any newly-created thread
428 for (unsigned int i = 0;i < get_num_threads();i++) {
429 thread_id_t tid = int_to_id(i);
430 Thread *thr = get_thread(tid);
431 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
432 switch_from_master(thr);
433 if (thr->is_waiting_on(thr))
434 assert_bug("Deadlock detected (thread %u)", i);
438 /* Don't schedule threads which should be disabled */
439 for (unsigned int i = 0;i < get_num_threads();i++) {
440 Thread *th = get_thread(int_to_id(i));
441 ModelAction *act = th->get_pending();
442 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
443 scheduler->sleep(th);
447 for (unsigned int i = 1;i < get_num_threads();i++) {
448 Thread *th = get_thread(int_to_id(i));
449 ModelAction *act = th->get_pending();
450 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ) {
451 if (act->is_write()) {
452 std::memory_order order = act->get_mo();
453 if (order == std::memory_order_relaxed || \
454 order == std::memory_order_release) {
458 } else if (act->get_type() == THREAD_CREATE || \
459 act->get_type() == PTHREAD_CREATE || \
460 act->get_type() == THREAD_START || \
461 act->get_type() == THREAD_FINISH) {
468 /* Catch assertions from prior take_step or from
469 * between-ModelAction bugs (e.g., data races) */
471 if (execution->has_asserted())
474 t = get_next_thread();
475 if (!t || t->is_model_thread())
477 if (t->just_woken_up()) {
478 t->set_wakeup_state(false);
479 t->set_pending(NULL);
481 continue; // Allow this thread to stash the next pending action
484 /* Consume the next action for a Thread */
485 ModelAction *curr = t->get_pending();
486 t->set_pending(NULL);
487 t = execution->take_step(curr);
488 } while (!should_terminate_execution());
489 finish_execution((exec+1) < params.maxexecutions);
490 //restore random number generator state after rollback
491 setstate(random_state);
494 model_print("******* Model-checking complete: *******\n");
497 /* Have the trace analyses dump their output. */
498 for (unsigned int i = 0;i < trace_analyses.size();i++)
499 trace_analyses[i]->finish();
501 /* unlink tmp file created by last child process */
503 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());