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 if (!isEndOfExecution) {
200 // Check if CG has been initialized, otherwise initialize it
201 Integer[] cgChoices = icsCG.getAllChoices();
202 // Record the events (from choices)
203 if (choices == null) {
205 // Make a copy of choices as reference
206 refChoices = copyChoices(choices);
207 // Record the max event choice (the last element of the choice array)
208 maxEventChoice = choices[choices.length - 1];
210 icsCG.setNewValues(choices);
212 // Use a modulo since choiceCounter is going to keep increasing
213 int choiceIndex = choiceCounter % choices.length;
214 icsCG.advance(choices[choiceIndex]);
216 // Set done all CGs while transitioning to a new execution
224 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
225 if (stateReductionMode) {
226 // Check the boolean CG and if it is flipped, we are resetting the analysis
227 if (currentCG instanceof BooleanChoiceGenerator) {
228 if (!isBooleanCGFlipped) {
229 isBooleanCGFlipped = true;
231 // Number of conflicts = first trace + subsequent backtrack points
232 numOfConflicts = 1 + doneBacktrackSet.size();
233 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
234 initializeStatesVariables();
237 // Check every choice generated and ensure fair scheduling!
238 if (currentCG instanceof IntChoiceFromSet) {
239 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
240 // If this is a new CG then we need to update data structures
241 resetStatesForNewExecution(icsCG, vm);
242 // If we don't see a fair scheduling of events/choices then we have to enforce it
243 ensureFairSchedulingAndSetupTransition(icsCG, vm);
244 // Update backtrack set of an executed event (transition): one transition before this one
245 updateBacktrackSet(currentExecution, choiceCounter - 1);
246 // Explore the next backtrack point:
247 // 1) if we have seen this state or this state contains cycles that involve all events, and
248 // 2) after the current CG is advanced at least once
249 if (terminateCurrentExecution() && choiceCounter > 0) {
250 exploreNextBacktrackPoints(vm, icsCG);
254 // Map state to event
255 mapStateToEvent(icsCG.getNextChoice());
256 justVisitedStates.clear();
265 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
266 if (stateReductionMode) {
267 if (!isEndOfExecution) {
268 // Has to be initialized and a integer CG
269 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
270 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
271 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
272 if (currentChoice < 0) { // If choice is -1 then skip
275 currentChoice = checkAndAdjustChoice(currentChoice, vm);
276 // Record accesses from executed instructions
277 if (executedInsn instanceof JVMFieldInstruction) {
278 // We don't care about libraries
279 if (!isFieldExcluded(executedInsn)) {
280 analyzeReadWriteAccesses(executedInsn, currentChoice);
282 } else if (executedInsn instanceof INVOKEINTERFACE) {
283 // Handle the read/write accesses that occur through iterators
284 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
296 // This class compactly stores backtrack execution:
297 // 1) backtrack choice list, and
298 // 2) first backtrack point (linking with predecessor execution)
299 private class BacktrackExecution {
300 private Integer[] choiceList;
301 private TransitionEvent firstTransition;
303 public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
304 choiceList = choList;
305 firstTransition = fTransition;
308 public Integer[] getChoiceList() {
312 public TransitionEvent getFirstTransition() {
313 return firstTransition;
317 // This class stores a representation of an execution
318 // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
319 // TODO: We basically need to keep track of:
320 // TODO: (1) last read/write access to each memory location
321 // TODO: (2) last state with two or more incoming events/transitions
322 private class Execution {
323 private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap; // Map between CG to choice numbers for O(1) access
324 private ArrayList<TransitionEvent> executionTrace; // The BacktrackPoint objects of this execution
325 private boolean isNew; // Track if this is the first time it is accessed
326 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
327 private HashMap<Integer, TransitionEvent> stateToTransitionMap; // For O(1) access to backtrack point
330 cgToChoiceMap = new HashMap<>();
331 executionTrace = new ArrayList<>();
333 readWriteFieldsMap = new HashMap<>();
334 stateToTransitionMap = 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 HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
358 return readWriteFieldsMap;
361 public TransitionEvent getTransitionFromState(int stateId) {
362 if (stateToTransitionMap.containsKey(stateId)) {
363 return stateToTransitionMap.get(stateId);
365 // Return the latest transition for unseen states (that have just been encountered in this transition)
366 return executionTrace.get(executionTrace.size() - 1);
369 public boolean isNew() {
371 // Right after this is accessed, it is no longer new
378 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
379 cgToChoiceMap.put(icsCG, choice);
382 public void mapStateToTransition(int stateId, TransitionEvent transition) {
383 stateToTransitionMap.put(stateId, transition);
387 // This class compactly stores a predecessor
388 // 1) a predecessor execution
389 // 2) the predecessor choice in that predecessor execution
390 private class Predecessor {
391 private int choice; // Predecessor choice
392 private Execution execution; // Predecessor execution
394 public Predecessor(int predChoice, Execution predExec) {
396 execution = predExec;
399 public int getChoice() {
403 public Execution getExecution() {
408 // This class represents a R-Graph (in the paper it is a state transition graph R)
409 // This implementation stores reachable transitions from and connects with past executions
410 private class RGraph {
411 private int hiStateId; // Maximum state Id
412 private HashMap<Integer, HashSet<TransitionEvent>> graph; // Reachable transitions from past executions
416 graph = new HashMap<>();
419 public void addReachableTransition(int stateId, TransitionEvent transition) {
420 HashSet<TransitionEvent> transitionSet;
421 if (graph.containsKey(stateId)) {
422 transitionSet = graph.get(stateId);
424 transitionSet = new HashSet<>();
425 graph.put(stateId, transitionSet);
427 // Insert into the set if it does not contain it yet
428 if (!transitionSet.contains(transition)) {
429 transitionSet.add(transition);
431 // Update highest state ID
432 if (hiStateId < stateId) {
437 public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
438 return graph.get(stateId);
441 public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
442 HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
443 // All transitions from states higher than the given state ID (until the highest state ID) are reachable
444 for(int stId = stateId; stId <= hiStateId; stId++) {
445 reachableTransitions.addAll(graph.get(stId));
447 return reachableTransitions;
451 // This class compactly stores Read and Write field sets
452 // We store the field name and its object ID
453 // Sharing the same field means the same field name and object ID
454 private class ReadWriteSet {
455 private HashMap<String, Integer> readMap;
456 private HashMap<String, Integer> writeMap;
458 public ReadWriteSet() {
459 readMap = new HashMap<>();
460 writeMap = new HashMap<>();
463 public void addReadField(String field, int objectId) {
464 readMap.put(field, objectId);
467 public void addWriteField(String field, int objectId) {
468 writeMap.put(field, objectId);
471 public void removeReadField(String field) {
472 readMap.remove(field);
475 public void removeWriteField(String field) {
476 writeMap.remove(field);
479 public boolean isEmpty() {
480 return readMap.isEmpty() && writeMap.isEmpty();
483 public ReadWriteSet getCopy() {
484 ReadWriteSet copyRWSet = new ReadWriteSet();
485 // Copy the maps in the set into the new object copy
486 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
487 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
491 public Set<String> getReadSet() {
492 return readMap.keySet();
495 public Set<String> getWriteSet() {
496 return writeMap.keySet();
499 public boolean readFieldExists(String field) {
500 return readMap.containsKey(field);
503 public boolean writeFieldExists(String field) {
504 return writeMap.containsKey(field);
507 public int readFieldObjectId(String field) {
508 return readMap.get(field);
511 public int writeFieldObjectId(String field) {
512 return writeMap.get(field);
515 private HashMap<String, Integer> getReadMap() {
519 private HashMap<String, Integer> getWriteMap() {
523 private void setReadMap(HashMap<String, Integer> rMap) {
527 private void setWriteMap(HashMap<String, Integer> wMap) {
532 // This class compactly stores transitions:
536 // 4) predecessors (for backward DFS).
537 private class TransitionEvent {
538 private int choice; // Choice chosen at this transition
539 private int choiceCounter; // Choice counter at this transition
540 private Execution execution; // The execution where this transition belongs
541 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
542 private int stateId; // State at this transition
543 private IntChoiceFromSet transitionCG; // CG at this transition
545 public TransitionEvent() {
549 predecessors = new HashSet<>();
554 public int getChoice() {
558 public int getChoiceCounter() {
559 return choiceCounter;
562 public Execution getExecution() {
566 public HashSet<Predecessor> getPredecessors() {
570 public int getStateId() {
574 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
576 public void recordPredecessor(Execution execution, int choice) {
577 predecessors.add(new Predecessor(choice, execution));
580 public void setChoice(int cho) {
584 public void setChoiceCounter(int choCounter) {
585 choiceCounter = choCounter;
588 public void setExecution(Execution exec) {
592 public void setPredecessors(HashSet<Predecessor> preds) {
593 predecessors = new HashSet<>(preds);
596 public void setStateId(int stId) {
600 public void setTransitionCG(IntChoiceFromSet cg) {
606 private final static String DO_CALL_METHOD = "doCall";
607 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
608 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
609 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
610 // Groovy library created fields
611 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
613 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
614 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
615 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
616 // Java and Groovy libraries
617 { "java", "org", "sun", "com", "gov", "groovy"};
618 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
619 private final static String GET_PROPERTY_METHOD =
620 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
621 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
622 private final static String JAVA_INTEGER = "int";
623 private final static String JAVA_STRING_LIB = "java.lang.String";
626 private Integer[] copyChoices(Integer[] choicesToCopy) {
628 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
629 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
630 return copyOfChoices;
633 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
634 // Check the next choice and if the value is not the same as the expected then force the expected value
635 int choiceIndex = choiceCounter % refChoices.length;
636 int nextChoice = icsCG.getNextChoice();
637 if (refChoices[choiceIndex] != nextChoice) {
638 int expectedChoice = refChoices[choiceIndex];
639 int currCGIndex = icsCG.getNextChoiceIndex();
640 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
641 icsCG.setChoice(currCGIndex, expectedChoice);
644 // Get state ID and associate it with this transition
645 int stateId = vm.getStateId();
646 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
647 // Add new transition to the current execution and map it in R-Graph
648 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
649 rGraph.addReachableTransition(stId, transition);
650 currentExecution.mapStateToTransition(stId, transition);
652 currentExecution.mapCGToChoice(icsCG, choiceCounter);
653 // Store restorable state object for this state (always store the latest)
654 RestorableVMState restorableState = vm.getRestorableState();
655 restorableStateMap.put(stateId, restorableState);
658 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
659 // Get a new transition
660 TransitionEvent transition;
661 if (currentExecution.isNew()) {
662 // We need to handle the first transition differently because this has a predecessor execution
663 transition = currentExecution.getFirstTransition();
665 transition = new TransitionEvent();
666 currentExecution.addTransition(transition);
667 transition.recordPredecessor(currentExecution, choiceCounter - 1);
669 transition.setExecution(currentExecution);
670 transition.setTransitionCG(icsCG);
671 transition.setStateId(stateId);
672 transition.setChoice(refChoices[choiceIndex]);
673 transition.setChoiceCounter(choiceCounter);
678 // --- Functions related to cycle detection and reachability graph
680 // Detect cycles in the current execution/trace
681 // We terminate the execution iff:
682 // (1) the state has been visited in the current execution
683 // (2) the state has one or more cycles that involve all the events
684 // With simple approach we only need to check for a re-visited state.
685 // Basically, we have to check that we have executed all events between two occurrences of such state.
686 private boolean completeFullCycle(int stId) {
687 // False if the state ID hasn't been recorded
688 if (!stateToEventMap.containsKey(stId)) {
691 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
692 // Check if this set contains all the event choices
693 // If not then this is not the terminating condition
694 for(int i=0; i<=maxEventChoice; i++) {
695 if (!visitedEvents.contains(i)) {
702 private void initializeStatesVariables() {
709 currVisitedStates = new HashSet<>();
710 justVisitedStates = new HashSet<>();
711 prevVisitedStates = new HashSet<>();
712 stateToEventMap = new HashMap<>();
714 backtrackMap = new HashMap<>();
715 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
716 currentExecution = new Execution();
717 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
718 doneBacktrackSet = new HashSet<>();
719 rGraph = new RGraph();
721 isEndOfExecution = false;
724 private void mapStateToEvent(int nextChoiceValue) {
725 // Update all states with this event/choice
726 // This means that all past states now see this transition
727 Set<Integer> stateSet = stateToEventMap.keySet();
728 for(Integer stateId : stateSet) {
729 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
730 eventSet.add(nextChoiceValue);
734 private boolean terminateCurrentExecution() {
735 // We need to check all the states that have just been visited
736 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
737 for(Integer stateId : justVisitedStates) {
738 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
745 private void updateStateInfo(Search search) {
746 // Update the state variables
747 int stateId = search.getStateId();
748 // Insert state ID into the map if it is new
749 if (!stateToEventMap.containsKey(stateId)) {
750 HashSet<Integer> eventSet = new HashSet<>();
751 stateToEventMap.put(stateId, eventSet);
753 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
754 justVisitedStates.add(stateId);
755 if (!prevVisitedStates.contains(stateId)) {
756 // It is a currently visited states if the state has not been seen in previous executions
757 currVisitedStates.add(stateId);
761 // --- Functions related to Read/Write access analysis on shared fields
763 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
764 // Insert backtrack point to the right state ID
765 LinkedList<BacktrackExecution> backtrackExecList;
766 if (backtrackMap.containsKey(stateId)) {
767 backtrackExecList = backtrackMap.get(stateId);
769 backtrackExecList = new LinkedList<>();
770 backtrackMap.put(stateId, backtrackExecList);
772 // Add the new backtrack execution object
773 TransitionEvent backtrackTransition = new TransitionEvent();
774 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
775 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
776 // Add to priority queue
777 if (!backtrackStateQ.contains(stateId)) {
778 backtrackStateQ.add(stateId);
782 // Analyze Read/Write accesses that are directly invoked on fields
783 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
784 // Get the field info
785 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
786 // Analyze only after being initialized
787 String fieldClass = fieldInfo.getFullName();
788 // Do the analysis to get Read and Write accesses to fields
789 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
790 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
791 // Record the field in the map
792 if (executedInsn instanceof WriteInstruction) {
793 // We first check the non-relevant fields set
794 if (!nonRelevantFields.contains(fieldInfo)) {
795 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
796 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
797 if (fieldClass.startsWith(str)) {
798 nonRelevantFields.add(fieldInfo);
803 // If we have this field in the non-relevant fields set then we return right away
806 rwSet.addWriteField(fieldClass, objectId);
807 } else if (executedInsn instanceof ReadInstruction) {
808 rwSet.addReadField(fieldClass, objectId);
812 // Analyze Read accesses that are indirect (performed through iterators)
813 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
814 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
816 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
817 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
818 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
819 // Extract info from the stack frame
820 StackFrame frame = ti.getTopFrame();
821 int[] frameSlots = frame.getSlots();
822 // Get the Groovy callsite library at index 0
823 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
824 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
827 // Get the iterated object whose property is accessed
828 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
829 if (eiAccessObj == null) {
832 // We exclude library classes (they start with java, org, etc.) and some more
833 ClassInfo classInfo = eiAccessObj.getClassInfo();
834 String objClassName = classInfo.getName();
835 // Check if this class info is part of the non-relevant classes set already
836 if (!nonRelevantClasses.contains(classInfo)) {
837 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
838 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
839 nonRelevantClasses.add(classInfo);
843 // If it is part of the non-relevant classes set then return immediately
846 // Extract fields from this object and put them into the read write
847 int numOfFields = eiAccessObj.getNumberOfFields();
848 for(int i=0; i<numOfFields; i++) {
849 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
850 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
851 String fieldClass = fieldInfo.getFullName();
852 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
853 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
854 // Record the field in the map
855 rwSet.addReadField(fieldClass, objectId);
861 private int checkAndAdjustChoice(int currentChoice, VM vm) {
862 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
863 // for certain method calls in the infrastructure, e.g., eventSince()
864 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
865 // This is the main event CG
866 if (currentCG instanceof IntIntervalGenerator) {
867 // This is the interval CG used in device handlers
868 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
869 // Iterate until we find the IntChoiceFromSet CG
870 while (!(parentCG instanceof IntChoiceFromSet)) {
871 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
873 // Find the choice related to the IntIntervalGenerator CG from the map
874 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
876 return currentChoice;
879 private void createBacktrackingPoint(Execution execution, int currentChoice,
880 Execution conflictExecution, int conflictChoice) {
881 // Create a new list of choices for backtrack based on the current choice and conflicting event number
882 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
883 // for the original set {0, 1, 2, 3}
884 Integer[] newChoiceList = new Integer[refChoices.length];
885 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
886 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
887 int currChoice = currentTrace.get(currentChoice).getChoice();
888 int stateId = conflictTrace.get(conflictChoice).getStateId();
889 // Check if this trace has been done from this state
890 if (isTraceAlreadyConstructed(currChoice, stateId)) {
893 // Put the conflicting event numbers first and reverse the order
894 newChoiceList[0] = currChoice;
895 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
896 for (int i = 0, j = 1; i < refChoices.length; i++) {
897 if (refChoices[i] != newChoiceList[0]) {
898 newChoiceList[j] = refChoices[i];
902 // Predecessor of the new backtrack point is the same as the conflict point's
903 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
906 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
907 for (String excludedField : excludedStrings) {
908 if (className.contains(excludedField)) {
915 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
916 for (String excludedField : excludedStrings) {
917 if (className.endsWith(excludedField)) {
924 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
925 for (String excludedField : excludedStrings) {
926 if (className.startsWith(excludedField)) {
933 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
934 // Check if we are reaching the end of our execution: no more backtracking points to explore
935 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
936 if (!backtrackStateQ.isEmpty()) {
937 // Set done all the other backtrack points
938 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
939 backtrackTransition.getTransitionCG().setDone();
941 // Reset the next backtrack point with the latest state
942 int hiStateId = backtrackStateQ.peek();
943 // Restore the state first if necessary
944 if (vm.getStateId() != hiStateId) {
945 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
946 vm.restoreState(restorableState);
948 // Set the backtrack CG
949 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
950 setBacktrackCG(hiStateId, backtrackCG);
952 // Set done this last CG (we save a few rounds)
955 // Save all the visited states when starting a new execution of trace
956 prevVisitedStates.addAll(currVisitedStates);
957 // This marks a transitional period to the new CG
958 isEndOfExecution = true;
961 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
962 ReadWriteSet currRWSet) {
963 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
964 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
965 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
966 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
967 if (!confRWFieldsMap.containsKey(conflictChoice) ||
968 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
971 // R/W set of choice/event that may have a potential conflict
972 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
973 // Check for conflicts with Read and Write fields for Write instructions
974 Set<String> currWriteSet = currRWSet.getWriteSet();
975 for(String writeField : currWriteSet) {
976 int currObjId = currRWSet.writeFieldObjectId(writeField);
977 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
978 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
979 // Remove this from the write set as we are tracking per memory location
980 currRWSet.removeWriteField(writeField);
984 // Check for conflicts with Write fields for Read instructions
985 Set<String> currReadSet = currRWSet.getReadSet();
986 for(String readField : currReadSet) {
987 int currObjId = currRWSet.readFieldObjectId(readField);
988 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
989 // Remove this from the read set as we are tracking per memory location
990 currRWSet.removeReadField(readField);
994 // Return false if no conflict is found
998 private ReadWriteSet getReadWriteSet(int currentChoice) {
999 // Do the analysis to get Read and Write accesses to fields
1001 // We already have an entry
1002 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1003 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1004 rwSet = currReadWriteFieldsMap.get(currentChoice);
1005 } else { // We need to create a new entry
1006 rwSet = new ReadWriteSet();
1007 currReadWriteFieldsMap.put(currentChoice, rwSet);
1012 private boolean isFieldExcluded(Instruction executedInsn) {
1013 // Get the field info
1014 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1015 // Check if the non-relevant fields set already has it
1016 if (nonRelevantFields.contains(fieldInfo)) {
1019 // Check if the relevant fields set already has it
1020 if (relevantFields.contains(fieldInfo)) {
1023 // Analyze only after being initialized
1024 String field = fieldInfo.getFullName();
1025 // Check against "starts-with", "ends-with", and "contains" list
1026 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1027 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1028 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1029 nonRelevantFields.add(fieldInfo);
1032 relevantFields.add(fieldInfo);
1036 // Check if this trace is already constructed
1037 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1038 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1039 // TODO: THIS IS AN OPTIMIZATION!
1040 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
1041 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
1042 // The second time this event 1 is explored, it will generate the same state as the first one
1043 StringBuilder sb = new StringBuilder();
1046 sb.append(firstChoice);
1047 // Check if the trace has been constructed as a backtrack point for this state
1048 if (doneBacktrackSet.contains(sb.toString())) {
1051 doneBacktrackSet.add(sb.toString());
1055 // Reset data structure for each new execution
1056 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1057 if (choices == null || choices != icsCG.getAllChoices()) {
1058 // Reset state variables
1060 choices = icsCG.getAllChoices();
1061 refChoices = copyChoices(choices);
1062 // Clear data structures
1063 currVisitedStates = new HashSet<>();
1064 stateToEventMap = new HashMap<>();
1065 isEndOfExecution = false;
1069 // Set a backtrack point for a particular state
1070 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1071 // Set a backtrack CG based on a state ID
1072 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1073 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1074 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1075 backtrackCG.setStateId(stateId);
1076 backtrackCG.reset();
1077 // Update current execution with this new execution
1078 Execution newExecution = new Execution();
1079 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1080 newExecution.addTransition(firstTransition);
1081 // Try to free some memory since this map is only used for the current execution
1082 currentExecution.clearCGToChoiceMap();
1083 currentExecution = newExecution;
1084 // Remove from the queue if we don't have more backtrack points for that state
1085 if (backtrackExecutions.isEmpty()) {
1086 backtrackMap.remove(stateId);
1087 backtrackStateQ.remove(stateId);
1091 // Update backtrack sets
1092 // 1) recursively, and
1093 // 2) track accesses per memory location (per shared variable/field)
1094 private void updateBacktrackSet(Execution execution, int currentChoice) {
1095 // Copy ReadWriteSet object
1096 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1097 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1098 if (currRWSet == null) {
1101 currRWSet = currRWSet.getCopy();
1102 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1103 HashSet<TransitionEvent> visited = new HashSet<>();
1104 // Update backtrack set recursively
1105 // TODO: The following is the call to the original version of the method
1106 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1107 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1108 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1111 // TODO: This is the original version of the recursive method
1112 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1113 // Execution conflictExecution, int conflictChoice,
1114 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1115 // // Halt when we have found the first read/write conflicts for all memory locations
1116 // if (currRWSet.isEmpty()) {
1119 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1120 // // Halt when we have visited this transition (in a cycle)
1121 // if (visited.contains(confTrans)) {
1124 // visited.add(confTrans);
1125 // // Explore all predecessors
1126 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1127 // // Get the predecessor (previous conflict choice)
1128 // conflictChoice = predecessor.getChoice();
1129 // conflictExecution = predecessor.getExecution();
1130 // // Check if a conflict is found
1131 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1132 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1134 // // Continue performing DFS if conflict is not found
1135 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1139 // TODO: This is the version of the method with pushing up happens-before transitions
1140 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1141 Execution conflictExecution, int conflictChoice,
1142 Execution hbExecution, int hbChoice,
1143 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1144 // Halt when we have found the first read/write conflicts for all memory locations
1145 if (currRWSet.isEmpty()) {
1148 TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1149 // Halt when we have visited this transition (in a cycle)
1150 if (visited.contains(confTrans)) {
1153 visited.add(confTrans);
1154 // Explore all predecessors
1155 for (Predecessor predecessor : confTrans.getPredecessors()) {
1156 // Get the predecessor (previous conflict choice)
1157 conflictChoice = predecessor.getChoice();
1158 conflictExecution = predecessor.getExecution();
1159 // Push up one happens-before transition
1160 int pushedChoice = hbChoice;
1161 Execution pushedExecution = hbExecution;
1162 // Check if a conflict is found
1163 if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1164 createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1165 pushedChoice = conflictChoice;
1166 pushedExecution = conflictExecution;
1168 // Continue performing DFS if conflict is not found
1169 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1170 pushedExecution, pushedChoice, currRWSet, visited);
1174 // --- Functions related to the reachability analysis when there is a state match
1176 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1177 // Perform this analysis only when:
1178 // 1) this is not during a switch to a new execution,
1179 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1180 // 3) state > 0 (state 0 is for boolean CG)
1181 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1182 if (currVisitedStates.contains(stateId)) {
1183 // Get the backtrack point from the current execution
1184 TransitionEvent transition = currentExecution.getTransitionFromState(stateId);
1185 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1186 updateBacktrackSetsFromPreviousExecution(stateId);
1187 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
1188 // Update past executions with a predecessor
1189 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1190 for(TransitionEvent transition : reachableTransitions) {
1191 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1193 updateBacktrackSetsFromPreviousExecution(stateId);
1198 // Update the backtrack sets from previous executions
1199 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1200 // Collect all the reachable transitions from R-Graph
1201 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1202 for(TransitionEvent transition : reachableTransitions) {
1203 Execution execution = transition.getExecution();
1204 int currentChoice = transition.getChoiceCounter();
1205 updateBacktrackSet(execution, currentChoice);