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 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() {
62 snapshot_system_init(100000);
63 model = new ModelChecker();
64 model->startChecker();
69 /** @brief Constructor */
70 ModelChecker::ModelChecker() :
71 /* Initialize default scheduler */
73 scheduler(new Scheduler()),
74 execution(new ModelExecution(this, scheduler)),
76 curr_thread_num(MAIN_THREAD_ID),
80 model_print("C11Tester\n"
81 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
82 "Distributed under the GPLv2\n"
83 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
85 real_memset(&stats,0,sizeof(struct execution_stats));
86 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
88 init_thread->setTLS((char *)get_tls_addr());
90 execution->add_thread(init_thread);
91 scheduler->set_current_thread(init_thread);
93 execution->setParams(¶ms);
94 param_defaults(¶ms);
95 parse_options(¶ms);
97 /* Configure output redirection for the model-checker */
101 /** @brief Destructor */
102 ModelChecker::~ModelChecker()
107 /** Method to set parameters */
108 model_params * ModelChecker::getParams() {
113 * Restores user program to initial state and resets all model-checker data
116 void ModelChecker::reset_to_initial_state()
120 * FIXME: if we utilize partial rollback, we will need to free only
121 * those pending actions which were NOT pending before the rollback
124 for (unsigned int i = 0;i < get_num_threads();i++)
125 delete get_thread(int_to_id(i))->get_pending();
127 snapshot_roll_back(snapshot);
130 /** @return the number of user threads created during this execution */
131 unsigned int ModelChecker::get_num_threads() const
133 return execution->get_num_threads();
137 * Must be called from user-thread context (e.g., through the global
138 * thread_current() interface)
140 * @return The currently executing Thread.
142 Thread * ModelChecker::get_current_thread() const
144 return scheduler->get_current_thread();
148 * Must be called from user-thread context (e.g., through the global
149 * thread_current_id() interface)
151 * @return The id of the currently executing Thread.
153 thread_id_t ModelChecker::get_current_thread_id() const
155 ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
156 return int_to_id(curr_thread_num);
160 * @brief Choose the next thread to execute.
162 * This function chooses the next thread that should execute. It can enforce
163 * execution replay/backtracking or, if the model-checker has no preference
164 * regarding the next thread (i.e., when exploring a new execution ordering),
165 * we defer to the scheduler.
167 * @return The next chosen thread to run, if any exist. Or else if the current
168 * execution should terminate, return NULL.
170 Thread * ModelChecker::get_next_thread()
174 * Have we completed exploring the preselected path? Then let the
177 return scheduler->select_next_thread();
181 * @brief Assert a bug in the executing program.
183 * Use this function to assert any sort of bug in the user program. If the
184 * current trace is feasible (actually, a prefix of some feasible execution),
185 * then this execution will be aborted, printing the appropriate message. If
186 * the current trace is not yet feasible, the error message will be stashed and
187 * printed if the execution ever becomes feasible.
189 * @param msg Descriptive message for the bug (do not include newline char)
190 * @return True if bug is immediately-feasible
192 void ModelChecker::assert_bug(const char *msg, ...)
198 vsnprintf(str, sizeof(str), msg, ap);
201 execution->assert_bug(str);
205 * @brief Assert a bug in the executing program, asserted by a user thread
206 * @see ModelChecker::assert_bug
207 * @param msg Descriptive message for the bug (do not include newline char)
209 void ModelChecker::assert_user_bug(const char *msg)
211 /* If feasible bug, bail out now */
216 /** @brief Print bug report listing for this execution (if any bugs exist) */
217 void ModelChecker::print_bugs() const
219 SnapVector<bug_message *> *bugs = execution->get_bugs();
221 model_print("Bug report: %zu bug%s detected\n",
223 bugs->size() > 1 ? "s" : "");
224 for (unsigned int i = 0;i < bugs->size();i++)
225 (*bugs)[i] -> print();
229 * @brief Record end-of-execution stats
231 * Must be run when exiting an execution. Records various stats.
232 * @see struct execution_stats
234 void ModelChecker::record_stats()
237 if (execution->have_bug_reports())
238 stats.num_buggy_executions ++;
239 else if (execution->is_complete_execution())
240 stats.num_complete ++;
242 //All threads are sleeping
244 * @todo We can violate this ASSERT() when fairness/sleep sets
245 * conflict to cause an execution to terminate, e.g. with:
246 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
248 //ASSERT(scheduler->all_threads_sleeping());
252 /** @brief Print execution stats */
253 void ModelChecker::print_stats() const
255 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
256 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
257 model_print("Total executions: %d\n", stats.num_total);
261 * @brief End-of-exeuction print
262 * @param printbugs Should any existing bugs be printed?
264 void ModelChecker::print_execution(bool printbugs) const
266 model_print("Program output from execution %d:\n",
267 get_execution_number());
268 print_program_output();
270 if (params.verbose >= 3) {
274 /* Don't print invalid bugs */
275 if (printbugs && execution->have_bug_reports()) {
282 execution->print_summary();
287 * Queries the model-checker for more executions to explore and, if one
288 * exists, resets the model-checker state to execute a new execution.
290 * @return If there are more executions to explore, return true. Otherwise,
293 void ModelChecker::finish_execution(bool more_executions)
296 /* Is this execution a feasible execution that's worth bug-checking? */
297 bool complete = (execution->is_complete_execution() ||
298 execution->have_bug_reports());
300 /* End-of-execution bug checks */
302 if (execution->is_deadlocked())
303 assert_bug("Deadlock detected");
305 run_trace_analyses();
310 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
311 print_execution(complete);
313 clear_program_output();
318 reset_to_initial_state();
321 /** @brief Run trace analyses on complete trace */
322 void ModelChecker::run_trace_analyses() {
323 for (unsigned int i = 0;i < trace_analyses.size();i ++)
324 trace_analyses[i] -> analyze(execution->get_action_trace());
328 * @brief Get a Thread reference by its ID
329 * @param tid The Thread's ID
330 * @return A Thread reference
332 Thread * ModelChecker::get_thread(thread_id_t tid) const
334 return execution->get_thread(tid);
338 * @brief Get a reference to the Thread in which a ModelAction was executed
339 * @param act The ModelAction
340 * @return A Thread reference
342 Thread * ModelChecker::get_thread(const ModelAction *act) const
344 return execution->get_thread(act);
347 void ModelChecker::startRunExecution(Thread *old) {
349 if (params.traceminsize != 0 &&
350 execution->get_curr_seq_num() > checkfree) {
351 checkfree += params.checkthreshold;
352 execution->collectActions();
355 curr_thread_num = MAIN_THREAD_ID;
356 Thread *thr = getNextThread(old);
357 if (thr != nullptr) {
358 scheduler->set_current_thread(thr);
360 if (Thread::swap(old, thr) < 0) {
361 perror("swap threads");
367 if (!handleChosenThread(old)) {
373 Thread* ModelChecker::getNextThread(Thread *old)
375 Thread *nextThread = nullptr;
376 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
377 thread_id_t tid = int_to_id(i);
378 Thread *thr = get_thread(tid);
380 if (!thr->is_complete()) {
381 if (!thr->get_pending()) {
386 } else if (thr != old && !thr->is_freed()) {
387 thr->freeResources();
390 ModelAction *act = thr->get_pending();
391 if (act && scheduler->is_enabled(tid)){
392 /* Don't schedule threads which should be disabled */
393 if (!execution->check_action_enabled(act)) {
394 scheduler->sleep(thr);
397 /* Allow pending relaxed/release stores or thread actions to perform first */
398 else if (!chosen_thread) {
399 if (act->is_write()) {
400 std::memory_order order = act->get_mo();
401 if (order == std::memory_order_relaxed || \
402 order == std::memory_order_release) {
405 } else if (act->get_type() == THREAD_CREATE || \
406 act->get_type() == PTHREAD_CREATE || \
407 act->get_type() == THREAD_START || \
408 act->get_type() == THREAD_FINISH) {
417 /* Swap back to system_context and terminate this execution */
418 void ModelChecker::finishRunExecution(Thread *old)
420 scheduler->set_current_thread(NULL);
422 /** Reset curr_thread_num to initial value for next execution. */
423 curr_thread_num = MAIN_THREAD_ID;
425 /** If we have more executions, we won't make it past this call. */
426 finish_execution(execution_number < params.maxexecutions);
429 /** We finished the final execution. Print stuff and exit. */
430 model_print("******* Model-checking complete: *******\n");
433 /* Have the trace analyses dump their output. */
434 for (unsigned int i = 0;i < trace_analyses.size();i++)
435 trace_analyses[i]->finish();
437 /* unlink tmp file created by last child process */
439 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
446 uint64_t ModelChecker::switch_thread(ModelAction *act)
449 static bool fork_message_printed = false;
451 if (!fork_message_printed) {
452 model_print("Fork handler or dead thread trying to call into model checker...\n");
453 fork_message_printed = true;
461 Thread *old = thread_current();
462 old->set_state(THREAD_READY);
464 ASSERT(!old->get_pending());
466 if (inspect_plugin != NULL) {
467 inspect_plugin->inspectModelAction(act);
470 old->set_pending(act);
472 if (old->is_waiting_on(old))
473 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
475 Thread* next = getNextThread(old);
476 if (next != nullptr) {
477 scheduler->set_current_thread(next);
478 if (Thread::swap(old, next) < 0) {
479 perror("swap threads");
483 if (handleChosenThread(old)) {
484 startRunExecution(old);
487 return old->get_return_value();
490 bool ModelChecker::handleChosenThread(Thread *old)
492 if (execution->has_asserted()) {
493 finishRunExecution(old);
496 if (!chosen_thread) {
497 chosen_thread = get_next_thread();
499 if (!chosen_thread) {
500 finishRunExecution(old);
503 if (chosen_thread->just_woken_up()) {
504 chosen_thread->set_wakeup_state(false);
505 chosen_thread->set_pending(NULL);
506 chosen_thread = NULL;
507 // Allow this thread to stash the next pending action
511 // Consume the next action for a Thread
512 ModelAction *curr = chosen_thread->get_pending();
513 chosen_thread->set_pending(NULL);
514 chosen_thread = execution->take_step(curr);
516 if (should_terminate_execution()) {
517 finishRunExecution(old);
524 void ModelChecker::startChecker() {
526 //Need to initial random number generator state to avoid resets on rollback
527 initstate(423121, random_state, sizeof(random_state));
529 snapshot = take_snapshot();
531 //reset random number generator state
532 setstate(random_state);
534 install_trace_analyses(get_execution());
539 bool ModelChecker::should_terminate_execution()
541 if (execution->have_bug_reports()) {
542 execution->set_assert();
544 } else if (execution->isFinished()) {