8e688cf833cf13700c0e9a645fd67b82677355a9
[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     if (!restorableStateMap.containsKey(stateId)) {
645       RestorableVMState restorableState = vm.getRestorableState();
646       restorableStateMap.put(stateId, restorableState);
647     }
648   }
649
650   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
651     // Get a new transition
652     TransitionEvent transition;
653     if (currentExecution.isNew()) {
654       // We need to handle the first transition differently because this has a predecessor execution
655       transition = currentExecution.getFirstTransition();
656     } else {
657       transition = new TransitionEvent();
658       currentExecution.addTransition(transition);
659       transition.recordPredecessor(currentExecution, choiceCounter - 1);
660     }
661     transition.setExecution(currentExecution);
662     transition.setTransitionCG(icsCG);
663     transition.setStateId(stateId);
664     transition.setChoice(refChoices[choiceIndex]);
665     transition.setChoiceCounter(choiceCounter);
666
667     return transition;
668   }
669
670   // --- Functions related to cycle detection and reachability graph
671
672   // Detect cycles in the current execution/trace
673   // We terminate the execution iff:
674   // (1) the state has been visited in the current execution
675   // (2) the state has one or more cycles that involve all the events
676   // With simple approach we only need to check for a re-visited state.
677   // Basically, we have to check that we have executed all events between two occurrences of such state.
678   private boolean completeFullCycle(int stId) {
679     // False if the state ID hasn't been recorded
680     if (!stateToEventMap.containsKey(stId)) {
681       return false;
682     }
683     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
684     // Check if this set contains all the event choices
685     // If not then this is not the terminating condition
686     for(int i=0; i<=maxEventChoice; i++) {
687       if (!visitedEvents.contains(i)) {
688         return false;
689       }
690     }
691     return true;
692   }
693
694   private void initializeStatesVariables() {
695     // DPOR-related
696     choices = null;
697     refChoices = null;
698     choiceCounter = 0;
699     maxEventChoice = 0;
700     // Cycle tracking
701     currVisitedStates = new HashSet<>();
702     justVisitedStates = new HashSet<>();
703     prevVisitedStates = new HashSet<>();
704     stateToEventMap = new HashMap<>();
705     // Backtracking
706     backtrackMap = new HashMap<>();
707     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
708     currentExecution = new Execution();
709     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
710     doneBacktrackMap = new HashMap<>();
711     rGraph = new RGraph();
712     // Booleans
713     isEndOfExecution = false;
714   }
715
716   private void mapStateToEvent(int nextChoiceValue) {
717     // Update all states with this event/choice
718     // This means that all past states now see this transition
719     Set<Integer> stateSet = stateToEventMap.keySet();
720     for(Integer stateId : stateSet) {
721       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
722       eventSet.add(nextChoiceValue);
723     }
724   }
725
726   private boolean terminateCurrentExecution() {
727     // We need to check all the states that have just been visited
728     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
729     for(Integer stateId : justVisitedStates) {
730       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
731         return true;
732       }
733     }
734     return false;
735   }
736
737   private void updateStateInfo(Search search) {
738     // Update the state variables
739     int stateId = search.getStateId();
740     // Insert state ID into the map if it is new
741     if (!stateToEventMap.containsKey(stateId)) {
742       HashSet<Integer> eventSet = new HashSet<>();
743       stateToEventMap.put(stateId, eventSet);
744     }
745     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
746     justVisitedStates.add(stateId);
747     if (!prevVisitedStates.contains(stateId)) {
748       // It is a currently visited states if the state has not been seen in previous executions
749       currVisitedStates.add(stateId);
750     }
751   }
752
753   // --- Functions related to Read/Write access analysis on shared fields
754
755   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
756     // Insert backtrack point to the right state ID
757     LinkedList<BacktrackExecution> backtrackExecList;
758     if (backtrackMap.containsKey(stateId)) {
759       backtrackExecList = backtrackMap.get(stateId);
760     } else {
761       backtrackExecList = new LinkedList<>();
762       backtrackMap.put(stateId, backtrackExecList);
763     }
764     // Add the new backtrack execution object
765     TransitionEvent backtrackTransition = new TransitionEvent();
766     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
767     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
768     // Add to priority queue
769     if (!backtrackStateQ.contains(stateId)) {
770       backtrackStateQ.add(stateId);
771     }
772   }
773
774   // Analyze Read/Write accesses that are directly invoked on fields
775   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
776     // Get the field info
777     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
778     // Analyze only after being initialized
779     String fieldClass = fieldInfo.getFullName();
780     // Do the analysis to get Read and Write accesses to fields
781     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
782     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
783     // Record the field in the map
784     if (executedInsn instanceof WriteInstruction) {
785       // We first check the non-relevant fields set
786       if (!nonRelevantFields.contains(fieldInfo)) {
787         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
788         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
789           if (fieldClass.startsWith(str)) {
790             nonRelevantFields.add(fieldInfo);
791             return;
792           }
793         }
794       } else {
795         // If we have this field in the non-relevant fields set then we return right away
796         return;
797       }
798       rwSet.addWriteField(fieldClass, objectId);
799     } else if (executedInsn instanceof ReadInstruction) {
800       rwSet.addReadField(fieldClass, objectId);
801     }
802   }
803
804   // Analyze Read accesses that are indirect (performed through iterators)
805   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
806   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
807     // Get method name
808     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
809     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
810             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
811       // Extract info from the stack frame
812       StackFrame frame = ti.getTopFrame();
813       int[] frameSlots = frame.getSlots();
814       // Get the Groovy callsite library at index 0
815       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
816       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
817         return;
818       }
819       // Get the iterated object whose property is accessed
820       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
821       if (eiAccessObj == null) {
822         return;
823       }
824       // We exclude library classes (they start with java, org, etc.) and some more
825       ClassInfo classInfo = eiAccessObj.getClassInfo();
826       String objClassName = classInfo.getName();
827       // Check if this class info is part of the non-relevant classes set already
828       if (!nonRelevantClasses.contains(classInfo)) {
829         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
830                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
831           nonRelevantClasses.add(classInfo);
832           return;
833         }
834       } else {
835         // If it is part of the non-relevant classes set then return immediately
836         return;
837       }
838       // Extract fields from this object and put them into the read write
839       int numOfFields = eiAccessObj.getNumberOfFields();
840       for(int i=0; i<numOfFields; i++) {
841         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
842         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
843           String fieldClass = fieldInfo.getFullName();
844           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
845           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
846           // Record the field in the map
847           rwSet.addReadField(fieldClass, objectId);
848         }
849       }
850     }
851   }
852
853   private int checkAndAdjustChoice(int currentChoice, VM vm) {
854     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
855     // for certain method calls in the infrastructure, e.g., eventSince()
856     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
857     // This is the main event CG
858     if (currentCG instanceof IntIntervalGenerator) {
859       // This is the interval CG used in device handlers
860       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
861       // Iterate until we find the IntChoiceFromSet CG
862       while (!(parentCG instanceof IntChoiceFromSet)) {
863         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
864       }
865       // Find the choice related to the IntIntervalGenerator CG from the map
866       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
867     }
868     return currentChoice;
869   }
870
871   private void createBacktrackingPoint(Execution execution, int currentChoice,
872                                        Execution conflictExecution, int conflictChoice) {
873     // Create a new list of choices for backtrack based on the current choice and conflicting event number
874     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
875     // for the original set {0, 1, 2, 3}
876     Integer[] newChoiceList = new Integer[refChoices.length];
877     ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
878     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
879     int currChoice = currentTrace.get(currentChoice).getChoice();
880     int stateId = conflictTrace.get(conflictChoice).getStateId();
881     // Check if this trace has been done from this state
882     if (isTraceAlreadyConstructed(currChoice, stateId)) {
883       return;
884     }
885     // Put the conflicting event numbers first and reverse the order
886     newChoiceList[0] = currChoice;
887     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
888     for (int i = 0, j = 1; i < refChoices.length; i++) {
889       if (refChoices[i] != newChoiceList[0]) {
890         newChoiceList[j] = refChoices[i];
891         j++;
892       }
893     }
894     // Predecessor of the new backtrack point is the same as the conflict point's
895     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
896   }
897
898   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
899     for (String excludedField : excludedStrings) {
900       if (className.contains(excludedField)) {
901         return true;
902       }
903     }
904     return false;
905   }
906
907   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
908     for (String excludedField : excludedStrings) {
909       if (className.endsWith(excludedField)) {
910         return true;
911       }
912     }
913     return false;
914   }
915
916   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
917     for (String excludedField : excludedStrings) {
918       if (className.startsWith(excludedField)) {
919         return true;
920       }
921     }
922     return false;
923   }
924
925   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
926                 // Check if we are reaching the end of our execution: no more backtracking points to explore
927                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
928                 if (!backtrackStateQ.isEmpty()) {
929                         // Set done all the other backtrack points
930                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
931         backtrackTransition.getTransitionCG().setDone();
932                         }
933                         // Reset the next backtrack point with the latest state
934                         int hiStateId = backtrackStateQ.peek();
935                         // Restore the state first if necessary
936                         if (vm.getStateId() != hiStateId) {
937                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
938                                 vm.restoreState(restorableState);
939                         }
940                         // Set the backtrack CG
941                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
942                         setBacktrackCG(hiStateId, backtrackCG);
943                 } else {
944                         // Set done this last CG (we save a few rounds)
945                         icsCG.setDone();
946                 }
947                 // Save all the visited states when starting a new execution of trace
948                 prevVisitedStates.addAll(currVisitedStates);
949                 // This marks a transitional period to the new CG
950                 isEndOfExecution = true;
951   }
952
953   private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
954                                   ReadWriteSet currRWSet) {
955     ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
956     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
957     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
958     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
959     if (!confRWFieldsMap.containsKey(conflictChoice) ||
960             executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
961       return false;
962     }
963     // R/W set of choice/event that may have a potential conflict
964     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
965     // Check for conflicts with Read and Write fields for Write instructions
966     Set<String> currWriteSet = currRWSet.getWriteSet();
967     for(String writeField : currWriteSet) {
968       int currObjId = currRWSet.writeFieldObjectId(writeField);
969       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
970           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
971         // Remove this from the write set as we are tracking per memory location
972         currRWSet.removeWriteField(writeField);
973         return true;
974       }
975     }
976     // Check for conflicts with Write fields for Read instructions
977     Set<String> currReadSet = currRWSet.getReadSet();
978     for(String readField : currReadSet) {
979       int currObjId = currRWSet.readFieldObjectId(readField);
980       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
981         // Remove this from the read set as we are tracking per memory location
982         currRWSet.removeReadField(readField);
983         return true;
984       }
985     }
986     // Return false if no conflict is found
987     return false;
988   }
989
990   private ReadWriteSet getReadWriteSet(int currentChoice) {
991     // Do the analysis to get Read and Write accesses to fields
992     ReadWriteSet rwSet;
993     // We already have an entry
994     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
995     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
996       rwSet = currReadWriteFieldsMap.get(currentChoice);
997     } else { // We need to create a new entry
998       rwSet = new ReadWriteSet();
999       currReadWriteFieldsMap.put(currentChoice, rwSet);
1000     }
1001     return rwSet;
1002   }
1003
1004   private boolean isFieldExcluded(Instruction executedInsn) {
1005     // Get the field info
1006     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1007     // Check if the non-relevant fields set already has it
1008     if (nonRelevantFields.contains(fieldInfo)) {
1009       return true;
1010     }
1011     // Check if the relevant fields set already has it
1012     if (relevantFields.contains(fieldInfo)) {
1013       return false;
1014     }
1015     // Analyze only after being initialized
1016     String field = fieldInfo.getFullName();
1017     // Check against "starts-with", "ends-with", and "contains" list
1018     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1019             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1020             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1021       nonRelevantFields.add(fieldInfo);
1022       return true;
1023     }
1024     relevantFields.add(fieldInfo);
1025     return false;
1026   }
1027
1028   // Check if this trace is already constructed
1029   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1030     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1031     // Check if the trace has been constructed as a backtrack point for this state
1032     // TODO: THIS IS AN OPTIMIZATION!
1033     HashSet<Integer> choiceSet;
1034     if (doneBacktrackMap.containsKey(stateId)) {
1035       choiceSet = doneBacktrackMap.get(stateId);
1036       if (choiceSet.contains(firstChoice)) {
1037         return true;
1038       }
1039     } else {
1040       choiceSet = new HashSet<>();
1041       choiceSet.add(firstChoice);
1042       doneBacktrackMap.put(stateId, choiceSet);
1043     }
1044
1045     return false;
1046   }
1047
1048   // Reset data structure for each new execution
1049   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1050     if (choices == null || choices != icsCG.getAllChoices()) {
1051       // Reset state variables
1052       choiceCounter = 0;
1053       choices = icsCG.getAllChoices();
1054       refChoices = copyChoices(choices);
1055       // Clear data structures
1056       currVisitedStates = new HashSet<>();
1057       stateToEventMap = new HashMap<>();
1058       isEndOfExecution = false;
1059     }
1060   }
1061
1062   // Set a backtrack point for a particular state
1063   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1064     // Set a backtrack CG based on a state ID
1065     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1066     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1067     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1068     backtrackCG.setStateId(stateId);
1069     backtrackCG.reset();
1070     // Update current execution with this new execution
1071     Execution newExecution = new Execution();
1072     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1073     newExecution.addTransition(firstTransition);
1074     // Try to free some memory since this map is only used for the current execution
1075     currentExecution.clearCGToChoiceMap();
1076     currentExecution = newExecution;
1077     // Remove from the queue if we don't have more backtrack points for that state
1078     if (backtrackExecutions.isEmpty()) {
1079       backtrackMap.remove(stateId);
1080       backtrackStateQ.remove(stateId);
1081     }
1082   }
1083
1084   // Update backtrack sets
1085   // 1) recursively, and
1086   // 2) track accesses per memory location (per shared variable/field)
1087   private void updateBacktrackSet(Execution execution, int currentChoice) {
1088     // Copy ReadWriteSet object
1089     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1090     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1091     if (currRWSet == null) {
1092       return;
1093     }
1094     currRWSet = currRWSet.getCopy();
1095     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1096     HashSet<TransitionEvent> visited = new HashSet<>();
1097     // Update backtrack set recursively
1098     // TODO: The following is the call to the original version of the method
1099 //    updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1100     // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1101     updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1102   }
1103
1104 //  TODO: This is the original version of the recursive method
1105 //  private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1106 //                                           Execution conflictExecution, int conflictChoice,
1107 //                                           ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1108 //    // Halt when we have found the first read/write conflicts for all memory locations
1109 //    if (currRWSet.isEmpty()) {
1110 //      return;
1111 //    }
1112 //    TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1113 //    // Halt when we have visited this transition (in a cycle)
1114 //    if (visited.contains(confTrans)) {
1115 //      return;
1116 //    }
1117 //    visited.add(confTrans);
1118 //    // Explore all predecessors
1119 //    for (Predecessor predecessor : confTrans.getPredecessors()) {
1120 //      // Get the predecessor (previous conflict choice)
1121 //      conflictChoice = predecessor.getChoice();
1122 //      conflictExecution = predecessor.getExecution();
1123 //      // Check if a conflict is found
1124 //      if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1125 //        createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1126 //      }
1127 //      // Continue performing DFS if conflict is not found
1128 //      updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1129 //    }
1130 //  }
1131
1132   // TODO: This is the version of the method with pushing up happens-before transitions
1133   private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1134                                            Execution conflictExecution, int conflictChoice,
1135                                            Execution hbExecution, int hbChoice,
1136                                            ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1137     // Halt when we have found the first read/write conflicts for all memory locations
1138     if (currRWSet.isEmpty()) {
1139       return;
1140     }
1141     TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1142     // Halt when we have visited this transition (in a cycle)
1143     if (visited.contains(confTrans)) {
1144       return;
1145     }
1146     visited.add(confTrans);
1147     // Explore all predecessors
1148     for (Predecessor predecessor : confTrans.getPredecessors()) {
1149       // Get the predecessor (previous conflict choice)
1150       conflictChoice = predecessor.getChoice();
1151       conflictExecution = predecessor.getExecution();
1152       // Push up one happens-before transition
1153       int pushedChoice = hbChoice;
1154       Execution pushedExecution = hbExecution;
1155       // Check if a conflict is found
1156       if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1157         createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1158         pushedChoice = conflictChoice;
1159         pushedExecution = conflictExecution;
1160       }
1161       // Continue performing DFS if conflict is not found
1162       updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1163               pushedExecution, pushedChoice, currRWSet, visited);
1164     }
1165     // Remove the transition after being explored
1166     // TODO: Seems to cause a lot of loops---commented out for now
1167     //visited.remove(confTrans);
1168   }
1169
1170   // --- Functions related to the reachability analysis when there is a state match
1171
1172   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1173     // Perform this analysis only when:
1174     // 1) this is not during a switch to a new execution,
1175     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1176     // 3) state > 0 (state 0 is for boolean CG)
1177     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1178       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1179         // Update reachable transitions in the graph with a predecessor
1180         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1181         for(TransitionEvent transition : reachableTransitions) {
1182           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1183         }
1184         updateBacktrackSetsFromPreviousExecution(stateId);
1185       }
1186     }
1187   }
1188
1189   // Update the backtrack sets from previous executions
1190   private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1191     // Collect all the reachable transitions from R-Graph
1192     HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1193     for(TransitionEvent transition : reachableTransitions) {
1194       Execution execution = transition.getExecution();
1195       int currentChoice = transition.getChoiceCounter();
1196       updateBacktrackSet(execution, currentChoice);
1197     }
1198   }
1199 }