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