Simplify 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 "history.h"
19 #include "bugmessage.h"
20 #include "params.h"
21 #include "plugins.h"
22
23 ModelChecker *model = NULL;
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
60 /** @brief Constructor */
61 ModelChecker::ModelChecker() :
62         /* Initialize default scheduler */
63         params(),
64         scheduler(new Scheduler()),
65         history(new ModelHistory()),
66         execution(new ModelExecution(this, scheduler)),
67         execution_number(1),
68         curr_thread_num(1),
69         trace_analyses(),
70         inspect_plugin(NULL)
71 {
72         model_print("C11Tester\n"
73                                                         "Copyright (c) 2013 and 2019 Regents of the University of California. All rights reserved.\n"
74                                                         "Distributed under the GPLv2\n"
75                                                         "Written by Weiyu Luo, Brian Norris, and Brian Demsky\n\n");
76         memset(&stats,0,sizeof(struct execution_stats));
77         init_thread = new Thread(execution->get_next_id(), (thrd_t *) model_malloc(sizeof(thrd_t)), &placeholder, NULL, NULL);
78 #ifdef TLS
79         init_thread->setTLS((char *)get_tls_addr());
80 #endif
81         execution->add_thread(init_thread);
82         scheduler->set_current_thread(init_thread);
83         register_plugins();
84         execution->setParams(&params);
85         param_defaults(&params);
86         parse_options(&params);
87         initRaceDetector();
88         /* Configure output redirection for the model-checker */
89         install_handler();
90 }
91
92 /** @brief Destructor */
93 ModelChecker::~ModelChecker()
94 {
95         delete scheduler;
96 }
97
98 /** Method to set parameters */
99 model_params * ModelChecker::getParams() {
100         return &params;
101 }
102
103 /**
104  * Restores user program to initial state and resets all model-checker data
105  * structures.
106  */
107 void ModelChecker::reset_to_initial_state()
108 {
109
110         /**
111          * FIXME: if we utilize partial rollback, we will need to free only
112          * those pending actions which were NOT pending before the rollback
113          * point
114          */
115         for (unsigned int i = 0;i < get_num_threads();i++)
116                 delete get_thread(int_to_id(i))->get_pending();
117
118         snapshot_roll_back(snapshot);
119 }
120
121 /** @return the number of user threads created during this execution */
122 unsigned int ModelChecker::get_num_threads() const
123 {
124         return execution->get_num_threads();
125 }
126
127 /**
128  * Must be called from user-thread context (e.g., through the global
129  * thread_current() interface)
130  *
131  * @return The currently executing Thread.
132  */
133 Thread * ModelChecker::get_current_thread() const
134 {
135         return scheduler->get_current_thread();
136 }
137
138 /**
139  * @brief Choose the next thread to execute.
140  *
141  * This function chooses the next thread that should execute. It can enforce
142  * execution replay/backtracking or, if the model-checker has no preference
143  * regarding the next thread (i.e., when exploring a new execution ordering),
144  * we defer to the scheduler.
145  *
146  * @return The next chosen thread to run, if any exist. Or else if the current
147  * execution should terminate, return NULL.
148  */
149 Thread * ModelChecker::get_next_thread()
150 {
151
152         /*
153          * Have we completed exploring the preselected path? Then let the
154          * scheduler decide
155          */
156         return scheduler->select_next_thread();
157 }
158
159 /**
160  * @brief Assert a bug in the executing program.
161  *
162  * Use this function to assert any sort of bug in the user program. If the
163  * current trace is feasible (actually, a prefix of some feasible execution),
164  * then this execution will be aborted, printing the appropriate message. If
165  * the current trace is not yet feasible, the error message will be stashed and
166  * printed if the execution ever becomes feasible.
167  *
168  * @param msg Descriptive message for the bug (do not include newline char)
169  * @return True if bug is immediately-feasible
170  */
171 void ModelChecker::assert_bug(const char *msg, ...)
172 {
173         char str[800];
174
175         va_list ap;
176         va_start(ap, msg);
177         vsnprintf(str, sizeof(str), msg, ap);
178         va_end(ap);
179
180         execution->assert_bug(str);
181 }
182
183 /**
184  * @brief Assert a bug in the executing program, asserted by a user thread
185  * @see ModelChecker::assert_bug
186  * @param msg Descriptive message for the bug (do not include newline char)
187  */
188 void ModelChecker::assert_user_bug(const char *msg)
189 {
190         /* If feasible bug, bail out now */
191         assert_bug(msg);
192         switch_thread(NULL);
193 }
194
195 /** @brief Print bug report listing for this execution (if any bugs exist) */
196 void ModelChecker::print_bugs() const
197 {
198         SnapVector<bug_message *> *bugs = execution->get_bugs();
199
200         model_print("Bug report: %zu bug%s detected\n",
201                                                         bugs->size(),
202                                                         bugs->size() > 1 ? "s" : "");
203         for (unsigned int i = 0;i < bugs->size();i++)
204                 (*bugs)[i] -> print();
205 }
206
207 /**
208  * @brief Record end-of-execution stats
209  *
210  * Must be run when exiting an execution. Records various stats.
211  * @see struct execution_stats
212  */
213 void ModelChecker::record_stats()
214 {
215         stats.num_total ++;
216         if (execution->have_bug_reports())
217                 stats.num_buggy_executions ++;
218         else if (execution->is_complete_execution())
219                 stats.num_complete ++;
220         else {
221                 //All threads are sleeping
222                 /**
223                  * @todo We can violate this ASSERT() when fairness/sleep sets
224                  * conflict to cause an execution to terminate, e.g. with:
225                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
226                  */
227                 //ASSERT(scheduler->all_threads_sleeping());
228         }
229 }
230
231 /** @brief Print execution stats */
232 void ModelChecker::print_stats() const
233 {
234         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
235         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
236         model_print("Total executions: %d\n", stats.num_total);
237 }
238
239 /**
240  * @brief End-of-exeuction print
241  * @param printbugs Should any existing bugs be printed?
242  */
243 void ModelChecker::print_execution(bool printbugs) const
244 {
245         model_print("Program output from execution %d:\n",
246                                                         get_execution_number());
247         print_program_output();
248
249         if (params.verbose >= 3) {
250                 print_stats();
251         }
252
253         /* Don't print invalid bugs */
254         if (printbugs && execution->have_bug_reports()) {
255                 model_print("\n");
256                 print_bugs();
257         }
258
259         model_print("\n");
260         execution->print_summary();
261 }
262
263 /**
264  * Queries the model-checker for more executions to explore and, if one
265  * exists, resets the model-checker state to execute a new execution.
266  *
267  * @return If there are more executions to explore, return true. Otherwise,
268  * return false.
269  */
270 void ModelChecker::finish_execution(bool more_executions)
271 {
272         DBG();
273         /* Is this execution a feasible execution that's worth bug-checking? */
274         bool complete = (execution->is_complete_execution() ||
275                                                                          execution->have_bug_reports());
276
277         /* End-of-execution bug checks */
278         if (complete) {
279                 if (execution->is_deadlocked())
280                         assert_bug("Deadlock detected");
281
282                 run_trace_analyses();
283         }
284
285         record_stats();
286         /* Output */
287         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
288                 print_execution(complete);
289         else
290                 clear_program_output();
291
292         execution_number ++;
293         history->set_new_exec_flag();
294
295         if (more_executions)
296                 reset_to_initial_state();
297 }
298
299 /** @brief Run trace analyses on complete trace */
300 void ModelChecker::run_trace_analyses() {
301         for (unsigned int i = 0;i < trace_analyses.size();i ++)
302                 trace_analyses[i] -> analyze(execution->get_action_trace());
303 }
304
305 /**
306  * @brief Get a Thread reference by its ID
307  * @param tid The Thread's ID
308  * @return A Thread reference
309  */
310 Thread * ModelChecker::get_thread(thread_id_t tid) const
311 {
312         return execution->get_thread(tid);
313 }
314
315 /**
316  * @brief Get a reference to the Thread in which a ModelAction was executed
317  * @param act The ModelAction
318  * @return A Thread reference
319  */
320 Thread * ModelChecker::get_thread(const ModelAction *act) const
321 {
322         return execution->get_thread(act);
323 }
324
325 void ModelChecker::startRunExecution(Thread *old) {
326         while (true) {
327                 if (params.traceminsize != 0 &&
328                                 execution->get_curr_seq_num() > checkfree) {
329                         checkfree += params.checkthreshold;
330                         execution->collectActions();
331                 }
332
333                 thread_chosen = false;
334                 curr_thread_num = 1;
335
336                 Thread *thr = getNextThread(old);
337                 if (thr != nullptr) {
338                         scheduler->set_current_thread(thr);
339
340                         if (Thread::swap(old, thr) < 0) {
341                                 perror("swap threads");
342                                 exit(EXIT_FAILURE);
343                         }
344                         return;
345                 }
346
347                 if (!handleChosenThread(old)) {
348                         return;
349                 }
350         }
351 }
352
353 Thread* ModelChecker::getNextThread(Thread *old)
354 {
355         Thread *nextThread = nullptr;
356         for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
357                 thread_id_t tid = int_to_id(i);
358                 Thread *thr = get_thread(tid);
359
360                 if (!thr->is_complete()) {
361                         if (!thr->get_pending()) {
362                                 curr_thread_num = i;
363                                 nextThread = thr;
364                                 break;
365                         }
366                 } else if (thr != old && !thr->is_freed()) {
367                         thr->freeResources();
368                 }
369
370                 /* Don't schedule threads which should be disabled */
371                 ModelAction *act = thr->get_pending();
372                 if (act && execution->is_enabled(thr) && !execution->check_action_enabled(act)) {
373                         scheduler->sleep(thr);
374                 }
375                 chooseThread(act, thr);
376         }
377         return nextThread;
378 }
379
380 /* Swap back to system_context and terminate this execution */
381 void ModelChecker::finishRunExecution(Thread *old)
382 {
383         scheduler->set_current_thread(NULL);
384
385         /** Reset curr_thread_num to initial value for next execution. */
386         curr_thread_num = 1;
387
388         /** If we have more executions, we won't make it past this call. */
389         finish_execution(execution_number < params.maxexecutions);
390
391
392         /** We finished the final execution.  Print stuff and exit. */
393         model_print("******* Model-checking complete: *******\n");
394         print_stats();
395
396         /* Have the trace analyses dump their output. */
397         for (unsigned int i = 0;i < trace_analyses.size();i++)
398                 trace_analyses[i]->finish();
399
400         /* unlink tmp file created by last child process */
401         char filename[256];
402         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
403         unlink(filename);
404
405         /* Exit. */
406         _Exit(0);
407 }
408
409 void ModelChecker::consumeAction()
410 {
411         ModelAction *curr = chosen_thread->get_pending();
412         chosen_thread->set_pending(NULL);
413         chosen_thread = execution->take_step(curr);
414 }
415
416 /* Allow pending relaxed/release stores or thread actions to perform first */
417 void ModelChecker::chooseThread(ModelAction *act, Thread *thr)
418 {
419         if (!thread_chosen && act && execution->is_enabled(thr) && (thr->get_state() != THREAD_BLOCKED) ) {
420                 if (act->is_write()) {
421                         std::memory_order order = act->get_mo();
422                         if (order == std::memory_order_relaxed || \
423                                         order == std::memory_order_release) {
424                                 chosen_thread = thr;
425                                 thread_chosen = true;
426                         }
427                 } else if (act->get_type() == THREAD_CREATE || \
428                                                          act->get_type() == PTHREAD_CREATE || \
429                                                          act->get_type() == THREAD_START || \
430                                                          act->get_type() == THREAD_FINISH) {
431                         chosen_thread = thr;
432                         thread_chosen = true;
433                 }
434         }
435 }
436
437 uint64_t ModelChecker::switch_thread(ModelAction *act)
438 {
439         if (modellock) {
440                 static bool fork_message_printed = false;
441
442                 if (!fork_message_printed) {
443                         model_print("Fork handler or dead thread trying to call into model checker...\n");
444                         fork_message_printed = true;
445                 }
446                 delete act;
447                 return 0;
448         }
449         DBG();
450         Thread *old = thread_current();
451         old->set_state(THREAD_READY);
452
453         ASSERT(!old->get_pending());
454
455         if (inspect_plugin != NULL) {
456                 inspect_plugin->inspectModelAction(act);
457         }
458
459         old->set_pending(act);
460
461         if (old->is_waiting_on(old))
462                 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
463
464         if (act && execution->is_enabled(old) && !execution->check_action_enabled(act)) {
465                 scheduler->sleep(old);
466         }
467
468         Thread* next = getNextThread(old);
469         if (next != nullptr) {
470                 scheduler->set_current_thread(next);
471                 if (Thread::swap(old, next) < 0) {
472                         perror("swap threads");
473                         exit(EXIT_FAILURE);
474                 }
475         } else {
476                 if (handleChosenThread(old)) {
477                         startRunExecution(old);
478                 }
479         }
480         return old->get_return_value();
481 }
482
483 bool ModelChecker::handleChosenThread(Thread *old)
484 {
485         if (execution->has_asserted()) {
486                 finishRunExecution(old);
487                 return false;
488         }
489         if (!chosen_thread) {
490                 chosen_thread = get_next_thread();
491         }
492         if (!chosen_thread || chosen_thread->is_model_thread()) {
493                 finishRunExecution(old);
494                 return false;
495         }
496         if (chosen_thread->just_woken_up()) {
497                 chosen_thread->set_wakeup_state(false);
498                 chosen_thread->set_pending(NULL);
499                 chosen_thread = NULL;
500                 // Allow this thread to stash the next pending action
501                 return true;
502         }
503
504         // Consume the next action for a Thread
505         consumeAction();
506
507         if (should_terminate_execution()) {
508                 finishRunExecution(old);
509                 return false;
510         } else {
511                 return true;
512         }
513 }
514
515 void ModelChecker::startChecker() {
516         startExecution();
517         //Need to initial random number generator state to avoid resets on rollback
518         initstate(423121, random_state, sizeof(random_state));
519
520         snapshot = take_snapshot();
521
522         //reset random number generator state
523         setstate(random_state);
524
525         install_trace_analyses(get_execution());
526         redirect_output();
527         initMainThread();
528 }
529
530 bool ModelChecker::should_terminate_execution()
531 {
532         if (execution->have_bug_reports()) {
533                 execution->set_assert();
534                 return true;
535         } else if (execution->isFinished()) {
536                 return true;
537         }
538         return false;
539 }