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