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