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