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