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);
409 private Integer[] copyChoices(Integer[] choicesToCopy) {
411 Integer[] copyOfChoices = new Integer[choicesToCopy.length];
412 System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
413 return copyOfChoices;
416 // --- Functions related to cycle detection
418 // Detect cycles in the current execution/trace
419 // We terminate the execution iff:
420 // (1) the state has been visited in the current execution
421 // (2) the state has one or more cycles that involve all the events
422 // With simple approach we only need to check for a re-visited state.
423 // Basically, we have to check that we have executed all events between two occurrences of such state.
424 private boolean containsCyclesWithAllEvents(int stId) {
426 // False if the state ID hasn't been recorded
427 if (!stateToEventMap.containsKey(stId)) {
430 HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
431 // Check if this set contains all the event choices
432 // If not then this is not the terminating condition
433 for(int i=0; i<=maxEventChoice; i++) {
434 if (!visitedEvents.contains(i)) {
441 private void initializeStatesVariables() {
448 currVisitedStates = new HashSet<>();
449 justVisitedStates = new HashSet<>();
450 prevVisitedStates = new HashSet<>();
451 stateToEventMap = new HashMap<>();
453 backtrackMap = new HashMap<>();
454 backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
455 backtrackPointList = new ArrayList<>();
456 conflictPairMap = new HashMap<>();
457 doneBacktrackSet = new HashSet<>();
458 readWriteFieldsMap = new HashMap<>();
459 stateToChoiceCounterMap = new HashMap<>();
461 isEndOfExecution = false;
464 private void mapStateToEvent(int nextChoiceValue) {
465 // Update all states with this event/choice
466 // This means that all past states now see this transition
467 Set<Integer> stateSet = stateToEventMap.keySet();
468 for(Integer stateId : stateSet) {
469 HashSet<Integer> eventSet = stateToEventMap.get(stateId);
470 eventSet.add(nextChoiceValue);
474 private boolean terminateCurrentExecution() {
475 // We need to check all the states that have just been visited
476 // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
477 for(Integer stateId : justVisitedStates) {
478 if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
485 private void updateStateInfo(Search search) {
486 // Update the state variables
487 // Line 19 in the paper page 11 (see the heading note above)
488 int stateId = search.getStateId();
489 // Insert state ID into the map if it is new
490 if (!stateToEventMap.containsKey(stateId)) {
491 HashSet<Integer> eventSet = new HashSet<>();
492 stateToEventMap.put(stateId, eventSet);
494 stateToChoiceCounterMap.put(stateId, choiceCounter);
495 analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
496 justVisitedStates.add(stateId);
497 currVisitedStates.add(stateId);
500 // --- Functions related to Read/Write access analysis on shared fields
502 private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList) {
503 // Insert backtrack point to the right state ID
504 LinkedList<Integer[]> backtrackList;
505 if (backtrackMap.containsKey(stateId)) {
506 backtrackList = backtrackMap.get(stateId);
508 backtrackList = new LinkedList<>();
509 backtrackMap.put(stateId, backtrackList);
511 backtrackList.addFirst(newChoiceList);
512 // Add to priority queue
513 if (!backtrackStateQ.contains(stateId)) {
514 backtrackStateQ.add(stateId);
518 // Analyze Read/Write accesses that are directly invoked on fields
519 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
520 // Do the analysis to get Read and Write accesses to fields
521 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
522 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
523 // Record the field in the map
524 if (executedInsn instanceof WriteInstruction) {
525 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
526 for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
527 if (fieldClass.startsWith(str)) {
531 rwSet.addWriteField(fieldClass, objectId);
532 } else if (executedInsn instanceof ReadInstruction) {
533 rwSet.addReadField(fieldClass, objectId);
537 // Analyze Read accesses that are indirect (performed through iterators)
538 // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
539 private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
541 INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
542 if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
543 insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
544 // Extract info from the stack frame
545 StackFrame frame = ti.getTopFrame();
546 int[] frameSlots = frame.getSlots();
547 // Get the Groovy callsite library at index 0
548 ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
549 if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
552 // Get the iterated object whose property is accessed
553 ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
554 if (eiAccessObj == null) {
557 // We exclude library classes (they start with java, org, etc.) and some more
558 String objClassName = eiAccessObj.getClassInfo().getName();
559 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName) ||
560 excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName)) {
563 // Extract fields from this object and put them into the read write
564 int numOfFields = eiAccessObj.getNumberOfFields();
565 for(int i=0; i<numOfFields; i++) {
566 FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
567 if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
568 String fieldClass = fieldInfo.getFullName();
569 ReadWriteSet rwSet = getReadWriteSet(currentChoice);
570 int objectId = fieldInfo.getClassInfo().getClassObjectRef();
571 // Record the field in the map
572 rwSet.addReadField(fieldClass, objectId);
578 private int checkAndAdjustChoice(int currentChoice, VM vm) {
579 // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
580 // for certain method calls in the infrastructure, e.g., eventSince()
581 int currChoiceInd = currentChoice % refChoices.length;
582 int currChoiceFromCG = currChoiceInd;
583 ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
584 // This is the main event CG
585 if (currentCG instanceof IntIntervalGenerator) {
586 // This is the interval CG used in device handlers
587 ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
588 // Iterate until we find the IntChoiceFromSet CG
589 while (!(parentCG instanceof IntChoiceFromSet)) {
590 parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
592 int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
593 // Find the index of the event/choice in refChoices
594 for (int i = 0; i<refChoices.length; i++) {
595 if (actualEvtNum == refChoices[i]) {
596 currChoiceFromCG = i;
601 if (currChoiceInd != currChoiceFromCG) {
602 currentChoice = (currentChoice - currChoiceInd) + currChoiceFromCG;
604 return currentChoice;
607 private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
609 // Create a new list of choices for backtrack based on the current choice and conflicting event number
610 // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
611 // for the original set {0, 1, 2, 3}
612 Integer[] newChoiceList = new Integer[refChoices.length];
613 // Put the conflicting event numbers first and reverse the order
614 int actualCurrCho = currentChoice % refChoices.length;
615 // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
616 newChoiceList[0] = choices[actualCurrCho];
617 newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
618 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
619 for (int i = 0, j = 2; i < refChoices.length; i++) {
620 if (refChoices[i] != newChoiceList[0] && refChoices[i] != newChoiceList[1]) {
621 newChoiceList[j] = refChoices[i];
625 // Get the backtrack CG for this backtrack point
626 int stateId = backtrackPointList.get(confEvtNum).getStateId();
627 // Check if this trace has been done starting from this state
628 if (isTraceAlreadyConstructed(newChoiceList, stateId)) {
631 addNewBacktrackPoint(stateId, newChoiceList);
634 private boolean excludeThisForItContains(String[] excludedStrings, String className) {
635 for (String excludedField : excludedStrings) {
636 if (className.contains(excludedField)) {
643 private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
644 for (String excludedField : excludedStrings) {
645 if (className.endsWith(excludedField)) {
652 private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
653 for (String excludedField : excludedStrings) {
654 if (className.startsWith(excludedField)) {
661 private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
663 // Check if we are reaching the end of our execution: no more backtracking points to explore
664 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
665 if (!backtrackStateQ.isEmpty()) {
666 // Set done all the other backtrack points
667 for (BacktrackPoint backtrackPoint : backtrackPointList) {
668 backtrackPoint.getBacktrackCG().setDone();
670 // Reset the next backtrack point with the latest state
671 int hiStateId = backtrackStateQ.peek();
672 // Restore the state first if necessary
673 if (vm.getStateId() != hiStateId) {
674 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
675 vm.restoreState(restorableState);
677 // Set the backtrack CG
678 IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
679 setBacktrackCG(hiStateId, backtrackCG);
681 // Set done this last CG (we save a few rounds)
684 // Save all the visited states when starting a new execution of trace
685 prevVisitedStates.addAll(currVisitedStates);
686 currVisitedStates.clear();
687 // This marks a transitional period to the new CG
688 isEndOfExecution = true;
691 private ReadWriteSet getReadWriteSet(int currentChoice) {
692 // Do the analysis to get Read and Write accesses to fields
694 // We already have an entry
695 if (readWriteFieldsMap.containsKey(currentChoice)) {
696 rwSet = readWriteFieldsMap.get(currentChoice);
697 } else { // We need to create a new entry
698 rwSet = new ReadWriteSet();
699 readWriteFieldsMap.put(currentChoice, rwSet);
704 private boolean isConflictFound(int eventCounter, int currentChoice) {
706 int actualCurrCho = currentChoice % refChoices.length;
707 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
708 if (!readWriteFieldsMap.containsKey(eventCounter) ||
709 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
713 ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
714 // R/W set of choice/event that may have a potential conflict
715 ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
716 // Check for conflicts with Read and Write fields for Write instructions
717 Set<String> currWriteSet = currRWSet.getWriteSet();
718 for(String writeField : currWriteSet) {
719 int currObjId = currRWSet.writeFieldObjectId(writeField);
720 if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
721 (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
725 // Check for conflicts with Write fields for Read instructions
726 Set<String> currReadSet = currRWSet.getReadSet();
727 for(String readField : currReadSet) {
728 int currObjId = currRWSet.readFieldObjectId(readField);
729 if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
733 // Return false if no conflict is found
737 private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
739 int actualCurrCho = currentChoice % refChoices.length;
740 // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
741 if (!readWriteFieldsMap.containsKey(eventCounter) ||
742 choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
745 ReadWriteSet rwSet = readWriteFieldsMap.get(eventCounter);
746 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
747 // Check for conflicts with Write fields for both Read and Write instructions
748 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
749 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
750 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
751 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
757 private boolean isFieldExcluded(String field) {
758 // Check against "starts-with", "ends-with", and "contains" list
759 if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
760 excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
761 excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
768 private boolean isNewConflict(int currentEvent, int eventNumber) {
769 HashSet<Integer> conflictSet;
770 if (!conflictPairMap.containsKey(currentEvent)) {
771 conflictSet = new HashSet<>();
772 conflictPairMap.put(currentEvent, conflictSet);
774 conflictSet = conflictPairMap.get(currentEvent);
776 // If this conflict has been recorded before, we return false because
777 // we don't want to save this backtrack point twice
778 if (conflictSet.contains(eventNumber)) {
781 // If it hasn't been recorded, then do otherwise
782 conflictSet.add(eventNumber);
786 private boolean isTraceAlreadyConstructed(Integer[] choiceList, int stateId) {
787 // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
788 // TODO: THIS IS AN OPTIMIZATION!
789 // This is the optimized version because after we execute, e.g., the trace 1:10234, we don't need to try
790 // another trace that starts with event 1 at state 1, e.g., the trace 1:13024
791 // The second time this event 1 is explored, it will generate the same state as the first one
792 StringBuilder sb = new StringBuilder();
795 sb.append(choiceList[0]);
796 // Check if the trace has been constructed as a backtrack point for this state
797 if (doneBacktrackSet.contains(sb.toString())) {
800 doneBacktrackSet.add(sb.toString());
804 private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
805 if (choices == null || choices != icsCG.getAllChoices()) {
806 // Reset state variables
808 choices = icsCG.getAllChoices();
809 refChoices = copyChoices(choices);
810 // Clearing data structures
811 conflictPairMap.clear();
812 readWriteFieldsMap.clear();
813 stateToEventMap.clear();
814 isEndOfExecution = false;
815 backtrackPointList.clear();
819 private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
820 // Set a backtrack CG based on a state ID
821 LinkedList<Integer[]> backtrackChoices = backtrackMap.get(stateId);
822 backtrackCG.setNewValues(backtrackChoices.removeLast()); // Get the last from the queue
823 backtrackCG.setStateId(stateId);
825 // Remove from the queue if we don't have more backtrack points for that state
826 if (backtrackChoices.isEmpty()) {
827 backtrackMap.remove(stateId);
828 backtrackStateQ.remove(stateId);
832 // --- Functions related to the reachability analysis when there is a state match
834 // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
835 // 1) Whenever there is state match, there is a cycle of events
836 // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
837 // 3) Then we create a new backtrack point for every new conflict
838 private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
839 // Perform this analysis only when:
840 // 1) there is a state match,
841 // 2) this is not during a switch to a new execution,
842 // 3) at least 2 choices/events have been explored (choiceCounter > 1),
843 // 4) the matched state has been encountered in the current execution, and
844 // 5) state > 0 (state 0 is for boolean CG)
845 if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 &&
846 currVisitedStates.contains(stateId) && (stateId > 0)) {
847 // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
848 if (stateToChoiceCounterMap.get(stateId) == null) {
849 System.out.println();
851 int conflictChoice = stateToChoiceCounterMap.get(stateId);
852 int currentChoice = choiceCounter - 1;
853 // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
854 while (conflictChoice < currentChoice) {
855 for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
856 if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
857 createBacktrackingPoint(conflictChoice, eventCounter);