Fixing bugs: moving VOD-graph building into the CGAdvanced method to have the most...
[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 = choiceCounter < choiceUpperBound ? choiceCounter + 1 : 0;
207           choiceCounter++;
208         } else {
209           // Set new CGs to done so that the search algorithm explores the existing CGs
210           icsCG.setDone();
211         }
212       }
213     }
214   }
215
216   private void resetAllCGs() {
217     // Extract the event numbers that have backtrack lists
218     Set<Integer> eventSet = backtrackMap.keySet();
219     // Return if there is no conflict at all (highly unlikely)
220     if (eventSet.isEmpty()) {
221       // Set every CG to done!
222       for (IntChoiceFromSet cg : cgMap.keySet()) {
223         cg.setDone();
224       }
225       return;
226     }
227     // Reset every CG with the first backtrack lists
228     for (IntChoiceFromSet cg : cgMap.keySet()) {
229       int event = cgMap.get(cg);
230       LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
231       if (choiceLists != null && choiceLists.peekFirst() != null) {
232         Integer[] choiceList = choiceLists.removeFirst();
233         // Deploy the new choice list for this CG
234         cg.setNewValues(choiceList);
235         cg.reset();
236       } else {
237         cg.setDone();
238       }
239     }
240     // Set done every CG in the unused CG set
241     for (IntChoiceFromSet cg : unusedCG) {
242       cg.setDone();
243     }
244     unusedCG.clear();
245     saveVisitedStates();
246   }
247
248   // Detect cycles in the current execution/trace
249   // We terminate the execution iff:
250   // (1) the state has been visited in the current execution
251   // (2) the state has one or more cycles that involve all the events
252   private boolean containsCyclesWithAllEvents(int stId) {
253
254     HashSet<ConflictTracker.Node> visitingStates = new HashSet<>();
255     HashSet<Integer> visitedEvents = new HashSet<>();
256     boolean containsCyclesWithAllEvts = false;
257     ConflictTracker.Node currNode = stateGraph.get(stId);
258     dfsFindCycles(currNode, visitingStates, visitedEvents, new HashSet<>());
259     if (checkIfAllEventsInvolved(visitedEvents)) {
260       containsCyclesWithAllEvts = true;
261     }
262
263     return containsCyclesWithAllEvts;
264   }
265
266   private void dfsFindCycles(ConflictTracker.Node currNode, HashSet<ConflictTracker.Node> visitingStates,
267                              HashSet<Integer> visitedEvents, HashSet<Integer> visitingEvents) {
268
269     // Stop when there is a cycle and record all the events
270     if (visitingStates.contains(currNode)) {
271       visitedEvents.addAll(visitingEvents);
272     } else {
273       visitingStates.add(currNode);
274       for(ConflictTracker.Edge edge : currNode.getOutEdges()) {
275         visitingEvents.add(edge.getEventNumber());
276         dfsFindCycles(edge.getDst(), visitingStates, visitedEvents, visitingEvents);
277         visitingEvents.remove(edge.getEventNumber());
278       }
279       visitingStates.remove(currNode);
280     }
281   }
282
283   private boolean checkIfAllEventsInvolved(HashSet<Integer> visitedEvents) {
284
285     // Check if this set contains all the event choices
286     // If not then this is not the terminating condition
287     for(int i=0; i<=choiceUpperBound; i++) {
288       if (!visitedEvents.contains(i)) {
289         return false;
290       }
291     }
292     return true;
293   }
294
295   private void saveVisitedStates() {
296     // CG is being reset
297     // Save all the visited states
298     prevVisitedStates.addAll(currVisitedStates);
299     currVisitedStates.clear();
300   }
301
302   @Override
303   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
304
305     if (stateReductionMode) {
306       // Check the boolean CG and if it is flipped, we are resetting the analysis
307       if (currentCG instanceof BooleanChoiceGenerator) {
308         if (!isBooleanCGFlipped) {
309           isBooleanCGFlipped = true;
310         } else {
311           initializeStateReduction();
312         }
313       }
314       // Check every choice generated and make sure that all the available choices
315       // are chosen first before repeating the same choice of value twice!
316       if (currentCG instanceof IntChoiceFromSet) {
317         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
318         // Update the current pointer to the current set of choices
319         if (choices == null || choices != icsCG.getAllChoices()) {
320           currCG = icsCG;
321           choices = icsCG.getAllChoices();
322           // Reset a few things for the sub-graph
323           conflictPairMap.clear();
324           readWriteFieldsMap.clear();
325           choiceCounter = 0;
326         }
327         // Check if we have seen this state or this state contains cycles that involve all events
328         if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
329           // Traverse the sub-graphs
330           if (isResetAfterAnalysis) {
331             // Advance choice counter for sub-graphs
332             choiceCounter++;
333             // Do this for every CG after finishing each backtrack list
334             // We try to update the CG with a backtrack list if the state has been visited multiple times
335             if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
336               int event = cgMap.get(icsCG);
337               LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
338               if (choiceLists != null && choiceLists.peekFirst() != null) {
339                 Integer[] choiceList = choiceLists.removeFirst();
340                 // Deploy the new choice list for this CG
341                 icsCG.setNewValues(choiceList);
342                 icsCG.reset();
343               } else {
344                 // Set done if this was the last backtrack list
345                 icsCG.setDone();
346               }
347               saveVisitedStates();
348             }
349           } else {
350             // Update and reset the CG if needed (do this for the first time after the analysis)
351             // Start backtracking if this is a visited state and it is not a repeating state
352             resetAllCGs();
353             isResetAfterAnalysis = true;
354           }
355         }
356         // Update the VOD graph always with the latest
357         updateVODGraph(icsCG.getNextChoice());
358       }
359     }
360   }
361
362   private void updateVODGraph(int currChoiceValue) {
363     // Update the graph when we have the current choice value
364     updateVODGraph(prevChoiceValue, currChoiceValue);
365     prevChoiceValue = currChoiceValue;
366   }
367
368   private void updateVODGraph(int prevChoice, int currChoice) {
369
370     HashSet<Integer> choiceSet;
371     if (vodGraphMap.containsKey(prevChoice)) {
372       // If the key already exists, just retrieve it
373       choiceSet = vodGraphMap.get(prevChoice);
374     } else {
375       // Create a new entry
376       choiceSet = new HashSet<>();
377       vodGraphMap.put(prevChoice, choiceSet);
378     }
379     choiceSet.add(currChoice);
380   }
381
382   @Override
383   public void stateAdvanced(Search search) {
384     if (debugMode) {
385       id = search.getStateId();
386       depth = search.getDepth();
387       transition = search.getTransition();
388       if (search.isNewState()) {
389         detail = "new";
390       } else {
391         detail = "visited";
392       }
393
394       if (search.isEndState()) {
395         out.println("\n==> DEBUG: This is the last state!\n");
396         detail += " end";
397       }
398       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
399               " which is " + detail + " Transition: " + transition + "\n");
400     }
401     if (stateReductionMode) {
402       // Update the state ID variables
403       stateId = search.getStateId();
404       currVisitedStates.add(stateId);
405     }
406   }
407
408   @Override
409   public void stateBacktracked(Search search) {
410     if (debugMode) {
411       id = search.getStateId();
412       depth = search.getDepth();
413       transition = search.getTransition();
414       detail = null;
415
416       // Update the state variables
417       // Line 19 in the paper page 11 (see the heading note above)
418       stateId = search.getStateId();
419       currVisitedStates.add(stateId);
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             // Skip cycles
668             if (nextNode == currChoice) {
669               continue;
670             }
671             nodesToVisit.addLast(nextNode);
672           }
673         }
674       }
675     }
676     return false;
677   }
678
679   @Override
680   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
681     if (stateReductionMode) {
682       if (isInitialized) {
683         if (choiceCounter <= 0 || choiceCounter > choices.length - 1) {
684           // We do not compute the conflicts for the choice '-1'
685           return;
686         }
687         int currentChoice = choiceCounter - 1;
688         // Record accesses from executed instructions
689         if (executedInsn instanceof JVMFieldInstruction) {
690           // Analyze only after being initialized
691           String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
692           // We don't care about libraries
693           if (!isFieldExcluded(fieldClass)) {
694             analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
695           }
696         }
697         // Analyze conflicts from next instructions
698         if (nextInsn instanceof JVMFieldInstruction) {
699           // The constructor is only called once when the object is initialized
700           // It does not have shared access with other objects
701           MethodInfo mi = nextInsn.getMethodInfo();
702           if (!mi.getName().equals("<init>")) {
703             String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
704             // We don't care about libraries
705             if (!isFieldExcluded(fieldClass)) {
706               // Check for conflict (go backward from currentChoice and get the first conflict)
707               // If the current event has conflicts with multiple events, then these will be detected
708               // one by one as this recursively checks backward when backtrack set is revisited and executed.
709               for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
710                 // Skip if this event number does not have any Read/Write set
711                 if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
712                   continue;
713                 }
714                 ReadWriteSet rwSet = readWriteFieldsMap.get(choices[eventNumber]);
715                 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
716                 // 1) Check for conflicts with Write fields for both Read and Write instructions
717                 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
718                         rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
719                         (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
720                                 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
721                   // We do not record and service the same backtrack pair/point twice!
722                   // If it has been serviced before, we just skip this
723                   if (recordConflictPair(currentChoice, eventNumber)) {
724                     // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
725                     if (vm.isNewState() ||
726                             (!vm.isNewState() && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
727                       createBacktrackChoiceList(currentChoice, eventNumber);
728                       // Break if a conflict is found!
729                       break;
730                     }
731                   }
732                 }
733               }
734             }
735           }
736         }
737       }
738     }
739   }
740 }