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