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<Integer[]>> backtrackMap; // Track created backtracking points
78 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
79 private ArrayList<BacktrackPoint> backtrackPointList; // Record backtrack points (CG, state Id, and choice)
80 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
81 private HashSet<String> doneBacktrackSet; // Record state ID and trace already constructed
82 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
83 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
84 private HashMap<Integer, Integer> stateToChoiceCounterMap; // Maps state IDs to the choice counter
85 private HashMap<Integer, ReachabilityGraph> stateToRGraph; // Maps state IDs to a ReachabilityGraph
88 private boolean isBooleanCGFlipped;
89 private boolean isEndOfExecution;
92 private int numOfConflicts;
93 private int numOfTransitions;
95 public DPORStateReducer(Config config, JPF jpf) {
96 verboseMode = config.getBoolean("printout_state_transition", false);
97 stateReductionMode = config.getBoolean("activate_state_reduction", true);
99 out = new PrintWriter(System.out, true);
103 String outputFile = config.getString("file_output");
104 if (!outputFile.isEmpty()) {
106 fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
107 } catch (IOException e) {
110 isBooleanCGFlipped = false;
112 numOfTransitions = 0;
113 restorableStateMap = new HashMap<>();
114 initializeStatesVariables();
118 public void stateRestored(Search search) {
120 id = search.getStateId();
121 depth = search.getDepth();
122 transition = search.getTransition();
124 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
125 " and depth: " + depth + "\n");
130 public void searchStarted(Search search) {
132 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
137 public void stateAdvanced(Search search) {
139 id = search.getStateId();
140 depth = search.getDepth();
141 transition = search.getTransition();
142 if (search.isNewState()) {
148 if (search.isEndState()) {
149 out.println("\n==> DEBUG: This is the last state!\n");
152 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
153 " which is " + detail + " Transition: " + transition + "\n");
155 if (stateReductionMode) {
156 updateStateInfo(search);
161 public void stateBacktracked(Search search) {
163 id = search.getStateId();
164 depth = search.getDepth();
165 transition = search.getTransition();
168 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
169 " and depth: " + depth + "\n");
171 if (stateReductionMode) {
172 updateStateInfo(search);
176 static Logger log = JPF.getLogger("report");
179 public void searchFinished(Search search) {
180 if (stateReductionMode) {
181 // Number of conflicts = first trace + subsequent backtrack points
182 numOfConflicts += 1 + doneBacktrackSet.size();
185 out.println("\n==> DEBUG: ----------------------------------- search finished");
186 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
187 out.println("\n==> DEBUG: Number of conflicts : " + numOfConflicts);
188 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
189 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
191 fileWriter.println("==> DEBUG: State reduction mode : " + stateReductionMode);
192 fileWriter.println("==> DEBUG: Number of conflicts : " + numOfConflicts);
193 fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
194 fileWriter.println();
200 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
201 if (stateReductionMode) {
202 // Initialize with necessary information from the CG
203 if (nextCG instanceof IntChoiceFromSet) {
204 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
205 if (!isEndOfExecution) {
206 // Check if CG has been initialized, otherwise initialize it
207 Integer[] cgChoices = icsCG.getAllChoices();
208 // Record the events (from choices)
209 if (choices == null) {
211 // Make a copy of choices as reference
212 refChoices = copyChoices(choices);
213 // Record the max event choice (the last element of the choice array)
214 maxEventChoice = choices[choices.length - 1];
216 icsCG.setNewValues(choices);
218 // Use a modulo since choiceCounter is going to keep increasing
219 int choiceIndex = choiceCounter % choices.length;
220 icsCG.advance(choices[choiceIndex]);
222 // Set done all CGs while transitioning to a new execution
230 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
232 if (stateReductionMode) {
233 // Check the boolean CG and if it is flipped, we are resetting the analysis
234 if (currentCG instanceof BooleanChoiceGenerator) {
235 if (!isBooleanCGFlipped) {
236 isBooleanCGFlipped = true;
238 // Number of conflicts = first trace + subsequent backtrack points
239 numOfConflicts = 1 + doneBacktrackSet.size();
240 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
241 initializeStatesVariables();
244 // Check every choice generated and ensure fair scheduling!
245 if (currentCG instanceof IntChoiceFromSet) {
246 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
247 // If this is a new CG then we need to update data structures
248 resetStatesForNewExecution(icsCG, vm);
249 // If we don't see a fair scheduling of events/choices then we have to enforce it
250 fairSchedulingAndBacktrackPoint(icsCG, vm);
251 // Explore the next backtrack point:
252 // 1) if we have seen this state or this state contains cycles that involve all events, and
253 // 2) after the current CG is advanced at least once
254 if (terminateCurrentExecution() && choiceCounter > 0) {
256 exploreNextBacktrackPoints(vm, icsCG);
260 // Map state to event
261 mapStateToEvent(icsCG.getNextChoice());
262 justVisitedStates.clear();
271 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
272 if (stateReductionMode) {
273 if (!isEndOfExecution) {
274 // Has to be initialized and a integer CG
275 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
276 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
277 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
278 if (currentChoice < 0) { // If choice is -1 then skip
281 currentChoice = checkAndAdjustChoice(currentChoice, vm);
282 // Record accesses from executed instructions
283 if (executedInsn instanceof JVMFieldInstruction) {
284 // Analyze only after being initialized
285 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
286 // We don't care about libraries
287 if (!isFieldExcluded(fieldClass)) {
288 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
290 } else if (executedInsn instanceof INVOKEINTERFACE) {
291 // Handle the read/write accesses that occur through iterators
292 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
294 // Analyze conflicts from next instructions
295 if (nextInsn instanceof JVMFieldInstruction) {
296 // Skip the constructor because it is called once and does not have shared access with other objects
297 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
298 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
299 if (!isFieldExcluded(fieldClass)) {
300 // Check for conflict (go backward from current choice and get the first conflict)
301 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
302 // Check for conflicts with Write fields for both Read and Write instructions
303 // Check and record a backtrack set for just once!
304 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
305 isNewConflict(currentChoice, eventCounter)) {
306 createBacktrackingPoint(currentChoice, eventCounter);
322 // This class compactly stores Read and Write field sets
323 // We store the field name and its object ID
324 // Sharing the same field means the same field name and object ID
325 private class ReadWriteSet {
326 private HashMap<String, Integer> readSet;
327 private HashMap<String, Integer> writeSet;
329 public ReadWriteSet() {
330 readSet = new HashMap<>();
331 writeSet = new HashMap<>();
334 public void addReadField(String field, int objectId) {
335 readSet.put(field, objectId);
338 public void addWriteField(String field, int objectId) {
339 writeSet.put(field, objectId);
342 public Set<String> getReadSet() {
343 return readSet.keySet();
346 public Set<String> getWriteSet() {
347 return writeSet.keySet();
350 public boolean readFieldExists(String field) {
351 return readSet.containsKey(field);
354 public boolean writeFieldExists(String field) {
355 return writeSet.containsKey(field);
358 public int readFieldObjectId(String field) {
359 return readSet.get(field);
362 public int writeFieldObjectId(String field) {
363 return writeSet.get(field);
367 // This class compactly stores backtrack points: 1) backtrack state ID, and 2) backtracking choices
368 private class BacktrackPoint {
369 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
370 private int stateId; // State at this backtrack point
371 private int choice; // Choice chosen at this backtrack point
373 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
379 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
381 public int getStateId() {
385 public int getChoice() {
390 // This class stores a compact representation of a reachability graph for past executions
391 private class ReachabilityGraph {
392 private ArrayList<BacktrackPoint> pastBacktrackPointList;
393 private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
395 public ReachabilityGraph(ArrayList<BacktrackPoint> btrackPointList,
396 HashMap<Integer, ReadWriteSet> rwFieldsMap) {
397 pastBacktrackPointList = btrackPointList;
398 pastReadWriteFieldsMap = rwFieldsMap;
401 public ArrayList<BacktrackPoint> getPastBacktrackPointList() {
402 return pastBacktrackPointList;
405 public HashMap<Integer, ReadWriteSet> getPastReadWriteFieldsMap() {
406 return pastReadWriteFieldsMap;
411 private final static String DO_CALL_METHOD = "doCall";
412 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
413 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
414 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
415 // Groovy library created fields
416 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
418 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
419 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
420 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
421 // Java and Groovy libraries
422 { "java", "org", "sun", "com", "gov", "groovy"};
423 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
424 private final static String GET_PROPERTY_METHOD =
425 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
426 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
427 private final static String JAVA_INTEGER = "int";
428 private final static String JAVA_STRING_LIB = "java.lang.String";
431 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
432 // Check the next choice and if the value is not the same as the expected then force the expected value
433 int choiceIndex = choiceCounter % refChoices.length;
434 int nextChoice = icsCG.getNextChoice();
435 if (refChoices[choiceIndex] != nextChoice) {
436 int expectedChoice = refChoices[choiceIndex];
437 int currCGIndex = icsCG.getNextChoiceIndex();
438 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
439 icsCG.setChoice(currCGIndex, expectedChoice);
442 // Record state ID and choice/event as backtrack point
443 int stateId = vm.getStateId();
444 backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
445 // Store restorable state object for this state (always store the latest)
446 RestorableVMState restorableState = vm.getRestorableState();
447 restorableStateMap.put(stateId, restorableState);
450 private Integer[] copyChoices(Integer[] choicesToCopy) {
452 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
453 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
454 return copyOfChoices;
457 // --- Functions related to cycle detection
459 // Detect cycles in the current execution/trace
460 // We terminate the execution iff:
461 // (1) the state has been visited in the current execution
462 // (2) the state has one or more cycles that involve all the events
463 // With simple approach we only need to check for a re-visited state.
464 // Basically, we have to check that we have executed all events between two occurrences of such state.
465 private boolean containsCyclesWithAllEvents(int stId) {
467 // False if the state ID hasn't been recorded
468 if (!stateToEventMap.containsKey(stId)) {
471 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
472 // Check if this set contains all the event choices
473 // If not then this is not the terminating condition
474 for(int i=0; i<=maxEventChoice; i++) {
475 if (!visitedEvents.contains(i)) {
482 private void initializeStatesVariables() {
489 currVisitedStates = new HashSet<>();
490 justVisitedStates = new HashSet<>();
491 prevVisitedStates = new HashSet<>();
492 stateToEventMap = new HashMap<>();
494 backtrackMap = new HashMap<>();
495 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
496 backtrackPointList = new ArrayList<>();
497 conflictPairMap = new HashMap<>();
498 doneBacktrackSet = new HashSet<>();
499 readWriteFieldsMap = new HashMap<>();
500 stateToChoiceCounterMap = new HashMap<>();
501 stateToRGraph = new HashMap<>();
503 isEndOfExecution = false;
506 private void mapStateToEvent(int nextChoiceValue) {
507 // Update all states with this event/choice
508 // This means that all past states now see this transition
509 Set<Integer> stateSet = stateToEventMap.keySet();
510 for(Integer stateId : stateSet) {
511 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
512 eventSet.add(nextChoiceValue);
516 private boolean terminateCurrentExecution() {
517 // We need to check all the states that have just been visited
518 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
519 for(Integer stateId : justVisitedStates) {
520 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
527 private void updateStateInfo(Search search) {
528 // Update the state variables
529 // Line 19 in the paper page 11 (see the heading note above)
530 int stateId = search.getStateId();
531 // Insert state ID into the map if it is new
532 if (!stateToEventMap.containsKey(stateId)) {
533 HashSet<Integer> eventSet = new HashSet<>();
534 stateToEventMap.put(stateId, eventSet);
536 stateToChoiceCounterMap.put(stateId, choiceCounter);
537 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
538 justVisitedStates.add(stateId);
539 currVisitedStates.add(stateId);
542 // --- Functions related to Read/Write access analysis on shared fields
544 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
545 // Insert backtrack point to the right state ID
546 LinkedList<Integer[]> backtrackList;
547 if (backtrackMap.containsKey(stateId)) {
548 backtrackList = backtrackMap.get(stateId);
550 backtrackList = new LinkedList<>();
551 backtrackMap.put(stateId, backtrackList);
553 backtrackList.addFirst(newChoiceList);
554 // Add to priority queue
555 if (!backtrackStateQ.contains(stateId)) {
556 backtrackStateQ.add(stateId);
560 // Analyze Read/Write accesses that are directly invoked on fields
561 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
562 // Do the analysis to get Read and Write accesses to fields
563 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
564 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
565 // Record the field in the map
566 if (executedInsn instanceof WriteInstruction) {
567 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
568 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
569 if (fieldClass.startsWith(str)) {
573 rwSet.addWriteField(fieldClass, objectId);
574 } else if (executedInsn instanceof ReadInstruction) {
575 rwSet.addReadField(fieldClass, objectId);
579 // Analyze Read accesses that are indirect (performed through iterators)
580 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
581 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
583 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
584 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
585 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
586 // Extract info from the stack frame
587 StackFrame frame = ti.getTopFrame();
588 int[] frameSlots = frame.getSlots();
589 // Get the Groovy callsite library at index 0
590 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
591 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
594 // Get the iterated object whose property is accessed
595 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
596 if (eiAccessObj == null) {
599 // We exclude library classes (they start with java, org, etc.) and some more
600 String objClassName = eiAccessObj.getClassInfo().getName();
601 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
602 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
605 // Extract fields from this object and put them into the read write
606 int numOfFields = eiAccessObj.getNumberOfFields();
607 for(int i=0; i<numOfFields; i++) {
608 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
609 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
610 String fieldClass = fieldInfo.getFullName();
611 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
612 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
613 // Record the field in the map
614 rwSet.addReadField(fieldClass, objectId);
620 private int checkAndAdjustChoice(int currentChoice, VM vm) {
621 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
622 // for certain method calls in the infrastructure, e.g., eventSince()
623 int currChoiceInd = currentChoice % refChoices.length;
624 int currChoiceFromCG = currChoiceInd;
625 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
626 // This is the main event CG
627 if (currentCG instanceof IntIntervalGenerator) {
628 // This is the interval CG used in device handlers
629 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
630 // Iterate until we find the IntChoiceFromSet CG
631 while (!(parentCG instanceof IntChoiceFromSet)) {
632 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
634 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
635 // Find the index of the event/choice in refChoices
636 for (int i = 0; i<refChoices.length; i++) {
637 if (actualEvtNum == refChoices[i]) {
638 currChoiceFromCG = i;
643 if (currChoiceInd != currChoiceFromCG) {
644 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
646 return currentChoice;
649 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
651 // Create a new list of choices for backtrack based on the current choice and conflicting event number
652 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
653 // for the original set {0, 1, 2, 3}
654 Integer[] newChoiceList = new Integer[refChoices.length];
655 // Put the conflicting event numbers first and reverse the order
656 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
657 newChoiceList[0] = backtrackPointList.get(currentChoice).getChoice();
658 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
659 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
660 for (int i = 0, j = 2; i < refChoices.length; i++) {
661 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
662 newChoiceList[j] = refChoices[i];
666 // Get the backtrack CG for this backtrack point
667 int stateId = backtrackPointList.get(confEvtNum).getStateId();
668 // Check if this trace has been done starting from this state
669 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
672 addNewBacktrackPoint(stateId, newChoiceList);
675 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
676 for (String excludedField : excludedStrings) {
677 if (className.contains(excludedField)) {
684 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
685 for (String excludedField : excludedStrings) {
686 if (className.endsWith(excludedField)) {
693 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
694 for (String excludedField : excludedStrings) {
695 if (className.startsWith(excludedField)) {
702 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
704 // Check if we are reaching the end of our execution: no more backtracking points to explore
705 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
706 if (!backtrackStateQ.isEmpty()) {
707 // Set done all the other backtrack points
708 for (BacktrackPoint backtrackPoint : backtrackPointList) {
709 backtrackPoint.getBacktrackCG().setDone();
711 // Reset the next backtrack point with the latest state
712 int hiStateId = backtrackStateQ.peek();
713 // Restore the state first if necessary
714 if (vm.getStateId() != hiStateId) {
715 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
716 vm.restoreState(restorableState);
718 // Set the backtrack CG
719 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
720 setBacktrackCG(hiStateId, backtrackCG);
722 // Set done this last CG (we save a few rounds)
725 // Save all the visited states when starting a new execution of trace
726 prevVisitedStates.addAll(currVisitedStates);
727 currVisitedStates.clear();
728 // This marks a transitional period to the new CG
729 isEndOfExecution = true;
732 private ReadWriteSet getReadWriteSet(int currentChoice) {
733 // Do the analysis to get Read and Write accesses to fields
735 // We already have an entry
736 if (readWriteFieldsMap.containsKey(currentChoice)) {
737 rwSet = readWriteFieldsMap.get(currentChoice);
738 } else { // We need to create a new entry
739 rwSet = new ReadWriteSet();
740 readWriteFieldsMap.put(currentChoice, rwSet);
745 private boolean isConflictFound(int eventCounter, int currentChoice) {
747 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
748 if (!readWriteFieldsMap.containsKey(eventCounter) ||
749 backtrackPointList.get(currentChoice).getChoice() == backtrackPointList.get(eventCounter).getChoice()) {
753 ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
754 // R/W set of choice/event that may have a potential conflict
755 ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
756 // Check for conflicts with Read and Write fields for Write instructions
757 Set<String> currWriteSet = currRWSet.getWriteSet();
758 for(String writeField : currWriteSet) {
759 int currObjId = currRWSet.writeFieldObjectId(writeField);
760 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
761 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
765 // Check for conflicts with Write fields for Read instructions
766 Set<String> currReadSet = currRWSet.getReadSet();
767 for(String readField : currReadSet) {
768 int currObjId = currRWSet.readFieldObjectId(readField);
769 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
773 // Return false if no conflict is found
777 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
779 int actualCurrCho = currentChoice % refChoices.length;
780 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
781 if (!readWriteFieldsMap.containsKey(eventCounter) ||
782 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
785 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
786 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
787 // Check for conflicts with Write fields for both Read and Write instructions
788 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
789 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
790 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
791 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
797 private boolean isFieldExcluded(String field) {
798 // Check against "starts-with", "ends-with", and "contains" list
799 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
800 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
801 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
808 private boolean isNewConflict(int currentEvent, int eventNumber) {
809 HashSet<Integer> conflictSet;
810 if (!conflictPairMap.containsKey(currentEvent)) {
811 conflictSet = new HashSet<>();
812 conflictPairMap.put(currentEvent, conflictSet);
814 conflictSet = conflictPairMap.get(currentEvent);
816 // If this conflict has been recorded before, we return false because
817 // we don't want to save this backtrack point twice
818 if (conflictSet.contains(eventNumber)) {
821 // If it hasn't been recorded, then do otherwise
822 conflictSet.add(eventNumber);
826 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
827 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
828 // TODO: THIS IS AN OPTIMIZATION!
829 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
830 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
831 // The second time this event 1 is explored, it will generate the same state as the first one
832 StringBuilder sb = new StringBuilder();
835 sb.append(choiceList[0]);
836 // Check if the trace has been constructed as a backtrack point for this state
837 if (doneBacktrackSet.contains(sb.toString())) {
840 doneBacktrackSet.add(sb.toString());
844 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
845 if (choices == null || choices != icsCG.getAllChoices()) {
846 // Reset state variables
848 choices = icsCG.getAllChoices();
849 refChoices = copyChoices(choices);
850 // Clear data structures
851 backtrackPointList = new ArrayList<>();
852 conflictPairMap = new HashMap<>();
853 readWriteFieldsMap = new HashMap<>();
854 stateToChoiceCounterMap = new HashMap<>();
855 stateToEventMap = new HashMap<>();
856 isEndOfExecution = false;
860 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
861 // Set a backtrack CG based on a state ID
862 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
863 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
864 backtrackCG.setStateId(stateId);
866 // Remove from the queue if we don't have more backtrack points for that state
867 if (backtrackChoices.isEmpty()) {
868 backtrackMap.remove(stateId);
869 backtrackStateQ.remove(stateId);
873 // --- Functions related to the reachability analysis when there is a state match
875 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
876 // 1) Whenever there is state match, there is a cycle of events
877 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
878 // 3) Then we create a new backtrack point for every new conflict
879 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
880 // Perform this analysis only when:
881 // 1) there is a state match,
882 // 2) this is not during a switch to a new execution,
883 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
884 // 4) the matched state has been encountered in the current execution, and
885 // 5) state > 0 (state 0 is for boolean CG)
886 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
887 if (currVisitedStates.contains(stateId)) {
888 // Update the backtrack sets in the cycle
889 updateBacktrackSetsInCycle(stateId);
890 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
891 // Update the backtrack sets in a previous execution
892 updateBacktrackSetsInPreviousExecution(stateId);
897 // Save the information from this execution for future reachability analysis
898 private void saveExecutionInfo() {
899 Set<Integer> states = stateToChoiceCounterMap.keySet();
900 ReachabilityGraph reachabilityGraph = new
901 ReachabilityGraph(backtrackPointList, readWriteFieldsMap);
902 // Map all the states visited in this execution to the same ReachabilityGraph object for fast access
903 for(Integer state : states) {
904 if (!prevVisitedStates.contains(state)) {
905 stateToRGraph.put(state, reachabilityGraph);
910 // Update the backtrack sets in the cycle
911 private void updateBacktrackSetsInCycle(int stateId) {
912 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
913 int conflictChoice = stateToChoiceCounterMap.get(stateId);
914 int currentChoice = choiceCounter - 1;
915 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
916 while (conflictChoice < currentChoice) {
917 for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
918 if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
919 createBacktrackingPoint(conflictChoice, eventCounter);
926 private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
927 // Iterate and find the first occurrence of the state ID
928 // It is guaranteed that a choice should be found because the state ID is in the list
929 int pastConfChoice = 0;
930 for(int i = 0; i<pastBacktrackPointList.size(); i++) {
931 BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
932 int stId = backtrackPoint.getStateId();
933 if (stId == stateId) {
938 return pastConfChoice;
941 // Update the backtrack sets in a previous execution
942 private void updateBacktrackSetsInPreviousExecution(int stateId) {
943 // Find the right ReachabilityGraph object that contains the stateId
944 ReachabilityGraph rGraph = stateToRGraph.get(stateId);
945 // Find the choice/event that marks the start of the subtrace from the previous execution
946 ArrayList<BacktrackPoint> pastBacktrackPointList = rGraph.getPastBacktrackPointList();
947 HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rGraph.getPastReadWriteFieldsMap();
948 int pastConfChoice = getPastConflictChoice(stateId, pastBacktrackPointList);
949 int conflictChoice = choiceCounter;
950 // Iterate from the starting point until the end of the past execution trace
951 while (pastConfChoice < pastBacktrackPointList.size() - 1) { // BacktrackPoint list always has a surplus of 1
952 // Get the info of the event from the past execution trace
953 BacktrackPoint confBtrackPoint = pastBacktrackPointList.get(pastConfChoice);
954 ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
955 // Append this event to the current list and map
956 backtrackPointList.add(confBtrackPoint);
957 readWriteFieldsMap.put(choiceCounter, rwSet);
958 for (int eventCounter = conflictChoice - 1; eventCounter >= 0; eventCounter--) {
959 if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
960 createBacktrackingPoint(conflictChoice, eventCounter);
963 // Remove this event to replace it with a new one
964 backtrackPointList.remove(backtrackPointList.size() - 1);
965 readWriteFieldsMap.remove(choiceCounter);