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