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