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
329 cgToChoiceMap = new HashMap<>();
330 executionTrace = new ArrayList<>();
332 readWriteFieldsMap = new HashMap<>();
335 public void addTransition(TransitionEvent newBacktrackPoint) {
336 executionTrace.add(newBacktrackPoint);
339 public void clearCGToChoiceMap() {
340 cgToChoiceMap = null;
343 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
344 return cgToChoiceMap.get(icsCG);
347 public ArrayList<TransitionEvent> getExecutionTrace() {
348 return executionTrace;
351 public TransitionEvent getFirstTransition() {
352 return executionTrace.get(0);
355 public TransitionEvent getLastTransition() {
356 return executionTrace.get(executionTrace.size() - 1);
359 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
360 return readWriteFieldsMap;
363 public boolean isNew() {
365 // Right after this is accessed, it is no longer new
372 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
373 cgToChoiceMap.put(icsCG, choice);
377 // This class compactly stores a predecessor
378 // 1) a predecessor execution
379 // 2) the predecessor choice in that predecessor execution
380 private class Predecessor {
381 private int choice; // Predecessor choice
382 private Execution execution; // Predecessor execution
384 public Predecessor(int predChoice, Execution predExec) {
386 execution = predExec;
389 public int getChoice() {
393 public Execution getExecution() {
398 // This class represents a R-Graph (in the paper it is a state transition graph R)
399 // This implementation stores reachable transitions from and connects with past executions
400 private class RGraph {
401 private int hiStateId; // Maximum state Id
402 private HashMap<Integer, HashSet<TransitionEvent>> graph; // Reachable transitions from past executions
406 graph = new HashMap<>();
409 public void addReachableTransition(int stateId, TransitionEvent transition) {
410 HashSet<TransitionEvent> transitionSet;
411 if (graph.containsKey(stateId)) {
412 transitionSet = graph.get(stateId);
414 transitionSet = new HashSet<>();
415 graph.put(stateId, transitionSet);
417 // Insert into the set if it does not contain it yet
418 if (!transitionSet.contains(transition)) {
419 transitionSet.add(transition);
421 // Update highest state ID
422 if (hiStateId < stateId) {
427 public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
428 if (!graph.containsKey(stateId)) {
429 // This is a loop from a transition to itself, so just return the current transition
430 HashSet<TransitionEvent> transitionSet = new HashSet<>();
431 transitionSet.add(currentExecution.getLastTransition());
432 return transitionSet;
434 return graph.get(stateId);
437 public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
438 HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
439 // All transitions from states higher than the given state ID (until the highest state ID) are reachable
440 for(int stId = stateId; stId <= hiStateId; stId++) {
441 reachableTransitions.addAll(graph.get(stId));
443 return reachableTransitions;
447 // This class compactly stores Read and Write field sets
448 // We store the field name and its object ID
449 // Sharing the same field means the same field name and object ID
450 private class ReadWriteSet {
451 private HashMap<String, Integer> readMap;
452 private HashMap<String, Integer> writeMap;
454 public ReadWriteSet() {
455 readMap = new HashMap<>();
456 writeMap = new HashMap<>();
459 public void addReadField(String field, int objectId) {
460 readMap.put(field, objectId);
463 public void addWriteField(String field, int objectId) {
464 writeMap.put(field, objectId);
467 public void removeReadField(String field) {
468 readMap.remove(field);
471 public void removeWriteField(String field) {
472 writeMap.remove(field);
475 public boolean isEmpty() {
476 return readMap.isEmpty() && writeMap.isEmpty();
479 public ReadWriteSet getCopy() {
480 ReadWriteSet copyRWSet = new ReadWriteSet();
481 // Copy the maps in the set into the new object copy
482 copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
483 copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
487 public Set<String> getReadSet() {
488 return readMap.keySet();
491 public Set<String> getWriteSet() {
492 return writeMap.keySet();
495 public boolean readFieldExists(String field) {
496 return readMap.containsKey(field);
499 public boolean writeFieldExists(String field) {
500 return writeMap.containsKey(field);
503 public int readFieldObjectId(String field) {
504 return readMap.get(field);
507 public int writeFieldObjectId(String field) {
508 return writeMap.get(field);
511 private HashMap<String, Integer> getReadMap() {
515 private HashMap<String, Integer> getWriteMap() {
519 private void setReadMap(HashMap<String, Integer> rMap) {
523 private void setWriteMap(HashMap<String, Integer> wMap) {
528 // This class compactly stores transitions:
532 // 4) predecessors (for backward DFS).
533 private class TransitionEvent {
534 private int choice; // Choice chosen at this transition
535 private int choiceCounter; // Choice counter at this transition
536 private Execution execution; // The execution where this transition belongs
537 private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
538 private int stateId; // State at this transition
539 private IntChoiceFromSet transitionCG; // CG at this transition
541 public TransitionEvent() {
545 predecessors = new HashSet<>();
550 public int getChoice() {
554 public int getChoiceCounter() {
555 return choiceCounter;
558 public Execution getExecution() {
562 public HashSet<Predecessor> getPredecessors() {
566 public int getStateId() {
570 public IntChoiceFromSet getTransitionCG() { return transitionCG; }
572 public void recordPredecessor(Execution execution, int choice) {
573 predecessors.add(new Predecessor(choice, execution));
576 public void setChoice(int cho) {
580 public void setChoiceCounter(int choCounter) {
581 choiceCounter = choCounter;
584 public void setExecution(Execution exec) {
588 public void setPredecessors(HashSet<Predecessor> preds) {
589 predecessors = new HashSet<>(preds);
592 public void setStateId(int stId) {
596 public void setTransitionCG(IntChoiceFromSet cg) {
602 private final static String DO_CALL_METHOD = "doCall";
603 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
604 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
605 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
606 // Groovy library created fields
607 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
609 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
610 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
611 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
612 // Java and Groovy libraries
613 { "java", "org", "sun", "com", "gov", "groovy"};
614 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
615 private final static String GET_PROPERTY_METHOD =
616 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
617 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
618 private final static String JAVA_INTEGER = "int";
619 private final static String JAVA_STRING_LIB = "java.lang.String";
622 private Integer[] copyChoices(Integer[] choicesToCopy) {
624 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
625 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
626 return copyOfChoices;
629 private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
630 // Check the next choice and if the value is not the same as the expected then force the expected value
631 int choiceIndex = choiceCounter % refChoices.length;
632 int nextChoice = icsCG.getNextChoice();
633 if (refChoices[choiceIndex] != nextChoice) {
634 int expectedChoice = refChoices[choiceIndex];
635 int currCGIndex = icsCG.getNextChoiceIndex();
636 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
637 icsCG.setChoice(currCGIndex, expectedChoice);
640 // Get state ID and associate it with this transition
641 int stateId = vm.getStateId();
642 TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
643 // Add new transition to the current execution and map it in R-Graph
644 for (Integer stId : justVisitedStates) { // Map this transition to all the previously passed states
645 rGraph.addReachableTransition(stId, transition);
647 currentExecution.mapCGToChoice(icsCG, choiceCounter);
648 // Store restorable state object for this state (always store the latest)
649 RestorableVMState restorableState = vm.getRestorableState();
650 restorableStateMap.put(stateId, restorableState);
653 private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
654 // Get a new transition
655 TransitionEvent transition;
656 if (currentExecution.isNew()) {
657 // We need to handle the first transition differently because this has a predecessor execution
658 transition = currentExecution.getFirstTransition();
660 transition = new TransitionEvent();
661 currentExecution.addTransition(transition);
662 transition.recordPredecessor(currentExecution, choiceCounter - 1);
664 transition.setExecution(currentExecution);
665 transition.setTransitionCG(icsCG);
666 transition.setStateId(stateId);
667 transition.setChoice(refChoices[choiceIndex]);
668 transition.setChoiceCounter(choiceCounter);
673 // --- Functions related to cycle detection and reachability graph
675 // Detect cycles in the current execution/trace
676 // We terminate the execution iff:
677 // (1) the state has been visited in the current execution
678 // (2) the state has one or more cycles that involve all the events
679 // With simple approach we only need to check for a re-visited state.
680 // Basically, we have to check that we have executed all events between two occurrences of such state.
681 private boolean completeFullCycle(int stId) {
682 // False if the state ID hasn't been recorded
683 if (!stateToEventMap.containsKey(stId)) {
686 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
687 // Check if this set contains all the event choices
688 // If not then this is not the terminating condition
689 for(int i=0; i<=maxEventChoice; i++) {
690 if (!visitedEvents.contains(i)) {
697 private void initializeStatesVariables() {
704 currVisitedStates = new HashSet<>();
705 justVisitedStates = new HashSet<>();
706 prevVisitedStates = new HashSet<>();
707 stateToEventMap = new HashMap<>();
709 backtrackMap = new HashMap<>();
710 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
711 currentExecution = new Execution();
712 currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
713 doneBacktrackSet = new HashSet<>();
714 rGraph = new RGraph();
716 isEndOfExecution = false;
719 private void mapStateToEvent(int nextChoiceValue) {
720 // Update all states with this event/choice
721 // This means that all past states now see this transition
722 Set<Integer> stateSet = stateToEventMap.keySet();
723 for(Integer stateId : stateSet) {
724 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
725 eventSet.add(nextChoiceValue);
729 private boolean terminateCurrentExecution() {
730 // We need to check all the states that have just been visited
731 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
732 for(Integer stateId : justVisitedStates) {
733 if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
740 private void updateStateInfo(Search search) {
741 // Update the state variables
742 int stateId = search.getStateId();
743 // Insert state ID into the map if it is new
744 if (!stateToEventMap.containsKey(stateId)) {
745 HashSet<Integer> eventSet = new HashSet<>();
746 stateToEventMap.put(stateId, eventSet);
748 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
749 justVisitedStates.add(stateId);
750 if (!prevVisitedStates.contains(stateId)) {
751 // It is a currently visited states if the state has not been seen in previous executions
752 currVisitedStates.add(stateId);
756 // --- Functions related to Read/Write access analysis on shared fields
758 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
759 // Insert backtrack point to the right state ID
760 LinkedList<BacktrackExecution> backtrackExecList;
761 if (backtrackMap.containsKey(stateId)) {
762 backtrackExecList = backtrackMap.get(stateId);
764 backtrackExecList = new LinkedList<>();
765 backtrackMap.put(stateId, backtrackExecList);
767 // Add the new backtrack execution object
768 TransitionEvent backtrackTransition = new TransitionEvent();
769 backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
770 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
771 // Add to priority queue
772 if (!backtrackStateQ.contains(stateId)) {
773 backtrackStateQ.add(stateId);
777 // Analyze Read/Write accesses that are directly invoked on fields
778 private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
779 // Get the field info
780 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
781 // Analyze only after being initialized
782 String fieldClass = fieldInfo.getFullName();
783 // Do the analysis to get Read and Write accesses to fields
784 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
785 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
786 // Record the field in the map
787 if (executedInsn instanceof WriteInstruction) {
788 // We first check the non-relevant fields set
789 if (!nonRelevantFields.contains(fieldInfo)) {
790 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
791 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
792 if (fieldClass.startsWith(str)) {
793 nonRelevantFields.add(fieldInfo);
798 // If we have this field in the non-relevant fields set then we return right away
801 rwSet.addWriteField(fieldClass, objectId);
802 } else if (executedInsn instanceof ReadInstruction) {
803 rwSet.addReadField(fieldClass, objectId);
807 // Analyze Read accesses that are indirect (performed through iterators)
808 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
809 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
811 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
812 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
813 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
814 // Extract info from the stack frame
815 StackFrame frame = ti.getTopFrame();
816 int[] frameSlots = frame.getSlots();
817 // Get the Groovy callsite library at index 0
818 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
819 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
822 // Get the iterated object whose property is accessed
823 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
824 if (eiAccessObj == null) {
827 // We exclude library classes (they start with java, org, etc.) and some more
828 ClassInfo classInfo = eiAccessObj.getClassInfo();
829 String objClassName = classInfo.getName();
830 // Check if this class info is part of the non-relevant classes set already
831 if (!nonRelevantClasses.contains(classInfo)) {
832 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
833 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
834 nonRelevantClasses.add(classInfo);
838 // If it is part of the non-relevant classes set then return immediately
841 // Extract fields from this object and put them into the read write
842 int numOfFields = eiAccessObj.getNumberOfFields();
843 for(int i=0; i<numOfFields; i++) {
844 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
845 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
846 String fieldClass = fieldInfo.getFullName();
847 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
848 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
849 // Record the field in the map
850 rwSet.addReadField(fieldClass, objectId);
856 private int checkAndAdjustChoice(int currentChoice, VM vm) {
857 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
858 // for certain method calls in the infrastructure, e.g., eventSince()
859 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
860 // This is the main event CG
861 if (currentCG instanceof IntIntervalGenerator) {
862 // This is the interval CG used in device handlers
863 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
864 // Iterate until we find the IntChoiceFromSet CG
865 while (!(parentCG instanceof IntChoiceFromSet)) {
866 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
868 // Find the choice related to the IntIntervalGenerator CG from the map
869 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
871 return currentChoice;
874 private void createBacktrackingPoint(Execution execution, int currentChoice,
875 Execution conflictExecution, int conflictChoice) {
876 // Create a new list of choices for backtrack based on the current choice and conflicting event number
877 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
878 // for the original set {0, 1, 2, 3}
879 Integer[] newChoiceList = new Integer[refChoices.length];
880 ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
881 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
882 int currChoice = currentTrace.get(currentChoice).getChoice();
883 int stateId = conflictTrace.get(conflictChoice).getStateId();
884 // Check if this trace has been done from this state
885 if (isTraceAlreadyConstructed(currChoice, stateId)) {
888 // Put the conflicting event numbers first and reverse the order
889 newChoiceList[0] = currChoice;
890 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
891 for (int i = 0, j = 1; i < refChoices.length; i++) {
892 if (refChoices[i] != newChoiceList[0]) {
893 newChoiceList[j] = refChoices[i];
897 // Predecessor of the new backtrack point is the same as the conflict point's
898 addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
901 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
902 for (String excludedField : excludedStrings) {
903 if (className.contains(excludedField)) {
910 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
911 for (String excludedField : excludedStrings) {
912 if (className.endsWith(excludedField)) {
919 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
920 for (String excludedField : excludedStrings) {
921 if (className.startsWith(excludedField)) {
928 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
929 // Check if we are reaching the end of our execution: no more backtracking points to explore
930 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
931 if (!backtrackStateQ.isEmpty()) {
932 // Set done all the other backtrack points
933 for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
934 backtrackTransition.getTransitionCG().setDone();
936 // Reset the next backtrack point with the latest state
937 int hiStateId = backtrackStateQ.peek();
938 // Restore the state first if necessary
939 if (vm.getStateId() != hiStateId) {
940 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
941 vm.restoreState(restorableState);
943 // Set the backtrack CG
944 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
945 setBacktrackCG(hiStateId, backtrackCG);
947 // Set done this last CG (we save a few rounds)
950 // Save all the visited states when starting a new execution of trace
951 prevVisitedStates.addAll(currVisitedStates);
952 // This marks a transitional period to the new CG
953 isEndOfExecution = true;
956 private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
957 ReadWriteSet currRWSet) {
958 ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
959 ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
960 HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
961 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
962 if (!confRWFieldsMap.containsKey(conflictChoice) ||
963 executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
966 // R/W set of choice/event that may have a potential conflict
967 ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
968 // Check for conflicts with Read and Write fields for Write instructions
969 Set<String> currWriteSet = currRWSet.getWriteSet();
970 for(String writeField : currWriteSet) {
971 int currObjId = currRWSet.writeFieldObjectId(writeField);
972 if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
973 (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
974 // Remove this from the write set as we are tracking per memory location
975 currRWSet.removeWriteField(writeField);
979 // Check for conflicts with Write fields for Read instructions
980 Set<String> currReadSet = currRWSet.getReadSet();
981 for(String readField : currReadSet) {
982 int currObjId = currRWSet.readFieldObjectId(readField);
983 if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
984 // Remove this from the read set as we are tracking per memory location
985 currRWSet.removeReadField(readField);
989 // Return false if no conflict is found
993 private ReadWriteSet getReadWriteSet(int currentChoice) {
994 // Do the analysis to get Read and Write accesses to fields
996 // We already have an entry
997 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
998 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
999 rwSet = currReadWriteFieldsMap.get(currentChoice);
1000 } else { // We need to create a new entry
1001 rwSet = new ReadWriteSet();
1002 currReadWriteFieldsMap.put(currentChoice, rwSet);
1007 private boolean isFieldExcluded(Instruction executedInsn) {
1008 // Get the field info
1009 FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1010 // Check if the non-relevant fields set already has it
1011 if (nonRelevantFields.contains(fieldInfo)) {
1014 // Check if the relevant fields set already has it
1015 if (relevantFields.contains(fieldInfo)) {
1018 // Analyze only after being initialized
1019 String field = fieldInfo.getFullName();
1020 // Check against "starts-with", "ends-with", and "contains" list
1021 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1022 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1023 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1024 nonRelevantFields.add(fieldInfo);
1027 relevantFields.add(fieldInfo);
1031 // Check if this trace is already constructed
1032 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1033 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1034 // TODO: THIS IS AN OPTIMIZATION!
1035 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
1036 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
1037 // The second time this event 1 is explored, it will generate the same state as the first one
1038 StringBuilder sb = new StringBuilder();
1041 sb.append(firstChoice);
1042 // Check if the trace has been constructed as a backtrack point for this state
1043 if (doneBacktrackSet.contains(sb.toString())) {
1046 doneBacktrackSet.add(sb.toString());
1050 // Reset data structure for each new execution
1051 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1052 if (choices == null || choices != icsCG.getAllChoices()) {
1053 // Reset state variables
1055 choices = icsCG.getAllChoices();
1056 refChoices = copyChoices(choices);
1057 // Clear data structures
1058 currVisitedStates = new HashSet<>();
1059 stateToEventMap = new HashMap<>();
1060 isEndOfExecution = false;
1064 // Set a backtrack point for a particular state
1065 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1066 // Set a backtrack CG based on a state ID
1067 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1068 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1069 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
1070 backtrackCG.setStateId(stateId);
1071 backtrackCG.reset();
1072 // Update current execution with this new execution
1073 Execution newExecution = new Execution();
1074 TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1075 newExecution.addTransition(firstTransition);
1076 // Try to free some memory since this map is only used for the current execution
1077 currentExecution.clearCGToChoiceMap();
1078 currentExecution = newExecution;
1079 // Remove from the queue if we don't have more backtrack points for that state
1080 if (backtrackExecutions.isEmpty()) {
1081 backtrackMap.remove(stateId);
1082 backtrackStateQ.remove(stateId);
1086 // Update backtrack sets
1087 // 1) recursively, and
1088 // 2) track accesses per memory location (per shared variable/field)
1089 private void updateBacktrackSet(Execution execution, int currentChoice) {
1090 // Copy ReadWriteSet object
1091 HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1092 ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1093 if (currRWSet == null) {
1096 currRWSet = currRWSet.getCopy();
1097 // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1098 HashSet<TransitionEvent> visited = new HashSet<>();
1099 // Update backtrack set recursively
1100 // TODO: The following is the call to the original version of the method
1101 // updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1102 // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1103 updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, execution, currentChoice, currRWSet, visited);
1106 // TODO: This is the original version of the recursive method
1107 // private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1108 // Execution conflictExecution, int conflictChoice,
1109 // ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1110 // // Halt when we have found the first read/write conflicts for all memory locations
1111 // if (currRWSet.isEmpty()) {
1114 // TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1115 // // Halt when we have visited this transition (in a cycle)
1116 // if (visited.contains(confTrans)) {
1119 // visited.add(confTrans);
1120 // // Explore all predecessors
1121 // for (Predecessor predecessor : confTrans.getPredecessors()) {
1122 // // Get the predecessor (previous conflict choice)
1123 // conflictChoice = predecessor.getChoice();
1124 // conflictExecution = predecessor.getExecution();
1125 // // Check if a conflict is found
1126 // if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1127 // createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1129 // // Continue performing DFS if conflict is not found
1130 // updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1134 // TODO: This is the version of the method with pushing up happens-before transitions
1135 private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1136 Execution conflictExecution, int conflictChoice,
1137 Execution hbExecution, int hbChoice,
1138 ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1139 // Halt when we have found the first read/write conflicts for all memory locations
1140 if (currRWSet.isEmpty()) {
1143 TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1144 // Halt when we have visited this transition (in a cycle)
1145 if (visited.contains(confTrans)) {
1148 visited.add(confTrans);
1149 // Explore all predecessors
1150 for (Predecessor predecessor : confTrans.getPredecessors()) {
1151 // Get the predecessor (previous conflict choice)
1152 conflictChoice = predecessor.getChoice();
1153 conflictExecution = predecessor.getExecution();
1154 // Push up one happens-before transition
1155 int pushedChoice = hbChoice;
1156 Execution pushedExecution = hbExecution;
1157 // Check if a conflict is found
1158 if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1159 createBacktrackingPoint(pushedExecution, pushedChoice, conflictExecution, conflictChoice);
1160 pushedChoice = conflictChoice;
1161 pushedExecution = conflictExecution;
1163 // Continue performing DFS if conflict is not found
1164 updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice,
1165 pushedExecution, pushedChoice, currRWSet, visited);
1167 // Remove the transition after being explored
1168 visited.remove(confTrans);
1171 // --- Functions related to the reachability analysis when there is a state match
1173 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1174 // Perform this analysis only when:
1175 // 1) this is not during a switch to a new execution,
1176 // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1177 // 3) state > 0 (state 0 is for boolean CG)
1178 if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1179 if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1180 // Update reachable transitions in the graph with a predecessor
1181 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1182 for(TransitionEvent transition : reachableTransitions) {
1183 transition.recordPredecessor(currentExecution, choiceCounter - 1);
1185 updateBacktrackSetsFromPreviousExecution(stateId);
1190 // Update the backtrack sets from previous executions
1191 private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1192 // Collect all the reachable transitions from R-Graph
1193 HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1194 for(TransitionEvent transition : reachableTransitions) {
1195 Execution execution = transition.getExecution();
1196 int currentChoice = transition.getChoiceCounter();
1197 updateBacktrackSet(execution, currentChoice);