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