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