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.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;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.PrintWriter;
36 import java.util.logging.Logger;
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.
44 public class DPORStateReducerEfficient extends ListenerAdapter {
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;
54 private Transition transition;
56 // DPOR-related fields
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
79 private boolean isBooleanCGFlipped;
80 private boolean isEndOfExecution;
83 private int numOfTransitions;
85 public DPORStateReducerEfficient(Config config, JPF jpf) {
86 verboseMode = config.getBoolean("printout_state_transition", false);
87 stateReductionMode = config.getBoolean("activate_state_reduction", true);
89 out = new PrintWriter(System.out, true);
93 String outputFile = config.getString("file_output");
94 if (!outputFile.isEmpty()) {
96 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
97 } catch (IOException e) {
100 isBooleanCGFlipped = false;
101 numOfTransitions = 0;
102 nonRelevantClasses = new HashSet<>();
103 nonRelevantFields = new HashSet<>();
104 relevantFields = new HashSet<>();
105 restorableStateMap = new HashMap<>();
106 initializeStatesVariables();
110 public void stateRestored(Search search) {
112 id = search.getStateId();
113 depth = search.getDepth();
114 transition = search.getTransition();
116 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
117 " and depth: " + depth + "\n");
122 public void searchStarted(Search search) {
124 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
129 public void stateAdvanced(Search search) {
131 id = search.getStateId();
132 depth = search.getDepth();
133 transition = search.getTransition();
134 if (search.isNewState()) {
140 if (search.isEndState()) {
141 out.println("\n==> DEBUG: This is the last state!\n");
144 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
145 " which is " + detail + " Transition: " + transition + "\n");
147 if (stateReductionMode) {
148 updateStateInfo(search);
153 public void stateBacktracked(Search search) {
155 id = search.getStateId();
156 depth = search.getDepth();
157 transition = search.getTransition();
160 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
161 " and depth: " + depth + "\n");
163 if (stateReductionMode) {
164 updateStateInfo(search);
168 static Logger log = JPF.getLogger("report");
171 public void searchFinished(Search search) {
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");
178 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
179 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
180 fileWriter.println();
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
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) {
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];
204 icsCG.setNewValues(choices);
206 // Use a modulo since choiceCounter is going to keep increasing
207 int choiceIndex = choiceCounter % choices.length;
208 icsCG.advance(choices[choiceIndex]);
210 // Set done all CGs while transitioning to a new execution
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;
225 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
226 initializeStatesVariables();
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);
246 // Map state to event
247 mapStateToEvent(icsCG.getNextChoice());
248 justVisitedStates.clear();
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
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);
274 } else if (executedInsn instanceof INVOKEINTERFACE) {
275 // Handle the read/write accesses that occur through iterators
276 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
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;
295 public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
296 choiceList = choList;
297 firstTransition = fTransition;
300 public Integer[] getChoiceList() {
304 public TransitionEvent getFirstTransition() {
305 return firstTransition;
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
321 cgToChoiceMap = new HashMap<>();
322 executionTrace = new ArrayList<>();
324 readWriteFieldsMap = new HashMap<>();
327 public void addTransition(TransitionEvent newBacktrackPoint) {
328 executionTrace.add(newBacktrackPoint);
331 public void clearCGToChoiceMap() {
332 cgToChoiceMap = null;
335 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
336 return cgToChoiceMap.get(icsCG);
339 public ArrayList<TransitionEvent> getExecutionTrace() {
340 return executionTrace;
343 public TransitionEvent getFirstTransition() {
344 return executionTrace.get(0);
347 public TransitionEvent getLastTransition() {
348 return executionTrace.get(executionTrace.size() - 1);
351 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
352 return readWriteFieldsMap;
355 public boolean isNew() {
357 // Right after this is accessed, it is no longer new
364 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
365 cgToChoiceMap.put(icsCG, choice);
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
376 public Predecessor(int predChoice, Execution predExec) {
378 execution = predExec;
381 public int getChoice() {
385 public Execution getExecution() {
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;
400 graph = new HashMap<>();
401 graphSummary = new HashMap<>();
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);
410 transitionSet = new HashSet<>();
411 graph.put(stateId, transitionSet);
413 // Insert into the set if it does not contain it yet
414 if (!transitionSet.contains(transition)) {
415 transitionSet.add(transition);
417 // Update highest state ID
418 if (hiStateId < stateId) {
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;
430 return graph.get(stateId);
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));
443 return reachableTransitions;
446 public HashMap<Integer, SummaryNode> getReachableTransitionsSummary(int stateId) {
447 return graphSummary.get(stateId);
450 private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
451 // Combine the same write accesses and record in the recordedRWSet
452 HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
453 HashMap<String, Integer> writeMap = rwSet.getWriteMap();
454 for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
455 String writeField = entry.getKey();
456 // Remove the entry from rwSet if both field and object ID are the same
457 if (writeMap.containsKey(writeField) &&
458 (writeMap.get(writeField) == recordedWriteMap.get(writeField))) {
459 writeMap.remove(writeField);
462 // Then add everything into the recorded map because these will be traversed
463 recordedWriteMap.putAll(writeMap);
464 // Combine the same read accesses and record in the recordedRWSet
465 HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
466 HashMap<String, Integer> readMap = rwSet.getReadMap();
467 for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
468 String readField = entry.getKey();
469 // Remove the entry from rwSet if both field and object ID are the same
470 if (readMap.containsKey(readField) &&
471 (readMap.get(readField) == recordedReadMap.get(readField))) {
472 readMap.remove(readField);
475 // Then add everything into the recorded map because these will be traversed
476 recordedReadMap.putAll(readMap);
481 public ReadWriteSet recordTransitionSummary(int stateId, TransitionEvent transition, ReadWriteSet rwSet) {
482 // Record transition into graphSummary
483 // TransitionMap maps event (choice) number to a R/W set
484 HashMap<Integer, SummaryNode> transitionSummary;
485 if (graphSummary.containsKey(stateId)) {
486 transitionSummary = graphSummary.get(stateId);
488 transitionSummary = new HashMap<>();
489 graphSummary.put(stateId, transitionSummary);
491 int choice = transition.getChoice();
492 SummaryNode summaryNode;
493 // Insert transition into the map if we haven't had this event number recorded
494 if (!transitionSummary.containsKey(choice)) {
495 summaryNode = new SummaryNode(transition, rwSet.getCopy());
496 transitionSummary.put(choice, summaryNode);
498 summaryNode = transitionSummary.get(choice);
499 // Perform union and subtraction between the recorded and the given R/W sets
500 rwSet = performUnion(summaryNode.getReadWriteSet(), rwSet);
506 // This class compactly stores Read and Write field sets
507 // We store the field name and its object ID
508 // Sharing the same field means the same field name and object ID
509 private class ReadWriteSet {
510 private HashMap<String, Integer> readMap;
511 private HashMap<String, Integer> writeMap;
513 public ReadWriteSet() {
514 readMap = new HashMap<>();
515 writeMap = new HashMap<>();
518 public void addReadField(String field, int objectId) {
519 readMap.put(field, objectId);
522 public void addWriteField(String field, int objectId) {
523 writeMap.put(field, objectId);
526 public void removeReadField(String field) {
527 readMap.remove(field);
530 public void removeWriteField(String field) {
531 writeMap.remove(field);
534 public boolean isEmpty() {
535 return readMap.isEmpty() && writeMap.isEmpty();
538 public ReadWriteSet getCopy() {
539 ReadWriteSet copyRWSet = new ReadWriteSet();
540 // Copy the maps in the set into the new object copy
541 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
542 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
546 public Set<String> getReadSet() {
547 return readMap.keySet();
550 public Set<String> getWriteSet() {
551 return writeMap.keySet();
554 public boolean readFieldExists(String field) {
555 return readMap.containsKey(field);
558 public boolean writeFieldExists(String field) {
559 return writeMap.containsKey(field);
562 public int readFieldObjectId(String field) {
563 return readMap.get(field);
566 public int writeFieldObjectId(String field) {
567 return writeMap.get(field);
570 private HashMap<String, Integer> getReadMap() {
574 private HashMap<String, Integer> getWriteMap() {
578 private void setReadMap(HashMap<String, Integer> rMap) {
582 private void setWriteMap(HashMap<String, Integer> wMap) {
587 // This class provides a data structure to store TransitionEvent and ReadWriteSet for a summary
588 private class SummaryNode {
589 private TransitionEvent transitionEvent;
590 private ReadWriteSet readWriteSet;
592 public SummaryNode(TransitionEvent transEvent, ReadWriteSet rwSet) {
593 transitionEvent = transEvent;
594 readWriteSet = rwSet;
597 public TransitionEvent getTransitionEvent() {
598 return transitionEvent;
601 public ReadWriteSet getReadWriteSet() {
606 // This class compactly stores transitions:
610 // 4) predecessors (for backward DFS).
611 private class TransitionEvent {
612 private int choice; // Choice chosen at this transition
613 private int choiceCounter; // Choice counter at this transition
614 private Execution execution; // The execution where this transition belongs
615 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
616 private int stateId; // State at this transition
617 private IntChoiceFromSet transitionCG; // CG at this transition
619 public TransitionEvent() {
623 predecessors = new HashSet<>();
628 public int getChoice() {
632 public int getChoiceCounter() {
633 return choiceCounter;
636 public Execution getExecution() {
640 public HashSet<Predecessor> getPredecessors() {
644 public int getStateId() {
648 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
650 public void recordPredecessor(Execution execution, int choice) {
651 predecessors.add(new Predecessor(choice, execution));
654 public void setChoice(int cho) {
658 public void setChoiceCounter(int choCounter) {
659 choiceCounter = choCounter;
662 public void setExecution(Execution exec) {
666 public void setPredecessors(HashSet<Predecessor> preds) {
667 predecessors = new HashSet<>(preds);
670 public void setStateId(int stId) {
674 public void setTransitionCG(IntChoiceFromSet cg) {
680 private final static String DO_CALL_METHOD = "doCall";
681 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
682 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
683 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
684 // Groovy library created fields
685 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
687 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
688 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
689 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
690 // Java and Groovy libraries
691 { "java", "org", "sun", "com", "gov", "groovy"};
692 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
693 private final static String GET_PROPERTY_METHOD =
694 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
695 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
696 private final static String JAVA_INTEGER = "int";
697 private final static String JAVA_STRING_LIB = "java.lang.String";
700 private Integer[] copyChoices(Integer[] choicesToCopy) {
702 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
703 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
704 return copyOfChoices;
707 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
708 // Check the next choice and if the value is not the same as the expected then force the expected value
709 int choiceIndex = choiceCounter % refChoices.length;
710 int nextChoice = icsCG.getNextChoice();
711 if (refChoices[choiceIndex] != nextChoice) {
712 int expectedChoice = refChoices[choiceIndex];
713 int currCGIndex = icsCG.getNextChoiceIndex();
714 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
715 icsCG.setChoice(currCGIndex, expectedChoice);
718 // Get state ID and associate it with this transition
719 int stateId = vm.getStateId();
720 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
721 // Add new transition to the current execution and map it in R-Graph
722 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
723 rGraph.addReachableTransition(stId, transition);
725 currentExecution.mapCGToChoice(icsCG, choiceCounter);
726 // Store restorable state object for this state (always store the latest)
727 if (!restorableStateMap.containsKey(stateId)) {
728 RestorableVMState restorableState = vm.getRestorableState();
729 restorableStateMap.put(stateId, restorableState);
733 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
734 // Get a new transition
735 TransitionEvent transition;
736 if (currentExecution.isNew()) {
737 // We need to handle the first transition differently because this has a predecessor execution
738 transition = currentExecution.getFirstTransition();
740 transition = new TransitionEvent();
741 currentExecution.addTransition(transition);
742 transition.recordPredecessor(currentExecution, choiceCounter - 1);
744 transition.setExecution(currentExecution);
745 transition.setTransitionCG(icsCG);
746 transition.setStateId(stateId);
747 transition.setChoice(refChoices[choiceIndex]);
748 transition.setChoiceCounter(choiceCounter);
753 // --- Functions related to cycle detection and reachability graph
755 // Detect cycles in the current execution/trace
756 // We terminate the execution iff:
757 // (1) the state has been visited in the current execution
758 // (2) the state has one or more cycles that involve all the events
759 // With simple approach we only need to check for a re-visited state.
760 // Basically, we have to check that we have executed all events between two occurrences of such state.
761 private boolean completeFullCycle(int stId) {
762 // False if the state ID hasn't been recorded
763 if (!stateToEventMap.containsKey(stId)) {
766 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
767 // Check if this set contains all the event choices
768 // If not then this is not the terminating condition
769 for(int i=0; i<=maxEventChoice; i++) {
770 if (!visitedEvents.contains(i)) {
777 private void initializeStatesVariables() {
784 currVisitedStates = new HashSet<>();
785 justVisitedStates = new HashSet<>();
786 prevVisitedStates = new HashSet<>();
787 stateToEventMap = new HashMap<>();
789 backtrackMap = new HashMap<>();
790 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
791 currentExecution = new Execution();
792 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
793 doneBacktrackMap = new HashMap<>();
794 rGraph = new RGraph();
796 isEndOfExecution = false;
799 private void mapStateToEvent(int nextChoiceValue) {
800 // Update all states with this event/choice
801 // This means that all past states now see this transition
802 Set<Integer> stateSet = stateToEventMap.keySet();
803 for(Integer stateId : stateSet) {
804 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
805 eventSet.add(nextChoiceValue);
809 private boolean terminateCurrentExecution() {
810 // We need to check all the states that have just been visited
811 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
812 for(Integer stateId : justVisitedStates) {
813 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
820 private void updateStateInfo(Search search) {
821 // Update the state variables
822 int stateId = search.getStateId();
823 // Insert state ID into the map if it is new
824 if (!stateToEventMap.containsKey(stateId)) {
825 HashSet<Integer> eventSet = new HashSet<>();
826 stateToEventMap.put(stateId, eventSet);
828 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
829 justVisitedStates.add(stateId);
830 if (!prevVisitedStates.contains(stateId)) {
831 // It is a currently visited states if the state has not been seen in previous executions
832 currVisitedStates.add(stateId);
836 // --- Functions related to Read/Write access analysis on shared fields
838 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
839 // Insert backtrack point to the right state ID
840 LinkedList<BacktrackExecution> backtrackExecList;
841 if (backtrackMap.containsKey(stateId)) {
842 backtrackExecList = backtrackMap.get(stateId);
844 backtrackExecList = new LinkedList<>();
845 backtrackMap.put(stateId, backtrackExecList);
847 // Add the new backtrack execution object
848 TransitionEvent backtrackTransition = new TransitionEvent();
849 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
850 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
851 // Add to priority queue
852 if (!backtrackStateQ.contains(stateId)) {
853 backtrackStateQ.add(stateId);
857 // Analyze Read/Write accesses that are directly invoked on fields
858 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
859 // Get the field info
860 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
861 // Analyze only after being initialized
862 String fieldClass = fieldInfo.getFullName();
863 // Do the analysis to get Read and Write accesses to fields
864 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
865 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
866 // Record the field in the map
867 if (executedInsn instanceof WriteInstruction) {
868 // We first check the non-relevant fields set
869 if (!nonRelevantFields.contains(fieldInfo)) {
870 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
871 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
872 if (fieldClass.startsWith(str)) {
873 nonRelevantFields.add(fieldInfo);
878 // If we have this field in the non-relevant fields set then we return right away
881 rwSet.addWriteField(fieldClass, objectId);
882 } else if (executedInsn instanceof ReadInstruction) {
883 rwSet.addReadField(fieldClass, objectId);
887 // Analyze Read accesses that are indirect (performed through iterators)
888 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
889 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
891 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
892 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
893 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
894 // Extract info from the stack frame
895 StackFrame frame = ti.getTopFrame();
896 int[] frameSlots = frame.getSlots();
897 // Get the Groovy callsite library at index 0
898 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
899 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
902 // Get the iterated object whose property is accessed
903 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
904 if (eiAccessObj == null) {
907 // We exclude library classes (they start with java, org, etc.) and some more
908 ClassInfo classInfo = eiAccessObj.getClassInfo();
909 String objClassName = classInfo.getName();
910 // Check if this class info is part of the non-relevant classes set already
911 if (!nonRelevantClasses.contains(classInfo)) {
912 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
913 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
914 nonRelevantClasses.add(classInfo);
918 // If it is part of the non-relevant classes set then return immediately
921 // Extract fields from this object and put them into the read write
922 int numOfFields = eiAccessObj.getNumberOfFields();
923 for(int i=0; i<numOfFields; i++) {
924 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
925 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
926 String fieldClass = fieldInfo.getFullName();
927 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
928 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
929 // Record the field in the map
930 rwSet.addReadField(fieldClass, objectId);
936 private int checkAndAdjustChoice(int currentChoice, VM vm) {
937 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
938 // for certain method calls in the infrastructure, e.g., eventSince()
939 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
940 // This is the main event CG
941 if (currentCG instanceof IntIntervalGenerator) {
942 // This is the interval CG used in device handlers
943 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
944 // Iterate until we find the IntChoiceFromSet CG
945 while (!(parentCG instanceof IntChoiceFromSet)) {
946 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
948 // Find the choice related to the IntIntervalGenerator CG from the map
949 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
951 return currentChoice;
954 private void createBacktrackingPoint(Execution execution, int currentChoice,
955 Execution conflictExecution, int conflictChoice) {
956 // Create a new list of choices for backtrack based on the current choice and conflicting event number
957 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
958 // for the original set {0, 1, 2, 3}
960 // execution/currentChoice represent the event/transaction that will be put into the backtracking set of
961 // conflictExecution/conflictChoice
962 Integer[] newChoiceList = new Integer[refChoices.length];
963 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
964 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
965 int currChoice = currentTrace.get(currentChoice).getChoice();
966 int stateId = conflictTrace.get(conflictChoice).getStateId();
967 // Check if this trace has been done from this state
968 if (isTraceAlreadyConstructed(currChoice, stateId)) {
971 // Put the conflicting event numbers first and reverse the order
972 newChoiceList[0] = currChoice;
973 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
974 for (int i = 0, j = 1; i < refChoices.length; i++) {
975 if (refChoices[i] != newChoiceList[0]) {
976 newChoiceList[j] = refChoices[i];
980 // Predecessor of the new backtrack point is the same as the conflict point's
981 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
984 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
985 for (String excludedField : excludedStrings) {
986 if (className.contains(excludedField)) {
993 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
994 for (String excludedField : excludedStrings) {
995 if (className.endsWith(excludedField)) {
1002 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1003 for (String excludedField : excludedStrings) {
1004 if (className.startsWith(excludedField)) {
1011 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1012 // Check if we are reaching the end of our execution: no more backtracking points to explore
1013 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1014 if (!backtrackStateQ.isEmpty()) {
1015 // Set done all the other backtrack points
1016 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1017 backtrackTransition.getTransitionCG().setDone();
1019 // Reset the next backtrack point with the latest state
1020 int hiStateId = backtrackStateQ.peek();
1021 // Restore the state first if necessary
1022 if (vm.getStateId() != hiStateId) {
1023 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1024 vm.restoreState(restorableState);
1026 // Set the backtrack CG
1027 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1028 setBacktrackCG(hiStateId, backtrackCG);
1030 // Set done this last CG (we save a few rounds)
1033 // Save all the visited states when starting a new execution of trace
1034 prevVisitedStates.addAll(currVisitedStates);
1035 // This marks a transitional period to the new CG
1036 isEndOfExecution = true;
1039 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
1040 ReadWriteSet currRWSet) {
1041 // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1042 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
1043 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1044 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1045 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1046 if (!confRWFieldsMap.containsKey(conflictChoice) ||
1047 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
1050 // R/W set of choice/event that may have a potential conflict
1051 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1052 // Check for conflicts with Read and Write fields for Write instructions
1053 Set<String> currWriteSet = currRWSet.getWriteSet();
1054 for(String writeField : currWriteSet) {
1055 int currObjId = currRWSet.writeFieldObjectId(writeField);
1056 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1057 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1058 // Remove this from the write set as we are tracking per memory location
1059 currRWSet.removeWriteField(writeField);
1063 // Check for conflicts with Write fields for Read instructions
1064 Set<String> currReadSet = currRWSet.getReadSet();
1065 for(String readField : currReadSet) {
1066 int currObjId = currRWSet.readFieldObjectId(readField);
1067 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1068 // Remove this from the read set as we are tracking per memory location
1069 currRWSet.removeReadField(readField);
1073 // Return false if no conflict is found
1077 private ReadWriteSet getReadWriteSet(int currentChoice) {
1078 // Do the analysis to get Read and Write accesses to fields
1080 // We already have an entry
1081 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1082 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1083 rwSet = currReadWriteFieldsMap.get(currentChoice);
1084 } else { // We need to create a new entry
1085 rwSet = new ReadWriteSet();
1086 currReadWriteFieldsMap.put(currentChoice, rwSet);
1091 private boolean isFieldExcluded(Instruction executedInsn) {
1092 // Get the field info
1093 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1094 // Check if the non-relevant fields set already has it
1095 if (nonRelevantFields.contains(fieldInfo)) {
1098 // Check if the relevant fields set already has it
1099 if (relevantFields.contains(fieldInfo)) {
1102 // Analyze only after being initialized
1103 String field = fieldInfo.getFullName();
1104 // Check against "starts-with", "ends-with", and "contains" list
1105 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1106 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1107 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1108 nonRelevantFields.add(fieldInfo);
1111 relevantFields.add(fieldInfo);
1115 // Check if this trace is already constructed
1116 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1117 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1118 // Check if the trace has been constructed as a backtrack point for this state
1119 // TODO: THIS IS AN OPTIMIZATION!
1120 HashSet<Integer> choiceSet;
1121 if (doneBacktrackMap.containsKey(stateId)) {
1122 choiceSet = doneBacktrackMap.get(stateId);
1123 if (choiceSet.contains(firstChoice)) {
1127 choiceSet = new HashSet<>();
1128 doneBacktrackMap.put(stateId, choiceSet);
1130 choiceSet.add(firstChoice);
1135 // Reset data structure for each new execution
1136 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1137 if (choices == null || choices != icsCG.getAllChoices()) {
1138 // Reset state variables
1140 choices = icsCG.getAllChoices();
1141 refChoices = copyChoices(choices);
1142 // Clear data structures
1143 currVisitedStates = new HashSet<>();
1144 stateToEventMap = new HashMap<>();
1145 isEndOfExecution = false;
1149 // Set a backtrack point for a particular state
1150 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1151 // Set a backtrack CG based on a state ID
1152 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1153 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1154 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1155 backtrackCG.setStateId(stateId);
1156 backtrackCG.reset();
1157 // Update current execution with this new execution
1158 Execution newExecution = new Execution();
1159 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1160 newExecution.addTransition(firstTransition);
1161 // Try to free some memory since this map is only used for the current execution
1162 currentExecution.clearCGToChoiceMap();
1163 currentExecution = newExecution;
1164 // Remove from the queue if we don't have more backtrack points for that state
1165 if (backtrackExecutions.isEmpty()) {
1166 backtrackMap.remove(stateId);
1167 backtrackStateQ.remove(stateId);
1171 // Update backtrack sets
1172 // 1) recursively, and
1173 // 2) track accesses per memory location (per shared variable/field)
1174 private void updateBacktrackSet(Execution execution, int currentChoice) {
1175 // Copy ReadWriteSet object
1176 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1177 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1178 if (currRWSet == null) {
1181 currRWSet = currRWSet.getCopy();
1182 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1183 HashSet<TransitionEvent> visited = new HashSet<>();
1184 // Update backtrack set recursively
1185 // TODO: The following is the call to the original version of the method
1186 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1187 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1188 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1191 // TODO: This is the original version of the recursive method
1192 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1193 // Execution conflictExecution, int conflictChoice,
1194 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1195 // // Halt when we have found the first read/write conflicts for all memory locations
1196 // if (currRWSet.isEmpty()) {
1199 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1200 // // Halt when we have visited this transition (in a cycle)
1201 // if (visited.contains(confTrans)) {
1204 // visited.add(confTrans);
1205 // // Explore all predecessors
1206 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1207 // // Get the predecessor (previous conflict choice)
1208 // conflictChoice = predecessor.getChoice();
1209 // conflictExecution = predecessor.getExecution();
1210 // // Check if a conflict is found
1211 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1212 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1214 // // Continue performing DFS if conflict is not found
1215 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1219 // TODO: This is the version of the method with pushing up happens-before transitions
1220 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1221 Execution conflictExecution, int conflictChoice,
1222 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1223 TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1224 // TODO: THIS IS THE ACCESS SUMMARY
1225 // Record this transition into rGraph summary
1226 currRWSet = rGraph.recordTransitionSummary(currTrans.getStateId(), currTrans, currRWSet);
1227 // Halt when we have found the first read/write conflicts for all memory locations
1228 if (currRWSet.isEmpty()) {
1231 if (visited.contains(currTrans)) {
1234 visited.add(currTrans);
1235 // Explore all predecessors
1236 for (Predecessor predecessor : currTrans.getPredecessors()) {
1237 // Get the predecessor (previous conflict choice)
1238 int predecessorChoice = predecessor.getChoice();
1239 Execution predecessorExecution = predecessor.getExecution();
1240 // Push up one happens-before transition
1241 int newConflictChoice = conflictChoice;
1242 Execution newConflictExecution = conflictExecution;
1243 // Check if a conflict is found
1244 if (isConflictFound(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1245 createBacktrackingPoint(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice);
1246 newConflictChoice = conflictChoice;
1247 newConflictExecution = conflictExecution;
1249 // Continue performing DFS if conflict is not found
1250 updateBacktrackSetRecursive(predecessorExecution, predecessorChoice, newConflictExecution, newConflictChoice,
1251 currRWSet, visited);
1253 // Remove the transition after being explored
1254 // TODO: Seems to cause a lot of loops---commented out for now
1255 //visited.remove(confTrans);
1258 // --- Functions related to the reachability analysis when there is a state match
1260 /*private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1261 // Perform this analysis only when:
1262 // 1) this is not during a switch to a new execution,
1263 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1264 // 3) state > 0 (state 0 is for boolean CG)
1265 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1266 if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1267 // Update reachable transitions in the graph with a predecessor
1268 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1269 for(TransitionEvent transition : reachableTransitions) {
1270 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1272 updateBacktrackSetsFromPreviousExecution(stateId);
1277 // Update the backtrack sets from previous executions
1278 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1279 // Collect all the reachable transitions from R-Graph
1280 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1281 for(TransitionEvent transition : reachableTransitions) {
1282 Execution execution = transition.getExecution();
1283 int currentChoice = transition.getChoiceCounter();
1284 updateBacktrackSet(execution, currentChoice);
1288 // TODO: THIS IS THE ACCESS SUMMARY
1289 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1290 // Perform this analysis only when:
1291 // 1) this is not during a switch to a new execution,
1292 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1293 // 3) state > 0 (state 0 is for boolean CG)
1294 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1295 if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1296 // Update reachable transitions in the graph with a predecessor
1297 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1298 for(TransitionEvent transition : reachableTransitions) {
1299 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1301 updateBacktrackSetsFromPreviousExecution(currentExecution, choiceCounter - 1, stateId);
1306 private void updateBacktrackSetsFromPreviousExecution(Execution execution, int currentChoice, int stateId) {
1307 // Collect all the reachable transitions from R-Graph
1308 HashMap<Integer, SummaryNode> reachableTransitions = rGraph.getReachableTransitionsSummary(stateId);
1309 for(Map.Entry<Integer, SummaryNode> transition : reachableTransitions.entrySet()) {
1310 TransitionEvent reachableTransition = transition.getValue().getTransitionEvent();
1311 Execution conflictExecution = reachableTransition.getExecution();
1312 int conflictChoice = reachableTransition.getChoiceCounter();
1313 // Copy ReadWriteSet object
1314 ReadWriteSet currRWSet = transition.getValue().getReadWriteSet();
1315 currRWSet = currRWSet.getCopy();
1316 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1317 HashSet<TransitionEvent> visited = new HashSet<>();
1318 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);