72fc44e6c67f8ec4a48cfa8dd141a2ab043c33c3
[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;
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<IntChoiceFromSet> cgList;                         // Record CGs for backtracking points
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           cgList.add(icsCG);
192         } else {
193           // Set done all CGs while transitioning to a new execution
194           icsCG.setDone();
195         }
196       }
197     }
198   }
199
200   @Override
201   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
202
203     if (stateReductionMode) {
204       // Check the boolean CG and if it is flipped, we are resetting the analysis
205       if (currentCG instanceof BooleanChoiceGenerator) {
206         if (!isBooleanCGFlipped) {
207           isBooleanCGFlipped = true;
208         } else {
209           // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
210           initializeStatesVariables();
211         }
212       }
213       // Check every choice generated and ensure fair scheduling!
214       if (currentCG instanceof IntChoiceFromSet) {
215         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
216         // If this is a new CG then we need to update data structures
217         resetStatesForNewExecution(icsCG);
218         // If we don't see a fair scheduling of events/choices then we have to enforce it
219         checkAndEnforceFairScheduling(icsCG);
220         // Map state to event
221         mapStateToEvent(icsCG.getNextChoice());
222         // Update the VOD graph always with the latest
223         updateVODGraph(icsCG.getNextChoice());
224         // Check if we have seen this state or this state contains cycles that involve all events
225         if (terminateCurrentExecution()) {
226           exploreNextBacktrackPoints(icsCG, vm);
227         }
228         justVisitedStates.clear();
229         choiceCounter++;
230       }
231     }
232   }
233
234   @Override
235   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
236     if (stateReductionMode) {
237       if (!isEndOfExecution) {
238         // Has to be initialized and a integer CG
239         ChoiceGenerator<?> cg = vm.getChoiceGenerator();
240         if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
241           int currentChoice = choiceCounter - 1;  // Accumulative choice w.r.t the current trace
242           if (currentChoice < 0) { // If choice is -1 then skip
243             return;
244           }
245           currentChoice = checkAndAdjustChoice(currentChoice, vm);
246           // Record accesses from executed instructions
247           if (executedInsn instanceof JVMFieldInstruction) {
248             // Analyze only after being initialized
249             String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
250             // We don't care about libraries
251             if (!isFieldExcluded(fieldClass)) {
252               analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
253             }
254           } else if (executedInsn instanceof INVOKEINTERFACE) {
255             // Handle the read/write accesses that occur through iterators
256             analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
257           }
258           // Analyze conflicts from next instructions
259           if (nextInsn instanceof JVMFieldInstruction) {
260             // Skip the constructor because it is called once and does not have shared access with other objects
261             if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
262               String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
263               if (!isFieldExcluded(fieldClass)) {
264                 // Check for conflict (go backward from current choice and get the first conflict)
265                 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
266                   // Check for conflicts with Write fields for both Read and Write instructions
267                   // Check and record a backtrack set for just once!
268                   if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
269                       isNewConflict(currentChoice, eventCounter)) {
270                     // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
271                     if (vm.isNewState() || isReachableInVODGraph(currentChoice)) {
272                       createBacktrackingPoint(currentChoice, eventCounter);
273                     }
274                   }
275                 }
276               }
277             }
278           }
279         }
280       }
281     }
282   }
283
284
285   // == HELPERS
286
287   // -- INNER CLASSES
288
289   // This class compactly stores Read and Write field sets
290   // We store the field name and its object ID
291   // Sharing the same field means the same field name and object ID
292   private class ReadWriteSet {
293     private HashMap<String, Integer> readSet;
294     private HashMap<String, Integer> writeSet;
295
296     public ReadWriteSet() {
297       readSet = new HashMap<>();
298       writeSet = new HashMap<>();
299     }
300
301     public void addReadField(String field, int objectId) {
302       readSet.put(field, objectId);
303     }
304
305     public void addWriteField(String field, int objectId) {
306       writeSet.put(field, objectId);
307     }
308
309     public boolean readFieldExists(String field) {
310       return readSet.containsKey(field);
311     }
312
313     public boolean writeFieldExists(String field) {
314       return writeSet.containsKey(field);
315     }
316
317     public int readFieldObjectId(String field) {
318       return readSet.get(field);
319     }
320
321     public int writeFieldObjectId(String field) {
322       return writeSet.get(field);
323     }
324   }
325
326   // This class compactly stores backtracking points: 1) backtracking ChoiceGenerator, and 2) backtracking choices
327   private class BacktrackPoint {
328     private IntChoiceFromSet backtrackCG; // CG to backtrack from
329     private Integer[] backtrackChoices;   // Choices to set for this backtrack CG
330
331     public BacktrackPoint(IntChoiceFromSet cg, Integer[] choices) {
332       backtrackCG = cg;
333       backtrackChoices = choices;
334     }
335
336     public IntChoiceFromSet getBacktrackCG() {
337       return backtrackCG;
338     }
339
340     public Integer[] getBacktrackChoices() {
341       return backtrackChoices;
342     }
343   }
344
345   // -- CONSTANTS
346   private final static String DO_CALL_METHOD = "doCall";
347   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
348   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
349   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
350           // Groovy library created fields
351           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
352           // Infrastructure
353           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
354           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
355   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
356           // Java and Groovy libraries
357           { "java", "org", "sun", "com", "gov", "groovy"};
358   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
359   private final static String GET_PROPERTY_METHOD =
360           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
361   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
362   private final static String JAVA_INTEGER = "int";
363   private final static String JAVA_STRING_LIB = "java.lang.String";
364
365   // -- FUNCTIONS
366   private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
367     // Check the next choice and if the value is not the same as the expected then force the expected value
368     int choiceIndex = choiceCounter % refChoices.length;
369     int nextChoice = icsCG.getNextChoice();
370     if (refChoices[choiceIndex] != nextChoice) {
371       int expectedChoice = refChoices[choiceIndex];
372       int currCGIndex = icsCG.getNextChoiceIndex();
373       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
374         icsCG.setChoice(currCGIndex, expectedChoice);
375       }
376     }
377   }
378
379   private Integer[] copyChoices(Integer[] choicesToCopy) {
380
381     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
382     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
383     return copyOfChoices;
384   }
385
386   // --- Functions related to cycle detection
387
388   // Detect cycles in the current execution/trace
389   // We terminate the execution iff:
390   // (1) the state has been visited in the current execution
391   // (2) the state has one or more cycles that involve all the events
392   // With simple approach we only need to check for a re-visited state.
393   // Basically, we have to check that we have executed all events between two occurrences of such state.
394   private boolean containsCyclesWithAllEvents(int stId) {
395
396     // False if the state ID hasn't been recorded
397     if (!stateToEventMap.containsKey(stId)) {
398       return false;
399     }
400     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
401     // Check if this set contains all the event choices
402     // If not then this is not the terminating condition
403     for(int i=0; i<=maxEventChoice; i++) {
404       if (!visitedEvents.contains(i)) {
405         return false;
406       }
407     }
408     return true;
409   }
410
411   private void initializeStatesVariables() {
412     // DPOR-related
413     choices = null;
414     refChoices = null;
415     choiceCounter = 0;
416     lastCGStateId = 0;
417     maxEventChoice = 0;
418     // Cycle tracking
419     currVisitedStates = new HashSet<>();
420     justVisitedStates = new HashSet<>();
421     prevVisitedStates = new HashSet<>();
422     stateToEventMap = new HashMap<>();
423     // Backtracking
424     backtrackMap = new HashMap<>();
425     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
426     cgList = new ArrayList<>();
427     cgMap = new HashMap<>();
428     conflictPairMap = new HashMap<>();
429     doneBacktrackSet = new HashSet<>();
430     readWriteFieldsMap = new HashMap<>();
431     // VOD graph
432     prevChoiceValue = -1;
433     vodGraphMap = new HashMap<>();
434     // Booleans
435     isEndOfExecution = false;
436     isFirstResetDone = 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   }
472
473   // --- Functions related to Read/Write access analysis on shared fields
474
475   private void addNewBacktrackPoint(IntChoiceFromSet backtrackCG, Integer[] newChoiceList) {
476     int stateId = backtrackCG.getStateId();
477     // Insert backtrack point to the right state ID
478     LinkedList<Integer[]> backtrackList;
479     if (backtrackMap.containsKey(stateId)) {
480       backtrackList = backtrackMap.get(stateId);
481     } else {
482       backtrackList = new LinkedList<>();
483       backtrackMap.put(stateId, backtrackList);
484     }
485     backtrackList.addFirst(newChoiceList);
486     // Add CG for this state ID if there isn't one yet
487     if (!cgMap.containsKey(stateId)) {
488       cgMap.put(stateId, backtrackCG);
489     }
490     // Add to priority queue
491     if (!backtrackStateQ.contains(stateId)) {
492       backtrackStateQ.add(stateId);
493     }
494   }
495
496   // Analyze Read/Write accesses that are directly invoked on fields
497   private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
498     // Do the analysis to get Read and Write accesses to fields
499     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
500     int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
501     // Record the field in the map
502     if (executedInsn instanceof WriteInstruction) {
503       // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
504       for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
505         if (fieldClass.startsWith(str)) {
506           return;
507         }
508       }
509       rwSet.addWriteField(fieldClass, objectId);
510     } else if (executedInsn instanceof ReadInstruction) {
511       rwSet.addReadField(fieldClass, objectId);
512     }
513   }
514
515   // Analyze Read accesses that are indirect (performed through iterators)
516   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
517   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
518     // Get method name
519     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
520     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
521             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
522       // Extract info from the stack frame
523       StackFrame frame = ti.getTopFrame();
524       int[] frameSlots = frame.getSlots();
525       // Get the Groovy callsite library at index 0
526       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
527       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
528         return;
529       }
530       // Get the iterated object whose property is accessed
531       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
532       if (eiAccessObj == null) {
533         return;
534       }
535       // We exclude library classes (they start with java, org, etc.) and some more
536       String objClassName = eiAccessObj.getClassInfo().getName();
537       if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
538           excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
539         return;
540       }
541       // Extract fields from this object and put them into the read write
542       int numOfFields = eiAccessObj.getNumberOfFields();
543       for(int i=0; i<numOfFields; i++) {
544         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
545         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
546           String fieldClass = fieldInfo.getFullName();
547           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
548           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
549           // Record the field in the map
550           rwSet.addReadField(fieldClass, objectId);
551         }
552       }
553     }
554   }
555
556   private int checkAndAdjustChoice(int currentChoice, VM vm) {
557     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
558     // for certain method calls in the infrastructure, e.g., eventSince()
559     int currChoiceInd = currentChoice % refChoices.length;
560     int currChoiceFromCG = getCurrentChoice(vm);
561     if (currChoiceInd != currChoiceFromCG) {
562       currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
563     }
564     return currentChoice;
565   }
566
567   private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
568
569     // Create a new list of choices for backtrack based on the current choice and conflicting event number
570     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
571     // for the original set {0, 1, 2, 3}
572     Integer[] newChoiceList = new Integer[refChoices.length];
573     // Put the conflicting event numbers first and reverse the order
574     int actualCurrCho = currentChoice % refChoices.length;
575     int actualConfEvtNum = confEvtNum % refChoices.length;
576     // We use the actual choices here in case they have been modified/adjusted
577     newChoiceList[0] = choices[actualCurrCho];
578     newChoiceList[1] = choices[actualConfEvtNum];
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     // Record the backtracking point in the stack as well
587     IntChoiceFromSet backtrackCG = cgList.get(confEvtNum);
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 CG for this execution
741                         cgList.add(icsCG);
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(IntChoiceFromSet cg : cgList) {
783       if (!backtrackCGs.contains(cg)) {
784         cg.setDone();
785       }
786     }
787     cgList.clear();
788   }
789
790   // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
791
792   // This method checks whether a choice is reachable in the VOD graph from a reference choice (BFS algorithm)
793   //private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
794   private boolean isReachableInVODGraph(int currentChoice) {
795     // Extract previous and current events
796     int choiceIndex = currentChoice % refChoices.length;
797     int currEvent = refChoices[choiceIndex];
798     int prevEvent = refChoices[choiceIndex - 1];
799     // Record visited choices as we search in the graph
800     HashSet<Integer> visitedChoice = new HashSet<>();
801     visitedChoice.add(prevEvent);
802     LinkedList<Integer> nodesToVisit = new LinkedList<>();
803     // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
804     // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
805     if (vodGraphMap.containsKey(prevEvent)) {
806       nodesToVisit.addAll(vodGraphMap.get(prevEvent));
807       while(!nodesToVisit.isEmpty()) {
808         int choice = nodesToVisit.getFirst();
809         if (choice == currEvent) {
810           return true;
811         }
812         if (visitedChoice.contains(choice)) { // If there is a loop then we don't find it
813           return false;
814         }
815         // Continue searching
816         visitedChoice.add(choice);
817         HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
818         if (choiceNextNodes != null) {
819           // Add only if there is a mapping for next nodes
820           for (Integer nextNode : choiceNextNodes) {
821             // Skip cycles
822             if (nextNode == choice) {
823               continue;
824             }
825             nodesToVisit.addLast(nextNode);
826           }
827         }
828       }
829     }
830     return false;
831   }
832
833   private void updateVODGraph(int currChoiceValue) {
834     // Update the graph when we have the current choice value
835     HashSet<Integer> choiceSet;
836     if (vodGraphMap.containsKey(prevChoiceValue)) {
837       // If the key already exists, just retrieve it
838       choiceSet = vodGraphMap.get(prevChoiceValue);
839     } else {
840       // Create a new entry
841       choiceSet = new HashSet<>();
842       vodGraphMap.put(prevChoiceValue, choiceSet);
843     }
844     choiceSet.add(currChoiceValue);
845     prevChoiceValue = currChoiceValue;
846   }
847 }