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;
26 void placeholder(void *) {
32 #define SIGSTACKSIZE 65536
33 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
35 model_print("Segmentation fault at %p\n", si->si_addr);
36 model_print("For debugging, place breakpoint at: %s:%d\n",
38 print_trace(); // Trace printing may cause dynamic memory allocation
43 void install_handler() {
45 ss.ss_sp = model_malloc(SIGSTACKSIZE);
46 ss.ss_size = SIGSTACKSIZE;
48 sigaltstack(&ss, NULL);
50 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
51 sigemptyset(&sa.sa_mask);
52 sa.sa_sigaction = mprot_handle_pf;
54 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
55 perror("sigaction(SIGSEGV)");
60 void createModelIfNotExist() {
62 snapshot_system_init(100000);
63 model = new ModelChecker();
64 model->startChecker();
68 /** @brief Constructor */
69 ModelChecker::ModelChecker() :
70 /* Initialize default scheduler */
72 scheduler(new Scheduler()),
73 history(new ModelHistory()),
74 execution(new ModelExecution(this, scheduler)),
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 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()) {
281 execution->print_summary();
285 * Queries the model-checker for more executions to explore and, if one
286 * exists, resets the model-checker state to execute a new execution.
288 * @return If there are more executions to explore, return true. Otherwise,
291 void ModelChecker::finish_execution(bool more_executions)
294 /* Is this execution a feasible execution that's worth bug-checking? */
295 bool complete = (execution->is_complete_execution() ||
296 execution->have_bug_reports());
298 /* End-of-execution bug checks */
300 if (execution->is_deadlocked())
301 assert_bug("Deadlock detected");
303 run_trace_analyses();
308 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
309 print_execution(complete);
311 clear_program_output();
314 history->set_new_exec_flag();
317 reset_to_initial_state();
320 /** @brief Run trace analyses on complete trace */
321 void ModelChecker::run_trace_analyses() {
322 for (unsigned int i = 0;i < trace_analyses.size();i ++)
323 trace_analyses[i] -> analyze(execution->get_action_trace());
327 * @brief Get a Thread reference by its ID
328 * @param tid The Thread's ID
329 * @return A Thread reference
331 Thread * ModelChecker::get_thread(thread_id_t tid) const
333 return execution->get_thread(tid);
337 * @brief Get a reference to the Thread in which a ModelAction was executed
338 * @param act The ModelAction
339 * @return A Thread reference
341 Thread * ModelChecker::get_thread(const ModelAction *act) const
343 return execution->get_thread(act);
346 void ModelChecker::startRunExecution(Thread *old) {
348 if (params.traceminsize != 0 &&
349 execution->get_curr_seq_num() > checkfree) {
350 checkfree += params.checkthreshold;
351 execution->collectActions();
355 Thread *thr = getNextThread(old);
356 if (thr != nullptr) {
357 scheduler->set_current_thread(thr);
359 if (Thread::swap(old, thr) < 0) {
360 perror("swap threads");
366 if (!handleChosenThread(old)) {
372 Thread* ModelChecker::getNextThread(Thread *old)
374 Thread *nextThread = nullptr;
375 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
376 thread_id_t tid = int_to_id(i);
377 Thread *thr = get_thread(tid);
379 if (!thr->is_complete()) {
380 if (!thr->get_pending()) {
385 } else if (thr != old && !thr->is_freed()) {
386 thr->freeResources();
389 ModelAction *act = thr->get_pending();
390 if (act && scheduler->is_enabled(tid)){
391 /* Don't schedule threads which should be disabled */
392 if (!execution->check_action_enabled(act)) {
393 scheduler->sleep(thr);
396 /* Allow pending relaxed/release stores or thread actions to perform first */
397 else if (!chosen_thread) {
398 if (act->is_write()) {
399 std::memory_order order = act->get_mo();
400 if (order == std::memory_order_relaxed || \
401 order == std::memory_order_release) {
404 } else if (act->get_type() == THREAD_CREATE || \
405 act->get_type() == PTHREAD_CREATE || \
406 act->get_type() == THREAD_START || \
407 act->get_type() == THREAD_FINISH) {
416 /* Swap back to system_context and terminate this execution */
417 void ModelChecker::finishRunExecution(Thread *old)
419 scheduler->set_current_thread(NULL);
421 /** Reset curr_thread_num to initial value for next execution. */
424 /** If we have more executions, we won't make it past this call. */
425 finish_execution(execution_number < params.maxexecutions);
428 /** We finished the final execution. Print stuff and exit. */
429 model_print("******* Model-checking complete: *******\n");
432 /* Have the trace analyses dump their output. */
433 for (unsigned int i = 0;i < trace_analyses.size();i++)
434 trace_analyses[i]->finish();
436 /* unlink tmp file created by last child process */
438 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
445 uint64_t ModelChecker::switch_thread(ModelAction *act)
448 static bool fork_message_printed = false;
450 if (!fork_message_printed) {
451 model_print("Fork handler or dead thread trying to call into model checker...\n");
452 fork_message_printed = true;
460 Thread *old = thread_current();
461 old->set_state(THREAD_READY);
463 ASSERT(!old->get_pending());
465 if (inspect_plugin != NULL) {
466 inspect_plugin->inspectModelAction(act);
469 old->set_pending(act);
471 if (old->is_waiting_on(old))
472 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
474 Thread* next = getNextThread(old);
475 if (next != nullptr) {
476 scheduler->set_current_thread(next);
477 if (Thread::swap(old, next) < 0) {
478 perror("swap threads");
482 if (handleChosenThread(old)) {
483 startRunExecution(old);
486 return old->get_return_value();
489 bool ModelChecker::handleChosenThread(Thread *old)
491 if (execution->has_asserted()) {
492 finishRunExecution(old);
495 if (!chosen_thread) {
496 chosen_thread = get_next_thread();
498 if (!chosen_thread) {
499 finishRunExecution(old);
502 if (chosen_thread->just_woken_up()) {
503 chosen_thread->set_wakeup_state(false);
504 chosen_thread->set_pending(NULL);
505 chosen_thread = NULL;
506 // Allow this thread to stash the next pending action
510 // Consume the next action for a Thread
511 ModelAction *curr = chosen_thread->get_pending();
512 chosen_thread->set_pending(NULL);
513 chosen_thread = execution->take_step(curr);
515 if (should_terminate_execution()) {
516 finishRunExecution(old);
523 void ModelChecker::startChecker() {
525 //Need to initial random number generator state to avoid resets on rollback
526 initstate(423121, random_state, sizeof(random_state));
528 snapshot = take_snapshot();
530 //reset random number generator state
531 setstate(random_state);
533 install_trace_analyses(get_execution());
538 bool ModelChecker::should_terminate_execution()
540 if (execution->have_bug_reports()) {
541 execution->set_assert();
543 } else if (execution->isFinished()) {