Rewrite recursion in terms of loops; make it a bit faster
[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         trace_analyses(),
69         inspect_plugin(NULL)
70 {
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);
77 #ifdef TLS
78         init_thread->setTLS((char *)get_tls_addr());
79 #endif
80         execution->add_thread(init_thread);
81         scheduler->set_current_thread(init_thread);
82         register_plugins();
83         execution->setParams(&params);
84         param_defaults(&params);
85         parse_options(&params);
86         initRaceDetector();
87         /* Configure output redirection for the model-checker */
88         install_handler();
89 }
90
91 /** @brief Destructor */
92 ModelChecker::~ModelChecker()
93 {
94         delete scheduler;
95 }
96
97 /** Method to set parameters */
98 model_params * ModelChecker::getParams() {
99         return &params;
100 }
101
102 /**
103  * Restores user program to initial state and resets all model-checker data
104  * structures.
105  */
106 void ModelChecker::reset_to_initial_state()
107 {
108
109         /**
110          * FIXME: if we utilize partial rollback, we will need to free only
111          * those pending actions which were NOT pending before the rollback
112          * point
113          */
114         for (unsigned int i = 0;i < get_num_threads();i++)
115                 delete get_thread(int_to_id(i))->get_pending();
116
117         snapshot_roll_back(snapshot);
118 }
119
120 /** @return the number of user threads created during this execution */
121 unsigned int ModelChecker::get_num_threads() const
122 {
123         return execution->get_num_threads();
124 }
125
126 /**
127  * Must be called from user-thread context (e.g., through the global
128  * thread_current() interface)
129  *
130  * @return The currently executing Thread.
131  */
132 Thread * ModelChecker::get_current_thread() const
133 {
134         return scheduler->get_current_thread();
135 }
136
137 /**
138  * @brief Choose the next thread to execute.
139  *
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.
144  *
145  * @return The next chosen thread to run, if any exist. Or else if the current
146  * execution should terminate, return NULL.
147  */
148 Thread * ModelChecker::get_next_thread()
149 {
150
151         /*
152          * Have we completed exploring the preselected path? Then let the
153          * scheduler decide
154          */
155         return scheduler->select_next_thread();
156 }
157
158 /**
159  * @brief Assert a bug in the executing program.
160  *
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.
166  *
167  * @param msg Descriptive message for the bug (do not include newline char)
168  * @return True if bug is immediately-feasible
169  */
170 void ModelChecker::assert_bug(const char *msg, ...)
171 {
172         char str[800];
173
174         va_list ap;
175         va_start(ap, msg);
176         vsnprintf(str, sizeof(str), msg, ap);
177         va_end(ap);
178
179         execution->assert_bug(str);
180 }
181
182 /**
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)
186  */
187 void ModelChecker::assert_user_bug(const char *msg)
188 {
189         /* If feasible bug, bail out now */
190         assert_bug(msg);
191         switch_to_master(NULL);
192 }
193
194 /** @brief Print bug report listing for this execution (if any bugs exist) */
195 void ModelChecker::print_bugs() const
196 {
197         SnapVector<bug_message *> *bugs = execution->get_bugs();
198
199         model_print("Bug report: %zu bug%s detected\n",
200                                                         bugs->size(),
201                                                         bugs->size() > 1 ? "s" : "");
202         for (unsigned int i = 0;i < bugs->size();i++)
203                 (*bugs)[i] -> print();
204 }
205
206 /**
207  * @brief Record end-of-execution stats
208  *
209  * Must be run when exiting an execution. Records various stats.
210  * @see struct execution_stats
211  */
212 void ModelChecker::record_stats()
213 {
214         stats.num_total ++;
215         if (execution->have_bug_reports())
216                 stats.num_buggy_executions ++;
217         else if (execution->is_complete_execution())
218                 stats.num_complete ++;
219         else {
220                 //All threads are sleeping
221                 /**
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]
225                  */
226                 //ASSERT(scheduler->all_threads_sleeping());
227         }
228 }
229
230 /** @brief Print execution stats */
231 void ModelChecker::print_stats() const
232 {
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);
236 }
237
238 /**
239  * @brief End-of-exeuction print
240  * @param printbugs Should any existing bugs be printed?
241  */
242 void ModelChecker::print_execution(bool printbugs) const
243 {
244         model_print("Program output from execution %d:\n",
245                                                         get_execution_number());
246         print_program_output();
247
248         if (params.verbose >= 3) {
249                 print_stats();
250         }
251
252         /* Don't print invalid bugs */
253         if (printbugs && execution->have_bug_reports()) {
254                 model_print("\n");
255                 print_bugs();
256         }
257
258         model_print("\n");
259         execution->print_summary();
260 }
261
262 /**
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.
265  *
266  * @return If there are more executions to explore, return true. Otherwise,
267  * return false.
268  */
269 void ModelChecker::finish_execution(bool more_executions)
270 {
271         DBG();
272         /* Is this execution a feasible execution that's worth bug-checking? */
273         bool complete = (execution->is_complete_execution() ||
274                                                                          execution->have_bug_reports());
275
276         /* End-of-execution bug checks */
277         if (complete) {
278                 if (execution->is_deadlocked())
279                         assert_bug("Deadlock detected");
280
281                 run_trace_analyses();
282         }
283
284         record_stats();
285         /* Output */
286         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
287                 print_execution(complete);
288         else
289                 clear_program_output();
290
291 // test code
292         execution_number ++;
293         if (more_executions)
294                 reset_to_initial_state();
295
296         history->set_new_exec_flag();
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 /**
326  * Switch from a model-checker context to a user-thread context. This is the
327  * complement of ModelChecker::switch_to_master and must be called from the
328  * model-checker context
329  *
330  * @param thread The user-thread to switch to
331  */
332 void ModelChecker::switch_from_master(Thread *thread)
333 {
334         scheduler->set_current_thread(thread);
335         Thread::swap(&system_context, thread);
336 }
337
338 /**
339  * Switch from a user-context to the "master thread" context (a.k.a. system
340  * context). This switch is made with the intention of exploring a particular
341  * model-checking action (described by a ModelAction object). Must be called
342  * from a user-thread context.
343  *
344  * @param act The current action that will be explored. May be NULL only if
345  * trace is exiting via an assertion (see ModelExecution::set_assert and
346  * ModelExecution::has_asserted).
347  * @return Return the value returned by the current action
348  */
349 uint64_t ModelChecker::switch_to_master(ModelAction *act)
350 {
351         if (modellock) {
352                 static bool fork_message_printed = false;
353
354                 if (!fork_message_printed) {
355                         model_print("Fork handler or dead thread trying to call into model checker...\n");
356                         fork_message_printed = true;
357                 }
358                 delete act;
359                 return 0;
360         }
361         DBG();
362         Thread *old = thread_current();
363         scheduler->set_current_thread(NULL);
364         ASSERT(!old->get_pending());
365
366         if (inspect_plugin != NULL) {
367                 inspect_plugin->inspectModelAction(act);
368         }
369
370         old->set_pending(act);
371         if (Thread::swap(old, &system_context) < 0) {
372                 perror("swap threads");
373                 exit(EXIT_FAILURE);
374         }
375         return old->get_return_value();
376 }
377
378 void ModelChecker::startRunExecution(Thread *old) 
379 {
380         while (true) {
381                 if (params.traceminsize != 0 &&
382                                 execution->get_curr_seq_num() > checkfree) {
383                         checkfree += params.checkthreshold;
384                         execution->collectActions();
385                 }
386
387                 thread_chosen = false;
388                 curr_thread_num = 1;
389
390                 Thread *thr = getNextThread();
391                 if (thr != nullptr) {
392                         scheduler->set_current_thread(thr);
393
394                         if (old == thr)
395                                 return;
396
397                         if (Thread::swap(old, thr) < 0) {
398                                 perror("swap threads");
399                                 exit(EXIT_FAILURE);
400                         }
401                         continue;
402                 }
403
404                 if (execution->has_asserted()) {
405                         finishRunExecution(old);
406                         return;
407                 }
408                 if (!chosen_thread)
409                         chosen_thread = get_next_thread();
410                 if (!chosen_thread || chosen_thread->is_model_thread()) {
411                         finishRunExecution(old);
412                         return;
413                 }
414                 if (chosen_thread->just_woken_up()) {
415                         chosen_thread->set_wakeup_state(false);
416                         chosen_thread->set_pending(NULL);
417                         chosen_thread = NULL;
418                         // Allow this thread to stash the next pending action
419                         continue;
420                 }
421
422                 /* Consume the next action for a Thread */
423                 consumeAction();
424
425                 if (should_terminate_execution()) {
426                         finishRunExecution(old);
427                         return;
428                 }
429         }
430 }
431
432 Thread* ModelChecker::getNextThread()
433 {
434         Thread *nextThread = nullptr;
435         for (unsigned int i = curr_thread_num; i < get_num_threads(); i++) {
436                 thread_id_t tid = int_to_id(i);
437                 Thread *thr = get_thread(tid);
438
439                 if (!thr->is_complete() && !thr->get_pending()) {
440                         curr_thread_num = i;
441                         nextThread = thr;
442                         break;
443                 }
444
445                 /* Don't schedule threads which should be disabled */
446                 ModelAction *act = thr->get_pending();
447                 if (act && execution->is_enabled(thr) && !execution->check_action_enabled(act)) {
448                         scheduler->sleep(thr);
449                 }
450                 chooseThread(act, thr);
451         }
452         return nextThread;
453 }
454
455 /* Swap back to system_context and terminate this execution */
456 void ModelChecker::finishRunExecution(Thread *old) 
457 {
458         scheduler->set_current_thread(NULL);
459         if (Thread::swap(old, &system_context) < 0) {
460                 perror("swap threads");
461                 exit(EXIT_FAILURE);
462         }
463         break_execution = true;
464 }
465
466 void ModelChecker::consumeAction()
467 {
468         ModelAction *curr = chosen_thread->get_pending();
469         Thread * th = thread_current();
470         if (curr->get_type() == THREAD_FINISH && th != NULL)  {
471                 // Thread finish must be consumed in the master context
472                 scheduler->set_current_thread(NULL);
473                 if (Thread::swap(th, &system_context) < 0) {
474                         perror("swap threads");
475                         exit(EXIT_FAILURE);
476                 }
477         } else {
478                 chosen_thread->set_pending(NULL);
479                 chosen_thread = execution->take_step(curr);
480         }
481 }
482
483 /* Allow pending relaxed/release stores or thread actions to perform first */
484 void ModelChecker::chooseThread(ModelAction *act, Thread *thr)
485 {
486         if (!thread_chosen && act && execution->is_enabled(thr) && (thr->get_state() != THREAD_BLOCKED) ) {
487                 if (act->is_write()) {
488                         std::memory_order order = act->get_mo();
489                         if (order == std::memory_order_relaxed || \
490                                         order == std::memory_order_release) {
491                                 chosen_thread = thr;
492                                 thread_chosen = true;
493                         }
494                 } else if (act->get_type() == THREAD_CREATE || \
495                                                         act->get_type() == PTHREAD_CREATE || \
496                                                         act->get_type() == THREAD_START || \
497                                                         act->get_type() == THREAD_FINISH) {
498                         chosen_thread = thr;
499                         thread_chosen = true;
500                 }
501         }
502 }
503
504 uint64_t ModelChecker::switch_thread(ModelAction *act)
505 {
506         if (modellock) {
507                 static bool fork_message_printed = false;
508
509                 if (!fork_message_printed) {
510                         model_print("Fork handler or dead thread trying to call into model checker...\n");
511                         fork_message_printed = true;
512                 }
513                 delete act;
514                 return 0;
515         }
516         DBG();
517         Thread *old = thread_current();
518         ASSERT(!old->get_pending());
519
520         if (inspect_plugin != NULL) {
521                 inspect_plugin->inspectModelAction(act);
522         }
523
524         old->set_pending(act);
525         
526         if (old->is_waiting_on(old))
527                 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
528
529         if (act && execution->is_enabled(old) && !execution->check_action_enabled(act)) {
530                 scheduler->sleep(old);
531         }
532         chooseThread(act, old);
533
534         curr_thread_num++;
535         Thread* next = getNextThread();
536         if (next != nullptr) {
537                 scheduler->set_current_thread(next);
538                 if (Thread::swap(old, next) < 0) {
539                         perror("swap threads");
540                         exit(EXIT_FAILURE);
541                 }
542         } else
543                 handleChosenThread(old);
544
545         return old->get_return_value();
546 }
547
548 void ModelChecker::handleChosenThread(Thread *old)
549 {
550         if (execution->has_asserted()) {
551                 finishRunExecution(old);
552                 return;
553         }
554         if (!chosen_thread)
555                 chosen_thread = get_next_thread();
556         if (!chosen_thread || chosen_thread->is_model_thread()) {
557                 finishRunExecution(old);
558                 return;
559         }
560         if (chosen_thread->just_woken_up()) {
561                 chosen_thread->set_wakeup_state(false);
562                 chosen_thread->set_pending(NULL);
563                 chosen_thread = NULL;
564                 // Allow this thread to stash the next pending action
565                 startRunExecution(old);
566                 return;
567         }
568
569         // Consume the next action for a Thread
570         consumeAction();
571
572         if (should_terminate_execution()) {
573                 finishRunExecution(old);
574                 return;
575         } else
576                 startRunExecution(old);
577 }
578
579 static void runChecker() {
580         model->run();
581         delete model;
582 }
583
584 void ModelChecker::startChecker() {
585         startExecution(get_system_context(), runChecker);
586         snapshot = take_snapshot();
587
588         install_trace_analyses(get_execution());
589         redirect_output();
590         initMainThread();
591 }
592
593 bool ModelChecker::should_terminate_execution()
594 {
595         if (execution->have_bug_reports()) {
596                 execution->set_assert();
597                 return true;
598         } else if (execution->isFinished()) {
599                 return true;
600         }
601         return false;
602 }
603
604 /** @brief Run ModelChecker for the user program */
605 void ModelChecker::run()
606 {
607         //Need to initial random number generator state to avoid resets on rollback
608         char random_state[256];
609         initstate(423121, random_state, sizeof(random_state));
610         checkfree = params.checkthreshold;
611         for(int exec = 0;exec < params.maxexecutions;exec++) {
612                 chosen_thread = init_thread;
613                 break_execution = false;
614                 do {
615                         if (params.traceminsize != 0 &&
616                                         execution->get_curr_seq_num() > checkfree) {
617                                 checkfree += params.checkthreshold;
618                                 execution->collectActions();
619                         }
620
621                         thread_chosen = false;
622                         curr_thread_num = 1;
623                         Thread *thr = getNextThread();
624                         if (thr != nullptr) {
625                                 switch_from_master(thr);
626                                 continue;
627                         }
628
629                         if (break_execution)
630                                 break;
631                         if (execution->has_asserted())
632                                 break;
633                         if (!chosen_thread)
634                                 chosen_thread = get_next_thread();
635                         if (!chosen_thread || chosen_thread->is_model_thread())
636                                 break;
637                         if (chosen_thread->just_woken_up()) {
638                                 chosen_thread->set_wakeup_state(false);
639                                 chosen_thread->set_pending(NULL);
640                                 chosen_thread = NULL;
641                                 continue;
642                         }
643
644                         /* Consume the next action for a Thread */
645                         ModelAction *curr = chosen_thread->get_pending();
646                         chosen_thread->set_pending(NULL);
647                         chosen_thread = execution->take_step(curr);
648                 } while (!should_terminate_execution());
649
650                 finish_execution((exec+1) < params.maxexecutions);
651                 //restore random number generator state after rollback
652                 setstate(random_state);
653         }
654
655         model_print("******* Model-checking complete: *******\n");
656         print_stats();
657
658         /* Have the trace analyses dump their output. */
659         for (unsigned int i = 0;i < trace_analyses.size();i++)
660                 trace_analyses[i]->finish();
661
662         /* unlink tmp file created by last child process */
663         char filename[256];
664         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
665         unlink(filename);
666 }