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 reachableTransitions.addAll(graph.get(stId));
445 return reachableTransitions;
449 // This class compactly stores Read and Write field sets
450 // We store the field name and its object ID
451 // Sharing the same field means the same field name and object ID
452 private class ReadWriteSet {
453 private HashMap<String, Integer> readMap;
454 private HashMap<String, Integer> writeMap;
456 public ReadWriteSet() {
457 readMap = new HashMap<>();
458 writeMap = new HashMap<>();
461 public void addReadField(String field, int objectId) {
462 readMap.put(field, objectId);
465 public void addWriteField(String field, int objectId) {
466 writeMap.put(field, objectId);
469 public void removeReadField(String field) {
470 readMap.remove(field);
473 public void removeWriteField(String field) {
474 writeMap.remove(field);
477 public boolean isEmpty() {
478 return readMap.isEmpty() && writeMap.isEmpty();
481 public ReadWriteSet getCopy() {
482 ReadWriteSet copyRWSet = new ReadWriteSet();
483 // Copy the maps in the set into the new object copy
484 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
485 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
489 public Set<String> getReadSet() {
490 return readMap.keySet();
493 public Set<String> getWriteSet() {
494 return writeMap.keySet();
497 public boolean readFieldExists(String field) {
498 return readMap.containsKey(field);
501 public boolean writeFieldExists(String field) {
502 return writeMap.containsKey(field);
505 public int readFieldObjectId(String field) {
506 return readMap.get(field);
509 public int writeFieldObjectId(String field) {
510 return writeMap.get(field);
513 private HashMap<String, Integer> getReadMap() {
517 private HashMap<String, Integer> getWriteMap() {
521 private void setReadMap(HashMap<String, Integer> rMap) {
525 private void setWriteMap(HashMap<String, Integer> wMap) {
530 // This class compactly stores transitions:
534 // 4) predecessors (for backward DFS).
535 private class TransitionEvent {
536 private int choice; // Choice chosen at this transition
537 private int choiceCounter; // Choice counter at this transition
538 private Execution execution; // The execution where this transition belongs
539 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
540 private int stateId; // State at this transition
541 private IntChoiceFromSet transitionCG; // CG at this transition
543 public TransitionEvent() {
547 predecessors = new HashSet<>();
552 public int getChoice() {
556 public int getChoiceCounter() {
557 return choiceCounter;
560 public Execution getExecution() {
564 public HashSet<Predecessor> getPredecessors() {
568 public int getStateId() {
572 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
574 public void recordPredecessor(Execution execution, int choice) {
575 predecessors.add(new Predecessor(choice, execution));
578 public void setChoice(int cho) {
582 public void setChoiceCounter(int choCounter) {
583 choiceCounter = choCounter;
586 public void setExecution(Execution exec) {
590 public void setPredecessors(HashSet<Predecessor> preds) {
591 predecessors = new HashSet<>(preds);
594 public void setStateId(int stId) {
598 public void setTransitionCG(IntChoiceFromSet cg) {
604 private final static String DO_CALL_METHOD = "doCall";
605 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
606 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
607 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
608 // Groovy library created fields
609 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
611 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
612 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
613 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
614 // Java and Groovy libraries
615 { "java", "org", "sun", "com", "gov", "groovy"};
616 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
617 private final static String GET_PROPERTY_METHOD =
618 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
619 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
620 private final static String JAVA_INTEGER = "int";
621 private final static String JAVA_STRING_LIB = "java.lang.String";
624 private Integer[] copyChoices(Integer[] choicesToCopy) {
626 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
627 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
628 return copyOfChoices;
631 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
632 // Check the next choice and if the value is not the same as the expected then force the expected value
633 int choiceIndex = choiceCounter % refChoices.length;
634 int nextChoice = icsCG.getNextChoice();
635 if (refChoices[choiceIndex] != nextChoice) {
636 int expectedChoice = refChoices[choiceIndex];
637 int currCGIndex = icsCG.getNextChoiceIndex();
638 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
639 icsCG.setChoice(currCGIndex, expectedChoice);
642 // Get state ID and associate it with this transition
643 int stateId = vm.getStateId();
644 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
645 // Add new transition to the current execution and map it in R-Graph
646 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
647 rGraph.addReachableTransition(stId, transition);
649 currentExecution.mapCGToChoice(icsCG, choiceCounter);
650 // Store restorable state object for this state (always store the latest)
651 RestorableVMState restorableState = vm.getRestorableState();
652 restorableStateMap.put(stateId, restorableState);
655 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
656 // Get a new transition
657 TransitionEvent transition;
658 if (currentExecution.isNew()) {
659 // We need to handle the first transition differently because this has a predecessor execution
660 transition = currentExecution.getFirstTransition();
662 transition = new TransitionEvent();
663 currentExecution.addTransition(transition);
664 transition.recordPredecessor(currentExecution, choiceCounter - 1);
666 transition.setExecution(currentExecution);
667 transition.setTransitionCG(icsCG);
668 transition.setStateId(stateId);
669 transition.setChoice(refChoices[choiceIndex]);
670 transition.setChoiceCounter(choiceCounter);
675 // --- Functions related to cycle detection and reachability graph
677 // Detect cycles in the current execution/trace
678 // We terminate the execution iff:
679 // (1) the state has been visited in the current execution
680 // (2) the state has one or more cycles that involve all the events
681 // With simple approach we only need to check for a re-visited state.
682 // Basically, we have to check that we have executed all events between two occurrences of such state.
683 private boolean completeFullCycle(int stId) {
684 // False if the state ID hasn't been recorded
685 if (!stateToEventMap.containsKey(stId)) {
688 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
689 // Check if this set contains all the event choices
690 // If not then this is not the terminating condition
691 for(int i=0; i<=maxEventChoice; i++) {
692 if (!visitedEvents.contains(i)) {
699 private void initializeStatesVariables() {
706 currVisitedStates = new HashSet<>();
707 justVisitedStates = new HashSet<>();
708 prevVisitedStates = new HashSet<>();
709 stateToEventMap = new HashMap<>();
711 backtrackMap = new HashMap<>();
712 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
713 currentExecution = new Execution();
714 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
715 doneBacktrackSet = new HashSet<>();
716 rGraph = new RGraph();
718 isEndOfExecution = false;
721 private void mapStateToEvent(int nextChoiceValue) {
722 // Update all states with this event/choice
723 // This means that all past states now see this transition
724 Set<Integer> stateSet = stateToEventMap.keySet();
725 for(Integer stateId : stateSet) {
726 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
727 eventSet.add(nextChoiceValue);
731 private boolean terminateCurrentExecution() {
732 // We need to check all the states that have just been visited
733 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
734 for(Integer stateId : justVisitedStates) {
735 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
742 private void updateStateInfo(Search search) {
743 // Update the state variables
744 int stateId = search.getStateId();
745 // Insert state ID into the map if it is new
746 if (!stateToEventMap.containsKey(stateId)) {
747 HashSet<Integer> eventSet = new HashSet<>();
748 stateToEventMap.put(stateId, eventSet);
750 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
751 justVisitedStates.add(stateId);
752 if (!prevVisitedStates.contains(stateId)) {
753 // It is a currently visited states if the state has not been seen in previous executions
754 currVisitedStates.add(stateId);
758 // --- Functions related to Read/Write access analysis on shared fields
760 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
761 // Insert backtrack point to the right state ID
762 LinkedList<BacktrackExecution> backtrackExecList;
763 if (backtrackMap.containsKey(stateId)) {
764 backtrackExecList = backtrackMap.get(stateId);
766 backtrackExecList = new LinkedList<>();
767 backtrackMap.put(stateId, backtrackExecList);
769 // Add the new backtrack execution object
770 TransitionEvent backtrackTransition = new TransitionEvent();
771 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
772 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
773 // Add to priority queue
774 if (!backtrackStateQ.contains(stateId)) {
775 backtrackStateQ.add(stateId);
779 // Analyze Read/Write accesses that are directly invoked on fields
780 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
781 // Get the field info
782 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
783 // Analyze only after being initialized
784 String fieldClass = fieldInfo.getFullName();
785 // Do the analysis to get Read and Write accesses to fields
786 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
787 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
788 // Record the field in the map
789 if (executedInsn instanceof WriteInstruction) {
790 // We first check the non-relevant fields set
791 if (!nonRelevantFields.contains(fieldInfo)) {
792 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
793 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
794 if (fieldClass.startsWith(str)) {
795 nonRelevantFields.add(fieldInfo);
800 // If we have this field in the non-relevant fields set then we return right away
803 rwSet.addWriteField(fieldClass, objectId);
804 } else if (executedInsn instanceof ReadInstruction) {
805 rwSet.addReadField(fieldClass, objectId);
809 // Analyze Read accesses that are indirect (performed through iterators)
810 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
811 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
813 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
814 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
815 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
816 // Extract info from the stack frame
817 StackFrame frame = ti.getTopFrame();
818 int[] frameSlots = frame.getSlots();
819 // Get the Groovy callsite library at index 0
820 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
821 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
824 // Get the iterated object whose property is accessed
825 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
826 if (eiAccessObj == null) {
829 // We exclude library classes (they start with java, org, etc.) and some more
830 ClassInfo classInfo = eiAccessObj.getClassInfo();
831 String objClassName = classInfo.getName();
832 // Check if this class info is part of the non-relevant classes set already
833 if (!nonRelevantClasses.contains(classInfo)) {
834 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
835 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
836 nonRelevantClasses.add(classInfo);
840 // If it is part of the non-relevant classes set then return immediately
843 // Extract fields from this object and put them into the read write
844 int numOfFields = eiAccessObj.getNumberOfFields();
845 for(int i=0; i<numOfFields; i++) {
846 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
847 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
848 String fieldClass = fieldInfo.getFullName();
849 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
850 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
851 // Record the field in the map
852 rwSet.addReadField(fieldClass, objectId);
858 private int checkAndAdjustChoice(int currentChoice, VM vm) {
859 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
860 // for certain method calls in the infrastructure, e.g., eventSince()
861 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
862 // This is the main event CG
863 if (currentCG instanceof IntIntervalGenerator) {
864 // This is the interval CG used in device handlers
865 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
866 // Iterate until we find the IntChoiceFromSet CG
867 while (!(parentCG instanceof IntChoiceFromSet)) {
868 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
870 // Find the choice related to the IntIntervalGenerator CG from the map
871 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
873 return currentChoice;
876 private void createBacktrackingPoint(Execution execution, int currentChoice,
877 Execution conflictExecution, int conflictChoice) {
878 // Create a new list of choices for backtrack based on the current choice and conflicting event number
879 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
880 // for the original set {0, 1, 2, 3}
881 Integer[] newChoiceList = new Integer[refChoices.length];
882 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
883 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
884 int currChoice = currentTrace.get(currentChoice).getChoice();
885 int stateId = conflictTrace.get(conflictChoice).getStateId();
886 // Check if this trace has been done from this state
887 if (isTraceAlreadyConstructed(currChoice, stateId)) {
890 // Put the conflicting event numbers first and reverse the order
891 newChoiceList[0] = currChoice;
892 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
893 for (int i = 0, j = 1; i < refChoices.length; i++) {
894 if (refChoices[i] != newChoiceList[0]) {
895 newChoiceList[j] = refChoices[i];
899 // Predecessor of the new backtrack point is the same as the conflict point's
900 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
903 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
904 for (String excludedField : excludedStrings) {
905 if (className.contains(excludedField)) {
912 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
913 for (String excludedField : excludedStrings) {
914 if (className.endsWith(excludedField)) {
921 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
922 for (String excludedField : excludedStrings) {
923 if (className.startsWith(excludedField)) {
930 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
931 // Check if we are reaching the end of our execution: no more backtracking points to explore
932 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
933 if (!backtrackStateQ.isEmpty()) {
934 // Set done all the other backtrack points
935 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
936 backtrackTransition.getTransitionCG().setDone();
938 // Reset the next backtrack point with the latest state
939 int hiStateId = backtrackStateQ.peek();
940 // Restore the state first if necessary
941 if (vm.getStateId() != hiStateId) {
942 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
943 vm.restoreState(restorableState);
945 // Set the backtrack CG
946 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
947 setBacktrackCG(hiStateId, backtrackCG);
949 // Set done this last CG (we save a few rounds)
952 // Save all the visited states when starting a new execution of trace
953 prevVisitedStates.addAll(currVisitedStates);
954 // This marks a transitional period to the new CG
955 isEndOfExecution = true;
958 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
959 ReadWriteSet currRWSet) {
960 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
961 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
962 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
963 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
964 if (!confRWFieldsMap.containsKey(conflictChoice) ||
965 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
968 // R/W set of choice/event that may have a potential conflict
969 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
970 // Check for conflicts with Read and Write fields for Write instructions
971 Set<String> currWriteSet = currRWSet.getWriteSet();
972 for(String writeField : currWriteSet) {
973 int currObjId = currRWSet.writeFieldObjectId(writeField);
974 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
975 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
976 // Remove this from the write set as we are tracking per memory location
977 currRWSet.removeWriteField(writeField);
981 // Check for conflicts with Write fields for Read instructions
982 Set<String> currReadSet = currRWSet.getReadSet();
983 for(String readField : currReadSet) {
984 int currObjId = currRWSet.readFieldObjectId(readField);
985 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
986 // Remove this from the read set as we are tracking per memory location
987 currRWSet.removeReadField(readField);
991 // Return false if no conflict is found
995 private ReadWriteSet getReadWriteSet(int currentChoice) {
996 // Do the analysis to get Read and Write accesses to fields
998 // We already have an entry
999 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1000 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1001 rwSet = currReadWriteFieldsMap.get(currentChoice);
1002 } else { // We need to create a new entry
1003 rwSet = new ReadWriteSet();
1004 currReadWriteFieldsMap.put(currentChoice, rwSet);
1009 private boolean isFieldExcluded(Instruction executedInsn) {
1010 // Get the field info
1011 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1012 // Check if the non-relevant fields set already has it
1013 if (nonRelevantFields.contains(fieldInfo)) {
1016 // Check if the relevant fields set already has it
1017 if (relevantFields.contains(fieldInfo)) {
1020 // Analyze only after being initialized
1021 String field = fieldInfo.getFullName();
1022 // Check against "starts-with", "ends-with", and "contains" list
1023 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1024 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1025 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1026 nonRelevantFields.add(fieldInfo);
1029 relevantFields.add(fieldInfo);
1033 // Check if this trace is already constructed
1034 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1035 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1036 // TODO: THIS IS AN OPTIMIZATION!
1037 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
1038 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
1039 // The second time this event 1 is explored, it will generate the same state as the first one
1040 StringBuilder sb = new StringBuilder();
1043 sb.append(firstChoice);
1044 // Check if the trace has been constructed as a backtrack point for this state
1045 if (doneBacktrackSet.contains(sb.toString())) {
1048 doneBacktrackSet.add(sb.toString());
1052 // Reset data structure for each new execution
1053 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1054 if (choices == null || choices != icsCG.getAllChoices()) {
1055 // Reset state variables
1057 choices = icsCG.getAllChoices();
1058 refChoices = copyChoices(choices);
1059 // Clear data structures
1060 currVisitedStates = new HashSet<>();
1061 stateToEventMap = new HashMap<>();
1062 isEndOfExecution = false;
1066 // Set a backtrack point for a particular state
1067 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1068 // Set a backtrack CG based on a state ID
1069 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1070 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1071 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1072 backtrackCG.setStateId(stateId);
1073 backtrackCG.reset();
1074 // Update current execution with this new execution
1075 Execution newExecution = new Execution();
1076 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1077 newExecution.addTransition(firstTransition);
1078 // Try to free some memory since this map is only used for the current execution
1079 currentExecution.clearCGToChoiceMap();
1080 currentExecution = newExecution;
1081 // Remove from the queue if we don't have more backtrack points for that state
1082 if (backtrackExecutions.isEmpty()) {
1083 backtrackMap.remove(stateId);
1084 backtrackStateQ.remove(stateId);
1088 // Update backtrack sets
1089 // 1) recursively, and
1090 // 2) track accesses per memory location (per shared variable/field)
1091 private void updateBacktrackSet(Execution execution, int currentChoice) {
1092 // Copy ReadWriteSet object
1093 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1094 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1095 if (currRWSet == null) {
1098 currRWSet = currRWSet.getCopy();
1099 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1100 HashSet<TransitionEvent> visited = new HashSet<>();
1101 // Update backtrack set recursively
1102 // TODO: The following is the call to the original version of the method
1103 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1104 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1105 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1108 // TODO: This is the original version of the recursive method
1109 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1110 // Execution conflictExecution, int conflictChoice,
1111 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1112 // // Halt when we have found the first read/write conflicts for all memory locations
1113 // if (currRWSet.isEmpty()) {
1116 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1117 // // Halt when we have visited this transition (in a cycle)
1118 // if (visited.contains(confTrans)) {
1121 // visited.add(confTrans);
1122 // // Explore all predecessors
1123 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1124 // // Get the predecessor (previous conflict choice)
1125 // conflictChoice = predecessor.getChoice();
1126 // conflictExecution = predecessor.getExecution();
1127 // // Check if a conflict is found
1128 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1129 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1131 // // Continue performing DFS if conflict is not found
1132 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1136 // TODO: This is the version of the method with pushing up happens-before transitions
1137 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1138 Execution conflictExecution, int conflictChoice,
1139 Execution hbExecution, int hbChoice,
1140 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1141 // Halt when we have found the first read/write conflicts for all memory locations
1142 if (currRWSet.isEmpty()) {
1145 TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1146 // Halt when we have visited this transition (in a cycle)
1147 if (visited.contains(confTrans)) {
1150 visited.add(confTrans);
1151 // Explore all predecessors
1152 for (Predecessor predecessor : confTrans.getPredecessors()) {
1153 // Get the predecessor (previous conflict choice)
1154 conflictChoice = predecessor.getChoice();
1155 conflictExecution = predecessor.getExecution();
1156 // Push up one happens-before transition
1157 int pushedChoice = hbChoice;
1158 Execution pushedExecution = hbExecution;
1159 // Check if a conflict is found
1160 if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1161 createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1162 pushedChoice = conflictChoice;
1163 pushedExecution = conflictExecution;
1165 // Continue performing DFS if conflict is not found
1166 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1167 pushedExecution, pushedChoice, currRWSet, visited);
1169 // Remove the transition after being explored
1170 // TODO: Seems to cause a lot of loops---commented out for now
1171 //visited.remove(confTrans);
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) || prevVisitedStates.contains(stateId)) {
1183 // Update reachable transitions in the graph with a predecessor
1184 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1185 for(TransitionEvent transition : reachableTransitions) {
1186 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1188 updateBacktrackSetsFromPreviousExecution(stateId);
1193 // Update the backtrack sets from previous executions
1194 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1195 // Collect all the reachable transitions from R-Graph
1196 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1197 for(TransitionEvent transition : reachableTransitions) {
1198 Execution execution = transition.getExecution();
1199 int currentChoice = transition.getChoiceCounter();
1200 updateBacktrackSet(execution, currentChoice);