Fixing more bugs with the reachability analysis.
[jpf-core.git] / src / main / gov / nasa / jpf / listener / DPORStateReducer.java
index a35286454e3025d6311d0b50c72cb7ab0f538082..26dd6bd0b274f2b4fc6e6b963f0176fc224ca545 100644 (file)
@@ -39,12 +39,13 @@ import java.util.*;
  * This DPOR implementation is augmented by the algorithm presented in this SPIN paper:
  * http://spinroot.com/spin/symposia/ws08/spin2008_submission_33.pdf
  *
- * The algorithm is presented on page 11 of the paper. Basically, we create a graph G
- * (i.e., visible operation dependency graph)
- * that maps inter-related threads/sub-programs that trigger state changes.
- * The key to this approach is that we evaluate graph G in every iteration/recursion to
- * only update the backtrack sets of the threads/sub-programs that are reachable in graph G
- * from the currently running thread/sub-program.
+ * The algorithm is presented on page 11 of the paper. Basically, we have a graph G
+ * (i.e., visible operation dependency graph).
+ * This DPOR implementation actually fixes the algorithm in the SPIN paper that does not
+ * consider cases where a state could be matched early. In this new algorithm/implementation,
+ * each run is terminated iff:
+ * - we find a state that matches a state in a previous run, or
+ * - we have a matched state in the current run that consists of cycles that contain all choices/events.
  */
 public class DPORStateReducer extends ListenerAdapter {
 
@@ -74,21 +75,17 @@ public class DPORStateReducer extends ListenerAdapter {
   private ArrayList<BacktrackPoint> backtrackPointList;           // Record backtrack points (CG, state Id, and choice)
   private HashMap<Integer, HashSet<Integer>> conflictPairMap;     // Record conflicting events
   private HashSet<String> doneBacktrackSet;                       // Record state ID and trace already constructed
-  private HashMap<Integer,Integer> newStateEventMap;              // Record event producing a new state ID
   private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;      // Record fields that are accessed
   private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
-
-  // Visible operation dependency graph implementation (SPIN paper) related fields
-  private int currChoiceValue;
-  private int prevChoiceValue;
-  private HashMap<Integer, HashSet<Integer>> vodGraphMap; // Visible operation dependency graph (VOD graph)
+  private HashMap<Integer, Integer> stateToChoiceCounterMap;      // Maps state IDs to the choice counter
 
   // Boolean states
   private boolean isBooleanCGFlipped;
   private boolean isEndOfExecution;
 
   // Statistics
-  private int numOfTransitions;        
+  private int numOfConflicts;
+  private int numOfTransitions;
        
   public DPORStateReducer(Config config, JPF jpf) {
     verboseMode = config.getBoolean("printout_state_transition", false);
@@ -99,6 +96,7 @@ public class DPORStateReducer extends ListenerAdapter {
       out = null;
     }
     isBooleanCGFlipped = false;
+               numOfConflicts = 0;
                numOfTransitions = 0;
     restorableStateMap = new HashMap<>();
     initializeStatesVariables();
@@ -165,9 +163,14 @@ public class DPORStateReducer extends ListenerAdapter {
 
   @Override
   public void searchFinished(Search search) {
+    if (stateReductionMode) {
+      // Number of conflicts = first trace + subsequent backtrack points
+      numOfConflicts += 1 + doneBacktrackSet.size();
+    }
     if (verboseMode) {
       out.println("\n==> DEBUG: ----------------------------------- search finished");
       out.println("\n==> DEBUG: State reduction mode  : " + stateReductionMode);
+      out.println("\n==> DEBUG: Number of conflicts   : " + numOfConflicts);
       out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
     }
@@ -212,6 +215,8 @@ public class DPORStateReducer extends ListenerAdapter {
         if (!isBooleanCGFlipped) {
           isBooleanCGFlipped = true;
         } else {
+          // Number of conflicts = first trace + subsequent backtrack points
+          numOfConflicts = 1 + doneBacktrackSet.size();
           // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
           initializeStatesVariables();
         }
@@ -277,10 +282,7 @@ public class DPORStateReducer extends ListenerAdapter {
                   // Check and record a backtrack set for just once!
                   if (isConflictFound(nextInsn, eventCounter, currentChoice, fieldClass) &&
                       isNewConflict(currentChoice, eventCounter)) {
-                    // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
-                    if (vm.isNewState() || isReachableInVODGraph(currentChoice, vm)) {
-                      createBacktrackingPoint(currentChoice, eventCounter);
-                    }
+                    createBacktrackingPoint(currentChoice, eventCounter);
                   }
                 }
               }
@@ -316,6 +318,14 @@ public class DPORStateReducer extends ListenerAdapter {
       writeSet.put(field, objectId);
     }
 
+    public Set<String> getReadSet() {
+      return readSet.keySet();
+    }
+
+    public Set<String> getWriteSet() {
+      return writeSet.keySet();
+    }
+
     public boolean readFieldExists(String field) {
       return readSet.containsKey(field);
     }
@@ -388,8 +398,6 @@ public class DPORStateReducer extends ListenerAdapter {
         icsCG.setChoice(currCGIndex, expectedChoice);
       }
     }
-    // Update current choice
-    currChoiceValue = refChoices[choiceIndex];
     // Record state ID and choice/event as backtrack point
     int stateId = vm.getStateId();
     backtrackPointList.add(new BacktrackPoint(icsCG, stateId, refChoices[choiceIndex]));
@@ -447,12 +455,8 @@ public class DPORStateReducer extends ListenerAdapter {
     backtrackPointList = new ArrayList<>();
     conflictPairMap = new HashMap<>();
     doneBacktrackSet = new HashSet<>();
-    newStateEventMap = new HashMap<>();
     readWriteFieldsMap = new HashMap<>();
-    // VOD graph
-    currChoiceValue = 0;
-    prevChoiceValue = -1;
-    vodGraphMap = new HashMap<>();
+    stateToChoiceCounterMap = new HashMap<>();
     // Booleans
     isEndOfExecution = false;
   }
@@ -482,15 +486,15 @@ public class DPORStateReducer extends ListenerAdapter {
     // Update the state variables
     // Line 19 in the paper page 11 (see the heading note above)
     int stateId = search.getStateId();
-    currVisitedStates.add(stateId);
     // Insert state ID into the map if it is new
     if (!stateToEventMap.containsKey(stateId)) {
       HashSet<Integer> eventSet = new HashSet<>();
       stateToEventMap.put(stateId, eventSet);
     }
+    stateToChoiceCounterMap.put(stateId, choiceCounter);
+    analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
     justVisitedStates.add(stateId);
-    // Update the VOD graph when there is a new state
-    updateVODGraph(search.getVM());
+    currVisitedStates.add(stateId);
   }
 
   // --- Functions related to Read/Write access analysis on shared fields
@@ -581,6 +585,10 @@ public class DPORStateReducer extends ListenerAdapter {
     if (currentCG instanceof IntIntervalGenerator) {
       // This is the interval CG used in device handlers
       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
+      // Iterate until we find the IntChoiceFromSet CG
+      while (!(parentCG instanceof IntChoiceFromSet)) {
+        parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
+      }
       int actualEvtNum = ((IntChoiceFromSet) parentCG).getNextChoice();
       // Find the index of the event/choice in refChoices
       for (int i = 0; i<refChoices.length; i++) {
@@ -693,6 +701,39 @@ public class DPORStateReducer extends ListenerAdapter {
     return rwSet;
   }
 
+  private boolean isConflictFound(int eventCounter, int currentChoice) {
+
+    int actualCurrCho = currentChoice % refChoices.length;
+    // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
+    if (!readWriteFieldsMap.containsKey(eventCounter) ||
+            choices[actualCurrCho] == backtrackPointList.get(eventCounter).getChoice()) {
+      return false;
+    }
+    // Current R/W set
+    ReadWriteSet currRWSet = readWriteFieldsMap.get(currentChoice);
+    // R/W set of choice/event that may have a potential conflict
+    ReadWriteSet evtRWSet = readWriteFieldsMap.get(eventCounter);
+    // Check for conflicts with Read and Write fields for Write instructions
+    Set<String> currWriteSet = currRWSet.getWriteSet();
+    for(String writeField : currWriteSet) {
+      int currObjId = currRWSet.writeFieldObjectId(writeField);
+      if ((evtRWSet.readFieldExists(writeField) && evtRWSet.readFieldObjectId(writeField) == currObjId) ||
+          (evtRWSet.writeFieldExists(writeField) && evtRWSet.writeFieldObjectId(writeField) == currObjId)) {
+        return true;
+      }
+    }
+    // Check for conflicts with Write fields for Read instructions
+    Set<String> currReadSet = currRWSet.getReadSet();
+    for(String readField : currReadSet) {
+      int currObjId = currRWSet.readFieldObjectId(readField);
+      if (evtRWSet.writeFieldExists(readField) && evtRWSet.writeFieldObjectId(readField) == currObjId) {
+        return true;
+      }
+    }
+    // Return false if no conflict is found
+    return false;
+  }
+
   private boolean isConflictFound(Instruction nextInsn, int eventCounter, int currentChoice, String fieldClass) {
 
     int actualCurrCho = currentChoice % refChoices.length;
@@ -788,70 +829,36 @@ public class DPORStateReducer extends ListenerAdapter {
     }
   }
 
-  // --- Functions related to the visible operation dependency graph implementation discussed in the SPIN paper
-
-  // This method checks whether a choice/event (transition) is reachable from the choice/event that produces
-  // the state right before this state in the VOD graph
-  // We use a BFS algorithm for this purpose
-  private boolean isReachableInVODGraph(int currentChoice, VM vm) {
-    // Current event
-    int choiceIndex = currentChoice % refChoices.length;
-    int currEvent = refChoices[choiceIndex];
-    // Previous event
-    int stateId = vm.getStateId();  // A state that has been seen
-    int prevEvent = newStateEventMap.get(stateId);
-    // Only start traversing the graph if prevEvent has an outgoing edge
-    if (vodGraphMap.containsKey(prevEvent)) {
-      // Record visited choices as we search in the graph
-      HashSet<Integer> visitedChoice = new HashSet<>();
-      visitedChoice.add(prevEvent);
-      // Get the first nodes to visit (the neighbors of prevEvent)
-      LinkedList<Integer> nodesToVisit = new LinkedList<>();
-      nodesToVisit.addAll(vodGraphMap.get(prevEvent));
-      // Traverse the graph using BFS
-      while (!nodesToVisit.isEmpty()) {
-        int choice = nodesToVisit.removeFirst();
-        if (choice == currEvent) {
-          return true;
-        }
-        if (visitedChoice.contains(choice)) { // If there is a loop then just continue the exploration
-          continue;
-        }
-        // Continue searching
-        visitedChoice.add(choice);
-        HashSet<Integer> choiceNextNodes = vodGraphMap.get(choice);
-        if (choiceNextNodes != null) {
-          // Add only if there is a mapping for next nodes
-          for (Integer nextNode : choiceNextNodes) {
-            // Skip cycles
-            if (nextNode == choice) {
-              continue;
-            }
-            nodesToVisit.addLast(nextNode);
+  // --- Functions related to the reachability analysis when there is a state match
+
+  // We use backtrackPointsList to analyze the reachable states/events when there is a state match:
+  // 1) Whenever there is state match, there is a cycle of events
+  // 2) We need to analyze and find conflicts for the reachable choices/events in the cycle
+  // 3) Then we create a new backtrack point for every new conflict
+  private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
+    // Perform this analysis only when:
+    // 1) there is a state match,
+    // 2) this is not during a switch to a new execution,
+    // 3) at least 2 choices/events have been explored (choiceCounter > 1),
+    // 4) the matched state has been encountered in the current execution, and
+    // 5) state > 0 (state 0 is for boolean CG)
+    if (!vm.isNewState() && !isEndOfExecution && choiceCounter > 1 &&
+            currVisitedStates.contains(stateId) && (stateId > 0)) {
+      // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
+      if (stateToChoiceCounterMap.get(stateId) == null) {
+        System.out.println();
+      }
+      int conflictChoice = stateToChoiceCounterMap.get(stateId);
+      int currentChoice = choiceCounter - 1;
+      // Find conflicts between choices/events in this cycle (we scan forward in the cycle, not backward)
+      while (conflictChoice < currentChoice) {
+        for (int eventCounter = conflictChoice + 1; eventCounter <= currentChoice; eventCounter++) {
+          if (isConflictFound(eventCounter, conflictChoice) && isNewConflict(conflictChoice, eventCounter)) {
+            createBacktrackingPoint(conflictChoice, eventCounter);
           }
         }
+        conflictChoice++;
       }
     }
-    return false;
-  }
-
-  private void updateVODGraph(VM vm) {
-    // Do this only if it is a new state
-    if (vm.isNewState()) {
-      // Update the graph when we have the current choice value
-      HashSet<Integer> choiceSet;
-      if (vodGraphMap.containsKey(prevChoiceValue)) {
-        // If the key already exists, just retrieve it
-        choiceSet = vodGraphMap.get(prevChoiceValue);
-      } else {
-        // Create a new entry
-        choiceSet = new HashSet<>();
-        vodGraphMap.put(prevChoiceValue, choiceSet);
-      }
-      choiceSet.add(currChoiceValue);
-      prevChoiceValue = currChoiceValue;
-      // Map this state ID to the event (transition) that produces it
-      newStateEventMap.put(vm.getStateId(), currChoiceValue);
-    }
   }
 }