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