12bd44ff802e2547e86e1e22856f32ff6e31c6bf
[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         // Explore the next backtrack point: 
232         // 1) if we have seen this state or this state contains cycles that involve all events, and
233         // 2) after the current CG is advanced at least once
234         if (terminateCurrentExecution() && choiceCounter > 0) {
235           exploreNextBacktrackPoints(vm, icsCG);
236         } else {
237           numOfTransitions++;
238         }
239         // Map state to event
240         mapStateToEvent(icsCG.getNextChoice());
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   }
408
409   private Integer[] copyChoices(Integer[] choicesToCopy) {
410
411     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
412     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
413     return copyOfChoices;
414   }
415
416   // --- Functions related to cycle detection
417
418   // Detect cycles in the current execution/trace
419   // We terminate the execution iff:
420   // (1) the state has been visited in the current execution
421   // (2) the state has one or more cycles that involve all the events
422   // With simple approach we only need to check for a re-visited state.
423   // Basically, we have to check that we have executed all events between two occurrences of such state.
424   private boolean containsCyclesWithAllEvents(int stId) {
425
426     // False if the state ID hasn't been recorded
427     if (!stateToEventMap.containsKey(stId)) {
428       return false;
429     }
430     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
431     // Check if this set contains all the event choices
432     // If not then this is not the terminating condition
433     for(int i=0; i<=maxEventChoice; i++) {
434       if (!visitedEvents.contains(i)) {
435         return false;
436       }
437     }
438     return true;
439   }
440
441   private void initializeStatesVariables() {
442     // DPOR-related
443     choices = null;
444     refChoices = null;
445     choiceCounter = 0;
446     maxEventChoice = 0;
447     // Cycle tracking
448     currVisitedStates = new HashSet<>();
449     justVisitedStates = new HashSet<>();
450     prevVisitedStates = new HashSet<>();
451     stateToEventMap = new HashMap<>();
452     // Backtracking
453     backtrackMap = new HashMap<>();
454     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
455     backtrackPointList = new ArrayList<>();
456     conflictPairMap = new HashMap<>();
457     doneBacktrackSet = new HashSet<>();
458     readWriteFieldsMap = new HashMap<>();
459     stateToChoiceCounterMap = new HashMap<>();
460     // Booleans
461     isEndOfExecution = false;
462   }
463
464   private void mapStateToEvent(int nextChoiceValue) {
465     // Update all states with this event/choice
466     // This means that all past states now see this transition
467     Set<Integer> stateSet = stateToEventMap.keySet();
468     for(Integer stateId : stateSet) {
469       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
470       eventSet.add(nextChoiceValue);
471     }
472   }
473
474   private boolean terminateCurrentExecution() {
475     // We need to check all the states that have just been visited
476     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
477     for(Integer stateId : justVisitedStates) {
478       if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
479         return true;
480       }
481     }
482     return false;
483   }
484
485   private void updateStateInfo(Search search) {
486     // Update the state variables
487     // Line 19 in the paper page 11 (see the heading note above)
488     int stateId = search.getStateId();
489     // Insert state ID into the map if it is new
490     if (!stateToEventMap.containsKey(stateId)) {
491       HashSet<Integer> eventSet = new HashSet<>();
492       stateToEventMap.put(stateId, eventSet);
493     }
494     stateToChoiceCounterMap.put(stateId, choiceCounter);
495     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
496     justVisitedStates.add(stateId);
497     currVisitedStates.add(stateId);
498   }
499
500   // --- Functions related to Read/Write access analysis on shared fields
501
502   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
503     // Insert backtrack point to the right state ID
504     LinkedList<Integer[]> backtrackList;
505     if (backtrackMap.containsKey(stateId)) {
506       backtrackList = backtrackMap.get(stateId);
507     } else {
508       backtrackList = new LinkedList<>();
509       backtrackMap.put(stateId, backtrackList);
510     }
511     backtrackList.addFirst(newChoiceList);
512     // Add to priority queue
513     if (!backtrackStateQ.contains(stateId)) {
514       backtrackStateQ.add(stateId);
515     }
516   }
517
518   // Analyze Read/Write accesses that are directly invoked on fields
519   private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
520     // Do the analysis to get Read and Write accesses to fields
521     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
522     int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
523     // Record the field in the map
524     if (executedInsn instanceof WriteInstruction) {
525       // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
526       for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
527         if (fieldClass.startsWith(str)) {
528           return;
529         }
530       }
531       rwSet.addWriteField(fieldClass, objectId);
532     } else if (executedInsn instanceof ReadInstruction) {
533       rwSet.addReadField(fieldClass, objectId);
534     }
535   }
536
537   // Analyze Read accesses that are indirect (performed through iterators)
538   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
539   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
540     // Get method name
541     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
542     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
543             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
544       // Extract info from the stack frame
545       StackFrame frame = ti.getTopFrame();
546       int[] frameSlots = frame.getSlots();
547       // Get the Groovy callsite library at index 0
548       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
549       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
550         return;
551       }
552       // Get the iterated object whose property is accessed
553       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
554       if (eiAccessObj == null) {
555         return;
556       }
557       // We exclude library classes (they start with java, org, etc.) and some more
558       String objClassName = eiAccessObj.getClassInfo().getName();
559       if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
560           excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
561         return;
562       }
563       // Extract fields from this object and put them into the read write
564       int numOfFields = eiAccessObj.getNumberOfFields();
565       for(int i=0; i<numOfFields; i++) {
566         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
567         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
568           String fieldClass = fieldInfo.getFullName();
569           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
570           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
571           // Record the field in the map
572           rwSet.addReadField(fieldClass, objectId);
573         }
574       }
575     }
576   }
577
578   private int checkAndAdjustChoice(int currentChoice, VM vm) {
579     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
580     // for certain method calls in the infrastructure, e.g., eventSince()
581     int currChoiceInd = currentChoice % refChoices.length;
582     int currChoiceFromCG = currChoiceInd;
583     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
584     // This is the main event CG
585     if (currentCG instanceof IntIntervalGenerator) {
586       // This is the interval CG used in device handlers
587       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
588       // Iterate until we find the IntChoiceFromSet CG
589       while (!(parentCG instanceof IntChoiceFromSet)) {
590         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
591       }
592       int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
593       // Find the index of the event/choice in refChoices
594       for (int i = 0; i<refChoices.length; i++) {
595         if (actualEvtNum == refChoices[i]) {
596           currChoiceFromCG = i;
597           break;
598         }
599       }
600     }
601     if (currChoiceInd != currChoiceFromCG) {
602       currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
603     }
604     return currentChoice;
605   }
606
607   private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
608
609     // Create a new list of choices for backtrack based on the current choice and conflicting event number
610     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
611     // for the original set {0, 1, 2, 3}
612     Integer[] newChoiceList = new Integer[refChoices.length];
613     // Put the conflicting event numbers first and reverse the order
614     int actualCurrCho = currentChoice % refChoices.length;
615     // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
616     newChoiceList[0] = choices[actualCurrCho];
617     newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
618     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
619     for (int i = 0, j = 2; i < refChoices.length; i++) {
620       if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
621         newChoiceList[j] = refChoices[i];
622         j++;
623       }
624     }
625     // Get the backtrack CG for this backtrack point
626     int stateId = backtrackPointList.get(confEvtNum).getStateId();
627     // Check if this trace has been done starting from this state
628     if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
629       return;
630     }
631     addNewBacktrackPoint(stateId, newChoiceList);
632   }
633
634   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
635     for (String excludedField : excludedStrings) {
636       if (className.contains(excludedField)) {
637         return true;
638       }
639     }
640     return false;
641   }
642
643   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
644     for (String excludedField : excludedStrings) {
645       if (className.endsWith(excludedField)) {
646         return true;
647       }
648     }
649     return false;
650   }
651
652   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
653     for (String excludedField : excludedStrings) {
654       if (className.startsWith(excludedField)) {
655         return true;
656       }
657     }
658     return false;
659   }
660
661   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
662
663                 // Check if we are reaching the end of our execution: no more backtracking points to explore
664                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
665                 if (!backtrackStateQ.isEmpty()) {
666                         // Set done all the other backtrack points
667                         for (BacktrackPoint backtrackPoint : backtrackPointList) {
668                                 backtrackPoint.getBacktrackCG().setDone();
669                         }
670                         // Reset the next backtrack point with the latest state
671                         int hiStateId = backtrackStateQ.peek();
672                         // Restore the state first if necessary
673                         if (vm.getStateId() != hiStateId) {
674                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
675                                 vm.restoreState(restorableState);
676                         }
677                         // Set the backtrack CG
678                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
679                         setBacktrackCG(hiStateId, backtrackCG);
680                 } else {
681                         // Set done this last CG (we save a few rounds)
682                         icsCG.setDone();
683                 }
684                 // Save all the visited states when starting a new execution of trace
685                 prevVisitedStates.addAll(currVisitedStates);
686                 currVisitedStates.clear();
687                 // This marks a transitional period to the new CG
688                 isEndOfExecution = true;
689   }
690
691   private ReadWriteSet getReadWriteSet(int currentChoice) {
692     // Do the analysis to get Read and Write accesses to fields
693     ReadWriteSet rwSet;
694     // We already have an entry
695     if (readWriteFieldsMap.containsKey(currentChoice)) {
696       rwSet = readWriteFieldsMap.get(currentChoice);
697     } else { // We need to create a new entry
698       rwSet = new ReadWriteSet();
699       readWriteFieldsMap.put(currentChoice, rwSet);
700     }
701     return rwSet;
702   }
703
704   private boolean isConflictFound(int eventCounter, int currentChoice) {
705
706     int actualCurrCho = currentChoice % refChoices.length;
707     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
708     if (!readWriteFieldsMap.containsKey(eventCounter) ||
709             choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
710       return false;
711     }
712     // Current R/W set
713     ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
714     // R/W set of choice/event that may have a potential conflict
715     ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
716     // Check for conflicts with Read and Write fields for Write instructions
717     Set<String> currWriteSet = currRWSet.getWriteSet();
718     for(String writeField : currWriteSet) {
719       int currObjId = currRWSet.writeFieldObjectId(writeField);
720       if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
721           (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
722         return true;
723       }
724     }
725     // Check for conflicts with Write fields for Read instructions
726     Set<String> currReadSet = currRWSet.getReadSet();
727     for(String readField : currReadSet) {
728       int currObjId = currRWSet.readFieldObjectId(readField);
729       if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
730         return true;
731       }
732     }
733     // Return false if no conflict is found
734     return false;
735   }
736
737   private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
738
739     int actualCurrCho = currentChoice % refChoices.length;
740     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
741     if (!readWriteFieldsMap.containsKey(eventCounter) ||
742          choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
743       return false;
744     }
745     ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
746     int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
747     // Check for conflicts with Write fields for both Read and Write instructions
748     if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
749           rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
750          (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
751           rwSet.readFieldObjectId(fieldClass) == currObjId)) {
752       return true;
753     }
754     return false;
755   }
756
757   private boolean isFieldExcluded(String field) {
758     // Check against "starts-with", "ends-with", and "contains" list
759     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
760             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
761             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
762       return true;
763     }
764
765     return false;
766   }
767
768   private boolean isNewConflict(int currentEvent, int eventNumber) {
769     HashSet<Integer> conflictSet;
770     if (!conflictPairMap.containsKey(currentEvent)) {
771       conflictSet = new HashSet<>();
772       conflictPairMap.put(currentEvent, conflictSet);
773     } else {
774       conflictSet = conflictPairMap.get(currentEvent);
775     }
776     // If this conflict has been recorded before, we return false because
777     // we don't want to save this backtrack point twice
778     if (conflictSet.contains(eventNumber)) {
779       return false;
780     }
781     // If it hasn't been recorded, then do otherwise
782     conflictSet.add(eventNumber);
783     return true;
784   }
785
786   private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
787     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
788     // TODO: THIS IS AN OPTIMIZATION!
789     // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
790     // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
791     // The second time this event 1 is explored, it will generate the same state as the first one
792     StringBuilder sb = new StringBuilder();
793     sb.append(stateId);
794     sb.append(':');
795     sb.append(choiceList[0]);
796     // Check if the trace has been constructed as a backtrack point for this state
797     if (doneBacktrackSet.contains(sb.toString())) {
798       return true;
799     }
800     doneBacktrackSet.add(sb.toString());
801     return false;
802   }
803
804   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
805     if (choices == null || choices != icsCG.getAllChoices()) {
806       // Reset state variables
807       choiceCounter = 0;
808       choices = icsCG.getAllChoices();
809       refChoices = copyChoices(choices);
810       // Clearing data structures
811       conflictPairMap.clear();
812       readWriteFieldsMap.clear();
813       stateToEventMap.clear();
814       isEndOfExecution = false;
815       backtrackPointList.clear();
816     }
817   }
818
819   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
820     // Set a backtrack CG based on a state ID
821     LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
822     backtrackCG.setNewValues(backtrackChoices.removeLast());  // Get the last from the queue
823     backtrackCG.setStateId(stateId);
824     backtrackCG.reset();
825     // Remove from the queue if we don't have more backtrack points for that state
826     if (backtrackChoices.isEmpty()) {
827       backtrackMap.remove(stateId);
828       backtrackStateQ.remove(stateId);
829     }
830   }
831
832   // --- Functions related to the reachability analysis when there is a state match
833
834   // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
835   // 1) Whenever there is state match, there is a cycle of events
836   // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
837   // 3) Then we create a new backtrack point for every new conflict
838   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
839     // Perform this analysis only when:
840     // 1) there is a state match,
841     // 2) this is not during a switch to a new execution,
842     // 3) at least 2 choices/events have been explored (choiceCounter > 1),
843     // 4) the matched state has been encountered in the current execution, and
844     // 5) state > 0 (state 0 is for boolean CG)
845     if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 &&
846             currVisitedStates.contains(stateId) && (stateId > 0)) {
847       // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
848       int conflictChoice = stateToChoiceCounterMap.get(stateId);
849       int currentChoice = choiceCounter - 1;
850       // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
851       while (conflictChoice < currentChoice) {
852         for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
853           if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
854             createBacktrackingPoint(conflictChoice, eventCounter);
855           }
856         }
857         conflictChoice++;
858       }
859     }
860   }
861 }