70d89356d1bce74435dbf8d56373854da6b51b24
[jpf-core.git] / src / main / gov / nasa / jpf / listener / DPORStateReducer.java
1 /*
2  * Copyright (C) 2014, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The Java Pathfinder core (jpf-core) platform is licensed under the
7  * Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0.
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package gov.nasa.jpf.listener;
19
20 import gov.nasa.jpf.Config;
21 import gov.nasa.jpf.JPF;
22 import gov.nasa.jpf.ListenerAdapter;
23 import gov.nasa.jpf.jvm.bytecode.INVOKEINTERFACE;
24 import gov.nasa.jpf.jvm.bytecode.JVMFieldInstruction;
25 import gov.nasa.jpf.search.Search;
26 import gov.nasa.jpf.vm.*;
27 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
28 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
29 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
30 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
31
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.PrintWriter;
35 import java.util.*;
36 import java.util.logging.Logger;
37
38 /**
39  * This a DPOR implementation for event-driven applications with loops that create cycles of state matching
40  * In this new DPOR algorithm/implementation, each run is terminated iff:
41  * - we find a state that matches a state in a previous run, or
42  * - we have a matched state in the current run that consists of cycles that contain all choices/events.
43  */
44 public class DPORStateReducer extends ListenerAdapter {
45
46   // Information printout fields for verbose mode
47   private boolean verboseMode;
48   private boolean stateReductionMode;
49   private final PrintWriter out;
50   private PrintWriter fileWriter;
51   private String detail;
52   private int depth;
53   private int id;
54   private Transition transition;
55
56   // DPOR-related fields
57   // Basic information
58   private Integer[] choices;
59   private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
60   private int choiceCounter;
61   private int maxEventChoice;
62   // Data structure to track the events seen by each state to track cycles (containing all events) for termination
63   private HashSet<Integer> currVisitedStates;   // States being visited in the current execution
64   private HashSet<Integer> justVisitedStates;   // States just visited in the previous choice/event
65   private HashSet<Integer> prevVisitedStates;   // States visited in the previous execution
66   private HashSet<ClassInfo> nonRelevantClasses;// Class info objects of non-relevant classes
67   private HashSet<FieldInfo> nonRelevantFields; // Field info objects of non-relevant fields
68   private HashSet<FieldInfo> relevantFields;    // Field info objects of relevant fields
69   private HashMap<Integer, HashSet<Integer>> stateToEventMap;
70   // Data structure to analyze field Read/Write accesses and conflicts
71   private HashMap<Integer, LinkedList<BacktrackExecution>> backtrackMap;  // Track created backtracking points
72   private PriorityQueue<Integer> backtrackStateQ;                 // Heap that returns the latest state
73   private Execution currentExecution;                             // Holds the information about the current execution
74   private HashMap<Integer, HashSet<Integer>> doneBacktrackMap;    // Record state ID and trace already constructed
75   private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
76   private RGraph rGraph;                                          // R-Graph for past executions
77
78   // Boolean states
79   private boolean isBooleanCGFlipped;
80   private boolean isEndOfExecution;
81
82   // Statistics
83   private int numOfTransitions;
84
85   public DPORStateReducer(Config config, JPF jpf) {
86     verboseMode = config.getBoolean("printout_state_transition", false);
87     stateReductionMode = config.getBoolean("activate_state_reduction", true);
88     if (verboseMode) {
89       out = new PrintWriter(System.out, true);
90     } else {
91       out = null;
92     }
93     String outputFile = config.getString("file_output");
94     if (!outputFile.isEmpty()) {
95       try {
96         fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
97       } catch (IOException e) {
98       }
99     }
100     isBooleanCGFlipped = false;
101                 numOfTransitions = 0;
102                 nonRelevantClasses = new HashSet<>();
103                 nonRelevantFields = new HashSet<>();
104                 relevantFields = new HashSet<>();
105     restorableStateMap = new HashMap<>();
106     initializeStatesVariables();
107   }
108
109   @Override
110   public void stateRestored(Search search) {
111     if (verboseMode) {
112       id = search.getStateId();
113       depth = search.getDepth();
114       transition = search.getTransition();
115       detail = null;
116       out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
117               " and depth: " + depth + "\n");
118     }
119   }
120
121   @Override
122   public void searchStarted(Search search) {
123     if (verboseMode) {
124       out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
125     }
126   }
127
128   @Override
129   public void stateAdvanced(Search search) {
130     if (verboseMode) {
131       id = search.getStateId();
132       depth = search.getDepth();
133       transition = search.getTransition();
134       if (search.isNewState()) {
135         detail = "new";
136       } else {
137         detail = "visited";
138       }
139
140       if (search.isEndState()) {
141         out.println("\n==> DEBUG: This is the last state!\n");
142         detail += " end";
143       }
144       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
145               " which is " + detail + " Transition: " + transition + "\n");
146     }
147     if (stateReductionMode) {
148       updateStateInfo(search);
149     }
150   }
151
152   @Override
153   public void stateBacktracked(Search search) {
154     if (verboseMode) {
155       id = search.getStateId();
156       depth = search.getDepth();
157       transition = search.getTransition();
158       detail = null;
159
160       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
161               " and depth: " + depth + "\n");
162     }
163     if (stateReductionMode) {
164       updateStateInfo(search);
165     }
166   }
167
168   static Logger log = JPF.getLogger("report");
169
170   @Override
171   public void searchFinished(Search search) {
172     if (verboseMode) {
173       out.println("\n==> DEBUG: ----------------------------------- search finished");
174       out.println("\n==> DEBUG: State reduction mode  : " + stateReductionMode);
175       out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
176       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
177
178       fileWriter.println("==> DEBUG: State reduction mode  : " + stateReductionMode);
179       fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
180       fileWriter.println();
181       fileWriter.close();
182     }
183   }
184
185   @Override
186   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
187     if (stateReductionMode) {
188       // Initialize with necessary information from the CG
189       if (nextCG instanceof IntChoiceFromSet) {
190         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
191         // Tell JPF that we are performing DPOR
192         icsCG.setDpor();
193         if (!isEndOfExecution) {
194           // Check if CG has been initialized, otherwise initialize it
195           Integer[] cgChoices = icsCG.getAllChoices();
196           // Record the events (from choices)
197           if (choices == null) {
198             choices = cgChoices;
199             // Make a copy of choices as reference
200             refChoices = copyChoices(choices);
201             // Record the max event choice (the last element of the choice array)
202             maxEventChoice = choices[choices.length - 1];
203           }
204           icsCG.setNewValues(choices);
205           icsCG.reset();
206           // Use a modulo since choiceCounter is going to keep increasing
207           int choiceIndex = choiceCounter % choices.length;
208           icsCG.advance(choices[choiceIndex]);
209         } else {
210           // Set done all CGs while transitioning to a new execution
211           icsCG.setDone();
212         }
213       }
214     }
215   }
216
217   @Override
218   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
219     if (stateReductionMode) {
220       // Check the boolean CG and if it is flipped, we are resetting the analysis
221       if (currentCG instanceof BooleanChoiceGenerator) {
222         if (!isBooleanCGFlipped) {
223           isBooleanCGFlipped = true;
224         } else {
225           // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
226           initializeStatesVariables();
227         }
228       }
229       // Check every choice generated and ensure fair scheduling!
230       if (currentCG instanceof IntChoiceFromSet) {
231         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
232         // If this is a new CG then we need to update data structures
233         resetStatesForNewExecution(icsCG, vm);
234         // If we don't see a fair scheduling of events/choices then we have to enforce it
235         ensureFairSchedulingAndSetupTransition(icsCG, vm);
236         // Update backtrack set of an executed event (transition): one transition before this one
237         updateBacktrackSet(currentExecution, choiceCounter - 1);
238         // Explore the next backtrack point:
239         // 1) if we have seen this state or this state contains cycles that involve all events, and
240         // 2) after the current CG is advanced at least once
241         if (terminateCurrentExecution() && choiceCounter > 0) {
242           exploreNextBacktrackPoints(vm, icsCG);
243         } else {
244           numOfTransitions++;
245         }
246         // Map state to event
247         mapStateToEvent(icsCG.getNextChoice());
248         justVisitedStates.clear();
249         choiceCounter++;
250       }
251     } else {
252       numOfTransitions++;
253     }
254   }
255
256   @Override
257   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
258     if (stateReductionMode) {
259       if (!isEndOfExecution) {
260         // Has to be initialized and a integer CG
261         ChoiceGenerator<?> cg = vm.getChoiceGenerator();
262         if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
263           int currentChoice = choiceCounter - 1;  // Accumulative choice w.r.t the current trace
264           if (currentChoice < 0) { // If choice is -1 then skip
265             return;
266           }
267           currentChoice = checkAndAdjustChoice(currentChoice, vm);
268           // Record accesses from executed instructions
269           if (executedInsn instanceof JVMFieldInstruction) {
270             // We don't care about libraries
271             if (!isFieldExcluded(executedInsn)) {
272               analyzeReadWriteAccesses(executedInsn, currentChoice);
273             }
274           } else if (executedInsn instanceof INVOKEINTERFACE) {
275             // Handle the read/write accesses that occur through iterators
276             analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
277           }
278         }
279       }
280     }
281   }
282
283
284   // == HELPERS
285
286   // -- INNER CLASSES
287
288   // This class compactly stores backtrack execution:
289   // 1) backtrack choice list, and
290   // 2) first backtrack point (linking with predecessor execution)
291   private class BacktrackExecution {
292     private Integer[] choiceList;
293     private TransitionEvent firstTransition;
294
295     public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
296       choiceList = choList;
297       firstTransition = fTransition;
298     }
299
300     public Integer[] getChoiceList() {
301       return choiceList;
302     }
303
304     public TransitionEvent getFirstTransition() {
305       return firstTransition;
306     }
307   }
308
309   // This class stores a representation of an execution
310   // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
311   // TODO: We basically need to keep track of:
312   // TODO:    (1) last read/write access to each memory location
313   // TODO:    (2) last state with two or more incoming events/transitions
314   private class Execution {
315     private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap;   // Map between CG to choice numbers for O(1) access
316     private ArrayList<TransitionEvent> executionTrace;          // The BacktrackPoint objects of this execution
317     private boolean isNew;                                      // Track if this is the first time it is accessed
318     private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;  // Record fields that are accessed
319
320     public Execution() {
321       cgToChoiceMap = new HashMap<>();
322       executionTrace = new ArrayList<>();
323       isNew = true;
324       readWriteFieldsMap = new HashMap<>();
325     }
326
327     public void addTransition(TransitionEvent newBacktrackPoint) {
328       executionTrace.add(newBacktrackPoint);
329     }
330
331     public void clearCGToChoiceMap() {
332       cgToChoiceMap = null;
333     }
334
335     public int getChoiceFromCG(IntChoiceFromSet icsCG) {
336       return cgToChoiceMap.get(icsCG);
337     }
338
339     public ArrayList<TransitionEvent> getExecutionTrace() {
340       return executionTrace;
341     }
342
343     public TransitionEvent getFirstTransition() {
344       return executionTrace.get(0);
345     }
346
347     public TransitionEvent getLastTransition() {
348       return executionTrace.get(executionTrace.size() - 1);
349     }
350
351     public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
352       return readWriteFieldsMap;
353     }
354
355     public boolean isNew() {
356       if (isNew) {
357         // Right after this is accessed, it is no longer new
358         isNew = false;
359         return true;
360       }
361       return false;
362     }
363
364     public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
365       cgToChoiceMap.put(icsCG, choice);
366     }
367   }
368
369   // This class compactly stores a predecessor
370   // 1) a predecessor execution
371   // 2) the predecessor choice in that predecessor execution
372   private class Predecessor {
373     private int choice;           // Predecessor choice
374     private Execution execution;  // Predecessor execution
375
376     public Predecessor(int predChoice, Execution predExec) {
377       choice = predChoice;
378       execution = predExec;
379     }
380
381     public int getChoice() {
382       return choice;
383     }
384
385     public Execution getExecution() {
386       return execution;
387     }
388   }
389
390   // This class represents a R-Graph (in the paper it is a state transition graph R)
391   // This implementation stores reachable transitions from and connects with past executions
392   private class RGraph {
393     private int hiStateId;                                     // Maximum state Id
394     private HashMap<Integer, HashSet<TransitionEvent>> graph;  // Reachable transitions from past executions
395
396     public RGraph() {
397       hiStateId = 0;
398       graph = new HashMap<>();
399     }
400
401     public void addReachableTransition(int stateId, TransitionEvent transition) {
402       HashSet<TransitionEvent> transitionSet;
403       if (graph.containsKey(stateId)) {
404         transitionSet = graph.get(stateId);
405       } else {
406         transitionSet = new HashSet<>();
407         graph.put(stateId, transitionSet);
408       }
409       // Insert into the set if it does not contain it yet
410       if (!transitionSet.contains(transition)) {
411         transitionSet.add(transition);
412       }
413       // Update highest state ID
414       if (hiStateId < stateId) {
415         hiStateId = stateId;
416       }
417     }
418
419     public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
420       if (!graph.containsKey(stateId)) {
421         // This is a loop from a transition to itself, so just return the current transition
422         HashSet<TransitionEvent> transitionSet = new HashSet<>();
423         transitionSet.add(currentExecution.getLastTransition());
424         return transitionSet;
425       }
426       return graph.get(stateId);
427     }
428
429     public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
430       HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
431       // All transitions from states higher than the given state ID (until the highest state ID) are reachable
432       for(int stId = stateId; stId <= hiStateId; stId++) {
433         // We might encounter state IDs from the first round of Boolean CG
434         // The second round of Boolean CG should consider these new states
435         if (graph.containsKey(stId)) {
436           reachableTransitions.addAll(graph.get(stId));
437         }
438       }
439       return reachableTransitions;
440     }
441   }
442
443   // This class compactly stores Read and Write field sets
444   // We store the field name and its object ID
445   // Sharing the same field means the same field name and object ID
446   private class ReadWriteSet {
447     private HashMap<String, Integer> readMap;
448     private HashMap<String, Integer> writeMap;
449
450     public ReadWriteSet() {
451       readMap = new HashMap<>();
452       writeMap = new HashMap<>();
453     }
454
455     public void addReadField(String field, int objectId) {
456       readMap.put(field, objectId);
457     }
458
459     public void addWriteField(String field, int objectId) {
460       writeMap.put(field, objectId);
461     }
462
463     public void removeReadField(String field) {
464       readMap.remove(field);
465     }
466
467     public void removeWriteField(String field) {
468       writeMap.remove(field);
469     }
470
471     public boolean isEmpty() {
472       return readMap.isEmpty() && writeMap.isEmpty();
473     }
474
475     public ReadWriteSet getCopy() {
476       ReadWriteSet copyRWSet = new ReadWriteSet();
477       // Copy the maps in the set into the new object copy
478       copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
479       copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
480       return copyRWSet;
481     }
482
483     public Set<String> getReadSet() {
484       return readMap.keySet();
485     }
486
487     public Set<String> getWriteSet() {
488       return writeMap.keySet();
489     }
490
491     public boolean readFieldExists(String field) {
492       return readMap.containsKey(field);
493     }
494
495     public boolean writeFieldExists(String field) {
496       return writeMap.containsKey(field);
497     }
498
499     public int readFieldObjectId(String field) {
500       return readMap.get(field);
501     }
502
503     public int writeFieldObjectId(String field) {
504       return writeMap.get(field);
505     }
506
507     private HashMap<String, Integer> getReadMap() {
508       return readMap;
509     }
510
511     private HashMap<String, Integer> getWriteMap() {
512       return writeMap;
513     }
514
515     private void setReadMap(HashMap<String, Integer> rMap) {
516       readMap = rMap;
517     }
518
519     private void setWriteMap(HashMap<String, Integer> wMap) {
520       writeMap = wMap;
521     }
522   }
523
524   // This class compactly stores transitions:
525   // 1) CG,
526   // 2) state ID,
527   // 3) choice,
528   // 4) predecessors (for backward DFS).
529   private class TransitionEvent {
530     private int choice;                        // Choice chosen at this transition
531     private int choiceCounter;                 // Choice counter at this transition
532     private Execution execution;               // The execution where this transition belongs
533     private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
534     private HashMap<Execution, HashSet<Integer>> recordedPredecessors;
535                                                // Memorize event and choice number to not record them twice
536     private int stateId;                       // State at this transition
537     private IntChoiceFromSet transitionCG;     // CG at this transition
538
539     public TransitionEvent() {
540       choice = 0;
541       choiceCounter = 0;
542       execution = null;
543       predecessors = new HashSet<>();
544       recordedPredecessors = new HashMap<>();
545       stateId = 0;
546       transitionCG = null;
547     }
548
549     public int getChoice() {
550       return choice;
551     }
552
553     public int getChoiceCounter() {
554       return choiceCounter;
555     }
556
557     public Execution getExecution() {
558       return execution;
559     }
560
561     public HashSet<Predecessor> getPredecessors() {
562       return predecessors;
563     }
564
565     public int getStateId() {
566       return stateId;
567     }
568
569     public IntChoiceFromSet getTransitionCG() { return transitionCG; }
570
571     private boolean isRecordedPredecessor(Execution execution, int choice) {
572       // See if we have recorded this predecessor earlier
573       HashSet<Integer> recordedChoices;
574       if (recordedPredecessors.containsKey(execution)) {
575         recordedChoices = recordedPredecessors.get(execution);
576         if (recordedChoices.contains(choice)) {
577           return true;
578         }
579       } else {
580         recordedChoices = new HashSet<>();
581         recordedPredecessors.put(execution, recordedChoices);
582       }
583       // Record the choice if we haven't seen it
584       recordedChoices.add(choice);
585
586       return false;
587     }
588
589     public void recordPredecessor(Execution execution, int choice) {
590       if (!isRecordedPredecessor(execution, choice)) {
591         predecessors.add(new Predecessor(choice, execution));
592       }
593     }
594
595     public void setChoice(int cho) {
596       choice = cho;
597     }
598
599     public void setChoiceCounter(int choCounter) {
600       choiceCounter = choCounter;
601     }
602
603     public void setExecution(Execution exec) {
604       execution = exec;
605     }
606
607     public void setPredecessors(HashSet<Predecessor> preds) {
608       predecessors = new HashSet<>(preds);
609     }
610
611     public void setStateId(int stId) {
612       stateId = stId;
613     }
614
615     public void setTransitionCG(IntChoiceFromSet cg) {
616       transitionCG = cg;
617     }
618   }
619
620   // -- CONSTANTS
621   private final static String DO_CALL_METHOD = "doCall";
622   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
623   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
624   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
625           // Groovy library created fields
626           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
627           // Infrastructure
628           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
629           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
630   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
631           // Java and Groovy libraries
632           { "java", "org", "sun", "com", "gov", "groovy"};
633   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
634   private final static String GET_PROPERTY_METHOD =
635           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
636   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
637   private final static String JAVA_INTEGER = "int";
638   private final static String JAVA_STRING_LIB = "java.lang.String";
639
640   // -- FUNCTIONS
641   private Integer[] copyChoices(Integer[] choicesToCopy) {
642
643     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
644     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
645     return copyOfChoices;
646   }
647
648   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
649     // Check the next choice and if the value is not the same as the expected then force the expected value
650     int choiceIndex = choiceCounter % refChoices.length;
651     int nextChoice = icsCG.getNextChoice();
652     if (refChoices[choiceIndex] != nextChoice) {
653       int expectedChoice = refChoices[choiceIndex];
654       int currCGIndex = icsCG.getNextChoiceIndex();
655       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
656         icsCG.setChoice(currCGIndex, expectedChoice);
657       }
658     }
659     // Get state ID and associate it with this transition
660     int stateId = vm.getStateId();
661     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
662     // Add new transition to the current execution and map it in R-Graph
663     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
664       rGraph.addReachableTransition(stId, transition);
665     }
666     currentExecution.mapCGToChoice(icsCG, choiceCounter);
667     // Store restorable state object for this state (always store the latest)
668     if (!restorableStateMap.containsKey(stateId)) {
669       RestorableVMState restorableState = vm.getRestorableState();
670       restorableStateMap.put(stateId, restorableState);
671     }
672   }
673
674   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
675     // Get a new transition
676     TransitionEvent transition;
677     if (currentExecution.isNew()) {
678       // We need to handle the first transition differently because this has a predecessor execution
679       transition = currentExecution.getFirstTransition();
680     } else {
681       transition = new TransitionEvent();
682       currentExecution.addTransition(transition);
683       transition.recordPredecessor(currentExecution, choiceCounter - 1);
684     }
685     transition.setExecution(currentExecution);
686     transition.setTransitionCG(icsCG);
687     transition.setStateId(stateId);
688     transition.setChoice(refChoices[choiceIndex]);
689     transition.setChoiceCounter(choiceCounter);
690
691     return transition;
692   }
693
694   // --- Functions related to cycle detection and reachability graph
695
696   // Detect cycles in the current execution/trace
697   // We terminate the execution iff:
698   // (1) the state has been visited in the current execution
699   // (2) the state has one or more cycles that involve all the events
700   // With simple approach we only need to check for a re-visited state.
701   // Basically, we have to check that we have executed all events between two occurrences of such state.
702   private boolean completeFullCycle(int stId) {
703     // False if the state ID hasn't been recorded
704     if (!stateToEventMap.containsKey(stId)) {
705       return false;
706     }
707     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
708     // Check if this set contains all the event choices
709     // If not then this is not the terminating condition
710     for(int i=0; i<=maxEventChoice; i++) {
711       if (!visitedEvents.contains(i)) {
712         return false;
713       }
714     }
715     return true;
716   }
717
718   private void initializeStatesVariables() {
719     // DPOR-related
720     choices = null;
721     refChoices = null;
722     choiceCounter = 0;
723     maxEventChoice = 0;
724     // Cycle tracking
725     currVisitedStates = new HashSet<>();
726     justVisitedStates = new HashSet<>();
727     prevVisitedStates = new HashSet<>();
728     stateToEventMap = new HashMap<>();
729     // Backtracking
730     backtrackMap = new HashMap<>();
731     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
732     currentExecution = new Execution();
733     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
734     doneBacktrackMap = new HashMap<>();
735     rGraph = new RGraph();
736     // Booleans
737     isEndOfExecution = false;
738   }
739
740   private void mapStateToEvent(int nextChoiceValue) {
741     // Update all states with this event/choice
742     // This means that all past states now see this transition
743     Set<Integer> stateSet = stateToEventMap.keySet();
744     for(Integer stateId : stateSet) {
745       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
746       eventSet.add(nextChoiceValue);
747     }
748   }
749
750   private boolean terminateCurrentExecution() {
751     // We need to check all the states that have just been visited
752     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
753     for(Integer stateId : justVisitedStates) {
754       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
755         return true;
756       }
757     }
758     return false;
759   }
760
761   private void updateStateInfo(Search search) {
762     // Update the state variables
763     int stateId = search.getStateId();
764     // Insert state ID into the map if it is new
765     if (!stateToEventMap.containsKey(stateId)) {
766       HashSet<Integer> eventSet = new HashSet<>();
767       stateToEventMap.put(stateId, eventSet);
768     }
769     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
770     justVisitedStates.add(stateId);
771     if (!prevVisitedStates.contains(stateId)) {
772       // It is a currently visited states if the state has not been seen in previous executions
773       currVisitedStates.add(stateId);
774     }
775   }
776
777   // --- Functions related to Read/Write access analysis on shared fields
778
779   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
780     // Insert backtrack point to the right state ID
781     LinkedList<BacktrackExecution> backtrackExecList;
782     if (backtrackMap.containsKey(stateId)) {
783       backtrackExecList = backtrackMap.get(stateId);
784     } else {
785       backtrackExecList = new LinkedList<>();
786       backtrackMap.put(stateId, backtrackExecList);
787     }
788     // Add the new backtrack execution object
789     TransitionEvent backtrackTransition = new TransitionEvent();
790     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
791     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
792     // Add to priority queue
793     if (!backtrackStateQ.contains(stateId)) {
794       backtrackStateQ.add(stateId);
795     }
796   }
797
798   // Analyze Read/Write accesses that are directly invoked on fields
799   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
800     // Get the field info
801     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
802     // Analyze only after being initialized
803     String fieldClass = fieldInfo.getFullName();
804     // Do the analysis to get Read and Write accesses to fields
805     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
806     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
807     // Record the field in the map
808     if (executedInsn instanceof WriteInstruction) {
809       // We first check the non-relevant fields set
810       if (!nonRelevantFields.contains(fieldInfo)) {
811         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
812         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
813           if (fieldClass.startsWith(str)) {
814             nonRelevantFields.add(fieldInfo);
815             return;
816           }
817         }
818       } else {
819         // If we have this field in the non-relevant fields set then we return right away
820         return;
821       }
822       rwSet.addWriteField(fieldClass, objectId);
823     } else if (executedInsn instanceof ReadInstruction) {
824       rwSet.addReadField(fieldClass, objectId);
825     }
826   }
827
828   // Analyze Read accesses that are indirect (performed through iterators)
829   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
830   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
831     // Get method name
832     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
833     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
834             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
835       // Extract info from the stack frame
836       StackFrame frame = ti.getTopFrame();
837       int[] frameSlots = frame.getSlots();
838       // Get the Groovy callsite library at index 0
839       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
840       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
841         return;
842       }
843       // Get the iterated object whose property is accessed
844       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
845       if (eiAccessObj == null) {
846         return;
847       }
848       // We exclude library classes (they start with java, org, etc.) and some more
849       ClassInfo classInfo = eiAccessObj.getClassInfo();
850       String objClassName = classInfo.getName();
851       // Check if this class info is part of the non-relevant classes set already
852       if (!nonRelevantClasses.contains(classInfo)) {
853         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
854                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
855           nonRelevantClasses.add(classInfo);
856           return;
857         }
858       } else {
859         // If it is part of the non-relevant classes set then return immediately
860         return;
861       }
862       // Extract fields from this object and put them into the read write
863       int numOfFields = eiAccessObj.getNumberOfFields();
864       for(int i=0; i<numOfFields; i++) {
865         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
866         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
867           String fieldClass = fieldInfo.getFullName();
868           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
869           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
870           // Record the field in the map
871           rwSet.addReadField(fieldClass, objectId);
872         }
873       }
874     }
875   }
876
877   private int checkAndAdjustChoice(int currentChoice, VM vm) {
878     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
879     // for certain method calls in the infrastructure, e.g., eventSince()
880     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
881     // This is the main event CG
882     if (currentCG instanceof IntIntervalGenerator) {
883       // This is the interval CG used in device handlers
884       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
885       // Iterate until we find the IntChoiceFromSet CG
886       while (!(parentCG instanceof IntChoiceFromSet)) {
887         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
888       }
889       // Find the choice related to the IntIntervalGenerator CG from the map
890       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
891     }
892     return currentChoice;
893   }
894
895   private void createBacktrackingPoint(Execution execution, int currentChoice,
896                                        Execution conflictExecution, int conflictChoice) {
897     // Create a new list of choices for backtrack based on the current choice and conflicting event number
898     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
899     // for the original set {0, 1, 2, 3}
900     
901     // execution/currentChoice represent the event/transaction that will be put into the backtracking set of
902     // conflictExecution/conflictChoice
903     Integer[] newChoiceList = new Integer[refChoices.length];
904     ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
905     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
906     int currChoice = currentTrace.get(currentChoice).getChoice();
907     int stateId = conflictTrace.get(conflictChoice).getStateId();
908     // Check if this trace has been done from this state
909     if (isTraceAlreadyConstructed(currChoice, stateId)) {
910       return;
911     }
912     // Put the conflicting event numbers first and reverse the order
913     newChoiceList[0] = currChoice;
914     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
915     for (int i = 0, j = 1; i < refChoices.length; i++) {
916       if (refChoices[i] != newChoiceList[0]) {
917         newChoiceList[j] = refChoices[i];
918         j++;
919       }
920     }
921     // Predecessor of the new backtrack point is the same as the conflict point's
922     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
923   }
924
925   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
926     for (String excludedField : excludedStrings) {
927       if (className.contains(excludedField)) {
928         return true;
929       }
930     }
931     return false;
932   }
933
934   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
935     for (String excludedField : excludedStrings) {
936       if (className.endsWith(excludedField)) {
937         return true;
938       }
939     }
940     return false;
941   }
942
943   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
944     for (String excludedField : excludedStrings) {
945       if (className.startsWith(excludedField)) {
946         return true;
947       }
948     }
949     return false;
950   }
951
952   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
953                 // Check if we are reaching the end of our execution: no more backtracking points to explore
954                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
955                 if (!backtrackStateQ.isEmpty()) {
956                         // Set done all the other backtrack points
957                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
958         backtrackTransition.getTransitionCG().setDone();
959                         }
960                         // Reset the next backtrack point with the latest state
961                         int hiStateId = backtrackStateQ.peek();
962                         // Restore the state first if necessary
963                         if (vm.getStateId() != hiStateId) {
964                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
965                                 vm.restoreState(restorableState);
966                         }
967                         // Set the backtrack CG
968                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
969                         setBacktrackCG(hiStateId, backtrackCG);
970                 } else {
971                         // Set done this last CG (we save a few rounds)
972                         icsCG.setDone();
973                 }
974                 // Save all the visited states when starting a new execution of trace
975                 prevVisitedStates.addAll(currVisitedStates);
976                 // This marks a transitional period to the new CG
977                 isEndOfExecution = true;
978   }
979
980   private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
981                                   ReadWriteSet currRWSet) {
982     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
983     ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
984     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
985     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
986     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
987     if (!confRWFieldsMap.containsKey(conflictChoice) ||
988             executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
989       return false;
990     }
991     // R/W set of choice/event that may have a potential conflict
992     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
993     // Check for conflicts with Read and Write fields for Write instructions
994     Set<String> currWriteSet = currRWSet.getWriteSet();
995     for(String writeField : currWriteSet) {
996       int currObjId = currRWSet.writeFieldObjectId(writeField);
997       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
998           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
999         // Remove this from the write set as we are tracking per memory location
1000         currRWSet.removeWriteField(writeField);
1001         return true;
1002       }
1003     }
1004     // Check for conflicts with Write fields for Read instructions
1005     Set<String> currReadSet = currRWSet.getReadSet();
1006     for(String readField : currReadSet) {
1007       int currObjId = currRWSet.readFieldObjectId(readField);
1008       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1009         // Remove this from the read set as we are tracking per memory location
1010         currRWSet.removeReadField(readField);
1011         return true;
1012       }
1013     }
1014     // Return false if no conflict is found
1015     return false;
1016   }
1017
1018   private ReadWriteSet getReadWriteSet(int currentChoice) {
1019     // Do the analysis to get Read and Write accesses to fields
1020     ReadWriteSet rwSet;
1021     // We already have an entry
1022     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1023     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1024       rwSet = currReadWriteFieldsMap.get(currentChoice);
1025     } else { // We need to create a new entry
1026       rwSet = new ReadWriteSet();
1027       currReadWriteFieldsMap.put(currentChoice, rwSet);
1028     }
1029     return rwSet;
1030   }
1031
1032   private boolean isFieldExcluded(Instruction executedInsn) {
1033     // Get the field info
1034     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1035     // Check if the non-relevant fields set already has it
1036     if (nonRelevantFields.contains(fieldInfo)) {
1037       return true;
1038     }
1039     // Check if the relevant fields set already has it
1040     if (relevantFields.contains(fieldInfo)) {
1041       return false;
1042     }
1043     // Analyze only after being initialized
1044     String field = fieldInfo.getFullName();
1045     // Check against "starts-with", "ends-with", and "contains" list
1046     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1047             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1048             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1049       nonRelevantFields.add(fieldInfo);
1050       return true;
1051     }
1052     relevantFields.add(fieldInfo);
1053     return false;
1054   }
1055
1056   // Check if this trace is already constructed
1057   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1058     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1059     // Check if the trace has been constructed as a backtrack point for this state
1060     // TODO: THIS IS AN OPTIMIZATION!
1061     HashSet<Integer> choiceSet;
1062     if (doneBacktrackMap.containsKey(stateId)) {
1063       choiceSet = doneBacktrackMap.get(stateId);
1064       if (choiceSet.contains(firstChoice)) {
1065         return true;
1066       }
1067     } else {
1068       choiceSet = new HashSet<>();
1069       doneBacktrackMap.put(stateId, choiceSet);
1070     }
1071     choiceSet.add(firstChoice);
1072
1073     return false;
1074   }
1075
1076   // Reset data structure for each new execution
1077   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1078     if (choices == null || choices != icsCG.getAllChoices()) {
1079       // Reset state variables
1080       choiceCounter = 0;
1081       choices = icsCG.getAllChoices();
1082       refChoices = copyChoices(choices);
1083       // Clear data structures
1084       currVisitedStates = new HashSet<>();
1085       stateToEventMap = new HashMap<>();
1086       isEndOfExecution = false;
1087     }
1088   }
1089
1090   // Set a backtrack point for a particular state
1091   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1092     // Set a backtrack CG based on a state ID
1093     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1094     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1095     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1096     backtrackCG.setStateId(stateId);
1097     backtrackCG.reset();
1098     // Update current execution with this new execution
1099     Execution newExecution = new Execution();
1100     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1101     newExecution.addTransition(firstTransition);
1102     // Try to free some memory since this map is only used for the current execution
1103     currentExecution.clearCGToChoiceMap();
1104     currentExecution = newExecution;
1105     // Remove from the queue if we don't have more backtrack points for that state
1106     if (backtrackExecutions.isEmpty()) {
1107       backtrackMap.remove(stateId);
1108       backtrackStateQ.remove(stateId);
1109     }
1110   }
1111
1112   // Update backtrack sets
1113   // 1) recursively, and
1114   // 2) track accesses per memory location (per shared variable/field)
1115   private void updateBacktrackSet(Execution execution, int currentChoice) {
1116     // Copy ReadWriteSet object
1117     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1118     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1119     if (currRWSet == null) {
1120       return;
1121     }
1122     currRWSet = currRWSet.getCopy();
1123     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1124     HashSet<TransitionEvent> visited = new HashSet<>();
1125     // Update backtrack set recursively
1126     // TODO: The following is the call to the original version of the method
1127 //    updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1128     // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1129     updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1130   }
1131
1132 //  TODO: This is the original version of the recursive method
1133 //  private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1134 //                                           Execution conflictExecution, int conflictChoice,
1135 //                                           ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1136 //    // Halt when we have found the first read/write conflicts for all memory locations
1137 //    if (currRWSet.isEmpty()) {
1138 //      return;
1139 //    }
1140 //    TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1141 //    // Halt when we have visited this transition (in a cycle)
1142 //    if (visited.contains(confTrans)) {
1143 //      return;
1144 //    }
1145 //    visited.add(confTrans);
1146 //    // Explore all predecessors
1147 //    for (Predecessor predecessor : confTrans.getPredecessors()) {
1148 //      // Get the predecessor (previous conflict choice)
1149 //      conflictChoice = predecessor.getChoice();
1150 //      conflictExecution = predecessor.getExecution();
1151 //      // Check if a conflict is found
1152 //      if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1153 //        createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1154 //      }
1155 //      // Continue performing DFS if conflict is not found
1156 //      updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1157 //    }
1158 //  }
1159
1160   // TODO: This is the version of the method with pushing up happens-before transitions
1161   private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1162                                            Execution conflictExecution, int conflictChoice,
1163                                            ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1164     // Halt when we have found the first read/write conflicts for all memory locations
1165     if (currRWSet.isEmpty()) {
1166       return;
1167     }
1168     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1169     // Halt when we have visited this transition (in a cycle)
1170     if (visited.contains(currTrans)) {
1171       return;
1172     }
1173     visited.add(currTrans);
1174     // Explore all predecessors
1175     for (Predecessor predecessor : currTrans.getPredecessors()) {
1176       // Get the predecessor (previous conflict choice)
1177       int predecessorChoice = predecessor.getChoice();
1178       Execution predecessorExecution = predecessor.getExecution();
1179       // Push up one happens-before transition
1180       int newConflictChoice = conflictChoice;
1181       Execution newConflictExecution = conflictExecution;
1182       // Check if a conflict is found
1183       if (isConflictFound(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1184         createBacktrackingPoint(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice);
1185         newConflictChoice = conflictChoice;
1186         newConflictExecution = conflictExecution;
1187       }
1188       // Continue performing DFS if conflict is not found
1189       updateBacktrackSetRecursive(predecessorExecution, predecessorChoice, newConflictExecution, newConflictChoice,
1190               currRWSet, visited);
1191     }
1192     // Remove the transition after being explored
1193     // TODO: Seems to cause a lot of loops---commented out for now
1194     //visited.remove(confTrans);
1195   }
1196
1197   // --- Functions related to the reachability analysis when there is a state match
1198
1199   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1200     // Perform this analysis only when:
1201     // 1) this is not during a switch to a new execution,
1202     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1203     // 3) state > 0 (state 0 is for boolean CG)
1204     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1205       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1206         // Update reachable transitions in the graph with a predecessor
1207         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1208         for(TransitionEvent transition : reachableTransitions) {
1209           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1210         }
1211         updateBacktrackSetsFromPreviousExecution(stateId);
1212       }
1213     }
1214   }
1215
1216   // Update the backtrack sets from previous executions
1217   private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1218     // Collect all the reachable transitions from R-Graph
1219     HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1220     for(TransitionEvent transition : reachableTransitions) {
1221       Execution execution = transition.getExecution();
1222       int currentChoice = transition.getChoiceCounter();
1223       updateBacktrackSet(execution, currentChoice);
1224     }
1225   }
1226 }