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