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 *) {
29 /** @brief Constructor */
30 ModelChecker::ModelChecker() :
31 /* Initialize default scheduler */
33 scheduler(new Scheduler()),
34 history(new ModelHistory()),
35 execution(new ModelExecution(this, scheduler)),
40 model_print("C11Tester\n"
41 "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
42 "Distributed under the GPLv2\n"
43 "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
44 memset(&stats,0,sizeof(struct execution_stats));
45 init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
47 init_thread->setTLS((char *)get_tls_addr());
49 execution->add_thread(init_thread);
50 scheduler->set_current_thread(init_thread);
52 execution->setParams(¶ms);
53 param_defaults(¶ms);
54 parse_options(¶ms);
56 /* Configure output redirection for the model-checker */
58 install_trace_analyses(get_execution());
61 /** @brief Destructor */
62 ModelChecker::~ModelChecker()
67 /** Method to set parameters */
68 model_params * ModelChecker::getParams() {
73 * Restores user program to initial state and resets all model-checker data
76 void ModelChecker::reset_to_initial_state()
80 * FIXME: if we utilize partial rollback, we will need to free only
81 * those pending actions which were NOT pending before the rollback
84 for (unsigned int i = 0;i < get_num_threads();i++)
85 delete get_thread(int_to_id(i))->get_pending();
87 snapshot_roll_back(snapshot);
90 /** @return the number of user threads created during this execution */
91 unsigned int ModelChecker::get_num_threads() const
93 return execution->get_num_threads();
97 * Must be called from user-thread context (e.g., through the global
98 * thread_current() interface)
100 * @return The currently executing Thread.
102 Thread * ModelChecker::get_current_thread() const
104 return scheduler->get_current_thread();
108 * @brief Choose the next thread to execute.
110 * This function chooses the next thread that should execute. It can enforce
111 * execution replay/backtracking or, if the model-checker has no preference
112 * regarding the next thread (i.e., when exploring a new execution ordering),
113 * we defer to the scheduler.
115 * @return The next chosen thread to run, if any exist. Or else if the current
116 * execution should terminate, return NULL.
118 Thread * ModelChecker::get_next_thread()
122 * Have we completed exploring the preselected path? Then let the
125 return scheduler->select_next_thread();
129 * @brief Assert a bug in the executing program.
131 * Use this function to assert any sort of bug in the user program. If the
132 * current trace is feasible (actually, a prefix of some feasible execution),
133 * then this execution will be aborted, printing the appropriate message. If
134 * the current trace is not yet feasible, the error message will be stashed and
135 * printed if the execution ever becomes feasible.
137 * @param msg Descriptive message for the bug (do not include newline char)
138 * @return True if bug is immediately-feasible
140 void ModelChecker::assert_bug(const char *msg, ...)
146 vsnprintf(str, sizeof(str), msg, ap);
149 execution->assert_bug(str);
153 * @brief Assert a bug in the executing program, asserted by a user thread
154 * @see ModelChecker::assert_bug
155 * @param msg Descriptive message for the bug (do not include newline char)
157 void ModelChecker::assert_user_bug(const char *msg)
159 /* If feasible bug, bail out now */
161 switch_to_master(NULL);
164 /** @brief Print bug report listing for this execution (if any bugs exist) */
165 void ModelChecker::print_bugs() const
167 SnapVector<bug_message *> *bugs = execution->get_bugs();
169 model_print("Bug report: %zu bug%s detected\n",
171 bugs->size() > 1 ? "s" : "");
172 for (unsigned int i = 0;i < bugs->size();i++)
173 (*bugs)[i] -> print();
177 * @brief Record end-of-execution stats
179 * Must be run when exiting an execution. Records various stats.
180 * @see struct execution_stats
182 void ModelChecker::record_stats()
185 if (execution->have_bug_reports())
186 stats.num_buggy_executions ++;
187 else if (execution->is_complete_execution())
188 stats.num_complete ++;
190 //All threads are sleeping
192 * @todo We can violate this ASSERT() when fairness/sleep sets
193 * conflict to cause an execution to terminate, e.g. with:
194 * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
196 //ASSERT(scheduler->all_threads_sleeping());
200 /** @brief Print execution stats */
201 void ModelChecker::print_stats() const
203 model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
204 model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
205 model_print("Total executions: %d\n", stats.num_total);
209 * @brief End-of-exeuction print
210 * @param printbugs Should any existing bugs be printed?
212 void ModelChecker::print_execution(bool printbugs) const
214 model_print("Program output from execution %d:\n",
215 get_execution_number());
216 print_program_output();
218 if (params.verbose >= 3) {
222 /* Don't print invalid bugs */
223 if (printbugs && execution->have_bug_reports()) {
229 execution->print_summary();
233 * Queries the model-checker for more executions to explore and, if one
234 * exists, resets the model-checker state to execute a new execution.
236 * @return If there are more executions to explore, return true. Otherwise,
239 void ModelChecker::finish_execution(bool more_executions)
242 /* Is this execution a feasible execution that's worth bug-checking? */
243 bool complete = (execution->is_complete_execution() ||
244 execution->have_bug_reports());
246 /* End-of-execution bug checks */
248 if (execution->is_deadlocked())
249 assert_bug("Deadlock detected");
251 run_trace_analyses();
256 if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
257 print_execution(complete);
259 clear_program_output();
264 reset_to_initial_state();
265 history->set_new_exec_flag();
268 /** @brief Run trace analyses on complete trace */
269 void ModelChecker::run_trace_analyses() {
270 for (unsigned int i = 0;i < trace_analyses.size();i ++)
271 trace_analyses[i] -> analyze(execution->get_action_trace());
275 * @brief Get a Thread reference by its ID
276 * @param tid The Thread's ID
277 * @return A Thread reference
279 Thread * ModelChecker::get_thread(thread_id_t tid) const
281 return execution->get_thread(tid);
285 * @brief Get a reference to the Thread in which a ModelAction was executed
286 * @param act The ModelAction
287 * @return A Thread reference
289 Thread * ModelChecker::get_thread(const ModelAction *act) const
291 return execution->get_thread(act);
295 * Switch from a model-checker context to a user-thread context. This is the
296 * complement of ModelChecker::switch_to_master and must be called from the
297 * model-checker context
299 * @param thread The user-thread to switch to
301 void ModelChecker::switch_from_master(Thread *thread)
303 scheduler->set_current_thread(thread);
304 Thread::swap(&system_context, thread);
308 * Switch from a user-context to the "master thread" context (a.k.a. system
309 * context). This switch is made with the intention of exploring a particular
310 * model-checking action (described by a ModelAction object). Must be called
311 * from a user-thread context.
313 * @param act The current action that will be explored. May be NULL only if
314 * trace is exiting via an assertion (see ModelExecution::set_assert and
315 * ModelExecution::has_asserted).
316 * @return Return the value returned by the current action
318 uint64_t ModelChecker::switch_to_master(ModelAction *act)
321 static bool fork_message_printed = false;
323 if (!fork_message_printed) {
324 model_print("Fork handler or dead thread trying to call into model checker...\n");
325 fork_message_printed = true;
331 Thread *old = thread_current();
332 scheduler->set_current_thread(NULL);
333 ASSERT(!old->get_pending());
335 if (inspect_plugin != NULL) {
336 inspect_plugin->inspectModelAction(act);
339 old->set_pending(act);
340 if (Thread::swap(old, &system_context) < 0) {
341 perror("swap threads");
344 return old->get_return_value();
347 void ModelChecker::continueExecution(Thread *old)
349 if (params.traceminsize != 0 &&
350 execution->get_curr_seq_num() > checkfree) {
351 checkfree += params.checkthreshold;
352 execution->collectActions();
355 thread_id_t tid = int_to_id(0);
356 Thread *thr = get_thread(tid);
357 scheduler->set_current_thread(thr);
358 if (Thread::swap(old, thr) < 0) {
359 perror("swap threads");
364 void ModelChecker::finishExecution(Thread *old)
366 scheduler->set_current_thread(NULL);
367 if (Thread::swap(old, &system_context) < 0) {
368 perror("swap threads");
373 void ModelChecker::consumeAction()
375 ModelAction *curr = chosen_thread->get_pending();
376 chosen_thread->set_pending(NULL);
377 chosen_thread = execution->take_step(curr);
380 uint64_t ModelChecker::switch_thread(ModelAction *act)
383 static bool fork_message_printed = false;
385 if (!fork_message_printed) {
386 model_print("Fork handler or dead thread trying to call into model checker...\n");
387 fork_message_printed = true;
393 Thread *old = thread_current();
394 ASSERT(!old->get_pending());
396 if (inspect_plugin != NULL) {
397 inspect_plugin->inspectModelAction(act);
400 old->set_pending(act);
404 while (curr_thread_num < get_num_threads()) {
405 thread_id_t tid = int_to_id(curr_thread_num);
406 next = get_thread(tid);
407 if (!next->is_model_thread() && !next->is_complete() && !next->get_pending())
411 if (curr_thread_num < get_num_threads()) {
412 scheduler->set_current_thread(next);
413 if (old->is_waiting_on(old))
414 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
416 ModelAction *act = old->get_pending();
418 if (act && execution->is_enabled(old) && !execution->check_action_enabled(act)) {
419 scheduler->sleep(old);
421 if (!thread_chosen && act && execution->is_enabled(old) && (old->get_state() != THREAD_BLOCKED) ) {
422 if (act->is_write()) {
423 std::memory_order order = act->get_mo();
424 if (order == std::memory_order_relaxed || \
425 order == std::memory_order_release) {
427 thread_chosen = true;
429 } else if (act->get_type() == THREAD_CREATE || \
430 act->get_type() == PTHREAD_CREATE || \
431 act->get_type() == THREAD_START || \
432 act->get_type() == THREAD_FINISH) {
434 thread_chosen = true;
438 if (Thread::swap(old, next) < 0) {
439 perror("swap threads");
443 if (old->is_waiting_on(old))
444 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
446 if (execution->has_asserted())
447 finishExecution(old);
449 chosen_thread = get_next_thread();
450 if (!chosen_thread || chosen_thread->is_model_thread())
451 finishExecution(old);
452 if (chosen_thread->just_woken_up()) {
453 chosen_thread->set_wakeup_state(false);
454 chosen_thread->set_pending(NULL);
455 chosen_thread = NULL;
456 // Allow this thread to stash the next pending action
457 if (should_terminate_execution())
458 finishExecution(old);
460 continueExecution(old);
462 /* Consume the next action for a Thread */
465 if (should_terminate_execution())
466 finishExecution(old);
468 continueExecution(old);
472 return old->get_return_value();
475 static void runChecker() {
480 void ModelChecker::startChecker() {
481 startExecution(get_system_context(), runChecker);
482 snapshot = take_snapshot();
486 bool ModelChecker::should_terminate_execution()
488 if (execution->have_bug_reports()) {
489 execution->set_assert();
491 } else if (execution->isFinished()) {
497 /** @brief Run ModelChecker for the user program */
498 void ModelChecker::run()
500 //Need to initial random number generator state to avoid resets on rollback
501 char random_state[256];
502 initstate(423121, random_state, sizeof(random_state));
503 checkfree = params.checkthreshold;
504 for(int exec = 0;exec < params.maxexecutions;exec++) {
505 chosen_thread = init_thread;
506 thread_chosen = false;
508 thread_id_t tid = int_to_id(0);
509 Thread *thr = get_thread(tid);
510 switch_from_master(thr);
511 finish_execution((exec+1) < params.maxexecutions);
512 //restore random number generator state after rollback
513 setstate(random_state);
516 model_print("******* Model-checking complete: *******\n");
519 /* Have the trace analyses dump their output. */
520 for (unsigned int i = 0;i < trace_analyses.size();i++)
521 trace_analyses[i]->finish();
523 /* unlink tmp file created by last child process */
525 snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());