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