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