a4bba3cf38a769a0baf9246384a19390ea62175f
[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         return scheduler->select_next_thread(node_stack->get_head());
105 }
106
107 /**
108  * We need to know what the next actions of all threads in the sleep
109  * set will be.  This method computes them and stores the actions at
110  * the corresponding thread object's pending action.
111  */
112 void ModelChecker::execute_sleep_set()
113 {
114         for (unsigned int i = 0; i < get_num_threads(); i++) {
115                 thread_id_t tid = int_to_id(i);
116                 Thread *thr = get_thread(tid);
117                 if (scheduler->is_sleep_set(thr) && thr->get_pending()) {
118                         thr->get_pending()->set_sleep_flag();
119                 }
120         }
121 }
122
123 /**
124  * @brief Assert a bug in the executing program.
125  *
126  * Use this function to assert any sort of bug in the user program. If the
127  * current trace is feasible (actually, a prefix of some feasible execution),
128  * then this execution will be aborted, printing the appropriate message. If
129  * the current trace is not yet feasible, the error message will be stashed and
130  * printed if the execution ever becomes feasible.
131  *
132  * @param msg Descriptive message for the bug (do not include newline char)
133  * @return True if bug is immediately-feasible
134  */
135 bool ModelChecker::assert_bug(const char *msg, ...)
136 {
137         char str[800];
138
139         va_list ap;
140         va_start(ap, msg);
141         vsnprintf(str, sizeof(str), msg, ap);
142         va_end(ap);
143
144         return execution->assert_bug(str);
145 }
146
147 /**
148  * @brief Assert a bug in the executing program, asserted by a user thread
149  * @see ModelChecker::assert_bug
150  * @param msg Descriptive message for the bug (do not include newline char)
151  */
152 void ModelChecker::assert_user_bug(const char *msg)
153 {
154         /* If feasible bug, bail out now */
155         if (assert_bug(msg))
156                 switch_to_master(NULL);
157 }
158
159 /** @brief Print bug report listing for this execution (if any bugs exist) */
160 void ModelChecker::print_bugs() const
161 {
162         SnapVector<bug_message *> *bugs = execution->get_bugs();
163
164         model_print("Bug report: %zu bug%s detected\n",
165                         bugs->size(),
166                         bugs->size() > 1 ? "s" : "");
167         for (unsigned int i = 0; i < bugs->size(); i++)
168                 (*bugs)[i]->print();
169 }
170
171 /**
172  * @brief Record end-of-execution stats
173  *
174  * Must be run when exiting an execution. Records various stats.
175  * @see struct execution_stats
176  */
177 void ModelChecker::record_stats()
178 {
179         stats.num_total++;
180         if (!execution->isfeasibleprefix())
181                 stats.num_infeasible++;
182         else if (execution->have_bug_reports())
183                 stats.num_buggy_executions++;
184         else if (execution->is_complete_execution())
185                 stats.num_complete++;
186         else {
187                 stats.num_redundant++;
188
189                 /**
190                  * @todo We can violate this ASSERT() when fairness/sleep sets
191                  * conflict to cause an execution to terminate, e.g. with:
192                  * Scheduler: [0: disabled][1: disabled][2: sleep][3: current, enabled]
193                  */
194                 //ASSERT(scheduler->all_threads_sleeping());
195         }
196 }
197
198 /** @brief Print execution stats */
199 void ModelChecker::print_stats() const
200 {
201         model_print("Number of complete, bug-free executions: %d\n", stats.num_complete);
202         model_print("Number of redundant executions: %d\n", stats.num_redundant);
203         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
204         model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
205         model_print("Total executions: %d\n", stats.num_total);
206         if (params.verbose)
207                 model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
208 }
209
210 /**
211  * @brief End-of-exeuction print
212  * @param printbugs Should any existing bugs be printed?
213  */
214 void ModelChecker::print_execution(bool printbugs) const
215 {
216         model_print("Program output from execution %d:\n",
217                         get_execution_number());
218         print_program_output();
219
220         if (params.verbose >= 3) {
221                 model_print("\nEarliest divergence point since last feasible execution:\n");
222                 if (earliest_diverge)
223                         earliest_diverge->print();
224                 else
225                         model_print("(Not set)\n");
226
227                 model_print("\n");
228                 print_stats();
229         }
230
231         /* Don't print invalid bugs */
232         if (printbugs && execution->have_bug_reports()) {
233                 model_print("\n");
234                 print_bugs();
235         }
236
237         model_print("\n");
238         execution->print_summary();
239 }
240
241 /**
242  * Queries the model-checker for more executions to explore and, if one
243  * exists, resets the model-checker state to execute a new execution.
244  *
245  * @return If there are more executions to explore, return true. Otherwise,
246  * return false.
247  */
248 bool ModelChecker::next_execution()
249 {
250         DBG();
251         /* Is this execution a feasible execution that's worth bug-checking? */
252         bool complete = execution->isfeasibleprefix() &&
253                 (execution->is_complete_execution() ||
254                  execution->have_bug_reports());
255
256         /* End-of-execution bug checks */
257         if (complete) {
258                 if (execution->is_deadlocked())
259                         assert_bug("Deadlock detected");
260
261                 checkDataRaces();
262                 run_trace_analyses();
263         } 
264
265         record_stats();
266         /* Output */
267         if ( (complete && params.verbose) || params.verbose>1 || (complete && execution->have_bug_reports()))
268                 print_execution(complete);
269         else
270                 clear_program_output();
271
272         if (restart_flag) {
273                 do_restart();
274                 return true;
275         }
276 // test code
277         execution_number++;
278         reset_to_initial_state();
279         node_stack->full_reset();
280         diverge = NULL;
281         return false;
282 /* test
283         if (complete)
284                 earliest_diverge = NULL;
285
286         if (exit_flag)
287                 return false;
288
289 //      diverge = execution->get_next_backtrack();
290         if (diverge == NULL) {
291                 execution_number++;
292                 reset_to_initial_state();
293                 model_print("Does not diverge\n");
294                 return false;
295         } 
296
297         if (DBG_ENABLED()) {
298                 model_print("Next execution will diverge at:\n");
299                 diverge->print();
300         }
301
302         execution_number++;
303
304         if (params.maxexecutions != 0 && stats.num_complete >= params.maxexecutions)
305                 return false;
306
307         reset_to_initial_state();
308         return true;
309 */
310
311 }
312
313 /** @brief Run trace analyses on complete trace */
314 void ModelChecker::run_trace_analyses() {
315         for (unsigned int i = 0; i < trace_analyses.size(); i++)
316                 trace_analyses[i]->analyze(execution->get_action_trace());
317 }
318
319 /**
320  * @brief Get a Thread reference by its ID
321  * @param tid The Thread's ID
322  * @return A Thread reference
323  */
324 Thread * ModelChecker::get_thread(thread_id_t tid) const
325 {
326         return execution->get_thread(tid);
327 }
328
329 /**
330  * @brief Get a reference to the Thread in which a ModelAction was executed
331  * @param act The ModelAction
332  * @return A Thread reference
333  */
334 Thread * ModelChecker::get_thread(const ModelAction *act) const
335 {
336         return execution->get_thread(act);
337 }
338
339 /**
340  * Switch from a model-checker context to a user-thread context. This is the
341  * complement of ModelChecker::switch_to_master and must be called from the
342  * model-checker context
343  *
344  * @param thread The user-thread to switch to
345  */
346 void ModelChecker::switch_from_master(Thread *thread)
347 {
348         scheduler->set_current_thread(thread);
349         Thread::swap(&system_context, thread);
350 }
351
352 /**
353  * Switch from a user-context to the "master thread" context (a.k.a. system
354  * context). This switch is made with the intention of exploring a particular
355  * model-checking action (described by a ModelAction object). Must be called
356  * from a user-thread context.
357  *
358  * @param act The current action that will be explored. May be NULL only if
359  * trace is exiting via an assertion (see ModelExecution::set_assert and
360  * ModelExecution::has_asserted).
361  * @return Return the value returned by the current action
362  */
363 uint64_t ModelChecker::switch_to_master(ModelAction *act)
364 {
365         DBG();
366         Thread *old = thread_current();
367         scheduler->set_current_thread(NULL);
368         ASSERT(!old->get_pending());
369 /* W: No plugin
370         if (inspect_plugin != NULL) {
371                 inspect_plugin->inspectModelAction(act); 
372         }*/
373         old->set_pending(act);
374         if (Thread::swap(old, &system_context) < 0) {
375                 perror("swap threads");
376                 exit(EXIT_FAILURE);
377         }
378         return old->get_return_value();
379 }
380
381 /** Wrapper to run the user's main function, with appropriate arguments */
382 void user_main_wrapper(void *)
383 {
384         user_main(model->params.argc, model->params.argv);
385 }
386
387 bool ModelChecker::should_terminate_execution()
388 {
389         /* Infeasible -> don't take any more steps */
390         if (execution->is_infeasible())
391                 return true;
392         else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
393                 execution->set_assert();
394                 return true;
395         }
396
397         if (execution->too_many_steps())
398                 return true;
399         return false;
400 }
401
402 /** @brief Exit ModelChecker upon returning to the run loop of the
403  *      model checker. */
404 void ModelChecker::exit_model_checker()
405 {
406         exit_flag = true;
407 }
408
409 /** @brief Restart ModelChecker upon returning to the run loop of the
410  *      model checker. */
411 void ModelChecker::restart()
412 {
413         restart_flag = true;
414 }
415
416 void ModelChecker::do_restart()
417 {
418         restart_flag = false;
419         diverge = NULL;
420         earliest_diverge = NULL;
421         reset_to_initial_state();
422         node_stack->full_reset();
423         memset(&stats,0,sizeof(struct execution_stats));
424         execution_number = 1;
425 }
426
427 /** @brief Run ModelChecker for the user program */
428 void ModelChecker::run()
429 {
430         bool has_next;
431         int i = 0;
432         do {
433                 thrd_t user_thread;
434                 Thread *t = new Thread(execution->get_next_id(), &user_thread, &user_main_wrapper, NULL, NULL); // L: user_main_wrapper passes the user program
435                 execution->add_thread(t);
436                 do {
437                         /*
438                          * Stash next pending action(s) for thread(s). There
439                          * should only need to stash one thread's action--the
440                          * thread which just took a step--plus the first step
441                          * for any newly-created thread
442                          */
443
444                         for (unsigned int i = 0; i < get_num_threads(); i++) {
445                                 thread_id_t tid = int_to_id(i);
446                                 Thread *thr = get_thread(tid);
447                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
448                                         switch_from_master(thr);        // L: context swapped, and action type of thr changed. 
449                                         if (thr->is_waiting_on(thr))
450                                                 assert_bug("Deadlock detected (thread %u)", i);
451                                 }
452                         }
453
454                         /* Don't schedule threads which should be disabled */
455                         for (unsigned int i = 0; i < get_num_threads(); i++) {
456                                 Thread *th = get_thread(int_to_id(i));
457                                 ModelAction *act = th->get_pending();
458                                 if (act && execution->is_enabled(th) && !execution->check_action_enabled(act)) {
459                                         scheduler->sleep(th);
460                                 }
461                         }
462
463                         for (unsigned int i = 1; i < get_num_threads(); i++) {
464                                 Thread *th = get_thread(int_to_id(i));
465                                 ModelAction *act = th->get_pending();
466                                 if (act && execution->is_enabled(th) && (th->get_state() != THREAD_BLOCKED) ){
467                                         if (act->is_write()){
468                                                 std::memory_order order = act->get_mo(); 
469                                                 if (order == std::memory_order_relaxed || \
470                                                         order == std::memory_order_release) {
471                                                         t = th;
472                                                         break;
473                                                 }
474                                         } else if (act->get_type() == THREAD_CREATE || \
475                                                         act->get_type() == PTHREAD_CREATE || \
476                                                         act->get_type() == THREAD_START || \
477                                                         act->get_type() == THREAD_FINISH) {
478                                                 t = th;
479                                                 break;
480                                         }                               
481                                 }
482                         }
483
484                         /* Catch assertions from prior take_step or from
485                          * between-ModelAction bugs (e.g., data races) */
486
487                         if (execution->has_asserted())
488                                 break;
489                         if (!t)                         
490                                 t = get_next_thread();
491                         if (!t || t->is_model_thread())
492                                 break;
493
494                         /* Consume the next action for a Thread */
495                         ModelAction *curr = t->get_pending();
496                         t->set_pending(NULL);
497                         t = execution->take_step(curr);
498                 } while (!should_terminate_execution());
499
500                 has_next = next_execution();
501                 i++;
502         } while (i<2); // while (has_next);
503
504         execution->fixup_release_sequences();
505
506         model_print("******* Model-checking complete: *******\n");
507         print_stats();
508
509         /* Have the trace analyses dump their output. */
510         for (unsigned int i = 0; i < trace_analyses.size(); i++)
511                 trace_analyses[i]->finish();
512 }