afa1f87fae24ecf4714bc87f460ad1666c687fee
[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 Integer[] refChoices;
63   private IntChoiceFromSet currCG;
64   private int choiceCounter;
65   private Integer choiceUpperBound;
66   private Integer maxUpperBound;
67   private boolean isInitialized;
68   private boolean isResetAfterAnalysis;
69   private boolean isBooleanCGFlipped;
70   private HashMap<IntChoiceFromSet, Integer> cgMap;
71   // Record the mapping between event number and field accesses (Read and Write)
72   private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;
73   // The following is the backtrack map (set) that stores all the backtrack information
74   // e.g., event number 1 can have two backtrack sequences: {3,1,2,4,...} and {2,1,3,4,...}
75   private HashMap<Integer, LinkedList<Integer[]>> backtrackMap;
76   // Stores explored backtrack lists in the form of HashSet of Strings
77   private HashSet<String> backtrackSet;
78   private HashMap<Integer, HashSet<Integer>> conflictPairMap;
79
80   // Map that represents graph G
81   // (i.e., visible operation dependency graph (VOD Graph)
82   private HashMap<Integer, HashSet<Integer>> vodGraphMap;
83   // Set that represents hash table H
84   // (i.e., hash table that records encountered states)
85   // VOD graph is updated when the state has not yet been seen
86   // Current state
87   private HashSet<Integer> justVisitedStates;
88   // Previous choice number
89   private int prevChoiceValue;
90   // HashSet that stores references to unused CGs
91   private HashSet<IntChoiceFromSet> unusedCG;
92
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     justVisitedStates = new HashSet<>();
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     stateToEventMap = new HashMap<>();
123     prevVisitedStates = new HashSet<>();
124     currVisitedStates = new HashSet<>();
125     initializeStateReduction();
126   }
127
128   private void initializeStateReduction() {
129     if (stateReductionMode) {
130       choices = null;
131       refChoices = null;
132       currCG = null;
133       choiceCounter = 0;
134       choiceUpperBound = 0;
135       maxUpperBound = 0;
136       isInitialized = false;
137       isResetAfterAnalysis = false;
138       cgMap.clear();
139       resetReadWriteAnalysis();
140       backtrackMap.clear();
141       backtrackSet.clear();
142     }
143   }
144
145   @Override
146   public void stateRestored(Search search) {
147     if (debugMode) {
148       id = search.getStateId();
149       depth = search.getDepth();
150       transition = search.getTransition();
151       detail = null;
152       out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
153               " and depth: " + depth + "\n");
154     }
155   }
156
157   //--- the ones we are interested in
158   @Override
159   public void searchStarted(Search search) {
160     if (debugMode) {
161       out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
162     }
163   }
164
165   private void resetReadWriteAnalysis() {
166     // Reset the following data structure when the choice counter reaches 0 again
167     conflictPairMap.clear();
168     readWriteFieldsMap.clear();
169   }
170
171   private IntChoiceFromSet setNewCG(IntChoiceFromSet icsCG) {
172     icsCG.setNewValues(choices);
173     icsCG.reset();
174     // Use a modulo since choiceCounter is going to keep increasing
175     int choiceIndex = choiceCounter % choices.length;
176     icsCG.advance(choices[choiceIndex]);
177     if (choiceIndex == 0) {
178       resetReadWriteAnalysis();
179     }
180     return icsCG;
181   }
182
183   private Integer[] copyChoices(Integer[] choicesToCopy) {
184
185     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
186     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
187     return copyOfChoices;
188   }
189
190   private void initializeChoiceGenerators(IntChoiceFromSet icsCG, Integer[] cgChoices) {
191     if (choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
192       // Update the choices of the first CG and add '-1'
193       if (choices == null) {
194         // Initialize backtrack set that stores all the explored backtrack lists
195         maxUpperBound = cgChoices.length;
196         // All the choices are always the same so we only need to update it once
197         // Get the choice array and final choice in the array
198         choices = cgChoices;
199         // Make a copy of choices as reference
200         refChoices = copyChoices(choices);
201         String firstChoiceListString = buildStringFromChoiceList(choices);
202         backtrackSet.add(firstChoiceListString);
203       }
204       IntChoiceFromSet setCG = setNewCG(icsCG);
205       cgMap.put(setCG, refChoices[choiceCounter]);
206     } else {
207       // We repeat the same trace if a state match is not found yet
208       IntChoiceFromSet setCG = setNewCG(icsCG);
209       unusedCG.add(setCG);
210     }
211     choiceCounter++;
212   }
213
214   @Override
215   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
216     if (stateReductionMode) {
217       // Initialize with necessary information from the CG
218       if (nextCG instanceof IntChoiceFromSet) {
219         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
220         // Check if CG has been initialized, otherwise initialize it
221         Integer[] cgChoices = icsCG.getAllChoices();
222         if (!isInitialized) {
223           // Get the upper bound from the last element of the choices
224           choiceUpperBound = cgChoices[cgChoices.length - 1];
225           isInitialized = true;
226         }
227         // Record the subsequent Integer CGs only until we hit the upper bound
228         if (!isResetAfterAnalysis) {
229           initializeChoiceGenerators(icsCG, cgChoices);
230         } else {
231           // Set new CGs to done so that the search algorithm explores the existing CGs
232           icsCG.setDone();
233         }
234       }
235     }
236   }
237
238   private void setDoneUnusedCG() {
239     // Set done every CG in the unused CG set
240     for (IntChoiceFromSet cg : unusedCG) {
241       cg.setDone();
242     }
243     unusedCG.clear();
244   }
245
246   private void resetAllCGs() {
247     // Extract the event numbers that have backtrack lists
248     Set<Integer> eventSet = backtrackMap.keySet();
249     // Return if there is no conflict at all (highly unlikely)
250     if (eventSet.isEmpty()) {
251       // Set every CG to done!
252       for (IntChoiceFromSet cg : cgMap.keySet()) {
253         cg.setDone();
254       }
255       return;
256     }
257     // Reset every CG with the first backtrack lists
258     for (IntChoiceFromSet cg : cgMap.keySet()) {
259       int event = cgMap.get(cg);
260       LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
261       if (choiceLists != null && choiceLists.peekFirst() != null) {
262         Integer[] choiceList = choiceLists.removeFirst();
263         // Deploy the new choice list for this CG
264         cg.setNewValues(choiceList);
265         cg.reset();
266       } else {
267         cg.setDone();
268       }
269     }
270     setDoneUnusedCG();
271     saveVisitedStates();
272   }
273
274   // Detect cycles in the current execution/trace
275   // We terminate the execution iff:
276   // (1) the state has been visited in the current execution
277   // (2) the state has one or more cycles that involve all the events
278   // With simple approach we only need to check for a re-visited state.
279   // Basically, we have to check that we have executed all events between two occurrences of such state.
280   private boolean containsCyclesWithAllEvents(int stId) {
281
282     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
283     boolean containsCyclesWithAllEvts = false;
284     if (checkIfAllEventsInvolved(visitedEvents)) {
285       containsCyclesWithAllEvts = true;
286     }
287
288     return containsCyclesWithAllEvts;
289   }
290
291   private boolean checkIfAllEventsInvolved(HashSet<Integer> visitedEvents) {
292
293     // Check if this set contains all the event choices
294     // If not then this is not the terminating condition
295     for(int i=0; i<=choiceUpperBound; i++) {
296       if (!visitedEvents.contains(i)) {
297         return false;
298       }
299     }
300     return true;
301   }
302
303   private void saveVisitedStates() {
304     // CG is being reset
305     // Save all the visited states
306     prevVisitedStates.addAll(currVisitedStates);
307     currVisitedStates.clear();
308   }
309
310   private void updateChoicesForNewExecution(IntChoiceFromSet icsCG) {
311     if (choices == null || choices != icsCG.getAllChoices()) {
312       currCG = icsCG;
313       choices = icsCG.getAllChoices();
314       refChoices = copyChoices(choices);
315       // Reset a few things for the sub-graph
316       resetReadWriteAnalysis();
317       choiceCounter = 0;
318     }
319   }
320
321   private void exploreNextBacktrackSets(IntChoiceFromSet icsCG) {
322     // Traverse the sub-graphs
323     if (isResetAfterAnalysis) {
324       // Advance choice counter for sub-graphs
325       choiceCounter++;
326       // Do this for every CG after finishing each backtrack list
327       // We try to update the CG with a backtrack list if the state has been visited multiple times
328       //if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
329       if ((!icsCG.hasMoreChoices() || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
330         int event = cgMap.get(icsCG);
331         LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
332         if (choiceLists != null && choiceLists.peekFirst() != null) {
333           Integer[] choiceList = choiceLists.removeFirst();
334           // Deploy the new choice list for this CG
335           icsCG.setNewValues(choiceList);
336           icsCG.reset();
337         } else {
338           // Set done if this was the last backtrack list
339           icsCG.setDone();
340         }
341         saveVisitedStates();
342       }
343     } else {
344       // Update and reset the CG if needed (do this for the first time after the analysis)
345       // Start backtracking if this is a visited state and it is not a repeating state
346       resetAllCGs();
347       isResetAfterAnalysis = true;
348     }
349   }
350
351   private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
352     // Check the next choice and if the value is not the same as the expected then force the expected value
353     int choiceIndex = (choiceCounter - 1) % refChoices.length;
354     if (choices[choiceIndex] != icsCG.getNextChoiceIndex()) {
355       int expectedChoice = refChoices[choiceIndex];
356       int currCGIndex = icsCG.getNextChoiceIndex();
357       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
358         icsCG.setChoice(currCGIndex, expectedChoice);
359       }
360     }
361   }
362
363   private boolean terminateCurrentExecution() {
364     // We need to check all the states that have just been visited
365     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
366     for(Integer stateId : justVisitedStates) {
367       if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
368         return true;
369       }
370     }
371     return false;
372   }
373
374   @Override
375   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
376
377     if (stateReductionMode) {
378       // Check the boolean CG and if it is flipped, we are resetting the analysis
379       if (currentCG instanceof BooleanChoiceGenerator) {
380         if (!isBooleanCGFlipped) {
381           isBooleanCGFlipped = true;
382         } else {
383           initializeStateReduction();
384         }
385       }
386       // Check every choice generated and make sure that all the available choices
387       // are chosen first before repeating the same choice of value twice!
388       if (currentCG instanceof IntChoiceFromSet) {
389         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
390         // Update the current pointer to the current set of choices
391         updateChoicesForNewExecution(icsCG);
392         // Check if we have seen this state or this state contains cycles that involve all events
393         if (terminateCurrentExecution()) {
394           exploreNextBacktrackSets(icsCG);
395         }
396         justVisitedStates.clear();
397         // If we don't see a fair scheduling of events/choices then we have to enforce it
398         checkAndEnforceFairScheduling(icsCG);
399         // Update the VOD graph always with the latest
400         updateVODGraph(icsCG.getNextChoice());
401       }
402     }
403   }
404
405   private void updateVODGraph(int currChoiceValue) {
406     // Update the graph when we have the current choice value
407     HashSet<Integer> choiceSet;
408     if (vodGraphMap.containsKey(prevChoiceValue)) {
409       // If the key already exists, just retrieve it
410       choiceSet = vodGraphMap.get(prevChoiceValue);
411     } else {
412       // Create a new entry
413       choiceSet = new HashSet<>();
414       vodGraphMap.put(prevChoiceValue, choiceSet);
415     }
416     choiceSet.add(currChoiceValue);
417     prevChoiceValue = currChoiceValue;
418   }
419
420   private void mapStateToEvent(Search search, int stateId) {
421     // Insert state ID and event choice into the map
422     HashSet<Integer> eventSet;
423     if (stateToEventMap.containsKey(stateId)) {
424       eventSet = stateToEventMap.get(stateId);
425     } else {
426       eventSet = new HashSet<>();
427       stateToEventMap.put(stateId, eventSet);
428     }
429     eventSet.add(prevChoiceValue);
430   }
431
432   private void updateStateInfo(Search search) {
433     if (stateReductionMode) {
434       // Update the state variables
435       // Line 19 in the paper page 11 (see the heading note above)
436       int stateId = search.getStateId();
437       currVisitedStates.add(stateId);
438       mapStateToEvent(search, stateId);
439       justVisitedStates.add(stateId);
440     }
441   }
442
443   @Override
444   public void stateAdvanced(Search search) {
445     if (debugMode) {
446       id = search.getStateId();
447       depth = search.getDepth();
448       transition = search.getTransition();
449       if (search.isNewState()) {
450         detail = "new";
451       } else {
452         detail = "visited";
453       }
454
455       if (search.isEndState()) {
456         out.println("\n==> DEBUG: This is the last state!\n");
457         detail += " end";
458       }
459       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
460               " which is " + detail + " Transition: " + transition + "\n");
461     }
462     updateStateInfo(search);
463   }
464
465   @Override
466   public void stateBacktracked(Search search) {
467     if (debugMode) {
468       id = search.getStateId();
469       depth = search.getDepth();
470       transition = search.getTransition();
471       detail = null;
472
473       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
474               " and depth: " + depth + "\n");
475     }
476     updateStateInfo(search);
477   }
478
479   @Override
480   public void searchFinished(Search search) {
481     if (debugMode) {
482       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
483     }
484   }
485
486   // This class compactly stores Read and Write field sets
487   // We store the field name and its object ID
488   // Sharing the same field means the same field name and object ID
489   private class ReadWriteSet {
490     private HashMap<String, Integer> readSet;
491     private HashMap<String, Integer> writeSet;
492
493     public ReadWriteSet() {
494       readSet = new HashMap<>();
495       writeSet = new HashMap<>();
496     }
497
498     public void addReadField(String field, int objectId) {
499       readSet.put(field, objectId);
500     }
501
502     public void addWriteField(String field, int objectId) {
503       writeSet.put(field, objectId);
504     }
505
506     public boolean readFieldExists(String field) {
507       return readSet.containsKey(field);
508     }
509
510     public boolean writeFieldExists(String field) {
511       return writeSet.containsKey(field);
512     }
513
514     public int readFieldObjectId(String field) {
515       return readSet.get(field);
516     }
517
518     public int writeFieldObjectId(String field) {
519       return writeSet.get(field);
520     }
521   }
522
523   private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
524     // Do the analysis to get Read and Write accesses to fields
525     ReadWriteSet rwSet;
526     // We already have an entry
527     if (readWriteFieldsMap.containsKey(refChoices[currentChoice])) {
528       rwSet = readWriteFieldsMap.get(refChoices[currentChoice]);
529     } else { // We need to create a new entry
530       rwSet = new ReadWriteSet();
531       readWriteFieldsMap.put(refChoices[currentChoice], rwSet);
532     }
533     int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
534     // Record the field in the map
535     if (executedInsn instanceof WriteInstruction) {
536       // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
537       for (String str : EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
538         if (fieldClass.startsWith(str)) {
539           return;
540         }
541       }
542       rwSet.addWriteField(fieldClass, objectId);
543     } else if (executedInsn instanceof ReadInstruction) {
544       rwSet.addReadField(fieldClass, objectId);
545     }
546   }
547
548   private boolean recordConflictPair(int currentEvent, int eventNumber) {
549     HashSet<Integer> conflictSet;
550     if (!conflictPairMap.containsKey(currentEvent)) {
551       conflictSet = new HashSet<>();
552       conflictPairMap.put(currentEvent, conflictSet);
553     } else {
554       conflictSet = conflictPairMap.get(currentEvent);
555     }
556     // If this conflict has been recorded before, we return false because
557     // we don't want to service this backtrack point twice
558     if (conflictSet.contains(eventNumber)) {
559       return false;
560     }
561     // If it hasn't been recorded, then do otherwise
562     conflictSet.add(eventNumber);
563     return true;
564   }
565
566   private String buildStringFromChoiceList(Integer[] newChoiceList) {
567
568     // When we see a choice list shorter than the upper bound, e.g., [3,2] for choices 0,1,2, and 3,
569     //  then we have to pad the beginning before we store it, because [3,2] actually means [0,1,3,2]
570     // First, calculate the difference between this choice list and the upper bound
571     //  The actual list doesn't include '-1' at the end
572     int actualListLength = newChoiceList.length - 1;
573     int diff = maxUpperBound - actualListLength;
574     StringBuilder sb = new StringBuilder();
575     // Pad the beginning if necessary
576     for (int i = 0; i < diff; i++) {
577       sb.append(i);
578     }
579     // Then continue with the actual choice list
580     // We don't include the '-1' at the end
581     for (int i = 0; i < newChoiceList.length - 1; i++) {
582       sb.append(newChoiceList[i]);
583     }
584     return sb.toString();
585   }
586
587   private void checkAndAddBacktrackList(LinkedList<Integer[]> backtrackChoiceLists, Integer[] newChoiceList) {
588
589     String newChoiceListString = buildStringFromChoiceList(newChoiceList);
590     // Add only if we haven't seen this combination before
591     if (!backtrackSet.contains(newChoiceListString)) {
592       backtrackSet.add(newChoiceListString);
593       backtrackChoiceLists.addLast(newChoiceList);
594     }
595   }
596
597   private void createBacktrackChoiceList(int currentChoice, int conflictEventNumber) {
598
599     LinkedList<Integer[]> backtrackChoiceLists;
600     // Create a new list of choices for backtrack based on the current choice and conflicting event number
601     // If we have a conflict between 1 and 3, then we create the list {3, 1, 2, 4, 5} for backtrack
602     // The backtrack point is the CG for event number 1 and the list length is one less than the original list
603     // (originally of length 6) since we don't start from event number 0
604     if (!isResetAfterAnalysis) {
605       // Check if we have a list for this choice number
606       // If not we create a new one for it
607       if (!backtrackMap.containsKey(conflictEventNumber)) {
608         backtrackChoiceLists = new LinkedList<>();
609         backtrackMap.put(conflictEventNumber, backtrackChoiceLists);
610       } else {
611         backtrackChoiceLists = backtrackMap.get(conflictEventNumber);
612       }
613       int maxListLength = choiceUpperBound + 1;
614       int listLength = maxListLength - conflictEventNumber;
615       Integer[] newChoiceList = new Integer[listLength];
616       // Put the conflicting event numbers first and reverse the order
617       newChoiceList[0] = refChoices[currentChoice];
618       newChoiceList[1] = refChoices[conflictEventNumber];
619       // Put the rest of the event numbers into the array starting from the minimum to the upper bound
620       for (int i = conflictEventNumber + 1, j = 2; j < listLength; i++) {
621         if (refChoices[i] != refChoices[currentChoice]) {
622           newChoiceList[j] = refChoices[i];
623           j++;
624         }
625       }
626       checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
627       // The start index for the recursion is always 1 (from the main branch)
628     } else { // This is a sub-graph
629       // There is a case/bug that after a re-initialization, currCG is not yet initialized
630       if (currCG != null && cgMap.containsKey(currCG)) {
631         int backtrackListIndex = cgMap.get(currCG);
632         backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
633         int listLength = refChoices.length;
634         Integer[] newChoiceList = new Integer[listLength];
635         // Copy everything before the conflict number
636         for (int i = 0; i < conflictEventNumber; i++) {
637           newChoiceList[i] = refChoices[i];
638         }
639         // Put the conflicting events
640         newChoiceList[conflictEventNumber] = refChoices[currentChoice];
641         newChoiceList[conflictEventNumber + 1] = refChoices[conflictEventNumber];
642         // Copy the rest
643         for (int i = conflictEventNumber + 1, j = conflictEventNumber + 2; j < listLength - 1; i++) {
644           if (refChoices[i] != refChoices[currentChoice]) {
645             newChoiceList[j] = refChoices[i];
646             j++;
647           }
648         }
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 % refChoices.length) - 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(refChoices[eventNumber])) {
761                   continue;
762                 }
763                 ReadWriteSet rwSet = readWriteFieldsMap.get(refChoices[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() || isReachableInVODGraph(refChoices[currentChoice], refChoices[currentChoice-1])) {
775                       createBacktrackChoiceList(currentChoice, eventNumber);
776                       // Break if a conflict is found!
777                       break;
778                     }
779                   }
780                 }
781               }
782             }
783           }
784         }
785       }
786     }
787   }
788 }