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)");
59 void createModelIfNotExist() {
61 snapshot_system_init(100000);
62 model = new ModelChecker();
63 model->startChecker();
67 /** @brief Constructor */
68 ModelChecker::ModelChecker() :
69 /* Initialize default scheduler */
71 scheduler(new Scheduler()),
72 history(new ModelHistory()),
73 execution(new ModelExecution(this, scheduler)),
79 model_print("C11Tester\n"
80 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
81 "Distributed under the GPLv2\n"
82 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
83 memset(&stats,0,sizeof(struct execution_stats));
84 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
86 init_thread->setTLS((char *)get_tls_addr());
88 execution->add_thread(init_thread);
89 scheduler->set_current_thread(init_thread);
91 execution->setParams(¶ms);
92 param_defaults(¶ms);
93 parse_options(¶ms);
95 /* Configure output redirection for the model-checker */
99 /** @brief Destructor */
100 ModelChecker::~ModelChecker()
105 /** Method to set parameters */
106 model_params * ModelChecker::getParams() {
111 * Restores user program to initial state and resets all model-checker data
114 void ModelChecker::reset_to_initial_state()
118 * FIXME: if we utilize partial rollback, we will need to free only
119 * those pending actions which were NOT pending before the rollback
122 for (unsigned int i = 0;i < get_num_threads();i++)
123 delete get_thread(int_to_id(i))->get_pending();
125 snapshot_roll_back(snapshot);
128 /** @return the number of user threads created during this execution */
129 unsigned int ModelChecker::get_num_threads() const
131 return execution->get_num_threads();
135 * Must be called from user-thread context (e.g., through the global
136 * thread_current() interface)
138 * @return The currently executing Thread.
140 Thread * ModelChecker::get_current_thread() const
142 return scheduler->get_current_thread();
146 * Must be called from user-thread context (e.g., through the global
147 * thread_current_id() interface)
149 * @return The id of the currently executing Thread.
151 thread_id_t ModelChecker::get_current_thread_id() const
153 ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
154 return int_to_id(curr_thread_num);
158 * @brief Choose the next thread to execute.
160 * This function chooses the next thread that should execute. It can enforce
161 * execution replay/backtracking or, if the model-checker has no preference
162 * regarding the next thread (i.e., when exploring a new execution ordering),
163 * we defer to the scheduler.
165 * @return The next chosen thread to run, if any exist. Or else if the current
166 * execution should terminate, return NULL.
168 Thread * ModelChecker::get_next_thread()
172 * Have we completed exploring the preselected path? Then let the
175 return scheduler->select_next_thread();
179 * @brief Assert a bug in the executing program.
181 * Use this function to assert any sort of bug in the user program. If the
182 * current trace is feasible (actually, a prefix of some feasible execution),
183 * then this execution will be aborted, printing the appropriate message. If
184 * the current trace is not yet feasible, the error message will be stashed and
185 * printed if the execution ever becomes feasible.
187 * @param msg Descriptive message for the bug (do not include newline char)
188 * @return True if bug is immediately-feasible
190 void ModelChecker::assert_bug(const char *msg, ...)
196 vsnprintf(str, sizeof(str), msg, ap);
199 execution->assert_bug(str);
203 * @brief Assert a bug in the executing program, asserted by a user thread
204 * @see ModelChecker::assert_bug
205 * @param msg Descriptive message for the bug (do not include newline char)
207 void ModelChecker::assert_user_bug(const char *msg)
209 /* If feasible bug, bail out now */
214 /** @brief Print bug report listing for this execution (if any bugs exist) */
215 void ModelChecker::print_bugs() const
217 SnapVector<bug_message *> *bugs = execution->get_bugs();
219 model_print("Bug report: %zu bug%s detected\n",
221 bugs->size() > 1 ? "s" : "");
222 for (unsigned int i = 0;i < bugs->size();i++)
223 (*bugs)[i] -> print();
227 * @brief Record end-of-execution stats
229 * Must be run when exiting an execution. Records various stats.
230 * @see struct execution_stats
232 void ModelChecker::record_stats()
235 if (execution->have_bug_reports())
236 stats.num_buggy_executions ++;
237 else if (execution->is_complete_execution())
238 stats.num_complete ++;
240 //All threads are sleeping
242 * @todo We can violate this ASSERT() when fairness/sleep sets
243 * conflict to cause an execution to terminate, e.g. with:
244 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
246 //ASSERT(scheduler->all_threads_sleeping());
250 /** @brief Print execution stats */
251 void ModelChecker::print_stats() const
253 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
254 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
255 model_print("Total executions: %d\n", stats.num_total);
259 * @brief End-of-exeuction print
260 * @param printbugs Should any existing bugs be printed?
262 void ModelChecker::print_execution(bool printbugs) const
264 model_print("Program output from execution %d:\n",
265 get_execution_number());
266 print_program_output();
268 if (params.verbose >= 3) {
272 /* Don't print invalid bugs */
273 if (printbugs && execution->have_bug_reports()) {
279 execution->print_summary();
283 * Queries the model-checker for more executions to explore and, if one
284 * exists, resets the model-checker state to execute a new execution.
286 * @return If there are more executions to explore, return true. Otherwise,
289 void ModelChecker::finish_execution(bool more_executions)
292 /* Is this execution a feasible execution that's worth bug-checking? */
293 bool complete = (execution->is_complete_execution() ||
294 execution->have_bug_reports());
296 /* End-of-execution bug checks */
298 if (execution->is_deadlocked())
299 assert_bug("Deadlock detected");
301 run_trace_analyses();
306 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
307 print_execution(complete);
309 clear_program_output();
312 history->set_new_exec_flag();
315 reset_to_initial_state();
318 /** @brief Run trace analyses on complete trace */
319 void ModelChecker::run_trace_analyses() {
320 for (unsigned int i = 0;i < trace_analyses.size();i ++)
321 trace_analyses[i] -> analyze(execution->get_action_trace());
325 * @brief Get a Thread reference by its ID
326 * @param tid The Thread's ID
327 * @return A Thread reference
329 Thread * ModelChecker::get_thread(thread_id_t tid) const
331 return execution->get_thread(tid);
335 * @brief Get a reference to the Thread in which a ModelAction was executed
336 * @param act The ModelAction
337 * @return A Thread reference
339 Thread * ModelChecker::get_thread(const ModelAction *act) const
341 return execution->get_thread(act);
344 void ModelChecker::startRunExecution(Thread *old) {
346 if (params.traceminsize != 0 &&
347 execution->get_curr_seq_num() > checkfree) {
348 checkfree += params.checkthreshold;
349 execution->collectActions();
353 Thread *thr = getNextThread(old);
354 if (thr != nullptr) {
355 scheduler->set_current_thread(thr);
357 if (Thread::swap(old, thr) < 0) {
358 perror("swap threads");
364 if (!handleChosenThread(old)) {
370 Thread* ModelChecker::getNextThread(Thread *old)
372 Thread *nextThread = nullptr;
373 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
374 thread_id_t tid = int_to_id(i);
375 Thread *thr = get_thread(tid);
377 if (!thr->is_complete()) {
378 if (!thr->get_pending()) {
383 } else if (thr != old && !thr->is_freed()) {
384 thr->freeResources();
387 ModelAction *act = thr->get_pending();
388 if (act && scheduler->is_enabled(tid)){
389 /* Don't schedule threads which should be disabled */
390 if (!execution->check_action_enabled(act)) {
391 scheduler->sleep(thr);
394 /* Allow pending relaxed/release stores or thread actions to perform first */
395 else if (!chosen_thread) {
396 if (act->is_write()) {
397 std::memory_order order = act->get_mo();
398 if (order == std::memory_order_relaxed || \
399 order == std::memory_order_release) {
402 } else if (act->get_type() == THREAD_CREATE || \
403 act->get_type() == PTHREAD_CREATE || \
404 act->get_type() == THREAD_START || \
405 act->get_type() == THREAD_FINISH) {
414 /* Swap back to system_context and terminate this execution */
415 void ModelChecker::finishRunExecution(Thread *old)
417 scheduler->set_current_thread(NULL);
419 /** Reset curr_thread_num to initial value for next execution. */
422 /** If we have more executions, we won't make it past this call. */
423 finish_execution(execution_number < params.maxexecutions);
426 /** We finished the final execution. Print stuff and exit. */
427 model_print("******* Model-checking complete: *******\n");
430 /* Have the trace analyses dump their output. */
431 for (unsigned int i = 0;i < trace_analyses.size();i++)
432 trace_analyses[i]->finish();
434 /* unlink tmp file created by last child process */
436 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
443 uint64_t ModelChecker::switch_thread(ModelAction *act)
446 static bool fork_message_printed = false;
448 if (!fork_message_printed) {
449 model_print("Fork handler or dead thread trying to call into model checker...\n");
450 fork_message_printed = true;
456 Thread *old = thread_current();
457 old->set_state(THREAD_READY);
459 ASSERT(!old->get_pending());
461 if (inspect_plugin != NULL) {
462 inspect_plugin->inspectModelAction(act);
465 old->set_pending(act);
467 if (old->is_waiting_on(old))
468 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
470 Thread* next = getNextThread(old);
471 if (next != nullptr) {
472 scheduler->set_current_thread(next);
473 if (Thread::swap(old, next) < 0) {
474 perror("swap threads");
478 if (handleChosenThread(old)) {
479 startRunExecution(old);
482 return old->get_return_value();
485 bool ModelChecker::handleChosenThread(Thread *old)
487 if (execution->has_asserted()) {
488 finishRunExecution(old);
491 if (!chosen_thread) {
492 chosen_thread = get_next_thread();
494 if (!chosen_thread) {
495 finishRunExecution(old);
498 if (chosen_thread->just_woken_up()) {
499 chosen_thread->set_wakeup_state(false);
500 chosen_thread->set_pending(NULL);
501 chosen_thread = NULL;
502 // Allow this thread to stash the next pending action
506 // Consume the next action for a Thread
507 ModelAction *curr = chosen_thread->get_pending();
508 chosen_thread->set_pending(NULL);
509 chosen_thread = execution->take_step(curr);
511 if (should_terminate_execution()) {
512 finishRunExecution(old);
519 void ModelChecker::startChecker() {
521 //Need to initial random number generator state to avoid resets on rollback
522 initstate(423121, random_state, sizeof(random_state));
524 snapshot = take_snapshot();
526 //reset random number generator state
527 setstate(random_state);
529 install_trace_analyses(get_execution());
534 bool ModelChecker::should_terminate_execution()
536 if (execution->have_bug_reports()) {
537 execution->set_assert();
539 } else if (execution->isFinished()) {