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.PrintWriter;
34 // TODO: Fix for Groovy's model-checking
35 // TODO: This is a setter to change the values of the ChoiceGenerator to implement POR
37 * Simple tool to log state changes.
39 * This DPOR implementation is augmented by the algorithm presented in this SPIN paper:
40 * http://spinroot.com/spin/symposia/ws08/spin2008_submission_33.pdf
42 * The algorithm is presented on page 11 of the paper. Basically, we create a graph G
43 * (i.e., visible operation dependency graph)
44 * that maps inter-related threads/sub-programs that trigger state changes.
45 * The key to this approach is that we evaluate graph G in every iteration/recursion to
46 * only update the backtrack sets of the threads/sub-programs that are reachable in graph G
47 * from the currently running thread/sub-program.
49 public class DPORStateReducer extends ListenerAdapter {
51 // Information printout fields for verbose mode
52 private boolean verboseMode;
53 private boolean stateReductionMode;
54 private final PrintWriter out;
55 private String detail;
58 private Transition transition;
60 // DPOR-related fields
62 private Integer[] choices;
63 private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
64 private int choiceCounter;
65 private int maxEventChoice;
66 // Data structure to track the events seen by each state to track cycles (containing all events) for termination
67 private HashSet<Integer> currVisitedStates; // States being visited in the current execution
68 private HashSet<Integer> justVisitedStates; // States just visited in the previous choice/event
69 private HashSet<Integer> prevVisitedStates; // States visited in the previous execution
70 private HashMap<Integer, HashSet<Integer>> stateToEventMap;
71 // Data structure to analyze field Read/Write accesses and conflicts
72 private HashMap<Integer, LinkedList<Integer[]>> backtrackMap; // Track created backtracking points
73 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
74 private ArrayList<BacktrackPoint> backtrackPointList; // Record backtrack points (CG, state Id, and choice)
75 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
76 private HashSet<String> doneBacktrackSet; // Record state ID and trace already constructed
77 private HashMap<Integer,Integer> newStateEventMap; // Record event producing a new state ID
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 currChoiceValue;
83 private int prevChoiceValue;
84 private HashMap<Integer, HashSet<Integer>> vodGraphMap; // Visible operation dependency graph (VOD graph)
87 private boolean isBooleanCGFlipped;
88 private boolean isEndOfExecution;
90 public DPORStateReducer(Config config, JPF jpf) {
91 verboseMode = config.getBoolean("printout_state_transition", false);
92 stateReductionMode = config.getBoolean("activate_state_reduction", true);
94 out = new PrintWriter(System.out, true);
98 isBooleanCGFlipped = false;
99 restorableStateMap = new HashMap<>();
100 initializeStatesVariables();
104 public void stateRestored(Search search) {
106 id = search.getStateId();
107 depth = search.getDepth();
108 transition = search.getTransition();
110 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
111 " and depth: " + depth + "\n");
116 public void searchStarted(Search search) {
118 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
123 public void stateAdvanced(Search search) {
125 id = search.getStateId();
126 depth = search.getDepth();
127 transition = search.getTransition();
128 if (search.isNewState()) {
134 if (search.isEndState()) {
135 out.println("\n==> DEBUG: This is the last state!\n");
138 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
139 " which is " + detail + " Transition: " + transition + "\n");
141 if (stateReductionMode) {
142 updateStateInfo(search);
147 public void stateBacktracked(Search search) {
149 id = search.getStateId();
150 depth = search.getDepth();
151 transition = search.getTransition();
154 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
155 " and depth: " + depth + "\n");
157 if (stateReductionMode) {
158 updateStateInfo(search);
163 public void searchFinished(Search search) {
165 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
170 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
171 if (stateReductionMode) {
172 // Initialize with necessary information from the CG
173 if (nextCG instanceof IntChoiceFromSet) {
174 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
175 if (!isEndOfExecution) {
176 // Check if CG has been initialized, otherwise initialize it
177 Integer[] cgChoices = icsCG.getAllChoices();
178 // Record the events (from choices)
179 if (choices == null) {
181 // Make a copy of choices as reference
182 refChoices = copyChoices(choices);
183 // Record the max event choice (the last element of the choice array)
184 maxEventChoice = choices[choices.length - 1];
186 icsCG.setNewValues(choices);
188 // Use a modulo since choiceCounter is going to keep increasing
189 int choiceIndex = choiceCounter % choices.length;
190 icsCG.advance(choices[choiceIndex]);
192 // Set done all CGs while transitioning to a new execution
200 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
202 if (stateReductionMode) {
203 // Check the boolean CG and if it is flipped, we are resetting the analysis
204 if (currentCG instanceof BooleanChoiceGenerator) {
205 if (!isBooleanCGFlipped) {
206 isBooleanCGFlipped = true;
208 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
209 initializeStatesVariables();
212 // Check every choice generated and ensure fair scheduling!
213 if (currentCG instanceof IntChoiceFromSet) {
214 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
215 // If this is a new CG then we need to update data structures
216 resetStatesForNewExecution(icsCG, vm);
217 // If we don't see a fair scheduling of events/choices then we have to enforce it
218 fairSchedulingAndBacktrackPoint(icsCG, vm);
219 // Map state to event
220 mapStateToEvent(icsCG.getNextChoice());
221 // Check if we have seen this state or this state contains cycles that involve all events
222 if (terminateCurrentExecution()) {
223 exploreNextBacktrackPoints(vm, icsCG);
225 justVisitedStates.clear();
232 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
233 if (stateReductionMode) {
234 if (!isEndOfExecution) {
235 // Has to be initialized and a integer CG
236 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
237 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
238 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
239 if (currentChoice < 0) { // If choice is -1 then skip
242 currentChoice = checkAndAdjustChoice(currentChoice, vm);
243 // Record accesses from executed instructions
244 if (executedInsn instanceof JVMFieldInstruction) {
245 // Analyze only after being initialized
246 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
247 // We don't care about libraries
248 if (!isFieldExcluded(fieldClass)) {
249 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
251 } else if (executedInsn instanceof INVOKEINTERFACE) {
252 // Handle the read/write accesses that occur through iterators
253 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
255 // Analyze conflicts from next instructions
256 if (nextInsn instanceof JVMFieldInstruction) {
257 // Skip the constructor because it is called once and does not have shared access with other objects
258 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
259 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
260 if (!isFieldExcluded(fieldClass)) {
261 // Check for conflict (go backward from current choice and get the first conflict)
262 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
263 // Check for conflicts with Write fields for both Read and Write instructions
264 // Check and record a backtrack set for just once!
265 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
266 isNewConflict(currentChoice, eventCounter)) {
267 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
268 if (vm.isNewState() || isReachableInVODGraph(currentChoice, vm)) {
269 createBacktrackingPoint(currentChoice, eventCounter);
286 // This class compactly stores Read and Write field sets
287 // We store the field name and its object ID
288 // Sharing the same field means the same field name and object ID
289 private class ReadWriteSet {
290 private HashMap<String, Integer> readSet;
291 private HashMap<String, Integer> writeSet;
293 public ReadWriteSet() {
294 readSet = new HashMap<>();
295 writeSet = new HashMap<>();
298 public void addReadField(String field, int objectId) {
299 readSet.put(field, objectId);
302 public void addWriteField(String field, int objectId) {
303 writeSet.put(field, objectId);
306 public boolean readFieldExists(String field) {
307 return readSet.containsKey(field);
310 public boolean writeFieldExists(String field) {
311 return writeSet.containsKey(field);
314 public int readFieldObjectId(String field) {
315 return readSet.get(field);
318 public int writeFieldObjectId(String field) {
319 return writeSet.get(field);
323 // This class compactly stores backtrack points: 1) backtrack state ID, and 2) backtracking choices
324 private class BacktrackPoint {
325 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
326 private int stateId; // State at this backtrack point
327 private int choice; // Choice chosen at this backtrack point
329 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
335 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
337 public int getStateId() {
341 public int getChoice() {
347 private final static String DO_CALL_METHOD = "doCall";
348 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
349 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
350 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
351 // Groovy library created fields
352 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
354 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
355 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
356 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
357 // Java and Groovy libraries
358 { "java", "org", "sun", "com", "gov", "groovy"};
359 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
360 private final static String GET_PROPERTY_METHOD =
361 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
362 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
363 private final static String JAVA_INTEGER = "int";
364 private final static String JAVA_STRING_LIB = "java.lang.String";
367 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
368 // Check the next choice and if the value is not the same as the expected then force the expected value
369 int choiceIndex = choiceCounter % refChoices.length;
370 int nextChoice = icsCG.getNextChoice();
371 if (refChoices[choiceIndex] != nextChoice) {
372 int expectedChoice = refChoices[choiceIndex];
373 int currCGIndex = icsCG.getNextChoiceIndex();
374 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
375 icsCG.setChoice(currCGIndex, expectedChoice);
378 // Update current choice
379 currChoiceValue = refChoices[choiceIndex];
380 // Record state ID and choice/event as backtrack point
381 int stateId = vm.getStateId();
382 backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
383 // Store restorable state object for this state (always store the latest)
384 RestorableVMState restorableState = vm.getRestorableState();
385 restorableStateMap.put(stateId, restorableState);
388 private Integer[] copyChoices(Integer[] choicesToCopy) {
390 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
391 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
392 return copyOfChoices;
395 // --- Functions related to cycle detection
397 // Detect cycles in the current execution/trace
398 // We terminate the execution iff:
399 // (1) the state has been visited in the current execution
400 // (2) the state has one or more cycles that involve all the events
401 // With simple approach we only need to check for a re-visited state.
402 // Basically, we have to check that we have executed all events between two occurrences of such state.
403 private boolean containsCyclesWithAllEvents(int stId) {
405 // False if the state ID hasn't been recorded
406 if (!stateToEventMap.containsKey(stId)) {
409 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
410 // Check if this set contains all the event choices
411 // If not then this is not the terminating condition
412 for(int i=0; i<=maxEventChoice; i++) {
413 if (!visitedEvents.contains(i)) {
420 private void initializeStatesVariables() {
427 currVisitedStates = new HashSet<>();
428 justVisitedStates = new HashSet<>();
429 prevVisitedStates = new HashSet<>();
430 stateToEventMap = new HashMap<>();
432 backtrackMap = new HashMap<>();
433 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
434 backtrackPointList = new ArrayList<>();
435 conflictPairMap = new HashMap<>();
436 doneBacktrackSet = new HashSet<>();
437 newStateEventMap = new HashMap<>();
438 readWriteFieldsMap = new HashMap<>();
441 prevChoiceValue = -1;
442 vodGraphMap = new HashMap<>();
444 isEndOfExecution = false;
447 private void mapStateToEvent(int nextChoiceValue) {
448 // Update all states with this event/choice
449 // This means that all past states now see this transition
450 Set<Integer> stateSet = stateToEventMap.keySet();
451 for(Integer stateId : stateSet) {
452 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
453 eventSet.add(nextChoiceValue);
457 private boolean terminateCurrentExecution() {
458 // We need to check all the states that have just been visited
459 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
460 for(Integer stateId : justVisitedStates) {
461 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
468 private void updateStateInfo(Search search) {
469 // Update the state variables
470 // Line 19 in the paper page 11 (see the heading note above)
471 int stateId = search.getStateId();
472 currVisitedStates.add(stateId);
473 // Insert state ID into the map if it is new
474 if (!stateToEventMap.containsKey(stateId)) {
475 HashSet<Integer> eventSet = new HashSet<>();
476 stateToEventMap.put(stateId, eventSet);
478 justVisitedStates.add(stateId);
479 // Update the VOD graph when there is a new state
480 updateVODGraph(search.getVM());
483 // --- Functions related to Read/Write access analysis on shared fields
485 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
486 // Insert backtrack point to the right state ID
487 LinkedList<Integer[]> backtrackList;
488 if (backtrackMap.containsKey(stateId)) {
489 backtrackList = backtrackMap.get(stateId);
491 backtrackList = new LinkedList<>();
492 backtrackMap.put(stateId, backtrackList);
494 backtrackList.addFirst(newChoiceList);
495 // Add to priority queue
496 if (!backtrackStateQ.contains(stateId)) {
497 backtrackStateQ.add(stateId);
501 // Analyze Read/Write accesses that are directly invoked on fields
502 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
503 // Do the analysis to get Read and Write accesses to fields
504 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
505 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
506 // Record the field in the map
507 if (executedInsn instanceof WriteInstruction) {
508 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
509 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
510 if (fieldClass.startsWith(str)) {
514 rwSet.addWriteField(fieldClass, objectId);
515 } else if (executedInsn instanceof ReadInstruction) {
516 rwSet.addReadField(fieldClass, objectId);
520 // Analyze Read accesses that are indirect (performed through iterators)
521 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
522 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
524 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
525 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
526 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
527 // Extract info from the stack frame
528 StackFrame frame = ti.getTopFrame();
529 int[] frameSlots = frame.getSlots();
530 // Get the Groovy callsite library at index 0
531 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
532 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
535 // Get the iterated object whose property is accessed
536 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
537 if (eiAccessObj == null) {
540 // We exclude library classes (they start with java, org, etc.) and some more
541 String objClassName = eiAccessObj.getClassInfo().getName();
542 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
543 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
546 // Extract fields from this object and put them into the read write
547 int numOfFields = eiAccessObj.getNumberOfFields();
548 for(int i=0; i<numOfFields; i++) {
549 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
550 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
551 String fieldClass = fieldInfo.getFullName();
552 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
553 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
554 // Record the field in the map
555 rwSet.addReadField(fieldClass, objectId);
561 private int checkAndAdjustChoice(int currentChoice, VM vm) {
562 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
563 // for certain method calls in the infrastructure, e.g., eventSince()
564 int currChoiceInd = currentChoice % refChoices.length;
565 int currChoiceFromCG = currChoiceInd;
566 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
567 // This is the main event CG
568 if (currentCG instanceof IntIntervalGenerator) {
569 // This is the interval CG used in device handlers
570 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
571 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
572 // Find the index of the event/choice in refChoices
573 for (int i = 0; i<refChoices.length; i++) {
574 if (actualEvtNum == refChoices[i]) {
575 currChoiceFromCG = i;
580 if (currChoiceInd != currChoiceFromCG) {
581 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
583 return currentChoice;
586 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
588 // Create a new list of choices for backtrack based on the current choice and conflicting event number
589 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
590 // for the original set {0, 1, 2, 3}
591 Integer[] newChoiceList = new Integer[refChoices.length];
592 // Put the conflicting event numbers first and reverse the order
593 int actualCurrCho = currentChoice % refChoices.length;
594 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
595 newChoiceList[0] = choices[actualCurrCho];
596 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
597 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
598 for (int i = 0, j = 2; i < refChoices.length; i++) {
599 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
600 newChoiceList[j] = refChoices[i];
604 // Get the backtrack CG for this backtrack point
605 int stateId = backtrackPointList.get(confEvtNum).getStateId();
606 // Check if this trace has been done starting from this state
607 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
610 addNewBacktrackPoint(stateId, newChoiceList);
613 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
614 for (String excludedField : excludedStrings) {
615 if (className.contains(excludedField)) {
622 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
623 for (String excludedField : excludedStrings) {
624 if (className.endsWith(excludedField)) {
631 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
632 for (String excludedField : excludedStrings) {
633 if (className.startsWith(excludedField)) {
640 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
642 // We can start exploring the next backtrack point after the current CG is advanced at least once
643 if (choiceCounter > 0) {
644 // Check if we are reaching the end of our execution: no more backtracking points to explore
645 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
646 if (!backtrackStateQ.isEmpty()) {
647 // Set done all the other backtrack points
648 for (BacktrackPoint backtrackPoint : backtrackPointList) {
649 backtrackPoint.getBacktrackCG().setDone();
651 // Reset the next backtrack point with the latest state
652 int hiStateId = backtrackStateQ.peek();
653 // Restore the state first if necessary
654 if (vm.getStateId() != hiStateId) {
655 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
656 vm.restoreState(restorableState);
658 // Set the backtrack CG
659 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
660 setBacktrackCG(hiStateId, backtrackCG);
662 // Set done this last CG (we save a few rounds)
665 // Save all the visited states when starting a new execution of trace
666 prevVisitedStates.addAll(currVisitedStates);
667 currVisitedStates.clear();
668 // This marks a transitional period to the new CG
669 isEndOfExecution = true;
673 private ReadWriteSet getReadWriteSet(int currentChoice) {
674 // Do the analysis to get Read and Write accesses to fields
676 // We already have an entry
677 if (readWriteFieldsMap.containsKey(currentChoice)) {
678 rwSet = readWriteFieldsMap.get(currentChoice);
679 } else { // We need to create a new entry
680 rwSet = new ReadWriteSet();
681 readWriteFieldsMap.put(currentChoice, rwSet);
686 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
688 int actualCurrCho = currentChoice % refChoices.length;
689 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
690 if (!readWriteFieldsMap.containsKey(eventCounter) ||
691 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
694 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
695 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
696 // Check for conflicts with Write fields for both Read and Write instructions
697 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
698 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
699 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
700 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
706 private boolean isFieldExcluded(String field) {
707 // Check against "starts-with", "ends-with", and "contains" list
708 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
709 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
710 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
717 private boolean isNewConflict(int currentEvent, int eventNumber) {
718 HashSet<Integer> conflictSet;
719 if (!conflictPairMap.containsKey(currentEvent)) {
720 conflictSet = new HashSet<>();
721 conflictPairMap.put(currentEvent, conflictSet);
723 conflictSet = conflictPairMap.get(currentEvent);
725 // If this conflict has been recorded before, we return false because
726 // we don't want to save this backtrack point twice
727 if (conflictSet.contains(eventNumber)) {
730 // If it hasn't been recorded, then do otherwise
731 conflictSet.add(eventNumber);
735 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
736 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
737 // TODO: THIS IS AN OPTIMIZATION!
738 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
739 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
740 // The second time this event 1 is explored, it will generate the same state as the first one
741 StringBuilder sb = new StringBuilder();
744 sb.append(choiceList[0]);
745 // Check if the trace has been constructed as a backtrack point for this state
746 if (doneBacktrackSet.contains(sb.toString())) {
749 doneBacktrackSet.add(sb.toString());
753 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
754 if (choices == null || choices != icsCG.getAllChoices()) {
755 // Reset state variables
757 choices = icsCG.getAllChoices();
758 refChoices = copyChoices(choices);
759 // Clearing data structures
760 conflictPairMap.clear();
761 readWriteFieldsMap.clear();
762 stateToEventMap.clear();
763 isEndOfExecution = false;
764 backtrackPointList.clear();
768 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
769 // Set a backtrack CG based on a state ID
770 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
771 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
772 backtrackCG.setStateId(stateId);
774 // Remove from the queue if we don't have more backtrack points for that state
775 if (backtrackChoices.isEmpty()) {
776 backtrackMap.remove(stateId);
777 backtrackStateQ.remove(stateId);
781 // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
783 // This method checks whether a choice/event (transition) is reachable from the choice/event that produces
784 // the state right before this state in the VOD graph
785 // We use a BFS algorithm for this purpose
786 private boolean isReachableInVODGraph(int currentChoice, VM vm) {
788 int choiceIndex = currentChoice % refChoices.length;
789 int currEvent = refChoices[choiceIndex];
791 int stateId = vm.getStateId(); // A state that has been seen
792 int prevEvent = newStateEventMap.get(stateId);
793 // Only start traversing the graph if prevEvent has an outgoing edge
794 if (vodGraphMap.containsKey(prevEvent)) {
795 // Record visited choices as we search in the graph
796 HashSet<Integer> visitedChoice = new HashSet<>();
797 visitedChoice.add(prevEvent);
798 // Get the first nodes to visit (the neighbors of prevEvent)
799 LinkedList<Integer> nodesToVisit = new LinkedList<>();
800 nodesToVisit.addAll(vodGraphMap.get(prevEvent));
801 // Traverse the graph using BFS
802 while (!nodesToVisit.isEmpty()) {
803 int choice = nodesToVisit.removeFirst();
804 if (choice == currEvent) {
807 if (visitedChoice.contains(choice)) { // If there is a loop then just continue the exploration
810 // Continue searching
811 visitedChoice.add(choice);
812 HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
813 if (choiceNextNodes != null) {
814 // Add only if there is a mapping for next nodes
815 for (Integer nextNode : choiceNextNodes) {
817 if (nextNode == choice) {
820 nodesToVisit.addLast(nextNode);
828 private void updateVODGraph(VM vm) {
829 // Do this only if it is a new state
830 if (vm.isNewState()) {
831 // Update the graph when we have the current choice value
832 HashSet<Integer> choiceSet;
833 if (vodGraphMap.containsKey(prevChoiceValue)) {
834 // If the key already exists, just retrieve it
835 choiceSet = vodGraphMap.get(prevChoiceValue);
837 // Create a new entry
838 choiceSet = new HashSet<>();
839 vodGraphMap.put(prevChoiceValue, choiceSet);
841 choiceSet.add(currChoiceValue);
842 prevChoiceValue = currChoiceValue;
843 // Map this state ID to the event (transition) that produces it
844 newStateEventMap.put(vm.getStateId(), currChoiceValue);