Cleaning up: checking source code for (potential) bugs.
[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 (terminateCurrentExecution() && choiceCounter > 0) {
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 choice, int stateId) {
639       HashMap<Integer, ReadWriteSet> stateSummary = mainSummary.get(stateId);
640       return stateSummary.get(choice);
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       HashMap<Integer, ReadWriteSet> stateSummary;
682       if (!mainSummary.containsKey(stateId)) {
683         stateSummary = new HashMap<>();
684         stateSummary.put(eventChoice, rwSet.getCopy());
685         mainSummary.put(stateId, stateSummary);
686       } else {
687         stateSummary = mainSummary.get(stateId);
688         if (!stateSummary.containsKey(eventChoice)) {
689           stateSummary.put(eventChoice, rwSet.getCopy());
690         } else {
691           rwSet = performUnion(stateSummary.get(eventChoice), rwSet);
692         }
693       }
694       return rwSet;
695     }
696   }
697
698   // -- CONSTANTS
699   private final static String DO_CALL_METHOD = "doCall";
700   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
701   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
702   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
703           // Groovy library created fields
704           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
705           // Infrastructure
706           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
707           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
708   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
709           // Java and Groovy libraries
710           { "java", "org", "sun", "com", "gov", "groovy"};
711   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
712   private final static String GET_PROPERTY_METHOD =
713           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
714   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
715   private final static String JAVA_INTEGER = "int";
716   private final static String JAVA_STRING_LIB = "java.lang.String";
717
718   // -- FUNCTIONS
719   private Integer[] copyChoices(Integer[] choicesToCopy) {
720
721     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
722     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
723     return copyOfChoices;
724   }
725
726   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
727     // Check the next choice and if the value is not the same as the expected then force the expected value
728     int choiceIndex = choiceCounter % refChoices.length;
729     int nextChoice = icsCG.getNextChoice();
730     if (refChoices[choiceIndex] != nextChoice) {
731       int expectedChoice = refChoices[choiceIndex];
732       int currCGIndex = icsCG.getNextChoiceIndex();
733       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
734         icsCG.setChoice(currCGIndex, expectedChoice);
735       }
736     }
737     // Get state ID and associate it with this transition
738     int stateId = vm.getStateId();
739     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
740     // Add new transition to the current execution and map it in R-Graph
741     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
742       rGraph.addReachableTransition(stId, transition);
743     }
744     currentExecution.mapCGToChoice(icsCG, choiceCounter);
745     // Store restorable state object for this state (always store the latest)
746     if (!restorableStateMap.containsKey(stateId)) {
747       RestorableVMState restorableState = vm.getRestorableState();
748       restorableStateMap.put(stateId, restorableState);
749     }
750   }
751
752   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
753     // Get a new transition
754     TransitionEvent transition;
755     if (currentExecution.isNew()) {
756       // We need to handle the first transition differently because this has a predecessor execution
757       transition = currentExecution.getFirstTransition();
758     } else {
759       transition = new TransitionEvent();
760       currentExecution.addTransition(transition);
761       transition.recordPredecessor(currentExecution, choiceCounter - 1);
762     }
763     transition.setExecution(currentExecution);
764     transition.setTransitionCG(icsCG);
765     transition.setStateId(stateId);
766     transition.setChoice(refChoices[choiceIndex]);
767     transition.setChoiceCounter(choiceCounter);
768
769     return transition;
770   }
771
772   // --- Functions related to cycle detection and reachability graph
773
774   // Detect cycles in the current execution/trace
775   // We terminate the execution iff:
776   // (1) the state has been visited in the current execution
777   // (2) the state has one or more cycles that involve all the events
778   // With simple approach we only need to check for a re-visited state.
779   // Basically, we have to check that we have executed all events between two occurrences of such state.
780   private boolean completeFullCycle(int stId) {
781     // False if the state ID hasn't been recorded
782     if (!stateToEventMap.containsKey(stId)) {
783       return false;
784     }
785     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
786     // Check if this set contains all the event choices
787     // If not then this is not the terminating condition
788     for(int i=0; i<=maxEventChoice; i++) {
789       if (!visitedEvents.contains(i)) {
790         return false;
791       }
792     }
793     return true;
794   }
795
796   private void initializeStatesVariables() {
797     // DPOR-related
798     choices = null;
799     refChoices = null;
800     choiceCounter = 0;
801     maxEventChoice = 0;
802     // Cycle tracking
803     currVisitedStates = new HashMap<>();
804     justVisitedStates = new HashSet<>();
805     prevVisitedStates = new HashSet<>();
806     stateToEventMap = new HashMap<>();
807     // Backtracking
808     backtrackMap = new HashMap<>();
809     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
810     currentExecution = new Execution();
811     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
812     doneBacktrackMap = new HashMap<>();
813     rGraph = new RGraph();
814     // Booleans
815     isEndOfExecution = false;
816   }
817
818   private void mapStateToEvent(int nextChoiceValue) {
819     // Update all states with this event/choice
820     // This means that all past states now see this transition
821     Set<Integer> stateSet = stateToEventMap.keySet();
822     for(Integer stateId : stateSet) {
823       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
824       eventSet.add(nextChoiceValue);
825     }
826   }
827
828   private boolean terminateCurrentExecution() {
829     // We need to check all the states that have just been visited
830     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
831     boolean terminate = false;
832     for(Integer stateId : justVisitedStates) {
833       // We perform updates on backtrack sets for every
834       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
835         updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
836         terminate = true;
837       }
838       // If frequency > 1 then this means we have visited this stateId more than once
839       if (currVisitedStates.containsKey(stateId) && currVisitedStates.get(stateId) > 1) {
840         updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
841       }
842     }
843     return terminate;
844   }
845
846   private void updateStateInfo(Search search) {
847     // Update the state variables
848     int stateId = search.getStateId();
849     // Insert state ID into the map if it is new
850     if (!stateToEventMap.containsKey(stateId)) {
851       HashSet<Integer> eventSet = new HashSet<>();
852       stateToEventMap.put(stateId, eventSet);
853     }
854     addPredecessorToRevisitedState(stateId);
855     justVisitedStates.add(stateId);
856     if (!prevVisitedStates.contains(stateId)) {
857       // It is a currently visited states if the state has not been seen in previous executions
858       int frequency = 0;
859       if (currVisitedStates.containsKey(stateId)) {
860         frequency = currVisitedStates.get(stateId);
861       }
862       currVisitedStates.put(stateId, frequency + 1);  // Increment frequency counter
863     }
864   }
865
866   // --- Functions related to Read/Write access analysis on shared fields
867
868   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
869     // Insert backtrack point to the right state ID
870     LinkedList<BacktrackExecution> backtrackExecList;
871     if (backtrackMap.containsKey(stateId)) {
872       backtrackExecList = backtrackMap.get(stateId);
873     } else {
874       backtrackExecList = new LinkedList<>();
875       backtrackMap.put(stateId, backtrackExecList);
876     }
877     // Add the new backtrack execution object
878     TransitionEvent backtrackTransition = new TransitionEvent();
879     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
880     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
881     // Add to priority queue
882     if (!backtrackStateQ.contains(stateId)) {
883       backtrackStateQ.add(stateId);
884     }
885   }
886
887   // Analyze Read/Write accesses that are directly invoked on fields
888   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
889     // Get the field info
890     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
891     // Analyze only after being initialized
892     String fieldClass = fieldInfo.getFullName();
893     // Do the analysis to get Read and Write accesses to fields
894     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
895     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
896     // Record the field in the map
897     if (executedInsn instanceof WriteInstruction) {
898       // We first check the non-relevant fields set
899       if (!nonRelevantFields.contains(fieldInfo)) {
900         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
901         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
902           if (fieldClass.startsWith(str)) {
903             nonRelevantFields.add(fieldInfo);
904             return;
905           }
906         }
907       } else {
908         // If we have this field in the non-relevant fields set then we return right away
909         return;
910       }
911       rwSet.addWriteField(fieldClass, objectId);
912     } else if (executedInsn instanceof ReadInstruction) {
913       rwSet.addReadField(fieldClass, objectId);
914     }
915   }
916
917   // Analyze Read accesses that are indirect (performed through iterators)
918   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
919   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
920     // Get method name
921     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
922     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
923             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
924       // Extract info from the stack frame
925       StackFrame frame = ti.getTopFrame();
926       int[] frameSlots = frame.getSlots();
927       // Get the Groovy callsite library at index 0
928       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
929       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
930         return;
931       }
932       // Get the iterated object whose property is accessed
933       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
934       if (eiAccessObj == null) {
935         return;
936       }
937       // We exclude library classes (they start with java, org, etc.) and some more
938       ClassInfo classInfo = eiAccessObj.getClassInfo();
939       String objClassName = classInfo.getName();
940       // Check if this class info is part of the non-relevant classes set already
941       if (!nonRelevantClasses.contains(classInfo)) {
942         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
943                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
944           nonRelevantClasses.add(classInfo);
945           return;
946         }
947       } else {
948         // If it is part of the non-relevant classes set then return immediately
949         return;
950       }
951       // Extract fields from this object and put them into the read write
952       int numOfFields = eiAccessObj.getNumberOfFields();
953       for(int i=0; i<numOfFields; i++) {
954         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
955         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
956           String fieldClass = fieldInfo.getFullName();
957           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
958           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
959           // Record the field in the map
960           rwSet.addReadField(fieldClass, objectId);
961         }
962       }
963     }
964   }
965
966   private int checkAndAdjustChoice(int currentChoice, VM vm) {
967     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
968     // for certain method calls in the infrastructure, e.g., eventSince()
969     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
970     // This is the main event CG
971     if (currentCG instanceof IntIntervalGenerator) {
972       // This is the interval CG used in device handlers
973       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
974       // Iterate until we find the IntChoiceFromSet CG
975       while (!(parentCG instanceof IntChoiceFromSet)) {
976         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
977       }
978       // Find the choice related to the IntIntervalGenerator CG from the map
979       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
980     }
981     return currentChoice;
982   }
983
984   private void createBacktrackingPoint(int eventChoice, Execution conflictExecution, int conflictChoice) {
985     // Create a new list of choices for backtrack based on the current choice and conflicting event number
986     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
987     // for the original set {0, 1, 2, 3}
988     
989     // eventChoice represent the event/transaction that will be put into the backtracking set of
990     // conflictExecution/conflictChoice
991     Integer[] newChoiceList = new Integer[refChoices.length];
992     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
993     int stateId = conflictTrace.get(conflictChoice).getStateId();
994     // Check if this trace has been done from this state
995     if (isTraceAlreadyConstructed(eventChoice, stateId)) {
996       return;
997     }
998     // Put the conflicting event numbers first and reverse the order
999     newChoiceList[0] = eventChoice;
1000     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
1001     for (int i = 0, j = 1; i < refChoices.length; i++) {
1002       if (refChoices[i] != newChoiceList[0]) {
1003         newChoiceList[j] = refChoices[i];
1004         j++;
1005       }
1006     }
1007     // Predecessor of the new backtrack point is the same as the conflict point's
1008     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
1009   }
1010
1011   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
1012     for (String excludedField : excludedStrings) {
1013       if (className.contains(excludedField)) {
1014         return true;
1015       }
1016     }
1017     return false;
1018   }
1019
1020   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
1021     for (String excludedField : excludedStrings) {
1022       if (className.endsWith(excludedField)) {
1023         return true;
1024       }
1025     }
1026     return false;
1027   }
1028
1029   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1030     for (String excludedField : excludedStrings) {
1031       if (className.startsWith(excludedField)) {
1032         return true;
1033       }
1034     }
1035     return false;
1036   }
1037
1038   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1039                 // Check if we are reaching the end of our execution: no more backtracking points to explore
1040                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1041                 if (!backtrackStateQ.isEmpty()) {
1042                         // Set done all the other backtrack points
1043                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1044         backtrackTransition.getTransitionCG().setDone();
1045                         }
1046                         // Reset the next backtrack point with the latest state
1047                         int hiStateId = backtrackStateQ.peek();
1048                         // Restore the state first if necessary
1049                         if (vm.getStateId() != hiStateId) {
1050                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1051                                 vm.restoreState(restorableState);
1052                         }
1053                         // Set the backtrack CG
1054                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1055                         setBacktrackCG(hiStateId, backtrackCG);
1056                 } else {
1057                         // Set done this last CG (we save a few rounds)
1058                         icsCG.setDone();
1059                 }
1060                 // Save all the visited states when starting a new execution of trace
1061                 prevVisitedStates.addAll(currVisitedStates.keySet());
1062                 // This marks a transitional period to the new CG
1063                 isEndOfExecution = true;
1064   }
1065
1066   private boolean isConflictFound(int eventChoice, Execution conflictExecution, int conflictChoice,
1067                                   ReadWriteSet currRWSet) {
1068     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1069     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1070     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1071     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1072     if (!confRWFieldsMap.containsKey(conflictChoice) ||
1073             eventChoice == conflictTrace.get(conflictChoice).getChoice()) {
1074       return false;
1075     }
1076     // R/W set of choice/event that may have a potential conflict
1077     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1078     // Check for conflicts with Read and Write fields for Write instructions
1079     Set<String> currWriteSet = currRWSet.getWriteSet();
1080     for(String writeField : currWriteSet) {
1081       int currObjId = currRWSet.writeFieldObjectId(writeField);
1082       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1083           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1084         // Remove this from the write set as we are tracking per memory location
1085         currRWSet.removeWriteField(writeField);
1086         return true;
1087       }
1088     }
1089     // Check for conflicts with Write fields for Read instructions
1090     Set<String> currReadSet = currRWSet.getReadSet();
1091     for(String readField : currReadSet) {
1092       int currObjId = currRWSet.readFieldObjectId(readField);
1093       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1094         // Remove this from the read set as we are tracking per memory location
1095         currRWSet.removeReadField(readField);
1096         return true;
1097       }
1098     }
1099     // Return false if no conflict is found
1100     return false;
1101   }
1102
1103   private ReadWriteSet getReadWriteSet(int currentChoice) {
1104     // Do the analysis to get Read and Write accesses to fields
1105     ReadWriteSet rwSet;
1106     // We already have an entry
1107     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1108     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1109       rwSet = currReadWriteFieldsMap.get(currentChoice);
1110     } else { // We need to create a new entry
1111       rwSet = new ReadWriteSet();
1112       currReadWriteFieldsMap.put(currentChoice, rwSet);
1113     }
1114     return rwSet;
1115   }
1116
1117   private boolean isFieldExcluded(Instruction executedInsn) {
1118     // Get the field info
1119     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1120     // Check if the non-relevant fields set already has it
1121     if (nonRelevantFields.contains(fieldInfo)) {
1122       return true;
1123     }
1124     // Check if the relevant fields set already has it
1125     if (relevantFields.contains(fieldInfo)) {
1126       return false;
1127     }
1128     // Analyze only after being initialized
1129     String field = fieldInfo.getFullName();
1130     // Check against "starts-with", "ends-with", and "contains" list
1131     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1132             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1133             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1134       nonRelevantFields.add(fieldInfo);
1135       return true;
1136     }
1137     relevantFields.add(fieldInfo);
1138     return false;
1139   }
1140
1141   // Check if this trace is already constructed
1142   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1143     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1144     // Check if the trace has been constructed as a backtrack point for this state
1145     // TODO: THIS IS AN OPTIMIZATION!
1146     HashSet<Integer> choiceSet;
1147     if (doneBacktrackMap.containsKey(stateId)) {
1148       choiceSet = doneBacktrackMap.get(stateId);
1149       if (choiceSet.contains(firstChoice)) {
1150         return true;
1151       }
1152     } else {
1153       choiceSet = new HashSet<>();
1154       doneBacktrackMap.put(stateId, choiceSet);
1155     }
1156     choiceSet.add(firstChoice);
1157
1158     return false;
1159   }
1160
1161   // Reset data structure for each new execution
1162   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1163     if (choices == null || choices != icsCG.getAllChoices()) {
1164       // Reset state variables
1165       choiceCounter = 0;
1166       choices = icsCG.getAllChoices();
1167       refChoices = copyChoices(choices);
1168       // Clear data structures
1169       currVisitedStates = new HashMap<>();
1170       stateToEventMap = new HashMap<>();
1171       isEndOfExecution = false;
1172     }
1173   }
1174
1175   // Set a backtrack point for a particular state
1176   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1177     // Set a backtrack CG based on a state ID
1178     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1179     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1180     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1181     backtrackCG.setStateId(stateId);
1182     backtrackCG.reset();
1183     // Update current execution with this new execution
1184     Execution newExecution = new Execution();
1185     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1186     newExecution.addTransition(firstTransition);
1187     // Try to free some memory since this map is only used for the current execution
1188     currentExecution.clearCGToChoiceMap();
1189     currentExecution = newExecution;
1190     // Remove from the queue if we don't have more backtrack points for that state
1191     if (backtrackExecutions.isEmpty()) {
1192       backtrackMap.remove(stateId);
1193       backtrackStateQ.remove(stateId);
1194     }
1195   }
1196
1197   // Update backtrack sets
1198   // 1) recursively, and
1199   // 2) track accesses per memory location (per shared variable/field)
1200   private void updateBacktrackSet(Execution execution, int currentChoice) {
1201     // Copy ReadWriteSet object
1202     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1203     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1204     if (currRWSet == null) {
1205       return;
1206     }
1207     currRWSet = currRWSet.getCopy();
1208     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1209     HashSet<TransitionEvent> visited = new HashSet<>();
1210     // Conflict TransitionEvent is essentially the current TransitionEvent
1211     TransitionEvent confTrans = execution.getExecutionTrace().get(currentChoice);
1212     // Update backtrack set recursively
1213     updateBacktrackSetDFS(execution, currentChoice, confTrans.getChoice(), currRWSet, visited);
1214   }
1215
1216   private void updateBacktrackSetDFS(Execution execution, int currentChoice, int conflictEventChoice,
1217                                      ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1218     // Halt when we have found the first read/write conflicts for all memory locations
1219     if (currRWSet.isEmpty()) {
1220       return;
1221     }
1222     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1223     // Record this transition into the state summary of main summary
1224     currRWSet = mainSummary.updateStateSummary(currTrans.getStateId(), conflictEventChoice, currRWSet);
1225     // Halt when we have visited this transition (in a cycle)
1226     if (visited.contains(currTrans)) {
1227       return;
1228     }
1229     visited.add(currTrans);
1230     // Explore all predecessors
1231     for (Predecessor predecessor : currTrans.getPredecessors()) {
1232       // Get the predecessor (previous conflict choice)
1233       int predecessorChoice = predecessor.getChoice();
1234       Execution predecessorExecution = predecessor.getExecution();
1235       // Push up one happens-before transition
1236       int newConflictEventChoice = conflictEventChoice;
1237       // Check if a conflict is found
1238       if (isConflictFound(conflictEventChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1239         createBacktrackingPoint(conflictEventChoice, predecessorExecution, predecessorChoice);
1240         // We need to extract the pushed happens-before event choice from the predecessor execution and choice
1241         newConflictEventChoice = predecessorExecution.getExecutionTrace().get(predecessorChoice).getChoice();
1242       }
1243       // Continue performing DFS if conflict is not found
1244       updateBacktrackSetDFS(predecessorExecution, predecessorChoice, newConflictEventChoice,
1245               currRWSet, visited);
1246     }
1247   }
1248
1249   // --- Functions related to the reachability analysis when there is a state match
1250
1251   private void addPredecessorToRevisitedState(int stateId) {
1252     // Perform this analysis only when:
1253     // 1) this is not during a switch to a new execution,
1254     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1255     // 3) state > 0 (state 0 is for boolean CG)
1256     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1257       if ((currVisitedStates.containsKey(stateId) && currVisitedStates.get(stateId) > 1) ||
1258               prevVisitedStates.contains(stateId)) {
1259         // Update reachable transitions in the graph with a predecessor
1260         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1261         for (TransitionEvent transition : reachableTransitions) {
1262           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1263         }
1264       }
1265     }
1266   }
1267
1268   // Update the backtrack sets from previous executions
1269   private void updateBacktrackSetsFromGraph(int stateId, Execution currExecution, int currChoice) {
1270     // Get events/choices at this state ID
1271     Set<Integer> eventsAtStateId = mainSummary.getEventChoicesAtStateId(stateId);
1272     for (Integer event : eventsAtStateId) {
1273       // Get the ReadWriteSet object for this event at state ID
1274       ReadWriteSet rwSet = mainSummary.getRWSetForEventChoiceAtState(event, stateId);
1275       // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1276       HashSet<TransitionEvent> visited = new HashSet<>();
1277       // Update the backtrack sets recursively
1278       updateBacktrackSetDFS(currExecution, currChoice, event, rwSet, visited);
1279     }
1280   }
1281 }