55949730f5c2a00428618dd8cfbe8bf65c96747f
[cdsspec-compiler.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3 #include <mutex>
4 #include <new>
5 #include <stdarg.h>
6
7 #include "model.h"
8 #include "action.h"
9 #include "nodestack.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 "bugmessage.h"
19
20 #define INITIAL_THREAD_ID       0
21
22 ModelChecker *model;
23
24 /** @brief Constructor */
25 ModelChecker::ModelChecker(struct model_params params) :
26         /* Initialize default scheduler */
27         params(params),
28         scheduler(new Scheduler()),
29         node_stack(new NodeStack()),
30         execution(new ModelExecution(&params, scheduler, node_stack)),
31         diverge(NULL),
32         earliest_diverge(NULL),
33         trace_analyses(new ModelVector<TraceAnalysis *>())
34 {
35 }
36
37 /** @brief Destructor */
38 ModelChecker::~ModelChecker()
39 {
40         delete node_stack;
41         for (unsigned int i = 0; i < trace_analyses->size(); i++)
42                 delete (*trace_analyses)[i];
43         delete trace_analyses;
44         delete scheduler;
45 }
46
47 /**
48  * Restores user program to initial state and resets all model-checker data
49  * structures.
50  */
51 void ModelChecker::reset_to_initial_state()
52 {
53         DEBUG("+++ Resetting to initial state +++\n");
54         node_stack->reset_execution();
55
56         /**
57          * FIXME: if we utilize partial rollback, we will need to free only
58          * those pending actions which were NOT pending before the rollback
59          * point
60          */
61         for (unsigned int i = 0; i < get_num_threads(); i++)
62                 delete get_thread(int_to_id(i))->get_pending();
63
64         snapshot_backtrack_before(0);
65 }
66
67 /** @return the number of user threads created during this execution */
68 unsigned int ModelChecker::get_num_threads() const
69 {
70         return execution->get_num_threads();
71 }
72
73 /**
74  * Must be called from user-thread context (e.g., through the global
75  * thread_current() interface)
76  *
77  * @return The currently executing Thread.
78  */
79 Thread * ModelChecker::get_current_thread() const
80 {
81         return scheduler->get_current_thread();
82 }
83
84 /**
85  * @brief Choose the next thread to execute.
86  *
87  * This function chooses the next thread that should execute. It can enforce
88  * execution replay/backtracking or, if the model-checker has no preference
89  * regarding the next thread (i.e., when exploring a new execution ordering),
90  * we defer to the scheduler.
91  *
92  * @return The next chosen thread to run, if any exist. Or else if the current
93  * execution should terminate, return NULL.
94  */
95 Thread * ModelChecker::get_next_thread()
96 {
97         thread_id_t tid;
98
99         /*
100          * Have we completed exploring the preselected path? Then let the
101          * scheduler decide
102          */
103         if (diverge == NULL)
104                 return scheduler->select_next_thread(node_stack->get_head());
105
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         if (execution->have_bug_reports()) {
206                 SnapVector<bug_message *> *bugs = execution->get_bugs();
207
208                 model_print("Bug report: %zu bug%s detected\n",
209                                 bugs->size(),
210                                 bugs->size() > 1 ? "s" : "");
211                 for (unsigned int i = 0; i < bugs->size(); i++)
212                         (*bugs)[i]->print();
213         }
214 }
215
216 /**
217  * @brief Record end-of-execution stats
218  *
219  * Must be run when exiting an execution. Records various stats.
220  * @see struct execution_stats
221  */
222 void ModelChecker::record_stats()
223 {
224         stats.num_total++;
225         if (!execution->isfeasibleprefix())
226                 stats.num_infeasible++;
227         else if (execution->have_bug_reports())
228                 stats.num_buggy_executions++;
229         else if (execution->is_complete_execution())
230                 stats.num_complete++;
231         else {
232                 stats.num_redundant++;
233
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 redundant executions: %d\n", stats.num_redundant);
248         model_print("Number of buggy executions: %d\n", stats.num_buggy_executions);
249         model_print("Number of infeasible executions: %d\n", stats.num_infeasible);
250         model_print("Total executions: %d\n", stats.num_total);
251         model_print("Total nodes created: %d\n", node_stack->get_total_nodes());
252 }
253
254 /**
255  * @brief End-of-exeuction print
256  * @param printbugs Should any existing bugs be printed?
257  */
258 void ModelChecker::print_execution(bool printbugs) const
259 {
260         print_program_output();
261
262         if (params.verbose) {
263                 model_print("Earliest divergence point since last feasible execution:\n");
264                 if (earliest_diverge)
265                         earliest_diverge->print();
266                 else
267                         model_print("(Not set)\n");
268
269                 model_print("\n");
270                 print_stats();
271         }
272
273         /* Don't print invalid bugs */
274         if (printbugs)
275                 print_bugs();
276
277         model_print("\n");
278         execution->print_summary();
279 }
280
281 /**
282  * Queries the model-checker for more executions to explore and, if one
283  * exists, resets the model-checker state to execute a new execution.
284  *
285  * @return If there are more executions to explore, return true. Otherwise,
286  * return false.
287  */
288 bool ModelChecker::next_execution()
289 {
290         DBG();
291         /* Is this execution a feasible execution that's worth bug-checking? */
292         bool complete = execution->isfeasibleprefix() &&
293                 (execution->is_complete_execution() ||
294                  execution->have_bug_reports());
295
296         /* End-of-execution bug checks */
297         if (complete) {
298                 if (execution->is_deadlocked())
299                         assert_bug("Deadlock detected");
300
301                 checkDataRaces();
302                 run_trace_analyses();
303         }
304
305         record_stats();
306
307         /* Output */
308         if (params.verbose || (complete && execution->have_bug_reports()))
309                 print_execution(complete);
310         else
311                 clear_program_output();
312
313         if (complete)
314                 earliest_diverge = NULL;
315
316         if ((diverge = execution->get_next_backtrack()) == NULL)
317                 return false;
318
319         if (DBG_ENABLED()) {
320                 model_print("Next execution will diverge at:\n");
321                 diverge->print();
322         }
323
324         execution->increment_execution_number();
325         reset_to_initial_state();
326         return true;
327 }
328
329 /** @brief Run trace analyses on complete trace */
330 void ModelChecker::run_trace_analyses() {
331         for (unsigned int i = 0; i < trace_analyses->size(); i++)
332                 (*trace_analyses)[i]->analyze(execution->get_action_trace());
333 }
334
335 /**
336  * @brief Get a Thread reference by its ID
337  * @param tid The Thread's ID
338  * @return A Thread reference
339  */
340 Thread * ModelChecker::get_thread(thread_id_t tid) const
341 {
342         return execution->get_thread(tid);
343 }
344
345 /**
346  * @brief Get a reference to the Thread in which a ModelAction was executed
347  * @param act The ModelAction
348  * @return A Thread reference
349  */
350 Thread * ModelChecker::get_thread(const ModelAction *act) const
351 {
352         return execution->get_thread(act);
353 }
354
355 /**
356  * @brief Check if a Thread is currently enabled
357  * @param t The Thread to check
358  * @return True if the Thread is currently enabled
359  */
360 bool ModelChecker::is_enabled(Thread *t) const
361 {
362         return scheduler->is_enabled(t);
363 }
364
365 /**
366  * @brief Check if a Thread is currently enabled
367  * @param tid The ID of the Thread to check
368  * @return True if the Thread is currently enabled
369  */
370 bool ModelChecker::is_enabled(thread_id_t tid) const
371 {
372         return scheduler->is_enabled(tid);
373 }
374
375 /**
376  * Switch from a model-checker context to a user-thread context. This is the
377  * complement of ModelChecker::switch_to_master and must be called from the
378  * model-checker context
379  *
380  * @param thread The user-thread to switch to
381  */
382 void ModelChecker::switch_from_master(Thread *thread)
383 {
384         scheduler->set_current_thread(thread);
385         Thread::swap(&system_context, thread);
386 }
387
388 /**
389  * Switch from a user-context to the "master thread" context (a.k.a. system
390  * context). This switch is made with the intention of exploring a particular
391  * model-checking action (described by a ModelAction object). Must be called
392  * from a user-thread context.
393  *
394  * @param act The current action that will be explored. May be NULL only if
395  * trace is exiting via an assertion (see ModelExecution::set_assert and
396  * ModelExecution::has_asserted).
397  * @return Return the value returned by the current action
398  */
399 uint64_t ModelChecker::switch_to_master(ModelAction *act)
400 {
401         DBG();
402         Thread *old = thread_current();
403         scheduler->set_current_thread(NULL);
404         ASSERT(!old->get_pending());
405         old->set_pending(act);
406         if (Thread::swap(old, &system_context) < 0) {
407                 perror("swap threads");
408                 exit(EXIT_FAILURE);
409         }
410         return old->get_return_value();
411 }
412
413 /** Wrapper to run the user's main function, with appropriate arguments */
414 void user_main_wrapper(void *)
415 {
416         user_main(model->params.argc, model->params.argv);
417 }
418
419 bool ModelChecker::should_terminate_execution()
420 {
421         /* Infeasible -> don't take any more steps */
422         if (execution->is_infeasible())
423                 return true;
424         else if (execution->isfeasibleprefix() && execution->have_bug_reports()) {
425                 execution->set_assert();
426                 return true;
427         }
428
429         if (execution->too_many_steps())
430                 return true;
431         return false;
432 }
433
434 /** @brief Run ModelChecker for the user program */
435 void ModelChecker::run()
436 {
437         do {
438                 thrd_t user_thread;
439                 Thread *t = new Thread(&user_thread, &user_main_wrapper, NULL, NULL);
440                 execution->add_thread(t);
441
442                 do {
443                         /*
444                          * Stash next pending action(s) for thread(s). There
445                          * should only need to stash one thread's action--the
446                          * thread which just took a step--plus the first step
447                          * for any newly-created thread
448                          */
449                         for (unsigned int i = 0; i < execution->get_num_threads(); i++) {
450                                 thread_id_t tid = int_to_id(i);
451                                 Thread *thr = get_thread(tid);
452                                 if (!thr->is_model_thread() && !thr->is_complete() && !thr->get_pending()) {
453                                         switch_from_master(thr);
454                                         if (thr->is_waiting_on(thr))
455                                                 assert_bug("Deadlock detected (thread %u)", i);
456                                 }
457                         }
458
459                         /* Don't schedule threads which should be disabled */
460                         for (unsigned int i = 0; i < get_num_threads(); i++) {
461                                 Thread *th = get_thread(int_to_id(i));
462                                 ModelAction *act = th->get_pending();
463                                 if (act && is_enabled(th) && !execution->check_action_enabled(act)) {
464                                         scheduler->sleep(th);
465                                 }
466                         }
467
468                         /* Catch assertions from prior take_step or from
469                          * between-ModelAction bugs (e.g., data races) */
470                         if (execution->has_asserted())
471                                 break;
472
473                         if (!t)
474                                 t = get_next_thread();
475                         if (!t || t->is_model_thread())
476                                 break;
477
478                         /* Consume the next action for a Thread */
479                         ModelAction *curr = t->get_pending();
480                         t->set_pending(NULL);
481                         t = execution->take_step(curr);
482                 } while (!should_terminate_execution());
483
484         } while (next_execution());
485
486         execution->fixup_release_sequences();
487
488         model_print("******* Model-checking complete: *******\n");
489         print_stats();
490 }