schedule: make print() const
[c11tester.git] / model.cc
1 #include <stdio.h>
2
3 #include "model.h"
4 #include "action.h"
5 #include "nodestack.h"
6 #include "schedule.h"
7 #include "snapshot-interface.h"
8 #include "common.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
11 #include "promise.h"
12
13 #define INITIAL_THREAD_ID       0
14
15 ModelChecker *model;
16
17 /** @brief Constructor */
18 ModelChecker::ModelChecker(struct model_params params) :
19         /* Initialize default scheduler */
20         scheduler(new Scheduler()),
21         /* First thread created will have id INITIAL_THREAD_ID */
22         next_thread_id(INITIAL_THREAD_ID),
23         used_sequence_numbers(0),
24         num_executions(0),
25         params(params),
26         current_action(NULL),
27         diverge(NULL),
28         nextThread(THREAD_ID_T_NONE),
29         action_trace(new action_list_t()),
30         thread_map(new HashTable<int, Thread *, int>()),
31         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
33         promises(new std::vector<Promise *>()),
34         thrd_last_action(new std::vector<ModelAction *>(1)),
35         node_stack(new NodeStack()),
36         next_backtrack(NULL),
37         cyclegraph(new CycleGraph()),
38         failed_promise(false)
39 {
40 }
41
42 /** @brief Destructor */
43 ModelChecker::~ModelChecker()
44 {
45         for (int i = 0; i < get_num_threads(); i++)
46                 delete thread_map->get(i);
47         delete thread_map;
48
49         delete obj_thrd_map;
50         delete obj_map;
51         delete action_trace;
52         delete thrd_last_action;
53         delete node_stack;
54         delete scheduler;
55         delete cyclegraph;
56 }
57
58 /**
59  * Restores user program to initial state and resets all model-checker data
60  * structures.
61  */
62 void ModelChecker::reset_to_initial_state()
63 {
64         DEBUG("+++ Resetting to initial state +++\n");
65         node_stack->reset_execution();
66         current_action = NULL;
67         next_thread_id = INITIAL_THREAD_ID;
68         used_sequence_numbers = 0;
69         nextThread = 0;
70         next_backtrack = NULL;
71         failed_promise = false;
72         snapshotObject->backTrackBeforeStep(0);
73 }
74
75 /** @returns a thread ID for a new Thread */
76 thread_id_t ModelChecker::get_next_id()
77 {
78         return next_thread_id++;
79 }
80
81 /** @returns the number of user threads created during this execution */
82 int ModelChecker::get_num_threads()
83 {
84         return next_thread_id;
85 }
86
87 /** @returns a sequence number for a new ModelAction */
88 modelclock_t ModelChecker::get_next_seq_num()
89 {
90         return ++used_sequence_numbers;
91 }
92
93 /**
94  * Performs the "scheduling" for the model-checker. That is, it checks if the
95  * model-checker has selected a "next thread to run" and returns it, if
96  * available. This function should be called from the Scheduler routine, where
97  * the Scheduler falls back to a default scheduling routine if needed.
98  *
99  * @return The next thread chosen by the model-checker. If the model-checker
100  * makes no selection, retuns NULL.
101  */
102 Thread * ModelChecker::schedule_next_thread()
103 {
104         Thread *t;
105         if (nextThread == THREAD_ID_T_NONE)
106                 return NULL;
107         t = thread_map->get(id_to_int(nextThread));
108
109         ASSERT(t != NULL);
110
111         return t;
112 }
113
114 /**
115  * Choose the next thread in the replay sequence.
116  *
117  * If the replay sequence has reached the 'diverge' point, returns a thread
118  * from the backtracking set. Otherwise, simply returns the next thread in the
119  * sequence that is being replayed.
120  */
121 thread_id_t ModelChecker::get_next_replay_thread()
122 {
123         thread_id_t tid;
124
125         /* Have we completed exploring the preselected path? */
126         if (diverge == NULL)
127                 return THREAD_ID_T_NONE;
128
129         /* Else, we are trying to replay an execution */
130         ModelAction * next = node_stack->get_next()->get_action();
131
132         if (next == diverge) {
133                 Node *nextnode = next->get_node();
134                 /* Reached divergence point */
135                 if (nextnode->increment_promise()) {
136                         /* The next node will try to satisfy a different set of promises. */
137                         tid = next->get_tid();
138                         node_stack->pop_restofstack(2);
139                 } else if (nextnode->increment_read_from()) {
140                         /* The next node will read from a different value. */
141                         tid = next->get_tid();
142                         node_stack->pop_restofstack(2);
143                 } else if (nextnode->increment_future_value()) {
144                         /* The next node will try to read from a different future value. */
145                         tid = next->get_tid();
146                         node_stack->pop_restofstack(2);
147                 } else {
148                         /* Make a different thread execute for next step */
149                         Node *node = nextnode->get_parent();
150                         tid = node->get_next_backtrack();
151                         node_stack->pop_restofstack(1);
152                 }
153                 DEBUG("*** Divergence point ***\n");
154                 diverge = NULL;
155         } else {
156                 tid = next->get_tid();
157         }
158         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
159         return tid;
160 }
161
162 /**
163  * Queries the model-checker for more executions to explore and, if one
164  * exists, resets the model-checker state to execute a new execution.
165  *
166  * @return If there are more executions to explore, return true. Otherwise,
167  * return false.
168  */
169 bool ModelChecker::next_execution()
170 {
171         DBG();
172
173         num_executions++;
174
175         if (isfinalfeasible() || DBG_ENABLED())
176                 print_summary();
177
178         if ((diverge = model->get_next_backtrack()) == NULL)
179                 return false;
180
181         if (DBG_ENABLED()) {
182                 printf("Next execution will diverge at:\n");
183                 diverge->print();
184         }
185
186         model->reset_to_initial_state();
187         return true;
188 }
189
190 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
191 {
192         action_type type = act->get_type();
193
194         switch (type) {
195                 case ATOMIC_READ:
196                 case ATOMIC_WRITE:
197                 case ATOMIC_RMW:
198                         break;
199                 default:
200                         return NULL;
201         }
202         /* linear search: from most recent to oldest */
203         action_list_t *list = obj_map->ensureptr(act->get_location());
204         action_list_t::reverse_iterator rit;
205         for (rit = list->rbegin(); rit != list->rend(); rit++) {
206                 ModelAction *prev = *rit;
207                 if (act->is_synchronizing(prev))
208                         return prev;
209         }
210         return NULL;
211 }
212
213 void ModelChecker::set_backtracking(ModelAction *act)
214 {
215         ModelAction *prev;
216         Node *node;
217         Thread *t = get_thread(act->get_tid());
218
219         prev = get_last_conflict(act);
220         if (prev == NULL)
221                 return;
222
223         node = prev->get_node()->get_parent();
224
225         while (!node->is_enabled(t))
226                 t = t->get_parent();
227
228         /* Check if this has been explored already */
229         if (node->has_been_explored(t->get_id()))
230                 return;
231
232         /* Cache the latest backtracking point */
233         if (!next_backtrack || *prev > *next_backtrack)
234                 next_backtrack = prev;
235
236         /* If this is a new backtracking point, mark the tree */
237         if (!node->set_backtrack(t->get_id()))
238                 return;
239         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
240                         prev->get_tid(), t->get_id());
241         if (DBG_ENABLED()) {
242                 prev->print();
243                 act->print();
244         }
245 }
246
247 /**
248  * Returns last backtracking point. The model checker will explore a different
249  * path for this point in the next execution.
250  * @return The ModelAction at which the next execution should diverge.
251  */
252 ModelAction * ModelChecker::get_next_backtrack()
253 {
254         ModelAction *next = next_backtrack;
255         next_backtrack = NULL;
256         return next;
257 }
258
259 void ModelChecker::check_current_action(void)
260 {
261         ModelAction *curr = this->current_action;
262         bool already_added = false;
263         this->current_action = NULL;
264         if (!curr) {
265                 DEBUG("trying to push NULL action...\n");
266                 return;
267         }
268
269         if (curr->is_rmwc() || curr->is_rmw()) {
270                 ModelAction *tmp = process_rmw(curr);
271                 already_added = true;
272                 delete curr;
273                 curr = tmp;
274         } else {
275                 ModelAction * tmp = node_stack->explore_action(curr);
276                 if (tmp) {
277                         /* Discard duplicate ModelAction; use action from NodeStack */
278                         /* First restore type and order in case of RMW operation */
279                         if (curr->is_rmwr())
280                                 tmp->copy_typeandorder(curr);
281
282                         /* If we have diverged, we need to reset the clock vector. */
283                         if (diverge == NULL)
284                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
285
286                         delete curr;
287                         curr = tmp;
288                 } else {
289                         /*
290                          * Perform one-time actions when pushing new ModelAction onto
291                          * NodeStack
292                          */
293                         curr->create_cv(get_parent_action(curr->get_tid()));
294                         /* Build may_read_from set */
295                         if (curr->is_read())
296                                 build_reads_from_past(curr);
297                         if (curr->is_write())
298                                 compute_promises(curr);
299                 }
300         }
301
302         /* Assign 'creation' parent */
303         if (curr->get_type() == THREAD_CREATE) {
304                 Thread *th = (Thread *)curr->get_location();
305                 th->set_creation(curr);
306         }
307
308         /* Deal with new thread */
309         if (curr->get_type() == THREAD_START)
310                 check_promises(NULL, curr->get_cv());
311
312         /* Assign reads_from values */
313         Thread *th = get_thread(curr->get_tid());
314         uint64_t value = VALUE_NONE;
315         if (curr->is_read()) {
316                 const ModelAction *reads_from = curr->get_node()->get_read_from();
317                 if (reads_from != NULL) {
318                         value = reads_from->get_value();
319                         /* Assign reads_from, perform release/acquire synchronization */
320                         curr->read_from(reads_from);
321                         r_modification_order(curr,reads_from);
322                 } else {
323                         /* Read from future value */
324                         value = curr->get_node()->get_future_value();
325                         curr->read_from(NULL);
326                         Promise * valuepromise = new Promise(curr, value);
327                         promises->push_back(valuepromise);
328                 }
329         } else if (curr->is_write()) {
330                 w_modification_order(curr);
331                 resolve_promises(curr);
332         }
333
334         th->set_return_value(value);
335
336         /* Add action to list.  */
337         if (!already_added)
338                 add_action_to_lists(curr);
339
340         /** @todo Is there a better interface for setting the next thread rather
341                  than this field/convoluted approach?  Perhaps like just returning
342                  it or something? */
343
344         /* Do not split atomic actions. */
345         if (curr->is_rmwr())
346                 nextThread = thread_current()->get_id();
347         else
348                 nextThread = get_next_replay_thread();
349
350         Node *currnode = curr->get_node();
351         Node *parnode = currnode->get_parent();
352
353         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
354                   !currnode->future_value_empty() || !currnode->promise_empty())
355                 if (!next_backtrack || *curr > *next_backtrack)
356                         next_backtrack = curr;
357
358         set_backtracking(curr);
359 }
360
361 /** @returns whether the current partial trace is feasible. */
362 bool ModelChecker::isfeasible() {
363         return !cyclegraph->checkForCycles() && !failed_promise;
364 }
365
366 /** Returns whether the current completed trace is feasible. */
367 bool ModelChecker::isfinalfeasible() {
368         return isfeasible() && promises->size() == 0;
369 }
370
371 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
372 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
373         int tid = id_to_int(act->get_tid());
374         ModelAction *lastread = get_last_action(tid);
375         lastread->process_rmw(act);
376         if (act->is_rmw())
377                 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
378         return lastread;
379 }
380
381 /**
382  * Updates the cyclegraph with the constraints imposed from the current read.
383  * @param curr The current action. Must be a read.
384  * @param rf The action that curr reads from. Must be a write.
385  */
386 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
387         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
388         unsigned int i;
389         ASSERT(curr->is_read());
390
391         /* Iterate over all threads */
392         for (i = 0; i < thrd_lists->size(); i++) {
393                 /* Iterate over actions in thread, starting from most recent */
394                 action_list_t *list = &(*thrd_lists)[i];
395                 action_list_t::reverse_iterator rit;
396                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
397                         ModelAction *act = *rit;
398
399                         /* Include at most one act per-thread that "happens before" curr */
400                         if (act->happens_before(curr)) {
401                                 if (act->is_read()) {
402                                         const ModelAction * prevreadfrom = act->get_reads_from();
403                                         if (prevreadfrom != NULL && rf != prevreadfrom)
404                                                 cyclegraph->addEdge(rf, prevreadfrom);
405                                 } else if (rf != act) {
406                                         cyclegraph->addEdge(rf, act);
407                                 }
408                                 break;
409                         }
410                 }
411         }
412 }
413
414 /** Updates the cyclegraph with the constraints imposed from the
415  *  current read. */
416 void ModelChecker::post_r_modification_order(ModelAction * curr, const ModelAction *rf) {
417         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
418         unsigned int i;
419         ASSERT(curr->is_read());
420
421         /* Iterate over all threads */
422         for (i = 0; i < thrd_lists->size(); i++) {
423                 /* Iterate over actions in thread, starting from most recent */
424                 action_list_t *list = &(*thrd_lists)[i];
425                 action_list_t::reverse_iterator rit;
426                 ModelAction *lastact = NULL;
427
428                 /* Find last action that happens after curr */
429                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
430                         ModelAction *act = *rit;
431                         if (curr->happens_before(act)) {
432                                 lastact = act;
433                         } else
434                                 break;
435                 }
436
437                         /* Include at most one act per-thread that "happens before" curr */
438                 if (lastact != NULL) {
439                         if (lastact->is_read()) {
440                                 const ModelAction * postreadfrom = lastact->get_reads_from();
441                                 if (postreadfrom != NULL&&rf != postreadfrom)
442                                         cyclegraph->addEdge(postreadfrom, rf);
443                         } else if (rf != lastact) {
444                                 cyclegraph->addEdge(lastact, rf);
445                         }
446                         break;
447                 }
448         }
449 }
450
451 /**
452  * Updates the cyclegraph with the constraints imposed from the current write.
453  * @param curr The current action. Must be a write.
454  */
455 void ModelChecker::w_modification_order(ModelAction * curr) {
456         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
457         unsigned int i;
458         ASSERT(curr->is_write());
459
460         if (curr->is_seqcst()) {
461                 /* We have to at least see the last sequentially consistent write,
462                          so we are initialized. */
463                 ModelAction * last_seq_cst = get_last_seq_cst(curr->get_location());
464                 if (last_seq_cst != NULL)
465                         cyclegraph->addEdge(curr, last_seq_cst);
466         }
467
468         /* Iterate over all threads */
469         for (i = 0; i < thrd_lists->size(); i++) {
470                 /* Iterate over actions in thread, starting from most recent */
471                 action_list_t *list = &(*thrd_lists)[i];
472                 action_list_t::reverse_iterator rit;
473                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
474                         ModelAction *act = *rit;
475
476                         /* Include at most one act per-thread that "happens before" curr */
477                         if (act->happens_before(curr)) {
478                                 if (act->is_read())
479                                         cyclegraph->addEdge(curr, act->get_reads_from());
480                                 else
481                                         cyclegraph->addEdge(curr, act);
482                                 break;
483                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
484                                                      !act->same_thread(curr)) {
485                                 /* We have an action that:
486                                    (1) did not happen before us
487                                    (2) is a read and we are a write
488                                    (3) cannot synchronize with us
489                                    (4) is in a different thread
490                                    =>
491                                    that read could potentially read from our write.
492                                  */
493                                 if (act->get_node()->add_future_value(curr->get_value()) &&
494                                                 (!next_backtrack || *act > *next_backtrack))
495                                         next_backtrack = act;
496                         }
497                 }
498         }
499 }
500
501 /**
502  * Performs various bookkeeping operations for the current ModelAction. For
503  * instance, adds action to the per-object, per-thread action vector and to the
504  * action trace list of all thread actions.
505  *
506  * @param act is the ModelAction to add.
507  */
508 void ModelChecker::add_action_to_lists(ModelAction *act)
509 {
510         int tid = id_to_int(act->get_tid());
511         action_trace->push_back(act);
512
513         obj_map->ensureptr(act->get_location())->push_back(act);
514
515         std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
516         if (tid >= (int)vec->size())
517                 vec->resize(next_thread_id);
518         (*vec)[tid].push_back(act);
519
520         if ((int)thrd_last_action->size() <= tid)
521                 thrd_last_action->resize(get_num_threads());
522         (*thrd_last_action)[tid] = act;
523 }
524
525 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
526 {
527         int nthreads = get_num_threads();
528         if ((int)thrd_last_action->size() < nthreads)
529                 thrd_last_action->resize(nthreads);
530         return (*thrd_last_action)[id_to_int(tid)];
531 }
532
533 /**
534  * Gets the last memory_order_seq_cst action (in the total global sequence)
535  * performed on a particular object (i.e., memory location).
536  * @param location The object location to check
537  * @return The last seq_cst action performed
538  */
539 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
540 {
541         action_list_t *list = obj_map->ensureptr(location);
542         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
543         action_list_t::reverse_iterator rit;
544         for (rit = list->rbegin(); rit != list->rend(); rit++)
545                 if ((*rit)->is_write() && (*rit)->is_seqcst())
546                         return *rit;
547         return NULL;
548 }
549
550 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
551 {
552         ModelAction *parent = get_last_action(tid);
553         if (!parent)
554                 parent = get_thread(tid)->get_creation();
555         return parent;
556 }
557
558 /**
559  * Returns the clock vector for a given thread.
560  * @param tid The thread whose clock vector we want
561  * @return Desired clock vector
562  */
563 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
564         return get_parent_action(tid)->get_cv();
565 }
566
567
568 /** Resolve the given promises. */
569
570 void ModelChecker::resolve_promises(ModelAction *write) {
571         for (unsigned int i = 0, promise_index = 0;promise_index<promises->size(); i++) {
572                 Promise * promise = (*promises)[promise_index];
573                 if (write->get_node()->get_promise(i)) {
574                         ModelAction * read = promise->get_action();
575                         read->read_from(write);
576                         r_modification_order(read, write);
577                         post_r_modification_order(read, write);
578                         promises->erase(promises->begin()+promise_index);
579                 } else
580                         promise_index++;
581         }
582 }
583
584 /** Compute the set of promises that could potentially be satisfied by
585  *  this action. */
586
587 void ModelChecker::compute_promises(ModelAction *curr) {
588         for (unsigned int i = 0;i<promises->size();i++) {
589                 Promise * promise = (*promises)[i];
590                 const ModelAction * act = promise->get_action();
591                 if (!act->happens_before(curr)&&
592                                 act->is_read()&&
593                                 !act->is_synchronizing(curr)&&
594                                 !act->same_thread(curr)&&
595                                 promise->get_value() == curr->get_value()) {
596                         curr->get_node()->set_promise(i);
597                 }
598         }
599 }
600
601 /** Checks promises in response to change in ClockVector Threads. */
602
603 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
604         for (unsigned int i = 0;i<promises->size();i++) {
605                 Promise * promise = (*promises)[i];
606                 const ModelAction * act = promise->get_action();
607                 if ((old_cv == NULL||!old_cv->synchronized_since(act))&&
608                                 merge_cv->synchronized_since(act)) {
609                         //This thread is no longer able to send values back to satisfy the promise
610                         int num_synchronized_threads = promise->increment_threads();
611                         if (num_synchronized_threads == model->get_num_threads()) {
612                                 //Promise has failed
613                                 failed_promise = true;
614                                 return;
615                         }
616                 }
617         }
618 }
619
620 /**
621  * Build up an initial set of all past writes that this 'read' action may read
622  * from. This set is determined by the clock vector's "happens before"
623  * relationship.
624  * @param curr is the current ModelAction that we are exploring; it must be a
625  * 'read' operation.
626  */
627 void ModelChecker::build_reads_from_past(ModelAction *curr)
628 {
629         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
630         unsigned int i;
631         ASSERT(curr->is_read());
632
633         ModelAction *last_seq_cst = NULL;
634
635         /* Track whether this object has been initialized */
636         bool initialized = false;
637
638         if (curr->is_seqcst()) {
639                 last_seq_cst = get_last_seq_cst(curr->get_location());
640                 /* We have to at least see the last sequentially consistent write,
641                          so we are initialized. */
642                 if (last_seq_cst != NULL)
643                         initialized = true;
644         }
645
646         /* Iterate over all threads */
647         for (i = 0; i < thrd_lists->size(); i++) {
648                 /* Iterate over actions in thread, starting from most recent */
649                 action_list_t *list = &(*thrd_lists)[i];
650                 action_list_t::reverse_iterator rit;
651                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
652                         ModelAction *act = *rit;
653
654                         /* Only consider 'write' actions */
655                         if (!act->is_write())
656                                 continue;
657
658                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
659                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
660                                 DEBUG("Adding action to may_read_from:\n");
661                                 if (DBG_ENABLED()) {
662                                         act->print();
663                                         curr->print();
664                                 }
665                                 curr->get_node()->add_read_from(act);
666                         }
667
668                         /* Include at most one act per-thread that "happens before" curr */
669                         if (act->happens_before(curr)) {
670                                 initialized = true;
671                                 break;
672                         }
673                 }
674         }
675
676         if (!initialized) {
677                 /** @todo Need a more informative way of reporting errors. */
678                 printf("ERROR: may read from uninitialized atomic\n");
679         }
680
681         if (DBG_ENABLED() || !initialized) {
682                 printf("Reached read action:\n");
683                 curr->print();
684                 printf("Printing may_read_from\n");
685                 curr->get_node()->print_may_read_from();
686                 printf("End printing may_read_from\n");
687         }
688
689         ASSERT(initialized);
690 }
691
692 static void print_list(action_list_t *list)
693 {
694         action_list_t::iterator it;
695
696         printf("---------------------------------------------------------------------\n");
697         printf("Trace:\n");
698
699         for (it = list->begin(); it != list->end(); it++) {
700                 (*it)->print();
701         }
702         printf("---------------------------------------------------------------------\n");
703 }
704
705 void ModelChecker::print_summary()
706 {
707         printf("\n");
708         printf("Number of executions: %d\n", num_executions);
709         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
710
711         scheduler->print();
712
713         if (!isfinalfeasible())
714                 printf("INFEASIBLE EXECUTION!\n");
715         print_list(action_trace);
716         printf("\n");
717 }
718
719 /**
720  * Add a Thread to the system for the first time. Should only be called once
721  * per thread.
722  * @param t The Thread to add
723  */
724 void ModelChecker::add_thread(Thread *t)
725 {
726         thread_map->put(id_to_int(t->get_id()), t);
727         scheduler->add_thread(t);
728 }
729
730 void ModelChecker::remove_thread(Thread *t)
731 {
732         scheduler->remove_thread(t);
733 }
734
735 /**
736  * Switch from a user-context to the "master thread" context (a.k.a. system
737  * context). This switch is made with the intention of exploring a particular
738  * model-checking action (described by a ModelAction object). Must be called
739  * from a user-thread context.
740  * @param act The current action that will be explored. May be NULL, although
741  * there is little reason to switch to the model-checker without an action to
742  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
743  * yield control without performing any progress; see thrd_join()).
744  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
745  */
746 int ModelChecker::switch_to_master(ModelAction *act)
747 {
748         DBG();
749         Thread * old = thread_current();
750         set_current_action(act);
751         old->set_state(THREAD_READY);
752         return Thread::swap(old, &system_context);
753 }
754
755 /**
756  * Takes the next step in the execution, if possible.
757  * @return Returns true (success) if a step was taken and false otherwise.
758  */
759 bool ModelChecker::take_step() {
760         Thread *curr, *next;
761
762         curr = thread_current();
763         if (curr) {
764                 if (curr->get_state() == THREAD_READY) {
765                         check_current_action();
766                         scheduler->add_thread(curr);
767                 } else if (curr->get_state() == THREAD_RUNNING) {
768                         /* Stopped while running; i.e., completed */
769                         curr->complete();
770                 } else {
771                         ASSERT(false);
772                 }
773         }
774         next = scheduler->next_thread();
775
776         /* Infeasible -> don't take any more steps */
777         if (!isfeasible())
778                 return false;
779
780         if (next)
781                 next->set_state(THREAD_RUNNING);
782         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
783
784         /* next == NULL -> don't take any more steps */
785         if (!next)
786                 return false;
787         /* Return false only if swap fails with an error */
788         return (Thread::swap(&system_context, next) == 0);
789 }
790
791 /** Runs the current execution until threre are no more steps to take. */
792 void ModelChecker::finish_execution() {
793         DBG();
794
795         while (take_step());
796 }