2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
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
10 * http://www.apache.org/licenses/LICENSE-2.0.
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.
18 package gov.nasa.jpf.listener;
20 import gov.nasa.jpf.Config;
21 import gov.nasa.jpf.JPF;
22 import gov.nasa.jpf.ListenerAdapter;
23 import gov.nasa.jpf.search.Search;
24 import gov.nasa.jpf.jvm.bytecode.*;
25 import gov.nasa.jpf.vm.*;
26 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
27 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
28 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
29 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
31 import java.io.FileWriter;
32 import java.io.PrintWriter;
34 import java.util.logging.Logger;
35 import java.io.IOException;
38 * This a DPOR implementation for event-driven applications with loops that create cycles of state matching
39 * In this new DPOR algorithm/implementation, each run is terminated iff:
40 * - we find a state that matches a state in a previous run, or
41 * - we have a matched state in the current run that consists of cycles that contain all choices/events.
43 public class DPORStateReducer extends ListenerAdapter {
45 // Information printout fields for verbose mode
46 private boolean verboseMode;
47 private boolean stateReductionMode;
48 private final PrintWriter out;
49 private PrintWriter fileWriter;
50 private String detail;
53 private Transition transition;
55 // DPOR-related fields
57 private Integer[] choices;
58 private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
59 private int choiceCounter;
60 private int maxEventChoice;
61 // Data structure to track the events seen by each state to track cycles (containing all events) for termination
62 private HashSet<Integer> currVisitedStates; // States being visited in the current execution
63 private HashSet<Integer> justVisitedStates; // States just visited in the previous choice/event
64 private HashSet<Integer> prevVisitedStates; // States visited in the previous execution
65 private HashSet<ClassInfo> nonRelevantClasses;// Class info objects of non-relevant classes
66 private HashSet<FieldInfo> nonRelevantFields; // Field info objects of non-relevant fields
67 private HashSet<FieldInfo> relevantFields; // Field info objects of relevant fields
68 private HashMap<Integer, HashSet<Integer>> stateToEventMap;
69 // Data structure to analyze field Read/Write accesses and conflicts
70 private HashMap<Integer, LinkedList<BacktrackExecution>> backtrackMap; // Track created backtracking points
71 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
72 private Execution currentExecution; // Holds the information about the current execution
73 private HashMap<Integer, HashSet<Integer>> doneBacktrackMap; // Record state ID and trace already constructed
74 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
75 private RGraph rGraph; // R-Graph for past executions
78 private boolean isBooleanCGFlipped;
79 private boolean isEndOfExecution;
82 private int numOfTransitions;
84 public DPORStateReducer(Config config, JPF jpf) {
85 verboseMode = config.getBoolean("printout_state_transition", false);
86 stateReductionMode = config.getBoolean("activate_state_reduction", true);
88 out = new PrintWriter(System.out, true);
92 String outputFile = config.getString("file_output");
93 if (!outputFile.isEmpty()) {
95 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
96 } catch (IOException e) {
99 isBooleanCGFlipped = false;
100 numOfTransitions = 0;
101 nonRelevantClasses = new HashSet<>();
102 nonRelevantFields = new HashSet<>();
103 relevantFields = new HashSet<>();
104 restorableStateMap = new HashMap<>();
105 initializeStatesVariables();
109 public void stateRestored(Search search) {
111 id = search.getStateId();
112 depth = search.getDepth();
113 transition = search.getTransition();
115 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
116 " and depth: " + depth + "\n");
121 public void searchStarted(Search search) {
123 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
128 public void stateAdvanced(Search search) {
130 id = search.getStateId();
131 depth = search.getDepth();
132 transition = search.getTransition();
133 if (search.isNewState()) {
139 if (search.isEndState()) {
140 out.println("\n==> DEBUG: This is the last state!\n");
143 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
144 " which is " + detail + " Transition: " + transition + "\n");
146 if (stateReductionMode) {
147 updateStateInfo(search);
152 public void stateBacktracked(Search search) {
154 id = search.getStateId();
155 depth = search.getDepth();
156 transition = search.getTransition();
159 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
160 " and depth: " + depth + "\n");
162 if (stateReductionMode) {
163 updateStateInfo(search);
167 static Logger log = JPF.getLogger("report");
170 public void searchFinished(Search search) {
172 out.println("\n==> DEBUG: ----------------------------------- search finished");
173 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
174 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
175 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
177 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
178 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
179 fileWriter.println();
185 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
186 if (stateReductionMode) {
187 // Initialize with necessary information from the CG
188 if (nextCG instanceof IntChoiceFromSet) {
189 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
190 // Tell JPF that we are performing DPOR
192 if (!isEndOfExecution) {
193 // Check if CG has been initialized, otherwise initialize it
194 Integer[] cgChoices = icsCG.getAllChoices();
195 // Record the events (from choices)
196 if (choices == null) {
198 // Make a copy of choices as reference
199 refChoices = copyChoices(choices);
200 // Record the max event choice (the last element of the choice array)
201 maxEventChoice = choices[choices.length - 1];
203 icsCG.setNewValues(choices);
205 // Use a modulo since choiceCounter is going to keep increasing
206 int choiceIndex = choiceCounter % choices.length;
207 icsCG.advance(choices[choiceIndex]);
209 // Set done all CGs while transitioning to a new execution
217 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
218 if (stateReductionMode) {
219 // Check the boolean CG and if it is flipped, we are resetting the analysis
220 if (currentCG instanceof BooleanChoiceGenerator) {
221 if (!isBooleanCGFlipped) {
222 isBooleanCGFlipped = true;
224 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
225 initializeStatesVariables();
228 // Check every choice generated and ensure fair scheduling!
229 if (currentCG instanceof IntChoiceFromSet) {
230 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
231 // If this is a new CG then we need to update data structures
232 resetStatesForNewExecution(icsCG, vm);
233 // If we don't see a fair scheduling of events/choices then we have to enforce it
234 ensureFairSchedulingAndSetupTransition(icsCG, vm);
235 // Update backtrack set of an executed event (transition): one transition before this one
236 updateBacktrackSet(currentExecution, choiceCounter - 1);
237 // Explore the next backtrack point:
238 // 1) if we have seen this state or this state contains cycles that involve all events, and
239 // 2) after the current CG is advanced at least once
240 if (terminateCurrentExecution() && choiceCounter > 0) {
241 exploreNextBacktrackPoints(vm, icsCG);
245 // Map state to event
246 mapStateToEvent(icsCG.getNextChoice());
247 justVisitedStates.clear();
256 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
257 if (stateReductionMode) {
258 if (!isEndOfExecution) {
259 // Has to be initialized and a integer CG
260 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
261 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
262 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
263 if (currentChoice < 0) { // If choice is -1 then skip
266 currentChoice = checkAndAdjustChoice(currentChoice, vm);
267 // Record accesses from executed instructions
268 if (executedInsn instanceof JVMFieldInstruction) {
269 // We don't care about libraries
270 if (!isFieldExcluded(executedInsn)) {
271 analyzeReadWriteAccesses(executedInsn, currentChoice);
273 } else if (executedInsn instanceof INVOKEINTERFACE) {
274 // Handle the read/write accesses that occur through iterators
275 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
287 // This class compactly stores backtrack execution:
288 // 1) backtrack choice list, and
289 // 2) first backtrack point (linking with predecessor execution)
290 private class BacktrackExecution {
291 private Integer[] choiceList;
292 private TransitionEvent firstTransition;
294 public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
295 choiceList = choList;
296 firstTransition = fTransition;
299 public Integer[] getChoiceList() {
303 public TransitionEvent getFirstTransition() {
304 return firstTransition;
308 // This class stores a representation of an execution
309 // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
310 // TODO: We basically need to keep track of:
311 // TODO: (1) last read/write access to each memory location
312 // TODO: (2) last state with two or more incoming events/transitions
313 private class Execution {
314 private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap; // Map between CG to choice numbers for O(1) access
315 private ArrayList<TransitionEvent> executionTrace; // The BacktrackPoint objects of this execution
316 private boolean isNew; // Track if this is the first time it is accessed
317 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
320 cgToChoiceMap = new HashMap<>();
321 executionTrace = new ArrayList<>();
323 readWriteFieldsMap = new HashMap<>();
326 public void addTransition(TransitionEvent newBacktrackPoint) {
327 executionTrace.add(newBacktrackPoint);
330 public void clearCGToChoiceMap() {
331 cgToChoiceMap = null;
334 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
335 return cgToChoiceMap.get(icsCG);
338 public ArrayList<TransitionEvent> getExecutionTrace() {
339 return executionTrace;
342 public TransitionEvent getFirstTransition() {
343 return executionTrace.get(0);
346 public TransitionEvent getLastTransition() {
347 return executionTrace.get(executionTrace.size() - 1);
350 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
351 return readWriteFieldsMap;
354 public boolean isNew() {
356 // Right after this is accessed, it is no longer new
363 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
364 cgToChoiceMap.put(icsCG, choice);
368 // This class compactly stores a predecessor
369 // 1) a predecessor execution
370 // 2) the predecessor choice in that predecessor execution
371 private class Predecessor {
372 private int choice; // Predecessor choice
373 private Execution execution; // Predecessor execution
375 public Predecessor(int predChoice, Execution predExec) {
377 execution = predExec;
380 public int getChoice() {
384 public Execution getExecution() {
389 // This class represents a R-Graph (in the paper it is a state transition graph R)
390 // This implementation stores reachable transitions from and connects with past executions
391 private class RGraph {
392 private int hiStateId; // Maximum state Id
393 private HashMap<Integer, HashSet<TransitionEvent>> graph; // Reachable transitions from past executions
397 graph = new HashMap<>();
400 public void addReachableTransition(int stateId, TransitionEvent transition) {
401 HashSet<TransitionEvent> transitionSet;
402 if (graph.containsKey(stateId)) {
403 transitionSet = graph.get(stateId);
405 transitionSet = new HashSet<>();
406 graph.put(stateId, transitionSet);
408 // Insert into the set if it does not contain it yet
409 if (!transitionSet.contains(transition)) {
410 transitionSet.add(transition);
412 // Update highest state ID
413 if (hiStateId < stateId) {
418 public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
419 if (!graph.containsKey(stateId)) {
420 // This is a loop from a transition to itself, so just return the current transition
421 HashSet<TransitionEvent> transitionSet = new HashSet<>();
422 transitionSet.add(currentExecution.getLastTransition());
423 return transitionSet;
425 return graph.get(stateId);
428 public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
429 HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
430 // All transitions from states higher than the given state ID (until the highest state ID) are reachable
431 for(int stId = stateId; stId <= hiStateId; stId++) {
432 // We might encounter state IDs from the first round of Boolean CG
433 // The second round of Boolean CG should consider these new states
434 if (graph.containsKey(stId)) {
435 reachableTransitions.addAll(graph.get(stId));
438 return reachableTransitions;
442 // This class compactly stores Read and Write field sets
443 // We store the field name and its object ID
444 // Sharing the same field means the same field name and object ID
445 private class ReadWriteSet {
446 private HashMap<String, Integer> readMap;
447 private HashMap<String, Integer> writeMap;
449 public ReadWriteSet() {
450 readMap = new HashMap<>();
451 writeMap = new HashMap<>();
454 public void addReadField(String field, int objectId) {
455 readMap.put(field, objectId);
458 public void addWriteField(String field, int objectId) {
459 writeMap.put(field, objectId);
462 public void removeReadField(String field) {
463 readMap.remove(field);
466 public void removeWriteField(String field) {
467 writeMap.remove(field);
470 public boolean isEmpty() {
471 return readMap.isEmpty() && writeMap.isEmpty();
474 public ReadWriteSet getCopy() {
475 ReadWriteSet copyRWSet = new ReadWriteSet();
476 // Copy the maps in the set into the new object copy
477 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
478 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
482 public Set<String> getReadSet() {
483 return readMap.keySet();
486 public Set<String> getWriteSet() {
487 return writeMap.keySet();
490 public boolean readFieldExists(String field) {
491 return readMap.containsKey(field);
494 public boolean writeFieldExists(String field) {
495 return writeMap.containsKey(field);
498 public int readFieldObjectId(String field) {
499 return readMap.get(field);
502 public int writeFieldObjectId(String field) {
503 return writeMap.get(field);
506 private HashMap<String, Integer> getReadMap() {
510 private HashMap<String, Integer> getWriteMap() {
514 private void setReadMap(HashMap<String, Integer> rMap) {
518 private void setWriteMap(HashMap<String, Integer> wMap) {
523 // This class compactly stores transitions:
527 // 4) predecessors (for backward DFS).
528 private class TransitionEvent {
529 private int choice; // Choice chosen at this transition
530 private int choiceCounter; // Choice counter at this transition
531 private Execution execution; // The execution where this transition belongs
532 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
533 private int stateId; // State at this transition
534 private IntChoiceFromSet transitionCG; // CG at this transition
536 public TransitionEvent() {
540 predecessors = new HashSet<>();
545 public int getChoice() {
549 public int getChoiceCounter() {
550 return choiceCounter;
553 public Execution getExecution() {
557 public HashSet<Predecessor> getPredecessors() {
561 public int getStateId() {
565 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
567 public void recordPredecessor(Execution execution, int choice) {
568 predecessors.add(new Predecessor(choice, execution));
571 public void setChoice(int cho) {
575 public void setChoiceCounter(int choCounter) {
576 choiceCounter = choCounter;
579 public void setExecution(Execution exec) {
583 public void setPredecessors(HashSet<Predecessor> preds) {
584 predecessors = new HashSet<>(preds);
587 public void setStateId(int stId) {
591 public void setTransitionCG(IntChoiceFromSet cg) {
597 private final static String DO_CALL_METHOD = "doCall";
598 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
599 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
600 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
601 // Groovy library created fields
602 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
604 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
605 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
606 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
607 // Java and Groovy libraries
608 { "java", "org", "sun", "com", "gov", "groovy"};
609 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
610 private final static String GET_PROPERTY_METHOD =
611 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
612 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
613 private final static String JAVA_INTEGER = "int";
614 private final static String JAVA_STRING_LIB = "java.lang.String";
617 private Integer[] copyChoices(Integer[] choicesToCopy) {
619 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
620 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
621 return copyOfChoices;
624 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
625 // Check the next choice and if the value is not the same as the expected then force the expected value
626 int choiceIndex = choiceCounter % refChoices.length;
627 int nextChoice = icsCG.getNextChoice();
628 if (refChoices[choiceIndex] != nextChoice) {
629 int expectedChoice = refChoices[choiceIndex];
630 int currCGIndex = icsCG.getNextChoiceIndex();
631 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
632 icsCG.setChoice(currCGIndex, expectedChoice);
635 // Get state ID and associate it with this transition
636 int stateId = vm.getStateId();
637 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
638 // Add new transition to the current execution and map it in R-Graph
639 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
640 rGraph.addReachableTransition(stId, transition);
642 currentExecution.mapCGToChoice(icsCG, choiceCounter);
643 // Store restorable state object for this state (always store the latest)
644 RestorableVMState restorableState = vm.getRestorableState();
645 restorableStateMap.put(stateId, restorableState);
648 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
649 // Get a new transition
650 TransitionEvent transition;
651 if (currentExecution.isNew()) {
652 // We need to handle the first transition differently because this has a predecessor execution
653 transition = currentExecution.getFirstTransition();
655 transition = new TransitionEvent();
656 currentExecution.addTransition(transition);
657 transition.recordPredecessor(currentExecution, choiceCounter - 1);
659 transition.setExecution(currentExecution);
660 transition.setTransitionCG(icsCG);
661 transition.setStateId(stateId);
662 transition.setChoice(refChoices[choiceIndex]);
663 transition.setChoiceCounter(choiceCounter);
668 // --- Functions related to cycle detection and reachability graph
670 // Detect cycles in the current execution/trace
671 // We terminate the execution iff:
672 // (1) the state has been visited in the current execution
673 // (2) the state has one or more cycles that involve all the events
674 // With simple approach we only need to check for a re-visited state.
675 // Basically, we have to check that we have executed all events between two occurrences of such state.
676 private boolean completeFullCycle(int stId) {
677 // False if the state ID hasn't been recorded
678 if (!stateToEventMap.containsKey(stId)) {
681 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
682 // Check if this set contains all the event choices
683 // If not then this is not the terminating condition
684 for(int i=0; i<=maxEventChoice; i++) {
685 if (!visitedEvents.contains(i)) {
692 private void initializeStatesVariables() {
699 currVisitedStates = new HashSet<>();
700 justVisitedStates = new HashSet<>();
701 prevVisitedStates = new HashSet<>();
702 stateToEventMap = new HashMap<>();
704 backtrackMap = new HashMap<>();
705 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
706 currentExecution = new Execution();
707 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
708 doneBacktrackMap = new HashMap<>();
709 rGraph = new RGraph();
711 isEndOfExecution = false;
714 private void mapStateToEvent(int nextChoiceValue) {
715 // Update all states with this event/choice
716 // This means that all past states now see this transition
717 Set<Integer> stateSet = stateToEventMap.keySet();
718 for(Integer stateId : stateSet) {
719 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
720 eventSet.add(nextChoiceValue);
724 private boolean terminateCurrentExecution() {
725 // We need to check all the states that have just been visited
726 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
727 for(Integer stateId : justVisitedStates) {
728 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
735 private void updateStateInfo(Search search) {
736 // Update the state variables
737 int stateId = search.getStateId();
738 // Insert state ID into the map if it is new
739 if (!stateToEventMap.containsKey(stateId)) {
740 HashSet<Integer> eventSet = new HashSet<>();
741 stateToEventMap.put(stateId, eventSet);
743 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
744 justVisitedStates.add(stateId);
745 if (!prevVisitedStates.contains(stateId)) {
746 // It is a currently visited states if the state has not been seen in previous executions
747 currVisitedStates.add(stateId);
751 // --- Functions related to Read/Write access analysis on shared fields
753 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
754 // Insert backtrack point to the right state ID
755 LinkedList<BacktrackExecution> backtrackExecList;
756 if (backtrackMap.containsKey(stateId)) {
757 backtrackExecList = backtrackMap.get(stateId);
759 backtrackExecList = new LinkedList<>();
760 backtrackMap.put(stateId, backtrackExecList);
762 // Add the new backtrack execution object
763 TransitionEvent backtrackTransition = new TransitionEvent();
764 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
765 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
766 // Add to priority queue
767 if (!backtrackStateQ.contains(stateId)) {
768 backtrackStateQ.add(stateId);
772 // Analyze Read/Write accesses that are directly invoked on fields
773 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
774 // Get the field info
775 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
776 // Analyze only after being initialized
777 String fieldClass = fieldInfo.getFullName();
778 // Do the analysis to get Read and Write accesses to fields
779 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
780 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
781 // Record the field in the map
782 if (executedInsn instanceof WriteInstruction) {
783 // We first check the non-relevant fields set
784 if (!nonRelevantFields.contains(fieldInfo)) {
785 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
786 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
787 if (fieldClass.startsWith(str)) {
788 nonRelevantFields.add(fieldInfo);
793 // If we have this field in the non-relevant fields set then we return right away
796 rwSet.addWriteField(fieldClass, objectId);
797 } else if (executedInsn instanceof ReadInstruction) {
798 rwSet.addReadField(fieldClass, objectId);
802 // Analyze Read accesses that are indirect (performed through iterators)
803 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
804 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
806 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
807 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
808 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
809 // Extract info from the stack frame
810 StackFrame frame = ti.getTopFrame();
811 int[] frameSlots = frame.getSlots();
812 // Get the Groovy callsite library at index 0
813 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
814 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
817 // Get the iterated object whose property is accessed
818 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
819 if (eiAccessObj == null) {
822 // We exclude library classes (they start with java, org, etc.) and some more
823 ClassInfo classInfo = eiAccessObj.getClassInfo();
824 String objClassName = classInfo.getName();
825 // Check if this class info is part of the non-relevant classes set already
826 if (!nonRelevantClasses.contains(classInfo)) {
827 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
828 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
829 nonRelevantClasses.add(classInfo);
833 // If it is part of the non-relevant classes set then return immediately
836 // Extract fields from this object and put them into the read write
837 int numOfFields = eiAccessObj.getNumberOfFields();
838 for(int i=0; i<numOfFields; i++) {
839 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
840 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
841 String fieldClass = fieldInfo.getFullName();
842 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
843 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
844 // Record the field in the map
845 rwSet.addReadField(fieldClass, objectId);
851 private int checkAndAdjustChoice(int currentChoice, VM vm) {
852 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
853 // for certain method calls in the infrastructure, e.g., eventSince()
854 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
855 // This is the main event CG
856 if (currentCG instanceof IntIntervalGenerator) {
857 // This is the interval CG used in device handlers
858 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
859 // Iterate until we find the IntChoiceFromSet CG
860 while (!(parentCG instanceof IntChoiceFromSet)) {
861 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
863 // Find the choice related to the IntIntervalGenerator CG from the map
864 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
866 return currentChoice;
869 private void createBacktrackingPoint(Execution execution, int currentChoice,
870 Execution conflictExecution, int conflictChoice) {
871 // Create a new list of choices for backtrack based on the current choice and conflicting event number
872 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
873 // for the original set {0, 1, 2, 3}
874 Integer[] newChoiceList = new Integer[refChoices.length];
875 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
876 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
877 int currChoice = currentTrace.get(currentChoice).getChoice();
878 int stateId = conflictTrace.get(conflictChoice).getStateId();
879 // Check if this trace has been done from this state
880 if (isTraceAlreadyConstructed(currChoice, stateId)) {
883 // Put the conflicting event numbers first and reverse the order
884 newChoiceList[0] = currChoice;
885 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
886 for (int i = 0, j = 1; i < refChoices.length; i++) {
887 if (refChoices[i] != newChoiceList[0]) {
888 newChoiceList[j] = refChoices[i];
892 // Predecessor of the new backtrack point is the same as the conflict point's
893 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
896 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
897 for (String excludedField : excludedStrings) {
898 if (className.contains(excludedField)) {
905 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
906 for (String excludedField : excludedStrings) {
907 if (className.endsWith(excludedField)) {
914 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
915 for (String excludedField : excludedStrings) {
916 if (className.startsWith(excludedField)) {
923 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
924 // Check if we are reaching the end of our execution: no more backtracking points to explore
925 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
926 if (!backtrackStateQ.isEmpty()) {
927 // Set done all the other backtrack points
928 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
929 backtrackTransition.getTransitionCG().setDone();
931 // Reset the next backtrack point with the latest state
932 int hiStateId = backtrackStateQ.peek();
933 // Restore the state first if necessary
934 if (vm.getStateId() != hiStateId) {
935 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
936 vm.restoreState(restorableState);
938 // Set the backtrack CG
939 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
940 setBacktrackCG(hiStateId, backtrackCG);
942 // Set done this last CG (we save a few rounds)
945 // Save all the visited states when starting a new execution of trace
946 prevVisitedStates.addAll(currVisitedStates);
947 // This marks a transitional period to the new CG
948 isEndOfExecution = true;
951 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
952 ReadWriteSet currRWSet) {
953 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
954 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
955 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
956 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
957 if (!confRWFieldsMap.containsKey(conflictChoice) ||
958 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
961 // R/W set of choice/event that may have a potential conflict
962 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
963 // Check for conflicts with Read and Write fields for Write instructions
964 Set<String> currWriteSet = currRWSet.getWriteSet();
965 for(String writeField : currWriteSet) {
966 int currObjId = currRWSet.writeFieldObjectId(writeField);
967 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
968 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
969 // Remove this from the write set as we are tracking per memory location
970 currRWSet.removeWriteField(writeField);
974 // Check for conflicts with Write fields for Read instructions
975 Set<String> currReadSet = currRWSet.getReadSet();
976 for(String readField : currReadSet) {
977 int currObjId = currRWSet.readFieldObjectId(readField);
978 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
979 // Remove this from the read set as we are tracking per memory location
980 currRWSet.removeReadField(readField);
984 // Return false if no conflict is found
988 private ReadWriteSet getReadWriteSet(int currentChoice) {
989 // Do the analysis to get Read and Write accesses to fields
991 // We already have an entry
992 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
993 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
994 rwSet = currReadWriteFieldsMap.get(currentChoice);
995 } else { // We need to create a new entry
996 rwSet = new ReadWriteSet();
997 currReadWriteFieldsMap.put(currentChoice, rwSet);
1002 private boolean isFieldExcluded(Instruction executedInsn) {
1003 // Get the field info
1004 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1005 // Check if the non-relevant fields set already has it
1006 if (nonRelevantFields.contains(fieldInfo)) {
1009 // Check if the relevant fields set already has it
1010 if (relevantFields.contains(fieldInfo)) {
1013 // Analyze only after being initialized
1014 String field = fieldInfo.getFullName();
1015 // Check against "starts-with", "ends-with", and "contains" list
1016 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1017 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1018 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1019 nonRelevantFields.add(fieldInfo);
1022 relevantFields.add(fieldInfo);
1026 // Check if this trace is already constructed
1027 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1028 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1029 // Check if the trace has been constructed as a backtrack point for this state
1030 // TODO: THIS IS AN OPTIMIZATION!
1031 HashSet<Integer> choiceSet;
1032 if (doneBacktrackMap.containsKey(stateId)) {
1033 choiceSet = doneBacktrackMap.get(stateId);
1034 if (choiceSet.contains(firstChoice)) {
1038 choiceSet = new HashSet<>();
1039 choiceSet.add(firstChoice);
1040 doneBacktrackMap.put(stateId, choiceSet);
1046 // Reset data structure for each new execution
1047 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1048 if (choices == null || choices != icsCG.getAllChoices()) {
1049 // Reset state variables
1051 choices = icsCG.getAllChoices();
1052 refChoices = copyChoices(choices);
1053 // Clear data structures
1054 currVisitedStates = new HashSet<>();
1055 stateToEventMap = new HashMap<>();
1056 isEndOfExecution = false;
1060 // Set a backtrack point for a particular state
1061 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1062 // Set a backtrack CG based on a state ID
1063 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1064 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1065 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1066 backtrackCG.setStateId(stateId);
1067 backtrackCG.reset();
1068 // Update current execution with this new execution
1069 Execution newExecution = new Execution();
1070 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1071 newExecution.addTransition(firstTransition);
1072 // Try to free some memory since this map is only used for the current execution
1073 currentExecution.clearCGToChoiceMap();
1074 currentExecution = newExecution;
1075 // Remove from the queue if we don't have more backtrack points for that state
1076 if (backtrackExecutions.isEmpty()) {
1077 backtrackMap.remove(stateId);
1078 backtrackStateQ.remove(stateId);
1082 // Update backtrack sets
1083 // 1) recursively, and
1084 // 2) track accesses per memory location (per shared variable/field)
1085 private void updateBacktrackSet(Execution execution, int currentChoice) {
1086 // Copy ReadWriteSet object
1087 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1088 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1089 if (currRWSet == null) {
1092 currRWSet = currRWSet.getCopy();
1093 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1094 HashSet<TransitionEvent> visited = new HashSet<>();
1095 // Update backtrack set recursively
1096 // TODO: The following is the call to the original version of the method
1097 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1098 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1099 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1102 // TODO: This is the original version of the recursive method
1103 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1104 // Execution conflictExecution, int conflictChoice,
1105 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1106 // // Halt when we have found the first read/write conflicts for all memory locations
1107 // if (currRWSet.isEmpty()) {
1110 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1111 // // Halt when we have visited this transition (in a cycle)
1112 // if (visited.contains(confTrans)) {
1115 // visited.add(confTrans);
1116 // // Explore all predecessors
1117 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1118 // // Get the predecessor (previous conflict choice)
1119 // conflictChoice = predecessor.getChoice();
1120 // conflictExecution = predecessor.getExecution();
1121 // // Check if a conflict is found
1122 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1123 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1125 // // Continue performing DFS if conflict is not found
1126 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1130 // TODO: This is the version of the method with pushing up happens-before transitions
1131 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1132 Execution conflictExecution, int conflictChoice,
1133 Execution hbExecution, int hbChoice,
1134 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1135 // Halt when we have found the first read/write conflicts for all memory locations
1136 if (currRWSet.isEmpty()) {
1139 TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1140 // Halt when we have visited this transition (in a cycle)
1141 if (visited.contains(confTrans)) {
1144 visited.add(confTrans);
1145 // Explore all predecessors
1146 for (Predecessor predecessor : confTrans.getPredecessors()) {
1147 // Get the predecessor (previous conflict choice)
1148 conflictChoice = predecessor.getChoice();
1149 conflictExecution = predecessor.getExecution();
1150 // Push up one happens-before transition
1151 int pushedChoice = hbChoice;
1152 Execution pushedExecution = hbExecution;
1153 // Check if a conflict is found
1154 if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1155 createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1156 pushedChoice = conflictChoice;
1157 pushedExecution = conflictExecution;
1159 // Continue performing DFS if conflict is not found
1160 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1161 pushedExecution, pushedChoice, currRWSet, visited);
1163 // Remove the transition after being explored
1164 // TODO: Seems to cause a lot of loops---commented out for now
1165 //visited.remove(confTrans);
1168 // --- Functions related to the reachability analysis when there is a state match
1170 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1171 // Perform this analysis only when:
1172 // 1) this is not during a switch to a new execution,
1173 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1174 // 3) state > 0 (state 0 is for boolean CG)
1175 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1176 if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1177 // Update reachable transitions in the graph with a predecessor
1178 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1179 for(TransitionEvent transition : reachableTransitions) {
1180 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1182 updateBacktrackSetsFromPreviousExecution(stateId);
1187 // Update the backtrack sets from previous executions
1188 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1189 // Collect all the reachable transitions from R-Graph
1190 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1191 for(TransitionEvent transition : reachableTransitions) {
1192 Execution execution = transition.getExecution();
1193 int currentChoice = transition.getChoiceCounter();
1194 updateBacktrackSet(execution, currentChoice);