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 lastCGStateId; // Record the state of the currently active CG
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<IntChoiceFromSet> cgList; // Record CGs for backtracking points
76 private HashMap<Integer, IntChoiceFromSet> cgMap; // Maps state IDs to CGs
77 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
78 private HashSet<String> doneBacktrackSet; // Record state ID and trace that are done
79 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
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 isFirstResetDone;
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 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]);
190 // Index the ChoiceGenerator to set backtracking points
193 // Set done all CGs while transitioning to a new execution
201 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
203 if (stateReductionMode) {
204 // Check the boolean CG and if it is flipped, we are resetting the analysis
205 if (currentCG instanceof BooleanChoiceGenerator) {
206 if (!isBooleanCGFlipped) {
207 isBooleanCGFlipped = true;
209 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
210 initializeStatesVariables();
213 // Check every choice generated and ensure fair scheduling!
214 if (currentCG instanceof IntChoiceFromSet) {
215 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
216 // If this is a new CG then we need to update data structures
217 resetStatesForNewExecution(icsCG);
218 // If we don't see a fair scheduling of events/choices then we have to enforce it
219 checkAndEnforceFairScheduling(icsCG);
220 // Map state to event
221 mapStateToEvent(icsCG.getNextChoice());
222 // Update the VOD graph always with the latest
223 updateVODGraph(icsCG.getNextChoice());
224 // Check if we have seen this state or this state contains cycles that involve all events
225 if (terminateCurrentExecution()) {
226 exploreNextBacktrackPoints(icsCG, vm);
228 justVisitedStates.clear();
235 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
236 if (stateReductionMode) {
237 if (!isEndOfExecution) {
238 // Has to be initialized and a integer CG
239 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
240 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
241 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
242 if (currentChoice < 0) { // If choice is -1 then skip
245 currentChoice = checkAndAdjustChoice(currentChoice, vm);
246 // Record accesses from executed instructions
247 if (executedInsn instanceof JVMFieldInstruction) {
248 // Analyze only after being initialized
249 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
250 // We don't care about libraries
251 if (!isFieldExcluded(fieldClass)) {
252 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
254 } else if (executedInsn instanceof INVOKEINTERFACE) {
255 // Handle the read/write accesses that occur through iterators
256 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
258 // Analyze conflicts from next instructions
259 if (nextInsn instanceof JVMFieldInstruction) {
260 // Skip the constructor because it is called once and does not have shared access with other objects
261 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
262 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
263 if (!isFieldExcluded(fieldClass)) {
264 // Check for conflict (go backward from current choice and get the first conflict)
265 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
266 // Check for conflicts with Write fields for both Read and Write instructions
267 // Check and record a backtrack set for just once!
268 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
269 isNewConflict(currentChoice, eventCounter)) {
270 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
271 if (vm.isNewState() || isReachableInVODGraph(currentChoice)) {
272 createBacktrackingPoint(currentChoice, eventCounter);
289 // This class compactly stores Read and Write field sets
290 // We store the field name and its object ID
291 // Sharing the same field means the same field name and object ID
292 private class ReadWriteSet {
293 private HashMap<String, Integer> readSet;
294 private HashMap<String, Integer> writeSet;
296 public ReadWriteSet() {
297 readSet = new HashMap<>();
298 writeSet = new HashMap<>();
301 public void addReadField(String field, int objectId) {
302 readSet.put(field, objectId);
305 public void addWriteField(String field, int objectId) {
306 writeSet.put(field, objectId);
309 public boolean readFieldExists(String field) {
310 return readSet.containsKey(field);
313 public boolean writeFieldExists(String field) {
314 return writeSet.containsKey(field);
317 public int readFieldObjectId(String field) {
318 return readSet.get(field);
321 public int writeFieldObjectId(String field) {
322 return writeSet.get(field);
326 // This class compactly stores backtracking points: 1) backtracking ChoiceGenerator, and 2) backtracking choices
327 private class BacktrackPoint {
328 private IntChoiceFromSet backtrackCG; // CG to backtrack from
329 private Integer[] backtrackChoices; // Choices to set for this backtrack CG
331 public BacktrackPoint(IntChoiceFromSet cg, Integer[] choices) {
333 backtrackChoices = choices;
336 public IntChoiceFromSet getBacktrackCG() {
340 public Integer[] getBacktrackChoices() {
341 return backtrackChoices;
346 private final static String DO_CALL_METHOD = "doCall";
347 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
348 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
349 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
350 // Groovy library created fields
351 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
353 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
354 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
355 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
356 // Java and Groovy libraries
357 { "java", "org", "sun", "com", "gov", "groovy"};
358 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
359 private final static String GET_PROPERTY_METHOD =
360 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
361 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
362 private final static String JAVA_INTEGER = "int";
363 private final static String JAVA_STRING_LIB = "java.lang.String";
366 private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
367 // Check the next choice and if the value is not the same as the expected then force the expected value
368 int choiceIndex = choiceCounter % refChoices.length;
369 int nextChoice = icsCG.getNextChoice();
370 if (refChoices[choiceIndex] != nextChoice) {
371 int expectedChoice = refChoices[choiceIndex];
372 int currCGIndex = icsCG.getNextChoiceIndex();
373 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
374 icsCG.setChoice(currCGIndex, expectedChoice);
379 private Integer[] copyChoices(Integer[] choicesToCopy) {
381 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
382 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
383 return copyOfChoices;
386 // --- Functions related to cycle detection
388 // Detect cycles in the current execution/trace
389 // We terminate the execution iff:
390 // (1) the state has been visited in the current execution
391 // (2) the state has one or more cycles that involve all the events
392 // With simple approach we only need to check for a re-visited state.
393 // Basically, we have to check that we have executed all events between two occurrences of such state.
394 private boolean containsCyclesWithAllEvents(int stId) {
396 // False if the state ID hasn't been recorded
397 if (!stateToEventMap.containsKey(stId)) {
400 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
401 // Check if this set contains all the event choices
402 // If not then this is not the terminating condition
403 for(int i=0; i<=maxEventChoice; i++) {
404 if (!visitedEvents.contains(i)) {
411 private void initializeStatesVariables() {
419 currVisitedStates = new HashSet<>();
420 justVisitedStates = new HashSet<>();
421 prevVisitedStates = new HashSet<>();
422 stateToEventMap = new HashMap<>();
424 backtrackMap = new HashMap<>();
425 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
426 cgList = new ArrayList<>();
427 cgMap = new HashMap<>();
428 conflictPairMap = new HashMap<>();
429 doneBacktrackSet = new HashSet<>();
430 readWriteFieldsMap = new HashMap<>();
432 prevChoiceValue = -1;
433 vodGraphMap = new HashMap<>();
435 isEndOfExecution = false;
436 isFirstResetDone = false;
439 private void mapStateToEvent(int nextChoiceValue) {
440 // Update all states with this event/choice
441 // This means that all past states now see this transition
442 Set<Integer> stateSet = stateToEventMap.keySet();
443 for(Integer stateId : stateSet) {
444 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
445 eventSet.add(nextChoiceValue);
449 private boolean terminateCurrentExecution() {
450 // We need to check all the states that have just been visited
451 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
452 for(Integer stateId : justVisitedStates) {
453 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
460 private void updateStateInfo(Search search) {
461 // Update the state variables
462 // Line 19 in the paper page 11 (see the heading note above)
463 int stateId = search.getStateId();
464 currVisitedStates.add(stateId);
465 // Insert state ID into the map if it is new
466 if (!stateToEventMap.containsKey(stateId)) {
467 HashSet<Integer> eventSet = new HashSet<>();
468 stateToEventMap.put(stateId, eventSet);
470 justVisitedStates.add(stateId);
473 // --- Functions related to Read/Write access analysis on shared fields
475 private void addNewBacktrackPoint(IntChoiceFromSet backtrackCG, Integer[] newChoiceList) {
476 int stateId = backtrackCG.getStateId();
477 // Insert backtrack point to the right state ID
478 LinkedList<Integer[]> backtrackList;
479 if (backtrackMap.containsKey(stateId)) {
480 backtrackList = backtrackMap.get(stateId);
482 backtrackList = new LinkedList<>();
483 backtrackMap.put(stateId, backtrackList);
485 backtrackList.addFirst(newChoiceList);
486 // Add CG for this state ID if there isn't one yet
487 if (!cgMap.containsKey(stateId)) {
488 cgMap.put(stateId, backtrackCG);
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 = getCurrentChoice(vm);
561 if (currChoiceInd != currChoiceFromCG) {
562 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
564 return currentChoice;
567 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
569 // Create a new list of choices for backtrack based on the current choice and conflicting event number
570 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
571 // for the original set {0, 1, 2, 3}
572 Integer[] newChoiceList = new Integer[refChoices.length];
573 // Put the conflicting event numbers first and reverse the order
574 int actualCurrCho = currentChoice % refChoices.length;
575 int actualConfEvtNum = confEvtNum % refChoices.length;
576 // We use the actual choices here in case they have been modified/adjusted
577 newChoiceList[0] = choices[actualCurrCho];
578 newChoiceList[1] = choices[actualConfEvtNum];
579 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
580 for (int i = 0, j = 2; i < refChoices.length; i++) {
581 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
582 newChoiceList[j] = refChoices[i];
586 // Record the backtracking point in the stack as well
587 IntChoiceFromSet backtrackCG = cgList.get(confEvtNum);
588 // Check if this trace has been done starting from this state
589 if (isTraceConstructed(newChoiceList, backtrackCG)) {
592 //BacktrackPoint backtrackPoint = new BacktrackPoint(backtrackCG, newChoiceList);
593 addNewBacktrackPoint(backtrackCG, newChoiceList);
596 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
597 for (String excludedField : excludedStrings) {
598 if (className.contains(excludedField)) {
605 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
606 for (String excludedField : excludedStrings) {
607 if (className.endsWith(excludedField)) {
614 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
615 for (String excludedField : excludedStrings) {
616 if (className.startsWith(excludedField)) {
623 private void exploreNextBacktrackPoints(IntChoiceFromSet icsCG, VM vm) {
624 // We can start exploring the next backtrack point after the current CG is advanced at least once
625 if (icsCG.getNextChoiceIndex() > 0) {
626 // Check if we are reaching the end of our execution: no more backtracking points to explore
627 if (!backtrackMap.isEmpty()) {
628 setNextBacktrackPoint(icsCG);
630 // Save all the visited states when starting a new execution of trace
631 prevVisitedStates.addAll(currVisitedStates);
632 currVisitedStates.clear();
633 // This marks a transitional period to the new CG
634 isEndOfExecution = true;
638 private int getCurrentChoice(VM vm) {
639 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
640 // This is the main event CG
641 if (currentCG instanceof IntChoiceFromSet) {
642 return ((IntChoiceFromSet) currentCG).getNextChoiceIndex();
644 // This is the interval CG used in device handlers
645 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
646 return ((IntChoiceFromSet) parentCG).getNextChoiceIndex();
650 private ReadWriteSet getReadWriteSet(int currentChoice) {
651 // Do the analysis to get Read and Write accesses to fields
653 // We already have an entry
654 if (readWriteFieldsMap.containsKey(currentChoice)) {
655 rwSet = readWriteFieldsMap.get(currentChoice);
656 } else { // We need to create a new entry
657 rwSet = new ReadWriteSet();
658 readWriteFieldsMap.put(currentChoice, rwSet);
663 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
664 int actualEvtCntr = eventCounter % refChoices.length;
665 int actualCurrCho = currentChoice % refChoices.length;
666 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
667 if (!readWriteFieldsMap.containsKey(eventCounter) || choices[actualCurrCho] == choices[actualEvtCntr]) {
670 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
671 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
672 // Check for conflicts with Write fields for both Read and Write instructions
673 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
674 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
675 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
676 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
682 private boolean isFieldExcluded(String field) {
683 // Check against "starts-with", "ends-with", and "contains" list
684 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
685 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
686 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
693 private boolean isNewConflict(int currentEvent, int eventNumber) {
694 HashSet<Integer> conflictSet;
695 if (!conflictPairMap.containsKey(currentEvent)) {
696 conflictSet = new HashSet<>();
697 conflictPairMap.put(currentEvent, conflictSet);
699 conflictSet = conflictPairMap.get(currentEvent);
701 // If this conflict has been recorded before, we return false because
702 // we don't want to save this backtrack point twice
703 if (conflictSet.contains(eventNumber)) {
706 // If it hasn't been recorded, then do otherwise
707 conflictSet.add(eventNumber);
711 private boolean isTraceConstructed(Integer[] choiceList, IntChoiceFromSet backtrackCG) {
712 // Concatenate state ID and trace in a string, e.g., "1:10234"
713 int stateId = backtrackCG.getStateId();
714 StringBuilder sb = new StringBuilder();
717 for(Integer choice : choiceList) {
720 // Check if the trace has been constructed as a backtrack point for this state
721 if (doneBacktrackSet.contains(sb.toString())) {
724 doneBacktrackSet.add(sb.toString());
728 private void resetStatesForNewExecution(IntChoiceFromSet icsCG) {
729 if (choices == null || choices != icsCG.getAllChoices()) {
730 // Reset state variables
732 choices = icsCG.getAllChoices();
733 refChoices = copyChoices(choices);
734 lastCGStateId = icsCG.getStateId();
735 // Clearing data structures
736 conflictPairMap.clear();
737 readWriteFieldsMap.clear();
738 stateToEventMap.clear();
739 isEndOfExecution = false;
740 // Adding this CG as the first CG for this execution
745 private void setBacktrackCG(int stateId) {
746 // Set a backtrack CG based on a state ID
747 IntChoiceFromSet backtrackCG = cgMap.get(stateId);
748 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
749 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
751 // Remove from the queue if we don't have more backtrack points for that state
752 if (backtrackChoices.isEmpty()) {
753 cgMap.remove(stateId);
754 backtrackMap.remove(stateId);
755 backtrackStateQ.remove(stateId);
759 private void setNextBacktrackPoint(IntChoiceFromSet icsCG) {
761 HashSet<IntChoiceFromSet> backtrackCGs = new HashSet<>(cgMap.values());
762 if (!isFirstResetDone) {
763 // Reset the last CG of every LinkedList in the map and set done everything else
764 for (Integer stateId : cgMap.keySet()) {
765 setBacktrackCG(stateId);
767 isFirstResetDone = true;
769 // Check if we still have backtrack points for the last state after the last backtrack
770 if (backtrackMap.containsKey(lastCGStateId)) {
771 setBacktrackCG(lastCGStateId);
773 // We try to reset new CGs (if we do have) when we are running out of active CGs
774 if (!backtrackStateQ.isEmpty()) {
775 // Reset the next CG with the latest state
776 int hiStateId = backtrackStateQ.peek();
777 setBacktrackCG(hiStateId);
782 for(IntChoiceFromSet cg : cgList) {
783 if (!backtrackCGs.contains(cg)) {
790 // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
792 // This method checks whether a choice is reachable in the VOD graph from a reference choice (BFS algorithm)
793 //private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
794 private boolean isReachableInVODGraph(int currentChoice) {
795 // Extract previous and current events
796 int choiceIndex = currentChoice % refChoices.length;
797 int currEvent = refChoices[choiceIndex];
798 int prevEvent = refChoices[choiceIndex - 1];
799 // Record visited choices as we search in the graph
800 HashSet<Integer> visitedChoice = new HashSet<>();
801 visitedChoice.add(prevEvent);
802 LinkedList<Integer> nodesToVisit = new LinkedList<>();
803 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
804 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
805 if (vodGraphMap.containsKey(prevEvent)) {
806 nodesToVisit.addAll(vodGraphMap.get(prevEvent));
807 while(!nodesToVisit.isEmpty()) {
808 int choice = nodesToVisit.getFirst();
809 if (choice == currEvent) {
812 if (visitedChoice.contains(choice)) { // If there is a loop then we don't find it
815 // Continue searching
816 visitedChoice.add(choice);
817 HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
818 if (choiceNextNodes != null) {
819 // Add only if there is a mapping for next nodes
820 for (Integer nextNode : choiceNextNodes) {
822 if (nextNode == choice) {
825 nodesToVisit.addLast(nextNode);
833 private void updateVODGraph(int currChoiceValue) {
834 // Update the graph when we have the current choice value
835 HashSet<Integer> choiceSet;
836 if (vodGraphMap.containsKey(prevChoiceValue)) {
837 // If the key already exists, just retrieve it
838 choiceSet = vodGraphMap.get(prevChoiceValue);
840 // Create a new entry
841 choiceSet = new HashSet<>();
842 vodGraphMap.put(prevChoiceValue, choiceSet);
844 choiceSet.add(currChoiceValue);
845 prevChoiceValue = currChoiceValue;