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