remove unused code
[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 "bugmessage.h"
19 #include "params.h"
20 #include "plugins.h"
21
22 ModelChecker *model = NULL;
23 int inside_model = 0;
24
25 void placeholder(void *) {
26         ASSERT(0);
27 }
28
29 #include <signal.h>
30
31 #define SIGSTACKSIZE 65536
32 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
33 {
34         model_print("Segmentation fault at %p\n", si->si_addr);
35         model_print("For debugging, place breakpoint at: %s:%d\n",
36                                                         __FILE__, __LINE__);
37         print_trace();  // Trace printing may cause dynamic memory allocation
38         while(1)
39                 ;
40 }
41
42 void install_handler() {
43         stack_t ss;
44         ss.ss_sp = model_malloc(SIGSTACKSIZE);
45         ss.ss_size = SIGSTACKSIZE;
46         ss.ss_flags = 0;
47         sigaltstack(&ss, NULL);
48         struct sigaction sa;
49         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
50         sigemptyset(&sa.sa_mask);
51         sa.sa_sigaction = mprot_handle_pf;
52
53         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
54                 perror("sigaction(SIGSEGV)");
55                 exit(EXIT_FAILURE);
56         }
57 }
58
59 void createModelIfNotExist() {
60         if (!model) {
61                 ENTER_MODEL_FLAG;
62                 snapshot_system_init(100000);
63                 model = new ModelChecker();
64                 model->startChecker();
65                 EXIT_MODEL_FLAG;
66         }
67 }
68
69 /** @brief Constructor */
70 ModelChecker::ModelChecker() :
71         /* Initialize default scheduler */
72         params(),
73         scheduler(new Scheduler()),
74         execution(new ModelExecution(this, scheduler)),
75         execution_number(1),
76         curr_thread_num(MAIN_THREAD_ID),
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         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);
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 #ifdef PRINT_TRACE
282         execution->print_summary();
283 #endif
284 }
285
286 /**
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.
289  *
290  * @return If there are more executions to explore, return true. Otherwise,
291  * return false.
292  */
293 void ModelChecker::finish_execution(bool more_executions)
294 {
295         DBG();
296         /* Is this execution a feasible execution that's worth bug-checking? */
297         bool complete = (execution->is_complete_execution() ||
298                                                                          execution->have_bug_reports());
299
300         /* End-of-execution bug checks */
301         if (complete) {
302                 if (execution->is_deadlocked())
303                         assert_bug("Deadlock detected");
304
305                 run_trace_analyses();
306         }
307
308         record_stats();
309         /* Output */
310         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
311                 print_execution(complete);
312         else
313                 clear_program_output();
314
315         execution_number ++;
316
317         if (more_executions)
318                 reset_to_initial_state();
319 }
320
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());
325 }
326
327 /**
328  * @brief Get a Thread reference by its ID
329  * @param tid The Thread's ID
330  * @return A Thread reference
331  */
332 Thread * ModelChecker::get_thread(thread_id_t tid) const
333 {
334         return execution->get_thread(tid);
335 }
336
337 /**
338  * @brief Get a reference to the Thread in which a ModelAction was executed
339  * @param act The ModelAction
340  * @return A Thread reference
341  */
342 Thread * ModelChecker::get_thread(const ModelAction *act) const
343 {
344         return execution->get_thread(act);
345 }
346
347 void ModelChecker::startRunExecution(Thread *old) {
348         while (true) {
349                 if (params.traceminsize != 0 &&
350                                 execution->get_curr_seq_num() > checkfree) {
351                         checkfree += params.checkthreshold;
352                         execution->collectActions();
353                 }
354
355                 curr_thread_num = MAIN_THREAD_ID;
356                 Thread *thr = getNextThread(old);
357                 if (thr != nullptr) {
358                         scheduler->set_current_thread(thr);
359                         EXIT_MODEL_FLAG;
360                         if (Thread::swap(old, thr) < 0) {
361                                 perror("swap threads");
362                                 exit(EXIT_FAILURE);
363                         }
364                         return;
365                 }
366
367                 if (!handleChosenThread(old)) {
368                         return;
369                 }
370         }
371 }
372
373 Thread* ModelChecker::getNextThread(Thread *old)
374 {
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);
379
380                 if (!thr->is_complete()) {
381                         if (!thr->get_pending()) {
382                                 curr_thread_num = i;
383                                 nextThread = thr;
384                                 break;
385                         }
386                 } else if (thr != old && !thr->is_freed()) {
387                         thr->freeResources();
388                 }
389
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);
395                         }
396
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) {
403                                                 chosen_thread = thr;
404                                         }
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) {
409                                         chosen_thread = thr;
410                                 }
411                         }
412                 }
413         }
414         return nextThread;
415 }
416
417 /* Swap back to system_context and terminate this execution */
418 void ModelChecker::finishRunExecution(Thread *old)
419 {
420         scheduler->set_current_thread(NULL);
421
422         /** Reset curr_thread_num to initial value for next execution. */
423         curr_thread_num = MAIN_THREAD_ID;
424
425         /** If we have more executions, we won't make it past this call. */
426         finish_execution(execution_number < params.maxexecutions);
427
428
429         /** We finished the final execution.  Print stuff and exit. */
430         model_print("******* Model-checking complete: *******\n");
431         print_stats();
432
433         /* Have the trace analyses dump their output. */
434         for (unsigned int i = 0;i < trace_analyses.size();i++)
435                 trace_analyses[i]->finish();
436
437         /* unlink tmp file created by last child process */
438         char filename[256];
439         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
440         unlink(filename);
441
442         /* Exit. */
443         _Exit(0);
444 }
445
446 uint64_t ModelChecker::switch_thread(ModelAction *act)
447 {
448         if (modellock) {
449                 static bool fork_message_printed = false;
450
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;
454                 }
455                 delete act;
456                 return 0;
457         }
458         ENTER_MODEL_FLAG;
459
460         DBG();
461         Thread *old = thread_current();
462         old->set_state(THREAD_READY);
463
464         ASSERT(!old->get_pending());
465
466         if (inspect_plugin != NULL) {
467                 inspect_plugin->inspectModelAction(act);
468         }
469
470         old->set_pending(act);
471
472         if (old->is_waiting_on(old))
473                 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
474
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");
480                         exit(EXIT_FAILURE);
481                 }
482         } else {
483                 if (handleChosenThread(old)) {
484                         startRunExecution(old);
485                 }
486         }
487         return old->get_return_value();
488 }
489
490 bool ModelChecker::handleChosenThread(Thread *old)
491 {
492         if (execution->has_asserted()) {
493                 finishRunExecution(old);
494                 return false;
495         }
496         if (!chosen_thread) {
497                 chosen_thread = get_next_thread();
498         }
499         if (!chosen_thread) {
500                 finishRunExecution(old);
501                 return false;
502         }
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
508                 return true;
509         }
510
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);
515
516         if (should_terminate_execution()) {
517                 finishRunExecution(old);
518                 return false;
519         } else {
520                 return true;
521         }
522 }
523
524 void ModelChecker::startChecker() {
525         startExecution();
526         //Need to initial random number generator state to avoid resets on rollback
527         initstate(423121, random_state, sizeof(random_state));
528
529         snapshot = take_snapshot();
530
531         //reset random number generator state
532         setstate(random_state);
533
534         install_trace_analyses(get_execution());
535         redirect_output();
536         initMainThread();
537 }
538
539 bool ModelChecker::should_terminate_execution()
540 {
541         if (execution->have_bug_reports()) {
542                 execution->set_assert();
543                 return true;
544         } else if (execution->isFinished()) {
545                 return true;
546         }
547         return false;
548 }