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, ArrayList<ReachableTrace>> rGraph; // Create a reachability graph
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 ReachableTrace {
391 private ArrayList<BacktrackPoint> pastBacktrackPointList;
392 private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
394 public ReachableTrace(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 rGraph = 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 Reachability only if
536 // (1) It is not a revisited state from a past execution, or
537 // (2) It is just a new backtracking point
538 if (!prevVisitedStates.contains(stateId) ||
539 choiceCounter <= 1) {
540 ReachableTrace reachableTrace= new
541 ReachableTrace(backtrackPointList, readWriteFieldsMap);
542 ArrayList<ReachableTrace> rTrace;
543 if (!prevVisitedStates.contains(stateId)) {
544 rTrace = new ArrayList<>();
545 rGraph.put(stateId, rTrace);
547 rTrace = rGraph.get(stateId);
549 rTrace.add(reachableTrace);
551 stateToChoiceCounterMap.put(stateId, choiceCounter);
552 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
553 justVisitedStates.add(stateId);
554 currVisitedStates.add(stateId);
557 // --- Functions related to Read/Write access analysis on shared fields
559 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
560 // Insert backtrack point to the right state ID
561 LinkedList<Integer[]> backtrackList;
562 if (backtrackMap.containsKey(stateId)) {
563 backtrackList = backtrackMap.get(stateId);
565 backtrackList = new LinkedList<>();
566 backtrackMap.put(stateId, backtrackList);
568 backtrackList.addFirst(newChoiceList);
569 // Add to priority queue
570 if (!backtrackStateQ.contains(stateId)) {
571 backtrackStateQ.add(stateId);
575 // Analyze Read/Write accesses that are directly invoked on fields
576 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
577 // Do the analysis to get Read and Write accesses to fields
578 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
579 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
580 // Record the field in the map
581 if (executedInsn instanceof WriteInstruction) {
582 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
583 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
584 if (fieldClass.startsWith(str)) {
588 rwSet.addWriteField(fieldClass, objectId);
589 } else if (executedInsn instanceof ReadInstruction) {
590 rwSet.addReadField(fieldClass, objectId);
594 // Analyze Read accesses that are indirect (performed through iterators)
595 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
596 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
598 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
599 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
600 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
601 // Extract info from the stack frame
602 StackFrame frame = ti.getTopFrame();
603 int[] frameSlots = frame.getSlots();
604 // Get the Groovy callsite library at index 0
605 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
606 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
609 // Get the iterated object whose property is accessed
610 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
611 if (eiAccessObj == null) {
614 // We exclude library classes (they start with java, org, etc.) and some more
615 String objClassName = eiAccessObj.getClassInfo().getName();
616 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
617 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
620 // Extract fields from this object and put them into the read write
621 int numOfFields = eiAccessObj.getNumberOfFields();
622 for(int i=0; i<numOfFields; i++) {
623 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
624 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
625 String fieldClass = fieldInfo.getFullName();
626 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
627 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
628 // Record the field in the map
629 rwSet.addReadField(fieldClass, objectId);
635 private int checkAndAdjustChoice(int currentChoice, VM vm) {
636 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
637 // for certain method calls in the infrastructure, e.g., eventSince()
638 int currChoiceInd = currentChoice % refChoices.length;
639 int currChoiceFromCG = currChoiceInd;
640 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
641 // This is the main event CG
642 if (currentCG instanceof IntIntervalGenerator) {
643 // This is the interval CG used in device handlers
644 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
645 // Iterate until we find the IntChoiceFromSet CG
646 while (!(parentCG instanceof IntChoiceFromSet)) {
647 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
649 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
650 // Find the index of the event/choice in refChoices
651 for (int i = 0; i<refChoices.length; i++) {
652 if (actualEvtNum == refChoices[i]) {
653 currChoiceFromCG = i;
658 if (currChoiceInd != currChoiceFromCG) {
659 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
661 return currentChoice;
664 private void createBacktrackingPoint(int currentChoice, int confEvtNum, boolean isPastTrace) {
666 // Create a new list of choices for backtrack based on the current choice and conflicting event number
667 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
668 // for the original set {0, 1, 2, 3}
669 Integer[] newChoiceList = new Integer[refChoices.length];
670 // Put the conflicting event numbers first and reverse the order
672 // For past trace we get the choice/event from the list
673 newChoiceList[0] = backtrackPointList.get(currentChoice).getChoice();
675 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
676 int actualCurrCho = currentChoice % refChoices.length;
677 newChoiceList[0] = choices[actualCurrCho];
679 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
680 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
681 for (int i = 0, j = 2; i < refChoices.length; i++) {
682 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
683 newChoiceList[j] = refChoices[i];
687 // Get the backtrack CG for this backtrack point
688 int stateId = backtrackPointList.get(confEvtNum).getStateId();
689 // Check if this trace has been done starting from this state
690 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
693 addNewBacktrackPoint(stateId, newChoiceList);
696 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
697 for (String excludedField : excludedStrings) {
698 if (className.contains(excludedField)) {
705 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
706 for (String excludedField : excludedStrings) {
707 if (className.endsWith(excludedField)) {
714 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
715 for (String excludedField : excludedStrings) {
716 if (className.startsWith(excludedField)) {
723 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
725 // Check if we are reaching the end of our execution: no more backtracking points to explore
726 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
727 if (!backtrackStateQ.isEmpty()) {
728 // Set done all the other backtrack points
729 for (BacktrackPoint backtrackPoint : backtrackPointList) {
730 backtrackPoint.getBacktrackCG().setDone();
732 // Reset the next backtrack point with the latest state
733 int hiStateId = backtrackStateQ.peek();
734 // Restore the state first if necessary
735 if (vm.getStateId() != hiStateId) {
736 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
737 vm.restoreState(restorableState);
739 // Set the backtrack CG
740 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
741 setBacktrackCG(hiStateId, backtrackCG);
743 // Set done this last CG (we save a few rounds)
746 // Save all the visited states when starting a new execution of trace
747 prevVisitedStates.addAll(currVisitedStates);
748 currVisitedStates.clear();
749 // This marks a transitional period to the new CG
750 isEndOfExecution = true;
753 private ReadWriteSet getReadWriteSet(int currentChoice) {
754 // Do the analysis to get Read and Write accesses to fields
756 // We already have an entry
757 if (readWriteFieldsMap.containsKey(currentChoice)) {
758 rwSet = readWriteFieldsMap.get(currentChoice);
759 } else { // We need to create a new entry
760 rwSet = new ReadWriteSet();
761 readWriteFieldsMap.put(currentChoice, rwSet);
766 private boolean isConflictFound(int eventCounter, int currentChoice, boolean isPastTrace) {
768 int currActualChoice;
770 currActualChoice = backtrackPointList.get(currentChoice).getChoice();
772 int actualCurrCho = currentChoice % refChoices.length;
773 currActualChoice = choices[actualCurrCho];
775 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
776 if (!readWriteFieldsMap.containsKey(eventCounter) ||
777 currActualChoice == backtrackPointList.get(eventCounter).getChoice()) {
781 ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
782 // R/W set of choice/event that may have a potential conflict
783 ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
784 // Check for conflicts with Read and Write fields for Write instructions
785 Set<String> currWriteSet = currRWSet.getWriteSet();
786 for(String writeField : currWriteSet) {
787 int currObjId = currRWSet.writeFieldObjectId(writeField);
788 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
789 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
793 // Check for conflicts with Write fields for Read instructions
794 Set<String> currReadSet = currRWSet.getReadSet();
795 for(String readField : currReadSet) {
796 int currObjId = currRWSet.readFieldObjectId(readField);
797 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
801 // Return false if no conflict is found
805 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
807 int actualCurrCho = currentChoice % refChoices.length;
808 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
809 if (!readWriteFieldsMap.containsKey(eventCounter) ||
810 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
813 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
814 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
815 // Check for conflicts with Write fields for both Read and Write instructions
816 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
817 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
818 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
819 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
825 private boolean isFieldExcluded(String field) {
826 // Check against "starts-with", "ends-with", and "contains" list
827 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
828 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
829 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
836 private boolean isNewConflict(int currentEvent, int eventNumber) {
837 HashSet<Integer> conflictSet;
838 if (!conflictPairMap.containsKey(currentEvent)) {
839 conflictSet = new HashSet<>();
840 conflictPairMap.put(currentEvent, conflictSet);
842 conflictSet = conflictPairMap.get(currentEvent);
844 // If this conflict has been recorded before, we return false because
845 // we don't want to save this backtrack point twice
846 if (conflictSet.contains(eventNumber)) {
849 // If it hasn't been recorded, then do otherwise
850 conflictSet.add(eventNumber);
854 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
855 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
856 // TODO: THIS IS AN OPTIMIZATION!
857 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
858 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
859 // The second time this event 1 is explored, it will generate the same state as the first one
860 StringBuilder sb = new StringBuilder();
863 sb.append(choiceList[0]);
864 // Check if the trace has been constructed as a backtrack point for this state
865 if (doneBacktrackSet.contains(sb.toString())) {
868 doneBacktrackSet.add(sb.toString());
872 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
873 if (choices == null || choices != icsCG.getAllChoices()) {
874 // Reset state variables
876 choices = icsCG.getAllChoices();
877 refChoices = copyChoices(choices);
878 // Clear data structures
879 backtrackPointList = new ArrayList<>();
880 conflictPairMap = new HashMap<>();
881 readWriteFieldsMap = new HashMap<>();
882 stateToChoiceCounterMap = new HashMap<>();
883 stateToEventMap = new HashMap<>();
884 isEndOfExecution = false;
888 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
889 // Set a backtrack CG based on a state ID
890 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
891 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
892 backtrackCG.setStateId(stateId);
894 // Remove from the queue if we don't have more backtrack points for that state
895 if (backtrackChoices.isEmpty()) {
896 backtrackMap.remove(stateId);
897 backtrackStateQ.remove(stateId);
901 // --- Functions related to the reachability analysis when there is a state match
903 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
904 // 1) Whenever there is state match, there is a cycle of events
905 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
906 // 3) Then we create a new backtrack point for every new conflict
907 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
908 // Perform this analysis only when:
909 // 1) there is a state match,
910 // 2) this is not during a switch to a new execution,
911 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
912 // 4) the matched state has been encountered in the current execution, and
913 // 5) state > 0 (state 0 is for boolean CG)
914 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 && (stateId > 0)) {
915 if (currVisitedStates.contains(stateId)) {
916 // Update the backtrack sets in the cycle
917 updateBacktrackSetsInCycle(stateId);
918 } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
919 // Update the backtrack sets in a previous execution
920 updateBacktrackSetsInPreviousExecution(stateId);
925 // Get the start event for the past execution trace when there is a state matched from a past execution
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 // Get a sorted list of reachable state IDs starting from the input stateId
942 private ArrayList<Integer> getReachableStateIds(Set<Integer> stateIds, int stateId) {
943 // Only include state IDs equal or greater than the input stateId: these are reachable states
944 ArrayList<Integer> sortedStateIds = new ArrayList<>();
945 for(Integer stId : stateIds) {
946 if (stId >= stateId) {
947 sortedStateIds.add(stId);
950 Collections.sort(sortedStateIds);
951 return sortedStateIds;
954 // Update the backtrack sets in the cycle
955 private void updateBacktrackSetsInCycle(int stateId) {
956 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
957 int conflictChoice = stateToChoiceCounterMap.get(stateId);
958 int currentChoice = choiceCounter - 1;
959 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
960 while (conflictChoice < currentChoice) {
961 for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
962 if (isConflictFound(eventCounter, conflictChoice, false) && isNewConflict(conflictChoice, eventCounter)) {
963 createBacktrackingPoint(conflictChoice, eventCounter, false);
970 // TODO: OPTIMIZATION!
971 // Check and make sure that state ID and choice haven't been explored for this trace
972 private boolean isNotChecked(HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice,
973 BacktrackPoint backtrackPoint) {
974 int stateId = backtrackPoint.getStateId();
975 int choice = backtrackPoint.getChoice();
976 HashSet<Integer> choiceSet;
977 if (checkedStateIdAndChoice.containsKey(stateId)) {
978 choiceSet = checkedStateIdAndChoice.get(stateId);
979 if (choiceSet.contains(choice)) {
980 // State ID and choice found. It has been checked!
984 choiceSet = new HashSet<>();
985 checkedStateIdAndChoice.put(stateId, choiceSet);
987 choiceSet.add(choice);
992 // Update the backtrack sets in a previous execution
993 private void updateBacktrackSetsInPreviousExecution(int stateId) {
994 // Don't check a past trace twice!
995 HashSet<ReachableTrace> checkedTrace = new HashSet<>();
996 // Don't check the same event twice for a revisited state
997 HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice = new HashMap<>();
998 // Get sorted reachable state IDs
999 ArrayList<Integer> reachableStateIds = getReachableStateIds(rGraph.keySet(), stateId);
1000 // Iterate from this state ID until the biggest state ID
1001 for(Integer stId : reachableStateIds) {
1002 // Find the right reachability graph object that contains the stateId
1003 ArrayList<ReachableTrace> rTraces = rGraph.get(stId);
1004 for (ReachableTrace rTrace : rTraces) {
1005 if (!checkedTrace.contains(rTrace)) {
1006 // Find the choice/event that marks the start of the subtrace from the previous execution
1007 ArrayList<BacktrackPoint> pastBacktrackPointList = rTrace.getPastBacktrackPointList();
1008 HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rTrace.getPastReadWriteFieldsMap();
1009 int pastConfChoice = getPastConflictChoice(stId, pastBacktrackPointList);
1010 int conflictChoice = choiceCounter;
1011 // Iterate from the starting point until the end of the past execution trace
1012 while (pastConfChoice < pastBacktrackPointList.size() - 1) { // BacktrackPoint list always has a surplus of 1
1013 // Get the info of the event from the past execution trace
1014 BacktrackPoint confBtrackPoint = pastBacktrackPointList.get(pastConfChoice);
1015 if (isNotChecked(checkedStateIdAndChoice, confBtrackPoint)) {
1016 ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
1017 // Append this event to the current list and map
1018 backtrackPointList.add(confBtrackPoint);
1019 readWriteFieldsMap.put(choiceCounter, rwSet);
1020 for (int eventCounter = conflictChoice - 1; eventCounter >= 0; eventCounter--) {
1021 if (isConflictFound(eventCounter, conflictChoice, true) && isNewConflict(conflictChoice, eventCounter)) {
1022 createBacktrackingPoint(conflictChoice, eventCounter, true);
1025 // Remove this event to replace it with a new one
1026 backtrackPointList.remove(backtrackPointList.size() - 1);
1027 readWriteFieldsMap.remove(choiceCounter);
1031 checkedTrace.add(rTrace);