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