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 have a graph G
43 * (i.e., visible operation dependency graph).
44 * This DPOR implementation actually fixes the algorithm in the SPIN paper that does not
45 * consider cases where a state could be matched early. In this new algorithm/implementation,
46 * each run is terminated iff:
47 * - we find a state that matches a state in a previous run, or
48 * - we have a matched state in the current run that consists of cycles that contain all choices/events.
50 public class DPORStateReducer extends ListenerAdapter {
52 // Information printout fields for verbose mode
53 private boolean verboseMode;
54 private boolean stateReductionMode;
55 private final PrintWriter out;
56 private String detail;
59 private Transition transition;
61 // DPOR-related fields
63 private Integer[] choices;
64 private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
65 private int choiceCounter;
66 private int maxEventChoice;
67 // Data structure to track the events seen by each state to track cycles (containing all events) for termination
68 private HashSet<Integer> currVisitedStates; // States being visited in the current execution
69 private HashSet<Integer> justVisitedStates; // States just visited in the previous choice/event
70 private HashSet<Integer> prevVisitedStates; // States visited in the previous execution
71 private HashMap<Integer, HashSet<Integer>> stateToEventMap;
72 // Data structure to analyze field Read/Write accesses and conflicts
73 private HashMap<Integer, LinkedList<Integer[]>> backtrackMap; // Track created backtracking points
74 private PriorityQueue<Integer> backtrackStateQ; // Heap that returns the latest state
75 private ArrayList<BacktrackPoint> backtrackPointList; // Record backtrack points (CG, state Id, and choice)
76 private HashMap<Integer, HashSet<Integer>> conflictPairMap; // Record conflicting events
77 private HashSet<String> doneBacktrackSet; // Record state ID and trace already constructed
78 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap; // Record fields that are accessed
79 private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
80 private HashMap<Integer, Integer> stateToChoiceCounterMap; // Maps state IDs to the choice counter
83 private boolean isBooleanCGFlipped;
84 private boolean isEndOfExecution;
87 private int numOfConflicts;
88 private int numOfTransitions;
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;
100 numOfTransitions = 0;
101 restorableStateMap = new HashMap<>();
102 initializeStatesVariables();
106 public void stateRestored(Search search) {
108 id = search.getStateId();
109 depth = search.getDepth();
110 transition = search.getTransition();
112 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
113 " and depth: " + depth + "\n");
118 public void searchStarted(Search search) {
120 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
125 public void stateAdvanced(Search search) {
127 id = search.getStateId();
128 depth = search.getDepth();
129 transition = search.getTransition();
130 if (search.isNewState()) {
136 if (search.isEndState()) {
137 out.println("\n==> DEBUG: This is the last state!\n");
140 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
141 " which is " + detail + " Transition: " + transition + "\n");
143 if (stateReductionMode) {
144 updateStateInfo(search);
149 public void stateBacktracked(Search search) {
151 id = search.getStateId();
152 depth = search.getDepth();
153 transition = search.getTransition();
156 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
157 " and depth: " + depth + "\n");
159 if (stateReductionMode) {
160 updateStateInfo(search);
165 public void searchFinished(Search search) {
166 if (stateReductionMode) {
167 // Number of conflicts = first trace + subsequent backtrack points
168 numOfConflicts += 1 + doneBacktrackSet.size();
171 out.println("\n==> DEBUG: ----------------------------------- search finished");
172 out.println("\n==> DEBUG: State reduction mode : " + stateReductionMode);
173 out.println("\n==> DEBUG: Number of conflicts : " + numOfConflicts);
174 out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
175 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
180 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
181 if (stateReductionMode) {
182 // Initialize with necessary information from the CG
183 if (nextCG instanceof IntChoiceFromSet) {
184 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
185 if (!isEndOfExecution) {
186 // Check if CG has been initialized, otherwise initialize it
187 Integer[] cgChoices = icsCG.getAllChoices();
188 // Record the events (from choices)
189 if (choices == null) {
191 // Make a copy of choices as reference
192 refChoices = copyChoices(choices);
193 // Record the max event choice (the last element of the choice array)
194 maxEventChoice = choices[choices.length - 1];
196 icsCG.setNewValues(choices);
198 // Use a modulo since choiceCounter is going to keep increasing
199 int choiceIndex = choiceCounter % choices.length;
200 icsCG.advance(choices[choiceIndex]);
202 // Set done all CGs while transitioning to a new execution
210 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
212 if (stateReductionMode) {
213 // Check the boolean CG and if it is flipped, we are resetting the analysis
214 if (currentCG instanceof BooleanChoiceGenerator) {
215 if (!isBooleanCGFlipped) {
216 isBooleanCGFlipped = true;
218 // Number of conflicts = first trace + subsequent backtrack points
219 numOfConflicts = 1 + doneBacktrackSet.size();
220 // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
221 initializeStatesVariables();
224 // Check every choice generated and ensure fair scheduling!
225 if (currentCG instanceof IntChoiceFromSet) {
226 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
227 // If this is a new CG then we need to update data structures
228 resetStatesForNewExecution(icsCG, vm);
229 // If we don't see a fair scheduling of events/choices then we have to enforce it
230 fairSchedulingAndBacktrackPoint(icsCG, vm);
231 // Map state to event
232 mapStateToEvent(icsCG.getNextChoice());
233 // Explore the next backtrack point:
234 // 1) if we have seen this state or this state contains cycles that involve all events, and
235 // 2) after the current CG is advanced at least once
236 if (terminateCurrentExecution() && choiceCounter > 0) {
237 exploreNextBacktrackPoints(vm, icsCG);
241 justVisitedStates.clear();
250 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
251 if (stateReductionMode) {
252 if (!isEndOfExecution) {
253 // Has to be initialized and a integer CG
254 ChoiceGenerator<?> cg = vm.getChoiceGenerator();
255 if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
256 int currentChoice = choiceCounter - 1; // Accumulative choice w.r.t the current trace
257 if (currentChoice < 0) { // If choice is -1 then skip
260 currentChoice = checkAndAdjustChoice(currentChoice, vm);
261 // Record accesses from executed instructions
262 if (executedInsn instanceof JVMFieldInstruction) {
263 // Analyze only after being initialized
264 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
265 // We don't care about libraries
266 if (!isFieldExcluded(fieldClass)) {
267 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
269 } else if (executedInsn instanceof INVOKEINTERFACE) {
270 // Handle the read/write accesses that occur through iterators
271 analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
273 // Analyze conflicts from next instructions
274 if (nextInsn instanceof JVMFieldInstruction) {
275 // Skip the constructor because it is called once and does not have shared access with other objects
276 if (!nextInsn.getMethodInfo().getName().equals("<init>")) {
277 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
278 if (!isFieldExcluded(fieldClass)) {
279 // Check for conflict (go backward from current choice and get the first conflict)
280 for (int eventCounter = currentChoice - 1; eventCounter >= 0; eventCounter--) {
281 // Check for conflicts with Write fields for both Read and Write instructions
282 // Check and record a backtrack set for just once!
283 if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
284 isNewConflict(currentChoice, eventCounter)) {
285 createBacktrackingPoint(currentChoice, eventCounter);
301 // This class compactly stores Read and Write field sets
302 // We store the field name and its object ID
303 // Sharing the same field means the same field name and object ID
304 private class ReadWriteSet {
305 private HashMap<String, Integer> readSet;
306 private HashMap<String, Integer> writeSet;
308 public ReadWriteSet() {
309 readSet = new HashMap<>();
310 writeSet = new HashMap<>();
313 public void addReadField(String field, int objectId) {
314 readSet.put(field, objectId);
317 public void addWriteField(String field, int objectId) {
318 writeSet.put(field, objectId);
321 public Set<String> getReadSet() {
322 return readSet.keySet();
325 public Set<String> getWriteSet() {
326 return writeSet.keySet();
329 public boolean readFieldExists(String field) {
330 return readSet.containsKey(field);
333 public boolean writeFieldExists(String field) {
334 return writeSet.containsKey(field);
337 public int readFieldObjectId(String field) {
338 return readSet.get(field);
341 public int writeFieldObjectId(String field) {
342 return writeSet.get(field);
346 // This class compactly stores backtrack points: 1) backtrack state ID, and 2) backtracking choices
347 private class BacktrackPoint {
348 private IntChoiceFromSet backtrackCG; // CG at this backtrack point
349 private int stateId; // State at this backtrack point
350 private int choice; // Choice chosen at this backtrack point
352 public BacktrackPoint(IntChoiceFromSet cg, int stId, int cho) {
358 public IntChoiceFromSet getBacktrackCG() { return backtrackCG; }
360 public int getStateId() {
364 public int getChoice() {
370 private final static String DO_CALL_METHOD = "doCall";
371 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
372 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
373 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
374 // Groovy library created fields
375 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
377 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
378 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
379 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
380 // Java and Groovy libraries
381 { "java", "org", "sun", "com", "gov", "groovy"};
382 private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
383 private final static String GET_PROPERTY_METHOD =
384 "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
385 private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
386 private final static String JAVA_INTEGER = "int";
387 private final static String JAVA_STRING_LIB = "java.lang.String";
390 private void fairSchedulingAndBacktrackPoint(IntChoiceFromSet icsCG, VM vm) {
391 // Check the next choice and if the value is not the same as the expected then force the expected value
392 int choiceIndex = choiceCounter % refChoices.length;
393 int nextChoice = icsCG.getNextChoice();
394 if (refChoices[choiceIndex] != nextChoice) {
395 int expectedChoice = refChoices[choiceIndex];
396 int currCGIndex = icsCG.getNextChoiceIndex();
397 if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
398 icsCG.setChoice(currCGIndex, expectedChoice);
401 // Record state ID and choice/event as backtrack point
402 int stateId = vm.getStateId();
403 backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
404 // Store restorable state object for this state (always store the latest)
405 RestorableVMState restorableState = vm.getRestorableState();
406 restorableStateMap.put(stateId, restorableState);
407 // Map multiple state IDs to a choice counter
408 for (Integer stId : justVisitedStates) {
409 stateToChoiceCounterMap.put(stId, choiceCounter);
413 private Integer[] copyChoices(Integer[] choicesToCopy) {
415 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
416 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
417 return copyOfChoices;
420 // --- Functions related to cycle detection
422 // Detect cycles in the current execution/trace
423 // We terminate the execution iff:
424 // (1) the state has been visited in the current execution
425 // (2) the state has one or more cycles that involve all the events
426 // With simple approach we only need to check for a re-visited state.
427 // Basically, we have to check that we have executed all events between two occurrences of such state.
428 private boolean containsCyclesWithAllEvents(int stId) {
430 // False if the state ID hasn't been recorded
431 if (!stateToEventMap.containsKey(stId)) {
434 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
435 // Check if this set contains all the event choices
436 // If not then this is not the terminating condition
437 for(int i=0; i<=maxEventChoice; i++) {
438 if (!visitedEvents.contains(i)) {
445 private void initializeStatesVariables() {
452 currVisitedStates = new HashSet<>();
453 justVisitedStates = new HashSet<>();
454 prevVisitedStates = new HashSet<>();
455 stateToEventMap = new HashMap<>();
457 backtrackMap = new HashMap<>();
458 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
459 backtrackPointList = new ArrayList<>();
460 conflictPairMap = new HashMap<>();
461 doneBacktrackSet = new HashSet<>();
462 readWriteFieldsMap = new HashMap<>();
463 stateToChoiceCounterMap = new HashMap<>();
465 isEndOfExecution = false;
468 private void mapStateToEvent(int nextChoiceValue) {
469 // Update all states with this event/choice
470 // This means that all past states now see this transition
471 Set<Integer> stateSet = stateToEventMap.keySet();
472 for(Integer stateId : stateSet) {
473 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
474 eventSet.add(nextChoiceValue);
478 private boolean terminateCurrentExecution() {
479 // We need to check all the states that have just been visited
480 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
481 for(Integer stateId : justVisitedStates) {
482 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
489 private void updateStateInfo(Search search) {
490 // Update the state variables
491 // Line 19 in the paper page 11 (see the heading note above)
492 int stateId = search.getStateId();
493 currVisitedStates.add(stateId);
494 // Insert state ID into the map if it is new
495 if (!stateToEventMap.containsKey(stateId)) {
496 HashSet<Integer> eventSet = new HashSet<>();
497 stateToEventMap.put(stateId, eventSet);
499 justVisitedStates.add(stateId);
500 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
503 // --- Functions related to Read/Write access analysis on shared fields
505 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
506 // Insert backtrack point to the right state ID
507 LinkedList<Integer[]> backtrackList;
508 if (backtrackMap.containsKey(stateId)) {
509 backtrackList = backtrackMap.get(stateId);
511 backtrackList = new LinkedList<>();
512 backtrackMap.put(stateId, backtrackList);
514 backtrackList.addFirst(newChoiceList);
515 // Add to priority queue
516 if (!backtrackStateQ.contains(stateId)) {
517 backtrackStateQ.add(stateId);
521 // Analyze Read/Write accesses that are directly invoked on fields
522 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
523 // Do the analysis to get Read and Write accesses to fields
524 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
525 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
526 // Record the field in the map
527 if (executedInsn instanceof WriteInstruction) {
528 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
529 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
530 if (fieldClass.startsWith(str)) {
534 rwSet.addWriteField(fieldClass, objectId);
535 } else if (executedInsn instanceof ReadInstruction) {
536 rwSet.addReadField(fieldClass, objectId);
540 // Analyze Read accesses that are indirect (performed through iterators)
541 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
542 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
544 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
545 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
546 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
547 // Extract info from the stack frame
548 StackFrame frame = ti.getTopFrame();
549 int[] frameSlots = frame.getSlots();
550 // Get the Groovy callsite library at index 0
551 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
552 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
555 // Get the iterated object whose property is accessed
556 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
557 if (eiAccessObj == null) {
560 // We exclude library classes (they start with java, org, etc.) and some more
561 String objClassName = eiAccessObj.getClassInfo().getName();
562 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
563 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
566 // Extract fields from this object and put them into the read write
567 int numOfFields = eiAccessObj.getNumberOfFields();
568 for(int i=0; i<numOfFields; i++) {
569 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
570 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
571 String fieldClass = fieldInfo.getFullName();
572 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
573 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
574 // Record the field in the map
575 rwSet.addReadField(fieldClass, objectId);
581 private int checkAndAdjustChoice(int currentChoice, VM vm) {
582 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
583 // for certain method calls in the infrastructure, e.g., eventSince()
584 int currChoiceInd = currentChoice % refChoices.length;
585 int currChoiceFromCG = currChoiceInd;
586 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
587 // This is the main event CG
588 if (currentCG instanceof IntIntervalGenerator) {
589 // This is the interval CG used in device handlers
590 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
591 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
592 // Find the index of the event/choice in refChoices
593 for (int i = 0; i<refChoices.length; i++) {
594 if (actualEvtNum == refChoices[i]) {
595 currChoiceFromCG = i;
600 if (currChoiceInd != currChoiceFromCG) {
601 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
603 return currentChoice;
606 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
608 // Create a new list of choices for backtrack based on the current choice and conflicting event number
609 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
610 // for the original set {0, 1, 2, 3}
611 Integer[] newChoiceList = new Integer[refChoices.length];
612 // Put the conflicting event numbers first and reverse the order
613 int actualCurrCho = currentChoice % refChoices.length;
614 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
615 newChoiceList[0] = choices[actualCurrCho];
616 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
617 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
618 for (int i = 0, j = 2; i < refChoices.length; i++) {
619 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
620 newChoiceList[j] = refChoices[i];
624 // Get the backtrack CG for this backtrack point
625 int stateId = backtrackPointList.get(confEvtNum).getStateId();
626 // Check if this trace has been done starting from this state
627 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
630 addNewBacktrackPoint(stateId, newChoiceList);
633 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
634 for (String excludedField : excludedStrings) {
635 if (className.contains(excludedField)) {
642 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
643 for (String excludedField : excludedStrings) {
644 if (className.endsWith(excludedField)) {
651 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
652 for (String excludedField : excludedStrings) {
653 if (className.startsWith(excludedField)) {
660 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
662 // Check if we are reaching the end of our execution: no more backtracking points to explore
663 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
664 if (!backtrackStateQ.isEmpty()) {
665 // Set done all the other backtrack points
666 for (BacktrackPoint backtrackPoint : backtrackPointList) {
667 backtrackPoint.getBacktrackCG().setDone();
669 // Reset the next backtrack point with the latest state
670 int hiStateId = backtrackStateQ.peek();
671 // Restore the state first if necessary
672 if (vm.getStateId() != hiStateId) {
673 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
674 vm.restoreState(restorableState);
676 // Set the backtrack CG
677 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
678 setBacktrackCG(hiStateId, backtrackCG);
680 // Set done this last CG (we save a few rounds)
683 // Save all the visited states when starting a new execution of trace
684 prevVisitedStates.addAll(currVisitedStates);
685 currVisitedStates.clear();
686 // This marks a transitional period to the new CG
687 isEndOfExecution = true;
690 private ReadWriteSet getReadWriteSet(int currentChoice) {
691 // Do the analysis to get Read and Write accesses to fields
693 // We already have an entry
694 if (readWriteFieldsMap.containsKey(currentChoice)) {
695 rwSet = readWriteFieldsMap.get(currentChoice);
696 } else { // We need to create a new entry
697 rwSet = new ReadWriteSet();
698 readWriteFieldsMap.put(currentChoice, rwSet);
703 private boolean isConflictFound(int eventCounter, int currentChoice) {
705 int actualCurrCho = currentChoice % refChoices.length;
706 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
707 if (!readWriteFieldsMap.containsKey(eventCounter) ||
708 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
712 ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
713 // R/W set of choice/event that may have a potential conflict
714 ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
715 // Check for conflicts with Read and Write fields for Write instructions
716 Set<String> currWriteSet = currRWSet.getWriteSet();
717 for(String writeField : currWriteSet) {
718 int currObjId = currRWSet.writeFieldObjectId(writeField);
719 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
720 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
724 // Check for conflicts with Write fields for Read instructions
725 Set<String> currReadSet = currRWSet.getReadSet();
726 for(String readField : currReadSet) {
727 int currObjId = currRWSet.readFieldObjectId(readField);
728 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
732 // Return false if no conflict is found
736 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
738 int actualCurrCho = currentChoice % refChoices.length;
739 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
740 if (!readWriteFieldsMap.containsKey(eventCounter) ||
741 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
744 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
745 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
746 // Check for conflicts with Write fields for both Read and Write instructions
747 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
748 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
749 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
750 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
756 private boolean isFieldExcluded(String field) {
757 // Check against "starts-with", "ends-with", and "contains" list
758 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
759 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
760 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
767 private boolean isNewConflict(int currentEvent, int eventNumber) {
768 HashSet<Integer> conflictSet;
769 if (!conflictPairMap.containsKey(currentEvent)) {
770 conflictSet = new HashSet<>();
771 conflictPairMap.put(currentEvent, conflictSet);
773 conflictSet = conflictPairMap.get(currentEvent);
775 // If this conflict has been recorded before, we return false because
776 // we don't want to save this backtrack point twice
777 if (conflictSet.contains(eventNumber)) {
780 // If it hasn't been recorded, then do otherwise
781 conflictSet.add(eventNumber);
785 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
786 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
787 // TODO: THIS IS AN OPTIMIZATION!
788 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
789 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
790 // The second time this event 1 is explored, it will generate the same state as the first one
791 StringBuilder sb = new StringBuilder();
794 sb.append(choiceList[0]);
795 // Check if the trace has been constructed as a backtrack point for this state
796 if (doneBacktrackSet.contains(sb.toString())) {
799 doneBacktrackSet.add(sb.toString());
803 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
804 if (choices == null || choices != icsCG.getAllChoices()) {
805 // Reset state variables
807 choices = icsCG.getAllChoices();
808 refChoices = copyChoices(choices);
809 // Clearing data structures
810 conflictPairMap.clear();
811 readWriteFieldsMap.clear();
812 stateToEventMap.clear();
813 isEndOfExecution = false;
814 backtrackPointList.clear();
818 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
819 // Set a backtrack CG based on a state ID
820 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
821 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
822 backtrackCG.setStateId(stateId);
824 // Remove from the queue if we don't have more backtrack points for that state
825 if (backtrackChoices.isEmpty()) {
826 backtrackMap.remove(stateId);
827 backtrackStateQ.remove(stateId);
831 // --- Functions related to the reachability analysis when there is a state match
833 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
834 // 1) Whenever there is state match, there is a cycle of events
835 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
836 // 3) Then we create a new backtrack point for every new conflict
837 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
838 // Perform this analysis only when there is a state match and state > 0 (state 0 is for boolean CG)
839 if (!vm.isNewState() && (stateId > 0)) {
840 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
841 int conflictChoice = stateToChoiceCounterMap.get(stateId);
842 int currentChoice = choiceCounter - 1;
843 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
844 while (conflictChoice < currentChoice) {
845 for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
846 if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
847 createBacktrackingPoint(conflictChoice, eventCounter);