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