08ae9a64c380d14c2e192bdf30a79638eab257bd
[jpf-core.git] / src / main / gov / nasa / jpf / listener / DPORStateReducerWithSummary.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.jvm.bytecode.INVOKEINTERFACE;
24 import gov.nasa.jpf.jvm.bytecode.JVMFieldInstruction;
25 import gov.nasa.jpf.report.Publisher;
26 import gov.nasa.jpf.search.Search;
27 import gov.nasa.jpf.vm.*;
28 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
29 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
30 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
31 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
32
33 import java.io.FileWriter;
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.util.*;
37 import java.util.logging.Logger;
38
39 /**
40  * This a DPOR implementation for event-driven applications with loops that create cycles of state matching
41  * In this new DPOR algorithm/implementation, each run is terminated iff:
42  * - we find a state that matches a state in a previous run, or
43  * - we have a matched state in the current run that consists of cycles that contain all choices/events.
44  */
45 public class DPORStateReducerWithSummary extends ListenerAdapter {
46
47   // Information printout fields for verbose mode
48   private boolean verboseMode;
49   private boolean stateReductionMode;
50   private final PrintWriter out;
51   private PrintWriter fileWriter;
52   private String detail;
53   private int depth;
54   private int id;
55   private Transition transition;
56
57   // DPOR-related fields
58   // Basic information
59   private Integer[] choices;
60   private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
61   private int choiceCounter;
62   private int maxEventChoice;
63   // Data structure to track the events seen by each state to track cycles (containing all events) for termination
64   private HashMap<Integer,Integer> currVisitedStates; // States visited in the current execution (maps to frequency)
65   private HashSet<Integer> justVisitedStates;   // States just visited in the previous choice/event
66   private HashSet<Integer> prevVisitedStates;   // States visited in the previous execution
67   private HashSet<ClassInfo> nonRelevantClasses;// Class info objects of non-relevant classes
68   private HashSet<FieldInfo> nonRelevantFields; // Field info objects of non-relevant fields
69   private HashSet<FieldInfo> relevantFields;    // Field info objects of relevant fields
70   private HashMap<Integer, HashSet<Integer>> stateToEventMap;       // Map state ID to events
71   // Data structure to analyze field Read/Write accesses and conflicts
72   private HashMap<Integer, LinkedList<BacktrackExecution>> backtrackMap;  // Track created backtracking points
73   private PriorityQueue<Integer> backtrackStateQ;                 // Heap that returns the latest state
74   private Execution currentExecution;                             // Holds the information about the current execution
75   private HashMap<Integer, HashSet<Integer>> doneBacktrackMap;    // Record state ID and trace already constructed
76   private MainSummary mainSummary;                                // Main summary (M) for state ID, event, and R/W set
77   private HashMap<Integer, PredecessorInfo> stateToPredInfo;      // Predecessor info indexed by state ID
78   private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
79   private RGraph rGraph;                                          // R-Graph for past executions
80
81   // Boolean states
82   private boolean isBooleanCGFlipped;
83   private boolean isEndOfExecution;
84   private boolean isNotCheckedForEventsYet;
85
86   // Statistics
87   private int numOfTransitions;
88   private HashMap<Integer, HashSet<Integer>> stateToUniqueEventMap;
89
90   public DPORStateReducerWithSummary(Config config, JPF jpf) {
91     verboseMode = config.getBoolean("printout_state_transition", false);
92     stateReductionMode = config.getBoolean("activate_state_reduction", true);
93     if (verboseMode) {
94       out = new PrintWriter(System.out, true);
95     } else {
96       out = null;
97     }
98     String outputFile = config.getString("file_output");
99     if (!outputFile.isEmpty()) {
100       try {
101         fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
102       } catch (IOException e) {
103       }
104     }
105     isBooleanCGFlipped = false;
106     isNotCheckedForEventsYet = true;
107     mainSummary = new MainSummary();
108     numOfTransitions = 0;
109     nonRelevantClasses = new HashSet<>();
110     nonRelevantFields = new HashSet<>();
111     relevantFields = new HashSet<>();
112     restorableStateMap = new HashMap<>();
113     stateToPredInfo = new HashMap<>();
114     stateToUniqueEventMap = new HashMap<>();
115     initializeStatesVariables();
116   }
117
118   @Override
119   public void stateRestored(Search search) {
120     if (verboseMode) {
121       id = search.getStateId();
122       depth = search.getDepth();
123       transition = search.getTransition();
124       detail = null;
125       out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
126               " and depth: " + depth + "\n");
127     }
128   }
129
130   @Override
131   public void searchStarted(Search search) {
132     if (verboseMode) {
133       out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
134     }
135   }
136
137   @Override
138   public void stateAdvanced(Search search) {
139     if (verboseMode) {
140       id = search.getStateId();
141       depth = search.getDepth();
142       transition = search.getTransition();
143       if (search.isNewState()) {
144         detail = "new";
145       } else {
146         detail = "visited";
147       }
148
149       if (search.isEndState()) {
150         out.println("\n==> DEBUG: This is the last state!\n");
151         detail += " end";
152       }
153       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
154               " which is " + detail + " Transition: " + transition + "\n");
155     }
156     if (stateReductionMode) {
157       updateStateInfo(search);
158     }
159   }
160
161   @Override
162   public void stateBacktracked(Search search) {
163     if (verboseMode) {
164       id = search.getStateId();
165       depth = search.getDepth();
166       transition = search.getTransition();
167       detail = null;
168
169       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
170               " and depth: " + depth + "\n");
171     }
172     if (stateReductionMode) {
173       updateStateInfo(search);
174     }
175   }
176
177   static Logger log = JPF.getLogger("report");
178
179   @Override
180   public void searchFinished(Search search) {
181     if (verboseMode) {
182       int summaryOfUniqueTransitions = summarizeUniqueTransitions();
183       out.println("\n==> DEBUG: ----------------------------------- search finished");
184       out.println("\n==> DEBUG: State reduction mode                : " + stateReductionMode);
185       out.println("\n==> DEBUG: Number of transitions               : " + numOfTransitions);
186       out.println("\n==> DEBUG: Number of unique transitions (DPOR) : " + summaryOfUniqueTransitions);
187       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
188
189       fileWriter.println("==> DEBUG: State reduction mode                : " + stateReductionMode);
190       fileWriter.println("==> DEBUG: Number of transitions               : " + numOfTransitions);
191       fileWriter.println("==> DEBUG: Number of unique transitions (DPOR) : " + summaryOfUniqueTransitions);
192       fileWriter.println();
193       fileWriter.close();
194     }
195   }
196
197   @Override
198   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
199     if (isNotCheckedForEventsYet) {
200       // Check if this benchmark has no events
201       if (nextCG instanceof IntChoiceFromSet) {
202         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
203         Integer[] cgChoices = icsCG.getAllChoices();
204         if (cgChoices.length == 2 && cgChoices[0] == 0 && cgChoices[1] == -1) {
205           // This means the benchmark only has 2 choices, i.e., 0 and -1 which means that it has no events
206           stateReductionMode = false;
207         }
208         isNotCheckedForEventsYet = false;
209       }
210     }
211     if (stateReductionMode) {
212       // Initialize with necessary information from the CG
213       if (nextCG instanceof IntChoiceFromSet) {
214         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
215         // Tell JPF that we are performing DPOR
216         icsCG.setDpor();
217         if (!isEndOfExecution) {
218           // Check if CG has been initialized, otherwise initialize it
219           Integer[] cgChoices = icsCG.getAllChoices();
220           // Record the events (from choices)
221           if (choices == null) {
222             choices = cgChoices;
223             // Make a copy of choices as reference
224             refChoices = copyChoices(choices);
225             // Record the max event choice (the last element of the choice array)
226             maxEventChoice = choices[choices.length - 1];
227           }
228           icsCG.setNewValues(choices);
229           icsCG.reset();
230           // Use a modulo since choiceCounter is going to keep increasing
231           int choiceIndex = choiceCounter % choices.length;
232           icsCG.advance(choices[choiceIndex]);
233         } else {
234           // Set done all CGs while transitioning to a new execution
235           icsCG.setDone();
236         }
237       }
238     }
239   }
240
241   @Override
242   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
243     if (stateReductionMode) {
244       // Check the boolean CG and if it is flipped, we are resetting the analysis
245       if (currentCG instanceof BooleanChoiceGenerator) {
246         if (!isBooleanCGFlipped) {
247           isBooleanCGFlipped = true;
248         } else {
249           // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
250           initializeStatesVariables();
251         }
252       }
253       // Check every choice generated and ensure fair scheduling!
254       if (currentCG instanceof IntChoiceFromSet) {
255         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
256         // If this is a new CG then we need to update data structures
257         resetStatesForNewExecution(icsCG, vm);
258         // If we don't see a fair scheduling of events/choices then we have to enforce it
259         ensureFairSchedulingAndSetupTransition(icsCG, vm);
260         // Update backtrack set of an executed event (transition): one transition before this one
261         updateBacktrackSet(currentExecution, choiceCounter - 1);
262         // Explore the next backtrack point:
263         // 1) if we have seen this state or this state contains cycles that involve all events, and
264         // 2) after the current CG is advanced at least once
265         if (choiceCounter > 0 && terminateCurrentExecution()) {
266           exploreNextBacktrackPoints(vm, icsCG);
267         } else {
268           // We only count IntChoiceFromSet CGs
269           numOfTransitions++;
270           countUniqueStateId(vm.getStateId(), icsCG.getNextChoice());
271         }
272         // Map state to event
273         mapStateToEvent(icsCG.getNextChoice());
274         justVisitedStates.clear();
275         choiceCounter++;
276       }
277     } else {
278       // We only count IntChoiceFromSet CGs
279       if (currentCG instanceof IntChoiceFromSet) {
280         numOfTransitions++;
281       }
282     }
283   }
284
285   @Override
286   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
287     if (stateReductionMode) {
288       if (!isEndOfExecution) {
289         // Has to be initialized and it is a integer CG
290         ChoiceGenerator<?> cg = vm.getChoiceGenerator();
291         if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
292           int currentChoice = choiceCounter - 1;  // Accumulative choice w.r.t the current trace
293           if (currentChoice < 0) { // If choice is -1 then skip
294             return;
295           }
296           currentChoice = checkAndAdjustChoice(currentChoice, vm);
297           // Record accesses from executed instructions
298           if (executedInsn instanceof JVMFieldInstruction) {
299             // We don't care about libraries
300             if (!isFieldExcluded(executedInsn)) {
301               analyzeReadWriteAccesses(executedInsn, currentChoice);
302             }
303           } else if (executedInsn instanceof INVOKEINTERFACE) {
304             // Handle the read/write accesses that occur through iterators
305             analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
306           }
307         }
308       }
309     }
310   }
311
312
313   // == HELPERS
314
315   // -- INNER CLASSES
316
317   // This class compactly stores backtrack execution:
318   // 1) backtrack choice list, and
319   // 2) first backtrack point (linking with predecessor execution)
320   private class BacktrackExecution {
321     private Integer[] choiceList;
322     private TransitionEvent firstTransition;
323
324     public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
325       choiceList = choList;
326       firstTransition = fTransition;
327     }
328
329     public Integer[] getChoiceList() {
330       return choiceList;
331     }
332
333     public TransitionEvent getFirstTransition() {
334       return firstTransition;
335     }
336   }
337
338   // This class stores a representation of an execution
339   // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
340   // TODO: We basically need to keep track of:
341   // TODO:    (1) last read/write access to each memory location
342   // TODO:    (2) last state with two or more incoming events/transitions
343   private class Execution {
344     private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap;   // Map between CG to choice numbers for O(1) access
345     private ArrayList<TransitionEvent> executionTrace;          // The BacktrackPoint objects of this execution
346     private boolean isNew;                                      // Track if this is the first time it is accessed
347     private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;  // Record fields that are accessed
348
349     public Execution() {
350       cgToChoiceMap = new HashMap<>();
351       executionTrace = new ArrayList<>();
352       isNew = true;
353       readWriteFieldsMap = new HashMap<>();
354     }
355
356     public void addTransition(TransitionEvent newBacktrackPoint) {
357       executionTrace.add(newBacktrackPoint);
358     }
359
360     public void clearCGToChoiceMap() {
361       cgToChoiceMap = null;
362     }
363
364     public int getChoiceFromCG(IntChoiceFromSet icsCG) {
365       return cgToChoiceMap.get(icsCG);
366     }
367
368     public ArrayList<TransitionEvent> getExecutionTrace() {
369       return executionTrace;
370     }
371
372     public TransitionEvent getFirstTransition() {
373       return executionTrace.get(0);
374     }
375
376     public TransitionEvent getLastTransition() {
377       return executionTrace.get(executionTrace.size() - 1);
378     }
379
380     public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
381       return readWriteFieldsMap;
382     }
383
384     public boolean isNew() {
385       if (isNew) {
386         // Right after this is accessed, it is no longer new
387         isNew = false;
388         return true;
389       }
390       return false;
391     }
392
393     public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
394       cgToChoiceMap.put(icsCG, choice);
395     }
396   }
397
398   // This class compactly stores a predecessor
399   // 1) a predecessor execution
400   // 2) the predecessor choice in that predecessor execution
401   private class Predecessor {
402     private int choice;           // Predecessor choice
403     private Execution execution;  // Predecessor execution
404
405     public Predecessor(int predChoice, Execution predExec) {
406       choice = predChoice;
407       execution = predExec;
408     }
409
410     public int getChoice() {
411       return choice;
412     }
413
414     public Execution getExecution() {
415       return execution;
416     }
417   }
418
419   // This class represents a R-Graph (in the paper it is a state transition graph R)
420   // This implementation stores reachable transitions from and connects with past executions
421   private class RGraph {
422     private int hiStateId;                                     // Maximum state Id
423     private HashMap<Integer, HashSet<TransitionEvent>> graph;  // Reachable transitions from past executions
424
425     public RGraph() {
426       hiStateId = 0;
427       graph = new HashMap<>();
428     }
429
430     public void addReachableTransition(int stateId, TransitionEvent transition) {
431       HashSet<TransitionEvent> transitionSet;
432       if (graph.containsKey(stateId)) {
433         transitionSet = graph.get(stateId);
434       } else {
435         transitionSet = new HashSet<>();
436         graph.put(stateId, transitionSet);
437       }
438       // Insert into the set if it does not contain it yet
439       if (!transitionSet.contains(transition)) {
440         transitionSet.add(transition);
441       }
442       // Update highest state ID
443       if (hiStateId < stateId) {
444         hiStateId = stateId;
445       }
446     }
447
448     public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
449       if (!graph.containsKey(stateId)) {
450         // This is a loop from a transition to itself, so just return the current transition
451         HashSet<TransitionEvent> transitionSet = new HashSet<>();
452         transitionSet.add(currentExecution.getLastTransition());
453         return transitionSet;
454       }
455       return graph.get(stateId);
456     }
457
458     public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
459       HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
460       // All transitions from states higher than the given state ID (until the highest state ID) are reachable
461       for(int stId = stateId; stId <= hiStateId; stId++) {
462         // We might encounter state IDs from the first round of Boolean CG
463         // The second round of Boolean CG should consider these new states
464         if (graph.containsKey(stId)) {
465           reachableTransitions.addAll(graph.get(stId));
466         }
467       }
468       return reachableTransitions;
469     }
470   }
471
472   // This class compactly stores Read and Write field sets
473   // We store the field name and its object ID
474   // Sharing the same field means the same field name and object ID
475   private class ReadWriteSet {
476     private HashMap<String, Integer> readMap;
477     private HashMap<String, Integer> writeMap;
478
479     public ReadWriteSet() {
480       readMap = new HashMap<>();
481       writeMap = new HashMap<>();
482     }
483
484     public void addReadField(String field, int objectId) {
485       readMap.put(field, objectId);
486     }
487
488     public void addWriteField(String field, int objectId) {
489       writeMap.put(field, objectId);
490     }
491
492     public void removeReadField(String field) {
493       readMap.remove(field);
494     }
495
496     public void removeWriteField(String field) {
497       writeMap.remove(field);
498     }
499
500     public boolean isEmpty() {
501       return readMap.isEmpty() && writeMap.isEmpty();
502     }
503
504     public ReadWriteSet getCopy() {
505       ReadWriteSet copyRWSet = new ReadWriteSet();
506       // Copy the maps in the set into the new object copy
507       copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
508       copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
509       return copyRWSet;
510     }
511
512     public Set<String> getReadSet() {
513       return readMap.keySet();
514     }
515
516     public Set<String> getWriteSet() {
517       return writeMap.keySet();
518     }
519
520     public boolean readFieldExists(String field) {
521       return readMap.containsKey(field);
522     }
523
524     public boolean writeFieldExists(String field) {
525       return writeMap.containsKey(field);
526     }
527
528     public int readFieldObjectId(String field) {
529       return readMap.get(field);
530     }
531
532     public int writeFieldObjectId(String field) {
533       return writeMap.get(field);
534     }
535
536     private HashMap<String, Integer> getReadMap() {
537       return readMap;
538     }
539
540     private HashMap<String, Integer> getWriteMap() {
541       return writeMap;
542     }
543
544     private void setReadMap(HashMap<String, Integer> rMap) {
545       readMap = rMap;
546     }
547
548     private void setWriteMap(HashMap<String, Integer> wMap) {
549       writeMap = wMap;
550     }
551   }
552
553   // This class is a representation of a state.
554   // It stores the predecessors to a state.
555   // TODO: We also have stateToEventMap, restorableStateMap, and doneBacktrackMap that has state Id as HashMap key.
556   private class PredecessorInfo {
557     private HashSet<Predecessor> predecessors;  // Maps incoming events/transitions (execution and choice)
558     private HashMap<Execution, HashSet<Integer>> recordedPredecessors;
559                                                 // Memorize event and choice number to not record them twice
560
561     public PredecessorInfo() {
562       predecessors = new HashSet<>();
563       recordedPredecessors = new HashMap<>();
564     }
565
566     public HashSet<Predecessor> getPredecessors() {
567       return predecessors;
568     }
569
570     private boolean isRecordedPredecessor(Execution execution, int choice) {
571       // See if we have recorded this predecessor earlier
572       HashSet<Integer> recordedChoices;
573       if (recordedPredecessors.containsKey(execution)) {
574         recordedChoices = recordedPredecessors.get(execution);
575         if (recordedChoices.contains(choice)) {
576           return true;
577         }
578       } else {
579         recordedChoices = new HashSet<>();
580         recordedPredecessors.put(execution, recordedChoices);
581       }
582       // Record the choice if we haven't seen it
583       recordedChoices.add(choice);
584
585       return false;
586     }
587
588     public void recordPredecessor(Execution execution, int choice) {
589       if (!isRecordedPredecessor(execution, choice)) {
590         predecessors.add(new Predecessor(choice, execution));
591       }
592     }
593   }
594
595   // This class compactly stores transitions:
596   // 1) CG,
597   // 2) state ID,
598   // 3) choice,
599   // 4) predecessors (for backward DFS).
600   private class TransitionEvent {
601     private int choice;                        // Choice chosen at this transition
602     private int choiceCounter;                 // Choice counter at this transition
603     private Execution execution;               // The execution where this transition belongs
604     private int stateId;                       // State at this transition
605     private IntChoiceFromSet transitionCG;     // CG at this transition
606
607     public TransitionEvent() {
608       choice = 0;
609       choiceCounter = 0;
610       execution = null;
611       stateId = 0;
612       transitionCG = null;
613     }
614
615     public int getChoice() {
616       return choice;
617     }
618
619     public int getChoiceCounter() {
620       return choiceCounter;
621     }
622
623     public Execution getExecution() {
624       return execution;
625     }
626
627     public int getStateId() {
628       return stateId;
629     }
630
631     public IntChoiceFromSet getTransitionCG() { return transitionCG; }
632
633     public void setChoice(int cho) {
634       choice = cho;
635     }
636
637     public void setChoiceCounter(int choCounter) {
638       choiceCounter = choCounter;
639     }
640
641     public void setExecution(Execution exec) {
642       execution = exec;
643     }
644
645     public void setStateId(int stId) {
646       stateId = stId;
647     }
648
649     public void setTransitionCG(IntChoiceFromSet cg) {
650       transitionCG = cg;
651     }
652   }
653
654   // -- PRIVATE CLASSES RELATED TO SUMMARY
655   // This class stores the main summary of states
656   // 1) Main mapping between state ID and state summary
657   // 2) State summary is a mapping between events (i.e., event choices) and their respective R/W sets
658   private class MainSummary {
659     private HashMap<Integer, HashMap<Integer, ReadWriteSet>> mainSummary;
660
661     public MainSummary() {
662       mainSummary = new HashMap<>();
663     }
664
665     public Set<Integer> getEventChoicesAtStateId(int stateId) {
666       HashMap<Integer, ReadWriteSet> stateSummary = mainSummary.get(stateId);
667       // Return a new set since this might get updated concurrently
668       return new HashSet<>(stateSummary.keySet());
669     }
670
671     public ReadWriteSet getRWSetForEventChoiceAtState(int eventChoice, int stateId) {
672       HashMap<Integer, ReadWriteSet> stateSummary = mainSummary.get(stateId);
673       return stateSummary.get(eventChoice);
674     }
675
676     public Set<Integer> getStateIds() {
677       return mainSummary.keySet();
678     }
679
680     private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
681       // Combine the same write accesses and record in the recordedRWSet
682       HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
683       HashMap<String, Integer> writeMap = rwSet.getWriteMap();
684       for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
685         String writeField = entry.getKey();
686         // Remove the entry from rwSet if both field and object ID are the same
687         if (writeMap.containsKey(writeField) &&
688                 (writeMap.get(writeField).equals(recordedWriteMap.get(writeField)))) {
689           writeMap.remove(writeField);
690         }
691       }
692       // Then add the rest (fields in rwSet but not in recordedRWSet)
693       // into the recorded map because these will be traversed
694       recordedWriteMap.putAll(writeMap);
695       // Combine the same read accesses and record in the recordedRWSet
696       HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
697       HashMap<String, Integer> readMap = rwSet.getReadMap();
698       for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
699         String readField = entry.getKey();
700         // Remove the entry from rwSet if both field and object ID are the same
701         if (readMap.containsKey(readField) &&
702                 (readMap.get(readField).equals(recordedReadMap.get(readField)))) {
703           readMap.remove(readField);
704         }
705       }
706       // Then add the rest (fields in rwSet but not in recordedRWSet)
707       // into the recorded map because these will be traversed
708       recordedReadMap.putAll(readMap);
709
710       return rwSet;
711     }
712
713     public ReadWriteSet updateStateSummary(int stateId, int eventChoice, ReadWriteSet rwSet) {
714       // If the state Id has not existed, insert the StateSummary object
715       // If the state Id has existed, find the event choice:
716       // 1) If the event choice has not existed, insert the ReadWriteSet object
717       // 2) If the event choice has existed, perform union between the two ReadWriteSet objects
718       if (!rwSet.isEmpty()) {
719         HashMap<Integer, ReadWriteSet> stateSummary;
720         if (!mainSummary.containsKey(stateId)) {
721           stateSummary = new HashMap<>();
722           stateSummary.put(eventChoice, rwSet.getCopy());
723           mainSummary.put(stateId, stateSummary);
724         } else {
725           stateSummary = mainSummary.get(stateId);
726           if (!stateSummary.containsKey(eventChoice)) {
727             stateSummary.put(eventChoice, rwSet.getCopy());
728           } else {
729             rwSet = performUnion(stateSummary.get(eventChoice), rwSet);
730           }
731         }
732       }
733       return rwSet;
734     }
735   }
736
737   // -- CONSTANTS
738   private final static String DO_CALL_METHOD = "doCall";
739   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
740   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
741   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
742           // Groovy library created fields
743           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
744           // Infrastructure
745           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
746           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
747   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
748           // Java and Groovy libraries
749           { "java", "org", "sun", "com", "gov", "groovy"};
750   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
751   private final static String GET_PROPERTY_METHOD =
752           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
753   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
754   private final static String JAVA_INTEGER = "int";
755   private final static String JAVA_STRING_LIB = "java.lang.String";
756
757   // -- FUNCTIONS
758   private Integer[] copyChoices(Integer[] choicesToCopy) {
759
760     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
761     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
762     return copyOfChoices;
763   }
764
765   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
766     // Check the next choice and if the value is not the same as the expected then force the expected value
767     int choiceIndex = choiceCounter % refChoices.length;
768     int nextChoice = icsCG.getNextChoice();
769     if (refChoices[choiceIndex] != nextChoice) {
770       int expectedChoice = refChoices[choiceIndex];
771       int currCGIndex = icsCG.getNextChoiceIndex();
772       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
773         icsCG.setChoice(currCGIndex, expectedChoice);
774       }
775     }
776     // Get state ID and associate it with this transition
777     int stateId = vm.getStateId();
778     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
779     // Add new transition to the current execution and map it in R-Graph
780     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
781       rGraph.addReachableTransition(stId, transition);
782     }
783     currentExecution.mapCGToChoice(icsCG, choiceCounter);
784     // Store restorable state object for this state (always store the latest)
785     if (!restorableStateMap.containsKey(stateId)) {
786       RestorableVMState restorableState = vm.getRestorableState();
787       restorableStateMap.put(stateId, restorableState);
788     }
789   }
790
791   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
792     // Get a new transition
793     TransitionEvent transition;
794     if (currentExecution.isNew()) {
795       // We need to handle the first transition differently because this has a predecessor execution
796       transition = currentExecution.getFirstTransition();
797     } else {
798       transition = new TransitionEvent();
799       currentExecution.addTransition(transition);
800       addPredecessors(stateId);
801     }
802     transition.setExecution(currentExecution);
803     transition.setTransitionCG(icsCG);
804     transition.setStateId(stateId);
805     transition.setChoice(refChoices[choiceIndex]);
806     transition.setChoiceCounter(choiceCounter);
807
808     return transition;
809   }
810
811   // --- Functions related to statistics counting
812   // Count unique state IDs
813   private void countUniqueStateId(int stateId, int nextChoiceValue) {
814     HashSet<Integer> events;
815     // Get the set of events
816     if (!stateToUniqueEventMap.containsKey(stateId)) {
817       events = new HashSet<>();
818       stateToUniqueEventMap.put(stateId, events);
819     } else {
820       events = stateToUniqueEventMap.get(stateId);
821     }
822     // Insert the event
823     if (!events.contains(nextChoiceValue)) {
824       events.add(nextChoiceValue);
825     }
826   }
827
828   // Summarize unique state IDs
829   private int summarizeUniqueTransitions() {
830     // Just count the set size of each of entry map and sum them up
831     int numOfUniqueTransitions = 0;
832     for (Map.Entry<Integer,HashSet<Integer>> entry : stateToUniqueEventMap.entrySet()) {
833       numOfUniqueTransitions = numOfUniqueTransitions + entry.getValue().size();
834     }
835
836     return numOfUniqueTransitions;
837   }
838
839   // --- Functions related to cycle detection and reachability graph
840
841   // Detect cycles in the current execution/trace
842   // We terminate the execution iff:
843   // (1) the state has been visited in the current execution
844   // (2) the state has one or more cycles that involve all the events
845   // With simple approach we only need to check for a re-visited state.
846   // Basically, we have to check that we have executed all events between two occurrences of such state.
847   private boolean completeFullCycle(int stId) {
848     // False if the state ID hasn't been recorded
849     if (!stateToEventMap.containsKey(stId)) {
850       return false;
851     }
852     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
853     // Check if this set contains all the event choices
854     // If not then this is not the terminating condition
855     for(int i=0; i<=maxEventChoice; i++) {
856       if (!visitedEvents.contains(i)) {
857         return false;
858       }
859     }
860     return true;
861   }
862
863   private void initializeStatesVariables() {
864     // DPOR-related
865     choices = null;
866     refChoices = null;
867     choiceCounter = 0;
868     maxEventChoice = 0;
869     // Cycle tracking
870     if (!isBooleanCGFlipped) {
871       currVisitedStates = new HashMap<>();
872       justVisitedStates = new HashSet<>();
873       prevVisitedStates = new HashSet<>();
874       stateToEventMap = new HashMap<>();
875     } else {
876       currVisitedStates.clear();
877       justVisitedStates.clear();
878       prevVisitedStates.clear();
879       stateToEventMap.clear();
880     }
881     // Backtracking
882     if (!isBooleanCGFlipped) {
883       backtrackMap = new HashMap<>();
884     } else {
885       backtrackMap.clear();
886     }
887     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
888     currentExecution = new Execution();
889     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
890     if (!isBooleanCGFlipped) {
891       doneBacktrackMap = new HashMap<>();
892     } else {
893       doneBacktrackMap.clear();
894     }
895     rGraph = new RGraph();
896     // Booleans
897     isEndOfExecution = false;
898   }
899
900   private void mapStateToEvent(int nextChoiceValue) {
901     // Update all states with this event/choice
902     // This means that all past states now see this transition
903     Set<Integer> stateSet = stateToEventMap.keySet();
904     for(Integer stateId : stateSet) {
905       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
906       eventSet.add(nextChoiceValue);
907     }
908   }
909
910   private boolean terminateCurrentExecution() {
911     // We need to check all the states that have just been visited
912     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
913     boolean terminate = false;
914     Set<Integer> mainStateIds = mainSummary.getStateIds();
915     for(Integer stateId : justVisitedStates) {
916       // We exclude states that are produced by other CGs that are not integer CG
917       // When we encounter these states, then we should also encounter the corresponding integer CG state ID
918       if (mainStateIds.contains(stateId)) {
919         // We perform updates on backtrack sets for every
920         if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
921           updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
922           terminate = true;
923         }
924         // If frequency > 1 then this means we have visited this stateId more than once in the current execution
925         if (currVisitedStates.containsKey(stateId) && currVisitedStates.get(stateId) > 1) {
926           updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
927         }
928       }
929     }
930     return terminate;
931   }
932
933   private void updateStateInfo(Search search) {
934     // Update the state variables
935     int stateId = search.getStateId();
936     // Insert state ID into the map if it is new
937     if (!stateToEventMap.containsKey(stateId)) {
938       HashSet<Integer> eventSet = new HashSet<>();
939       stateToEventMap.put(stateId, eventSet);
940     }
941     addPredecessorToRevisitedState(stateId);
942     justVisitedStates.add(stateId);
943     if (!prevVisitedStates.contains(stateId)) {
944       // It is a currently visited states if the state has not been seen in previous executions
945       int frequency = 0;
946       if (currVisitedStates.containsKey(stateId)) {
947         frequency = currVisitedStates.get(stateId);
948       }
949       currVisitedStates.put(stateId, frequency + 1);  // Increment frequency counter
950     }
951   }
952
953   // --- Functions related to Read/Write access analysis on shared fields
954
955   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
956     // Insert backtrack point to the right state ID
957     LinkedList<BacktrackExecution> backtrackExecList;
958     if (backtrackMap.containsKey(stateId)) {
959       backtrackExecList = backtrackMap.get(stateId);
960     } else {
961       backtrackExecList = new LinkedList<>();
962       backtrackMap.put(stateId, backtrackExecList);
963     }
964     // Add the new backtrack execution object
965     TransitionEvent backtrackTransition = new TransitionEvent();
966     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
967     // Add to priority queue
968     if (!backtrackStateQ.contains(stateId)) {
969       backtrackStateQ.add(stateId);
970     }
971   }
972
973   private void addPredecessors(int stateId) {
974     PredecessorInfo predecessorInfo;
975     if (!stateToPredInfo.containsKey(stateId)) {
976       predecessorInfo = new PredecessorInfo();
977       stateToPredInfo.put(stateId, predecessorInfo);
978     } else {  // This is a new state Id
979       predecessorInfo = stateToPredInfo.get(stateId);
980     }
981     predecessorInfo.recordPredecessor(currentExecution, choiceCounter - 1);
982   }
983
984   // Analyze Read/Write accesses that are directly invoked on fields
985   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
986     // Get the field info
987     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
988     // Analyze only after being initialized
989     String fieldClass = fieldInfo.getFullName();
990     // Do the analysis to get Read and Write accesses to fields
991     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
992     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
993     // Record the field in the map
994     if (executedInsn instanceof WriteInstruction) {
995       // We first check the non-relevant fields set
996       if (!nonRelevantFields.contains(fieldInfo)) {
997         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
998         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
999           if (fieldClass.startsWith(str)) {
1000             nonRelevantFields.add(fieldInfo);
1001             return;
1002           }
1003         }
1004       } else {
1005         // If we have this field in the non-relevant fields set then we return right away
1006         return;
1007       }
1008       rwSet.addWriteField(fieldClass, objectId);
1009     } else if (executedInsn instanceof ReadInstruction) {
1010       rwSet.addReadField(fieldClass, objectId);
1011     }
1012   }
1013
1014   // Analyze Read accesses that are indirect (performed through iterators)
1015   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
1016   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
1017     // Get method name
1018     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
1019     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
1020             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
1021       // Extract info from the stack frame
1022       StackFrame frame = ti.getTopFrame();
1023       int[] frameSlots = frame.getSlots();
1024       // Get the Groovy callsite library at index 0
1025       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
1026       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
1027         return;
1028       }
1029       // Get the iterated object whose property is accessed
1030       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
1031       if (eiAccessObj == null) {
1032         return;
1033       }
1034       // We exclude library classes (they start with java, org, etc.) and some more
1035       ClassInfo classInfo = eiAccessObj.getClassInfo();
1036       String objClassName = classInfo.getName();
1037       // Check if this class info is part of the non-relevant classes set already
1038       if (!nonRelevantClasses.contains(classInfo)) {
1039         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
1040                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
1041           nonRelevantClasses.add(classInfo);
1042           return;
1043         }
1044       } else {
1045         // If it is part of the non-relevant classes set then return immediately
1046         return;
1047       }
1048       // Extract fields from this object and put them into the read write
1049       int numOfFields = eiAccessObj.getNumberOfFields();
1050       for(int i=0; i<numOfFields; i++) {
1051         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
1052         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
1053           String fieldClass = fieldInfo.getFullName();
1054           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
1055           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
1056           // Record the field in the map
1057           rwSet.addReadField(fieldClass, objectId);
1058         }
1059       }
1060     }
1061   }
1062
1063   private int checkAndAdjustChoice(int currentChoice, VM vm) {
1064     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
1065     // for certain method calls in the infrastructure, e.g., eventSince()
1066     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
1067     // This is the main event CG
1068     if (currentCG instanceof IntIntervalGenerator) {
1069       // This is the interval CG used in device handlers
1070       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
1071       // Iterate until we find the IntChoiceFromSet CG
1072       while (!(parentCG instanceof IntChoiceFromSet)) {
1073         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
1074       }
1075       // Find the choice related to the IntIntervalGenerator CG from the map
1076       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
1077     }
1078     return currentChoice;
1079   }
1080
1081   private void createBacktrackingPoint(int eventChoice, Execution conflictExecution, int conflictChoice) {
1082     // Create a new list of choices for backtrack based on the current choice and conflicting event number
1083     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
1084     // for the original set {0, 1, 2, 3}
1085     
1086     // eventChoice represents the event/transaction that will be put into the backtracking set of
1087     // conflictExecution/conflictChoice
1088     Integer[] newChoiceList = new Integer[refChoices.length];
1089     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1090     int stateId = conflictTrace.get(conflictChoice).getStateId();
1091     // Check if this trace has been done from this state
1092     if (isTraceAlreadyConstructed(eventChoice, stateId)) {
1093       return;
1094     }
1095     // Put the conflicting event numbers first and reverse the order
1096     newChoiceList[0] = eventChoice;
1097     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
1098     for (int i = 0, j = 1; i < refChoices.length; i++) {
1099       if (refChoices[i] != newChoiceList[0]) {
1100         newChoiceList[j] = refChoices[i];
1101         j++;
1102       }
1103     }
1104     // Predecessor of the new backtrack point is the same as the conflict point's
1105     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
1106   }
1107
1108   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
1109     for (String excludedField : excludedStrings) {
1110       if (className.contains(excludedField)) {
1111         return true;
1112       }
1113     }
1114     return false;
1115   }
1116
1117   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
1118     for (String excludedField : excludedStrings) {
1119       if (className.endsWith(excludedField)) {
1120         return true;
1121       }
1122     }
1123     return false;
1124   }
1125
1126   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1127     for (String excludedField : excludedStrings) {
1128       if (className.startsWith(excludedField)) {
1129         return true;
1130       }
1131     }
1132     return false;
1133   }
1134
1135   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1136     // Check if we are reaching the end of our execution: no more backtracking points to explore
1137     // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1138     if (!backtrackStateQ.isEmpty()) {
1139       // Set done all the other backtrack points
1140       for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1141         backtrackTransition.getTransitionCG().setDone();
1142       }
1143       // Reset the next backtrack point with the latest state
1144       int hiStateId = backtrackStateQ.peek();
1145       // Restore the state first if necessary
1146       if (vm.getStateId() != hiStateId) {
1147         RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1148         vm.restoreState(restorableState);
1149       }
1150       // Set the backtrack CG
1151       IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1152       setBacktrackCG(hiStateId, backtrackCG);
1153     } else {
1154       // Set done this last CG (we save a few rounds)
1155       icsCG.setDone();
1156     }
1157     // Save all the visited states when starting a new execution of trace
1158     prevVisitedStates.addAll(currVisitedStates.keySet());
1159     // This marks a transitional period to the new CG
1160     isEndOfExecution = true;
1161   }
1162
1163   private boolean isConflictFound(int eventChoice, Execution conflictExecution, int conflictChoice,
1164                                   ReadWriteSet currRWSet) {
1165     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1166     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1167     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1168     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1169     if (!confRWFieldsMap.containsKey(conflictChoice) || eventChoice == conflictTrace.get(conflictChoice).getChoice()) {
1170       return false;
1171     }
1172     // R/W set of choice/event that may have a potential conflict
1173     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1174     // Check for conflicts with Read and Write fields for Write instructions
1175     Set<String> currWriteSet = currRWSet.getWriteSet();
1176     for(String writeField : currWriteSet) {
1177       int currObjId = currRWSet.writeFieldObjectId(writeField);
1178       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1179           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1180         // Remove this from the write set as we are tracking per memory location
1181         currRWSet.removeWriteField(writeField);
1182         return true;
1183       }
1184     }
1185     // Check for conflicts with Write fields for Read instructions
1186     Set<String> currReadSet = currRWSet.getReadSet();
1187     for(String readField : currReadSet) {
1188       int currObjId = currRWSet.readFieldObjectId(readField);
1189       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1190         // Remove this from the read set as we are tracking per memory location
1191         currRWSet.removeReadField(readField);
1192         return true;
1193       }
1194     }
1195     // Return false if no conflict is found
1196     return false;
1197   }
1198
1199   private boolean isFieldExcluded(Instruction executedInsn) {
1200     // Get the field info
1201     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1202     // Check if the non-relevant fields set already has it
1203     if (nonRelevantFields.contains(fieldInfo)) {
1204       return true;
1205     }
1206     // Check if the relevant fields set already has it
1207     if (relevantFields.contains(fieldInfo)) {
1208       return false;
1209     }
1210     // Analyze only after being initialized
1211     String field = fieldInfo.getFullName();
1212     // Check against "starts-with", "ends-with", and "contains" list
1213     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1214             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1215             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1216       nonRelevantFields.add(fieldInfo);
1217       return true;
1218     }
1219     relevantFields.add(fieldInfo);
1220     return false;
1221   }
1222
1223   // Check if this trace is already constructed
1224   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1225     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1226     // Check if the trace has been constructed as a backtrack point for this state
1227     // TODO: THIS IS AN OPTIMIZATION!
1228     HashSet<Integer> choiceSet;
1229     if (doneBacktrackMap.containsKey(stateId)) {
1230       choiceSet = doneBacktrackMap.get(stateId);
1231       if (choiceSet.contains(firstChoice)) {
1232         return true;
1233       }
1234     } else {
1235       choiceSet = new HashSet<>();
1236       doneBacktrackMap.put(stateId, choiceSet);
1237     }
1238     choiceSet.add(firstChoice);
1239
1240     return false;
1241   }
1242
1243   private HashSet<Predecessor> getPredecessors(int stateId) {
1244     // Get a set of predecessors for this state ID
1245     HashSet<Predecessor> predecessors;
1246     if (stateToPredInfo.containsKey(stateId)) {
1247       PredecessorInfo predecessorInfo = stateToPredInfo.get(stateId);
1248       predecessors = predecessorInfo.getPredecessors();
1249     } else {
1250       predecessors = new HashSet<>();
1251     }
1252
1253     return predecessors;
1254   }
1255
1256   private ReadWriteSet getReadWriteSet(int currentChoice) {
1257     // Do the analysis to get Read and Write accesses to fields
1258     ReadWriteSet rwSet;
1259     // We already have an entry
1260     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1261     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1262       rwSet = currReadWriteFieldsMap.get(currentChoice);
1263     } else { // We need to create a new entry
1264       rwSet = new ReadWriteSet();
1265       currReadWriteFieldsMap.put(currentChoice, rwSet);
1266     }
1267     return rwSet;
1268   }
1269
1270   // Reset data structure for each new execution
1271   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1272     if (choices == null || choices != icsCG.getAllChoices()) {
1273       // Reset state variables
1274       choiceCounter = 0;
1275       choices = icsCG.getAllChoices();
1276       refChoices = copyChoices(choices);
1277       // Clear data structures
1278       currVisitedStates.clear();
1279       stateToEventMap.clear();
1280       isEndOfExecution = false;
1281     }
1282   }
1283
1284   // Set a backtrack point for a particular state
1285   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1286     // Set a backtrack CG based on a state ID
1287     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1288     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1289     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1290     backtrackCG.setStateId(stateId);
1291     backtrackCG.reset();
1292     // Update current execution with this new execution
1293     Execution newExecution = new Execution();
1294     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1295     newExecution.addTransition(firstTransition);
1296     // Try to free some memory since this map is only used for the current execution
1297     currentExecution.clearCGToChoiceMap();
1298     currentExecution = newExecution;
1299     // Remove from the queue if we don't have more backtrack points for that state
1300     if (backtrackExecutions.isEmpty()) {
1301       backtrackMap.remove(stateId);
1302       backtrackStateQ.remove(stateId);
1303     }
1304   }
1305
1306   // Update backtrack sets
1307   // 1) recursively, and
1308   // 2) track accesses per memory location (per shared variable/field)
1309   private void updateBacktrackSet(Execution execution, int currentChoice) {
1310     // Copy ReadWriteSet object
1311     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1312     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1313     if (currRWSet == null) {
1314       return;
1315     }
1316     currRWSet = currRWSet.getCopy();
1317     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1318     HashSet<TransitionEvent> visited = new HashSet<>();
1319     // Conflict TransitionEvent is essentially the current TransitionEvent
1320     TransitionEvent confTrans = execution.getExecutionTrace().get(currentChoice);
1321     // Update backtrack set recursively
1322     updateBacktrackSetDFS(execution, currentChoice, confTrans.getChoice(), currRWSet, visited);
1323   }
1324
1325   private void updateBacktrackSetDFS(Execution execution, int currentChoice, int conflictEventChoice,
1326                                      ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1327     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1328     // Record this transition into the state summary of main summary
1329     currRWSet = mainSummary.updateStateSummary(currTrans.getStateId(), conflictEventChoice, currRWSet);
1330     // Halt when we have visited this transition (in a cycle)
1331     if (visited.contains(currTrans)) {
1332       return;
1333     }
1334     visited.add(currTrans);
1335     // Check the predecessors only if the set is not empty
1336     if (!currRWSet.isEmpty()) {
1337       // Explore all predecessors
1338       for (Predecessor predecessor : getPredecessors(currTrans.getStateId())) {
1339         // Get the predecessor (previous conflict choice)
1340         int predecessorChoice = predecessor.getChoice();
1341         Execution predecessorExecution = predecessor.getExecution();
1342         // Push up one happens-before transition
1343         int newConflictEventChoice = conflictEventChoice;
1344         // Check if a conflict is found
1345         ReadWriteSet newCurrRWSet = currRWSet.getCopy();
1346         if (isConflictFound(conflictEventChoice, predecessorExecution, predecessorChoice, newCurrRWSet)) {
1347           createBacktrackingPoint(conflictEventChoice, predecessorExecution, predecessorChoice);
1348           // We need to extract the pushed happens-before event choice from the predecessor execution and choice
1349           newConflictEventChoice = predecessorExecution.getExecutionTrace().get(predecessorChoice).getChoice();
1350         }
1351         // Continue performing DFS if conflict is not found
1352         updateBacktrackSetDFS(predecessorExecution, predecessorChoice, newConflictEventChoice,
1353                 newCurrRWSet, visited);
1354       }
1355     }
1356   }
1357
1358   // --- Functions related to the reachability analysis when there is a state match
1359
1360   private void addPredecessorToRevisitedState(int stateId) {
1361     // Perform this analysis only when:
1362     // 1) this is not during a switch to a new execution,
1363     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1364     // 3) state > 0 (state 0 is for boolean CG)
1365     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1366       if ((currVisitedStates.containsKey(stateId) && currVisitedStates.get(stateId) > 1) ||
1367               prevVisitedStates.contains(stateId)) {
1368         // Record a new predecessor for a revisited state
1369         addPredecessors(stateId);
1370       }
1371     }
1372   }
1373
1374   // Update the backtrack sets from previous executions
1375   private void updateBacktrackSetsFromGraph(int stateId, Execution currExecution, int currChoice) {
1376     // Get events/choices at this state ID
1377     Set<Integer> eventChoicesAtStateId = mainSummary.getEventChoicesAtStateId(stateId);
1378     for (Integer eventChoice : eventChoicesAtStateId) {
1379       // Get the ReadWriteSet object for this event at state ID
1380       ReadWriteSet rwSet = mainSummary.getRWSetForEventChoiceAtState(eventChoice, stateId).getCopy();
1381       // We have to first check for conflicts between the event and the current transition
1382       // Push up one happens-before transition
1383       int conflictEventChoice = eventChoice;
1384       if (isConflictFound(eventChoice, currExecution, currChoice, rwSet)) {
1385         createBacktrackingPoint(eventChoice, currExecution, currChoice);
1386         // We need to extract the pushed happens-before event choice from the predecessor execution and choice
1387         conflictEventChoice = currExecution.getExecutionTrace().get(currChoice).getChoice();
1388       }
1389       // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1390       HashSet<TransitionEvent> visited = new HashSet<>();
1391       // Update the backtrack sets recursively
1392       updateBacktrackSetDFS(currExecution, currChoice, conflictEventChoice, rwSet, visited);
1393     }
1394   }
1395 }