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