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