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