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<Execution>> rGraph; // Create a reachability graph for past executions
86 private boolean isBooleanCGFlipped;
87 private boolean isEndOfExecution;
90 private int numOfConflicts;
91 private int numOfTransitions;
93 public DPORStateReducer(Config config, JPF jpf) {
94 verboseMode = config.getBoolean("printout_state_transition", false);
95 stateReductionMode = config.getBoolean("activate_state_reduction", true);
97 out = new PrintWriter(System.out, true);
101 String outputFile = config.getString("file_output");
102 if (!outputFile.isEmpty()) {
104 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
105 } catch (IOException e) {
108 isBooleanCGFlipped = false;
110 numOfTransitions = 0;
111 restorableStateMap = new HashMap<>();
112 initializeStatesVariables();
116 public void stateRestored(Search search) {
118 id = search.getStateId();
119 depth = search.getDepth();
120 transition = search.getTransition();
122 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
123 " and depth: " + depth + "\n");
128 public void searchStarted(Search search) {
130 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
135 public void stateAdvanced(Search search) {
137 id = search.getStateId();
138 depth = search.getDepth();
139 transition = search.getTransition();
140 if (search.isNewState()) {
146 if (search.isEndState()) {
147 out.println("\n==> DEBUG: This is the last state!\n");
150 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
151 " which is " + detail + " Transition: " + transition + "\n");
153 if (stateReductionMode) {
154 updateStateInfo(search);
159 public void stateBacktracked(Search search) {
161 id = search.getStateId();
162 depth = search.getDepth();
163 transition = search.getTransition();
166 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
167 " and depth: " + depth + "\n");
169 if (stateReductionMode) {
170 updateStateInfo(search);
174 static Logger log = JPF.getLogger("report");
177 public void searchFinished(Search search) {
178 if (stateReductionMode) {
179 // Number of conflicts = first trace + subsequent backtrack points
180 numOfConflicts += 1 + doneBacktrackSet.size();
183 out.println("\n==> DEBUG: ----------------------------------- search finished");
184 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
185 out.println("\n==> DEBUG: Number of conflicts : " + numOfConflicts);
186 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
187 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
189 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
190 fileWriter.println("==> DEBUG: Number of conflicts : " + numOfConflicts);
191 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
192 fileWriter.println();
198 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
199 if (stateReductionMode) {
200 // Initialize with necessary information from the CG
201 if (nextCG instanceof IntChoiceFromSet) {
202 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
203 if (!isEndOfExecution) {
204 // Check if CG has been initialized, otherwise initialize it
205 Integer[] cgChoices = icsCG.getAllChoices();
206 // Record the events (from choices)
207 if (choices == null) {
209 // Make a copy of choices as reference
210 refChoices = copyChoices(choices);
211 // Record the max event choice (the last element of the choice array)
212 maxEventChoice = choices[choices.length - 1];
214 icsCG.setNewValues(choices);
216 // Use a modulo since choiceCounter is going to keep increasing
217 int choiceIndex = choiceCounter % choices.length;
218 icsCG.advance(choices[choiceIndex]);
220 // Set done all CGs while transitioning to a new execution
228 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
230 if (stateReductionMode) {
231 // Check the boolean CG and if it is flipped, we are resetting the analysis
232 if (currentCG instanceof BooleanChoiceGenerator) {
233 if (!isBooleanCGFlipped) {
234 isBooleanCGFlipped = true;
236 // Number of conflicts = first trace + subsequent backtrack points
237 numOfConflicts = 1 + doneBacktrackSet.size();
238 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
239 initializeStatesVariables();
242 // Check every choice generated and ensure fair scheduling!
243 if (currentCG instanceof IntChoiceFromSet) {
244 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
245 // If this is a new CG then we need to update data structures
246 resetStatesForNewExecution(icsCG, vm);
247 // If we don't see a fair scheduling of events/choices then we have to enforce it
248 fairSchedulingAndBacktrackPoint(icsCG, vm);
249 // Explore the next backtrack point:
250 // 1) if we have seen this state or this state contains cycles that involve all events, and
251 // 2) after the current CG is advanced at least once
252 if (terminateCurrentExecution() && choiceCounter > 0) {
253 exploreNextBacktrackPoints(vm, icsCG);
257 // Map state to event
258 mapStateToEvent(icsCG.getNextChoice());
259 justVisitedStates.clear();
268 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
269 if (stateReductionMode) {
270 if (!isEndOfExecution) {
271 // Has to be initialized and a integer CG
272 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
273 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
274 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
275 if (currentChoice < 0) { // If choice is -1 then skip
278 currentChoice = checkAndAdjustChoice(currentChoice, vm);
279 // Record accesses from executed instructions
280 if (executedInsn instanceof JVMFieldInstruction) {
281 // Analyze only after being initialized
282 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
283 // We don't care about libraries
284 if (!isFieldExcluded(fieldClass)) {
285 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
287 } else if (executedInsn instanceof INVOKEINTERFACE) {
288 // Handle the read/write accesses that occur through iterators
289 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
291 // Analyze conflicts from next instructions
292 if (nextInsn instanceof JVMFieldInstruction) {
293 // Skip the constructor because it is called once and does not have shared access with other objects
294 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
295 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
296 if (!isFieldExcluded(fieldClass)) {
297 findFirstConflictAndCreateBacktrackPoint(currentChoice, nextInsn, fieldClass);
311 // This class compactly stores backtrack execution:
312 // 1) backtrack choice list, and
313 // 2) backtrack execution
314 private class BacktrackExecution {
315 private Integer[] choiceList;
316 private Execution execution;
318 public BacktrackExecution(Integer[] choList, Execution exec) {
319 choiceList = choList;
323 public Integer[] getChoiceList() {
327 public Execution getExecution() {
332 // This class compactly stores backtrack points:
333 // 1) backtrack state ID, and
334 // 2) backtracking choices
335 private class BacktrackPoint {
336 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
337 private int stateId; // State at this backtrack point
338 private int choice; // Choice chosen at this backtrack point
340 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
346 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
348 public int getStateId() {
352 public int getChoice() {
357 // This class stores a representation of the execution graph node
358 private class Execution {
359 private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap; // Map between CG to choice numbers for O(1) access
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 cgToChoiceMap = new HashMap<>();
367 executionTrace = new ArrayList<>();
370 readWriteFieldsMap = new HashMap<>();
373 public void addBacktrackPoint(BacktrackPoint newBacktrackPoint) {
374 executionTrace.add(newBacktrackPoint);
377 public void clearCGToChoiceMap() {
378 cgToChoiceMap = null;
381 public ArrayList<BacktrackPoint> getExecutionTrace() {
382 return executionTrace;
385 public int getChoiceFromCG(IntChoiceFromSet icsCG) {
386 return cgToChoiceMap.get(icsCG);
389 public int getParentChoice() {
393 public Execution getParent() {
397 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
398 return readWriteFieldsMap;
401 public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
402 cgToChoiceMap.put(icsCG, choice);
405 public void setParentChoice(int parChoice) {
406 parentChoice = parChoice;
409 public void setParent(Execution par) {
414 // This class compactly stores Read and Write field sets
415 // We store the field name and its object ID
416 // Sharing the same field means the same field name and object ID
417 private class ReadWriteSet {
418 private HashMap<String, Integer> readSet;
419 private HashMap<String, Integer> writeSet;
421 public ReadWriteSet() {
422 readSet = new HashMap<>();
423 writeSet = new HashMap<>();
426 public void addReadField(String field, int objectId) {
427 readSet.put(field, objectId);
430 public void addWriteField(String field, int objectId) {
431 writeSet.put(field, objectId);
434 public Set<String> getReadSet() {
435 return readSet.keySet();
438 public Set<String> getWriteSet() {
439 return writeSet.keySet();
442 public boolean readFieldExists(String field) {
443 return readSet.containsKey(field);
446 public boolean writeFieldExists(String field) {
447 return writeSet.containsKey(field);
450 public int readFieldObjectId(String field) {
451 return readSet.get(field);
454 public int writeFieldObjectId(String field) {
455 return writeSet.get(field);
460 private final static String DO_CALL_METHOD = "doCall";
461 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
462 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
463 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
464 // Groovy library created fields
465 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
467 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
468 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
469 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
470 // Java and Groovy libraries
471 { "java", "org", "sun", "com", "gov", "groovy"};
472 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
473 private final static String GET_PROPERTY_METHOD =
474 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
475 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
476 private final static String JAVA_INTEGER = "int";
477 private final static String JAVA_STRING_LIB = "java.lang.String";
480 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
481 // Check the next choice and if the value is not the same as the expected then force the expected value
482 int choiceIndex = choiceCounter % refChoices.length;
483 int nextChoice = icsCG.getNextChoice();
484 if (refChoices[choiceIndex] != nextChoice) {
485 int expectedChoice = refChoices[choiceIndex];
486 int currCGIndex = icsCG.getNextChoiceIndex();
487 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
488 icsCG.setChoice(currCGIndex, expectedChoice);
491 // Record state ID and choice/event as backtrack point
492 int stateId = vm.getStateId();
493 currentExecution.addBacktrackPoint(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
494 currentExecution.mapCGToChoice(icsCG, choiceCounter);
495 // Store restorable state object for this state (always store the latest)
496 RestorableVMState restorableState = vm.getRestorableState();
497 restorableStateMap.put(stateId, restorableState);
500 private Integer[] copyChoices(Integer[] choicesToCopy) {
502 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
503 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
504 return copyOfChoices;
507 // --- Functions related to cycle detection and reachability graph
509 // Detect cycles in the current execution/trace
510 // We terminate the execution iff:
511 // (1) the state has been visited in the current execution
512 // (2) the state has one or more cycles that involve all the events
513 // With simple approach we only need to check for a re-visited state.
514 // Basically, we have to check that we have executed all events between two occurrences of such state.
515 private boolean containsCyclesWithAllEvents(int stId) {
517 // False if the state ID hasn't been recorded
518 if (!stateToEventMap.containsKey(stId)) {
521 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
522 // Check if this set contains all the event choices
523 // If not then this is not the terminating condition
524 for(int i=0; i<=maxEventChoice; i++) {
525 if (!visitedEvents.contains(i)) {
532 private void initializeStatesVariables() {
539 currVisitedStates = new HashSet<>();
540 justVisitedStates = new HashSet<>();
541 prevVisitedStates = new HashSet<>();
542 stateToEventMap = new HashMap<>();
544 backtrackMap = new HashMap<>();
545 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
546 currentExecution = new Execution();
547 doneBacktrackSet = new HashSet<>();
548 stateToChoiceCounterMap = new HashMap<>();
549 rGraph = new HashMap<>();
551 isEndOfExecution = false;
554 private void mapStateToEvent(int nextChoiceValue) {
555 // Update all states with this event/choice
556 // This means that all past states now see this transition
557 Set<Integer> stateSet = stateToEventMap.keySet();
558 for(Integer stateId : stateSet) {
559 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
560 eventSet.add(nextChoiceValue);
564 private void saveExecutionToRGraph(int stateId) {
565 // Save execution state into the reachability graph only if
566 // (1) It is not a revisited state from a past execution, or
567 // (2) It is just a new backtracking point
568 if (!prevVisitedStates.contains(stateId) ||
569 choiceCounter <= 1) {
570 ArrayList<Execution> reachableExecutions;
571 if (!prevVisitedStates.contains(stateId)) {
572 reachableExecutions = new ArrayList<>();
573 rGraph.put(stateId, reachableExecutions);
575 reachableExecutions = rGraph.get(stateId);
577 reachableExecutions.add(currentExecution);
581 private boolean terminateCurrentExecution() {
582 // We need to check all the states that have just been visited
583 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
584 for(Integer stateId : justVisitedStates) {
585 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
592 private void updateStateInfo(Search search) {
593 // Update the state variables
594 // Line 19 in the paper page 11 (see the heading note above)
595 int stateId = search.getStateId();
596 // Insert state ID into the map if it is new
597 if (!stateToEventMap.containsKey(stateId)) {
598 HashSet<Integer> eventSet = new HashSet<>();
599 stateToEventMap.put(stateId, eventSet);
601 saveExecutionToRGraph(stateId);
602 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
603 stateToChoiceCounterMap.put(stateId, choiceCounter);
604 justVisitedStates.add(stateId);
605 currVisitedStates.add(stateId);
608 // --- Functions related to Read/Write access analysis on shared fields
610 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, Execution parentExecution, int parentChoice) {
611 // Insert backtrack point to the right state ID
612 LinkedList<BacktrackExecution> backtrackExecList;
613 if (backtrackMap.containsKey(stateId)) {
614 backtrackExecList = backtrackMap.get(stateId);
616 backtrackExecList = new LinkedList<>();
617 backtrackMap.put(stateId, backtrackExecList);
619 // Add the new backtrack execution object
620 Execution newExecution = new Execution();
621 newExecution.setParent(parentExecution);
622 newExecution.setParentChoice(parentChoice);
623 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, newExecution));
624 // Add to priority queue
625 if (!backtrackStateQ.contains(stateId)) {
626 backtrackStateQ.add(stateId);
630 // Analyze Read/Write accesses that are directly invoked on fields
631 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
632 // Do the analysis to get Read and Write accesses to fields
633 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
634 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
635 // Record the field in the map
636 if (executedInsn instanceof WriteInstruction) {
637 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
638 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
639 if (fieldClass.startsWith(str)) {
643 rwSet.addWriteField(fieldClass, objectId);
644 } else if (executedInsn instanceof ReadInstruction) {
645 rwSet.addReadField(fieldClass, objectId);
649 // Analyze Read accesses that are indirect (performed through iterators)
650 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
651 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
653 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
654 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
655 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
656 // Extract info from the stack frame
657 StackFrame frame = ti.getTopFrame();
658 int[] frameSlots = frame.getSlots();
659 // Get the Groovy callsite library at index 0
660 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
661 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
664 // Get the iterated object whose property is accessed
665 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
666 if (eiAccessObj == null) {
669 // We exclude library classes (they start with java, org, etc.) and some more
670 String objClassName = eiAccessObj.getClassInfo().getName();
671 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
672 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
675 // Extract fields from this object and put them into the read write
676 int numOfFields = eiAccessObj.getNumberOfFields();
677 for(int i=0; i<numOfFields; i++) {
678 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
679 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
680 String fieldClass = fieldInfo.getFullName();
681 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
682 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
683 // Record the field in the map
684 rwSet.addReadField(fieldClass, objectId);
690 private int checkAndAdjustChoice(int currentChoice, VM vm) {
691 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
692 // for certain method calls in the infrastructure, e.g., eventSince()
693 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
694 // This is the main event CG
695 if (currentCG instanceof IntIntervalGenerator) {
696 // This is the interval CG used in device handlers
697 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
698 // Iterate until we find the IntChoiceFromSet CG
699 while (!(parentCG instanceof IntChoiceFromSet)) {
700 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
702 // Find the choice related to the IntIntervalGenerator CG from the map
703 currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
705 return currentChoice;
708 private void createBacktrackingPoint(int backtrackChoice, int conflictChoice, Execution execution) {
710 // Create a new list of choices for backtrack based on the current choice and conflicting event number
711 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
712 // for the original set {0, 1, 2, 3}
713 Integer[] newChoiceList = new Integer[refChoices.length];
714 //int firstChoice = choices[actualChoice];
715 ArrayList<BacktrackPoint> pastTrace = execution.getExecutionTrace();
716 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
717 int btrackChoice = currTrace.get(backtrackChoice).getChoice();
718 int stateId = pastTrace.get(conflictChoice).getStateId();
719 // Check if this trace has been done from this state
720 if (isTraceAlreadyConstructed(btrackChoice, stateId)) {
723 // Put the conflicting event numbers first and reverse the order
724 newChoiceList[0] = btrackChoice;
725 newChoiceList[1] = pastTrace.get(conflictChoice).getChoice();
726 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
727 for (int i = 0, j = 2; i < refChoices.length; i++) {
728 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
729 newChoiceList[j] = refChoices[i];
733 // Parent choice is conflict choice - 1
734 addNewBacktrackPoint(stateId, newChoiceList, execution, conflictChoice - 1);
737 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
738 for (String excludedField : excludedStrings) {
739 if (className.contains(excludedField)) {
746 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
747 for (String excludedField : excludedStrings) {
748 if (className.endsWith(excludedField)) {
755 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
756 for (String excludedField : excludedStrings) {
757 if (className.startsWith(excludedField)) {
764 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
766 // Check if we are reaching the end of our execution: no more backtracking points to explore
767 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
768 if (!backtrackStateQ.isEmpty()) {
769 // Set done all the other backtrack points
770 for (BacktrackPoint backtrackPoint : currentExecution.getExecutionTrace()) {
771 backtrackPoint.getBacktrackCG().setDone();
773 // Reset the next backtrack point with the latest state
774 int hiStateId = backtrackStateQ.peek();
775 // Restore the state first if necessary
776 if (vm.getStateId() != hiStateId) {
777 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
778 vm.restoreState(restorableState);
780 // Set the backtrack CG
781 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
782 setBacktrackCG(hiStateId, backtrackCG);
784 // Set done this last CG (we save a few rounds)
787 // Save all the visited states when starting a new execution of trace
788 prevVisitedStates.addAll(currVisitedStates);
789 // This marks a transitional period to the new CG
790 isEndOfExecution = true;
793 private void findFirstConflictAndCreateBacktrackPoint(int currentChoice, Instruction nextInsn, String fieldClass) {
794 // Check for conflict (go backward from current choice and get the first conflict)
795 Execution execution = currentExecution;
796 // Choice/event we want to check for conflict against (start from actual choice)
797 int pastChoice = currentChoice;
798 // Perform backward DFS through the execution graph
800 // Get the next conflict choice
801 if (pastChoice > 0) {
802 // Case #1: check against a previous choice in the same execution for conflict
803 pastChoice = pastChoice - 1;
804 } else { // pastChoice == 0 means we are at the first BacktrackPoint of this execution path
805 // Case #2: check against a previous choice in a parent execution
806 int parentChoice = execution.getParentChoice();
807 if (parentChoice > -1) {
808 // Get the parent execution
809 execution = execution.getParent();
810 pastChoice = execution.getParentChoice();
812 // If parent is -1 then this is the first execution (it has no parent) and we stop here
816 // Check if a conflict is found
817 if (isConflictFound(nextInsn, fieldClass, currentChoice, pastChoice, execution)) {
818 createBacktrackingPoint(currentChoice, pastChoice, execution);
819 break; // Stop at the first found conflict
824 private boolean isConflictFound(Instruction nextInsn, String fieldClass, int currentChoice,
825 int pastChoice, Execution pastExecution) {
827 HashMap<Integer, ReadWriteSet> pastRWFieldsMap = pastExecution.getReadWriteFieldsMap();
828 ArrayList<BacktrackPoint> pastTrace = pastExecution.getExecutionTrace();
829 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
830 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
831 if (!pastRWFieldsMap.containsKey(pastChoice) ||
832 currTrace.get(currentChoice).getChoice() == pastTrace.get(pastChoice).getChoice()) {
835 HashMap<Integer, ReadWriteSet> currRWFieldsMap = pastExecution.getReadWriteFieldsMap();
836 ReadWriteSet rwSet = currRWFieldsMap.get(pastChoice);
837 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
838 // Check for conflicts with Write fields for both Read and Write instructions
839 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
840 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
841 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
842 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
848 private boolean isConflictFound(int reachableChoice, int conflictChoice, Execution execution) {
850 ArrayList<BacktrackPoint> executionTrace = execution.getExecutionTrace();
851 HashMap<Integer, ReadWriteSet> execRWFieldsMap = execution.getReadWriteFieldsMap();
852 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
853 if (!execRWFieldsMap.containsKey(conflictChoice) ||
854 executionTrace.get(reachableChoice).getChoice() == executionTrace.get(conflictChoice).getChoice()) {
858 ReadWriteSet currRWSet = execRWFieldsMap.get(reachableChoice);
859 // R/W set of choice/event that may have a potential conflict
860 ReadWriteSet evtRWSet = execRWFieldsMap.get(conflictChoice);
861 // Check for conflicts with Read and Write fields for Write instructions
862 Set<String> currWriteSet = currRWSet.getWriteSet();
863 for(String writeField : currWriteSet) {
864 int currObjId = currRWSet.writeFieldObjectId(writeField);
865 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
866 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
870 // Check for conflicts with Write fields for Read instructions
871 Set<String> currReadSet = currRWSet.getReadSet();
872 for(String readField : currReadSet) {
873 int currObjId = currRWSet.readFieldObjectId(readField);
874 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
878 // Return false if no conflict is found
882 private ReadWriteSet getReadWriteSet(int currentChoice) {
883 // Do the analysis to get Read and Write accesses to fields
885 // We already have an entry
886 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
887 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
888 rwSet = currReadWriteFieldsMap.get(currentChoice);
889 } else { // We need to create a new entry
890 rwSet = new ReadWriteSet();
891 currReadWriteFieldsMap.put(currentChoice, rwSet);
896 private boolean isFieldExcluded(String field) {
897 // Check against "starts-with", "ends-with", and "contains" list
898 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
899 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
900 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
907 // Check if this trace is already constructed
908 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
909 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
910 // TODO: THIS IS AN OPTIMIZATION!
911 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
912 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
913 // The second time this event 1 is explored, it will generate the same state as the first one
914 StringBuilder sb = new StringBuilder();
917 sb.append(firstChoice);
918 // Check if the trace has been constructed as a backtrack point for this state
919 if (doneBacktrackSet.contains(sb.toString())) {
922 doneBacktrackSet.add(sb.toString());
926 // Reset data structure for each new execution
927 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
928 if (choices == null || choices != icsCG.getAllChoices()) {
929 // Reset state variables
931 choices = icsCG.getAllChoices();
932 refChoices = copyChoices(choices);
933 // Clear data structures
934 currVisitedStates = new HashSet<>();
935 stateToChoiceCounterMap = new HashMap<>();
936 stateToEventMap = new HashMap<>();
937 isEndOfExecution = false;
941 // Set a backtrack point for a particular state
942 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
943 // Set a backtrack CG based on a state ID
944 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
945 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
946 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
947 backtrackCG.setStateId(stateId);
949 // Update current execution with this new execution
950 Execution newExecution = backtrackExecution.getExecution();
951 if (newExecution.getParentChoice() == -1) {
952 // If it is -1 then that means we should start from the end of the parent trace for backward DFS
953 ArrayList<BacktrackPoint> parentTrace = newExecution.getParent().getExecutionTrace();
954 newExecution.setParentChoice(parentTrace.size() - 1);
956 // Try to free some memory since this map is only used for the current execution
957 currentExecution.clearCGToChoiceMap();
958 currentExecution = newExecution;
959 // Remove from the queue if we don't have more backtrack points for that state
960 if (backtrackExecutions.isEmpty()) {
961 backtrackMap.remove(stateId);
962 backtrackStateQ.remove(stateId);
966 // --- Functions related to the reachability analysis when there is a state match
968 // TODO: OPTIMIZATION!
969 // Check and make sure that state ID and choice haven't been explored for this trace
970 private boolean isAlreadyChecked(HashSet<String> checkedStateIdAndChoice, BacktrackPoint backtrackPoint) {
971 int stateId = backtrackPoint.getStateId();
972 int choice = backtrackPoint.getChoice();
973 StringBuilder sb = new StringBuilder();
977 // Check if the trace has been constructed as a backtrack point for this state
978 if (checkedStateIdAndChoice.contains(sb.toString())) {
981 checkedStateIdAndChoice.add(sb.toString());
985 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
986 // 1) Whenever there is state match, there is a cycle of events
987 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
988 // 3) Then we create a new backtrack point for every new conflict
989 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
990 // Perform this analysis only when:
991 // 1) there is a state match,
992 // 2) this is not during a switch to a new execution,
993 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
994 // 4) the matched state has been encountered in the current execution, and
995 // 5) state > 0 (state 0 is for boolean CG)
996 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
997 if (currVisitedStates.contains(stateId)) {
998 // Update the backtrack sets in the cycle
999 updateBacktrackSetsInCycle(stateId);
1000 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
1001 // Update the backtrack sets in a previous execution
1002 updateBacktrackSetsInPreviousExecutions(stateId);
1007 // Get the start event for the past execution trace when there is a state matched from a past execution
1008 private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
1009 // Iterate and find the first occurrence of the state ID
1010 // It is guaranteed that a choice should be found because the state ID is in the list
1011 int pastConfChoice = 0;
1012 for(int i = 0; i<pastBacktrackPointList.size(); i++) {
1013 BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
1014 int stId = backtrackPoint.getStateId();
1015 if (stId == stateId) {
1020 return pastConfChoice;
1023 // Get a sorted list of reachable state IDs starting from the input stateId
1024 private ArrayList<Integer> getReachableStateIds(Set<Integer> stateIds, int stateId) {
1025 // Only include state IDs equal or greater than the input stateId: these are reachable states
1026 ArrayList<Integer> sortedStateIds = new ArrayList<>();
1027 for(Integer stId : stateIds) {
1028 if (stId >= stateId) {
1029 sortedStateIds.add(stId);
1032 Collections.sort(sortedStateIds);
1033 return sortedStateIds;
1036 // Update the backtrack sets in the cycle
1037 private void updateBacktrackSetsInCycle(int stateId) {
1038 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
1039 int reachableChoice = stateToChoiceCounterMap.get(stateId);
1040 int cycleEndChoice = choiceCounter - 1;
1041 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
1042 while (reachableChoice < cycleEndChoice) {
1043 for (int conflictChoice = reachableChoice + 1; conflictChoice <= cycleEndChoice; conflictChoice++) {
1044 if (isConflictFound(reachableChoice, conflictChoice, currentExecution)) {
1045 createBacktrackingPoint(reachableChoice, conflictChoice, currentExecution);
1052 // Update the backtrack sets in a previous execution
1053 private void updateBacktrackSetsInPreviousExecution(Execution rExecution, int stateId,
1054 HashSet<String> checkedStateIdAndChoice) {
1055 // Find the choice/event that marks the start of the subtrace from the previous execution
1056 ArrayList<BacktrackPoint> pastExecutionTrace = rExecution.getExecutionTrace();
1057 HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rExecution.getReadWriteFieldsMap();
1058 int pastConfChoice = getPastConflictChoice(stateId, pastExecutionTrace);
1059 int reachableChoice = choiceCounter;
1060 // Iterate from the starting point until the end of the past execution trace
1061 while (pastConfChoice < pastExecutionTrace.size() - 1) { // BacktrackPoint list always has a surplus of 1
1062 // Get the info of the event from the past execution trace
1063 BacktrackPoint confBtrackPoint = pastExecutionTrace.get(pastConfChoice);
1064 if (!isAlreadyChecked(checkedStateIdAndChoice, confBtrackPoint)) {
1065 ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
1066 // Append this event to the current list and map
1067 ArrayList<BacktrackPoint> currentTrace = currentExecution.getExecutionTrace();
1068 HashMap<Integer, ReadWriteSet> currRWFieldsMap = currentExecution.getReadWriteFieldsMap();
1069 currentTrace.add(confBtrackPoint);
1070 currRWFieldsMap.put(choiceCounter, rwSet);
1071 for (int conflictChoice = reachableChoice - 1; conflictChoice >= 0; conflictChoice--) {
1072 if (isConflictFound(reachableChoice, conflictChoice, currentExecution)) {
1073 createBacktrackingPoint(reachableChoice, conflictChoice, currentExecution);
1076 // Remove this event to replace it with a new one
1077 currentTrace.remove(currentTrace.size() - 1);
1078 currRWFieldsMap.remove(choiceCounter);
1084 // Update the backtrack sets in previous executions
1085 private void updateBacktrackSetsInPreviousExecutions(int stateId) {
1086 // Don't check a past trace twice!
1087 HashSet<Execution> checkedTrace = new HashSet<>();
1088 // Don't check the same event twice for a revisited state
1089 HashSet<String> checkedStateIdAndChoice = new HashSet<>();
1090 // Get sorted reachable state IDs
1091 ArrayList<Integer> reachableStateIds = getReachableStateIds(rGraph.keySet(), stateId);
1092 // Iterate from this state ID until the biggest state ID
1093 for(Integer stId : reachableStateIds) {
1094 // Find the right reachability graph object that contains the stateId
1095 ArrayList<Execution> rExecutions = rGraph.get(stId);
1096 for (Execution rExecution : rExecutions) {
1097 if (!checkedTrace.contains(rExecution)) {
1098 updateBacktrackSetsInPreviousExecution(rExecution, stateId, checkedStateIdAndChoice);
1099 checkedTrace.add(rExecution);