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)),
72 model_print("C11Tester\n"
73 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
74 "Distributed under the GPLv2\n"
75 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
76 memset(&stats,0,sizeof(struct execution_stats));
77 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
79 init_thread->setTLS((char *)get_tls_addr());
81 execution->add_thread(init_thread);
82 scheduler->set_current_thread(init_thread);
84 execution->setParams(¶ms);
85 param_defaults(¶ms);
86 parse_options(¶ms);
88 /* Configure output redirection for the model-checker */
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 * Must be called from user-thread context (e.g., through the global
140 * thread_current_id() interface)
142 * @return The id of the currently executing Thread.
144 thread_id_t ModelChecker::get_current_thread_id() const
146 ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
147 return int_to_id(curr_thread_num);
151 * @brief Choose the next thread to execute.
153 * This function chooses the next thread that should execute. It can enforce
154 * execution replay/backtracking or, if the model-checker has no preference
155 * regarding the next thread (i.e., when exploring a new execution ordering),
156 * we defer to the scheduler.
158 * @return The next chosen thread to run, if any exist. Or else if the current
159 * execution should terminate, return NULL.
161 Thread * ModelChecker::get_next_thread()
165 * Have we completed exploring the preselected path? Then let the
168 return scheduler->select_next_thread();
172 * @brief Assert a bug in the executing program.
174 * Use this function to assert any sort of bug in the user program. If the
175 * current trace is feasible (actually, a prefix of some feasible execution),
176 * then this execution will be aborted, printing the appropriate message. If
177 * the current trace is not yet feasible, the error message will be stashed and
178 * printed if the execution ever becomes feasible.
180 * @param msg Descriptive message for the bug (do not include newline char)
181 * @return True if bug is immediately-feasible
183 void ModelChecker::assert_bug(const char *msg, ...)
189 vsnprintf(str, sizeof(str), msg, ap);
192 execution->assert_bug(str);
196 * @brief Assert a bug in the executing program, asserted by a user thread
197 * @see ModelChecker::assert_bug
198 * @param msg Descriptive message for the bug (do not include newline char)
200 void ModelChecker::assert_user_bug(const char *msg)
202 /* If feasible bug, bail out now */
207 /** @brief Print bug report listing for this execution (if any bugs exist) */
208 void ModelChecker::print_bugs() const
210 SnapVector<bug_message *> *bugs = execution->get_bugs();
212 model_print("Bug report: %zu bug%s detected\n",
214 bugs->size() > 1 ? "s" : "");
215 for (unsigned int i = 0;i < bugs->size();i++)
216 (*bugs)[i] -> print();
220 * @brief Record end-of-execution stats
222 * Must be run when exiting an execution. Records various stats.
223 * @see struct execution_stats
225 void ModelChecker::record_stats()
228 if (execution->have_bug_reports())
229 stats.num_buggy_executions ++;
230 else if (execution->is_complete_execution())
231 stats.num_complete ++;
233 //All threads are sleeping
235 * @todo We can violate this ASSERT() when fairness/sleep sets
236 * conflict to cause an execution to terminate, e.g. with:
237 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
239 //ASSERT(scheduler->all_threads_sleeping());
243 /** @brief Print execution stats */
244 void ModelChecker::print_stats() const
246 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
247 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
248 model_print("Total executions: %d\n", stats.num_total);
252 * @brief End-of-exeuction print
253 * @param printbugs Should any existing bugs be printed?
255 void ModelChecker::print_execution(bool printbugs) const
257 model_print("Program output from execution %d:\n",
258 get_execution_number());
259 print_program_output();
261 if (params.verbose >= 3) {
265 /* Don't print invalid bugs */
266 if (printbugs && execution->have_bug_reports()) {
272 execution->print_summary();
276 * Queries the model-checker for more executions to explore and, if one
277 * exists, resets the model-checker state to execute a new execution.
279 * @return If there are more executions to explore, return true. Otherwise,
282 void ModelChecker::finish_execution(bool more_executions)
285 /* Is this execution a feasible execution that's worth bug-checking? */
286 bool complete = (execution->is_complete_execution() ||
287 execution->have_bug_reports());
289 /* End-of-execution bug checks */
291 if (execution->is_deadlocked())
292 assert_bug("Deadlock detected");
294 run_trace_analyses();
299 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
300 print_execution(complete);
302 clear_program_output();
305 history->set_new_exec_flag();
308 reset_to_initial_state();
311 /** @brief Run trace analyses on complete trace */
312 void ModelChecker::run_trace_analyses() {
313 for (unsigned int i = 0;i < trace_analyses.size();i ++)
314 trace_analyses[i] -> analyze(execution->get_action_trace());
318 * @brief Get a Thread reference by its ID
319 * @param tid The Thread's ID
320 * @return A Thread reference
322 Thread * ModelChecker::get_thread(thread_id_t tid) const
324 return execution->get_thread(tid);
328 * @brief Get a reference to the Thread in which a ModelAction was executed
329 * @param act The ModelAction
330 * @return A Thread reference
332 Thread * ModelChecker::get_thread(const ModelAction *act) const
334 return execution->get_thread(act);
337 void ModelChecker::startRunExecution(Thread *old) {
339 if (params.traceminsize != 0 &&
340 execution->get_curr_seq_num() > checkfree) {
341 checkfree += params.checkthreshold;
342 execution->collectActions();
346 Thread *thr = getNextThread(old);
347 if (thr != nullptr) {
348 scheduler->set_current_thread(thr);
350 if (Thread::swap(old, thr) < 0) {
351 perror("swap threads");
357 if (!handleChosenThread(old)) {
363 Thread* ModelChecker::getNextThread(Thread *old)
365 Thread *nextThread = nullptr;
366 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
367 thread_id_t tid = int_to_id(i);
368 Thread *thr = get_thread(tid);
370 if (!thr->is_complete()) {
371 if (!thr->get_pending()) {
376 } else if (thr != old && !thr->is_freed()) {
377 thr->freeResources();
380 ModelAction *act = thr->get_pending();
381 if (act && execution->is_enabled(tid)){
382 /* Don't schedule threads which should be disabled */
383 if (!execution->check_action_enabled(act)) {
384 scheduler->sleep(thr);
387 /* Allow pending relaxed/release stores or thread actions to perform first */
388 else if (!chosen_thread) {
389 if (act->is_write()) {
390 std::memory_order order = act->get_mo();
391 if (order == std::memory_order_relaxed || \
392 order == std::memory_order_release) {
395 } else if (act->get_type() == THREAD_CREATE || \
396 act->get_type() == PTHREAD_CREATE || \
397 act->get_type() == THREAD_START || \
398 act->get_type() == THREAD_FINISH) {
407 /* Swap back to system_context and terminate this execution */
408 void ModelChecker::finishRunExecution(Thread *old)
410 scheduler->set_current_thread(NULL);
412 /** Reset curr_thread_num to initial value for next execution. */
415 /** If we have more executions, we won't make it past this call. */
416 finish_execution(execution_number < params.maxexecutions);
419 /** We finished the final execution. Print stuff and exit. */
420 model_print("******* Model-checking complete: *******\n");
423 /* Have the trace analyses dump their output. */
424 for (unsigned int i = 0;i < trace_analyses.size();i++)
425 trace_analyses[i]->finish();
427 /* unlink tmp file created by last child process */
429 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
436 uint64_t ModelChecker::switch_thread(ModelAction *act)
439 static bool fork_message_printed = false;
441 if (!fork_message_printed) {
442 model_print("Fork handler or dead thread trying to call into model checker...\n");
443 fork_message_printed = true;
449 Thread *old = thread_current();
450 old->set_state(THREAD_READY);
452 ASSERT(!old->get_pending());
454 if (inspect_plugin != NULL) {
455 inspect_plugin->inspectModelAction(act);
458 old->set_pending(act);
460 if (old->is_waiting_on(old))
461 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
463 Thread* next = getNextThread(old);
464 if (next != nullptr) {
465 scheduler->set_current_thread(next);
466 if (Thread::swap(old, next) < 0) {
467 perror("swap threads");
471 if (handleChosenThread(old)) {
472 startRunExecution(old);
475 return old->get_return_value();
478 bool ModelChecker::handleChosenThread(Thread *old)
480 if (execution->has_asserted()) {
481 finishRunExecution(old);
484 if (!chosen_thread) {
485 chosen_thread = get_next_thread();
487 if (!chosen_thread) {
488 finishRunExecution(old);
491 if (chosen_thread->just_woken_up()) {
492 chosen_thread->set_wakeup_state(false);
493 chosen_thread->set_pending(NULL);
494 chosen_thread = NULL;
495 // Allow this thread to stash the next pending action
499 // Consume the next action for a Thread
500 ModelAction *curr = chosen_thread->get_pending();
501 chosen_thread->set_pending(NULL);
502 chosen_thread = execution->take_step(curr);
504 if (should_terminate_execution()) {
505 finishRunExecution(old);
512 void ModelChecker::startChecker() {
514 //Need to initial random number generator state to avoid resets on rollback
515 initstate(423121, random_state, sizeof(random_state));
517 snapshot = take_snapshot();
519 //reset random number generator state
520 setstate(random_state);
522 install_trace_analyses(get_execution());
527 bool ModelChecker::should_terminate_execution()
529 if (execution->have_bug_reports()) {
530 execution->set_assert();
532 } else if (execution->isFinished()) {