Fixing a bug: completing reachability graph with missing past traces.
[jpf-core.git] / src / main / gov / nasa / jpf / listener / DPORStateReducer.java
index 22cc82f859545e3e2bdf1d778cdc06c191d34b41..885add3e489bf49126c388171fc51811bad1d4af 100644 (file)
@@ -28,8 +28,11 @@ import gov.nasa.jpf.vm.bytecode.WriteInstruction;
 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
 
+import java.io.FileWriter;
 import java.io.PrintWriter;
 import java.util.*;
+import java.util.logging.Logger;
+import java.io.IOException;
 
 // TODO: Fix for Groovy's model-checking
 // TODO: This is a setter to change the values of the ChoiceGenerator to implement POR
@@ -39,12 +42,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 {
 
@@ -52,6 +56,7 @@ public class DPORStateReducer extends ListenerAdapter {
   private boolean verboseMode;
   private boolean stateReductionMode;
   private final PrintWriter out;
+  private PrintWriter fileWriter;
   private String detail;
   private int depth;
   private int id;
@@ -74,14 +79,10 @@ 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
+  private HashMap<Integer, ArrayList<ReachableTrace>> rGraph;     // Create a reachability graph
 
   // Boolean states
   private boolean isBooleanCGFlipped;
@@ -99,6 +100,13 @@ public class DPORStateReducer extends ListenerAdapter {
     } else {
       out = null;
     }
+    String outputFile = config.getString("file_output");
+    if (!outputFile.isEmpty()) {
+      try {
+        fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
+      } catch (IOException e) {
+      }
+    }
     isBooleanCGFlipped = false;
                numOfConflicts = 0;
                numOfTransitions = 0;
@@ -165,6 +173,8 @@ public class DPORStateReducer extends ListenerAdapter {
     }
   }
 
+  static Logger log = JPF.getLogger("report");
+
   @Override
   public void searchFinished(Search search) {
     if (stateReductionMode) {
@@ -177,6 +187,12 @@ public class DPORStateReducer extends ListenerAdapter {
       out.println("\n==> DEBUG: Number of conflicts   : " + numOfConflicts);
       out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
+
+      fileWriter.println("==> DEBUG: State reduction mode  : " + stateReductionMode);
+      fileWriter.println("==> DEBUG: Number of conflicts   : " + numOfConflicts);
+      fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
+      fileWriter.println();
+      fileWriter.close();
     }
   }
 
@@ -232,8 +248,6 @@ public class DPORStateReducer extends ListenerAdapter {
         resetStatesForNewExecution(icsCG, vm);
         // If we don't see a fair scheduling of events/choices then we have to enforce it
         fairSchedulingAndBacktrackPoint(icsCG, vm);
-        // Map state to event
-        mapStateToEvent(icsCG.getNextChoice());
         // Explore the next backtrack point: 
         // 1) if we have seen this state or this state contains cycles that involve all events, and
         // 2) after the current CG is advanced at least once
@@ -242,6 +256,8 @@ public class DPORStateReducer extends ListenerAdapter {
         } else {
           numOfTransitions++;
         }
+        // Map state to event
+        mapStateToEvent(icsCG.getNextChoice());
         justVisitedStates.clear();
         choiceCounter++;
       }
@@ -286,10 +302,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, false);
                   }
                 }
               }
@@ -325,6 +338,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);
     }
@@ -365,6 +386,26 @@ public class DPORStateReducer extends ListenerAdapter {
     }
   }
 
+  // This class stores a compact representation of a reachability graph for past executions
+  private class ReachableTrace {
+    private ArrayList<BacktrackPoint> pastBacktrackPointList;
+    private HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap;
+
+    public ReachableTrace(ArrayList<BacktrackPoint> btrackPointList,
+                             HashMap<Integer, ReadWriteSet> rwFieldsMap) {
+      pastBacktrackPointList = btrackPointList;
+      pastReadWriteFieldsMap = rwFieldsMap;
+    }
+
+    public ArrayList<BacktrackPoint> getPastBacktrackPointList() {
+      return pastBacktrackPointList;
+    }
+
+    public HashMap<Integer, ReadWriteSet> getPastReadWriteFieldsMap() {
+      return pastReadWriteFieldsMap;
+    }
+  }
+
   // -- CONSTANTS
   private final static String DO_CALL_METHOD = "doCall";
   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
@@ -397,8 +438,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]));
@@ -456,12 +495,9 @@ 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<>();
+    rGraph = new HashMap<>();
     // Booleans
     isEndOfExecution = false;
   }
@@ -491,15 +527,31 @@ 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);
     }
+    // Save execution state into the Reachability only if
+    // (1) It is not a revisited state from a past execution, or
+    // (2) It is just a new backtracking point
+    if (!prevVisitedStates.contains(stateId) ||
+            choiceCounter <= 1) {
+      ReachableTrace reachableTrace= new
+              ReachableTrace(backtrackPointList, readWriteFieldsMap);
+      ArrayList<ReachableTrace> rTrace;
+      if (!prevVisitedStates.contains(stateId)) {
+        rTrace = new ArrayList<>();
+        rGraph.put(stateId, rTrace);
+      } else {
+        rTrace = rGraph.get(stateId);
+      }
+      rTrace.add(reachableTrace);
+    }
+    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
@@ -590,6 +642,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++) {
@@ -605,16 +661,21 @@ public class DPORStateReducer extends ListenerAdapter {
     return currentChoice;
   }
 
-  private void createBacktrackingPoint(int currentChoice, int confEvtNum) {
+  private void createBacktrackingPoint(int currentChoice, int confEvtNum, boolean isPastTrace) {
 
     // Create a new list of choices for backtrack based on the current choice and conflicting event number
     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
     // for the original set {0, 1, 2, 3}
     Integer[] newChoiceList = new Integer[refChoices.length];
     // Put the conflicting event numbers first and reverse the order
-    int actualCurrCho = currentChoice % refChoices.length;
-    // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
-    newChoiceList[0] = choices[actualCurrCho];
+    if (isPastTrace) {
+      // For past trace we get the choice/event from the list
+      newChoiceList[0] = backtrackPointList.get(currentChoice).getChoice();
+    } else {
+      // We use the actual choices here in case they have been modified/adjusted by the fair scheduling method
+      int actualCurrCho = currentChoice % refChoices.length;
+      newChoiceList[0] = choices[actualCurrCho];
+    }
     newChoiceList[1] = backtrackPointList.get(confEvtNum).getChoice();
     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
     for (int i = 0, j = 2; i < refChoices.length; i++) {
@@ -702,6 +763,45 @@ public class DPORStateReducer extends ListenerAdapter {
     return rwSet;
   }
 
+  private boolean isConflictFound(int eventCounter, int currentChoice, boolean isPastTrace) {
+
+    int currActualChoice;
+    if (isPastTrace) {
+      currActualChoice = backtrackPointList.get(currentChoice).getChoice();
+    } else {
+      int actualCurrCho = currentChoice % refChoices.length;
+      currActualChoice = choices[actualCurrCho];
+    }
+    // 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) ||
+            currActualChoice == 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;
@@ -775,12 +875,13 @@ public class DPORStateReducer extends ListenerAdapter {
       choiceCounter = 0;
       choices = icsCG.getAllChoices();
       refChoices = copyChoices(choices);
-      // Clearing data structures
-      conflictPairMap.clear();
-      readWriteFieldsMap.clear();
-      stateToEventMap.clear();
+      // Clear data structures
+      backtrackPointList = new ArrayList<>();
+      conflictPairMap = new HashMap<>();
+      readWriteFieldsMap = new HashMap<>();
+      stateToChoiceCounterMap = new HashMap<>();
+      stateToEventMap = new HashMap<>();
       isEndOfExecution = false;
-      backtrackPointList.clear();
     }
   }
 
@@ -797,70 +898,139 @@ 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 && (stateId > 0)) {
+      if (currVisitedStates.contains(stateId)) {
+        // Update the backtrack sets in the cycle
+        updateBacktrackSetsInCycle(stateId);
+      } else if (prevVisitedStates.contains(stateId)) { // We visit a state in a previous execution
+        // Update the backtrack sets in a previous execution
+        updateBacktrackSetsInPreviousExecution(stateId);
+      }
+    }
+  }
+
+  // Get the start event for the past execution trace when there is a state matched from a past execution
+  private int getPastConflictChoice(int stateId, ArrayList<BacktrackPoint> pastBacktrackPointList) {
+    // Iterate and find the first occurrence of the state ID
+    // It is guaranteed that a choice should be found because the state ID is in the list
+    int pastConfChoice = 0;
+    for(int i = 0; i<pastBacktrackPointList.size(); i++) {
+      BacktrackPoint backtrackPoint = pastBacktrackPointList.get(i);
+      int stId = backtrackPoint.getStateId();
+      if (stId == stateId) {
+        pastConfChoice = i;
+        break;
+      }
+    }
+    return pastConfChoice;
+  }
+
+  // Get a sorted list of reachable state IDs starting from the input stateId
+  private ArrayList<Integer> getReachableStateIds(Set<Integer> stateIds, int stateId) {
+    // Only include state IDs equal or greater than the input stateId: these are reachable states
+    ArrayList<Integer> sortedStateIds = new ArrayList<>();
+    for(Integer stId : stateIds) {
+      if (stId >= stateId) {
+        sortedStateIds.add(stId);
+      }
+    }
+    Collections.sort(sortedStateIds);
+    return sortedStateIds;
+  }
+
+  // Update the backtrack sets in the cycle
+  private void updateBacktrackSetsInCycle(int stateId) {
+    // Find the choice/event that marks the start of this cycle: first choice we explore for conflicts
+    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, false) && isNewConflict(conflictChoice, eventCounter)) {
+          createBacktrackingPoint(conflictChoice, eventCounter, false);
         }
       }
+      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);
+  // TODO: OPTIMIZATION!
+  // Check and make sure that state ID and choice haven't been explored for this trace
+  private boolean isNotChecked(HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice,
+                               BacktrackPoint backtrackPoint) {
+    int stateId = backtrackPoint.getStateId();
+    int choice = backtrackPoint.getChoice();
+    HashSet<Integer> choiceSet;
+    if (checkedStateIdAndChoice.containsKey(stateId)) {
+      choiceSet = checkedStateIdAndChoice.get(stateId);
+      if (choiceSet.contains(choice)) {
+        // State ID and choice found. It has been checked!
+        return false;
+      }
+    } else {
+      choiceSet = new HashSet<>();
+      checkedStateIdAndChoice.put(stateId, choiceSet);
+    }
+    choiceSet.add(choice);
+
+    return true;
+  }
+
+  // Update the backtrack sets in a previous execution
+  private void updateBacktrackSetsInPreviousExecution(int stateId) {
+    // Don't check a past trace twice!
+    HashSet<ReachableTrace> checkedTrace = new HashSet<>();
+    // Don't check the same event twice for a revisited state
+    HashMap<Integer, HashSet<Integer>> checkedStateIdAndChoice = new HashMap<>();
+    // Get sorted reachable state IDs
+    ArrayList<Integer> reachableStateIds = getReachableStateIds(rGraph.keySet(), stateId);
+    // Iterate from this state ID until the biggest state ID
+    for(Integer stId : reachableStateIds) {
+      // Find the right reachability graph object that contains the stateId
+      ArrayList<ReachableTrace> rTraces = rGraph.get(stId);
+      for (ReachableTrace rTrace : rTraces) {
+        if (!checkedTrace.contains(rTrace)) {
+          // Find the choice/event that marks the start of the subtrace from the previous execution
+          ArrayList<BacktrackPoint> pastBacktrackPointList = rTrace.getPastBacktrackPointList();
+          HashMap<Integer, ReadWriteSet> pastReadWriteFieldsMap = rTrace.getPastReadWriteFieldsMap();
+          int pastConfChoice = getPastConflictChoice(stId, pastBacktrackPointList);
+          int conflictChoice = choiceCounter;
+          // Iterate from the starting point until the end of the past execution trace
+          while (pastConfChoice < pastBacktrackPointList.size() - 1) {  // BacktrackPoint list always has a surplus of 1
+            // Get the info of the event from the past execution trace
+            BacktrackPoint confBtrackPoint = pastBacktrackPointList.get(pastConfChoice);
+            if (isNotChecked(checkedStateIdAndChoice, confBtrackPoint)) {
+              ReadWriteSet rwSet = pastReadWriteFieldsMap.get(pastConfChoice);
+              // Append this event to the current list and map
+              backtrackPointList.add(confBtrackPoint);
+              readWriteFieldsMap.put(choiceCounter, rwSet);
+              for (int eventCounter = conflictChoice - 1; eventCounter >= 0; eventCounter--) {
+                if (isConflictFound(eventCounter, conflictChoice, true) && isNewConflict(conflictChoice, eventCounter)) {
+                  createBacktrackingPoint(conflictChoice, eventCounter, true);
+                }
+              }
+              // Remove this event to replace it with a new one
+              backtrackPointList.remove(backtrackPointList.size() - 1);
+              readWriteFieldsMap.remove(choiceCounter);
+            }
+            pastConfChoice++;
+          }
+          checkedTrace.add(rTrace);
+        }
       }
-      choiceSet.add(currChoiceValue);
-      prevChoiceValue = currChoiceValue;
-      // Map this state ID to the event (transition) that produces it
-      newStateEventMap.put(vm.getStateId(), currChoiceValue);
     }
   }
 }