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;
34 import java.util.logging.Logger;
35 import java.io.IOException;
37 // TODO: Fix for Groovy's model-checking
38 // TODO: This is a setter to change the values of the ChoiceGenerator to implement POR
40 * Simple tool to log state changes.
42 * This DPOR implementation is augmented by the algorithm presented in this SPIN paper:
43 * http://spinroot.com/spin/symposia/ws08/spin2008_submission_33.pdf
45 * The algorithm is presented on page 11 of the paper. Basically, we have a graph G
46 * (i.e., visible operation dependency graph).
47 * This DPOR implementation actually fixes the algorithm in the SPIN paper that does not
48 * consider cases where a state could be matched early. In this new algorithm/implementation,
49 * each run is terminated iff:
50 * - we find a state that matches a state in a previous run, or
51 * - we have a matched state in the current run that consists of cycles that contain all choices/events.
53 public class DPORStateReducer extends ListenerAdapter {
55 // Information printout fields for verbose mode
56 private boolean verboseMode;
57 private boolean stateReductionMode;
58 private final PrintWriter out;
59 private PrintWriter fileWriter;
60 private String detail;
63 private Transition transition;
65 // DPOR-related fields
67 private Integer[] choices;
68 private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
69 private int choiceCounter;
70 private int maxEventChoice;
71 // Data structure to track the events seen by each state to track cycles (containing all events) for termination
72 private HashSet<Integer> currVisitedStates; // States being visited in the current execution
73 private HashSet<Integer> justVisitedStates; // States just visited in the previous choice/event
74 private HashSet<Integer> prevVisitedStates; // States visited in the previous execution
75 private HashMap<Integer, HashSet<Integer>> stateToEventMap;
76 // Data structure to analyze field Read/Write accesses and conflicts
77 private HashMap<Integer, LinkedList<BacktrackExecution>> backtrackMap; // Track created backtracking points
78 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
79 private Execution currentExecution; // Holds the information about the current execution
80 private HashSet<String> doneBacktrackSet; // Record state ID and trace already constructed
81 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
82 private HashMap<Integer, Integer> stateToChoiceCounterMap; // Maps state IDs to the choice counter
83 //private HashMap<Integer, ArrayList<ReachableTrace>> rGraph; // Create a reachability graph
84 private HashMap<Integer, ArrayList<Execution>> rGraph; // Create a reachability graph for past executions
87 private boolean isBooleanCGFlipped;
88 private boolean isEndOfExecution;
91 private int numOfConflicts;
92 private int numOfTransitions;
94 public DPORStateReducer(Config config, JPF jpf) {
95 verboseMode = config.getBoolean("printout_state_transition", false);
96 stateReductionMode = config.getBoolean("activate_state_reduction", true);
98 out = new PrintWriter(System.out, true);
102 String outputFile = config.getString("file_output");
103 if (!outputFile.isEmpty()) {
105 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
106 } catch (IOException e) {
109 isBooleanCGFlipped = false;
111 numOfTransitions = 0;
112 restorableStateMap = new HashMap<>();
113 initializeStatesVariables();
117 public void stateRestored(Search search) {
119 id = search.getStateId();
120 depth = search.getDepth();
121 transition = search.getTransition();
123 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
124 " and depth: " + depth + "\n");
129 public void searchStarted(Search search) {
131 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
136 public void stateAdvanced(Search search) {
138 id = search.getStateId();
139 depth = search.getDepth();
140 transition = search.getTransition();
141 if (search.isNewState()) {
147 if (search.isEndState()) {
148 out.println("\n==> DEBUG: This is the last state!\n");
151 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
152 " which is " + detail + " Transition: " + transition + "\n");
154 if (stateReductionMode) {
155 updateStateInfo(search);
160 public void stateBacktracked(Search search) {
162 id = search.getStateId();
163 depth = search.getDepth();
164 transition = search.getTransition();
167 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
168 " and depth: " + depth + "\n");
170 if (stateReductionMode) {
171 updateStateInfo(search);
175 static Logger log = JPF.getLogger("report");
178 public void searchFinished(Search search) {
179 if (stateReductionMode) {
180 // Number of conflicts = first trace + subsequent backtrack points
181 numOfConflicts += 1 + doneBacktrackSet.size();
184 out.println("\n==> DEBUG: ----------------------------------- search finished");
185 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
186 out.println("\n==> DEBUG: Number of conflicts : " + numOfConflicts);
187 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
188 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
190 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
191 fileWriter.println("==> DEBUG: Number of conflicts : " + numOfConflicts);
192 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
193 fileWriter.println();
199 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
200 if (stateReductionMode) {
201 // Initialize with necessary information from the CG
202 if (nextCG instanceof IntChoiceFromSet) {
203 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
204 if (!isEndOfExecution) {
205 // Check if CG has been initialized, otherwise initialize it
206 Integer[] cgChoices = icsCG.getAllChoices();
207 // Record the events (from choices)
208 if (choices == null) {
210 // Make a copy of choices as reference
211 refChoices = copyChoices(choices);
212 // Record the max event choice (the last element of the choice array)
213 maxEventChoice = choices[choices.length - 1];
215 icsCG.setNewValues(choices);
217 // Use a modulo since choiceCounter is going to keep increasing
218 int choiceIndex = choiceCounter % choices.length;
219 icsCG.advance(choices[choiceIndex]);
221 // Set done all CGs while transitioning to a new execution
229 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
231 if (stateReductionMode) {
232 // Check the boolean CG and if it is flipped, we are resetting the analysis
233 if (currentCG instanceof BooleanChoiceGenerator) {
234 if (!isBooleanCGFlipped) {
235 isBooleanCGFlipped = true;
237 // Number of conflicts = first trace + subsequent backtrack points
238 numOfConflicts = 1 + doneBacktrackSet.size();
239 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
240 initializeStatesVariables();
243 // Check every choice generated and ensure fair scheduling!
244 if (currentCG instanceof IntChoiceFromSet) {
245 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
246 // If this is a new CG then we need to update data structures
247 resetStatesForNewExecution(icsCG, vm);
248 // If we don't see a fair scheduling of events/choices then we have to enforce it
249 fairSchedulingAndBacktrackPoint(icsCG, vm);
250 // Explore the next backtrack point:
251 // 1) if we have seen this state or this state contains cycles that involve all events, and
252 // 2) after the current CG is advanced at least once
253 if (terminateCurrentExecution() && choiceCounter > 0) {
254 exploreNextBacktrackPoints(vm, icsCG);
258 // Map state to event
259 mapStateToEvent(icsCG.getNextChoice());
260 justVisitedStates.clear();
269 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
270 if (stateReductionMode) {
271 if (!isEndOfExecution) {
272 // Has to be initialized and a integer CG
273 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
274 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
275 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
276 if (currentChoice < 0) { // If choice is -1 then skip
279 currentChoice = checkAndAdjustChoice(currentChoice, vm);
280 // Record accesses from executed instructions
281 if (executedInsn instanceof JVMFieldInstruction) {
282 // Analyze only after being initialized
283 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
284 // We don't care about libraries
285 if (!isFieldExcluded(fieldClass)) {
286 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
288 } else if (executedInsn instanceof INVOKEINTERFACE) {
289 // Handle the read/write accesses that occur through iterators
290 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
292 // Analyze conflicts from next instructions
293 if (nextInsn instanceof JVMFieldInstruction) {
294 // Skip the constructor because it is called once and does not have shared access with other objects
295 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
296 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
297 if (!isFieldExcluded(fieldClass)) {
298 findFirstConflictAndCreateBacktrackPoint(currentChoice, nextInsn, fieldClass);
312 // This class compactly stores backtrack execution:
313 // 1) backtrack choice list, and
314 // 2) backtrack execution
315 private class BacktrackExecution {
316 private Integer[] choiceList;
317 private Execution execution;
319 public BacktrackExecution(Integer[] choList, Execution exec) {
320 choiceList = choList;
324 public Integer[] getChoiceList() {
328 public Execution getExecution() {
333 // This class compactly stores backtrack points:
334 // 1) backtrack state ID, and
335 // 2) backtracking choices
336 private class BacktrackPoint {
337 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
338 private int stateId; // State at this backtrack point
339 private int choice; // Choice chosen at this backtrack point
341 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
347 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
349 public int getStateId() {
353 public int getChoice() {
358 // This class stores a representation of the execution graph node
359 private class Execution {
360 private ArrayList<BacktrackPoint> executionTrace; // The BacktrackPoint objects of this execution
361 private int parentChoice; // The parent's choice that leads to this execution
362 private Execution parent; // Store the parent for backward DFS to find conflicts
363 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
366 executionTrace = new ArrayList<>();
369 readWriteFieldsMap = new HashMap<>();
372 public void addBacktrackPoint(BacktrackPoint newBacktrackPoint) {
373 executionTrace.add(newBacktrackPoint);
376 public ArrayList<BacktrackPoint> getExecutionTrace() {
377 return executionTrace;
380 public int getParentChoice() {
384 public Execution getParent() {
388 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
389 return readWriteFieldsMap;
392 public void setParentChoice(int parChoice) {
393 parentChoice = parChoice;
396 public void setParent(Execution par) {
401 // This class compactly stores Read and Write field sets
402 // We store the field name and its object ID
403 // Sharing the same field means the same field name and object ID
404 private class ReadWriteSet {
405 private HashMap<String, Integer> readSet;
406 private HashMap<String, Integer> writeSet;
408 public ReadWriteSet() {
409 readSet = new HashMap<>();
410 writeSet = new HashMap<>();
413 public void addReadField(String field, int objectId) {
414 readSet.put(field, objectId);
417 public void addWriteField(String field, int objectId) {
418 writeSet.put(field, objectId);
421 public Set<String> getReadSet() {
422 return readSet.keySet();
425 public Set<String> getWriteSet() {
426 return writeSet.keySet();
429 public boolean readFieldExists(String field) {
430 return readSet.containsKey(field);
433 public boolean writeFieldExists(String field) {
434 return writeSet.containsKey(field);
437 public int readFieldObjectId(String field) {
438 return readSet.get(field);
441 public int writeFieldObjectId(String field) {
442 return writeSet.get(field);
446 // This class stores a compact representation of a reachability graph for past executions
447 // private class ReachableTrace {
448 // private ArrayList<BacktrackPoint> pastBacktrackPointList;
449 // private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
451 // public ReachableTrace(ArrayList<BacktrackPoint> btrackPointList,
452 // HashMap<Integer, ReadWriteSet> rwFieldsMap) {
453 // pastBacktrackPointList = btrackPointList;
454 // pastReadWriteFieldsMap = rwFieldsMap;
457 // public ArrayList<BacktrackPoint> getPastBacktrackPointList() {
458 // return pastBacktrackPointList;
461 // public HashMap<Integer, ReadWriteSet> getPastReadWriteFieldsMap() {
462 // return pastReadWriteFieldsMap;
467 private final static String DO_CALL_METHOD = "doCall";
468 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
469 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
470 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
471 // Groovy library created fields
472 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
474 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
475 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
476 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
477 // Java and Groovy libraries
478 { "java", "org", "sun", "com", "gov", "groovy"};
479 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
480 private final static String GET_PROPERTY_METHOD =
481 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
482 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
483 private final static String JAVA_INTEGER = "int";
484 private final static String JAVA_STRING_LIB = "java.lang.String";
487 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
488 // Check the next choice and if the value is not the same as the expected then force the expected value
489 int choiceIndex = choiceCounter % refChoices.length;
490 int nextChoice = icsCG.getNextChoice();
491 if (refChoices[choiceIndex] != nextChoice) {
492 int expectedChoice = refChoices[choiceIndex];
493 int currCGIndex = icsCG.getNextChoiceIndex();
494 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
495 icsCG.setChoice(currCGIndex, expectedChoice);
498 // Record state ID and choice/event as backtrack point
499 int stateId = vm.getStateId();
500 currentExecution.addBacktrackPoint(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
501 // Store restorable state object for this state (always store the latest)
502 RestorableVMState restorableState = vm.getRestorableState();
503 restorableStateMap.put(stateId, restorableState);
506 private Integer[] copyChoices(Integer[] choicesToCopy) {
508 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
509 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
510 return copyOfChoices;
513 // --- Functions related to cycle detection and reachability graph
515 // Detect cycles in the current execution/trace
516 // We terminate the execution iff:
517 // (1) the state has been visited in the current execution
518 // (2) the state has one or more cycles that involve all the events
519 // With simple approach we only need to check for a re-visited state.
520 // Basically, we have to check that we have executed all events between two occurrences of such state.
521 private boolean containsCyclesWithAllEvents(int stId) {
523 // False if the state ID hasn't been recorded
524 if (!stateToEventMap.containsKey(stId)) {
527 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
528 // Check if this set contains all the event choices
529 // If not then this is not the terminating condition
530 for(int i=0; i<=maxEventChoice; i++) {
531 if (!visitedEvents.contains(i)) {
538 private void initializeStatesVariables() {
545 currVisitedStates = new HashSet<>();
546 justVisitedStates = new HashSet<>();
547 prevVisitedStates = new HashSet<>();
548 stateToEventMap = new HashMap<>();
550 backtrackMap = new HashMap<>();
551 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
552 currentExecution = new Execution();
553 doneBacktrackSet = new HashSet<>();
554 stateToChoiceCounterMap = new HashMap<>();
555 rGraph = new HashMap<>();
557 isEndOfExecution = false;
560 private void mapStateToEvent(int nextChoiceValue) {
561 // Update all states with this event/choice
562 // This means that all past states now see this transition
563 Set<Integer> stateSet = stateToEventMap.keySet();
564 for(Integer stateId : stateSet) {
565 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
566 eventSet.add(nextChoiceValue);
570 private void saveExecutionToRGraph(int stateId) {
571 // Save execution state into the reachability graph only if
572 // (1) It is not a revisited state from a past execution, or
573 // (2) It is just a new backtracking point
574 if (!prevVisitedStates.contains(stateId) ||
575 choiceCounter <= 1) {
576 ArrayList<Execution> reachableExecutions;
577 if (!prevVisitedStates.contains(stateId)) {
578 reachableExecutions = new ArrayList<>();
579 rGraph.put(stateId, reachableExecutions);
581 reachableExecutions = rGraph.get(stateId);
583 reachableExecutions.add(currentExecution);
587 private boolean terminateCurrentExecution() {
588 // We need to check all the states that have just been visited
589 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
590 for(Integer stateId : justVisitedStates) {
591 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
598 private void updateStateInfo(Search search) {
599 // Update the state variables
600 // Line 19 in the paper page 11 (see the heading note above)
601 int stateId = search.getStateId();
602 // Insert state ID into the map if it is new
603 if (!stateToEventMap.containsKey(stateId)) {
604 HashSet<Integer> eventSet = new HashSet<>();
605 stateToEventMap.put(stateId, eventSet);
607 saveExecutionToRGraph(stateId);
608 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
609 stateToChoiceCounterMap.put(stateId, choiceCounter);
610 justVisitedStates.add(stateId);
611 currVisitedStates.add(stateId);
614 // --- Functions related to Read/Write access analysis on shared fields
616 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, Execution parentExecution, int parentChoice) {
617 // Insert backtrack point to the right state ID
618 LinkedList<BacktrackExecution> backtrackExecList;
619 if (backtrackMap.containsKey(stateId)) {
620 backtrackExecList = backtrackMap.get(stateId);
622 backtrackExecList = new LinkedList<>();
623 backtrackMap.put(stateId, backtrackExecList);
625 // Add the new backtrack execution object
626 Execution newExecution = new Execution();
627 newExecution.setParent(parentExecution);
628 newExecution.setParentChoice(parentChoice);
629 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, newExecution));
630 // Add to priority queue
631 if (!backtrackStateQ.contains(stateId)) {
632 backtrackStateQ.add(stateId);
636 // Analyze Read/Write accesses that are directly invoked on fields
637 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
638 // Do the analysis to get Read and Write accesses to fields
639 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
640 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
641 // Record the field in the map
642 if (executedInsn instanceof WriteInstruction) {
643 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
644 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
645 if (fieldClass.startsWith(str)) {
649 rwSet.addWriteField(fieldClass, objectId);
650 } else if (executedInsn instanceof ReadInstruction) {
651 rwSet.addReadField(fieldClass, objectId);
655 // Analyze Read accesses that are indirect (performed through iterators)
656 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
657 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
659 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
660 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
661 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
662 // Extract info from the stack frame
663 StackFrame frame = ti.getTopFrame();
664 int[] frameSlots = frame.getSlots();
665 // Get the Groovy callsite library at index 0
666 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
667 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
670 // Get the iterated object whose property is accessed
671 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
672 if (eiAccessObj == null) {
675 // We exclude library classes (they start with java, org, etc.) and some more
676 String objClassName = eiAccessObj.getClassInfo().getName();
677 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
678 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
681 // Extract fields from this object and put them into the read write
682 int numOfFields = eiAccessObj.getNumberOfFields();
683 for(int i=0; i<numOfFields; i++) {
684 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
685 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
686 String fieldClass = fieldInfo.getFullName();
687 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
688 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
689 // Record the field in the map
690 rwSet.addReadField(fieldClass, objectId);
696 private int checkAndAdjustChoice(int currentChoice, VM vm) {
697 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
698 // for certain method calls in the infrastructure, e.g., eventSince()
699 int currChoiceInd = currentChoice % refChoices.length;
700 int currChoiceFromCG = currChoiceInd;
701 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
702 // This is the main event CG
703 if (currentCG instanceof IntIntervalGenerator) {
704 // This is the interval CG used in device handlers
705 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
706 // Iterate until we find the IntChoiceFromSet CG
707 while (!(parentCG instanceof IntChoiceFromSet)) {
708 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
710 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
711 // Find the index of the event/choice in refChoices
712 for (int i = 0; i<refChoices.length; i++) {
713 if (actualEvtNum == refChoices[i]) {
714 currChoiceFromCG = i;
719 if (currChoiceInd != currChoiceFromCG) {
720 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
722 return currentChoice;
725 private void createBacktrackingPoint(int backtrackChoice, int conflictChoice, Execution execution) {
727 // Create a new list of choices for backtrack based on the current choice and conflicting event number
728 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
729 // for the original set {0, 1, 2, 3}
730 Integer[] newChoiceList = new Integer[refChoices.length];
731 //int firstChoice = choices[actualChoice];
732 ArrayList<BacktrackPoint> pastTrace = execution.getExecutionTrace();
733 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
734 int btrackChoice = currTrace.get(backtrackChoice).getChoice();
735 int stateId = pastTrace.get(conflictChoice).getStateId();
736 // Check if this trace has been done from this state
737 if (isTraceAlreadyConstructed(btrackChoice, stateId)) {
740 // Put the conflicting event numbers first and reverse the order
741 newChoiceList[0] = btrackChoice;
742 newChoiceList[1] = pastTrace.get(conflictChoice).getChoice();
743 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
744 for (int i = 0, j = 2; i < refChoices.length; i++) {
745 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
746 newChoiceList[j] = refChoices[i];
750 // Parent choice is conflict choice - 1
751 addNewBacktrackPoint(stateId, newChoiceList, execution, conflictChoice - 1);
754 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
755 for (String excludedField : excludedStrings) {
756 if (className.contains(excludedField)) {
763 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
764 for (String excludedField : excludedStrings) {
765 if (className.endsWith(excludedField)) {
772 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
773 for (String excludedField : excludedStrings) {
774 if (className.startsWith(excludedField)) {
781 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
783 // Check if we are reaching the end of our execution: no more backtracking points to explore
784 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
785 if (!backtrackStateQ.isEmpty()) {
786 // Set done all the other backtrack points
787 for (BacktrackPoint backtrackPoint : currentExecution.getExecutionTrace()) {
788 backtrackPoint.getBacktrackCG().setDone();
790 // Reset the next backtrack point with the latest state
791 int hiStateId = backtrackStateQ.peek();
792 // Restore the state first if necessary
793 if (vm.getStateId() != hiStateId) {
794 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
795 vm.restoreState(restorableState);
797 // Set the backtrack CG
798 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
799 setBacktrackCG(hiStateId, backtrackCG);
801 // Set done this last CG (we save a few rounds)
804 // Save all the visited states when starting a new execution of trace
805 prevVisitedStates.addAll(currVisitedStates);
806 // This marks a transitional period to the new CG
807 isEndOfExecution = true;
810 private void findFirstConflictAndCreateBacktrackPoint(int currentChoice, Instruction nextInsn, String fieldClass) {
811 // Check for conflict (go backward from current choice and get the first conflict)
812 Execution execution = currentExecution;
813 // Actual choice of the current execution trace
814 //int actualChoice = currentChoice % refChoices.length;
815 // Choice/event we want to check for conflict against (start from actual choice)
816 int pastChoice = currentChoice;
817 // Perform backward DFS through the execution graph
819 // Get the next conflict choice
820 if (pastChoice > 0) {
821 // Case #1: check against a previous choice in the same execution for conflict
822 pastChoice = pastChoice - 1;
823 } else { // pastChoice == 0 means we are at the first BacktrackPoint of this execution path
824 // Case #2: check against a previous choice in a parent execution
825 int parentChoice = execution.getParentChoice();
826 if (parentChoice > -1) {
827 // Get the parent execution
828 execution = execution.getParent();
829 pastChoice = execution.getParentChoice();
831 // If parent is -1 then this is the first execution (it has no parent) and we stop here
835 // Check if a conflict is found
836 if (isConflictFound(nextInsn, fieldClass, currentChoice, pastChoice, execution)) {
837 createBacktrackingPoint(currentChoice, pastChoice, execution);
838 break; // Stop at the first found conflict
843 private boolean isConflictFound(Instruction nextInsn, String fieldClass, int currentChoice,
844 int pastChoice, Execution pastExecution) {
846 HashMap<Integer, ReadWriteSet> pastRWFieldsMap = pastExecution.getReadWriteFieldsMap();
847 ArrayList<BacktrackPoint> pastTrace = pastExecution.getExecutionTrace();
848 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
849 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
850 if (!pastRWFieldsMap.containsKey(pastChoice) ||
851 //choices[actualChoice] == pastTrace.get(pastChoice).getChoice()) {
852 currTrace.get(currentChoice).getChoice() == pastTrace.get(pastChoice).getChoice()) {
855 HashMap<Integer, ReadWriteSet> currRWFieldsMap = pastExecution.getReadWriteFieldsMap();
856 ReadWriteSet rwSet = currRWFieldsMap.get(pastChoice);
857 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
858 // Check for conflicts with Write fields for both Read and Write instructions
859 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
860 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
861 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
862 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
868 private boolean isConflictFound(int reachableChoice, int conflictChoice, Execution execution) {
870 ArrayList<BacktrackPoint> executionTrace = execution.getExecutionTrace();
871 HashMap<Integer, ReadWriteSet> execRWFieldsMap = execution.getReadWriteFieldsMap();
872 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
873 if (!execRWFieldsMap.containsKey(conflictChoice) ||
874 executionTrace.get(reachableChoice).getChoice() == executionTrace.get(conflictChoice).getChoice()) {
878 ReadWriteSet currRWSet = execRWFieldsMap.get(reachableChoice);
879 // R/W set of choice/event that may have a potential conflict
880 ReadWriteSet evtRWSet = execRWFieldsMap.get(conflictChoice);
881 // Check for conflicts with Read and Write fields for Write instructions
882 Set<String> currWriteSet = currRWSet.getWriteSet();
883 for(String writeField : currWriteSet) {
884 int currObjId = currRWSet.writeFieldObjectId(writeField);
885 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
886 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
890 // Check for conflicts with Write fields for Read instructions
891 Set<String> currReadSet = currRWSet.getReadSet();
892 for(String readField : currReadSet) {
893 int currObjId = currRWSet.readFieldObjectId(readField);
894 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
898 // Return false if no conflict is found
902 private ReadWriteSet getReadWriteSet(int currentChoice) {
903 // Do the analysis to get Read and Write accesses to fields
905 // We already have an entry
906 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
907 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
908 rwSet = currReadWriteFieldsMap.get(currentChoice);
909 } else { // We need to create a new entry
910 rwSet = new ReadWriteSet();
911 currReadWriteFieldsMap.put(currentChoice, rwSet);
916 private boolean isFieldExcluded(String field) {
917 // Check against "starts-with", "ends-with", and "contains" list
918 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
919 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
920 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
927 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
928 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
929 // TODO: THIS IS AN OPTIMIZATION!
930 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
931 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
932 // The second time this event 1 is explored, it will generate the same state as the first one
933 StringBuilder sb = new StringBuilder();
936 sb.append(firstChoice);
937 // Check if the trace has been constructed as a backtrack point for this state
938 if (doneBacktrackSet.contains(sb.toString())) {
941 doneBacktrackSet.add(sb.toString());
945 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
946 if (choices == null || choices != icsCG.getAllChoices()) {
947 // Reset state variables
949 choices = icsCG.getAllChoices();
950 refChoices = copyChoices(choices);
951 // Clear data structures
952 currVisitedStates = new HashSet<>();
953 stateToChoiceCounterMap = new HashMap<>();
954 stateToEventMap = new HashMap<>();
955 isEndOfExecution = false;
959 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
960 // Set a backtrack CG based on a state ID
961 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
962 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
963 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
964 backtrackCG.setStateId(stateId);
966 // Update current execution with this new execution
967 Execution newExecution = backtrackExecution.getExecution();
968 if (newExecution.getParentChoice() == -1) {
969 // If it is -1 then that means we should start from the end of the parent trace for backward DFS
970 ArrayList<BacktrackPoint> parentTrace = newExecution.getParent().getExecutionTrace();
971 newExecution.setParentChoice(parentTrace.size() - 1);
973 currentExecution = newExecution;
974 // Remove from the queue if we don't have more backtrack points for that state
975 if (backtrackExecutions.isEmpty()) {
976 backtrackMap.remove(stateId);
977 backtrackStateQ.remove(stateId);
981 // --- Functions related to the reachability analysis when there is a state match
983 // TODO: OPTIMIZATION!
984 // Check and make sure that state ID and choice haven't been explored for this trace
985 private boolean alreadyChecked(HashSet<String> checkedStateIdAndChoice, BacktrackPoint backtrackPoint) {
986 int stateId = backtrackPoint.getStateId();
987 int choice = backtrackPoint.getChoice();
988 StringBuilder sb = new StringBuilder();
992 // Check if the trace has been constructed as a backtrack point for this state
993 if (checkedStateIdAndChoice.contains(sb.toString())) {
996 checkedStateIdAndChoice.add(sb.toString());
1000 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
1001 // 1) Whenever there is state match, there is a cycle of events
1002 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
1003 // 3) Then we create a new backtrack point for every new conflict
1004 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1005 // Perform this analysis only when:
1006 // 1) there is a state match,
1007 // 2) this is not during a switch to a new execution,
1008 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
1009 // 4) the matched state has been encountered in the current execution, and
1010 // 5) state > 0 (state 0 is for boolean CG)
1011 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
1012 if (currVisitedStates.contains(stateId)) {
1013 // Update the backtrack sets in the cycle
1014 updateBacktrackSetsInCycle(stateId);
1015 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
1016 // Update the backtrack sets in a previous execution
1017 updateBacktrackSetsInPreviousExecutions(stateId);
1022 // Get the start event for the past execution trace when there is a state matched from a past execution
1023 private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
1024 // Iterate and find the first occurrence of the state ID
1025 // It is guaranteed that a choice should be found because the state ID is in the list
1026 int pastConfChoice = 0;
1027 for(int i = 0; i<pastBacktrackPointList.size(); i++) {
1028 BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
1029 int stId = backtrackPoint.getStateId();
1030 if (stId == stateId) {
1035 return pastConfChoice;
1038 // Get a sorted list of reachable state IDs starting from the input stateId
1039 private ArrayList<Integer> getReachableStateIds(Set<Integer> stateIds, int stateId) {
1040 // Only include state IDs equal or greater than the input stateId: these are reachable states
1041 ArrayList<Integer> sortedStateIds = new ArrayList<>();
1042 for(Integer stId : stateIds) {
1043 if (stId >= stateId) {
1044 sortedStateIds.add(stId);
1047 Collections.sort(sortedStateIds);
1048 return sortedStateIds;
1051 // Update the backtrack sets in the cycle
1052 private void updateBacktrackSetsInCycle(int stateId) {
1053 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
1054 int reachableChoice = stateToChoiceCounterMap.get(stateId);
1055 int cycleEndChoice = choiceCounter - 1;
1056 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
1057 while (reachableChoice < cycleEndChoice) {
1058 for (int conflictChoice = reachableChoice + 1; conflictChoice <= cycleEndChoice; conflictChoice++) {
1059 if (isConflictFound(reachableChoice, conflictChoice, currentExecution)) {
1060 createBacktrackingPoint(reachableChoice, conflictChoice, currentExecution);
1067 private void updateBacktrackSetsInPreviousExecution(Execution rExecution, int stateId,
1068 HashSet<String> checkedStateIdAndChoice) {
1069 // Find the choice/event that marks the start of the subtrace from the previous execution
1070 ArrayList<BacktrackPoint> pastExecutionTrace = rExecution.getExecutionTrace();
1071 HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rExecution.getReadWriteFieldsMap();
1072 int pastConfChoice = getPastConflictChoice(stateId, pastExecutionTrace);
1073 int reachableChoice = choiceCounter;
1074 // Iterate from the starting point until the end of the past execution trace
1075 while (pastConfChoice < pastExecutionTrace.size() - 1) { // BacktrackPoint list always has a surplus of 1
1076 // Get the info of the event from the past execution trace
1077 BacktrackPoint confBtrackPoint = pastExecutionTrace.get(pastConfChoice);
1078 if (!alreadyChecked(checkedStateIdAndChoice, confBtrackPoint)) {
1079 ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
1080 // Append this event to the current list and map
1081 ArrayList<BacktrackPoint> currentTrace = currentExecution.getExecutionTrace();
1082 HashMap<Integer, ReadWriteSet> currRWFieldsMap = currentExecution.getReadWriteFieldsMap();
1083 currentTrace.add(confBtrackPoint);
1084 currRWFieldsMap.put(choiceCounter, rwSet);
1085 for (int conflictChoice = reachableChoice - 1; conflictChoice >= 0; conflictChoice--) {
1086 if (isConflictFound(reachableChoice, conflictChoice, currentExecution)) {
1087 createBacktrackingPoint(reachableChoice, conflictChoice, currentExecution);
1090 // Remove this event to replace it with a new one
1091 currentTrace.remove(currentTrace.size() - 1);
1092 currRWFieldsMap.remove(choiceCounter);
1098 // Update the backtrack sets in a previous execution
1099 private void updateBacktrackSetsInPreviousExecutions(int stateId) {
1100 // Don't check a past trace twice!
1101 HashSet<Execution> checkedTrace = new HashSet<>();
1102 // Don't check the same event twice for a revisited state
1103 HashSet<String> checkedStateIdAndChoice = new HashSet<>();
1104 // Get sorted reachable state IDs
1105 ArrayList<Integer> reachableStateIds = getReachableStateIds(rGraph.keySet(), stateId);
1106 // Iterate from this state ID until the biggest state ID
1107 for(Integer stId : reachableStateIds) {
1108 // Find the right reachability graph object that contains the stateId
1109 ArrayList<Execution> rExecutions = rGraph.get(stId);
1110 for (Execution rExecution : rExecutions) {
1111 if (!checkedTrace.contains(rExecution)) {
1112 updateBacktrackSetsInPreviousExecution(rExecution, stateId, checkedStateIdAndChoice);
1113 checkedTrace.add(rExecution);