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 and choice)
75 private HashMap<Integer, IntChoiceFromSet> cgMap; // Maps state IDs to CGs
76 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
77 private HashSet<String> doneBacktrackSet; // Record state ID and trace that are done
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 isEndOfExecution;
88 public DPORStateReducer(Config config, JPF jpf) {
89 verboseMode = config.getBoolean("printout_state_transition", false);
90 stateReductionMode = config.getBoolean("activate_state_reduction", true);
92 out = new PrintWriter(System.out, true);
96 isBooleanCGFlipped = false;
97 initializeStatesVariables();
101 public void stateRestored(Search search) {
103 id = search.getStateId();
104 depth = search.getDepth();
105 transition = search.getTransition();
107 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
108 " and depth: " + depth + "\n");
113 public void searchStarted(Search search) {
115 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
120 public void stateAdvanced(Search search) {
122 id = search.getStateId();
123 depth = search.getDepth();
124 transition = search.getTransition();
125 if (search.isNewState()) {
131 if (search.isEndState()) {
132 out.println("\n==> DEBUG: This is the last state!\n");
135 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
136 " which is " + detail + " Transition: " + transition + "\n");
138 if (stateReductionMode) {
139 updateStateInfo(search);
144 public void stateBacktracked(Search search) {
146 id = search.getStateId();
147 depth = search.getDepth();
148 transition = search.getTransition();
151 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
152 " and depth: " + depth + "\n");
154 if (stateReductionMode) {
155 updateStateInfo(search);
160 public void searchFinished(Search search) {
162 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
167 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
168 if (stateReductionMode) {
169 // Initialize with necessary information from the CG
170 if (nextCG instanceof IntChoiceFromSet) {
171 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
172 if (!isEndOfExecution) {
173 // Check if CG has been initialized, otherwise initialize it
174 Integer[] cgChoices = icsCG.getAllChoices();
175 // Record the events (from choices)
176 if (choices == null) {
178 // Make a copy of choices as reference
179 refChoices = copyChoices(choices);
180 // Record the max event choice (the last element of the choice array)
181 maxEventChoice = choices[choices.length - 1];
183 icsCG.setNewValues(choices);
185 // Use a modulo since choiceCounter is going to keep increasing
186 int choiceIndex = choiceCounter % choices.length;
187 icsCG.advance(choices[choiceIndex]);
188 // Index the ChoiceGenerator to set backtracking points
189 BacktrackPoint backtrackPoint = new BacktrackPoint(icsCG, choices[choiceIndex]);
190 backtrackPointList.add(backtrackPoint);
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);
217 // If we don't see a fair scheduling of events/choices then we have to enforce it
218 checkAndEnforceFairScheduling(icsCG);
219 // Map state to event
220 mapStateToEvent(icsCG.getNextChoice());
221 // Update the VOD graph always with the latest
222 updateVODGraph(icsCG.getNextChoice());
223 // Check if we have seen this state or this state contains cycles that involve all events
224 if (terminateCurrentExecution()) {
225 exploreNextBacktrackPoints(icsCG);
227 justVisitedStates.clear();
234 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
235 if (stateReductionMode) {
236 if (!isEndOfExecution) {
237 // Has to be initialized and a integer CG
238 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
239 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
240 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
241 if (currentChoice < 0) { // If choice is -1 then skip
244 currentChoice = checkAndAdjustChoice(currentChoice, vm);
245 // Record accesses from executed instructions
246 if (executedInsn instanceof JVMFieldInstruction) {
247 // Analyze only after being initialized
248 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
249 // We don't care about libraries
250 if (!isFieldExcluded(fieldClass)) {
251 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
253 } else if (executedInsn instanceof INVOKEINTERFACE) {
254 // Handle the read/write accesses that occur through iterators
255 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
257 // Analyze conflicts from next instructions
258 if (nextInsn instanceof JVMFieldInstruction) {
259 // Skip the constructor because it is called once and does not have shared access with other objects
260 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
261 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
262 if (!isFieldExcluded(fieldClass)) {
263 // Check for conflict (go backward from current choice and get the first conflict)
264 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
265 // Check for conflicts with Write fields for both Read and Write instructions
266 // Check and record a backtrack set for just once!
267 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
268 isNewConflict(currentChoice, eventCounter)) {
269 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
270 if (vm.isNewState() || isReachableInVODGraph(currentChoice)) {
271 createBacktrackingPoint(currentChoice, eventCounter);
288 // This class compactly stores Read and Write field sets
289 // We store the field name and its object ID
290 // Sharing the same field means the same field name and object ID
291 private class ReadWriteSet {
292 private HashMap<String, Integer> readSet;
293 private HashMap<String, Integer> writeSet;
295 public ReadWriteSet() {
296 readSet = new HashMap<>();
297 writeSet = new HashMap<>();
300 public void addReadField(String field, int objectId) {
301 readSet.put(field, objectId);
304 public void addWriteField(String field, int objectId) {
305 writeSet.put(field, objectId);
308 public boolean readFieldExists(String field) {
309 return readSet.containsKey(field);
312 public boolean writeFieldExists(String field) {
313 return writeSet.containsKey(field);
316 public int readFieldObjectId(String field) {
317 return readSet.get(field);
320 public int writeFieldObjectId(String field) {
321 return writeSet.get(field);
325 // This class compactly stores backtracking points: 1) backtracking ChoiceGenerator, and 2) backtracking choices
326 private class BacktrackPoint {
327 private IntChoiceFromSet backtrackCG; // CG to backtrack from
328 private int choice; // Choice chosen at this backtrack point
330 public BacktrackPoint(IntChoiceFromSet cg, int cho) {
335 public IntChoiceFromSet getBacktrackCG() {
339 public int getChoice() {
345 private final static String DO_CALL_METHOD = "doCall";
346 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
347 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
348 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
349 // Groovy library created fields
350 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
352 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
353 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
354 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
355 // Java and Groovy libraries
356 { "java", "org", "sun", "com", "gov", "groovy"};
357 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
358 private final static String GET_PROPERTY_METHOD =
359 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
360 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
361 private final static String JAVA_INTEGER = "int";
362 private final static String JAVA_STRING_LIB = "java.lang.String";
365 private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
366 // Check the next choice and if the value is not the same as the expected then force the expected value
367 int choiceIndex = choiceCounter % refChoices.length;
368 int nextChoice = icsCG.getNextChoice();
369 if (refChoices[choiceIndex] != nextChoice) {
370 int expectedChoice = refChoices[choiceIndex];
371 int currCGIndex = icsCG.getNextChoiceIndex();
372 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
373 icsCG.setChoice(currCGIndex, expectedChoice);
378 private Integer[] copyChoices(Integer[] choicesToCopy) {
380 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
381 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
382 return copyOfChoices;
385 // --- Functions related to cycle detection
387 // Detect cycles in the current execution/trace
388 // We terminate the execution iff:
389 // (1) the state has been visited in the current execution
390 // (2) the state has one or more cycles that involve all the events
391 // With simple approach we only need to check for a re-visited state.
392 // Basically, we have to check that we have executed all events between two occurrences of such state.
393 private boolean containsCyclesWithAllEvents(int stId) {
395 // False if the state ID hasn't been recorded
396 if (!stateToEventMap.containsKey(stId)) {
399 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
400 // Check if this set contains all the event choices
401 // If not then this is not the terminating condition
402 for(int i=0; i<=maxEventChoice; i++) {
403 if (!visitedEvents.contains(i)) {
410 private void initializeStatesVariables() {
417 currVisitedStates = new HashSet<>();
418 justVisitedStates = new HashSet<>();
419 prevVisitedStates = new HashSet<>();
420 stateToEventMap = new HashMap<>();
422 backtrackMap = new HashMap<>();
423 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
424 backtrackPointList = new ArrayList<>();
425 cgMap = new HashMap<>();
426 conflictPairMap = new HashMap<>();
427 doneBacktrackSet = new HashSet<>();
428 readWriteFieldsMap = new HashMap<>();
430 prevChoiceValue = -1;
431 vodGraphMap = new HashMap<>();
433 isEndOfExecution = false;
436 private void mapStateToEvent(int nextChoiceValue) {
437 // Update all states with this event/choice
438 // This means that all past states now see this transition
439 Set<Integer> stateSet = stateToEventMap.keySet();
440 for(Integer stateId : stateSet) {
441 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
442 eventSet.add(nextChoiceValue);
446 private boolean terminateCurrentExecution() {
447 // We need to check all the states that have just been visited
448 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
449 for(Integer stateId : justVisitedStates) {
450 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
457 private void updateStateInfo(Search search) {
458 // Update the state variables
459 // Line 19 in the paper page 11 (see the heading note above)
460 int stateId = search.getStateId();
461 currVisitedStates.add(stateId);
462 // Insert state ID into the map if it is new
463 if (!stateToEventMap.containsKey(stateId)) {
464 HashSet<Integer> eventSet = new HashSet<>();
465 stateToEventMap.put(stateId, eventSet);
467 justVisitedStates.add(stateId);
470 // --- Functions related to Read/Write access analysis on shared fields
472 private void addNewBacktrackPoint(IntChoiceFromSet backtrackCG, Integer[] newChoiceList) {
473 int stateId = backtrackCG.getStateId();
474 // Insert backtrack point to the right state ID
475 LinkedList<Integer[]> backtrackList;
476 if (backtrackMap.containsKey(stateId)) {
477 backtrackList = backtrackMap.get(stateId);
479 backtrackList = new LinkedList<>();
480 backtrackMap.put(stateId, backtrackList);
482 backtrackList.addFirst(newChoiceList);
483 // Add CG for this state ID if there isn't one yet
484 if (!cgMap.containsKey(stateId)) {
485 cgMap.put(stateId, backtrackCG);
487 // Add to priority queue
488 if (!backtrackStateQ.contains(stateId)) {
489 backtrackStateQ.add(stateId);
493 // Analyze Read/Write accesses that are directly invoked on fields
494 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
495 // Do the analysis to get Read and Write accesses to fields
496 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
497 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
498 // Record the field in the map
499 if (executedInsn instanceof WriteInstruction) {
500 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
501 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
502 if (fieldClass.startsWith(str)) {
506 rwSet.addWriteField(fieldClass, objectId);
507 } else if (executedInsn instanceof ReadInstruction) {
508 rwSet.addReadField(fieldClass, objectId);
512 // Analyze Read accesses that are indirect (performed through iterators)
513 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
514 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
516 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
517 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
518 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
519 // Extract info from the stack frame
520 StackFrame frame = ti.getTopFrame();
521 int[] frameSlots = frame.getSlots();
522 // Get the Groovy callsite library at index 0
523 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
524 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
527 // Get the iterated object whose property is accessed
528 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
529 if (eiAccessObj == null) {
532 // We exclude library classes (they start with java, org, etc.) and some more
533 String objClassName = eiAccessObj.getClassInfo().getName();
534 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
535 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
538 // Extract fields from this object and put them into the read write
539 int numOfFields = eiAccessObj.getNumberOfFields();
540 for(int i=0; i<numOfFields; i++) {
541 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
542 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
543 String fieldClass = fieldInfo.getFullName();
544 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
545 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
546 // Record the field in the map
547 rwSet.addReadField(fieldClass, objectId);
553 private int checkAndAdjustChoice(int currentChoice, VM vm) {
554 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
555 // for certain method calls in the infrastructure, e.g., eventSince()
556 int currChoiceInd = currentChoice % refChoices.length;
557 int currChoiceFromCG = getCurrentChoice(vm);
558 if (currChoiceInd != currChoiceFromCG) {
559 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
561 return currentChoice;
564 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
566 // Create a new list of choices for backtrack based on the current choice and conflicting event number
567 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
568 // for the original set {0, 1, 2, 3}
569 Integer[] newChoiceList = new Integer[refChoices.length];
570 // Put the conflicting event numbers first and reverse the order
571 int actualCurrCho = currentChoice % refChoices.length;
572 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
573 newChoiceList[0] = choices[actualCurrCho];
574 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
575 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
576 for (int i = 0, j = 2; i < refChoices.length; i++) {
577 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
578 newChoiceList[j] = refChoices[i];
582 // Get the backtrack CG for this backtrack point
583 IntChoiceFromSet backtrackCG = backtrackPointList.get(confEvtNum).getBacktrackCG();
584 // Check if this trace has been done starting from this state
585 if (isTraceConstructed(newChoiceList, backtrackCG)) {
588 //BacktrackPoint backtrackPoint = new BacktrackPoint(backtrackCG, newChoiceList);
589 addNewBacktrackPoint(backtrackCG, newChoiceList);
592 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
593 for (String excludedField : excludedStrings) {
594 if (className.contains(excludedField)) {
601 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
602 for (String excludedField : excludedStrings) {
603 if (className.endsWith(excludedField)) {
610 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
611 for (String excludedField : excludedStrings) {
612 if (className.startsWith(excludedField)) {
619 private void exploreNextBacktrackPoints(IntChoiceFromSet icsCG) {
620 // We can start exploring the next backtrack point after the current CG is advanced at least once
621 if (icsCG.getNextChoiceIndex() > 0) {
622 HashSet<IntChoiceFromSet> backtrackCGs = new HashSet<>(cgMap.values());
623 // Check if we are reaching the end of our execution: no more backtracking points to explore
624 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
625 if (!backtrackStateQ.isEmpty()) {
626 // Reset the next CG with the latest state
627 int hiStateId = backtrackStateQ.peek();
628 // Check with the current state and if it's lower than the highest state, we defer to this lower state
629 int currStateId = icsCG.getStateId();
630 if (currStateId < hiStateId && cgMap.keySet().contains(currStateId)) {
631 hiStateId = currStateId;
633 setBacktrackCG(hiStateId, backtrackCGs);
636 for (BacktrackPoint backtrackPoint : backtrackPointList) {
637 IntChoiceFromSet cg = backtrackPoint.getBacktrackCG();
638 if (!backtrackCGs.contains(cg)) {
642 backtrackPointList.clear();
643 // Save all the visited states when starting a new execution of trace
644 prevVisitedStates.addAll(currVisitedStates);
645 currVisitedStates.clear();
646 // This marks a transitional period to the new CG
647 isEndOfExecution = true;
651 private int getCurrentChoice(VM vm) {
652 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
653 // This is the main event CG
654 if (currentCG instanceof IntChoiceFromSet) {
655 return ((IntChoiceFromSet) currentCG).getNextChoiceIndex();
657 // This is the interval CG used in device handlers
658 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
659 return ((IntChoiceFromSet) parentCG).getNextChoiceIndex();
663 private ReadWriteSet getReadWriteSet(int currentChoice) {
664 // Do the analysis to get Read and Write accesses to fields
666 // We already have an entry
667 if (readWriteFieldsMap.containsKey(currentChoice)) {
668 rwSet = readWriteFieldsMap.get(currentChoice);
669 } else { // We need to create a new entry
670 rwSet = new ReadWriteSet();
671 readWriteFieldsMap.put(currentChoice, rwSet);
676 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
678 int actualCurrCho = currentChoice % refChoices.length;
679 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
680 if (!readWriteFieldsMap.containsKey(eventCounter) ||
681 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
684 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
685 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
686 // Check for conflicts with Write fields for both Read and Write instructions
687 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
688 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
689 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
690 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
696 private boolean isFieldExcluded(String field) {
697 // Check against "starts-with", "ends-with", and "contains" list
698 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
699 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
700 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
707 private boolean isNewConflict(int currentEvent, int eventNumber) {
708 HashSet<Integer> conflictSet;
709 if (!conflictPairMap.containsKey(currentEvent)) {
710 conflictSet = new HashSet<>();
711 conflictPairMap.put(currentEvent, conflictSet);
713 conflictSet = conflictPairMap.get(currentEvent);
715 // If this conflict has been recorded before, we return false because
716 // we don't want to save this backtrack point twice
717 if (conflictSet.contains(eventNumber)) {
720 // If it hasn't been recorded, then do otherwise
721 conflictSet.add(eventNumber);
725 private boolean isTraceConstructed(Integer[] choiceList, IntChoiceFromSet backtrackCG) {
726 // Concatenate state ID and trace in a string, e.g., "1:10234"
727 int stateId = backtrackCG.getStateId();
728 StringBuilder sb = new StringBuilder();
731 for(Integer choice : choiceList) {
734 // Check if the trace has been constructed as a backtrack point for this state
735 if (doneBacktrackSet.contains(sb.toString())) {
738 doneBacktrackSet.add(sb.toString());
742 private void resetStatesForNewExecution(IntChoiceFromSet icsCG) {
743 if (choices == null || choices != icsCG.getAllChoices()) {
744 // Reset state variables
746 choices = icsCG.getAllChoices();
747 refChoices = copyChoices(choices);
748 // Clearing data structures
749 conflictPairMap.clear();
750 readWriteFieldsMap.clear();
751 stateToEventMap.clear();
752 isEndOfExecution = false;
753 // Adding this CG as the first backtrack point for this execution
754 backtrackPointList.add(new BacktrackPoint(icsCG, choices[0]));
758 private void setBacktrackCG(int stateId, HashSet<IntChoiceFromSet> backtrackCGs) {
759 // Set a backtrack CG based on a state ID
760 IntChoiceFromSet backtrackCG = cgMap.get(stateId);
761 // Need to reset the CGs first so that the CG last reset will be chosen next
762 for (IntChoiceFromSet cg : backtrackCGs) {
763 if (cg != backtrackCG && cg.getNextChoiceIndex() > -1) {
767 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
768 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
770 // Remove from the queue if we don't have more backtrack points for that state
771 if (backtrackChoices.isEmpty()) {
772 cgMap.remove(stateId);
773 backtrackMap.remove(stateId);
774 backtrackStateQ.remove(stateId);
778 // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
780 // This method checks whether a choice is reachable in the VOD graph from a reference choice (BFS algorithm)
781 //private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
782 private boolean isReachableInVODGraph(int currentChoice) {
783 // Extract previous and current events
784 int choiceIndex = currentChoice % refChoices.length;
785 int currEvent = refChoices[choiceIndex];
786 int prevEvent = refChoices[choiceIndex - 1];
787 // Record visited choices as we search in the graph
788 HashSet<Integer> visitedChoice = new HashSet<>();
789 visitedChoice.add(prevEvent);
790 LinkedList<Integer> nodesToVisit = new LinkedList<>();
791 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
792 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
793 if (vodGraphMap.containsKey(prevEvent)) {
794 nodesToVisit.addAll(vodGraphMap.get(prevEvent));
795 while(!nodesToVisit.isEmpty()) {
796 int choice = nodesToVisit.getFirst();
797 if (choice == currEvent) {
800 if (visitedChoice.contains(choice)) { // If there is a loop then we don't find it
803 // Continue searching
804 visitedChoice.add(choice);
805 HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
806 if (choiceNextNodes != null) {
807 // Add only if there is a mapping for next nodes
808 for (Integer nextNode : choiceNextNodes) {
810 if (nextNode == choice) {
813 nodesToVisit.addLast(nextNode);
821 private void updateVODGraph(int currChoiceValue) {
822 // Update the graph when we have the current choice value
823 HashSet<Integer> choiceSet;
824 if (vodGraphMap.containsKey(prevChoiceValue)) {
825 // If the key already exists, just retrieve it
826 choiceSet = vodGraphMap.get(prevChoiceValue);
828 // Create a new entry
829 choiceSet = new HashSet<>();
830 vodGraphMap.put(prevChoiceValue, choiceSet);
832 choiceSet.add(currChoiceValue);
833 prevChoiceValue = currChoiceValue;