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