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