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) {
255 exploreNextBacktrackPoints(vm, icsCG);
259 // Map state to event
260 mapStateToEvent(icsCG.getNextChoice());
261 justVisitedStates.clear();
270 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
271 if (stateReductionMode) {
272 if (!isEndOfExecution) {
273 // Has to be initialized and a integer CG
274 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
275 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
276 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
277 if (currentChoice < 0) { // If choice is -1 then skip
280 currentChoice = checkAndAdjustChoice(currentChoice, vm);
281 // Record accesses from executed instructions
282 if (executedInsn instanceof JVMFieldInstruction) {
283 // Analyze only after being initialized
284 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
285 // We don't care about libraries
286 if (!isFieldExcluded(fieldClass)) {
287 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
289 } else if (executedInsn instanceof INVOKEINTERFACE) {
290 // Handle the read/write accesses that occur through iterators
291 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
293 // Analyze conflicts from next instructions
294 if (nextInsn instanceof JVMFieldInstruction) {
295 // Skip the constructor because it is called once and does not have shared access with other objects
296 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
297 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
298 if (!isFieldExcluded(fieldClass)) {
299 // Check for conflict (go backward from current choice and get the first conflict)
300 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
301 // Check for conflicts with Write fields for both Read and Write instructions
302 // Check and record a backtrack set for just once!
303 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
304 isNewConflict(currentChoice, eventCounter)) {
305 createBacktrackingPoint(currentChoice, eventCounter, false);
321 // This class compactly stores Read and Write field sets
322 // We store the field name and its object ID
323 // Sharing the same field means the same field name and object ID
324 private class ReadWriteSet {
325 private HashMap<String, Integer> readSet;
326 private HashMap<String, Integer> writeSet;
328 public ReadWriteSet() {
329 readSet = new HashMap<>();
330 writeSet = new HashMap<>();
333 public void addReadField(String field, int objectId) {
334 readSet.put(field, objectId);
337 public void addWriteField(String field, int objectId) {
338 writeSet.put(field, objectId);
341 public Set<String> getReadSet() {
342 return readSet.keySet();
345 public Set<String> getWriteSet() {
346 return writeSet.keySet();
349 public boolean readFieldExists(String field) {
350 return readSet.containsKey(field);
353 public boolean writeFieldExists(String field) {
354 return writeSet.containsKey(field);
357 public int readFieldObjectId(String field) {
358 return readSet.get(field);
361 public int writeFieldObjectId(String field) {
362 return writeSet.get(field);
366 // This class compactly stores backtrack points: 1) backtrack state ID, and 2) backtracking choices
367 private class BacktrackPoint {
368 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
369 private int stateId; // State at this backtrack point
370 private int choice; // Choice chosen at this backtrack point
372 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
378 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
380 public int getStateId() {
384 public int getChoice() {
389 // This class stores a compact representation of a reachability graph for past executions
390 private class ReachabilityGraph {
391 private ArrayList<BacktrackPoint> pastBacktrackPointList;
392 private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
394 public ReachabilityGraph(ArrayList<BacktrackPoint> btrackPointList,
395 HashMap<Integer, ReadWriteSet> rwFieldsMap) {
396 pastBacktrackPointList = btrackPointList;
397 pastReadWriteFieldsMap = rwFieldsMap;
400 public ArrayList<BacktrackPoint> getPastBacktrackPointList() {
401 return pastBacktrackPointList;
404 public HashMap<Integer, ReadWriteSet> getPastReadWriteFieldsMap() {
405 return pastReadWriteFieldsMap;
410 private final static String DO_CALL_METHOD = "doCall";
411 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
412 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
413 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
414 // Groovy library created fields
415 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
417 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
418 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
419 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
420 // Java and Groovy libraries
421 { "java", "org", "sun", "com", "gov", "groovy"};
422 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
423 private final static String GET_PROPERTY_METHOD =
424 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
425 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
426 private final static String JAVA_INTEGER = "int";
427 private final static String JAVA_STRING_LIB = "java.lang.String";
430 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
431 // Check the next choice and if the value is not the same as the expected then force the expected value
432 int choiceIndex = choiceCounter % refChoices.length;
433 int nextChoice = icsCG.getNextChoice();
434 if (refChoices[choiceIndex] != nextChoice) {
435 int expectedChoice = refChoices[choiceIndex];
436 int currCGIndex = icsCG.getNextChoiceIndex();
437 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
438 icsCG.setChoice(currCGIndex, expectedChoice);
441 // Record state ID and choice/event as backtrack point
442 int stateId = vm.getStateId();
443 backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
444 // Store restorable state object for this state (always store the latest)
445 RestorableVMState restorableState = vm.getRestorableState();
446 restorableStateMap.put(stateId, restorableState);
449 private Integer[] copyChoices(Integer[] choicesToCopy) {
451 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
452 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
453 return copyOfChoices;
456 // --- Functions related to cycle detection
458 // Detect cycles in the current execution/trace
459 // We terminate the execution iff:
460 // (1) the state has been visited in the current execution
461 // (2) the state has one or more cycles that involve all the events
462 // With simple approach we only need to check for a re-visited state.
463 // Basically, we have to check that we have executed all events between two occurrences of such state.
464 private boolean containsCyclesWithAllEvents(int stId) {
466 // False if the state ID hasn't been recorded
467 if (!stateToEventMap.containsKey(stId)) {
470 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
471 // Check if this set contains all the event choices
472 // If not then this is not the terminating condition
473 for(int i=0; i<=maxEventChoice; i++) {
474 if (!visitedEvents.contains(i)) {
481 private void initializeStatesVariables() {
488 currVisitedStates = new HashSet<>();
489 justVisitedStates = new HashSet<>();
490 prevVisitedStates = new HashSet<>();
491 stateToEventMap = new HashMap<>();
493 backtrackMap = new HashMap<>();
494 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
495 backtrackPointList = new ArrayList<>();
496 conflictPairMap = new HashMap<>();
497 doneBacktrackSet = new HashSet<>();
498 readWriteFieldsMap = new HashMap<>();
499 stateToChoiceCounterMap = new HashMap<>();
500 stateToRGraph = new HashMap<>();
502 isEndOfExecution = false;
505 private void mapStateToEvent(int nextChoiceValue) {
506 // Update all states with this event/choice
507 // This means that all past states now see this transition
508 Set<Integer> stateSet = stateToEventMap.keySet();
509 for(Integer stateId : stateSet) {
510 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
511 eventSet.add(nextChoiceValue);
515 private boolean terminateCurrentExecution() {
516 // We need to check all the states that have just been visited
517 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
518 for(Integer stateId : justVisitedStates) {
519 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
526 private void updateStateInfo(Search search) {
527 // Update the state variables
528 // Line 19 in the paper page 11 (see the heading note above)
529 int stateId = search.getStateId();
530 // Insert state ID into the map if it is new
531 if (!stateToEventMap.containsKey(stateId)) {
532 HashSet<Integer> eventSet = new HashSet<>();
533 stateToEventMap.put(stateId, eventSet);
535 // Save execution state into the map
536 if (!prevVisitedStates.contains(stateId)) {
537 ReachabilityGraph reachabilityGraph = new
538 ReachabilityGraph(backtrackPointList, readWriteFieldsMap);
539 stateToRGraph.put(stateId, reachabilityGraph);
541 stateToChoiceCounterMap.put(stateId, choiceCounter);
542 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
543 justVisitedStates.add(stateId);
544 currVisitedStates.add(stateId);
547 // --- Functions related to Read/Write access analysis on shared fields
549 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
550 // Insert backtrack point to the right state ID
551 LinkedList<Integer[]> backtrackList;
552 if (backtrackMap.containsKey(stateId)) {
553 backtrackList = backtrackMap.get(stateId);
555 backtrackList = new LinkedList<>();
556 backtrackMap.put(stateId, backtrackList);
558 backtrackList.addFirst(newChoiceList);
559 // Add to priority queue
560 if (!backtrackStateQ.contains(stateId)) {
561 backtrackStateQ.add(stateId);
565 // Analyze Read/Write accesses that are directly invoked on fields
566 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
567 // Do the analysis to get Read and Write accesses to fields
568 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
569 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
570 // Record the field in the map
571 if (executedInsn instanceof WriteInstruction) {
572 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
573 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
574 if (fieldClass.startsWith(str)) {
578 rwSet.addWriteField(fieldClass, objectId);
579 } else if (executedInsn instanceof ReadInstruction) {
580 rwSet.addReadField(fieldClass, objectId);
584 // Analyze Read accesses that are indirect (performed through iterators)
585 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
586 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
588 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
589 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
590 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
591 // Extract info from the stack frame
592 StackFrame frame = ti.getTopFrame();
593 int[] frameSlots = frame.getSlots();
594 // Get the Groovy callsite library at index 0
595 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
596 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
599 // Get the iterated object whose property is accessed
600 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
601 if (eiAccessObj == null) {
604 // We exclude library classes (they start with java, org, etc.) and some more
605 String objClassName = eiAccessObj.getClassInfo().getName();
606 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
607 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
610 // Extract fields from this object and put them into the read write
611 int numOfFields = eiAccessObj.getNumberOfFields();
612 for(int i=0; i<numOfFields; i++) {
613 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
614 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
615 String fieldClass = fieldInfo.getFullName();
616 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
617 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
618 // Record the field in the map
619 rwSet.addReadField(fieldClass, objectId);
625 private int checkAndAdjustChoice(int currentChoice, VM vm) {
626 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
627 // for certain method calls in the infrastructure, e.g., eventSince()
628 int currChoiceInd = currentChoice % refChoices.length;
629 int currChoiceFromCG = currChoiceInd;
630 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
631 // This is the main event CG
632 if (currentCG instanceof IntIntervalGenerator) {
633 // This is the interval CG used in device handlers
634 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
635 // Iterate until we find the IntChoiceFromSet CG
636 while (!(parentCG instanceof IntChoiceFromSet)) {
637 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
639 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
640 // Find the index of the event/choice in refChoices
641 for (int i = 0; i<refChoices.length; i++) {
642 if (actualEvtNum == refChoices[i]) {
643 currChoiceFromCG = i;
648 if (currChoiceInd != currChoiceFromCG) {
649 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
651 return currentChoice;
654 private void createBacktrackingPoint(int currentChoice, int confEvtNum, boolean isPastTrace) {
656 // Create a new list of choices for backtrack based on the current choice and conflicting event number
657 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
658 // for the original set {0, 1, 2, 3}
659 Integer[] newChoiceList = new Integer[refChoices.length];
660 // Put the conflicting event numbers first and reverse the order
662 // For past trace we get the choice/event from the list
663 newChoiceList[0] = backtrackPointList.get(currentChoice).getChoice();
665 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
666 int actualCurrCho = currentChoice % refChoices.length;
667 newChoiceList[0] = choices[actualCurrCho];
669 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
670 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
671 for (int i = 0, j = 2; i < refChoices.length; i++) {
672 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
673 newChoiceList[j] = refChoices[i];
677 // Get the backtrack CG for this backtrack point
678 int stateId = backtrackPointList.get(confEvtNum).getStateId();
679 // Check if this trace has been done starting from this state
680 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
683 addNewBacktrackPoint(stateId, newChoiceList);
686 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
687 for (String excludedField : excludedStrings) {
688 if (className.contains(excludedField)) {
695 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
696 for (String excludedField : excludedStrings) {
697 if (className.endsWith(excludedField)) {
704 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
705 for (String excludedField : excludedStrings) {
706 if (className.startsWith(excludedField)) {
713 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
715 // Check if we are reaching the end of our execution: no more backtracking points to explore
716 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
717 if (!backtrackStateQ.isEmpty()) {
718 // Set done all the other backtrack points
719 for (BacktrackPoint backtrackPoint : backtrackPointList) {
720 backtrackPoint.getBacktrackCG().setDone();
722 // Reset the next backtrack point with the latest state
723 int hiStateId = backtrackStateQ.peek();
724 // Restore the state first if necessary
725 if (vm.getStateId() != hiStateId) {
726 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
727 vm.restoreState(restorableState);
729 // Set the backtrack CG
730 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
731 setBacktrackCG(hiStateId, backtrackCG);
733 // Set done this last CG (we save a few rounds)
736 // Save all the visited states when starting a new execution of trace
737 prevVisitedStates.addAll(currVisitedStates);
738 currVisitedStates.clear();
739 // This marks a transitional period to the new CG
740 isEndOfExecution = true;
743 private ReadWriteSet getReadWriteSet(int currentChoice) {
744 // Do the analysis to get Read and Write accesses to fields
746 // We already have an entry
747 if (readWriteFieldsMap.containsKey(currentChoice)) {
748 rwSet = readWriteFieldsMap.get(currentChoice);
749 } else { // We need to create a new entry
750 rwSet = new ReadWriteSet();
751 readWriteFieldsMap.put(currentChoice, rwSet);
756 private boolean isConflictFound(int eventCounter, int currentChoice, boolean isPastTrace) {
758 int currActualChoice;
760 currActualChoice = backtrackPointList.get(currentChoice).getChoice();
762 int actualCurrCho = currentChoice % refChoices.length;
763 currActualChoice = choices[actualCurrCho];
765 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
766 if (!readWriteFieldsMap.containsKey(eventCounter) ||
767 currActualChoice == backtrackPointList.get(eventCounter).getChoice()) {
771 ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
772 // R/W set of choice/event that may have a potential conflict
773 ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
774 // Check for conflicts with Read and Write fields for Write instructions
775 Set<String> currWriteSet = currRWSet.getWriteSet();
776 for(String writeField : currWriteSet) {
777 int currObjId = currRWSet.writeFieldObjectId(writeField);
778 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
779 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
783 // Check for conflicts with Write fields for Read instructions
784 Set<String> currReadSet = currRWSet.getReadSet();
785 for(String readField : currReadSet) {
786 int currObjId = currRWSet.readFieldObjectId(readField);
787 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
791 // Return false if no conflict is found
795 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
797 int actualCurrCho = currentChoice % refChoices.length;
798 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
799 if (!readWriteFieldsMap.containsKey(eventCounter) ||
800 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
803 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
804 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
805 // Check for conflicts with Write fields for both Read and Write instructions
806 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
807 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
808 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
809 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
815 private boolean isFieldExcluded(String field) {
816 // Check against "starts-with", "ends-with", and "contains" list
817 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
818 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
819 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
826 private boolean isNewConflict(int currentEvent, int eventNumber) {
827 HashSet<Integer> conflictSet;
828 if (!conflictPairMap.containsKey(currentEvent)) {
829 conflictSet = new HashSet<>();
830 conflictPairMap.put(currentEvent, conflictSet);
832 conflictSet = conflictPairMap.get(currentEvent);
834 // If this conflict has been recorded before, we return false because
835 // we don't want to save this backtrack point twice
836 if (conflictSet.contains(eventNumber)) {
839 // If it hasn't been recorded, then do otherwise
840 conflictSet.add(eventNumber);
844 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
845 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
846 // TODO: THIS IS AN OPTIMIZATION!
847 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
848 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
849 // The second time this event 1 is explored, it will generate the same state as the first one
850 StringBuilder sb = new StringBuilder();
853 sb.append(choiceList[0]);
854 // Check if the trace has been constructed as a backtrack point for this state
855 if (doneBacktrackSet.contains(sb.toString())) {
858 doneBacktrackSet.add(sb.toString());
862 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
863 if (choices == null || choices != icsCG.getAllChoices()) {
864 // Reset state variables
866 choices = icsCG.getAllChoices();
867 refChoices = copyChoices(choices);
868 // Clear data structures
869 backtrackPointList = new ArrayList<>();
870 conflictPairMap = new HashMap<>();
871 readWriteFieldsMap = new HashMap<>();
872 stateToChoiceCounterMap = new HashMap<>();
873 stateToEventMap = new HashMap<>();
874 isEndOfExecution = false;
878 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
879 // Set a backtrack CG based on a state ID
880 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
881 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
882 backtrackCG.setStateId(stateId);
884 // Remove from the queue if we don't have more backtrack points for that state
885 if (backtrackChoices.isEmpty()) {
886 backtrackMap.remove(stateId);
887 backtrackStateQ.remove(stateId);
891 // --- Functions related to the reachability analysis when there is a state match
893 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
894 // 1) Whenever there is state match, there is a cycle of events
895 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
896 // 3) Then we create a new backtrack point for every new conflict
897 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
898 // Perform this analysis only when:
899 // 1) there is a state match,
900 // 2) this is not during a switch to a new execution,
901 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
902 // 4) the matched state has been encountered in the current execution, and
903 // 5) state > 0 (state 0 is for boolean CG)
904 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
905 if (currVisitedStates.contains(stateId)) {
906 // Update the backtrack sets in the cycle
907 updateBacktrackSetsInCycle(stateId);
908 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
909 // Update the backtrack sets in a previous execution
910 updateBacktrackSetsInPreviousExecution(stateId);
915 // Get the start event for the past execution trace when there is a state matched from a past execution
916 private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
917 // Iterate and find the first occurrence of the state ID
918 // It is guaranteed that a choice should be found because the state ID is in the list
919 int pastConfChoice = 0;
920 for(int i = 0; i<pastBacktrackPointList.size(); i++) {
921 BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
922 int stId = backtrackPoint.getStateId();
923 if (stId == stateId) {
928 return pastConfChoice;
931 // Save the information from this execution for future reachability analysis
932 // private void saveExecutionInfo() {
933 // Set<Integer> states = stateToChoiceCounterMap.keySet();
934 // // Map all the states visited in this execution to the same ReachabilityGraph object for fast access
935 // for(Integer state : states) {
936 // if (!prevVisitedStates.contains(state)) {
937 // ReachabilityGraph reachabilityGraph = new
938 // ReachabilityGraph(backtrackPointList, readWriteFieldsMap);
939 // stateToRGraph.put(state, reachabilityGraph);
944 // Update the backtrack sets in the cycle
945 private void updateBacktrackSetsInCycle(int stateId) {
946 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
947 int conflictChoice = stateToChoiceCounterMap.get(stateId);
948 int currentChoice = choiceCounter - 1;
949 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
950 while (conflictChoice < currentChoice) {
951 for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
952 if (isConflictFound(eventCounter, conflictChoice, false) && isNewConflict(conflictChoice, eventCounter)) {
953 createBacktrackingPoint(conflictChoice, eventCounter, false);
960 // Update the backtrack sets in a previous execution
961 private void updateBacktrackSetsInPreviousExecution(int stateId) {
962 // Find the right ReachabilityGraph object that contains the stateId
963 ReachabilityGraph rGraph = stateToRGraph.get(stateId);
964 // Find the choice/event that marks the start of the subtrace from the previous execution
965 ArrayList<BacktrackPoint> pastBacktrackPointList = rGraph.getPastBacktrackPointList();
966 HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rGraph.getPastReadWriteFieldsMap();
967 int pastConfChoice = getPastConflictChoice(stateId, pastBacktrackPointList);
968 int conflictChoice = choiceCounter;
969 // Iterate from the starting point until the end of the past execution trace
970 while (pastConfChoice < pastBacktrackPointList.size() - 1) { // BacktrackPoint list always has a surplus of 1
971 // Get the info of the event from the past execution trace
972 BacktrackPoint confBtrackPoint = pastBacktrackPointList.get(pastConfChoice);
973 ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
974 // Append this event to the current list and map
975 backtrackPointList.add(confBtrackPoint);
976 readWriteFieldsMap.put(choiceCounter, rwSet);
977 for (int eventCounter = conflictChoice - 1; eventCounter >= 0; eventCounter--) {
978 if (isConflictFound(eventCounter, conflictChoice, true) && isNewConflict(conflictChoice, eventCounter)) {
979 createBacktrackingPoint(conflictChoice, eventCounter, true);
982 // Remove this event to replace it with a new one
983 backtrackPointList.remove(backtrackPointList.size() - 1);
984 readWriteFieldsMap.remove(choiceCounter);