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