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