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 DPORStateReducerMainStatesWithSummary 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 HashMap<Integer,Integer> currVisitedStates; // States visited in the current execution (maps to frequency)
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 MainSummary mainSummary; // Main summary (M) for state ID, event, and R/W set
75 private HashMap<Integer, PredecessorInfo> stateToPredInfo; // Predecessor info indexed by state ID
76 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
77 private RGraph rGraph; // R-Graph for past executions
80 private boolean isBooleanCGFlipped;
81 private boolean isEndOfExecution;
84 private int numOfTransitions;
86 public DPORStateReducerMainStatesWithSummary(Config config, JPF jpf) {
87 verboseMode = config.getBoolean("printout_state_transition", false);
88 stateReductionMode = config.getBoolean("activate_state_reduction", true);
90 out = new PrintWriter(System.out, true);
94 String outputFile = config.getString("file_output");
95 if (!outputFile.isEmpty()) {
97 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
98 } catch (IOException e) {
101 isBooleanCGFlipped = false;
102 mainSummary = new MainSummary();
103 numOfTransitions = 0;
104 nonRelevantClasses = new HashSet<>();
105 nonRelevantFields = new HashSet<>();
106 relevantFields = new HashSet<>();
107 restorableStateMap = new HashMap<>();
108 stateToPredInfo = new HashMap<>();
109 initializeStatesVariables();
113 public void stateRestored(Search search) {
115 id = search.getStateId();
116 depth = search.getDepth();
117 transition = search.getTransition();
119 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
120 " and depth: " + depth + "\n");
125 public void searchStarted(Search search) {
127 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
132 public void stateAdvanced(Search search) {
134 id = search.getStateId();
135 depth = search.getDepth();
136 transition = search.getTransition();
137 if (search.isNewState()) {
143 if (search.isEndState()) {
144 out.println("\n==> DEBUG: This is the last state!\n");
147 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
148 " which is " + detail + " Transition: " + transition + "\n");
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");
165 static Logger log = JPF.getLogger("report");
168 public void searchFinished(Search search) {
170 out.println("\n==> DEBUG: ----------------------------------- search finished");
171 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
172 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
173 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
175 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
176 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
177 fileWriter.println();
183 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
184 if (stateReductionMode) {
185 // Initialize with necessary information from the CG
186 if (nextCG instanceof IntChoiceFromSet) {
187 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
188 // Tell JPF that we are performing DPOR
190 if (!isEndOfExecution) {
191 // Check if CG has been initialized, otherwise initialize it
192 Integer[] cgChoices = icsCG.getAllChoices();
193 // Record the events (from choices)
194 if (choices == null) {
196 // Make a copy of choices as reference
197 refChoices = copyChoices(choices);
198 // Record the max event choice (the last element of the choice array)
199 maxEventChoice = choices[choices.length - 1];
201 icsCG.setNewValues(choices);
203 // Use a modulo since choiceCounter is going to keep increasing
204 int choiceIndex = choiceCounter % choices.length;
205 icsCG.advance(choices[choiceIndex]);
207 // Set done all CGs while transitioning to a new execution
215 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
216 if (stateReductionMode) {
217 // Check the boolean CG and if it is flipped, we are resetting the analysis
218 if (currentCG instanceof BooleanChoiceGenerator) {
219 if (!isBooleanCGFlipped) {
220 isBooleanCGFlipped = true;
222 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
223 initializeStatesVariables();
226 // Check every choice generated and ensure fair scheduling!
227 if (currentCG instanceof IntChoiceFromSet) {
228 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 (choiceCounter > 0 && terminateCurrentExecution(vm)) {
241 exploreNextBacktrackPoints(vm, icsCG);
245 // Map state to event
246 mapStateToEvent(icsCG.getNextChoice());
255 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
256 if (stateReductionMode) {
257 if (!isEndOfExecution) {
258 // Has to be initialized and it is a integer CG
259 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
260 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
261 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
262 if (currentChoice < 0) { // If choice is -1 then skip
265 currentChoice = checkAndAdjustChoice(currentChoice, vm);
266 // Record accesses from executed instructions
267 if (executedInsn instanceof JVMFieldInstruction) {
268 // We don't care about libraries
269 if (!isFieldExcluded(executedInsn)) {
270 analyzeReadWriteAccesses(executedInsn, currentChoice);
272 } else if (executedInsn instanceof INVOKEINTERFACE) {
273 // Handle the read/write accesses that occur through iterators
274 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
286 // This class compactly stores backtrack execution:
287 // 1) backtrack choice list, and
288 // 2) first backtrack point (linking with predecessor execution)
289 private class BacktrackExecution {
290 private Integer[] choiceList;
291 private TransitionEvent firstTransition;
293 public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
294 choiceList = choList;
295 firstTransition = fTransition;
298 public Integer[] getChoiceList() {
302 public TransitionEvent getFirstTransition() {
303 return firstTransition;
307 // This class stores a representation of an execution
308 // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
309 // TODO: We basically need to keep track of:
310 // TODO: (1) last read/write access to each memory location
311 // TODO: (2) last state with two or more incoming events/transitions
312 private class Execution {
313 private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap; // Map between CG to choice numbers for O(1) access
314 private ArrayList<TransitionEvent> executionTrace; // The BacktrackPoint objects of this execution
315 private boolean isNew; // Track if this is the first time it is accessed
316 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
319 cgToChoiceMap = new HashMap<>();
320 executionTrace = new ArrayList<>();
322 readWriteFieldsMap = new HashMap<>();
325 public void addTransition(TransitionEvent newBacktrackPoint) {
326 executionTrace.add(newBacktrackPoint);
329 public void clearCGToChoiceMap() {
330 cgToChoiceMap = null;
333 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
334 return cgToChoiceMap.get(icsCG);
337 public ArrayList<TransitionEvent> getExecutionTrace() {
338 return executionTrace;
341 public TransitionEvent getFirstTransition() {
342 return executionTrace.get(0);
345 public TransitionEvent getLastTransition() {
346 return executionTrace.get(executionTrace.size() - 1);
349 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
350 return readWriteFieldsMap;
353 public boolean isNew() {
355 // Right after this is accessed, it is no longer new
362 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
363 cgToChoiceMap.put(icsCG, choice);
367 // This class compactly stores a predecessor
368 // 1) a predecessor execution
369 // 2) the predecessor choice in that predecessor execution
370 private class Predecessor {
371 private int choice; // Predecessor choice
372 private Execution execution; // Predecessor execution
374 public Predecessor(int predChoice, Execution predExec) {
376 execution = predExec;
379 public int getChoice() {
383 public Execution getExecution() {
388 // This class represents a R-Graph (in the paper it is a state transition graph R)
389 // This implementation stores reachable transitions from and connects with past executions
390 private class RGraph {
391 private int hiStateId; // Maximum state Id
392 private HashMap<Integer, HashSet<TransitionEvent>> graph; // Reachable transitions from past executions
396 graph = new HashMap<>();
399 public void addReachableTransition(int stateId, TransitionEvent transition) {
400 HashSet<TransitionEvent> transitionSet;
401 if (graph.containsKey(stateId)) {
402 transitionSet = graph.get(stateId);
404 transitionSet = new HashSet<>();
405 graph.put(stateId, transitionSet);
407 // Insert into the set if it does not contain it yet
408 if (!transitionSet.contains(transition)) {
409 transitionSet.add(transition);
411 // Update highest state ID
412 if (hiStateId < stateId) {
417 public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
418 if (!graph.containsKey(stateId)) {
419 // This is a loop from a transition to itself, so just return the current transition
420 HashSet<TransitionEvent> transitionSet = new HashSet<>();
421 transitionSet.add(currentExecution.getLastTransition());
422 return transitionSet;
424 return graph.get(stateId);
427 public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
428 HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
429 // All transitions from states higher than the given state ID (until the highest state ID) are reachable
430 for(int stId = stateId; stId <= hiStateId; stId++) {
431 // We might encounter state IDs from the first round of Boolean CG
432 // The second round of Boolean CG should consider these new states
433 if (graph.containsKey(stId)) {
434 reachableTransitions.addAll(graph.get(stId));
437 return reachableTransitions;
441 // This class compactly stores Read and Write field sets
442 // We store the field name and its object ID
443 // Sharing the same field means the same field name and object ID
444 private class ReadWriteSet {
445 private HashMap<String, Integer> readMap;
446 private HashMap<String, Integer> writeMap;
448 public ReadWriteSet() {
449 readMap = new HashMap<>();
450 writeMap = new HashMap<>();
453 public void addReadField(String field, int objectId) {
454 readMap.put(field, objectId);
457 public void addWriteField(String field, int objectId) {
458 writeMap.put(field, objectId);
461 public void removeReadField(String field) {
462 readMap.remove(field);
465 public void removeWriteField(String field) {
466 writeMap.remove(field);
469 public boolean isEmpty() {
470 return readMap.isEmpty() && writeMap.isEmpty();
473 public ReadWriteSet getCopy() {
474 ReadWriteSet copyRWSet = new ReadWriteSet();
475 // Copy the maps in the set into the new object copy
476 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
477 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
481 public Set<String> getReadSet() {
482 return readMap.keySet();
485 public Set<String> getWriteSet() {
486 return writeMap.keySet();
489 public boolean readFieldExists(String field) {
490 return readMap.containsKey(field);
493 public boolean writeFieldExists(String field) {
494 return writeMap.containsKey(field);
497 public int readFieldObjectId(String field) {
498 return readMap.get(field);
501 public int writeFieldObjectId(String field) {
502 return writeMap.get(field);
505 private HashMap<String, Integer> getReadMap() {
509 private HashMap<String, Integer> getWriteMap() {
513 private void setReadMap(HashMap<String, Integer> rMap) {
517 private void setWriteMap(HashMap<String, Integer> wMap) {
522 // This class is a representation of a state.
523 // It stores the predecessors to a state.
524 // TODO: We also have stateToEventMap, restorableStateMap, and doneBacktrackMap that has state Id as HashMap key.
525 private class PredecessorInfo {
526 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
527 private HashMap<Execution, HashSet<Integer>> recordedPredecessors;
528 // Memorize event and choice number to not record them twice
530 public PredecessorInfo() {
531 predecessors = new HashSet<>();
532 recordedPredecessors = new HashMap<>();
535 public HashSet<Predecessor> getPredecessors() {
539 private boolean isRecordedPredecessor(Execution execution, int choice) {
540 // See if we have recorded this predecessor earlier
541 HashSet<Integer> recordedChoices;
542 if (recordedPredecessors.containsKey(execution)) {
543 recordedChoices = recordedPredecessors.get(execution);
544 if (recordedChoices.contains(choice)) {
548 recordedChoices = new HashSet<>();
549 recordedPredecessors.put(execution, recordedChoices);
551 // Record the choice if we haven't seen it
552 recordedChoices.add(choice);
557 public void recordPredecessor(Execution execution, int choice) {
558 if (!isRecordedPredecessor(execution, choice)) {
559 predecessors.add(new Predecessor(choice, execution));
564 // This class compactly stores transitions:
568 // 4) predecessors (for backward DFS).
569 private class TransitionEvent {
570 private int choice; // Choice chosen at this transition
571 private int choiceCounter; // Choice counter at this transition
572 private Execution execution; // The execution where this transition belongs
573 private int stateId; // State at this transition
574 private IntChoiceFromSet transitionCG; // CG at this transition
576 public TransitionEvent() {
584 public int getChoice() {
588 public int getChoiceCounter() {
589 return choiceCounter;
592 public Execution getExecution() {
596 public int getStateId() {
600 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
602 public void setChoice(int cho) {
606 public void setChoiceCounter(int choCounter) {
607 choiceCounter = choCounter;
610 public void setExecution(Execution exec) {
614 public void setStateId(int stId) {
618 public void setTransitionCG(IntChoiceFromSet cg) {
623 // -- PRIVATE CLASSES RELATED TO SUMMARY
624 // This class stores the main summary of states
625 // 1) Main mapping between state ID and state summary
626 // 2) State summary is a mapping between events (i.e., event choices) and their respective R/W sets
627 private class MainSummary {
628 private HashMap<Integer, HashMap<Integer, ReadWriteSet>> mainSummary;
630 public MainSummary() {
631 mainSummary = new HashMap<>();
634 public Set<Integer> getEventChoicesAtStateId(int stateId) {
635 HashMap<Integer, ReadWriteSet> stateSummary = mainSummary.get(stateId);
636 // Return a new set since this might get updated concurrently
637 return new HashSet<>(stateSummary.keySet());
640 public ReadWriteSet getRWSetForEventChoiceAtState(int eventChoice, int stateId) {
641 HashMap<Integer, ReadWriteSet> stateSummary = mainSummary.get(stateId);
642 return stateSummary.get(eventChoice);
645 public Set<Integer> getStateIds() {
646 return mainSummary.keySet();
649 private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
650 // Combine the same write accesses and record in the recordedRWSet
651 HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
652 HashMap<String, Integer> writeMap = rwSet.getWriteMap();
653 for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
654 String writeField = entry.getKey();
655 // Remove the entry from rwSet if both field and object ID are the same
656 if (writeMap.containsKey(writeField) &&
657 (writeMap.get(writeField).equals(recordedWriteMap.get(writeField)))) {
658 writeMap.remove(writeField);
661 // Then add the rest (fields in rwSet but not in recordedRWSet)
662 // into the recorded map because these will be traversed
663 recordedWriteMap.putAll(writeMap);
664 // Combine the same read accesses and record in the recordedRWSet
665 HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
666 HashMap<String, Integer> readMap = rwSet.getReadMap();
667 for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
668 String readField = entry.getKey();
669 // Remove the entry from rwSet if both field and object ID are the same
670 if (readMap.containsKey(readField) &&
671 (readMap.get(readField).equals(recordedReadMap.get(readField)))) {
672 readMap.remove(readField);
675 // Then add the rest (fields in rwSet but not in recordedRWSet)
676 // into the recorded map because these will be traversed
677 recordedReadMap.putAll(readMap);
682 public ReadWriteSet updateStateSummary(int stateId, int eventChoice, ReadWriteSet rwSet) {
683 // If the state Id has not existed, insert the StateSummary object
684 // If the state Id has existed, find the event choice:
685 // 1) If the event choice has not existed, insert the ReadWriteSet object
686 // 2) If the event choice has existed, perform union between the two ReadWriteSet objects
687 if (!rwSet.isEmpty()) {
688 HashMap<Integer, ReadWriteSet> stateSummary;
689 if (!mainSummary.containsKey(stateId)) {
690 stateSummary = new HashMap<>();
691 stateSummary.put(eventChoice, rwSet.getCopy());
692 mainSummary.put(stateId, stateSummary);
694 stateSummary = mainSummary.get(stateId);
695 if (!stateSummary.containsKey(eventChoice)) {
696 stateSummary.put(eventChoice, rwSet.getCopy());
698 rwSet = performUnion(stateSummary.get(eventChoice), rwSet);
707 private final static String DO_CALL_METHOD = "doCall";
708 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
709 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
710 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
711 // Groovy library created fields
712 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
714 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
715 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
716 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
717 // Java and Groovy libraries
718 { "java", "org", "sun", "com", "gov", "groovy"};
719 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
720 private final static String GET_PROPERTY_METHOD =
721 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
722 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
723 private final static String JAVA_INTEGER = "int";
724 private final static String JAVA_STRING_LIB = "java.lang.String";
727 private Integer[] copyChoices(Integer[] choicesToCopy) {
729 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
730 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
731 return copyOfChoices;
734 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
735 // Check the next choice and if the value is not the same as the expected then force the expected value
736 int choiceIndex = choiceCounter % refChoices.length;
737 int nextChoice = icsCG.getNextChoice();
738 if (refChoices[choiceIndex] != nextChoice) {
739 int expectedChoice = refChoices[choiceIndex];
740 int currCGIndex = icsCG.getNextChoiceIndex();
741 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
742 icsCG.setChoice(currCGIndex, expectedChoice);
745 // Get state ID and associate it with this transition
746 int stateId = vm.getStateId();
747 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
748 rGraph.addReachableTransition(stateId, transition);
749 currentExecution.mapCGToChoice(icsCG, choiceCounter);
750 // Store restorable state object for this state (always store the latest)
751 if (!restorableStateMap.containsKey(stateId)) {
752 RestorableVMState restorableState = vm.getRestorableState();
753 restorableStateMap.put(stateId, restorableState);
757 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
758 // Get a new transition
759 TransitionEvent transition;
760 if (currentExecution.isNew()) {
761 // We need to handle the first transition differently because this has a predecessor execution
762 transition = currentExecution.getFirstTransition();
764 transition = new TransitionEvent();
765 currentExecution.addTransition(transition);
766 addPredecessors(stateId);
768 transition.setExecution(currentExecution);
769 transition.setTransitionCG(icsCG);
770 transition.setStateId(stateId);
771 transition.setChoice(refChoices[choiceIndex]);
772 transition.setChoiceCounter(choiceCounter);
777 // --- Functions related to cycle detection and reachability graph
779 // Detect cycles in the current execution/trace
780 // We terminate the execution iff:
781 // (1) the state has been visited in the current execution
782 // (2) the state has one or more cycles that involve all the events
783 // With simple approach we only need to check for a re-visited state.
784 // Basically, we have to check that we have executed all events between two occurrences of such state.
785 private boolean completeFullCycle(int stId) {
786 // False if the state ID hasn't been recorded
787 if (!stateToEventMap.containsKey(stId)) {
790 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
791 // Check if this set contains all the event choices
792 // If not then this is not the terminating condition
793 for(int i=0; i<=maxEventChoice; i++) {
794 if (!visitedEvents.contains(i)) {
801 private void initializeStatesVariables() {
808 if (!isBooleanCGFlipped) {
809 currVisitedStates = new HashMap<>();
810 prevVisitedStates = new HashSet<>();
811 stateToEventMap = new HashMap<>();
813 currVisitedStates.clear();
814 prevVisitedStates.clear();
815 stateToEventMap.clear();
818 if (!isBooleanCGFlipped) {
819 backtrackMap = new HashMap<>();
821 backtrackMap.clear();
823 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
824 currentExecution = new Execution();
825 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
826 if (!isBooleanCGFlipped) {
827 doneBacktrackMap = new HashMap<>();
829 doneBacktrackMap.clear();
831 rGraph = new RGraph();
833 isEndOfExecution = false;
836 private void mapStateToEvent(int nextChoiceValue) {
837 // Update all states with this event/choice
838 // This means that all past states now see this transition
839 Set<Integer> stateSet = stateToEventMap.keySet();
840 for(Integer stateId : stateSet) {
841 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
842 eventSet.add(nextChoiceValue);
846 private boolean terminateCurrentExecution(VM vm) {
847 int stateId = vm.getStateId();
848 // We need to check all the states that have just been visited
849 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
850 boolean terminate = false;
851 // We perform updates on backtrack sets for every
852 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
853 addPredecessors(stateId);
854 updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
857 // If frequency > 1 then this means we have visited this stateId more than once in the current execution
858 if (currVisitedStates.containsKey(stateId) && currVisitedStates.get(stateId) > 1) {
860 addPredecessors(stateId);
862 updateBacktrackSetsFromGraph(stateId, currentExecution, choiceCounter - 1);
867 private void updateStateInfo(VM vm) {
868 // Update the state variables
869 int stateId = vm.getStateId();
870 // Insert state ID into the map if it is new
871 if (!stateToEventMap.containsKey(stateId)) {
872 HashSet<Integer> eventSet = new HashSet<>();
873 stateToEventMap.put(stateId, eventSet);
875 if (!prevVisitedStates.contains(stateId)) {
876 // It is a currently visited states if the state has not been seen in previous executions
878 if (currVisitedStates.containsKey(stateId)) {
879 frequency = currVisitedStates.get(stateId);
881 currVisitedStates.put(stateId, frequency + 1); // Increment frequency counter
885 // --- Functions related to Read/Write access analysis on shared fields
887 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
888 // Insert backtrack point to the right state ID
889 LinkedList<BacktrackExecution> backtrackExecList;
890 if (backtrackMap.containsKey(stateId)) {
891 backtrackExecList = backtrackMap.get(stateId);
893 backtrackExecList = new LinkedList<>();
894 backtrackMap.put(stateId, backtrackExecList);
896 // Add the new backtrack execution object
897 TransitionEvent backtrackTransition = new TransitionEvent();
898 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
899 // Add to priority queue
900 if (!backtrackStateQ.contains(stateId)) {
901 backtrackStateQ.add(stateId);
905 private void addPredecessors(int stateId) {
906 PredecessorInfo predecessorInfo;
907 if (!stateToPredInfo.containsKey(stateId)) {
908 predecessorInfo = new PredecessorInfo();
909 stateToPredInfo.put(stateId, predecessorInfo);
910 } else { // This is a new state Id
911 predecessorInfo = stateToPredInfo.get(stateId);
913 predecessorInfo.recordPredecessor(currentExecution, choiceCounter - 1);
916 // Analyze Read/Write accesses that are directly invoked on fields
917 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
918 // Get the field info
919 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
920 // Analyze only after being initialized
921 String fieldClass = fieldInfo.getFullName();
922 // Do the analysis to get Read and Write accesses to fields
923 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
924 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
925 // Record the field in the map
926 if (executedInsn instanceof WriteInstruction) {
927 // We first check the non-relevant fields set
928 if (!nonRelevantFields.contains(fieldInfo)) {
929 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
930 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
931 if (fieldClass.startsWith(str)) {
932 nonRelevantFields.add(fieldInfo);
937 // If we have this field in the non-relevant fields set then we return right away
940 rwSet.addWriteField(fieldClass, objectId);
941 } else if (executedInsn instanceof ReadInstruction) {
942 rwSet.addReadField(fieldClass, objectId);
946 // Analyze Read accesses that are indirect (performed through iterators)
947 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
948 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
950 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
951 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
952 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
953 // Extract info from the stack frame
954 StackFrame frame = ti.getTopFrame();
955 int[] frameSlots = frame.getSlots();
956 // Get the Groovy callsite library at index 0
957 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
958 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
961 // Get the iterated object whose property is accessed
962 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
963 if (eiAccessObj == null) {
966 // We exclude library classes (they start with java, org, etc.) and some more
967 ClassInfo classInfo = eiAccessObj.getClassInfo();
968 String objClassName = classInfo.getName();
969 // Check if this class info is part of the non-relevant classes set already
970 if (!nonRelevantClasses.contains(classInfo)) {
971 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
972 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
973 nonRelevantClasses.add(classInfo);
977 // If it is part of the non-relevant classes set then return immediately
980 // Extract fields from this object and put them into the read write
981 int numOfFields = eiAccessObj.getNumberOfFields();
982 for(int i=0; i<numOfFields; i++) {
983 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
984 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
985 String fieldClass = fieldInfo.getFullName();
986 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
987 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
988 // Record the field in the map
989 rwSet.addReadField(fieldClass, objectId);
995 private int checkAndAdjustChoice(int currentChoice, VM vm) {
996 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
997 // for certain method calls in the infrastructure, e.g., eventSince()
998 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
999 // This is the main event CG
1000 if (currentCG instanceof IntIntervalGenerator) {
1001 // This is the interval CG used in device handlers
1002 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
1003 // Iterate until we find the IntChoiceFromSet CG
1004 while (!(parentCG instanceof IntChoiceFromSet)) {
1005 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
1007 // Find the choice related to the IntIntervalGenerator CG from the map
1008 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
1010 return currentChoice;
1013 private void createBacktrackingPoint(int eventChoice, Execution conflictExecution, int conflictChoice) {
1014 // Create a new list of choices for backtrack based on the current choice and conflicting event number
1015 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
1016 // for the original set {0, 1, 2, 3}
1018 // eventChoice represents the event/transaction that will be put into the backtracking set of
1019 // conflictExecution/conflictChoice
1020 Integer[] newChoiceList = new Integer[refChoices.length];
1021 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1022 int stateId = conflictTrace.get(conflictChoice).getStateId();
1023 // Check if this trace has been done from this state
1024 if (isTraceAlreadyConstructed(eventChoice, stateId)) {
1027 // Put the conflicting event numbers first and reverse the order
1028 newChoiceList[0] = eventChoice;
1029 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
1030 for (int i = 0, j = 1; i < refChoices.length; i++) {
1031 if (refChoices[i] != newChoiceList[0]) {
1032 newChoiceList[j] = refChoices[i];
1036 // Predecessor of the new backtrack point is the same as the conflict point's
1037 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
1040 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
1041 for (String excludedField : excludedStrings) {
1042 if (className.contains(excludedField)) {
1049 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
1050 for (String excludedField : excludedStrings) {
1051 if (className.endsWith(excludedField)) {
1058 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1059 for (String excludedField : excludedStrings) {
1060 if (className.startsWith(excludedField)) {
1067 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1068 // Check if we are reaching the end of our execution: no more backtracking points to explore
1069 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1070 if (!backtrackStateQ.isEmpty()) {
1071 // Set done all the other backtrack points
1072 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1073 backtrackTransition.getTransitionCG().setDone();
1075 // Reset the next backtrack point with the latest state
1076 int hiStateId = backtrackStateQ.peek();
1077 // Restore the state first if necessary
1078 if (vm.getStateId() != hiStateId) {
1079 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1080 vm.restoreState(restorableState);
1082 // Set the backtrack CG
1083 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1084 setBacktrackCG(hiStateId, backtrackCG);
1086 // Set done this last CG (we save a few rounds)
1089 // Save all the visited states when starting a new execution of trace
1090 prevVisitedStates.addAll(currVisitedStates.keySet());
1091 // This marks a transitional period to the new CG
1092 isEndOfExecution = true;
1095 private boolean isConflictFound(int eventChoice, Execution conflictExecution, int conflictChoice,
1096 ReadWriteSet currRWSet) {
1097 // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1098 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1099 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1100 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1101 if (!confRWFieldsMap.containsKey(conflictChoice) || eventChoice == conflictTrace.get(conflictChoice).getChoice()) {
1104 // R/W set of choice/event that may have a potential conflict
1105 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1106 // Check for conflicts with Read and Write fields for Write instructions
1107 Set<String> currWriteSet = currRWSet.getWriteSet();
1108 for(String writeField : currWriteSet) {
1109 int currObjId = currRWSet.writeFieldObjectId(writeField);
1110 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1111 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1112 // Remove this from the write set as we are tracking per memory location
1113 currRWSet.removeWriteField(writeField);
1117 // Check for conflicts with Write fields for Read instructions
1118 Set<String> currReadSet = currRWSet.getReadSet();
1119 for(String readField : currReadSet) {
1120 int currObjId = currRWSet.readFieldObjectId(readField);
1121 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1122 // Remove this from the read set as we are tracking per memory location
1123 currRWSet.removeReadField(readField);
1127 // Return false if no conflict is found
1131 private boolean isFieldExcluded(Instruction executedInsn) {
1132 // Get the field info
1133 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1134 // Check if the non-relevant fields set already has it
1135 if (nonRelevantFields.contains(fieldInfo)) {
1138 // Check if the relevant fields set already has it
1139 if (relevantFields.contains(fieldInfo)) {
1142 // Analyze only after being initialized
1143 String field = fieldInfo.getFullName();
1144 // Check against "starts-with", "ends-with", and "contains" list
1145 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1146 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1147 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1148 nonRelevantFields.add(fieldInfo);
1151 relevantFields.add(fieldInfo);
1155 // Check if this trace is already constructed
1156 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1157 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1158 // Check if the trace has been constructed as a backtrack point for this state
1159 // TODO: THIS IS AN OPTIMIZATION!
1160 HashSet<Integer> choiceSet;
1161 if (doneBacktrackMap.containsKey(stateId)) {
1162 choiceSet = doneBacktrackMap.get(stateId);
1163 if (choiceSet.contains(firstChoice)) {
1167 choiceSet = new HashSet<>();
1168 doneBacktrackMap.put(stateId, choiceSet);
1170 choiceSet.add(firstChoice);
1175 private HashSet<Predecessor> getPredecessors(int stateId) {
1176 // Get a set of predecessors for this state ID
1177 HashSet<Predecessor> predecessors;
1178 if (stateToPredInfo.containsKey(stateId)) {
1179 PredecessorInfo predecessorInfo = stateToPredInfo.get(stateId);
1180 predecessors = predecessorInfo.getPredecessors();
1182 predecessors = new HashSet<>();
1185 return predecessors;
1188 private ReadWriteSet getReadWriteSet(int currentChoice) {
1189 // Do the analysis to get Read and Write accesses to fields
1191 // We already have an entry
1192 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1193 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1194 rwSet = currReadWriteFieldsMap.get(currentChoice);
1195 } else { // We need to create a new entry
1196 rwSet = new ReadWriteSet();
1197 currReadWriteFieldsMap.put(currentChoice, rwSet);
1202 // Reset data structure for each new execution
1203 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1204 if (choices == null || choices != icsCG.getAllChoices()) {
1205 // Reset state variables
1207 choices = icsCG.getAllChoices();
1208 refChoices = copyChoices(choices);
1209 // Clear data structures
1210 currVisitedStates.clear();
1211 stateToEventMap.clear();
1212 isEndOfExecution = false;
1216 // Set a backtrack point for a particular state
1217 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1218 // Set a backtrack CG based on a state ID
1219 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1220 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1221 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1222 backtrackCG.setStateId(stateId);
1223 backtrackCG.reset();
1224 // Update current execution with this new execution
1225 Execution newExecution = new Execution();
1226 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1227 newExecution.addTransition(firstTransition);
1228 // Try to free some memory since this map is only used for the current execution
1229 currentExecution.clearCGToChoiceMap();
1230 currentExecution = newExecution;
1231 // Remove from the queue if we don't have more backtrack points for that state
1232 if (backtrackExecutions.isEmpty()) {
1233 backtrackMap.remove(stateId);
1234 backtrackStateQ.remove(stateId);
1238 // Update backtrack sets
1239 // 1) recursively, and
1240 // 2) track accesses per memory location (per shared variable/field)
1241 private void updateBacktrackSet(Execution execution, int currentChoice) {
1242 // Copy ReadWriteSet object
1243 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1244 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1245 if (currRWSet == null) {
1248 currRWSet = currRWSet.getCopy();
1249 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1250 HashSet<TransitionEvent> visited = new HashSet<>();
1251 // Conflict TransitionEvent is essentially the current TransitionEvent
1252 TransitionEvent confTrans = execution.getExecutionTrace().get(currentChoice);
1253 // Update backtrack set recursively
1254 updateBacktrackSetDFS(execution, currentChoice, confTrans.getChoice(), currRWSet, visited);
1257 private void updateBacktrackSetDFS(Execution execution, int currentChoice, int conflictEventChoice,
1258 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1259 TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1260 // Record this transition into the state summary of main summary
1261 currRWSet = mainSummary.updateStateSummary(currTrans.getStateId(), conflictEventChoice, currRWSet);
1262 // Halt when we have visited this transition (in a cycle)
1263 if (visited.contains(currTrans)) {
1266 visited.add(currTrans);
1267 // Check the predecessors only if the set is not empty
1268 if (!currRWSet.isEmpty()) {
1269 // Explore all predecessors
1270 for (Predecessor predecessor : getPredecessors(currTrans.getStateId())) {
1271 // Get the predecessor (previous conflict choice)
1272 int predecessorChoice = predecessor.getChoice();
1273 Execution predecessorExecution = predecessor.getExecution();
1274 // Push up one happens-before transition
1275 int newConflictEventChoice = conflictEventChoice;
1276 // Check if a conflict is found
1277 ReadWriteSet newCurrRWSet = currRWSet.getCopy();
1278 if (isConflictFound(conflictEventChoice, predecessorExecution, predecessorChoice, newCurrRWSet)) {
1279 createBacktrackingPoint(conflictEventChoice, predecessorExecution, predecessorChoice);
1280 // We need to extract the pushed happens-before event choice from the predecessor execution and choice
1281 newConflictEventChoice = predecessorExecution.getExecutionTrace().get(predecessorChoice).getChoice();
1283 // Continue performing DFS if conflict is not found
1284 updateBacktrackSetDFS(predecessorExecution, predecessorChoice, newConflictEventChoice,
1285 newCurrRWSet, visited);
1290 // --- Functions related to the reachability analysis when there is a state match
1292 // Update the backtrack sets from previous executions
1293 private void updateBacktrackSetsFromGraph(int stateId, Execution currExecution, int currChoice) {
1294 // Get events/choices at this state ID
1295 Set<Integer> eventChoicesAtStateId = mainSummary.getEventChoicesAtStateId(stateId);
1296 for (Integer eventChoice : eventChoicesAtStateId) {
1297 // Get the ReadWriteSet object for this event at state ID
1298 ReadWriteSet rwSet = mainSummary.getRWSetForEventChoiceAtState(eventChoice, stateId);
1299 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1300 HashSet<TransitionEvent> visited = new HashSet<>();
1301 // Update the backtrack sets recursively
1302 updateBacktrackSetDFS(currExecution, currChoice, eventChoice, rwSet.getCopy(), visited);