try to add support for pthread_create/pthread_join
[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 "nodestack.h"
11 #include "schedule.h"
12 #include "snapshot-interface.h"
13 #include "common.h"
14 #include "datarace.h"
15 #include "threads-model.h"
16 #include "output.h"
17 #include "traceanalysis.h"
18 #include "execution.h"
19 #include "bugmessage.h"
20
21 ModelChecker *model;
22
23 /** @brief Constructor */
24 ModelChecker::ModelChecker(struct model_params params) :
25         /* Initialize default scheduler */
26         params(params),
27         restart_flag(false),
28         exit_flag(false),
29         scheduler(new Scheduler()),
30         node_stack(new NodeStack()),
31         execution(new ModelExecution(this, &this->params, scheduler, node_stack)),      // L: Model thread is created inside
32         execution_number(1),
33         diverge(NULL),
34         earliest_diverge(NULL),
35         trace_analyses(),
36         inspect_plugin(NULL)
37 {
38         memset(&stats,0,sizeof(struct execution_stats));
39 }
40
41 /** @brief Destructor */
42 ModelChecker::~ModelChecker()
43 {
44         delete node_stack;
45         delete scheduler;
46 }
47
48 /**
49  * Restores user program to initial state and resets all model-checker data
50  * structures.
51  */
52 void ModelChecker::reset_to_initial_state()
53 {
54         DEBUG("+++ Resetting to initial state +++\n");
55         node_stack->reset_execution();
56
57         /**
58          * FIXME: if we utilize partial rollback, we will need to free only
59          * those pending actions which were NOT pending before the rollback
60          * point
61          */
62         for (unsigned int i = 0; i < get_num_threads(); i++)
63                 delete get_thread(int_to_id(i))->get_pending();
64
65         snapshot_backtrack_before(0);
66 }
67
68 /** @return the number of user threads created during this execution */
69 unsigned int ModelChecker::get_num_threads() const
70 {
71         return execution->get_num_threads();
72 }
73
74 /**
75  * Must be called from user-thread context (e.g., through the global
76  * thread_current() interface)
77  *
78  * @return The currently executing Thread.
79  */
80 Thread * ModelChecker::get_current_thread() const
81 {
82         return scheduler->get_current_thread();
83 }
84
85 /**
86  * @brief Choose the next thread to execute.
87  *
88  * This function chooses the next thread that should execute. It can enforce
89  * execution replay/backtracking or, if the model-checker has no preference
90  * regarding the next thread (i.e., when exploring a new execution ordering),
91  * we defer to the scheduler.
92  *
93  * @return The next chosen thread to run, if any exist. Or else if the current
94  * execution should terminate, return NULL.
95  */
96 Thread * ModelChecker::get_next_thread()
97 {
98         thread_id_t tid;
99
100         /*
101          * Have we completed exploring the preselected path? Then let the
102          * scheduler decide
103          */
104         if (diverge == NULL)    // W: diverge is set to NULL permanently
105                 return scheduler->select_next_thread(node_stack->get_head());
106
107         /* Else, we are trying to replay an execution */
108         ModelAction *next = node_stack->get_next()->get_action();
109
110         if (next == diverge) {
111                 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
112                         earliest_diverge = diverge;
113
114                 Node *nextnode = next->get_node();
115                 Node *prevnode = nextnode->get_parent();
116                 scheduler->update_sleep_set(prevnode);
117
118                 /* Reached divergence point */
119                 if (nextnode->increment_behaviors()) {
120                         /* Execute the same thread with a new behavior */
121                         tid = next->get_tid();
122                         node_stack->pop_restofstack(2);
123                 } else {
124                         ASSERT(prevnode);
125                         /* Make a different thread execute for next step */
126                         scheduler->add_sleep(get_thread(next->get_tid()));
127                         tid = prevnode->get_next_backtrack();
128                         /* Make sure the backtracked thread isn't sleeping. */
129                         node_stack->pop_restofstack(1);
130                         if (diverge == earliest_diverge) {
131                                 earliest_diverge = prevnode->get_action();
132                         }
133                 }
134                 /* Start the round robin scheduler from this thread id */
135                 scheduler->set_scheduler_thread(tid);
136                 /* The correct sleep set is in the parent node. */
137                 execute_sleep_set();
138
139                 DEBUG("*** Divergence point ***\n");
140
141                 diverge = NULL;
142         } else {
143                 tid = next->get_tid();
144         }
145         DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
146         ASSERT(tid != THREAD_ID_T_NONE);
147         return get_thread(id_to_int(tid));
148 }
149
150 /**
151  * We need to know what the next actions of all threads in the sleep
152  * set will be.  This method computes them and stores the actions at
153  * the corresponding thread object's pending action.
154  */
155 void ModelChecker::execute_sleep_set()
156 {
157         for (unsigned int i = 0; i < get_num_threads(); i++) {
158                 thread_id_t tid = int_to_id(i);
159                 Thread *thr = get_thread(tid);
160                 if (scheduler->is_sleep_set(thr) && thr->get_pending()) {
161                         thr->get_pending()->set_sleep_flag();
162                 }
163         }
164 }
165
166 /**
167  * @brief Assert a bug in the executing program.
168  *
169  * Use this function to assert any sort of bug in the user program. If the
170  * current trace is feasible (actually, a prefix of some feasible execution),
171  * then this execution will be aborted, printing the appropriate message. If
172  * the current trace is not yet feasible, the error message will be stashed and
173  * printed if the execution ever becomes feasible.
174  *
175  * @param msg Descriptive message for the bug (do not include newline char)
176  * @return True if bug is immediately-feasible
177  */
178 bool ModelChecker::assert_bug(const char *msg, ...)
179 {
180         char str[800];
181
182         va_list ap;
183         va_start(ap, msg);
184         vsnprintf(str, sizeof(str), msg, ap);
185         va_end(ap);
186
187         return execution->assert_bug(str);
188 }
189
190 /**
191  * @brief Assert a bug in the executing program, asserted by a user thread
192  * @see ModelChecker::assert_bug
193  * @param msg Descriptive message for the bug (do not include newline char)
194  */
195 void ModelChecker::assert_user_bug(const char *msg)
196 {
197         /* If feasible bug, bail out now */
198         if (assert_bug(msg))
199                 switch_to_master(NULL);
200 }
201
202 /** @brief Print bug report listing for this execution (if any bugs exist) */
203 void ModelChecker::print_bugs() const
204 {
205         SnapVector<bug_message *> *bugs = execution->get_bugs();
206
207         model_print("Bug report: %zu bug%s detected\n",
208                         bugs->size(),
209                         bugs->size() > 1 ? "s" : "");
210         for (unsigned int i = 0; i < bugs->size(); i++)
211                 (*bugs)[i]->print();
212 }
213
214 /**
215  * @brief Record end-of-execution stats
216  *
217  * Must be run when exiting an execution. Records various stats.
218  * @see struct execution_stats
219  */
220 void ModelChecker::record_stats()
221 {
222         stats.num_total++;
223         if (!execution->isfeasibleprefix())
224                 stats.num_infeasible++;
225         else if (execution->have_bug_reports())
226                 stats.num_buggy_executions++;
227         else if (execution->is_complete_execution())
228                 stats.num_complete++;
229         else {
230                 stats.num_redundant++;
231
232                 /**
233                  * @todo We can violate this ASSERT() when fairness/sleep sets
234                  * conflict to cause an execution to terminate, e.g. with:
235                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
236                  */
237                 //ASSERT(scheduler->all_threads_sleeping());
238         }
239 }
240
241 /** @brief Print execution stats */
242 void ModelChecker::print_stats() const
243 {
244         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
245         model_print("Number of redundant executions: %d\n", stats.num_redundant);
246         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
247         model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
248         model_print("Total executions: %d\n", stats.num_total);
249         if (params.verbose)
250                 model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
251 }
252
253 /**
254  * @brief End-of-exeuction print
255  * @param printbugs Should any existing bugs be printed?
256  */
257 void ModelChecker::print_execution(bool printbugs) const
258 {
259         model_print("Program output from execution %d:\n",
260                         get_execution_number());
261         print_program_output();
262
263         if (params.verbose >= 3) {
264                 model_print("\nEarliest divergence point since last feasible execution:\n");
265                 if (earliest_diverge)
266                         earliest_diverge->print();
267                 else
268                         model_print("(Not set)\n");
269
270                 model_print("\n");
271                 print_stats();
272         }
273
274         /* Don't print invalid bugs */
275         if (printbugs && execution->have_bug_reports()) {
276                 model_print("\n");
277                 print_bugs();
278         }
279
280         model_print("\n");
281         execution->print_summary();
282 }
283
284 /**
285  * Queries the model-checker for more executions to explore and, if one
286  * exists, resets the model-checker state to execute a new execution.
287  *
288  * @return If there are more executions to explore, return true. Otherwise,
289  * return false.
290  */
291 bool ModelChecker::next_execution()
292 {
293         DBG();
294         /* Is this execution a feasible execution that's worth bug-checking? */
295         bool complete = execution->isfeasibleprefix() &&
296                 (execution->is_complete_execution() ||
297                  execution->have_bug_reports());
298
299         /* End-of-execution bug checks */
300         if (complete) {
301                 if (execution->is_deadlocked())
302                         assert_bug("Deadlock detected");
303
304                 checkDataRaces();
305                 run_trace_analyses();
306         } 
307
308         record_stats();
309         /* Output */
310         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
311                 print_execution(complete);
312         else
313                 clear_program_output();
314
315         if (restart_flag) {
316                 do_restart();
317                 return true;
318         }
319 // test code
320         execution_number++;
321         reset_to_initial_state();
322         node_stack->pop_restofstack(2);
323 //      node_stack->full_reset();
324         diverge = NULL;
325         return false;
326 /* test
327         if (complete)
328                 earliest_diverge = NULL;
329
330         if (exit_flag)
331                 return false;
332
333 //      diverge = execution->get_next_backtrack();
334         if (diverge == NULL) {
335                 execution_number++;
336                 reset_to_initial_state();
337                 model_print("Does not diverge\n");
338                 return false;
339         } 
340
341         if (DBG_ENABLED()) {
342                 model_print("Next execution will diverge at:\n");
343                 diverge->print();
344         }
345
346         execution_number++;
347
348         if (params.maxexecutions != 0 && stats.num_complete >= params.maxexecutions)
349                 return false;
350
351         reset_to_initial_state();
352         return true;
353 */
354
355 }
356
357 /** @brief Run trace analyses on complete trace */
358 void ModelChecker::run_trace_analyses() {
359         for (unsigned int i = 0; i < trace_analyses.size(); i++)
360                 trace_analyses[i]->analyze(execution->get_action_trace());
361 }
362
363 /**
364  * @brief Get a Thread reference by its ID
365  * @param tid The Thread's ID
366  * @return A Thread reference
367  */
368 Thread * ModelChecker::get_thread(thread_id_t tid) const
369 {
370         return execution->get_thread(tid);
371 }
372
373 /**
374  * @brief Get a reference to the Thread in which a ModelAction was executed
375  * @param act The ModelAction
376  * @return A Thread reference
377  */
378 Thread * ModelChecker::get_thread(const ModelAction *act) const
379 {
380         return execution->get_thread(act);
381 }
382
383 /**
384  * Switch from a model-checker context to a user-thread context. This is the
385  * complement of ModelChecker::switch_to_master and must be called from the
386  * model-checker context
387  *
388  * @param thread The user-thread to switch to
389  */
390 void ModelChecker::switch_from_master(Thread *thread)
391 {
392         scheduler->set_current_thread(thread);
393         Thread::swap(&system_context, thread);
394 }
395
396 /**
397  * Switch from a user-context to the "master thread" context (a.k.a. system
398  * context). This switch is made with the intention of exploring a particular
399  * model-checking action (described by a ModelAction object). Must be called
400  * from a user-thread context.
401  *
402  * @param act The current action that will be explored. May be NULL only if
403  * trace is exiting via an assertion (see ModelExecution::set_assert and
404  * ModelExecution::has_asserted).
405  * @return Return the value returned by the current action
406  */
407 uint64_t ModelChecker::switch_to_master(ModelAction *act)
408 {
409         DBG();
410         Thread *old = thread_current();
411         scheduler->set_current_thread(NULL);
412         ASSERT(!old->get_pending());
413 /* W: No plugin
414         if (inspect_plugin != NULL) {
415                 inspect_plugin->inspectModelAction(act); 
416         }*/
417         old->set_pending(act);
418         if (Thread::swap(old, &system_context) < 0) {
419                 perror("swap threads");
420                 exit(EXIT_FAILURE);
421         }
422         return old->get_return_value();
423 }
424
425 /** Wrapper to run the user's main function, with appropriate arguments */
426 void user_main_wrapper(void *)
427 {
428         user_main(model->params.argc, model->params.argv);
429 }
430
431 bool ModelChecker::should_terminate_execution()
432 {
433         /* Infeasible -> don't take any more steps */
434         if (execution->is_infeasible())
435                 return true;
436         else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
437                 execution->set_assert();
438                 return true;
439         }
440
441         if (execution->too_many_steps())
442                 return true;
443         return false;
444 }
445
446 /** @brief Exit ModelChecker upon returning to the run loop of the
447  *      model checker. */
448 void ModelChecker::exit_model_checker()
449 {
450         exit_flag = true;
451 }
452
453 /** @brief Restart ModelChecker upon returning to the run loop of the
454  *      model checker. */
455 void ModelChecker::restart()
456 {
457         restart_flag = true;
458 }
459
460 void ModelChecker::do_restart()
461 {
462         restart_flag = false;
463         diverge = NULL;
464         earliest_diverge = NULL;
465         reset_to_initial_state();
466         node_stack->full_reset();
467         memset(&stats,0,sizeof(struct execution_stats));
468         execution_number = 1;
469 }
470
471 /** @brief Run ModelChecker for the user program */
472 void ModelChecker::run()
473 {
474         bool has_next;
475         int i = 0;
476         do {
477                 thrd_t user_thread;
478                 Thread *t = new Thread(execution->get_next_id(), &user_thread, &user_main_wrapper, NULL, NULL); // L: user_main_wrapper passes the user program
479                 execution->add_thread(t);
480                 do {
481                         /*
482                          * Stash next pending action(s) for thread(s). There
483                          * should only need to stash one thread's action--the
484                          * thread which just took a step--plus the first step
485                          * for any newly-created thread
486                          */
487
488                         for (unsigned int i = 0; i < get_num_threads(); i++) {
489                                 thread_id_t tid = int_to_id(i);
490                                 Thread *thr = get_thread(tid);
491                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
492                                         switch_from_master(thr);        // L: context swapped, and action type of thr changed. 
493                                         if (thr->is_waiting_on(thr))
494                                                 assert_bug("Deadlock detected (thread %u)", i);
495                                 }
496                         }
497
498                         /* Don't schedule threads which should be disabled */
499                         for (unsigned int i = 0; i < get_num_threads(); i++) {
500                                 Thread *th = get_thread(int_to_id(i));
501                                 ModelAction *act = th->get_pending();
502                                 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
503                                         scheduler->sleep(th);
504                                 }
505                         }
506                         /* Catch assertions from prior take_step or from
507                          * between-ModelAction bugs (e.g., data races) */
508
509                         for (unsigned int i = 1; i < get_num_threads(); i++) {
510                                 Thread *th = get_thread(int_to_id(i));
511                                 ModelAction *act = th->get_pending();
512                                 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ){
513                                         if (act->is_write()){
514                                                 std::memory_order order = act->get_mo(); 
515                                                 if (order == std::memory_order_relaxed || \
516                                                         order == std::memory_order_release) {
517                                                         t = th;
518                                                         break;
519                                                 }
520                                         } else if (act->get_type() == THREAD_CREATE || \
521                                                         act->get_type() == PTHREAD_CREATE || \ // WL
522                                                         act->get_type() == THREAD_START || \
523                                                         act->get_type() == THREAD_FINISH) {
524                                                 t = th;
525                                                 break;
526                                         }                               
527                                 }
528                         }
529
530
531                         if (execution->has_asserted())
532                                 break;
533                         if (!t)                         
534                                 t = get_next_thread();
535                         if (!t || t->is_model_thread())
536                                 break;
537
538                         /* Consume the next action for a Thread */
539                         ModelAction *curr = t->get_pending();
540                         t->set_pending(NULL);
541                         t = execution->take_step(curr);
542                 } while (!should_terminate_execution());
543
544                 has_next = next_execution();
545                 i++;
546         } while (i<1); // while (has_next);
547
548         execution->fixup_release_sequences();
549
550         model_print("******* Model-checking complete: *******\n");
551         print_stats();
552
553         /* Have the trace analyses dump their output. */
554         for (unsigned int i = 0; i < trace_analyses.size(); i++)
555                 trace_analyses[i]->finish();
556 }