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