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