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