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)),
71 model_print("C11Tester\n"
72 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
73 "Distributed under the GPLv2\n"
74 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
75 memset(&stats,0,sizeof(struct execution_stats));
76 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
78 init_thread->setTLS((char *)get_tls_addr());
80 execution->add_thread(init_thread);
81 scheduler->set_current_thread(init_thread);
83 execution->setParams(¶ms);
84 param_defaults(¶ms);
85 parse_options(¶ms);
87 /* Configure output redirection for the model-checker */
91 /** @brief Destructor */
92 ModelChecker::~ModelChecker()
97 /** Method to set parameters */
98 model_params * ModelChecker::getParams() {
103 * Restores user program to initial state and resets all model-checker data
106 void ModelChecker::reset_to_initial_state()
110 * FIXME: if we utilize partial rollback, we will need to free only
111 * those pending actions which were NOT pending before the rollback
114 for (unsigned int i = 0;i < get_num_threads();i++)
115 delete get_thread(int_to_id(i))->get_pending();
117 snapshot_roll_back(snapshot);
120 /** @return the number of user threads created during this execution */
121 unsigned int ModelChecker::get_num_threads() const
123 return execution->get_num_threads();
127 * Must be called from user-thread context (e.g., through the global
128 * thread_current() interface)
130 * @return The currently executing Thread.
132 Thread * ModelChecker::get_current_thread() const
134 return scheduler->get_current_thread();
138 * @brief Choose the next thread to execute.
140 * This function chooses the next thread that should execute. It can enforce
141 * execution replay/backtracking or, if the model-checker has no preference
142 * regarding the next thread (i.e., when exploring a new execution ordering),
143 * we defer to the scheduler.
145 * @return The next chosen thread to run, if any exist. Or else if the current
146 * execution should terminate, return NULL.
148 Thread * ModelChecker::get_next_thread()
152 * Have we completed exploring the preselected path? Then let the
155 return scheduler->select_next_thread();
159 * @brief Assert a bug in the executing program.
161 * Use this function to assert any sort of bug in the user program. If the
162 * current trace is feasible (actually, a prefix of some feasible execution),
163 * then this execution will be aborted, printing the appropriate message. If
164 * the current trace is not yet feasible, the error message will be stashed and
165 * printed if the execution ever becomes feasible.
167 * @param msg Descriptive message for the bug (do not include newline char)
168 * @return True if bug is immediately-feasible
170 void ModelChecker::assert_bug(const char *msg, ...)
176 vsnprintf(str, sizeof(str), msg, ap);
179 execution->assert_bug(str);
183 * @brief Assert a bug in the executing program, asserted by a user thread
184 * @see ModelChecker::assert_bug
185 * @param msg Descriptive message for the bug (do not include newline char)
187 void ModelChecker::assert_user_bug(const char *msg)
189 /* If feasible bug, bail out now */
194 /** @brief Print bug report listing for this execution (if any bugs exist) */
195 void ModelChecker::print_bugs() const
197 SnapVector<bug_message *> *bugs = execution->get_bugs();
199 model_print("Bug report: %zu bug%s detected\n",
201 bugs->size() > 1 ? "s" : "");
202 for (unsigned int i = 0;i < bugs->size();i++)
203 (*bugs)[i] -> print();
207 * @brief Record end-of-execution stats
209 * Must be run when exiting an execution. Records various stats.
210 * @see struct execution_stats
212 void ModelChecker::record_stats()
215 if (execution->have_bug_reports())
216 stats.num_buggy_executions ++;
217 else if (execution->is_complete_execution())
218 stats.num_complete ++;
220 //All threads are sleeping
222 * @todo We can violate this ASSERT() when fairness/sleep sets
223 * conflict to cause an execution to terminate, e.g. with:
224 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
226 //ASSERT(scheduler->all_threads_sleeping());
230 /** @brief Print execution stats */
231 void ModelChecker::print_stats() const
233 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
234 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
235 model_print("Total executions: %d\n", stats.num_total);
239 * @brief End-of-exeuction print
240 * @param printbugs Should any existing bugs be printed?
242 void ModelChecker::print_execution(bool printbugs) const
244 model_print("Program output from execution %d:\n",
245 get_execution_number());
246 print_program_output();
248 if (params.verbose >= 3) {
252 /* Don't print invalid bugs */
253 if (printbugs && execution->have_bug_reports()) {
259 execution->print_summary();
263 * Queries the model-checker for more executions to explore and, if one
264 * exists, resets the model-checker state to execute a new execution.
266 * @return If there are more executions to explore, return true. Otherwise,
269 void ModelChecker::finish_execution(bool more_executions)
272 /* Is this execution a feasible execution that's worth bug-checking? */
273 bool complete = (execution->is_complete_execution() ||
274 execution->have_bug_reports());
276 /* End-of-execution bug checks */
278 if (execution->is_deadlocked())
279 assert_bug("Deadlock detected");
281 run_trace_analyses();
286 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
287 print_execution(complete);
289 clear_program_output();
292 history->set_new_exec_flag();
295 reset_to_initial_state();
298 /** @brief Run trace analyses on complete trace */
299 void ModelChecker::run_trace_analyses() {
300 for (unsigned int i = 0;i < trace_analyses.size();i ++)
301 trace_analyses[i] -> analyze(execution->get_action_trace());
305 * @brief Get a Thread reference by its ID
306 * @param tid The Thread's ID
307 * @return A Thread reference
309 Thread * ModelChecker::get_thread(thread_id_t tid) const
311 return execution->get_thread(tid);
315 * @brief Get a reference to the Thread in which a ModelAction was executed
316 * @param act The ModelAction
317 * @return A Thread reference
319 Thread * ModelChecker::get_thread(const ModelAction *act) const
321 return execution->get_thread(act);
324 void ModelChecker::startRunExecution(Thread *old) {
326 if (params.traceminsize != 0 &&
327 execution->get_curr_seq_num() > checkfree) {
328 checkfree += params.checkthreshold;
329 execution->collectActions();
332 thread_chosen = false;
335 Thread *thr = getNextThread();
336 if (thr != nullptr) {
337 scheduler->set_current_thread(thr);
339 if (Thread::swap(old, thr) < 0) {
340 perror("swap threads");
346 if (execution->has_asserted()) {
347 finishRunExecution(old);
351 chosen_thread = get_next_thread();
352 if (!chosen_thread || chosen_thread->is_model_thread()) {
353 finishRunExecution(old);
356 if (chosen_thread->just_woken_up()) {
357 chosen_thread->set_wakeup_state(false);
358 chosen_thread->set_pending(NULL);
359 chosen_thread = NULL;
360 // Allow this thread to stash the next pending action
364 /* Consume the next action for a Thread */
367 if (should_terminate_execution()) {
368 finishRunExecution(old);
374 Thread* ModelChecker::getNextThread()
376 Thread *nextThread = nullptr;
377 for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
378 thread_id_t tid = int_to_id(i);
379 Thread *thr = get_thread(tid);
381 if (!thr->is_complete() && !thr->get_pending()) {
387 /* Don't schedule threads which should be disabled */
388 ModelAction *act = thr->get_pending();
389 if (act && execution->is_enabled(thr) && !execution->check_action_enabled(act)) {
390 scheduler->sleep(thr);
392 chooseThread(act, thr);
397 /* Swap back to system_context and terminate this execution */
398 void ModelChecker::finishRunExecution(Thread *old)
400 scheduler->set_current_thread(NULL);
402 /** If we have more executions, we won't make it past this call. */
403 finish_execution(execution_number < params.maxexecutions);
406 /** We finished the final execution. Print stuff and exit. */
407 model_print("******* Model-checking complete: *******\n");
410 /* Have the trace analyses dump their output. */
411 for (unsigned int i = 0;i < trace_analyses.size();i++)
412 trace_analyses[i]->finish();
414 /* unlink tmp file created by last child process */
416 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
423 void ModelChecker::consumeAction()
425 ModelAction *curr = chosen_thread->get_pending();
426 Thread * th = thread_current();
427 chosen_thread->set_pending(NULL);
428 chosen_thread = execution->take_step(curr);
431 /* Allow pending relaxed/release stores or thread actions to perform first */
432 void ModelChecker::chooseThread(ModelAction *act, Thread *thr)
434 if (!thread_chosen && act && execution->is_enabled(thr) && (thr->get_state() != THREAD_BLOCKED) ) {
435 if (act->is_write()) {
436 std::memory_order order = act->get_mo();
437 if (order == std::memory_order_relaxed || \
438 order == std::memory_order_release) {
440 thread_chosen = true;
442 } else if (act->get_type() == THREAD_CREATE || \
443 act->get_type() == PTHREAD_CREATE || \
444 act->get_type() == THREAD_START || \
445 act->get_type() == THREAD_FINISH) {
447 thread_chosen = true;
452 uint64_t ModelChecker::switch_thread(ModelAction *act)
455 static bool fork_message_printed = false;
457 if (!fork_message_printed) {
458 model_print("Fork handler or dead thread trying to call into model checker...\n");
459 fork_message_printed = true;
465 Thread *old = thread_current();
466 ASSERT(!old->get_pending());
468 if (inspect_plugin != NULL) {
469 inspect_plugin->inspectModelAction(act);
472 old->set_pending(act);
474 if (old->is_waiting_on(old))
475 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
477 if (act && execution->is_enabled(old) && !execution->check_action_enabled(act)) {
478 scheduler->sleep(old);
480 chooseThread(act, old);
483 Thread* next = getNextThread();
484 if (next != nullptr) {
485 scheduler->set_current_thread(next);
486 if (Thread::swap(old, next) < 0) {
487 perror("swap threads");
491 handleChosenThread(old);
493 return old->get_return_value();
496 void ModelChecker::handleChosenThread(Thread *old)
498 if (execution->has_asserted()) {
499 finishRunExecution(old);
503 chosen_thread = get_next_thread();
504 if (!chosen_thread || chosen_thread->is_model_thread()) {
505 finishRunExecution(old);
508 if (chosen_thread->just_woken_up()) {
509 chosen_thread->set_wakeup_state(false);
510 chosen_thread->set_pending(NULL);
511 chosen_thread = NULL;
512 // Allow this thread to stash the next pending action
513 startRunExecution(old);
517 // Consume the next action for a Thread
520 if (should_terminate_execution()) {
521 finishRunExecution(old);
524 startRunExecution(old);
527 void ModelChecker::startChecker() {
529 //Need to initial random number generator state to avoid resets on rollback
530 initstate(423121, random_state, sizeof(random_state));
532 snapshot = take_snapshot();
534 //reset random number generator state
535 setstate(random_state);
537 install_trace_analyses(get_execution());
542 bool ModelChecker::should_terminate_execution()
544 if (execution->have_bug_reports()) {
545 execution->set_assert();
547 } else if (execution->isFinished()) {