450aac5a51f2201c62d4743d94339c0cab0c2469
[c11tester.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3 #include <new>
4 #include <stdarg.h>
5 #include <string.h>
6 #include <cstdlib>
7
8 #include "model.h"
9 #include "action.h"
10 #include "schedule.h"
11 #include "snapshot-interface.h"
12 #include "common.h"
13 #include "datarace.h"
14 #include "threads-model.h"
15 #include "output.h"
16 #include "traceanalysis.h"
17 #include "execution.h"
18 #include "history.h"
19 #include "bugmessage.h"
20 #include "params.h"
21 #include "plugins.h"
22
23 ModelChecker *model = NULL;
24 int inside_model = 0;
25
26 void placeholder(void *) {
27         ASSERT(0);
28 }
29
30 #include <signal.h>
31
32 #define SIGSTACKSIZE 65536
33 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
34 {
35         model_print("Segmentation fault at %p\n", si->si_addr);
36         model_print("For debugging, place breakpoint at: %s:%d\n",
37                                                         __FILE__, __LINE__);
38         print_trace();  // Trace printing may cause dynamic memory allocation
39         while(1)
40                 ;
41 }
42
43 void install_handler() {
44         stack_t ss;
45         ss.ss_sp = model_malloc(SIGSTACKSIZE);
46         ss.ss_size = SIGSTACKSIZE;
47         ss.ss_flags = 0;
48         sigaltstack(&ss, NULL);
49         struct sigaction sa;
50         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
51         sigemptyset(&sa.sa_mask);
52         sa.sa_sigaction = mprot_handle_pf;
53
54         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
55                 perror("sigaction(SIGSEGV)");
56                 exit(EXIT_FAILURE);
57         }
58 }
59
60 void createModelIfNotExist() {
61         if (!model) {
62                 snapshot_system_init(100000);
63                 model = new ModelChecker();
64                 model->startChecker();
65         }
66 }
67
68 /** @brief Constructor */
69 ModelChecker::ModelChecker() :
70         /* Initialize default scheduler */
71         params(),
72         scheduler(new Scheduler()),
73         history(new ModelHistory()),
74         execution(new ModelExecution(this, scheduler)),
75         execution_number(1),
76         curr_thread_num(1),
77         trace_analyses(),
78         inspect_plugin(NULL)
79 {
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");
84         init_memory_ops();
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);
87 #ifdef TLS
88         init_thread->setTLS((char *)get_tls_addr());
89 #endif
90         execution->add_thread(init_thread);
91         scheduler->set_current_thread(init_thread);
92         register_plugins();
93         execution->setParams(&params);
94         param_defaults(&params);
95         parse_options(&params);
96         initRaceDetector();
97         /* Configure output redirection for the model-checker */
98         install_handler();
99 }
100
101 /** @brief Destructor */
102 ModelChecker::~ModelChecker()
103 {
104         delete scheduler;
105 }
106
107 /** Method to set parameters */
108 model_params * ModelChecker::getParams() {
109         return &params;
110 }
111
112 /**
113  * Restores user program to initial state and resets all model-checker data
114  * structures.
115  */
116 void ModelChecker::reset_to_initial_state()
117 {
118
119         /**
120          * FIXME: if we utilize partial rollback, we will need to free only
121          * those pending actions which were NOT pending before the rollback
122          * point
123          */
124         for (unsigned int i = 0;i < get_num_threads();i++)
125                 delete get_thread(int_to_id(i))->get_pending();
126
127         snapshot_roll_back(snapshot);
128 }
129
130 /** @return the number of user threads created during this execution */
131 unsigned int ModelChecker::get_num_threads() const
132 {
133         return execution->get_num_threads();
134 }
135
136 /**
137  * Must be called from user-thread context (e.g., through the global
138  * thread_current() interface)
139  *
140  * @return The currently executing Thread.
141  */
142 Thread * ModelChecker::get_current_thread() const
143 {
144         return scheduler->get_current_thread();
145 }
146
147 /**
148  * Must be called from user-thread context (e.g., through the global
149  * thread_current_id() interface)
150  *
151  * @return The id of the currently executing Thread.
152  */
153 thread_id_t ModelChecker::get_current_thread_id() const
154 {
155         ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
156         return int_to_id(curr_thread_num);
157 }
158
159 /**
160  * @brief Choose the next thread to execute.
161  *
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.
166  *
167  * @return The next chosen thread to run, if any exist. Or else if the current
168  * execution should terminate, return NULL.
169  */
170 Thread * ModelChecker::get_next_thread()
171 {
172
173         /*
174          * Have we completed exploring the preselected path? Then let the
175          * scheduler decide
176          */
177         return scheduler->select_next_thread();
178 }
179
180 /**
181  * @brief Assert a bug in the executing program.
182  *
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.
188  *
189  * @param msg Descriptive message for the bug (do not include newline char)
190  * @return True if bug is immediately-feasible
191  */
192 void ModelChecker::assert_bug(const char *msg, ...)
193 {
194         char str[800];
195
196         va_list ap;
197         va_start(ap, msg);
198         vsnprintf(str, sizeof(str), msg, ap);
199         va_end(ap);
200
201         execution->assert_bug(str);
202 }
203
204 /**
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)
208  */
209 void ModelChecker::assert_user_bug(const char *msg)
210 {
211         /* If feasible bug, bail out now */
212         assert_bug(msg);
213         switch_thread(NULL);
214 }
215
216 /** @brief Print bug report listing for this execution (if any bugs exist) */
217 void ModelChecker::print_bugs() const
218 {
219         SnapVector<bug_message *> *bugs = execution->get_bugs();
220
221         model_print("Bug report: %zu bug%s detected\n",
222                                                         bugs->size(),
223                                                         bugs->size() > 1 ? "s" : "");
224         for (unsigned int i = 0;i < bugs->size();i++)
225                 (*bugs)[i] -> print();
226 }
227
228 /**
229  * @brief Record end-of-execution stats
230  *
231  * Must be run when exiting an execution. Records various stats.
232  * @see struct execution_stats
233  */
234 void ModelChecker::record_stats()
235 {
236         stats.num_total ++;
237         if (execution->have_bug_reports())
238                 stats.num_buggy_executions ++;
239         else if (execution->is_complete_execution())
240                 stats.num_complete ++;
241         else {
242                 //All threads are sleeping
243                 /**
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]
247                  */
248                 //ASSERT(scheduler->all_threads_sleeping());
249         }
250 }
251
252 /** @brief Print execution stats */
253 void ModelChecker::print_stats() const
254 {
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);
258 }
259
260 /**
261  * @brief End-of-exeuction print
262  * @param printbugs Should any existing bugs be printed?
263  */
264 void ModelChecker::print_execution(bool printbugs) const
265 {
266         model_print("Program output from execution %d:\n",
267                                                         get_execution_number());
268         print_program_output();
269
270         if (params.verbose >= 3) {
271                 print_stats();
272         }
273
274         /* Don't print invalid bugs */
275         if (printbugs && execution->have_bug_reports()) {
276                 model_print("\n");
277                 print_bugs();
278         }
279
280         model_print("\n");
281         execution->print_summary();
282 }
283
284 /**
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.
287  *
288  * @return If there are more executions to explore, return true. Otherwise,
289  * return false.
290  */
291 void ModelChecker::finish_execution(bool more_executions)
292 {
293         DBG();
294         /* Is this execution a feasible execution that's worth bug-checking? */
295         bool complete = (execution->is_complete_execution() ||
296                                                                          execution->have_bug_reports());
297
298         /* End-of-execution bug checks */
299         if (complete) {
300                 if (execution->is_deadlocked())
301                         assert_bug("Deadlock detected");
302
303                 run_trace_analyses();
304         }
305
306         record_stats();
307         /* Output */
308         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
309                 print_execution(complete);
310         else
311                 clear_program_output();
312
313         execution_number ++;
314         history->set_new_exec_flag();
315
316         if (more_executions)
317                 reset_to_initial_state();
318 }
319
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());
324 }
325
326 /**
327  * @brief Get a Thread reference by its ID
328  * @param tid The Thread's ID
329  * @return A Thread reference
330  */
331 Thread * ModelChecker::get_thread(thread_id_t tid) const
332 {
333         return execution->get_thread(tid);
334 }
335
336 /**
337  * @brief Get a reference to the Thread in which a ModelAction was executed
338  * @param act The ModelAction
339  * @return A Thread reference
340  */
341 Thread * ModelChecker::get_thread(const ModelAction *act) const
342 {
343         return execution->get_thread(act);
344 }
345
346 void ModelChecker::startRunExecution(Thread *old) {
347         while (true) {
348                 if (params.traceminsize != 0 &&
349                                 execution->get_curr_seq_num() > checkfree) {
350                         checkfree += params.checkthreshold;
351                         execution->collectActions();
352                 }
353
354                 curr_thread_num = 1;
355                 Thread *thr = getNextThread(old);
356                 if (thr != nullptr) {
357                         scheduler->set_current_thread(thr);
358                         inside_model = 0;
359                         if (Thread::swap(old, thr) < 0) {
360                                 perror("swap threads");
361                                 exit(EXIT_FAILURE);
362                         }
363                         return;
364                 }
365
366                 if (!handleChosenThread(old)) {
367                         return;
368                 }
369         }
370 }
371
372 Thread* ModelChecker::getNextThread(Thread *old)
373 {
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);
378
379                 if (!thr->is_complete()) {
380                         if (!thr->get_pending()) {
381                                 curr_thread_num = i;
382                                 nextThread = thr;
383                                 break;
384                         }
385                 } else if (thr != old && !thr->is_freed()) {
386                         thr->freeResources();
387                 }
388
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);
394                         }
395
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) {
402                                                 chosen_thread = thr;
403                                         }
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) {
408                                         chosen_thread = thr;
409                                 }
410                         }
411                 }
412         }
413         return nextThread;
414 }
415
416 /* Swap back to system_context and terminate this execution */
417 void ModelChecker::finishRunExecution(Thread *old)
418 {
419         scheduler->set_current_thread(NULL);
420
421         /** Reset curr_thread_num to initial value for next execution. */
422         curr_thread_num = 1;
423
424         /** If we have more executions, we won't make it past this call. */
425         finish_execution(execution_number < params.maxexecutions);
426
427
428         /** We finished the final execution.  Print stuff and exit. */
429         model_print("******* Model-checking complete: *******\n");
430         print_stats();
431
432         /* Have the trace analyses dump their output. */
433         for (unsigned int i = 0;i < trace_analyses.size();i++)
434                 trace_analyses[i]->finish();
435
436         /* unlink tmp file created by last child process */
437         char filename[256];
438         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
439         unlink(filename);
440
441         /* Exit. */
442         _Exit(0);
443 }
444
445 uint64_t ModelChecker::switch_thread(ModelAction *act)
446 {
447         if (modellock) {
448                 static bool fork_message_printed = false;
449
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;
453                 }
454                 delete act;
455                 return 0;
456         }
457         inside_model = 1;
458
459         DBG();
460         Thread *old = thread_current();
461         old->set_state(THREAD_READY);
462
463         ASSERT(!old->get_pending());
464
465         if (inspect_plugin != NULL) {
466                 inspect_plugin->inspectModelAction(act);
467         }
468
469         old->set_pending(act);
470
471         if (old->is_waiting_on(old))
472                 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
473
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");
479                         exit(EXIT_FAILURE);
480                 }
481         } else {
482                 if (handleChosenThread(old)) {
483                         startRunExecution(old);
484                 }
485         }
486         return old->get_return_value();
487 }
488
489 bool ModelChecker::handleChosenThread(Thread *old)
490 {
491         if (execution->has_asserted()) {
492                 finishRunExecution(old);
493                 return false;
494         }
495         if (!chosen_thread) {
496                 chosen_thread = get_next_thread();
497         }
498         if (!chosen_thread) {
499                 finishRunExecution(old);
500                 return false;
501         }
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
507                 return true;
508         }
509
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);
514
515         if (should_terminate_execution()) {
516                 finishRunExecution(old);
517                 return false;
518         } else {
519                 return true;
520         }
521 }
522
523 void ModelChecker::startChecker() {
524         startExecution();
525         //Need to initial random number generator state to avoid resets on rollback
526         initstate(423121, random_state, sizeof(random_state));
527
528         snapshot = take_snapshot();
529
530         //reset random number generator state
531         setstate(random_state);
532
533         install_trace_analyses(get_execution());
534         redirect_output();
535         initMainThread();
536 }
537
538 bool ModelChecker::should_terminate_execution()
539 {
540         if (execution->have_bug_reports()) {
541                 execution->set_assert();
542                 return true;
543         } else if (execution->isFinished()) {
544                 return true;
545         }
546         return false;
547 }