Adding graph traversal to find cycles; adding debug mode for ConflictTracker.
[jpf-core.git] / src / main / gov / nasa / jpf / listener / StateReducer.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
30 import java.io.PrintWriter;
31
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 StateReducer extends ListenerAdapter {
50
51   // Debug info fields
52   private boolean debugMode;
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   // State reduction fields
61   private Integer[] choices;
62   private IntChoiceFromSet currCG;
63   private int choiceCounter;
64   private Integer choiceUpperBound;
65   private Integer maxUpperBound;
66   private boolean isInitialized;
67   private boolean isResetAfterAnalysis;
68   private boolean isBooleanCGFlipped;
69   private HashMap<IntChoiceFromSet, Integer> cgMap;
70   // Record the mapping between event number and field accesses (Read and Write)
71   private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;
72   // The following is the backtrack map (set) that stores all the backtrack information
73   // e.g., event number 1 can have two backtrack sequences: {3,1,2,4,...} and {2,1,3,4,...}
74   private HashMap<Integer, LinkedList<Integer[]>> backtrackMap;
75   // Stores explored backtrack lists in the form of HashSet of Strings
76   private HashSet<String> backtrackSet;
77   private HashMap<Integer, HashSet<Integer>> conflictPairMap;
78
79   // Map that represents graph G
80   // (i.e., visible operation dependency graph (VOD Graph)
81   private HashMap<Integer, HashSet<Integer>> vodGraphMap;
82   // Set that represents hash table H
83   // (i.e., hash table that records encountered states)
84   // VOD graph is updated when the state has not yet been seen
85   // Current state
86   private int stateId;
87   // Previous choice number
88   private int prevChoiceValue;
89   // HashSet that stores references to unused CGs
90   private HashSet<IntChoiceFromSet> unusedCG;
91
92   // Reference to the state graph in the ConflictTracker class
93   private HashMap<Integer, ConflictTracker.Node> stateGraph;
94   // Visited states in the previous and current executions/traces for terminating condition
95   private HashSet<Integer> prevVisitedStates;
96   private HashSet<Integer> currVisitedStates;
97
98   public StateReducer(Config config, JPF jpf) {
99     debugMode = config.getBoolean("debug_state_transition", false);
100     stateReductionMode = config.getBoolean("activate_state_reduction", true);
101     if (debugMode) {
102       out = new PrintWriter(System.out, true);
103     } else {
104       out = null;
105     }
106     detail = null;
107     depth = 0;
108     id = 0;
109     transition = null;
110     isBooleanCGFlipped = false;
111     vodGraphMap = new HashMap<>();
112     stateId = -1;
113     prevChoiceValue = -1;
114     cgMap = new HashMap<>();
115     readWriteFieldsMap = new HashMap<>();
116     backtrackMap = new HashMap<>();
117     backtrackSet = new HashSet<>();
118     conflictPairMap = new HashMap<>();
119     unusedCG = new HashSet<>();
120     // TODO: We are assuming that the StateReducer is always used together with the ConflictTracker
121     stateGraph = ConflictTracker.nodes;
122     prevVisitedStates = new HashSet<>();
123     currVisitedStates = new HashSet<>();
124     initializeStateReduction();
125   }
126
127   private void initializeStateReduction() {
128     if (stateReductionMode) {
129       choices = null;
130       currCG = null;
131       choiceCounter = 0;
132       choiceUpperBound = 0;
133       maxUpperBound = 0;
134       isInitialized = false;
135       isResetAfterAnalysis = false;
136       cgMap.clear();
137       readWriteFieldsMap.clear();
138       backtrackMap.clear();
139       backtrackSet.clear();
140       conflictPairMap.clear();
141     }
142   }
143
144   @Override
145   public void stateRestored(Search search) {
146     if (debugMode) {
147       id = search.getStateId();
148       depth = search.getDepth();
149       transition = search.getTransition();
150       detail = null;
151       out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
152               " and depth: " + depth + "\n");
153     }
154   }
155
156   //--- the ones we are interested in
157   @Override
158   public void searchStarted(Search search) {
159     if (debugMode) {
160       out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
161     }
162   }
163
164   @Override
165   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
166     if (stateReductionMode) {
167       // Initialize with necessary information from the CG
168       if (nextCG instanceof IntChoiceFromSet) {
169         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
170         // Check if CG has been initialized, otherwise initialize it
171         Integer[] cgChoices = icsCG.getAllChoices();
172         if (!isInitialized) {
173           // Get the upper bound from the last element of the choices
174           choiceUpperBound = cgChoices[cgChoices.length - 1];
175           isInitialized = true;
176         }
177         // Record the subsequent Integer CGs only until we hit the upper bound
178         if (!isResetAfterAnalysis) {
179           if (choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
180             // Update the choices of the first CG and add '-1'
181             if (choices == null) {
182               // Initialize backtrack set that stores all the explored backtrack lists
183               maxUpperBound = cgChoices.length;
184               // All the choices are always the same so we only need to update it once
185               choices = new Integer[cgChoices.length + 1];
186               System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
187               choices[choices.length - 1] = -1;
188               String firstChoiceListString = buildStringFromChoiceList(choices);
189               backtrackSet.add(firstChoiceListString);
190             }
191             icsCG.setNewValues(choices);
192             icsCG.reset();
193             // Advance the current Integer CG
194             // This way we explore all the event numbers in the first pass
195             icsCG.advance(choices[choiceCounter]);
196             cgMap.put(icsCG, choices[choiceCounter]);
197           } else {
198             // We repeat the same trace if a state match is not found yet
199             icsCG.setNewValues(choices);
200             icsCG.reset();
201             // Use a modulo since choiceCounter is going to keep increasing
202             int choiceIndex = choiceCounter % (choices.length - 1);
203             icsCG.advance(choices[choiceIndex]);
204             unusedCG.add(icsCG);
205           }
206           choiceCounter++;
207         } else {
208           // Set new CGs to done so that the search algorithm explores the existing CGs
209           icsCG.setDone();
210         }
211       }
212     }
213   }
214
215   private void resetAllCGs() {
216     // Extract the event numbers that have backtrack lists
217     Set<Integer> eventSet = backtrackMap.keySet();
218     // Return if there is no conflict at all (highly unlikely)
219     if (eventSet.isEmpty()) {
220       // Set every CG to done!
221       for (IntChoiceFromSet cg : cgMap.keySet()) {
222         cg.setDone();
223       }
224       return;
225     }
226     // Reset every CG with the first backtrack lists
227     for (IntChoiceFromSet cg : cgMap.keySet()) {
228       int event = cgMap.get(cg);
229       LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
230       if (choiceLists != null && choiceLists.peekFirst() != null) {
231         Integer[] choiceList = choiceLists.removeFirst();
232         // Deploy the new choice list for this CG
233         cg.setNewValues(choiceList);
234         cg.reset();
235       } else {
236         cg.setDone();
237       }
238     }
239     // Set done every CG in the unused CG set
240     for (IntChoiceFromSet cg : unusedCG) {
241       cg.setDone();
242     }
243     unusedCG.clear();
244   }
245
246   // Detect cycles in the current execution/trace
247   // We terminate the execution iff:
248   // (1) the state has been visited in the current execution
249   // (2) the state has one or more cycles that involve all the events
250   private boolean containsCyclesWithAllEvents(int stId) {
251
252     HashSet<Integer> visitedEvents = new HashSet<>();
253     boolean containsCyclesWithAllEvts = false;
254     ConflictTracker.Node currNode = stateGraph.get(stId);
255     for(ConflictTracker.Edge edge : currNode.getOutEdges()) {
256       dfsFindCycles(edge.getDst(), visitedEvents, new HashSet<>());
257     }
258     if (checkIfAllEventsInvolved(visitedEvents)) {
259       containsCyclesWithAllEvts = true;
260     }
261
262     return containsCyclesWithAllEvts;
263   }
264
265   private void dfsFindCycles(ConflictTracker.Node currNode, HashSet<Integer> visitedEvents,
266                              HashSet<Integer> visitingEvents) {
267
268     // Stop when there is a cycle and record all the events
269     if (visitingEvents.contains(currNode.getId())) {
270       visitedEvents.addAll(visitingEvents);
271     } else {
272       for(ConflictTracker.Edge edge : currNode.getOutEdges()) {
273         visitingEvents.add(edge.getEventNumber());
274         dfsFindCycles(edge.getDst(), visitedEvents, visitingEvents);
275         visitingEvents.remove(edge.getEventNumber());
276       }
277     }
278   }
279
280   private boolean checkIfAllEventsInvolved(HashSet<Integer> visitedEvents) {
281
282     // Check if this set contains all the event choices
283     // If not then this is not the terminating condition
284     for(int i=0; i<=choiceUpperBound; i++) {
285       if (!visitedEvents.contains(i)) {
286         return false;
287       }
288     }
289     return true;
290   }
291
292   @Override
293   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
294
295     if (stateReductionMode) {
296       // Check the boolean CG and if it is flipped, we are resetting the analysis
297       if (currentCG instanceof BooleanChoiceGenerator) {
298         if (!isBooleanCGFlipped) {
299           isBooleanCGFlipped = true;
300         } else {
301           initializeStateReduction();
302         }
303       }
304       // Check every choice generated and make sure that all the available choices
305       // are chosen first before repeating the same choice of value twice!
306       if (currentCG instanceof IntChoiceFromSet) {
307         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
308         // Update the current pointer to the current set of choices
309         if (choices == null || choices != icsCG.getAllChoices()) {
310           currCG = icsCG;
311           choices = icsCG.getAllChoices();
312           // Reset a few things for the sub-graph
313           conflictPairMap.clear();
314           readWriteFieldsMap.clear();
315           choiceCounter = 0;
316         }
317         // Check if we have seen this state or this state contains cycles that involve all events
318 //        if (prevStateId != -1 && stateId != prevStateId && isVisitedMultipleTimes(stateId)) {
319         if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
320           // Traverse the sub-graphs
321           if (isResetAfterAnalysis) {
322             // Advance choice counter for sub-graphs
323             choiceCounter++;
324             // Do this for every CG after finishing each backtrack list
325             // We try to update the CG with a backtrack list if the state has been visited multiple times
326             if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
327               int event = cgMap.get(icsCG);
328               LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
329               if (choiceLists != null && choiceLists.peekFirst() != null) {
330                 Integer[] choiceList = choiceLists.removeFirst();
331                 // Deploy the new choice list for this CG
332                 icsCG.setNewValues(choiceList);
333                 icsCG.reset();
334               } else {
335                 // Set done if this was the last backtrack list
336                 icsCG.setDone();
337               }
338             }
339           } else {
340             // Update and reset the CG if needed (do this for the first time after the analysis)
341             // Start backtracking if this is a visited state and it is not a repeating state
342             resetAllCGs();
343             isResetAfterAnalysis = true;
344           }
345           // Save all the visited states
346           prevVisitedStates.addAll(currVisitedStates);
347         }
348       }
349     }
350   }
351
352   private void updateVODGraph(int prevChoice, int currChoice) {
353
354     HashSet<Integer> choiceSet;
355     if (vodGraphMap.containsKey(prevChoice)) {
356       // If the key already exists, just retrieve it
357       choiceSet = vodGraphMap.get(prevChoice);
358     } else {
359       // Create a new entry
360       choiceSet = new HashSet<>();
361       vodGraphMap.put(prevChoice, choiceSet);
362     }
363     choiceSet.add(currChoice);
364   }
365
366   @Override
367   public void stateAdvanced(Search search) {
368     if (debugMode) {
369       id = search.getStateId();
370       depth = search.getDepth();
371       transition = search.getTransition();
372       if (search.isNewState()) {
373         detail = "new";
374       } else {
375         detail = "visited";
376       }
377
378       if (search.isEndState()) {
379         out.println("\n==> DEBUG: This is the last state!\n");
380         detail += " end";
381       }
382       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
383               " which is " + detail + " Transition: " + transition + "\n");
384     }
385     if (stateReductionMode) {
386       // Update vodGraph
387       int currChoice = choiceCounter - 1;
388       // Adjust currChoice with modulo
389       currChoice = currChoice >= 0 ? currChoice % (choices.length -1) : currChoice;
390       if (currChoice < 0 || choices[currChoice] == -1 ||
391               prevChoiceValue == choices[currChoice]) {
392         // When current choice is 0, previous choice could be -1
393 //        updateVODGraph(prevChoiceValue, choices[currChoice]);
394         // Update the state ID variables
395         stateId = search.getStateId();
396         currVisitedStates.add(stateId);
397         return;
398       }
399       // When current choice is 0, previous choice could be -1
400       updateVODGraph(prevChoiceValue, choices[currChoice]);
401       // Current choice becomes previous choice in the next iteration
402       prevChoiceValue = choices[currChoice];
403       // Update the state ID variables
404       stateId = search.getStateId();
405       currVisitedStates.add(stateId);
406     }
407   }
408
409   @Override
410   public void stateBacktracked(Search search) {
411     if (debugMode) {
412       id = search.getStateId();
413       depth = search.getDepth();
414       transition = search.getTransition();
415       detail = null;
416
417       // Update the state variables
418       // Line 19 in the paper page 11 (see the heading note above)
419       stateId = search.getStateId();
420
421       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
422               " and depth: " + depth + "\n");
423     }
424   }
425
426   @Override
427   public void searchFinished(Search search) {
428     if (debugMode) {
429       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
430     }
431   }
432
433   // This class compactly stores Read and Write field sets
434   // We store the field name and its object ID
435   // Sharing the same field means the same field name and object ID
436   private class ReadWriteSet {
437     private HashMap<String, Integer> readSet;
438     private HashMap<String, Integer> writeSet;
439
440     public ReadWriteSet() {
441       readSet = new HashMap<>();
442       writeSet = new HashMap<>();
443     }
444
445     public void addReadField(String field, int objectId) {
446       readSet.put(field, objectId);
447     }
448
449     public void addWriteField(String field, int objectId) {
450       writeSet.put(field, objectId);
451     }
452
453     public boolean readFieldExists(String field) {
454       return readSet.containsKey(field);
455     }
456
457     public boolean writeFieldExists(String field) {
458       return writeSet.containsKey(field);
459     }
460
461     public int readFieldObjectId(String field) {
462       return readSet.get(field);
463     }
464
465     public int writeFieldObjectId(String field) {
466       return writeSet.get(field);
467     }
468   }
469
470   private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
471     // Do the analysis to get Read and Write accesses to fields
472     ReadWriteSet rwSet;
473     // We already have an entry
474     if (readWriteFieldsMap.containsKey(choices[currentChoice])) {
475       rwSet = readWriteFieldsMap.get(choices[currentChoice]);
476     } else { // We need to create a new entry
477       rwSet = new ReadWriteSet();
478       readWriteFieldsMap.put(choices[currentChoice], rwSet);
479     }
480     int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
481     // Record the field in the map
482     if (executedInsn instanceof WriteInstruction) {
483       // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
484       for (String str : EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
485         if (fieldClass.startsWith(str)) {
486           return;
487         }
488       }
489       rwSet.addWriteField(fieldClass, objectId);
490     } else if (executedInsn instanceof ReadInstruction) {
491       rwSet.addReadField(fieldClass, objectId);
492     }
493   }
494
495   private boolean recordConflictPair(int currentEvent, int eventNumber) {
496     HashSet<Integer> conflictSet;
497     if (!conflictPairMap.containsKey(currentEvent)) {
498       conflictSet = new HashSet<>();
499       conflictPairMap.put(currentEvent, conflictSet);
500     } else {
501       conflictSet = conflictPairMap.get(currentEvent);
502     }
503     // If this conflict has been recorded before, we return false because
504     // we don't want to service this backtrack point twice
505     if (conflictSet.contains(eventNumber)) {
506       return false;
507     }
508     // If it hasn't been recorded, then do otherwise
509     conflictSet.add(eventNumber);
510     return true;
511   }
512
513   private String buildStringFromChoiceList(Integer[] newChoiceList) {
514
515     // When we see a choice list shorter than the upper bound, e.g., [3,2] for choices 0,1,2, and 3,
516     //  then we have to pad the beginning before we store it, because [3,2] actually means [0,1,3,2]
517     // First, calculate the difference between this choice list and the upper bound
518     //  The actual list doesn't include '-1' at the end
519     int actualListLength = newChoiceList.length - 1;
520     int diff = maxUpperBound - actualListLength;
521     StringBuilder sb = new StringBuilder();
522     // Pad the beginning if necessary
523     for (int i = 0; i < diff; i++) {
524       sb.append(i);
525     }
526     // Then continue with the actual choice list
527     // We don't include the '-1' at the end
528     for (int i = 0; i < newChoiceList.length - 1; i++) {
529       sb.append(newChoiceList[i]);
530     }
531     return sb.toString();
532   }
533
534   private void checkAndAddBacktrackList(LinkedList<Integer[]> backtrackChoiceLists, Integer[] newChoiceList) {
535
536     String newChoiceListString = buildStringFromChoiceList(newChoiceList);
537     // Add only if we haven't seen this combination before
538     if (!backtrackSet.contains(newChoiceListString)) {
539       backtrackSet.add(newChoiceListString);
540       backtrackChoiceLists.addLast(newChoiceList);
541     }
542   }
543
544   private void createBacktrackChoiceList(int currentChoice, int conflictEventNumber) {
545
546     LinkedList<Integer[]> backtrackChoiceLists;
547     // Create a new list of choices for backtrack based on the current choice and conflicting event number
548     // If we have a conflict between 1 and 3, then we create the list {3, 1, 2, 4, 5} for backtrack
549     // The backtrack point is the CG for event number 1 and the list length is one less than the original list
550     // (originally of length 6) since we don't start from event number 0
551     if (!isResetAfterAnalysis) {
552       // Check if we have a list for this choice number
553       // If not we create a new one for it
554       if (!backtrackMap.containsKey(conflictEventNumber)) {
555         backtrackChoiceLists = new LinkedList<>();
556         backtrackMap.put(conflictEventNumber, backtrackChoiceLists);
557       } else {
558         backtrackChoiceLists = backtrackMap.get(conflictEventNumber);
559       }
560       int maxListLength = choiceUpperBound + 1;
561       int listLength = maxListLength - conflictEventNumber;
562       Integer[] newChoiceList = new Integer[listLength + 1];
563       // Put the conflicting event numbers first and reverse the order
564       newChoiceList[0] = choices[currentChoice];
565       newChoiceList[1] = choices[conflictEventNumber];
566       // Put the rest of the event numbers into the array starting from the minimum to the upper bound
567       for (int i = conflictEventNumber + 1, j = 2; j < listLength; i++) {
568         if (choices[i] != choices[currentChoice]) {
569           newChoiceList[j] = choices[i];
570           j++;
571         }
572       }
573       // Set the last element to '-1' as the end of the sequence
574       newChoiceList[newChoiceList.length - 1] = -1;
575       checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
576       // The start index for the recursion is always 1 (from the main branch)
577     } else { // This is a sub-graph
578       // There is a case/bug that after a re-initialization, currCG is not yet initialized
579       if (currCG != null && cgMap.containsKey(currCG)) {
580         int backtrackListIndex = cgMap.get(currCG);
581         backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
582         int listLength = choices.length;
583         Integer[] newChoiceList = new Integer[listLength];
584         // Copy everything before the conflict number
585         for (int i = 0; i < conflictEventNumber; i++) {
586           newChoiceList[i] = choices[i];
587         }
588         // Put the conflicting events
589         newChoiceList[conflictEventNumber] = choices[currentChoice];
590         newChoiceList[conflictEventNumber + 1] = choices[conflictEventNumber];
591         // Copy the rest
592         for (int i = conflictEventNumber + 1, j = conflictEventNumber + 2; j < listLength - 1; i++) {
593           if (choices[i] != choices[currentChoice]) {
594             newChoiceList[j] = choices[i];
595             j++;
596           }
597         }
598         // Set the last element to '-1' as the end of the sequence
599         newChoiceList[newChoiceList.length - 1] = -1;
600         checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
601       }
602     }
603   }
604
605   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
606   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
607           // Java and Groovy libraries
608           { "java", "org", "sun", "com", "gov", "groovy"};
609   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
610           // Groovy library created fields
611           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
612                   // Infrastructure
613                   "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
614                   "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
615   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
616   private final static String[] EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
617
618   private boolean isFieldExcluded(String field) {
619     // Check against "starts-with" list
620     for(String str : EXCLUDED_FIELDS_STARTS_WITH_LIST) {
621       if (field.startsWith(str)) {
622         return true;
623       }
624     }
625     // Check against "ends-with" list
626     for(String str : EXCLUDED_FIELDS_ENDS_WITH_LIST) {
627       if (field.endsWith(str)) {
628         return true;
629       }
630     }
631     // Check against "contains" list
632     for(String str : EXCLUDED_FIELDS_CONTAINS_LIST) {
633       if (field.contains(str)) {
634         return true;
635       }
636     }
637
638     return false;
639   }
640
641   // This method checks whether a choice is reachable in the VOD graph from a reference choice
642   // This is a BFS search
643   private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
644     // Record visited choices as we search in the graph
645     HashSet<Integer> visitedChoice = new HashSet<>();
646     visitedChoice.add(referenceChoice);
647     LinkedList<Integer> nodesToVisit = new LinkedList<>();
648     // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
649     // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
650     if (vodGraphMap.containsKey(referenceChoice)) {
651       nodesToVisit.addAll(vodGraphMap.get(referenceChoice));
652       while(!nodesToVisit.isEmpty()) {
653         int currChoice = nodesToVisit.getFirst();
654         if (currChoice == checkedChoice) {
655           return true;
656         }
657         if (visitedChoice.contains(currChoice)) {
658           // If there is a loop then we don't find it
659           return false;
660         }
661         // Continue searching
662         visitedChoice.add(currChoice);
663         HashSet<Integer> currChoiceNextNodes = vodGraphMap.get(currChoice);
664         if (currChoiceNextNodes != null) {
665           // Add only if there is a mapping for next nodes
666           for (Integer nextNode : currChoiceNextNodes) {
667             nodesToVisit.addLast(nextNode);
668           }
669         }
670       }
671     }
672     return false;
673   }
674
675   @Override
676   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
677     if (stateReductionMode) {
678       if (isInitialized) {
679         if (choiceCounter <= 0 || choiceCounter > choices.length - 1) {
680           // We do not compute the conflicts for the choice '-1'
681           return;
682         }
683         int currentChoice = choiceCounter - 1;
684         // Record accesses from executed instructions
685         if (executedInsn instanceof JVMFieldInstruction) {
686           // Analyze only after being initialized
687           String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
688           // We don't care about libraries
689           if (!isFieldExcluded(fieldClass)) {
690             analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
691           }
692         }
693         // Analyze conflicts from next instructions
694         if (nextInsn instanceof JVMFieldInstruction) {
695           // The constructor is only called once when the object is initialized
696           // It does not have shared access with other objects
697           MethodInfo mi = nextInsn.getMethodInfo();
698           if (!mi.getName().equals("<init>")) {
699             String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
700             // We don't care about libraries
701             if (!isFieldExcluded(fieldClass)) {
702               // Check for conflict (go backward from currentChoice and get the first conflict)
703               // If the current event has conflicts with multiple events, then these will be detected
704               // one by one as this recursively checks backward when backtrack set is revisited and executed.
705               for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
706                 // Skip if this event number does not have any Read/Write set
707                 if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
708                   continue;
709                 }
710                 ReadWriteSet rwSet = readWriteFieldsMap.get(choices[eventNumber]);
711                 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
712                 // 1) Check for conflicts with Write fields for both Read and Write instructions
713                 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
714                         rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
715                         (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
716                                 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
717                   // We do not record and service the same backtrack pair/point twice!
718                   // If it has been serviced before, we just skip this
719                   if (recordConflictPair(currentChoice, eventNumber)) {
720                     // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
721                     if (vm.isNewState() ||
722                             (!vm.isNewState() && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
723                       createBacktrackChoiceList(currentChoice, eventNumber);
724                       // Break if a conflict is found!
725                       break;
726                     }
727                   }
728                 }
729               }
730             }
731           }
732         }
733       }
734     }
735   }
736 }