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
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 ArrayList<BacktrackPoint> executionTrace; // The BacktrackPoint objects of this execution
360 private int parentChoice; // The parent's choice that leads to this execution
361 private Execution parent; // Store the parent for backward DFS to find conflicts
362 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
365 executionTrace = new ArrayList<>();
368 readWriteFieldsMap = new HashMap<>();
371 public void addBacktrackPoint(BacktrackPoint newBacktrackPoint) {
372 executionTrace.add(newBacktrackPoint);
375 public ArrayList<BacktrackPoint> getExecutionTrace() {
376 return executionTrace;
379 public int getParentChoice() {
383 public Execution getParent() {
387 public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
388 return readWriteFieldsMap;
391 public void setParentChoice(int parChoice) {
392 parentChoice = parChoice;
395 public void setParent(Execution par) {
400 // This class compactly stores Read and Write field sets
401 // We store the field name and its object ID
402 // Sharing the same field means the same field name and object ID
403 private class ReadWriteSet {
404 private HashMap<String, Integer> readSet;
405 private HashMap<String, Integer> writeSet;
407 public ReadWriteSet() {
408 readSet = new HashMap<>();
409 writeSet = new HashMap<>();
412 public void addReadField(String field, int objectId) {
413 readSet.put(field, objectId);
416 public void addWriteField(String field, int objectId) {
417 writeSet.put(field, objectId);
420 public Set<String> getReadSet() {
421 return readSet.keySet();
424 public Set<String> getWriteSet() {
425 return writeSet.keySet();
428 public boolean readFieldExists(String field) {
429 return readSet.containsKey(field);
432 public boolean writeFieldExists(String field) {
433 return writeSet.containsKey(field);
436 public int readFieldObjectId(String field) {
437 return readSet.get(field);
440 public int writeFieldObjectId(String field) {
441 return writeSet.get(field);
447 // This class stores a compact representation of a reachability graph for past executions
448 private class ReachableTrace {
449 private ArrayList<BacktrackPoint> pastBacktrackPointList;
450 private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
452 public ReachableTrace(ArrayList<BacktrackPoint> btrackPointList,
453 HashMap<Integer, ReadWriteSet> rwFieldsMap) {
454 pastBacktrackPointList = btrackPointList;
455 pastReadWriteFieldsMap = rwFieldsMap;
458 public ArrayList<BacktrackPoint> getPastBacktrackPointList() {
459 return pastBacktrackPointList;
462 public HashMap<Integer, ReadWriteSet> getPastReadWriteFieldsMap() {
463 return pastReadWriteFieldsMap;
468 private final static String DO_CALL_METHOD = "doCall";
469 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
470 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
471 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
472 // Groovy library created fields
473 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
475 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
476 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
477 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
478 // Java and Groovy libraries
479 { "java", "org", "sun", "com", "gov", "groovy"};
480 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
481 private final static String GET_PROPERTY_METHOD =
482 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
483 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
484 private final static String JAVA_INTEGER = "int";
485 private final static String JAVA_STRING_LIB = "java.lang.String";
488 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
489 // Check the next choice and if the value is not the same as the expected then force the expected value
490 int choiceIndex = choiceCounter % refChoices.length;
491 int nextChoice = icsCG.getNextChoice();
492 if (refChoices[choiceIndex] != nextChoice) {
493 int expectedChoice = refChoices[choiceIndex];
494 int currCGIndex = icsCG.getNextChoiceIndex();
495 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
496 icsCG.setChoice(currCGIndex, expectedChoice);
499 // Record state ID and choice/event as backtrack point
500 int stateId = vm.getStateId();
501 // backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
502 currentExecution.addBacktrackPoint(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
503 // Store restorable state object for this state (always store the latest)
504 RestorableVMState restorableState = vm.getRestorableState();
505 restorableStateMap.put(stateId, restorableState);
508 private Integer[] copyChoices(Integer[] choicesToCopy) {
510 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
511 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
512 return copyOfChoices;
515 // --- Functions related to cycle detection
517 // Detect cycles in the current execution/trace
518 // We terminate the execution iff:
519 // (1) the state has been visited in the current execution
520 // (2) the state has one or more cycles that involve all the events
521 // With simple approach we only need to check for a re-visited state.
522 // Basically, we have to check that we have executed all events between two occurrences of such state.
523 private boolean containsCyclesWithAllEvents(int stId) {
525 // False if the state ID hasn't been recorded
526 if (!stateToEventMap.containsKey(stId)) {
529 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
530 // Check if this set contains all the event choices
531 // If not then this is not the terminating condition
532 for(int i=0; i<=maxEventChoice; i++) {
533 if (!visitedEvents.contains(i)) {
540 private void initializeStatesVariables() {
547 currVisitedStates = new HashSet<>();
548 justVisitedStates = new HashSet<>();
549 prevVisitedStates = new HashSet<>();
550 stateToEventMap = new HashMap<>();
552 backtrackMap = new HashMap<>();
553 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
554 currentExecution = new Execution();
555 doneBacktrackSet = new HashSet<>();
556 stateToChoiceCounterMap = new HashMap<>();
557 rGraph = new HashMap<>();
559 isEndOfExecution = false;
562 private void mapStateToEvent(int nextChoiceValue) {
563 // Update all states with this event/choice
564 // This means that all past states now see this transition
565 Set<Integer> stateSet = stateToEventMap.keySet();
566 for(Integer stateId : stateSet) {
567 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
568 eventSet.add(nextChoiceValue);
572 private boolean terminateCurrentExecution() {
573 // We need to check all the states that have just been visited
574 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
575 for(Integer stateId : justVisitedStates) {
576 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
583 private void updateStateInfo(Search search) {
584 // Update the state variables
585 // Line 19 in the paper page 11 (see the heading note above)
586 int stateId = search.getStateId();
587 // Insert state ID into the map if it is new
588 if (!stateToEventMap.containsKey(stateId)) {
589 HashSet<Integer> eventSet = new HashSet<>();
590 stateToEventMap.put(stateId, eventSet);
592 // Save execution state into the Reachability only if
593 // (1) It is not a revisited state from a past execution, or
594 // (2) It is just a new backtracking point
595 // TODO: New algorithm
596 /* if (!prevVisitedStates.contains(stateId) ||
597 choiceCounter <= 1) {
598 ReachableTrace reachableTrace= new
599 ReachableTrace(backtrackPointList, readWriteFieldsMap);
600 ArrayList<ReachableTrace> rTrace;
601 if (!prevVisitedStates.contains(stateId)) {
602 rTrace = new ArrayList<>();
603 rGraph.put(stateId, rTrace);
605 rTrace = rGraph.get(stateId);
607 rTrace.add(reachableTrace);
609 stateToChoiceCounterMap.put(stateId, choiceCounter);
610 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);*/
611 justVisitedStates.add(stateId);
612 currVisitedStates.add(stateId);
615 // --- Functions related to Read/Write access analysis on shared fields
617 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, Execution parentExecution, int parentChoice) {
618 // Insert backtrack point to the right state ID
619 LinkedList<BacktrackExecution> backtrackExecList;
620 if (backtrackMap.containsKey(stateId)) {
621 backtrackExecList = backtrackMap.get(stateId);
623 backtrackExecList = new LinkedList<>();
624 backtrackMap.put(stateId, backtrackExecList);
626 // Add the new backtrack execution object
627 Execution newExecution = new Execution();
628 newExecution.setParent(parentExecution);
629 newExecution.setParentChoice(parentChoice);
630 backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, newExecution));
631 // Add to priority queue
632 if (!backtrackStateQ.contains(stateId)) {
633 backtrackStateQ.add(stateId);
637 // Analyze Read/Write accesses that are directly invoked on fields
638 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
639 // Do the analysis to get Read and Write accesses to fields
640 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
641 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
642 // Record the field in the map
643 if (executedInsn instanceof WriteInstruction) {
644 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
645 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
646 if (fieldClass.startsWith(str)) {
650 rwSet.addWriteField(fieldClass, objectId);
651 } else if (executedInsn instanceof ReadInstruction) {
652 rwSet.addReadField(fieldClass, objectId);
656 // Analyze Read accesses that are indirect (performed through iterators)
657 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
658 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
660 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
661 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
662 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
663 // Extract info from the stack frame
664 StackFrame frame = ti.getTopFrame();
665 int[] frameSlots = frame.getSlots();
666 // Get the Groovy callsite library at index 0
667 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
668 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
671 // Get the iterated object whose property is accessed
672 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
673 if (eiAccessObj == null) {
676 // We exclude library classes (they start with java, org, etc.) and some more
677 String objClassName = eiAccessObj.getClassInfo().getName();
678 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
679 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
682 // Extract fields from this object and put them into the read write
683 int numOfFields = eiAccessObj.getNumberOfFields();
684 for(int i=0; i<numOfFields; i++) {
685 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
686 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
687 String fieldClass = fieldInfo.getFullName();
688 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
689 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
690 // Record the field in the map
691 rwSet.addReadField(fieldClass, objectId);
697 private int checkAndAdjustChoice(int currentChoice, VM vm) {
698 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
699 // for certain method calls in the infrastructure, e.g., eventSince()
700 int currChoiceInd = currentChoice % refChoices.length;
701 int currChoiceFromCG = currChoiceInd;
702 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
703 // This is the main event CG
704 if (currentCG instanceof IntIntervalGenerator) {
705 // This is the interval CG used in device handlers
706 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
707 // Iterate until we find the IntChoiceFromSet CG
708 while (!(parentCG instanceof IntChoiceFromSet)) {
709 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
711 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
712 // Find the index of the event/choice in refChoices
713 for (int i = 0; i<refChoices.length; i++) {
714 if (actualEvtNum == refChoices[i]) {
715 currChoiceFromCG = i;
720 if (currChoiceInd != currChoiceFromCG) {
721 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
723 return currentChoice;
726 private void createBacktrackingPoint(int currentChoice, int conflictChoice, Execution execution) {
728 // Create a new list of choices for backtrack based on the current choice and conflicting event number
729 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
730 // for the original set {0, 1, 2, 3}
731 Integer[] newChoiceList = new Integer[refChoices.length];
732 //int firstChoice = choices[actualChoice];
733 ArrayList<BacktrackPoint> pastTrace = execution.getExecutionTrace();
734 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
735 int backtrackEvent = currTrace.get(currentChoice).getChoice();
736 int stateId = pastTrace.get(conflictChoice).getStateId();
737 // Check if this trace has been done from this state
738 if (isTraceAlreadyConstructed(backtrackEvent, stateId)) {
741 // Put the conflicting event numbers first and reverse the order
742 newChoiceList[0] = backtrackEvent;
743 newChoiceList[1] = pastTrace.get(conflictChoice).getChoice();
744 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
745 for (int i = 0, j = 2; i < refChoices.length; i++) {
746 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
747 newChoiceList[j] = refChoices[i];
751 // Parent choice is conflict choice - 1
752 addNewBacktrackPoint(stateId, newChoiceList, execution, conflictChoice - 1);
755 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
756 for (String excludedField : excludedStrings) {
757 if (className.contains(excludedField)) {
764 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
765 for (String excludedField : excludedStrings) {
766 if (className.endsWith(excludedField)) {
773 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
774 for (String excludedField : excludedStrings) {
775 if (className.startsWith(excludedField)) {
782 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
784 // Check if we are reaching the end of our execution: no more backtracking points to explore
785 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
786 if (!backtrackStateQ.isEmpty()) {
787 // Set done all the other backtrack points
788 for (BacktrackPoint backtrackPoint : currentExecution.getExecutionTrace()) {
789 backtrackPoint.getBacktrackCG().setDone();
791 // Reset the next backtrack point with the latest state
792 int hiStateId = backtrackStateQ.peek();
793 // Restore the state first if necessary
794 if (vm.getStateId() != hiStateId) {
795 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
796 vm.restoreState(restorableState);
798 // Set the backtrack CG
799 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
800 setBacktrackCG(hiStateId, backtrackCG);
802 // Set done this last CG (we save a few rounds)
805 // Save all the visited states when starting a new execution of trace
806 prevVisitedStates.addAll(currVisitedStates);
807 currVisitedStates.clear();
808 // This marks a transitional period to the new CG
809 isEndOfExecution = true;
812 private void findFirstConflictAndCreateBacktrackPoint(int currentChoice, Instruction nextInsn, String fieldClass) {
813 // Check for conflict (go backward from current choice and get the first conflict)
814 Execution execution = currentExecution;
815 // Actual choice of the current execution trace
816 //int actualChoice = currentChoice % refChoices.length;
817 // Choice/event we want to check for conflict against (start from actual choice)
818 int pastChoice = currentChoice;
819 // Perform backward DFS through the execution graph
821 // Get the next conflict choice
822 if (pastChoice > 0) {
823 // Case #1: check against a previous choice in the same execution for conflict
824 pastChoice = pastChoice - 1;
825 } else { // pastChoice == 0 means we are at the first BacktrackPoint of this execution path
826 // Case #2: check against a previous choice in a parent execution
827 int parentChoice = execution.getParentChoice();
828 if (parentChoice > -1) {
829 // Get the parent execution
830 execution = execution.getParent();
831 pastChoice = execution.getParentChoice();
833 // If parent is -1 then this is the first execution (it has no parent) and we stop here
837 // Check if a conflict is found
838 if (isConflictFound(nextInsn, pastChoice, execution, currentChoice, fieldClass)) {
839 createBacktrackingPoint(currentChoice, pastChoice, execution);
840 break; // Stop at the first found conflict
845 private boolean isConflictFound(Instruction nextInsn, int pastChoice, Execution pastExecution,
846 int currentChoice, String fieldClass) {
848 HashMap<Integer, ReadWriteSet> pastRWFieldsMap = pastExecution.getReadWriteFieldsMap();
849 ArrayList<BacktrackPoint> pastTrace = pastExecution.getExecutionTrace();
850 ArrayList<BacktrackPoint> currTrace = currentExecution.getExecutionTrace();
851 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
852 if (!pastRWFieldsMap.containsKey(pastChoice) ||
853 //choices[actualChoice] == pastTrace.get(pastChoice).getChoice()) {
854 currTrace.get(currentChoice).getChoice() == pastTrace.get(pastChoice).getChoice()) {
857 HashMap<Integer, ReadWriteSet> currRWFieldsMap = pastExecution.getReadWriteFieldsMap();
858 ReadWriteSet rwSet = currRWFieldsMap.get(pastChoice);
859 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
860 // Check for conflicts with Write fields for both Read and Write instructions
861 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
862 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
863 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
864 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
870 // private boolean isConflictFound(int eventCounter, int currentChoice, boolean isPastTrace) {
872 // int currActualChoice;
873 // if (isPastTrace) {
874 // currActualChoice = backtrackPointList.get(currentChoice).getChoice();
876 // int actualCurrCho = currentChoice % refChoices.length;
877 // currActualChoice = choices[actualCurrCho];
879 // // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
880 // if (!readWriteFieldsMap.containsKey(eventCounter) ||
881 // currActualChoice == backtrackPointList.get(eventCounter).getChoice()) {
884 // // Current R/W set
885 // ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
886 // // R/W set of choice/event that may have a potential conflict
887 // ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
888 // // Check for conflicts with Read and Write fields for Write instructions
889 // Set<String> currWriteSet = currRWSet.getWriteSet();
890 // for(String writeField : currWriteSet) {
891 // int currObjId = currRWSet.writeFieldObjectId(writeField);
892 // if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
893 // (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
897 // // Check for conflicts with Write fields for Read instructions
898 // Set<String> currReadSet = currRWSet.getReadSet();
899 // for(String readField : currReadSet) {
900 // int currObjId = currRWSet.readFieldObjectId(readField);
901 // if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
905 // // Return false if no conflict is found
909 // private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
911 // int actualCurrCho = currentChoice % refChoices.length;
912 // // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
913 // if (!readWriteFieldsMap.containsKey(eventCounter) ||
914 // choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
917 // ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
918 // int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
919 // // Check for conflicts with Write fields for both Read and Write instructions
920 // if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
921 // rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
922 // (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
923 // rwSet.readFieldObjectId(fieldClass) == currObjId)) {
929 private ReadWriteSet getReadWriteSet(int currentChoice) {
930 // Do the analysis to get Read and Write accesses to fields
932 // We already have an entry
933 HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
934 if (currReadWriteFieldsMap.containsKey(currentChoice)) {
935 rwSet = currReadWriteFieldsMap.get(currentChoice);
936 } else { // We need to create a new entry
937 rwSet = new ReadWriteSet();
938 currReadWriteFieldsMap.put(currentChoice, rwSet);
943 private boolean isFieldExcluded(String field) {
944 // Check against "starts-with", "ends-with", and "contains" list
945 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
946 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
947 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
954 private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
955 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
956 // TODO: THIS IS AN OPTIMIZATION!
957 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
958 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
959 // The second time this event 1 is explored, it will generate the same state as the first one
960 StringBuilder sb = new StringBuilder();
963 sb.append(firstChoice);
964 // Check if the trace has been constructed as a backtrack point for this state
965 if (doneBacktrackSet.contains(sb.toString())) {
968 doneBacktrackSet.add(sb.toString());
972 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
973 if (choices == null || choices != icsCG.getAllChoices()) {
974 // Reset state variables
976 choices = icsCG.getAllChoices();
977 refChoices = copyChoices(choices);
978 // Clear data structures
979 stateToChoiceCounterMap = new HashMap<>();
980 stateToEventMap = new HashMap<>();
981 isEndOfExecution = false;
985 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
986 // Set a backtrack CG based on a state ID
987 LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
988 BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
989 backtrackCG.setNewValues(backtrackExecution.getChoiceList()); // Get the last from the queue
990 backtrackCG.setStateId(stateId);
992 // Update current execution with this new execution
993 Execution newExecution = backtrackExecution.getExecution();
994 if (newExecution.getParentChoice() == -1) {
995 // If it is -1 then that means we should start from the end of the parent trace for backward DFS
996 ArrayList<BacktrackPoint> parentTrace = newExecution.getParent().getExecutionTrace();
997 newExecution.setParentChoice(parentTrace.size() - 1);
999 currentExecution = newExecution;
1000 // Remove from the queue if we don't have more backtrack points for that state
1001 if (backtrackExecutions.isEmpty()) {
1002 backtrackMap.remove(stateId);
1003 backtrackStateQ.remove(stateId);
1007 // --- Functions related to the reachability analysis when there is a state match
1009 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
1010 // 1) Whenever there is state match, there is a cycle of events
1011 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
1012 // 3) Then we create a new backtrack point for every new conflict
1013 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1014 // Perform this analysis only when:
1015 // 1) there is a state match,
1016 // 2) this is not during a switch to a new execution,
1017 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
1018 // 4) the matched state has been encountered in the current execution, and
1019 // 5) state > 0 (state 0 is for boolean CG)
1020 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
1021 if (currVisitedStates.contains(stateId)) {
1022 // Update the backtrack sets in the cycle
1023 updateBacktrackSetsInCycle(stateId);
1024 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
1025 // Update the backtrack sets in a previous execution
1026 updateBacktrackSetsInPreviousExecution(stateId);
1031 // Get the start event for the past execution trace when there is a state matched from a past execution
1032 private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
1033 // Iterate and find the first occurrence of the state ID
1034 // It is guaranteed that a choice should be found because the state ID is in the list
1035 int pastConfChoice = 0;
1036 for(int i = 0; i<pastBacktrackPointList.size(); i++) {
1037 BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
1038 int stId = backtrackPoint.getStateId();
1039 if (stId == stateId) {
1044 return pastConfChoice;
1047 // Get a sorted list of reachable state IDs starting from the input stateId
1048 private ArrayList<Integer> getReachableStateIds(Set<Integer> stateIds, int stateId) {
1049 // Only include state IDs equal or greater than the input stateId: these are reachable states
1050 ArrayList<Integer> sortedStateIds = new ArrayList<>();
1051 for(Integer stId : stateIds) {
1052 if (stId >= stateId) {
1053 sortedStateIds.add(stId);
1056 Collections.sort(sortedStateIds);
1057 return sortedStateIds;
1060 // Update the backtrack sets in the cycle
1061 private void updateBacktrackSetsInCycle(int stateId) {
1062 // // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
1063 // int conflictChoice = stateToChoiceCounterMap.get(stateId);
1064 // int currentChoice = choiceCounter - 1;
1065 // // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
1066 // while (conflictChoice < currentChoice) {
1067 // for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
1068 // if (isConflictFound(eventCounter, conflictChoice, false)) {
1069 //// && isNewConflict(conflictChoice, eventCounter)) {
1070 // createBacktrackingPoint(conflictChoice, eventCounter, false);
1073 // conflictChoice++;
1077 // TODO: OPTIMIZATION!
1078 // Check and make sure that state ID and choice haven't been explored for this trace
1079 private boolean isNotChecked(HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice,
1080 BacktrackPoint backtrackPoint) {
1081 int stateId = backtrackPoint.getStateId();
1082 int choice = backtrackPoint.getChoice();
1083 HashSet<Integer> choiceSet;
1084 if (checkedStateIdAndChoice.containsKey(stateId)) {
1085 choiceSet = checkedStateIdAndChoice.get(stateId);
1086 if (choiceSet.contains(choice)) {
1087 // State ID and choice found. It has been checked!
1091 choiceSet = new HashSet<>();
1092 checkedStateIdAndChoice.put(stateId, choiceSet);
1094 choiceSet.add(choice);
1099 // Update the backtrack sets in a previous execution
1100 private void updateBacktrackSetsInPreviousExecution(int stateId) {
1101 // // Don't check a past trace twice!
1102 // HashSet<ReachableTrace> checkedTrace = new HashSet<>();
1103 // // Don't check the same event twice for a revisited state
1104 // HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice = new HashMap<>();
1105 // // Get sorted reachable state IDs
1106 // ArrayList<Integer> reachableStateIds = getReachableStateIds(rGraph.keySet(), stateId);
1107 // // Iterate from this state ID until the biggest state ID
1108 // for(Integer stId : reachableStateIds) {
1109 // // Find the right reachability graph object that contains the stateId
1110 // ArrayList<ReachableTrace> rTraces = rGraph.get(stId);
1111 // for (ReachableTrace rTrace : rTraces) {
1112 // if (!checkedTrace.contains(rTrace)) {
1113 // // Find the choice/event that marks the start of the subtrace from the previous execution
1114 // ArrayList<BacktrackPoint> pastBacktrackPointList = rTrace.getPastBacktrackPointList();
1115 // HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rTrace.getPastReadWriteFieldsMap();
1116 // int pastConfChoice = getPastConflictChoice(stId, pastBacktrackPointList);
1117 // int conflictChoice = choiceCounter;
1118 // // Iterate from the starting point until the end of the past execution trace
1119 // while (pastConfChoice < pastBacktrackPointList.size() - 1) { // BacktrackPoint list always has a surplus of 1
1120 // // Get the info of the event from the past execution trace
1121 // BacktrackPoint confBtrackPoint = pastBacktrackPointList.get(pastConfChoice);
1122 // if (isNotChecked(checkedStateIdAndChoice, confBtrackPoint)) {
1123 // ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
1124 // // Append this event to the current list and map
1125 // backtrackPointList.add(confBtrackPoint);
1126 // readWriteFieldsMap.put(choiceCounter, rwSet);
1127 // for (int eventCounter = conflictChoice - 1; eventCounter >= 0; eventCounter--) {
1128 // if (isConflictFound(eventCounter, conflictChoice, true)) {
1129 // && isNewConflict(conflictChoice, eventCounter)) {
1130 // createBacktrackingPoint(conflictChoice, eventCounter, true);
1133 // // Remove this event to replace it with a new one
1134 // backtrackPointList.remove(backtrackPointList.size() - 1);
1135 // readWriteFieldsMap.remove(choiceCounter);
1137 // pastConfChoice++;
1139 // checkedTrace.add(rTrace);