11 #include "snapshot-interface.h"
14 #include "threads-model.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
18 #include "bugmessage.h"
22 ModelChecker *model = NULL;
25 uint64_t get_nanotime()
27 struct timespec currtime;
28 clock_gettime(CLOCK_MONOTONIC, &currtime);
30 return currtime.tv_nsec;
33 void placeholder(void *) {
39 #define SIGSTACKSIZE 65536
40 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
42 model_print("Segmentation fault at %p\n", si->si_addr);
43 model_print("For debugging, place breakpoint at: %s:%d\n",
45 print_trace(); // Trace printing may cause dynamic memory allocation
50 void install_handler() {
52 ss.ss_sp = model_malloc(SIGSTACKSIZE);
53 ss.ss_size = SIGSTACKSIZE;
55 sigaltstack(&ss, NULL);
57 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
58 sigemptyset(&sa.sa_mask);
59 sa.sa_sigaction = mprot_handle_pf;
61 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
62 perror("sigaction(SIGSEGV)");
67 void createModelIfNotExist() {
70 snapshot_system_init(100000);
71 model = new ModelChecker();
72 model->startChecker();
77 /** @brief Constructor */
78 ModelChecker::ModelChecker() :
79 /* Initialize default scheduler */
81 scheduler(new Scheduler()),
82 execution(new ModelExecution(this, scheduler)),
84 curr_thread_num(MAIN_THREAD_ID),
88 model_print("C11Tester\n"
89 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
90 "Distributed under the GPLv2\n"
91 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
93 real_memset(&stats,0,sizeof(struct execution_stats));
94 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
96 init_thread->setTLS((char *)get_tls_addr());
98 execution->add_thread(init_thread);
99 scheduler->set_current_thread(init_thread);
101 execution->setParams(¶ms);
102 param_defaults(¶ms);
103 parse_options(¶ms);
105 /* Configure output redirection for the model-checker */
109 /** @brief Destructor */
110 ModelChecker::~ModelChecker()
115 /** Method to set parameters */
116 model_params * ModelChecker::getParams() {
121 * Restores user program to initial state and resets all model-checker data
124 void ModelChecker::reset_to_initial_state()
128 * FIXME: if we utilize partial rollback, we will need to free only
129 * those pending actions which were NOT pending before the rollback
132 for (unsigned int i = 0;i < get_num_threads();i++)
133 delete get_thread(int_to_id(i))->get_pending();
135 snapshot_roll_back(snapshot);
138 /** @return the number of user threads created during this execution */
139 unsigned int ModelChecker::get_num_threads() const
141 return execution->get_num_threads();
145 * Must be called from user-thread context (e.g., through the global
146 * thread_current() interface)
148 * @return The currently executing Thread.
150 Thread * ModelChecker::get_current_thread() const
152 return scheduler->get_current_thread();
156 * Must be called from user-thread context (e.g., through the global
157 * thread_current_id() interface)
159 * @return The id of the currently executing Thread.
161 thread_id_t ModelChecker::get_current_thread_id() const
163 ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
164 return int_to_id(curr_thread_num);
168 * @brief Choose the next thread to execute.
170 * This function chooses the next thread that should execute. It can enforce
171 * execution replay/backtracking or, if the model-checker has no preference
172 * regarding the next thread (i.e., when exploring a new execution ordering),
173 * we defer to the scheduler.
175 * @return The next chosen thread to run, if any exist. Or else if the current
176 * execution should terminate, return NULL.
178 Thread * ModelChecker::get_next_thread()
182 * Have we completed exploring the preselected path? Then let the
185 return scheduler->select_next_thread();
189 * @brief Assert a bug in the executing program.
191 * Use this function to assert any sort of bug in the user program. If the
192 * current trace is feasible (actually, a prefix of some feasible execution),
193 * then this execution will be aborted, printing the appropriate message. If
194 * the current trace is not yet feasible, the error message will be stashed and
195 * printed if the execution ever becomes feasible.
197 * @param msg Descriptive message for the bug (do not include newline char)
198 * @return True if bug is immediately-feasible
200 void ModelChecker::assert_bug(const char *msg, ...)
206 vsnprintf(str, sizeof(str), msg, ap);
209 execution->assert_bug(str);
213 * @brief Assert a bug in the executing program, asserted by a user thread
214 * @see ModelChecker::assert_bug
215 * @param msg Descriptive message for the bug (do not include newline char)
217 void ModelChecker::assert_user_bug(const char *msg)
219 /* If feasible bug, bail out now */
224 /** @brief Print bug report listing for this execution (if any bugs exist) */
225 void ModelChecker::print_bugs() const
227 SnapVector<bug_message *> *bugs = execution->get_bugs();
229 model_print("Bug report: %zu bug%s detected\n",
231 bugs->size() > 1 ? "s" : "");
232 for (unsigned int i = 0;i < bugs->size();i++)
233 (*bugs)[i] -> print();
237 * @brief Record end-of-execution stats
239 * Must be run when exiting an execution. Records various stats.
240 * @see struct execution_stats
242 void ModelChecker::record_stats()
245 if (execution->have_bug_reports())
246 stats.num_buggy_executions ++;
247 else if (execution->is_complete_execution())
248 stats.num_complete ++;
250 //All threads are sleeping
252 * @todo We can violate this ASSERT() when fairness/sleep sets
253 * conflict to cause an execution to terminate, e.g. with:
254 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
256 //ASSERT(scheduler->all_threads_sleeping());
260 /** @brief Print execution stats */
261 void ModelChecker::print_stats() const
263 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
264 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
265 model_print("Total executions: %d\n", stats.num_total);
269 * @brief End-of-exeuction print
270 * @param printbugs Should any existing bugs be printed?
272 void ModelChecker::print_execution(bool printbugs) const
274 model_print("Program output from execution %d:\n",
275 get_execution_number());
276 print_program_output();
278 if (params.verbose >= 3) {
282 /* Don't print invalid bugs */
283 if (printbugs && execution->have_bug_reports()) {
290 execution->print_summary();
295 * Queries the model-checker for more executions to explore and, if one
296 * exists, resets the model-checker state to execute a new execution.
298 * @return If there are more executions to explore, return true. Otherwise,
301 void ModelChecker::finish_execution(bool more_executions)
304 /* Is this execution a feasible execution that's worth bug-checking? */
305 bool complete = (execution->is_complete_execution() ||
306 execution->have_bug_reports());
308 /* End-of-execution bug checks */
310 if (execution->is_deadlocked())
311 assert_bug("Deadlock detected");
313 run_trace_analyses();
318 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
319 print_execution(complete);
321 clear_program_output();
326 reset_to_initial_state();
329 /** @brief Run trace analyses on complete trace */
330 void ModelChecker::run_trace_analyses() {
331 for (unsigned int i = 0;i < trace_analyses.size();i ++)
332 trace_analyses[i] -> analyze(execution->get_action_trace());
336 * @brief Get a Thread reference by its ID
337 * @param tid The Thread's ID
338 * @return A Thread reference
340 Thread * ModelChecker::get_thread(thread_id_t tid) const
342 return execution->get_thread(tid);
346 * @brief Get a reference to the Thread in which a ModelAction was executed
347 * @param act The ModelAction
348 * @return A Thread reference
350 Thread * ModelChecker::get_thread(const ModelAction *act) const
352 return execution->get_thread(act);
355 void ModelChecker::startRunExecution(Thread *old) {
357 if (params.traceminsize != 0 &&
358 execution->get_curr_seq_num() > checkfree) {
359 checkfree += params.checkthreshold;
360 execution->collectActions();
363 curr_thread_num = MAIN_THREAD_ID;
364 Thread *thr = getNextThread(old);
365 if (thr != nullptr) {
366 scheduler->set_current_thread(thr);
368 if (Thread::swap(old, thr) < 0) {
369 perror("swap threads");
375 if (!handleChosenThread(old)) {
381 Thread* ModelChecker::getNextThread(Thread *old)
383 Thread *nextThread = nullptr;
384 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
385 thread_id_t tid = int_to_id(i);
386 Thread *thr = get_thread(tid);
388 if (!thr->is_complete()) {
389 if (!thr->get_pending()) {
394 } else if (thr != old && !thr->is_freed()) {
395 thr->freeResources();
398 ModelAction *act = thr->get_pending();
399 if (act && scheduler->is_enabled(tid)){
400 /* Don't schedule threads which should be disabled */
401 if (!execution->check_action_enabled(act)) {
402 scheduler->sleep(thr);
405 /* Allow pending relaxed/release stores or thread actions to perform first */
406 else if (!chosen_thread) {
407 if (act->is_write()) {
408 std::memory_order order = act->get_mo();
409 if (order == std::memory_order_relaxed || \
410 order == std::memory_order_release) {
413 } else if (act->get_type() == THREAD_CREATE || \
414 act->get_type() == PTHREAD_CREATE || \
415 act->get_type() == THREAD_START || \
416 act->get_type() == THREAD_FINISH) {
425 /* Swap back to system_context and terminate this execution */
426 void ModelChecker::finishRunExecution(Thread *old)
428 scheduler->set_current_thread(NULL);
430 /** Reset curr_thread_num to initial value for next execution. */
431 curr_thread_num = MAIN_THREAD_ID;
433 /** If we have more executions, we won't make it past this call. */
434 finish_execution(execution_number < params.maxexecutions);
437 /** We finished the final execution. Print stuff and exit. */
438 model_print("******* Model-checking complete: *******\n");
441 /* Have the trace analyses dump their output. */
442 for (unsigned int i = 0;i < trace_analyses.size();i++)
443 trace_analyses[i]->finish();
445 /* unlink tmp file created by last child process */
447 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
454 uint64_t ModelChecker::switch_thread(ModelAction *act)
457 static bool fork_message_printed = false;
459 if (!fork_message_printed) {
460 model_print("Fork handler or dead thread trying to call into model checker...\n");
461 fork_message_printed = true;
469 Thread *old = thread_current();
470 old->set_state(THREAD_READY);
472 ASSERT(!old->get_pending());
474 if (inspect_plugin != NULL) {
475 inspect_plugin->inspectModelAction(act);
478 old->set_pending(act);
480 if (old->is_waiting_on(old))
481 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
483 Thread* next = getNextThread(old);
484 if (next != nullptr) {
485 scheduler->set_current_thread(next);
486 if (Thread::swap(old, next) < 0) {
487 perror("swap threads");
491 if (handleChosenThread(old)) {
492 startRunExecution(old);
495 return old->get_return_value();
498 bool ModelChecker::handleChosenThread(Thread *old)
500 if (execution->has_asserted()) {
501 finishRunExecution(old);
504 if (!chosen_thread) {
505 chosen_thread = get_next_thread();
507 if (!chosen_thread) {
508 finishRunExecution(old);
511 if (chosen_thread->just_woken_up()) {
512 chosen_thread->set_wakeup_state(false);
513 chosen_thread->set_pending(NULL);
514 chosen_thread = NULL;
515 // Allow this thread to stash the next pending action
519 // Consume the next action for a Thread
520 ModelAction *curr = chosen_thread->get_pending();
521 chosen_thread->set_pending(NULL);
522 chosen_thread = execution->take_step(curr);
524 if (should_terminate_execution()) {
525 finishRunExecution(old);
532 void ModelChecker::startChecker() {
534 //Need to initial random number generator state to avoid resets on rollback
535 //initstate(423121, random_state, sizeof(random_state));
536 uint64_t seed = get_nanotime();
539 snapshot = take_snapshot();
541 //reset random number generator state
542 //setstate(random_state);
543 seed = get_nanotime();
546 install_trace_analyses(get_execution());
551 bool ModelChecker::should_terminate_execution()
553 if (execution->have_bug_reports()) {
554 execution->set_assert();
556 } else if (execution->isFinished()) {