2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
6 * The Java Pathfinder core (jpf-core) platform is licensed under the
7 * Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0.
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 package gov.nasa.jpf.listener;
20 import gov.nasa.jpf.Config;
21 import gov.nasa.jpf.JPF;
22 import gov.nasa.jpf.ListenerAdapter;
23 import gov.nasa.jpf.search.Search;
24 import gov.nasa.jpf.jvm.bytecode.*;
25 import gov.nasa.jpf.vm.*;
26 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
27 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
28 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
29 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
31 import java.io.FileWriter;
32 import java.io.PrintWriter;
33 import java.lang.reflect.Field;
35 import java.util.logging.Logger;
36 import java.io.IOException;
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 DPORStateReducer 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 HashSet<String> doneBacktrackSet; // 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 numOfConflicts;
84 private int numOfTransitions;
86 public DPORStateReducer(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;
103 numOfTransitions = 0;
104 nonRelevantClasses = new HashSet<>();
105 nonRelevantFields = new HashSet<>();
106 relevantFields = new HashSet<>();
107 restorableStateMap = new HashMap<>();
108 initializeStatesVariables();
112 public void stateRestored(Search search) {
114 id = search.getStateId();
115 depth = search.getDepth();
116 transition = search.getTransition();
118 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
119 " and depth: " + depth + "\n");
124 public void searchStarted(Search search) {
126 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
131 public void stateAdvanced(Search search) {
133 id = search.getStateId();
134 depth = search.getDepth();
135 transition = search.getTransition();
136 if (search.isNewState()) {
142 if (search.isEndState()) {
143 out.println("\n==> DEBUG: This is the last state!\n");
146 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
147 " which is " + detail + " Transition: " + transition + "\n");
149 if (stateReductionMode) {
150 updateStateInfo(search);
155 public void stateBacktracked(Search search) {
157 id = search.getStateId();
158 depth = search.getDepth();
159 transition = search.getTransition();
162 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
163 " and depth: " + depth + "\n");
165 if (stateReductionMode) {
166 updateStateInfo(search);
170 static Logger log = JPF.getLogger("report");
173 public void searchFinished(Search search) {
174 if (stateReductionMode) {
175 // Number of conflicts = first trace + subsequent backtrack points
176 numOfConflicts += 1 + doneBacktrackSet.size();
179 out.println("\n==> DEBUG: ----------------------------------- search finished");
180 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
181 out.println("\n==> DEBUG: Number of conflicts : " + numOfConflicts);
182 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
183 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
185 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
186 fileWriter.println("==> DEBUG: Number of conflicts : " + numOfConflicts);
187 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
188 fileWriter.println();
194 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
195 if (stateReductionMode) {
196 // Initialize with necessary information from the CG
197 if (nextCG instanceof IntChoiceFromSet) {
198 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
199 // Tell JPF that we are performing DPOR
201 if (!isEndOfExecution) {
202 // Check if CG has been initialized, otherwise initialize it
203 Integer[] cgChoices = icsCG.getAllChoices();
204 // Record the events (from choices)
205 if (choices == null) {
207 // Make a copy of choices as reference
208 refChoices = copyChoices(choices);
209 // Record the max event choice (the last element of the choice array)
210 maxEventChoice = choices[choices.length - 1];
212 icsCG.setNewValues(choices);
214 // Use a modulo since choiceCounter is going to keep increasing
215 int choiceIndex = choiceCounter % choices.length;
216 icsCG.advance(choices[choiceIndex]);
218 // Set done all CGs while transitioning to a new execution
226 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
227 if (stateReductionMode) {
228 // Check the boolean CG and if it is flipped, we are resetting the analysis
229 if (currentCG instanceof BooleanChoiceGenerator) {
230 if (!isBooleanCGFlipped) {
231 isBooleanCGFlipped = true;
233 // Number of conflicts = first trace + subsequent backtrack points
234 numOfConflicts = 1 + doneBacktrackSet.size();
235 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
236 initializeStatesVariables();
239 // Check every choice generated and ensure fair scheduling!
240 if (currentCG instanceof IntChoiceFromSet) {
241 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
242 // If this is a new CG then we need to update data structures
243 resetStatesForNewExecution(icsCG, vm);
244 // If we don't see a fair scheduling of events/choices then we have to enforce it
245 ensureFairSchedulingAndSetupTransition(icsCG, vm);
246 // Update backtrack set of an executed event (transition): one transition before this one
247 updateBacktrackSet(currentExecution, choiceCounter - 1);
248 // Explore the next backtrack point:
249 // 1) if we have seen this state or this state contains cycles that involve all events, and
250 // 2) after the current CG is advanced at least once
251 if (terminateCurrentExecution() && choiceCounter > 0) {
252 exploreNextBacktrackPoints(vm, icsCG);
256 // Map state to event
257 mapStateToEvent(icsCG.getNextChoice());
258 justVisitedStates.clear();
267 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
268 if (stateReductionMode) {
269 if (!isEndOfExecution) {
270 // Has to be initialized and a integer CG
271 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
272 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
273 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
274 if (currentChoice < 0) { // If choice is -1 then skip
277 currentChoice = checkAndAdjustChoice(currentChoice, vm);
278 // Record accesses from executed instructions
279 if (executedInsn instanceof JVMFieldInstruction) {
280 // We don't care about libraries
281 if (!isFieldExcluded(executedInsn)) {
282 analyzeReadWriteAccesses(executedInsn, currentChoice);
284 } else if (executedInsn instanceof INVOKEINTERFACE) {
285 // Handle the read/write accesses that occur through iterators
286 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
298 // This class compactly stores backtrack execution:
299 // 1) backtrack choice list, and
300 // 2) first backtrack point (linking with predecessor execution)
301 private class BacktrackExecution {
302 private Integer[] choiceList;
303 private TransitionEvent firstTransition;
305 public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
306 choiceList = choList;
307 firstTransition = fTransition;
310 public Integer[] getChoiceList() {
314 public TransitionEvent getFirstTransition() {
315 return firstTransition;
319 // This class stores a representation of an execution
320 // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
321 // TODO: We basically need to keep track of:
322 // TODO: (1) last read/write access to each memory location
323 // TODO: (2) last state with two or more incoming events/transitions
324 private class Execution {
325 private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap; // Map between CG to choice numbers for O(1) access
326 private ArrayList<TransitionEvent> executionTrace; // The BacktrackPoint objects of this execution
327 private boolean isNew; // Track if this is the first time it is accessed
328 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
331 cgToChoiceMap = new HashMap<>();
332 executionTrace = new ArrayList<>();
334 readWriteFieldsMap = new HashMap<>();
337 public void addTransition(TransitionEvent newBacktrackPoint) {
338 executionTrace.add(newBacktrackPoint);
341 public void clearCGToChoiceMap() {
342 cgToChoiceMap = null;
345 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
346 return cgToChoiceMap.get(icsCG);
349 public ArrayList<TransitionEvent> getExecutionTrace() {
350 return executionTrace;
353 public TransitionEvent getFirstTransition() {
354 return executionTrace.get(0);
357 public TransitionEvent getLastTransition() {
358 return executionTrace.get(executionTrace.size() - 1);
361 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
362 return readWriteFieldsMap;
365 public boolean isNew() {
367 // Right after this is accessed, it is no longer new
374 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
375 cgToChoiceMap.put(icsCG, choice);
379 // This class compactly stores a predecessor
380 // 1) a predecessor execution
381 // 2) the predecessor choice in that predecessor execution
382 private class Predecessor {
383 private int choice; // Predecessor choice
384 private Execution execution; // Predecessor execution
386 public Predecessor(int predChoice, Execution predExec) {
388 execution = predExec;
391 public int getChoice() {
395 public Execution getExecution() {
400 // This class represents a R-Graph (in the paper it is a state transition graph R)
401 // This implementation stores reachable transitions from and connects with past executions
402 private class RGraph {
403 private int hiStateId; // Maximum state Id
404 private HashMap<Integer, HashSet<TransitionEvent>> graph; // Reachable transitions from past executions
408 graph = new HashMap<>();
411 public void addReachableTransition(int stateId, TransitionEvent transition) {
412 HashSet<TransitionEvent> transitionSet;
413 if (graph.containsKey(stateId)) {
414 transitionSet = graph.get(stateId);
416 transitionSet = new HashSet<>();
417 graph.put(stateId, transitionSet);
419 // Insert into the set if it does not contain it yet
420 if (!transitionSet.contains(transition)) {
421 transitionSet.add(transition);
423 // Update highest state ID
424 if (hiStateId < stateId) {
429 public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
430 if (!graph.containsKey(stateId)) {
431 // This is a loop from a transition to itself, so just return the current transition
432 HashSet<TransitionEvent> transitionSet = new HashSet<>();
433 transitionSet.add(currentExecution.getLastTransition());
434 return transitionSet;
436 return graph.get(stateId);
439 public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
440 HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
441 // All transitions from states higher than the given state ID (until the highest state ID) are reachable
442 for(int stId = stateId; stId <= hiStateId; stId++) {
443 // We might encounter state IDs from the first round of Boolean CG
444 // The second round of Boolean CG should consider these new states
445 if (graph.containsKey(stId)) {
446 reachableTransitions.addAll(graph.get(stId));
449 return reachableTransitions;
453 // This class compactly stores Read and Write field sets
454 // We store the field name and its object ID
455 // Sharing the same field means the same field name and object ID
456 private class ReadWriteSet {
457 private HashMap<String, Integer> readMap;
458 private HashMap<String, Integer> writeMap;
460 public ReadWriteSet() {
461 readMap = new HashMap<>();
462 writeMap = new HashMap<>();
465 public void addReadField(String field, int objectId) {
466 readMap.put(field, objectId);
469 public void addWriteField(String field, int objectId) {
470 writeMap.put(field, objectId);
473 public void removeReadField(String field) {
474 readMap.remove(field);
477 public void removeWriteField(String field) {
478 writeMap.remove(field);
481 public boolean isEmpty() {
482 return readMap.isEmpty() && writeMap.isEmpty();
485 public ReadWriteSet getCopy() {
486 ReadWriteSet copyRWSet = new ReadWriteSet();
487 // Copy the maps in the set into the new object copy
488 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
489 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
493 public Set<String> getReadSet() {
494 return readMap.keySet();
497 public Set<String> getWriteSet() {
498 return writeMap.keySet();
501 public boolean readFieldExists(String field) {
502 return readMap.containsKey(field);
505 public boolean writeFieldExists(String field) {
506 return writeMap.containsKey(field);
509 public int readFieldObjectId(String field) {
510 return readMap.get(field);
513 public int writeFieldObjectId(String field) {
514 return writeMap.get(field);
517 private HashMap<String, Integer> getReadMap() {
521 private HashMap<String, Integer> getWriteMap() {
525 private void setReadMap(HashMap<String, Integer> rMap) {
529 private void setWriteMap(HashMap<String, Integer> wMap) {
534 // This class compactly stores transitions:
538 // 4) predecessors (for backward DFS).
539 private class TransitionEvent {
540 private int choice; // Choice chosen at this transition
541 private int choiceCounter; // Choice counter at this transition
542 private Execution execution; // The execution where this transition belongs
543 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
544 private int stateId; // State at this transition
545 private IntChoiceFromSet transitionCG; // CG at this transition
547 public TransitionEvent() {
551 predecessors = new HashSet<>();
556 public int getChoice() {
560 public int getChoiceCounter() {
561 return choiceCounter;
564 public Execution getExecution() {
568 public HashSet<Predecessor> getPredecessors() {
572 public int getStateId() {
576 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
578 public void recordPredecessor(Execution execution, int choice) {
579 predecessors.add(new Predecessor(choice, execution));
582 public void setChoice(int cho) {
586 public void setChoiceCounter(int choCounter) {
587 choiceCounter = choCounter;
590 public void setExecution(Execution exec) {
594 public void setPredecessors(HashSet<Predecessor> preds) {
595 predecessors = new HashSet<>(preds);
598 public void setStateId(int stId) {
602 public void setTransitionCG(IntChoiceFromSet cg) {
608 private final static String DO_CALL_METHOD = "doCall";
609 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
610 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
611 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
612 // Groovy library created fields
613 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
615 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
616 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
617 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
618 // Java and Groovy libraries
619 { "java", "org", "sun", "com", "gov", "groovy"};
620 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
621 private final static String GET_PROPERTY_METHOD =
622 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
623 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
624 private final static String JAVA_INTEGER = "int";
625 private final static String JAVA_STRING_LIB = "java.lang.String";
628 private Integer[] copyChoices(Integer[] choicesToCopy) {
630 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
631 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
632 return copyOfChoices;
635 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
636 // Check the next choice and if the value is not the same as the expected then force the expected value
637 int choiceIndex = choiceCounter % refChoices.length;
638 int nextChoice = icsCG.getNextChoice();
639 if (refChoices[choiceIndex] != nextChoice) {
640 int expectedChoice = refChoices[choiceIndex];
641 int currCGIndex = icsCG.getNextChoiceIndex();
642 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
643 icsCG.setChoice(currCGIndex, expectedChoice);
646 // Get state ID and associate it with this transition
647 int stateId = vm.getStateId();
648 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
649 // Add new transition to the current execution and map it in R-Graph
650 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
651 rGraph.addReachableTransition(stId, transition);
653 currentExecution.mapCGToChoice(icsCG, choiceCounter);
654 // Store restorable state object for this state (always store the latest)
655 if (!restorableStateMap.containsKey(stateId)) {
656 RestorableVMState restorableState = vm.getRestorableState();
657 restorableStateMap.put(stateId, restorableState);
661 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
662 // Get a new transition
663 TransitionEvent transition;
664 if (currentExecution.isNew()) {
665 // We need to handle the first transition differently because this has a predecessor execution
666 transition = currentExecution.getFirstTransition();
668 transition = new TransitionEvent();
669 currentExecution.addTransition(transition);
670 transition.recordPredecessor(currentExecution, choiceCounter - 1);
672 transition.setExecution(currentExecution);
673 transition.setTransitionCG(icsCG);
674 transition.setStateId(stateId);
675 transition.setChoice(refChoices[choiceIndex]);
676 transition.setChoiceCounter(choiceCounter);
681 // --- Functions related to cycle detection and reachability graph
683 // Detect cycles in the current execution/trace
684 // We terminate the execution iff:
685 // (1) the state has been visited in the current execution
686 // (2) the state has one or more cycles that involve all the events
687 // With simple approach we only need to check for a re-visited state.
688 // Basically, we have to check that we have executed all events between two occurrences of such state.
689 private boolean completeFullCycle(int stId) {
690 // False if the state ID hasn't been recorded
691 if (!stateToEventMap.containsKey(stId)) {
694 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
695 // Check if this set contains all the event choices
696 // If not then this is not the terminating condition
697 for(int i=0; i<=maxEventChoice; i++) {
698 if (!visitedEvents.contains(i)) {
705 private void initializeStatesVariables() {
712 currVisitedStates = new HashSet<>();
713 justVisitedStates = new HashSet<>();
714 prevVisitedStates = new HashSet<>();
715 stateToEventMap = new HashMap<>();
717 backtrackMap = new HashMap<>();
718 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
719 currentExecution = new Execution();
720 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
721 doneBacktrackSet = new HashSet<>();
722 rGraph = new RGraph();
724 isEndOfExecution = false;
727 private void mapStateToEvent(int nextChoiceValue) {
728 // Update all states with this event/choice
729 // This means that all past states now see this transition
730 Set<Integer> stateSet = stateToEventMap.keySet();
731 for(Integer stateId : stateSet) {
732 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
733 eventSet.add(nextChoiceValue);
737 private boolean terminateCurrentExecution() {
738 // We need to check all the states that have just been visited
739 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
740 for(Integer stateId : justVisitedStates) {
741 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
748 private void updateStateInfo(Search search) {
749 // Update the state variables
750 int stateId = search.getStateId();
751 // Insert state ID into the map if it is new
752 if (!stateToEventMap.containsKey(stateId)) {
753 HashSet<Integer> eventSet = new HashSet<>();
754 stateToEventMap.put(stateId, eventSet);
756 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
757 justVisitedStates.add(stateId);
758 if (!prevVisitedStates.contains(stateId)) {
759 // It is a currently visited states if the state has not been seen in previous executions
760 currVisitedStates.add(stateId);
764 // --- Functions related to Read/Write access analysis on shared fields
766 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
767 // Insert backtrack point to the right state ID
768 LinkedList<BacktrackExecution> backtrackExecList;
769 if (backtrackMap.containsKey(stateId)) {
770 backtrackExecList = backtrackMap.get(stateId);
772 backtrackExecList = new LinkedList<>();
773 backtrackMap.put(stateId, backtrackExecList);
775 // Add the new backtrack execution object
776 TransitionEvent backtrackTransition = new TransitionEvent();
777 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
778 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
779 // Add to priority queue
780 if (!backtrackStateQ.contains(stateId)) {
781 backtrackStateQ.add(stateId);
785 // Analyze Read/Write accesses that are directly invoked on fields
786 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
787 // Get the field info
788 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
789 // Analyze only after being initialized
790 String fieldClass = fieldInfo.getFullName();
791 // Do the analysis to get Read and Write accesses to fields
792 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
793 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
794 // Record the field in the map
795 if (executedInsn instanceof WriteInstruction) {
796 // We first check the non-relevant fields set
797 if (!nonRelevantFields.contains(fieldInfo)) {
798 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
799 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
800 if (fieldClass.startsWith(str)) {
801 nonRelevantFields.add(fieldInfo);
806 // If we have this field in the non-relevant fields set then we return right away
809 rwSet.addWriteField(fieldClass, objectId);
810 } else if (executedInsn instanceof ReadInstruction) {
811 rwSet.addReadField(fieldClass, objectId);
815 // Analyze Read accesses that are indirect (performed through iterators)
816 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
817 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
819 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
820 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
821 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
822 // Extract info from the stack frame
823 StackFrame frame = ti.getTopFrame();
824 int[] frameSlots = frame.getSlots();
825 // Get the Groovy callsite library at index 0
826 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
827 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
830 // Get the iterated object whose property is accessed
831 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
832 if (eiAccessObj == null) {
835 // We exclude library classes (they start with java, org, etc.) and some more
836 ClassInfo classInfo = eiAccessObj.getClassInfo();
837 String objClassName = classInfo.getName();
838 // Check if this class info is part of the non-relevant classes set already
839 if (!nonRelevantClasses.contains(classInfo)) {
840 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
841 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
842 nonRelevantClasses.add(classInfo);
846 // If it is part of the non-relevant classes set then return immediately
849 // Extract fields from this object and put them into the read write
850 int numOfFields = eiAccessObj.getNumberOfFields();
851 for(int i=0; i<numOfFields; i++) {
852 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
853 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
854 String fieldClass = fieldInfo.getFullName();
855 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
856 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
857 // Record the field in the map
858 rwSet.addReadField(fieldClass, objectId);
864 private int checkAndAdjustChoice(int currentChoice, VM vm) {
865 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
866 // for certain method calls in the infrastructure, e.g., eventSince()
867 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
868 // This is the main event CG
869 if (currentCG instanceof IntIntervalGenerator) {
870 // This is the interval CG used in device handlers
871 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
872 // Iterate until we find the IntChoiceFromSet CG
873 while (!(parentCG instanceof IntChoiceFromSet)) {
874 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
876 // Find the choice related to the IntIntervalGenerator CG from the map
877 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
879 return currentChoice;
882 private void createBacktrackingPoint(Execution execution, int currentChoice,
883 Execution conflictExecution, int conflictChoice) {
884 // Create a new list of choices for backtrack based on the current choice and conflicting event number
885 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
886 // for the original set {0, 1, 2, 3}
887 Integer[] newChoiceList = new Integer[refChoices.length];
888 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
889 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
890 int currChoice = currentTrace.get(currentChoice).getChoice();
891 int stateId = conflictTrace.get(conflictChoice).getStateId();
892 // Check if this trace has been done from this state
893 if (isTraceAlreadyConstructed(currChoice, stateId)) {
896 // Put the conflicting event numbers first and reverse the order
897 newChoiceList[0] = currChoice;
898 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
899 for (int i = 0, j = 1; i < refChoices.length; i++) {
900 if (refChoices[i] != newChoiceList[0]) {
901 newChoiceList[j] = refChoices[i];
905 // Predecessor of the new backtrack point is the same as the conflict point's
906 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
909 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
910 for (String excludedField : excludedStrings) {
911 if (className.contains(excludedField)) {
918 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
919 for (String excludedField : excludedStrings) {
920 if (className.endsWith(excludedField)) {
927 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
928 for (String excludedField : excludedStrings) {
929 if (className.startsWith(excludedField)) {
936 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
937 // Check if we are reaching the end of our execution: no more backtracking points to explore
938 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
939 if (!backtrackStateQ.isEmpty()) {
940 // Set done all the other backtrack points
941 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
942 backtrackTransition.getTransitionCG().setDone();
944 // Reset the next backtrack point with the latest state
945 int hiStateId = backtrackStateQ.peek();
946 // Restore the state first if necessary
947 if (vm.getStateId() != hiStateId) {
948 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
949 vm.restoreState(restorableState);
951 // Set the backtrack CG
952 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
953 setBacktrackCG(hiStateId, backtrackCG);
955 // Set done this last CG (we save a few rounds)
958 // Save all the visited states when starting a new execution of trace
959 prevVisitedStates.addAll(currVisitedStates);
960 // This marks a transitional period to the new CG
961 isEndOfExecution = true;
964 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
965 ReadWriteSet currRWSet) {
966 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
967 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
968 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
969 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
970 if (!confRWFieldsMap.containsKey(conflictChoice) ||
971 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
974 // R/W set of choice/event that may have a potential conflict
975 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
976 // Check for conflicts with Read and Write fields for Write instructions
977 Set<String> currWriteSet = currRWSet.getWriteSet();
978 for(String writeField : currWriteSet) {
979 int currObjId = currRWSet.writeFieldObjectId(writeField);
980 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
981 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
982 // Remove this from the write set as we are tracking per memory location
983 currRWSet.removeWriteField(writeField);
987 // Check for conflicts with Write fields for Read instructions
988 Set<String> currReadSet = currRWSet.getReadSet();
989 for(String readField : currReadSet) {
990 int currObjId = currRWSet.readFieldObjectId(readField);
991 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
992 // Remove this from the read set as we are tracking per memory location
993 currRWSet.removeReadField(readField);
997 // Return false if no conflict is found
1001 private ReadWriteSet getReadWriteSet(int currentChoice) {
1002 // Do the analysis to get Read and Write accesses to fields
1004 // We already have an entry
1005 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1006 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1007 rwSet = currReadWriteFieldsMap.get(currentChoice);
1008 } else { // We need to create a new entry
1009 rwSet = new ReadWriteSet();
1010 currReadWriteFieldsMap.put(currentChoice, rwSet);
1015 private boolean isFieldExcluded(Instruction executedInsn) {
1016 // Get the field info
1017 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1018 // Check if the non-relevant fields set already has it
1019 if (nonRelevantFields.contains(fieldInfo)) {
1022 // Check if the relevant fields set already has it
1023 if (relevantFields.contains(fieldInfo)) {
1026 // Analyze only after being initialized
1027 String field = fieldInfo.getFullName();
1028 // Check against "starts-with", "ends-with", and "contains" list
1029 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1030 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1031 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1032 nonRelevantFields.add(fieldInfo);
1035 relevantFields.add(fieldInfo);
1039 // Check if this trace is already constructed
1040 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1041 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1042 // TODO: THIS IS AN OPTIMIZATION!
1043 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
1044 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
1045 // The second time this event 1 is explored, it will generate the same state as the first one
1046 StringBuilder sb = new StringBuilder();
1049 sb.append(firstChoice);
1050 // Check if the trace has been constructed as a backtrack point for this state
1051 if (doneBacktrackSet.contains(sb.toString())) {
1054 doneBacktrackSet.add(sb.toString());
1058 // Reset data structure for each new execution
1059 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1060 if (choices == null || choices != icsCG.getAllChoices()) {
1061 // Reset state variables
1063 choices = icsCG.getAllChoices();
1064 refChoices = copyChoices(choices);
1065 // Clear data structures
1066 currVisitedStates = new HashSet<>();
1067 stateToEventMap = new HashMap<>();
1068 isEndOfExecution = false;
1072 // Set a backtrack point for a particular state
1073 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1074 // Set a backtrack CG based on a state ID
1075 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1076 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1077 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1078 backtrackCG.setStateId(stateId);
1079 backtrackCG.reset();
1080 // Update current execution with this new execution
1081 Execution newExecution = new Execution();
1082 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1083 newExecution.addTransition(firstTransition);
1084 // Try to free some memory since this map is only used for the current execution
1085 currentExecution.clearCGToChoiceMap();
1086 currentExecution = newExecution;
1087 // Remove from the queue if we don't have more backtrack points for that state
1088 if (backtrackExecutions.isEmpty()) {
1089 backtrackMap.remove(stateId);
1090 backtrackStateQ.remove(stateId);
1094 // Update backtrack sets
1095 // 1) recursively, and
1096 // 2) track accesses per memory location (per shared variable/field)
1097 private void updateBacktrackSet(Execution execution, int currentChoice) {
1098 // Copy ReadWriteSet object
1099 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1100 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1101 if (currRWSet == null) {
1104 currRWSet = currRWSet.getCopy();
1105 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1106 HashSet<TransitionEvent> visited = new HashSet<>();
1107 // Update backtrack set recursively
1108 // TODO: The following is the call to the original version of the method
1109 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1110 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1111 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1114 // TODO: This is the original version of the recursive method
1115 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1116 // Execution conflictExecution, int conflictChoice,
1117 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1118 // // Halt when we have found the first read/write conflicts for all memory locations
1119 // if (currRWSet.isEmpty()) {
1122 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1123 // // Halt when we have visited this transition (in a cycle)
1124 // if (visited.contains(confTrans)) {
1127 // visited.add(confTrans);
1128 // // Explore all predecessors
1129 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1130 // // Get the predecessor (previous conflict choice)
1131 // conflictChoice = predecessor.getChoice();
1132 // conflictExecution = predecessor.getExecution();
1133 // // Check if a conflict is found
1134 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1135 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1137 // // Continue performing DFS if conflict is not found
1138 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1142 // TODO: This is the version of the method with pushing up happens-before transitions
1143 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1144 Execution conflictExecution, int conflictChoice,
1145 Execution hbExecution, int hbChoice,
1146 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1147 // Halt when we have found the first read/write conflicts for all memory locations
1148 if (currRWSet.isEmpty()) {
1151 TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1152 // Halt when we have visited this transition (in a cycle)
1153 if (visited.contains(confTrans)) {
1156 visited.add(confTrans);
1157 // Explore all predecessors
1158 for (Predecessor predecessor : confTrans.getPredecessors()) {
1159 // Get the predecessor (previous conflict choice)
1160 conflictChoice = predecessor.getChoice();
1161 conflictExecution = predecessor.getExecution();
1162 // Push up one happens-before transition
1163 int pushedChoice = hbChoice;
1164 Execution pushedExecution = hbExecution;
1165 // Check if a conflict is found
1166 if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1167 createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1168 pushedChoice = conflictChoice;
1169 pushedExecution = conflictExecution;
1171 // Continue performing DFS if conflict is not found
1172 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1173 pushedExecution, pushedChoice, currRWSet, visited);
1175 // Remove the transition after being explored
1176 // TODO: Seems to cause a lot of loops---commented out for now
1177 //visited.remove(confTrans);
1180 // --- Functions related to the reachability analysis when there is a state match
1182 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1183 // Perform this analysis only when:
1184 // 1) this is not during a switch to a new execution,
1185 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1186 // 3) state > 0 (state 0 is for boolean CG)
1187 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1188 if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1189 // Update reachable transitions in the graph with a predecessor
1190 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1191 for(TransitionEvent transition : reachableTransitions) {
1192 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1194 updateBacktrackSetsFromPreviousExecution(stateId);
1199 // Update the backtrack sets from previous executions
1200 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1201 // Collect all the reachable transitions from R-Graph
1202 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1203 for(TransitionEvent transition : reachableTransitions) {
1204 Execution execution = transition.getExecution();
1205 int currentChoice = transition.getChoiceCounter();
1206 updateBacktrackSet(execution, currentChoice);