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