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