Find a faster way to get currently executing thread's id
[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  * Must be called from user-thread context (e.g., through the global
140  * thread_current_id() interface)
141  *
142  * @return The id of the currently executing Thread.
143  */
144 thread_id_t ModelChecker::get_current_thread_id() const
145 {
146         ASSERT(int_to_id(curr_thread_num) == get_current_thread()->get_id());
147         return int_to_id(curr_thread_num);
148 }
149
150 /**
151  * @brief Choose the next thread to execute.
152  *
153  * This function chooses the next thread that should execute. It can enforce
154  * execution replay/backtracking or, if the model-checker has no preference
155  * regarding the next thread (i.e., when exploring a new execution ordering),
156  * we defer to the scheduler.
157  *
158  * @return The next chosen thread to run, if any exist. Or else if the current
159  * execution should terminate, return NULL.
160  */
161 Thread * ModelChecker::get_next_thread()
162 {
163
164         /*
165          * Have we completed exploring the preselected path? Then let the
166          * scheduler decide
167          */
168         return scheduler->select_next_thread();
169 }
170
171 /**
172  * @brief Assert a bug in the executing program.
173  *
174  * Use this function to assert any sort of bug in the user program. If the
175  * current trace is feasible (actually, a prefix of some feasible execution),
176  * then this execution will be aborted, printing the appropriate message. If
177  * the current trace is not yet feasible, the error message will be stashed and
178  * printed if the execution ever becomes feasible.
179  *
180  * @param msg Descriptive message for the bug (do not include newline char)
181  * @return True if bug is immediately-feasible
182  */
183 void ModelChecker::assert_bug(const char *msg, ...)
184 {
185         char str[800];
186
187         va_list ap;
188         va_start(ap, msg);
189         vsnprintf(str, sizeof(str), msg, ap);
190         va_end(ap);
191
192         execution->assert_bug(str);
193 }
194
195 /**
196  * @brief Assert a bug in the executing program, asserted by a user thread
197  * @see ModelChecker::assert_bug
198  * @param msg Descriptive message for the bug (do not include newline char)
199  */
200 void ModelChecker::assert_user_bug(const char *msg)
201 {
202         /* If feasible bug, bail out now */
203         assert_bug(msg);
204         switch_thread(NULL);
205 }
206
207 /** @brief Print bug report listing for this execution (if any bugs exist) */
208 void ModelChecker::print_bugs() const
209 {
210         SnapVector<bug_message *> *bugs = execution->get_bugs();
211
212         model_print("Bug report: %zu bug%s detected\n",
213                                                         bugs->size(),
214                                                         bugs->size() > 1 ? "s" : "");
215         for (unsigned int i = 0;i < bugs->size();i++)
216                 (*bugs)[i] -> print();
217 }
218
219 /**
220  * @brief Record end-of-execution stats
221  *
222  * Must be run when exiting an execution. Records various stats.
223  * @see struct execution_stats
224  */
225 void ModelChecker::record_stats()
226 {
227         stats.num_total ++;
228         if (execution->have_bug_reports())
229                 stats.num_buggy_executions ++;
230         else if (execution->is_complete_execution())
231                 stats.num_complete ++;
232         else {
233                 //All threads are sleeping
234                 /**
235                  * @todo We can violate this ASSERT() when fairness/sleep sets
236                  * conflict to cause an execution to terminate, e.g. with:
237                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
238                  */
239                 //ASSERT(scheduler->all_threads_sleeping());
240         }
241 }
242
243 /** @brief Print execution stats */
244 void ModelChecker::print_stats() const
245 {
246         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
247         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
248         model_print("Total executions: %d\n", stats.num_total);
249 }
250
251 /**
252  * @brief End-of-exeuction print
253  * @param printbugs Should any existing bugs be printed?
254  */
255 void ModelChecker::print_execution(bool printbugs) const
256 {
257         model_print("Program output from execution %d:\n",
258                                                         get_execution_number());
259         print_program_output();
260
261         if (params.verbose >= 3) {
262                 print_stats();
263         }
264
265         /* Don't print invalid bugs */
266         if (printbugs && execution->have_bug_reports()) {
267                 model_print("\n");
268                 print_bugs();
269         }
270
271         model_print("\n");
272         execution->print_summary();
273 }
274
275 /**
276  * Queries the model-checker for more executions to explore and, if one
277  * exists, resets the model-checker state to execute a new execution.
278  *
279  * @return If there are more executions to explore, return true. Otherwise,
280  * return false.
281  */
282 void ModelChecker::finish_execution(bool more_executions)
283 {
284         DBG();
285         /* Is this execution a feasible execution that's worth bug-checking? */
286         bool complete = (execution->is_complete_execution() ||
287                                                                          execution->have_bug_reports());
288
289         /* End-of-execution bug checks */
290         if (complete) {
291                 if (execution->is_deadlocked())
292                         assert_bug("Deadlock detected");
293
294                 run_trace_analyses();
295         }
296
297         record_stats();
298         /* Output */
299         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
300                 print_execution(complete);
301         else
302                 clear_program_output();
303
304         execution_number ++;
305         history->set_new_exec_flag();
306
307         if (more_executions)
308                 reset_to_initial_state();
309 }
310
311 /** @brief Run trace analyses on complete trace */
312 void ModelChecker::run_trace_analyses() {
313         for (unsigned int i = 0;i < trace_analyses.size();i ++)
314                 trace_analyses[i] -> analyze(execution->get_action_trace());
315 }
316
317 /**
318  * @brief Get a Thread reference by its ID
319  * @param tid The Thread's ID
320  * @return A Thread reference
321  */
322 Thread * ModelChecker::get_thread(thread_id_t tid) const
323 {
324         return execution->get_thread(tid);
325 }
326
327 /**
328  * @brief Get a reference to the Thread in which a ModelAction was executed
329  * @param act The ModelAction
330  * @return A Thread reference
331  */
332 Thread * ModelChecker::get_thread(const ModelAction *act) const
333 {
334         return execution->get_thread(act);
335 }
336
337 void ModelChecker::startRunExecution(Thread *old) {
338         while (true) {
339                 if (params.traceminsize != 0 &&
340                                 execution->get_curr_seq_num() > checkfree) {
341                         checkfree += params.checkthreshold;
342                         execution->collectActions();
343                 }
344
345                 thread_chosen = false;
346                 curr_thread_num = 1;
347                 Thread *thr = getNextThread(old);
348                 if (thr != nullptr) {
349                         scheduler->set_current_thread(thr);
350
351                         if (Thread::swap(old, thr) < 0) {
352                                 perror("swap threads");
353                                 exit(EXIT_FAILURE);
354                         }
355                         return;
356                 }
357
358                 if (!handleChosenThread(old)) {
359                         return;
360                 }
361         }
362 }
363
364 Thread* ModelChecker::getNextThread(Thread *old)
365 {
366         Thread *nextThread = nullptr;
367         for (unsigned int i = curr_thread_num;i < get_num_threads();i++) {
368                 thread_id_t tid = int_to_id(i);
369                 Thread *thr = get_thread(tid);
370
371                 if (!thr->is_complete()) {
372                         if (!thr->get_pending()) {
373                                 curr_thread_num = i;
374                                 nextThread = thr;
375                                 break;
376                         }
377                 } else if (thr != old && !thr->is_freed()) {
378                         thr->freeResources();
379                 }
380
381                 ModelAction *act = thr->get_pending();
382                 if (act && execution->is_enabled(tid)){
383                         /* Don't schedule threads which should be disabled */
384                         if (!execution->check_action_enabled(act)) {
385                                 scheduler->sleep(thr);
386                         }
387
388                         /* Allow pending relaxed/release stores or thread actions to perform first */
389                         else if (!thread_chosen) {
390                                 if (act->is_write()) {
391                                         std::memory_order order = act->get_mo();
392                                         if (order == std::memory_order_relaxed || \
393                                                         order == std::memory_order_release) {
394                                                 chosen_thread = thr;
395                                                 thread_chosen = true;
396                                         }
397                                 } else if (act->get_type() == THREAD_CREATE || \
398                                                                          act->get_type() == PTHREAD_CREATE || \
399                                                                          act->get_type() == THREAD_START || \
400                                                                          act->get_type() == THREAD_FINISH) {
401                                         chosen_thread = thr;
402                                         thread_chosen = true;
403                                 }
404                         }
405                 }
406         }
407         return nextThread;
408 }
409
410 /* Swap back to system_context and terminate this execution */
411 void ModelChecker::finishRunExecution(Thread *old)
412 {
413         scheduler->set_current_thread(NULL);
414
415         /** Reset curr_thread_num to initial value for next execution. */
416         curr_thread_num = 1;
417
418         /** If we have more executions, we won't make it past this call. */
419         finish_execution(execution_number < params.maxexecutions);
420
421
422         /** We finished the final execution.  Print stuff and exit. */
423         model_print("******* Model-checking complete: *******\n");
424         print_stats();
425
426         /* Have the trace analyses dump their output. */
427         for (unsigned int i = 0;i < trace_analyses.size();i++)
428                 trace_analyses[i]->finish();
429
430         /* unlink tmp file created by last child process */
431         char filename[256];
432         snprintf_(filename, sizeof(filename), "C11FuzzerTmp%d", getpid());
433         unlink(filename);
434
435         /* Exit. */
436         _Exit(0);
437 }
438
439 uint64_t ModelChecker::switch_thread(ModelAction *act)
440 {
441         if (modellock) {
442                 static bool fork_message_printed = false;
443
444                 if (!fork_message_printed) {
445                         model_print("Fork handler or dead thread trying to call into model checker...\n");
446                         fork_message_printed = true;
447                 }
448                 delete act;
449                 return 0;
450         }
451         DBG();
452         Thread *old = thread_current();
453         old->set_state(THREAD_READY);
454
455         ASSERT(!old->get_pending());
456
457         if (inspect_plugin != NULL) {
458                 inspect_plugin->inspectModelAction(act);
459         }
460
461         old->set_pending(act);
462
463         if (old->is_waiting_on(old))
464                 assert_bug("Deadlock detected (thread %u)", curr_thread_num);
465
466         Thread* next = getNextThread(old);
467         if (next != nullptr) {
468                 scheduler->set_current_thread(next);
469                 if (Thread::swap(old, next) < 0) {
470                         perror("swap threads");
471                         exit(EXIT_FAILURE);
472                 }
473         } else {
474                 if (handleChosenThread(old)) {
475                         startRunExecution(old);
476                 }
477         }
478         return old->get_return_value();
479 }
480
481 bool ModelChecker::handleChosenThread(Thread *old)
482 {
483         if (execution->has_asserted()) {
484                 finishRunExecution(old);
485                 return false;
486         }
487         if (!chosen_thread) {
488                 chosen_thread = get_next_thread();
489         }
490         if (!chosen_thread || chosen_thread->is_model_thread()) {
491                 finishRunExecution(old);
492                 return false;
493         }
494         if (chosen_thread->just_woken_up()) {
495                 chosen_thread->set_wakeup_state(false);
496                 chosen_thread->set_pending(NULL);
497                 chosen_thread = NULL;
498                 // Allow this thread to stash the next pending action
499                 return true;
500         }
501
502         // Consume the next action for a Thread
503         ModelAction *curr = chosen_thread->get_pending();
504         chosen_thread->set_pending(NULL);
505         chosen_thread = execution->take_step(curr);
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 }