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;
32 import java.io.PrintWriter;
35 // TODO: Fix for Groovy's model-checking
36 // TODO: This is a setter to change the values of the ChoiceGenerator to implement POR
38 * Simple tool to log state changes.
40 * This DPOR implementation is augmented by the algorithm presented in this SPIN paper:
41 * http://spinroot.com/spin/symposia/ws08/spin2008_submission_33.pdf
43 * The algorithm is presented on page 11 of the paper. Basically, we create a graph G
44 * (i.e., visible operation dependency graph)
45 * that maps inter-related threads/sub-programs that trigger state changes.
46 * The key to this approach is that we evaluate graph G in every iteration/recursion to
47 * only update the backtrack sets of the threads/sub-programs that are reachable in graph G
48 * from the currently running thread/sub-program.
50 public class DPORStateReducer extends ListenerAdapter {
52 // Information printout fields for verbose mode
53 private boolean verboseMode;
54 private boolean stateReductionMode;
55 private final PrintWriter out;
56 private String detail;
59 private Transition transition;
61 // DPOR-related fields
63 private Integer[] choices;
64 private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
65 private int choiceCounter;
66 private int maxEventChoice;
67 // Data structure to track the events seen by each state to track cycles (containing all events) for termination
68 private HashSet<Integer> currVisitedStates; // States being visited in the current execution
69 private HashSet<Integer> justVisitedStates; // States just visited in the previous choice/event
70 private HashSet<Integer> prevVisitedStates; // States visited in the previous execution
71 private HashMap<Integer, HashSet<Integer>> stateToEventMap;
72 // Data structure to analyze field Read/Write accesses and conflicts
73 private HashMap<Integer, LinkedList<Integer[]>> backtrackMap; // Track created backtracking points
74 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
75 private ArrayList<BacktrackPoint> backtrackPointList; // Record backtrack points (CG, state Id, and choice)
76 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
77 private HashSet<String> doneBacktrackSet; // Record state ID and trace already constructed
78 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
79 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
81 // Visible operation dependency graph implementation (SPIN paper) related fields
82 private int prevChoiceValue;
83 private HashMap<Integer, HashSet<Integer>> vodGraphMap; // Visible operation dependency graph (VOD graph)
86 private boolean isBooleanCGFlipped;
87 private boolean isEndOfExecution;
89 public DPORStateReducer(Config config, JPF jpf) {
90 verboseMode = config.getBoolean("printout_state_transition", false);
91 stateReductionMode = config.getBoolean("activate_state_reduction", true);
93 out = new PrintWriter(System.out, true);
97 isBooleanCGFlipped = false;
98 restorableStateMap = new HashMap<>();
99 initializeStatesVariables();
103 public void stateRestored(Search search) {
105 id = search.getStateId();
106 depth = search.getDepth();
107 transition = search.getTransition();
109 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
110 " and depth: " + depth + "\n");
115 public void searchStarted(Search search) {
117 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
122 public void stateAdvanced(Search search) {
124 id = search.getStateId();
125 depth = search.getDepth();
126 transition = search.getTransition();
127 if (search.isNewState()) {
133 if (search.isEndState()) {
134 out.println("\n==> DEBUG: This is the last state!\n");
137 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
138 " which is " + detail + " Transition: " + transition + "\n");
140 if (stateReductionMode) {
141 updateStateInfo(search);
146 public void stateBacktracked(Search search) {
148 id = search.getStateId();
149 depth = search.getDepth();
150 transition = search.getTransition();
153 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
154 " and depth: " + depth + "\n");
156 if (stateReductionMode) {
157 updateStateInfo(search);
162 public void searchFinished(Search search) {
164 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
169 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
170 if (stateReductionMode) {
171 // Initialize with necessary information from the CG
172 if (nextCG instanceof IntChoiceFromSet) {
173 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
174 if (!isEndOfExecution) {
175 // Check if CG has been initialized, otherwise initialize it
176 Integer[] cgChoices = icsCG.getAllChoices();
177 // Record the events (from choices)
178 if (choices == null) {
180 // Make a copy of choices as reference
181 refChoices = copyChoices(choices);
182 // Record the max event choice (the last element of the choice array)
183 maxEventChoice = choices[choices.length - 1];
185 icsCG.setNewValues(choices);
187 // Use a modulo since choiceCounter is going to keep increasing
188 int choiceIndex = choiceCounter % choices.length;
189 icsCG.advance(choices[choiceIndex]);
191 // Set done all CGs while transitioning to a new execution
199 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
201 if (stateReductionMode) {
202 // Check the boolean CG and if it is flipped, we are resetting the analysis
203 if (currentCG instanceof BooleanChoiceGenerator) {
204 if (!isBooleanCGFlipped) {
205 isBooleanCGFlipped = true;
207 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
208 initializeStatesVariables();
211 // Check every choice generated and ensure fair scheduling!
212 if (currentCG instanceof IntChoiceFromSet) {
213 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
214 // If this is a new CG then we need to update data structures
215 resetStatesForNewExecution(icsCG, vm);
216 // If we don't see a fair scheduling of events/choices then we have to enforce it
217 fairSchedulingAndBacktrackPoint(icsCG, vm);
218 // Map state to event
219 mapStateToEvent(icsCG.getNextChoice());
220 // Update the VOD graph always with the latest
221 updateVODGraph(icsCG.getNextChoice());
222 // Check if we have seen this state or this state contains cycles that involve all events
223 if (terminateCurrentExecution()) {
224 exploreNextBacktrackPoints(vm, icsCG);
226 justVisitedStates.clear();
233 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
234 if (stateReductionMode) {
235 if (!isEndOfExecution) {
236 // Has to be initialized and a integer CG
237 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
238 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
239 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
240 if (currentChoice < 0) { // If choice is -1 then skip
243 currentChoice = checkAndAdjustChoice(currentChoice, vm);
244 // Record accesses from executed instructions
245 if (executedInsn instanceof JVMFieldInstruction) {
246 // Analyze only after being initialized
247 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
248 // We don't care about libraries
249 if (!isFieldExcluded(fieldClass)) {
250 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
252 } else if (executedInsn instanceof INVOKEINTERFACE) {
253 // Handle the read/write accesses that occur through iterators
254 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
256 // Analyze conflicts from next instructions
257 if (nextInsn instanceof JVMFieldInstruction) {
258 // Skip the constructor because it is called once and does not have shared access with other objects
259 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
260 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
261 if (!isFieldExcluded(fieldClass)) {
262 // Check for conflict (go backward from current choice and get the first conflict)
263 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
264 // Check for conflicts with Write fields for both Read and Write instructions
265 // Check and record a backtrack set for just once!
266 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
267 isNewConflict(currentChoice, eventCounter)) {
268 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
269 if (vm.isNewState() || isReachableInVODGraph(currentChoice)) {
270 createBacktrackingPoint(currentChoice, eventCounter);
287 // This class compactly stores Read and Write field sets
288 // We store the field name and its object ID
289 // Sharing the same field means the same field name and object ID
290 private class ReadWriteSet {
291 private HashMap<String, Integer> readSet;
292 private HashMap<String, Integer> writeSet;
294 public ReadWriteSet() {
295 readSet = new HashMap<>();
296 writeSet = new HashMap<>();
299 public void addReadField(String field, int objectId) {
300 readSet.put(field, objectId);
303 public void addWriteField(String field, int objectId) {
304 writeSet.put(field, objectId);
307 public boolean readFieldExists(String field) {
308 return readSet.containsKey(field);
311 public boolean writeFieldExists(String field) {
312 return writeSet.containsKey(field);
315 public int readFieldObjectId(String field) {
316 return readSet.get(field);
319 public int writeFieldObjectId(String field) {
320 return writeSet.get(field);
324 // This class compactly stores backtrack points: 1) backtrack state ID, and 2) backtracking choices
325 private class BacktrackPoint {
326 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
327 private int stateId; // State at this backtrack point
328 private int choice; // Choice chosen at this backtrack point
330 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
336 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
338 public int getStateId() {
342 public int getChoice() {
348 private final static String DO_CALL_METHOD = "doCall";
349 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
350 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
351 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
352 // Groovy library created fields
353 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
355 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
356 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
357 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
358 // Java and Groovy libraries
359 { "java", "org", "sun", "com", "gov", "groovy"};
360 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
361 private final static String GET_PROPERTY_METHOD =
362 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
363 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
364 private final static String JAVA_INTEGER = "int";
365 private final static String JAVA_STRING_LIB = "java.lang.String";
368 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
369 // Check the next choice and if the value is not the same as the expected then force the expected value
370 int choiceIndex = choiceCounter % refChoices.length;
371 int nextChoice = icsCG.getNextChoice();
372 if (refChoices[choiceIndex] != nextChoice) {
373 int expectedChoice = refChoices[choiceIndex];
374 int currCGIndex = icsCG.getNextChoiceIndex();
375 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
376 icsCG.setChoice(currCGIndex, expectedChoice);
379 // Record state ID and choice/event as backtrack point
380 int stateId = vm.getStateId();
381 backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
382 // Store restorable state object for this state (always store the latest)
383 RestorableVMState restorableState = vm.getRestorableState();
384 restorableStateMap.put(stateId, restorableState);
387 private Integer[] copyChoices(Integer[] choicesToCopy) {
389 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
390 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
391 return copyOfChoices;
394 // --- Functions related to cycle detection
396 // Detect cycles in the current execution/trace
397 // We terminate the execution iff:
398 // (1) the state has been visited in the current execution
399 // (2) the state has one or more cycles that involve all the events
400 // With simple approach we only need to check for a re-visited state.
401 // Basically, we have to check that we have executed all events between two occurrences of such state.
402 private boolean containsCyclesWithAllEvents(int stId) {
404 // False if the state ID hasn't been recorded
405 if (!stateToEventMap.containsKey(stId)) {
408 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
409 // Check if this set contains all the event choices
410 // If not then this is not the terminating condition
411 for(int i=0; i<=maxEventChoice; i++) {
412 if (!visitedEvents.contains(i)) {
419 private void initializeStatesVariables() {
426 currVisitedStates = new HashSet<>();
427 justVisitedStates = new HashSet<>();
428 prevVisitedStates = new HashSet<>();
429 stateToEventMap = new HashMap<>();
431 backtrackMap = new HashMap<>();
432 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
433 backtrackPointList = new ArrayList<>();
434 conflictPairMap = new HashMap<>();
435 doneBacktrackSet = new HashSet<>();
436 readWriteFieldsMap = new HashMap<>();
438 prevChoiceValue = -1;
439 vodGraphMap = new HashMap<>();
441 isEndOfExecution = false;
444 private void mapStateToEvent(int nextChoiceValue) {
445 // Update all states with this event/choice
446 // This means that all past states now see this transition
447 Set<Integer> stateSet = stateToEventMap.keySet();
448 for(Integer stateId : stateSet) {
449 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
450 eventSet.add(nextChoiceValue);
454 private boolean terminateCurrentExecution() {
455 // We need to check all the states that have just been visited
456 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
457 for(Integer stateId : justVisitedStates) {
458 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
465 private void updateStateInfo(Search search) {
466 // Update the state variables
467 // Line 19 in the paper page 11 (see the heading note above)
468 int stateId = search.getStateId();
469 currVisitedStates.add(stateId);
470 // Insert state ID into the map if it is new
471 if (!stateToEventMap.containsKey(stateId)) {
472 HashSet<Integer> eventSet = new HashSet<>();
473 stateToEventMap.put(stateId, eventSet);
475 justVisitedStates.add(stateId);
478 // --- Functions related to Read/Write access analysis on shared fields
480 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
481 // Insert backtrack point to the right state ID
482 LinkedList<Integer[]> backtrackList;
483 if (backtrackMap.containsKey(stateId)) {
484 backtrackList = backtrackMap.get(stateId);
486 backtrackList = new LinkedList<>();
487 backtrackMap.put(stateId, backtrackList);
489 backtrackList.addFirst(newChoiceList);
490 // Add to priority queue
491 if (!backtrackStateQ.contains(stateId)) {
492 backtrackStateQ.add(stateId);
496 // Analyze Read/Write accesses that are directly invoked on fields
497 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
498 // Do the analysis to get Read and Write accesses to fields
499 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
500 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
501 // Record the field in the map
502 if (executedInsn instanceof WriteInstruction) {
503 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
504 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
505 if (fieldClass.startsWith(str)) {
509 rwSet.addWriteField(fieldClass, objectId);
510 } else if (executedInsn instanceof ReadInstruction) {
511 rwSet.addReadField(fieldClass, objectId);
515 // Analyze Read accesses that are indirect (performed through iterators)
516 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
517 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
519 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
520 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
521 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
522 // Extract info from the stack frame
523 StackFrame frame = ti.getTopFrame();
524 int[] frameSlots = frame.getSlots();
525 // Get the Groovy callsite library at index 0
526 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
527 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
530 // Get the iterated object whose property is accessed
531 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
532 if (eiAccessObj == null) {
535 // We exclude library classes (they start with java, org, etc.) and some more
536 String objClassName = eiAccessObj.getClassInfo().getName();
537 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
538 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
541 // Extract fields from this object and put them into the read write
542 int numOfFields = eiAccessObj.getNumberOfFields();
543 for(int i=0; i<numOfFields; i++) {
544 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
545 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
546 String fieldClass = fieldInfo.getFullName();
547 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
548 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
549 // Record the field in the map
550 rwSet.addReadField(fieldClass, objectId);
556 private int checkAndAdjustChoice(int currentChoice, VM vm) {
557 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
558 // for certain method calls in the infrastructure, e.g., eventSince()
559 int currChoiceInd = currentChoice % refChoices.length;
560 int currChoiceFromCG = currChoiceInd;
561 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
562 // This is the main event CG
563 if (currentCG instanceof IntIntervalGenerator) {
564 // This is the interval CG used in device handlers
565 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
566 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
567 // Find the index of the event/choice in refChoices
568 for (int i = 0; i<refChoices.length; i++) {
569 if (actualEvtNum == refChoices[i]) {
570 currChoiceFromCG = i;
575 if (currChoiceInd != currChoiceFromCG) {
576 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
578 return currentChoice;
581 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
583 // Create a new list of choices for backtrack based on the current choice and conflicting event number
584 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
585 // for the original set {0, 1, 2, 3}
586 Integer[] newChoiceList = new Integer[refChoices.length];
587 // Put the conflicting event numbers first and reverse the order
588 int actualCurrCho = currentChoice % refChoices.length;
589 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
590 newChoiceList[0] = choices[actualCurrCho];
591 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
592 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
593 for (int i = 0, j = 2; i < refChoices.length; i++) {
594 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
595 newChoiceList[j] = refChoices[i];
599 // Get the backtrack CG for this backtrack point
600 int stateId = backtrackPointList.get(confEvtNum).getStateId();
601 // Check if this trace has been done starting from this state
602 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
605 addNewBacktrackPoint(stateId, newChoiceList);
608 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
609 for (String excludedField : excludedStrings) {
610 if (className.contains(excludedField)) {
617 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
618 for (String excludedField : excludedStrings) {
619 if (className.endsWith(excludedField)) {
626 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
627 for (String excludedField : excludedStrings) {
628 if (className.startsWith(excludedField)) {
635 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
637 // We can start exploring the next backtrack point after the current CG is advanced at least once
638 if (choiceCounter > 0) {
639 // Check if we are reaching the end of our execution: no more backtracking points to explore
640 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
641 if (!backtrackStateQ.isEmpty()) {
642 // Set done all the other backtrack points
643 for (BacktrackPoint backtrackPoint : backtrackPointList) {
644 backtrackPoint.getBacktrackCG().setDone();
646 // Reset the next backtrack point with the latest state
647 int hiStateId = backtrackStateQ.peek();
648 // Restore the state first if necessary
649 if (vm.getStateId() != hiStateId) {
650 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
651 vm.restoreState(restorableState);
653 // Set the backtrack CG
654 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
655 setBacktrackCG(hiStateId, backtrackCG);
657 // Set done this last CG (we save a few rounds)
660 // Save all the visited states when starting a new execution of trace
661 prevVisitedStates.addAll(currVisitedStates);
662 currVisitedStates.clear();
663 // This marks a transitional period to the new CG
664 isEndOfExecution = true;
668 private ReadWriteSet getReadWriteSet(int currentChoice) {
669 // Do the analysis to get Read and Write accesses to fields
671 // We already have an entry
672 if (readWriteFieldsMap.containsKey(currentChoice)) {
673 rwSet = readWriteFieldsMap.get(currentChoice);
674 } else { // We need to create a new entry
675 rwSet = new ReadWriteSet();
676 readWriteFieldsMap.put(currentChoice, rwSet);
681 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
683 int actualCurrCho = currentChoice % refChoices.length;
684 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
685 if (!readWriteFieldsMap.containsKey(eventCounter) ||
686 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
689 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
690 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
691 // Check for conflicts with Write fields for both Read and Write instructions
692 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
693 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
694 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
695 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
701 private boolean isFieldExcluded(String field) {
702 // Check against "starts-with", "ends-with", and "contains" list
703 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
704 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
705 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
712 private boolean isNewConflict(int currentEvent, int eventNumber) {
713 HashSet<Integer> conflictSet;
714 if (!conflictPairMap.containsKey(currentEvent)) {
715 conflictSet = new HashSet<>();
716 conflictPairMap.put(currentEvent, conflictSet);
718 conflictSet = conflictPairMap.get(currentEvent);
720 // If this conflict has been recorded before, we return false because
721 // we don't want to save this backtrack point twice
722 if (conflictSet.contains(eventNumber)) {
725 // If it hasn't been recorded, then do otherwise
726 conflictSet.add(eventNumber);
730 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
731 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
732 // TODO: THIS IS AN OPTIMIZATION!
733 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
734 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
735 // The second time this event 1 is explored, it will generate the same state as the first one
736 StringBuilder sb = new StringBuilder();
739 sb.append(choiceList[0]);
740 // Check if the trace has been constructed as a backtrack point for this state
741 if (doneBacktrackSet.contains(sb.toString())) {
744 doneBacktrackSet.add(sb.toString());
748 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
749 if (choices == null || choices != icsCG.getAllChoices()) {
750 // Reset state variables
752 choices = icsCG.getAllChoices();
753 refChoices = copyChoices(choices);
754 // Clearing data structures
755 conflictPairMap.clear();
756 readWriteFieldsMap.clear();
757 stateToEventMap.clear();
758 isEndOfExecution = false;
759 backtrackPointList.clear();
763 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
764 // Set a backtrack CG based on a state ID
765 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
766 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
767 backtrackCG.setStateId(stateId);
769 // Remove from the queue if we don't have more backtrack points for that state
770 if (backtrackChoices.isEmpty()) {
771 backtrackMap.remove(stateId);
772 backtrackStateQ.remove(stateId);
776 // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
778 // This method checks whether a choice is reachable in the VOD graph from a reference choice (BFS algorithm)
779 //private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
780 private boolean isReachableInVODGraph(int currentChoice) {
781 // Extract previous and current events
782 int choiceIndex = currentChoice % refChoices.length;
783 int prevChoIndex = (currentChoice - 1) % refChoices.length;
784 int currEvent = refChoices[choiceIndex];
785 int prevEvent = refChoices[prevChoIndex];
786 // Record visited choices as we search in the graph
787 HashSet<Integer> visitedChoice = new HashSet<>();
788 visitedChoice.add(prevEvent);
789 LinkedList<Integer> nodesToVisit = new LinkedList<>();
790 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
791 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
792 if (vodGraphMap.containsKey(prevEvent)) {
793 nodesToVisit.addAll(vodGraphMap.get(prevEvent));
794 while(!nodesToVisit.isEmpty()) {
795 int choice = nodesToVisit.removeFirst();
796 if (choice == currEvent) {
799 if (visitedChoice.contains(choice)) { // If there is a loop then just continue the exploration
802 // Continue searching
803 visitedChoice.add(choice);
804 HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
805 if (choiceNextNodes != null) {
806 // Add only if there is a mapping for next nodes
807 for (Integer nextNode : choiceNextNodes) {
809 if (nextNode == choice) {
812 nodesToVisit.addLast(nextNode);
820 private void updateVODGraph(int currChoiceValue) {
821 // Update the graph when we have the current choice value
822 HashSet<Integer> choiceSet;
823 if (vodGraphMap.containsKey(prevChoiceValue)) {
824 // If the key already exists, just retrieve it
825 choiceSet = vodGraphMap.get(prevChoiceValue);
827 // Create a new entry
828 choiceSet = new HashSet<>();
829 vodGraphMap.put(prevChoiceValue, choiceSet);
831 choiceSet.add(currChoiceValue);
832 prevChoiceValue = currChoiceValue;