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