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