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