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