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;
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<IntChoiceFromSet> cgList; // Record CGs for backtracking points
75 private HashMap<Integer, IntChoiceFromSet> cgMap; // Maps state IDs to CGs
76 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
77 // private HashSet<IntChoiceFromSet> activeBacktrackCGs; // Record active backtrack CGs
78 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
80 // Visible operation dependency graph implementation (SPIN paper) related fields
81 private int prevChoiceValue;
82 private HashMap<Integer, HashSet<Integer>> vodGraphMap; // Visible operation dependency graph (VOD graph)
85 private boolean isBooleanCGFlipped;
86 private boolean isFirstResetDone;
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);
103 currVisitedStates = new HashSet<>();
104 justVisitedStates = new HashSet<>();
105 prevVisitedStates = new HashSet<>();
106 stateToEventMap = new HashMap<>();
108 backtrackMap = new HashMap<>();
109 backtrackStateQ = new PriorityQueue<>();
110 cgList = new ArrayList<>();
111 cgMap = new HashMap<>();
112 conflictPairMap = new HashMap<>();
113 // activeBacktrackCGs = new HashSet<>();
114 readWriteFieldsMap = new HashMap<>();
116 prevChoiceValue = -1;
117 vodGraphMap = new HashMap<>();
119 isBooleanCGFlipped = false;
120 isEndOfExecution = false;
121 isFirstResetDone = false;
125 public void stateRestored(Search search) {
127 id = search.getStateId();
128 depth = search.getDepth();
129 transition = search.getTransition();
131 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
132 " and depth: " + depth + "\n");
137 public void searchStarted(Search search) {
139 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
144 public void stateAdvanced(Search search) {
146 id = search.getStateId();
147 depth = search.getDepth();
148 transition = search.getTransition();
149 if (search.isNewState()) {
155 if (search.isEndState()) {
156 out.println("\n==> DEBUG: This is the last state!\n");
159 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
160 " which is " + detail + " Transition: " + transition + "\n");
162 if (stateReductionMode) {
163 updateStateInfo(search);
168 public void stateBacktracked(Search search) {
170 id = search.getStateId();
171 depth = search.getDepth();
172 transition = search.getTransition();
175 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
176 " and depth: " + depth + "\n");
178 if (stateReductionMode) {
179 updateStateInfo(search);
184 public void searchFinished(Search search) {
186 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
191 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
192 if (stateReductionMode) {
193 // Initialize with necessary information from the CG
194 if (nextCG instanceof IntChoiceFromSet) {
195 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
196 if (!isEndOfExecution) {
197 // Check if CG has been initialized, otherwise initialize it
198 Integer[] cgChoices = icsCG.getAllChoices();
199 // Record the events (from choices)
200 if (choices == null) {
202 // Make a copy of choices as reference
203 refChoices = copyChoices(choices);
204 // Record the max event choice (the last element of the choice array)
205 maxEventChoice = choices[choices.length - 1];
207 icsCG.setNewValues(choices);
209 // Use a modulo since choiceCounter is going to keep increasing
210 int choiceIndex = choiceCounter % choices.length;
211 icsCG.advance(choices[choiceIndex]);
212 // Index the ChoiceGenerator to set backtracking points
215 // Set done all CGs while transitioning to a new execution
223 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
225 if (stateReductionMode) {
226 // Check the boolean CG and if it is flipped, we are resetting the analysis
227 // if (currentCG instanceof BooleanChoiceGenerator) {
228 // if (!isBooleanCGFlipped) {
229 // isBooleanCGFlipped = true;
231 // initializeStateReduction();
234 // Check every choice generated and ensure fair scheduling!
235 if (currentCG instanceof IntChoiceFromSet) {
236 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
237 // If this is a new CG then we need to update data structures
238 resetStatesForNewExecution(icsCG);
239 // If we don't see a fair scheduling of events/choices then we have to enforce it
240 checkAndEnforceFairScheduling(icsCG);
241 // Map state to event
242 mapStateToEvent(icsCG.getNextChoice());
243 // Update the VOD graph always with the latest
244 updateVODGraph(icsCG.getNextChoice());
245 // Check if we have seen this state or this state contains cycles that involve all events
246 if (terminateCurrentExecution()) {
247 exploreNextBacktrackPoints(icsCG, vm);
249 justVisitedStates.clear();
256 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
257 if (stateReductionMode) {
258 if (!isEndOfExecution) {
259 // Has to be initialized and a integer CG
260 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
261 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
262 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
263 if (currentChoice < 0) { // If choice is -1 then skip
266 currentChoice = checkAndAdjustChoice(currentChoice, vm);
267 // Record accesses from executed instructions
268 if (executedInsn instanceof JVMFieldInstruction) {
269 // Analyze only after being initialized
270 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
271 // We don't care about libraries
272 if (!isFieldExcluded(fieldClass)) {
273 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
275 } else if (executedInsn instanceof INVOKEINTERFACE) {
276 // Handle the read/write accesses that occur through iterators
277 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
279 // Analyze conflicts from next instructions
280 if (nextInsn instanceof JVMFieldInstruction) {
281 // Skip the constructor because it is called once and does not have shared access with other objects
282 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
283 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
284 if (!isFieldExcluded(fieldClass)) {
285 // Check for conflict (go backward from current choice and get the first conflict)
286 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
287 // Check for conflicts with Write fields for both Read and Write instructions
288 // Check and record a backtrack set for just once!
289 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
290 isNewConflict(currentChoice, eventCounter)) {
291 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
292 if (vm.isNewState() || isReachableInVODGraph(currentChoice)) {
293 createBacktrackingPoint(currentChoice, eventCounter);
310 // This class compactly stores Read and Write field sets
311 // We store the field name and its object ID
312 // Sharing the same field means the same field name and object ID
313 private class ReadWriteSet {
314 private HashMap<String, Integer> readSet;
315 private HashMap<String, Integer> writeSet;
317 public ReadWriteSet() {
318 readSet = new HashMap<>();
319 writeSet = new HashMap<>();
322 public void addReadField(String field, int objectId) {
323 readSet.put(field, objectId);
326 public void addWriteField(String field, int objectId) {
327 writeSet.put(field, objectId);
330 public boolean readFieldExists(String field) {
331 return readSet.containsKey(field);
334 public boolean writeFieldExists(String field) {
335 return writeSet.containsKey(field);
338 public int readFieldObjectId(String field) {
339 return readSet.get(field);
342 public int writeFieldObjectId(String field) {
343 return writeSet.get(field);
347 // This class compactly stores backtracking points: 1) backtracking ChoiceGenerator, and 2) backtracking choices
348 private class BacktrackPoint {
349 private IntChoiceFromSet backtrackCG; // CG to backtrack from
350 private Integer[] backtrackChoices; // Choices to set for this backtrack CG
352 public BacktrackPoint(IntChoiceFromSet cg, Integer[] choices) {
354 backtrackChoices = choices;
357 public IntChoiceFromSet getBacktrackCG() {
361 public Integer[] getBacktrackChoices() {
362 return backtrackChoices;
367 private final static String DO_CALL_METHOD = "doCall";
368 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
369 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
370 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
371 // Groovy library created fields
372 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
374 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
375 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
376 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
377 // Java and Groovy libraries
378 { "java", "org", "sun", "com", "gov", "groovy"};
379 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
380 private final static String GET_PROPERTY_METHOD =
381 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
382 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
383 private final static String JAVA_INTEGER = "int";
384 private final static String JAVA_STRING_LIB = "java.lang.String";
387 private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
388 // Check the next choice and if the value is not the same as the expected then force the expected value
389 int choiceIndex = choiceCounter % refChoices.length;
390 int nextChoice = icsCG.getNextChoice();
391 if (refChoices[choiceIndex] != nextChoice) {
392 int expectedChoice = refChoices[choiceIndex];
393 int currCGIndex = icsCG.getNextChoiceIndex();
394 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
395 icsCG.setChoice(currCGIndex, expectedChoice);
400 private Integer[] copyChoices(Integer[] choicesToCopy) {
402 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
403 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
404 return copyOfChoices;
407 // --- Functions related to cycle detection
409 // Detect cycles in the current execution/trace
410 // We terminate the execution iff:
411 // (1) the state has been visited in the current execution
412 // (2) the state has one or more cycles that involve all the events
413 // With simple approach we only need to check for a re-visited state.
414 // Basically, we have to check that we have executed all events between two occurrences of such state.
415 private boolean containsCyclesWithAllEvents(int stId) {
417 // False if the state ID hasn't been recorded
418 if (!stateToEventMap.containsKey(stId)) {
421 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
422 // Check if this set contains all the event choices
423 // If not then this is not the terminating condition
424 for(int i=0; i<=maxEventChoice; i++) {
425 if (!visitedEvents.contains(i)) {
432 private void mapStateToEvent(int nextChoiceValue) {
433 // Update all states with this event/choice
434 // This means that all past states now see this transition
435 Set<Integer> stateSet = stateToEventMap.keySet();
436 for(Integer stateId : stateSet) {
437 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
438 eventSet.add(nextChoiceValue);
442 private boolean terminateCurrentExecution() {
443 // We need to check all the states that have just been visited
444 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
445 for(Integer stateId : justVisitedStates) {
446 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
453 private void updateStateInfo(Search search) {
454 // Update the state variables
455 // Line 19 in the paper page 11 (see the heading note above)
456 int stateId = search.getStateId();
457 currVisitedStates.add(stateId);
458 // Insert state ID into the map if it is new
459 if (!stateToEventMap.containsKey(stateId)) {
460 HashSet<Integer> eventSet = new HashSet<>();
461 stateToEventMap.put(stateId, eventSet);
463 justVisitedStates.add(stateId);
466 // --- Functions related to Read/Write access analysis on shared fields
468 private void addNewBacktrackPoint(IntChoiceFromSet backtrackCG, Integer[] newChoiceList) {
469 int stateId = backtrackCG.getStateId();
470 // Insert backtrack point to the right state ID
471 LinkedList<Integer[]> backtrackList;
472 if (backtrackMap.containsKey(stateId)) {
473 backtrackList = backtrackMap.get(stateId);
475 backtrackList = new LinkedList<>();
477 backtrackList.addFirst(newChoiceList);
478 // Add CG for this state ID if there isn't one yet
479 if (!cgMap.containsKey(stateId)) {
480 cgMap.put(stateId, backtrackCG);
482 // Add to priority queue
483 if (!backtrackStateQ.contains(stateId)) {
484 backtrackStateQ.add(stateId);
488 // Analyze Read/Write accesses that are directly invoked on fields
489 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
490 // Do the analysis to get Read and Write accesses to fields
491 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
492 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
493 // Record the field in the map
494 if (executedInsn instanceof WriteInstruction) {
495 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
496 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
497 if (fieldClass.startsWith(str)) {
501 rwSet.addWriteField(fieldClass, objectId);
502 } else if (executedInsn instanceof ReadInstruction) {
503 rwSet.addReadField(fieldClass, objectId);
507 // Analyze Read accesses that are indirect (performed through iterators)
508 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
509 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
511 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
512 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
513 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
514 // Extract info from the stack frame
515 StackFrame frame = ti.getTopFrame();
516 int[] frameSlots = frame.getSlots();
517 // Get the Groovy callsite library at index 0
518 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
519 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
522 // Get the iterated object whose property is accessed
523 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
524 if (eiAccessObj == null) {
527 // We exclude library classes (they start with java, org, etc.) and some more
528 String objClassName = eiAccessObj.getClassInfo().getName();
529 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
530 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
533 // Extract fields from this object and put them into the read write
534 int numOfFields = eiAccessObj.getNumberOfFields();
535 for(int i=0; i<numOfFields; i++) {
536 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
537 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
538 String fieldClass = fieldInfo.getFullName();
539 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
540 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
541 // Record the field in the map
542 rwSet.addReadField(fieldClass, objectId);
548 private int checkAndAdjustChoice(int currentChoice, VM vm) {
549 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
550 // for certain method calls in the infrastructure, e.g., eventSince()
551 int currChoiceInd = currentChoice % refChoices.length;
552 int currChoiceFromCG = getCurrentChoice(vm);
553 if (currChoiceInd != currChoiceFromCG) {
554 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
556 return currentChoice;
559 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
561 // Create a new list of choices for backtrack based on the current choice and conflicting event number
562 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
563 // for the original set {0, 1, 2, 3}
564 Integer[] newChoiceList = new Integer[refChoices.length];
565 // Put the conflicting event numbers first and reverse the order
566 int actualCurrCho = currentChoice % refChoices.length;
567 int actualConfEvtNum = confEvtNum % refChoices.length;
568 newChoiceList[0] = refChoices[actualCurrCho];
569 newChoiceList[1] = refChoices[actualConfEvtNum];
570 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
571 for (int i = 0, j = 2; i < refChoices.length; i++) {
572 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
573 newChoiceList[j] = refChoices[i];
577 // Record the backtracking point in the stack as well
578 IntChoiceFromSet backtrackCG = cgList.get(confEvtNum);
579 //BacktrackPoint backtrackPoint = new BacktrackPoint(backtrackCG, newChoiceList);
580 addNewBacktrackPoint(backtrackCG, newChoiceList);
583 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
584 for (String excludedField : excludedStrings) {
585 if (className.contains(excludedField)) {
592 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
593 for (String excludedField : excludedStrings) {
594 if (className.endsWith(excludedField)) {
601 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
602 for (String excludedField : excludedStrings) {
603 if (className.startsWith(excludedField)) {
610 private void exploreNextBacktrackPoints(IntChoiceFromSet icsCG, VM vm) {
611 // We can start exploring the next backtrack point after the current CG is advanced at least once
612 if (icsCG.getNextChoiceIndex() > 0) {
613 if (backtrackMap.isEmpty()) {
614 // This means we are reaching the end of our execution: no more backtracking points to explore
617 setNextBacktrackPoint(icsCG);
618 // Save all the visited states when starting a new execution of trace
619 prevVisitedStates.addAll(currVisitedStates);
620 currVisitedStates.clear();
621 // This marks a transitional period to the new CG
622 isEndOfExecution = true;
626 private int getCurrentChoice(VM vm) {
627 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
628 // This is the main event CG
629 if (currentCG instanceof IntChoiceFromSet) {
630 return ((IntChoiceFromSet) currentCG).getNextChoiceIndex();
632 // This is the interval CG used in device handlers
633 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
634 return ((IntChoiceFromSet) parentCG).getNextChoiceIndex();
638 private ReadWriteSet getReadWriteSet(int currentChoice) {
639 // Do the analysis to get Read and Write accesses to fields
641 // We already have an entry
642 if (readWriteFieldsMap.containsKey(currentChoice)) {
643 rwSet = readWriteFieldsMap.get(currentChoice);
644 } else { // We need to create a new entry
645 rwSet = new ReadWriteSet();
646 readWriteFieldsMap.put(currentChoice, rwSet);
651 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
652 int actualEvtCntr = eventCounter % refChoices.length;
653 int actualCurrCho = currentChoice % refChoices.length;
654 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
655 if (!readWriteFieldsMap.containsKey(eventCounter) || (actualEvtCntr == actualCurrCho)) {
658 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
659 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
660 // Check for conflicts with Write fields for both Read and Write instructions
661 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
662 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
663 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
664 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
670 private boolean isFieldExcluded(String field) {
671 // Check against "starts-with", "ends-with", and "contains" list
672 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
673 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
674 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
681 private boolean isNewConflict(int currentEvent, int eventNumber) {
682 HashSet<Integer> conflictSet;
683 if (!conflictPairMap.containsKey(currentEvent)) {
684 conflictSet = new HashSet<>();
685 conflictPairMap.put(currentEvent, conflictSet);
687 conflictSet = conflictPairMap.get(currentEvent);
689 // If this conflict has been recorded before, we return false because
690 // we don't want to save this backtrack point twice
691 if (conflictSet.contains(eventNumber)) {
694 // If it hasn't been recorded, then do otherwise
695 conflictSet.add(eventNumber);
699 private void resetStatesForNewExecution(IntChoiceFromSet icsCG) {
700 if (choices == null || choices != icsCG.getAllChoices()) {
701 // Reset state variables
703 choices = icsCG.getAllChoices();
704 refChoices = copyChoices(choices);
705 // Clearing data structures
706 backtrackMap.clear();
707 conflictPairMap.clear();
708 readWriteFieldsMap.clear();
709 stateToEventMap.clear();
710 isEndOfExecution = false;
714 private IntChoiceFromSet setBacktrackCG(int stateId) {
715 // Set a backtrack CG based on a state ID
716 IntChoiceFromSet backtrackCG = cgMap.get(stateId);
717 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
718 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
720 // Remove from the queue if we don't have more backtrack points for that state
721 if (backtrackChoices.isEmpty()) {
722 cgMap.remove(stateId);
723 backtrackMap.remove(stateId);
724 backtrackStateQ.remove(stateId);
729 private void setNextBacktrackPoint(IntChoiceFromSet icsCG) {
731 HashSet<IntChoiceFromSet> backtrackCGs = new HashSet<>(cgMap.values());
732 if (!isFirstResetDone) {
733 // Reset the last CG of every LinkedList in the map and set done everything else
734 for (Integer stateId : cgMap.keySet()) {
735 setBacktrackCG(stateId);
737 // activeBacktrackCGs.addAll(cgMap.values());
738 isFirstResetDone = true;
740 // Check if we still have backtrack points for the current CG
741 int currStateId = icsCG.getStateId();
742 if (backtrackMap.containsKey(currStateId)) {
743 setBacktrackCG(currStateId);
745 // activeBacktrackCGs.remove(icsCG);
746 // We try to reset new CGs (if we do have) when we are running out of active CGs
747 if (!backtrackStateQ.isEmpty()) {
748 // Reset the next CG with the latest state
749 int hiStateId = backtrackStateQ.peek();
750 IntChoiceFromSet backtrackCG = setBacktrackCG(hiStateId);
751 // activeBacktrackCGs.add(backtrackCG);
756 for(IntChoiceFromSet cg : cgList) {
757 if (!backtrackCGs.contains(cg)) {
764 // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
766 // This method checks whether a choice is reachable in the VOD graph from a reference choice (BFS algorithm)
767 //private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
768 private boolean isReachableInVODGraph(int currentChoice) {
769 // Extract previous and current events
770 int choiceIndex = currentChoice % refChoices.length;
771 int currEvent = refChoices[choiceIndex];
772 int prevEvent = refChoices[choiceIndex - 1];
773 // Record visited choices as we search in the graph
774 HashSet<Integer> visitedChoice = new HashSet<>();
775 visitedChoice.add(prevEvent);
776 LinkedList<Integer> nodesToVisit = new LinkedList<>();
777 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
778 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
779 if (vodGraphMap.containsKey(prevEvent)) {
780 nodesToVisit.addAll(vodGraphMap.get(prevEvent));
781 while(!nodesToVisit.isEmpty()) {
782 int choice = nodesToVisit.getFirst();
783 if (choice == currEvent) {
786 if (visitedChoice.contains(choice)) { // If there is a loop then we don't find it
789 // Continue searching
790 visitedChoice.add(choice);
791 HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
792 if (choiceNextNodes != null) {
793 // Add only if there is a mapping for next nodes
794 for (Integer nextNode : choiceNextNodes) {
796 if (nextNode == choice) {
799 nodesToVisit.addLast(nextNode);
807 private void updateVODGraph(int currChoiceValue) {
808 // Update the graph when we have the current choice value
809 HashSet<Integer> choiceSet;
810 if (vodGraphMap.containsKey(prevChoiceValue)) {
811 // If the key already exists, just retrieve it
812 choiceSet = vodGraphMap.get(prevChoiceValue);
814 // Create a new entry
815 choiceSet = new HashSet<>();
816 vodGraphMap.put(prevChoiceValue, choiceSet);
818 choiceSet.add(currChoiceValue);
819 prevChoiceValue = currChoiceValue;