Fixing bugs and cleaning up: Continuing sub-graph executions when there is no matched...
[jpf-core.git] / src / main / gov / nasa / jpf / listener / StateReducer.java
index 532076b91d1418696ca8c31a96558b71a95ca542..e03135454330bf21df98cb80db167cfc819fd8de 100644 (file)
@@ -59,6 +59,7 @@ public class StateReducer extends ListenerAdapter {
 
   // State reduction fields
   private Integer[] choices;
+  private Integer[] refChoices;
   private IntChoiceFromSet currCG;
   private int choiceCounter;
   private Integer choiceUpperBound;
@@ -83,14 +84,15 @@ public class StateReducer extends ListenerAdapter {
   // (i.e., hash table that records encountered states)
   // VOD graph is updated when the state has not yet been seen
   // Current state
-  private int stateId;
+  private HashSet<Integer> justVisitedStates;
   // Previous choice number
   private int prevChoiceValue;
   // HashSet that stores references to unused CGs
   private HashSet<IntChoiceFromSet> unusedCG;
 
-  // Reference to the state graph in the ConflictTracker class
-  private HashMap<Integer, ConflictTracker.Node> stateGraph;
+  //private HashMap<Integer, ConflictTracker.Node> stateGraph;
+  private HashMap<Integer, HashSet<Integer>> stateToEventMap;
+  // Map state to event
   // Visited states in the previous and current executions/traces for terminating condition
   private HashSet<Integer> prevVisitedStates;
   private HashSet<Integer> currVisitedStates;
@@ -109,7 +111,7 @@ public class StateReducer extends ListenerAdapter {
     transition = null;
     isBooleanCGFlipped = false;
     vodGraphMap = new HashMap<>();
-    stateId = -1;
+    justVisitedStates = new HashSet<>();
     prevChoiceValue = -1;
     cgMap = new HashMap<>();
     readWriteFieldsMap = new HashMap<>();
@@ -117,8 +119,7 @@ public class StateReducer extends ListenerAdapter {
     backtrackSet = new HashSet<>();
     conflictPairMap = new HashMap<>();
     unusedCG = new HashSet<>();
-    // TODO: We are assuming that the StateReducer is always used together with the ConflictTracker
-    stateGraph = ConflictTracker.nodes;
+    stateToEventMap = new HashMap<>();
     prevVisitedStates = new HashSet<>();
     currVisitedStates = new HashSet<>();
     initializeStateReduction();
@@ -127,6 +128,7 @@ public class StateReducer extends ListenerAdapter {
   private void initializeStateReduction() {
     if (stateReductionMode) {
       choices = null;
+      refChoices = null;
       currCG = null;
       choiceCounter = 0;
       choiceUpperBound = 0;
@@ -134,10 +136,9 @@ public class StateReducer extends ListenerAdapter {
       isInitialized = false;
       isResetAfterAnalysis = false;
       cgMap.clear();
-      readWriteFieldsMap.clear();
+      resetReadWriteAnalysis();
       backtrackMap.clear();
       backtrackSet.clear();
-      conflictPairMap.clear();
     }
   }
 
@@ -161,6 +162,68 @@ public class StateReducer extends ListenerAdapter {
     }
   }
 
+  private void resetReadWriteAnalysis() {
+    // Reset the following data structure when the choice counter reaches 0 again
+    conflictPairMap.clear();
+    readWriteFieldsMap.clear();
+  }
+
+  private IntChoiceFromSet setNewCG(IntChoiceFromSet icsCG) {
+    icsCG.setNewValues(choices);
+    icsCG.reset();
+    // Use a modulo since choiceCounter is going to keep increasing
+    int choiceIndex = choiceCounter % choices.length;
+    icsCG.advance(choices[choiceIndex]);
+    if (choiceIndex == 0) {
+      resetReadWriteAnalysis();
+    }
+    return icsCG;
+  }
+
+  private Integer[] copyChoices(Integer[] choicesToCopy) {
+
+    Integer[] copyOfChoices = new Integer[choicesToCopy.length];
+    System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
+    return copyOfChoices;
+  }
+
+  private void continueExecutingThisTrace(IntChoiceFromSet icsCG) {
+    // We repeat the same trace if a state match is not found yet
+    IntChoiceFromSet setCG = setNewCG(icsCG);
+    unusedCG.add(setCG);
+  }
+
+  private void initializeChoiceGenerators(IntChoiceFromSet icsCG, Integer[] cgChoices) {
+    if (choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
+      // Update the choices of the first CG and add '-1'
+      if (choices == null) {
+        // Initialize backtrack set that stores all the explored backtrack lists
+        maxUpperBound = cgChoices.length;
+        // All the choices are always the same so we only need to update it once
+        // Get the choice array and final choice in the array
+        choices = cgChoices;
+        // Make a copy of choices as reference
+        refChoices = copyChoices(choices);
+        String firstChoiceListString = buildStringFromChoiceList(choices);
+        backtrackSet.add(firstChoiceListString);
+      }
+      IntChoiceFromSet setCG = setNewCG(icsCG);
+      cgMap.put(setCG, refChoices[choiceCounter]);
+    } else {
+      continueExecutingThisTrace(icsCG);
+    }
+  }
+
+  private void manageChoiceGeneratorsInSubsequentTraces(IntChoiceFromSet icsCG) {
+    // If this is the first iteration of the trace then set other CGs done
+    if (choiceCounter <= choiceUpperBound) {
+      icsCG.setDone();
+    } else {
+      // If this is the subsequent iterations of the trace then set up new CGs to continue the execution
+      continueExecutingThisTrace(icsCG);
+    }
+  }
+
   @Override
   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
     if (stateReductionMode) {
@@ -176,43 +239,25 @@ public class StateReducer extends ListenerAdapter {
         }
         // Record the subsequent Integer CGs only until we hit the upper bound
         if (!isResetAfterAnalysis) {
-          if (choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
-            // Update the choices of the first CG and add '-1'
-            if (choices == null) {
-              // Initialize backtrack set that stores all the explored backtrack lists
-              maxUpperBound = cgChoices.length;
-              // All the choices are always the same so we only need to update it once
-              choices = new Integer[cgChoices.length + 1];
-              System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
-              choices[choices.length - 1] = -1;
-              String firstChoiceListString = buildStringFromChoiceList(choices);
-              backtrackSet.add(firstChoiceListString);
-            }
-            icsCG.setNewValues(choices);
-            icsCG.reset();
-            // Advance the current Integer CG
-            // This way we explore all the event numbers in the first pass
-            icsCG.advance(choices[choiceCounter]);
-            cgMap.put(icsCG, choices[choiceCounter]);
-          } else {
-            // We repeat the same trace if a state match is not found yet
-            icsCG.setNewValues(choices);
-            icsCG.reset();
-            // Use a modulo since choiceCounter is going to keep increasing
-            int choiceIndex = choiceCounter % (choices.length - 1);
-            icsCG.advance(choices[choiceIndex]);
-            unusedCG.add(icsCG);
-          }
-          //choiceCounter = choiceCounter < choiceUpperBound ? choiceCounter + 1 : 0;
-          choiceCounter++;
+          initializeChoiceGenerators(icsCG, cgChoices);
         } else {
           // Set new CGs to done so that the search algorithm explores the existing CGs
-          icsCG.setDone();
+          //icsCG.setDone();
+          manageChoiceGeneratorsInSubsequentTraces(icsCG);
         }
+        choiceCounter++;
       }
     }
   }
 
+  private void setDoneUnusedCG() {
+    // Set done every CG in the unused CG set
+    for (IntChoiceFromSet cg : unusedCG) {
+      cg.setDone();
+    }
+    unusedCG.clear();
+  }
+
   private void resetAllCGs() {
     // Extract the event numbers that have backtrack lists
     Set<Integer> eventSet = backtrackMap.keySet();
@@ -237,11 +282,7 @@ public class StateReducer extends ListenerAdapter {
         cg.setDone();
       }
     }
-    // Set done every CG in the unused CG set
-    for (IntChoiceFromSet cg : unusedCG) {
-      cg.setDone();
-    }
-    unusedCG.clear();
+    setDoneUnusedCG();
     saveVisitedStates();
   }
 
@@ -249,13 +290,12 @@ public class StateReducer extends ListenerAdapter {
   // We terminate the execution iff:
   // (1) the state has been visited in the current execution
   // (2) the state has one or more cycles that involve all the events
+  // With simple approach we only need to check for a re-visited state.
+  // Basically, we have to check that we have executed all events between two occurrences of such state.
   private boolean containsCyclesWithAllEvents(int stId) {
 
-    HashSet<ConflictTracker.Node> visitingStates = new HashSet<>();
-    HashSet<Integer> visitedEvents = new HashSet<>();
+    HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
     boolean containsCyclesWithAllEvts = false;
-    ConflictTracker.Node currNode = stateGraph.get(stId);
-    dfsFindCycles(currNode, visitingStates, visitedEvents, new HashSet<>());
     if (checkIfAllEventsInvolved(visitedEvents)) {
       containsCyclesWithAllEvts = true;
     }
@@ -263,23 +303,6 @@ public class StateReducer extends ListenerAdapter {
     return containsCyclesWithAllEvts;
   }
 
-  private void dfsFindCycles(ConflictTracker.Node currNode, HashSet<ConflictTracker.Node> visitingStates,
-                             HashSet<Integer> visitedEvents, HashSet<Integer> visitingEvents) {
-
-    // Stop when there is a cycle and record all the events
-    if (visitingStates.contains(currNode)) {
-      visitedEvents.addAll(visitingEvents);
-    } else {
-      visitingStates.add(currNode);
-      for(ConflictTracker.Edge edge : currNode.getOutEdges()) {
-        visitingEvents.add(edge.getEventNumber());
-        dfsFindCycles(edge.getDst(), visitingStates, visitedEvents, visitingEvents);
-        visitingEvents.remove(edge.getEventNumber());
-      }
-      visitingStates.remove(currNode);
-    }
-  }
-
   private boolean checkIfAllEventsInvolved(HashSet<Integer> visitedEvents) {
 
     // Check if this set contains all the event choices
@@ -299,6 +322,70 @@ public class StateReducer extends ListenerAdapter {
     currVisitedStates.clear();
   }
 
+  private void updateChoicesForNewExecution(IntChoiceFromSet icsCG) {
+    if (choices == null || choices != icsCG.getAllChoices()) {
+      currCG = icsCG;
+      choices = icsCG.getAllChoices();
+      refChoices = copyChoices(choices);
+      // Reset a few things for the sub-graph
+      resetReadWriteAnalysis();
+      choiceCounter = 0;
+    }
+  }
+
+  private void exploreNextBacktrackSets(IntChoiceFromSet icsCG) {
+    // Traverse the sub-graphs
+    if (isResetAfterAnalysis) {
+      // Do this for every CG after finishing each backtrack list
+      // We try to update the CG with a backtrack list if the state has been visited multiple times
+      //if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
+      //if ((!icsCG.hasMoreChoices() || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
+      if (choiceCounter > 1 && cgMap.containsKey(icsCG)) {
+        int event = cgMap.get(icsCG);
+        LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
+        if (choiceLists != null && choiceLists.peekFirst() != null) {
+          Integer[] choiceList = choiceLists.removeFirst();
+          // Deploy the new choice list for this CG
+          icsCG.setNewValues(choiceList);
+          icsCG.reset();
+        } else {
+          // Set done if this was the last backtrack list
+          icsCG.setDone();
+        }
+        setDoneUnusedCG();
+        saveVisitedStates();
+      }
+    } else {
+      // Update and reset the CG if needed (do this for the first time after the analysis)
+      // Start backtracking if this is a visited state and it is not a repeating state
+      resetAllCGs();
+      isResetAfterAnalysis = true;
+    }
+  }
+
+  private void checkAndEnforceFairScheduling(IntChoiceFromSet icsCG) {
+    // Check the next choice and if the value is not the same as the expected then force the expected value
+    int choiceIndex = (choiceCounter - 1) % refChoices.length;
+    if (choices[choiceIndex] != icsCG.getNextChoiceIndex()) {
+      int expectedChoice = refChoices[choiceIndex];
+      int currCGIndex = icsCG.getNextChoiceIndex();
+      if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
+        icsCG.setChoice(currCGIndex, expectedChoice);
+      }
+    }
+  }
+
+  private boolean terminateCurrentExecution() {
+    // We need to check all the states that have just been visited
+    // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
+    for(Integer stateId : justVisitedStates) {
+      if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   @Override
   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
 
@@ -316,43 +403,14 @@ public class StateReducer extends ListenerAdapter {
       if (currentCG instanceof IntChoiceFromSet) {
         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
         // Update the current pointer to the current set of choices
-        if (choices == null || choices != icsCG.getAllChoices()) {
-          currCG = icsCG;
-          choices = icsCG.getAllChoices();
-          // Reset a few things for the sub-graph
-          conflictPairMap.clear();
-          readWriteFieldsMap.clear();
-          choiceCounter = 0;
-        }
+        updateChoicesForNewExecution(icsCG);
         // Check if we have seen this state or this state contains cycles that involve all events
-        if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
-          // Traverse the sub-graphs
-          if (isResetAfterAnalysis) {
-            // Advance choice counter for sub-graphs
-            choiceCounter++;
-            // Do this for every CG after finishing each backtrack list
-            // We try to update the CG with a backtrack list if the state has been visited multiple times
-            if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
-              int event = cgMap.get(icsCG);
-              LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
-              if (choiceLists != null && choiceLists.peekFirst() != null) {
-                Integer[] choiceList = choiceLists.removeFirst();
-                // Deploy the new choice list for this CG
-                icsCG.setNewValues(choiceList);
-                icsCG.reset();
-              } else {
-                // Set done if this was the last backtrack list
-                icsCG.setDone();
-              }
-              saveVisitedStates();
-            }
-          } else {
-            // Update and reset the CG if needed (do this for the first time after the analysis)
-            // Start backtracking if this is a visited state and it is not a repeating state
-            resetAllCGs();
-            isResetAfterAnalysis = true;
-          }
+        if (terminateCurrentExecution()) {
+          exploreNextBacktrackSets(icsCG);
         }
+        justVisitedStates.clear();
+        // If we don't see a fair scheduling of events/choices then we have to enforce it
+        checkAndEnforceFairScheduling(icsCG);
         // Update the VOD graph always with the latest
         updateVODGraph(icsCG.getNextChoice());
       }
@@ -361,22 +419,40 @@ public class StateReducer extends ListenerAdapter {
 
   private void updateVODGraph(int currChoiceValue) {
     // Update the graph when we have the current choice value
-    updateVODGraph(prevChoiceValue, currChoiceValue);
-    prevChoiceValue = currChoiceValue;
-  }
-
-  private void updateVODGraph(int prevChoice, int currChoice) {
-
     HashSet<Integer> choiceSet;
-    if (vodGraphMap.containsKey(prevChoice)) {
+    if (vodGraphMap.containsKey(prevChoiceValue)) {
       // If the key already exists, just retrieve it
-      choiceSet = vodGraphMap.get(prevChoice);
+      choiceSet = vodGraphMap.get(prevChoiceValue);
     } else {
       // Create a new entry
       choiceSet = new HashSet<>();
-      vodGraphMap.put(prevChoice, choiceSet);
+      vodGraphMap.put(prevChoiceValue, choiceSet);
+    }
+    choiceSet.add(currChoiceValue);
+    prevChoiceValue = currChoiceValue;
+  }
+
+  private void mapStateToEvent(Search search, int stateId) {
+    // Insert state ID and event choice into the map
+    HashSet<Integer> eventSet;
+    if (stateToEventMap.containsKey(stateId)) {
+      eventSet = stateToEventMap.get(stateId);
+    } else {
+      eventSet = new HashSet<>();
+      stateToEventMap.put(stateId, eventSet);
+    }
+    eventSet.add(prevChoiceValue);
+  }
+
+  private void updateStateInfo(Search search) {
+    if (stateReductionMode) {
+      // Update the state variables
+      // Line 19 in the paper page 11 (see the heading note above)
+      int stateId = search.getStateId();
+      currVisitedStates.add(stateId);
+      mapStateToEvent(search, stateId);
+      justVisitedStates.add(stateId);
     }
-    choiceSet.add(currChoice);
   }
 
   @Override
@@ -398,11 +474,7 @@ public class StateReducer extends ListenerAdapter {
       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
               " which is " + detail + " Transition: " + transition + "\n");
     }
-    if (stateReductionMode) {
-      // Update the state ID variables
-      stateId = search.getStateId();
-      currVisitedStates.add(stateId);
-    }
+    updateStateInfo(search);
   }
 
   @Override
@@ -413,14 +485,10 @@ public class StateReducer extends ListenerAdapter {
       transition = search.getTransition();
       detail = null;
 
-      // Update the state variables
-      // Line 19 in the paper page 11 (see the heading note above)
-      stateId = search.getStateId();
-      currVisitedStates.add(stateId);
-
       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
               " and depth: " + depth + "\n");
     }
+    updateStateInfo(search);
   }
 
   @Override
@@ -471,11 +539,11 @@ public class StateReducer extends ListenerAdapter {
     // Do the analysis to get Read and Write accesses to fields
     ReadWriteSet rwSet;
     // We already have an entry
-    if (readWriteFieldsMap.containsKey(choices[currentChoice])) {
-      rwSet = readWriteFieldsMap.get(choices[currentChoice]);
+    if (readWriteFieldsMap.containsKey(refChoices[currentChoice])) {
+      rwSet = readWriteFieldsMap.get(refChoices[currentChoice]);
     } else { // We need to create a new entry
       rwSet = new ReadWriteSet();
-      readWriteFieldsMap.put(choices[currentChoice], rwSet);
+      readWriteFieldsMap.put(refChoices[currentChoice], rwSet);
     }
     int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
     // Record the field in the map
@@ -559,19 +627,17 @@ public class StateReducer extends ListenerAdapter {
       }
       int maxListLength = choiceUpperBound + 1;
       int listLength = maxListLength - conflictEventNumber;
-      Integer[] newChoiceList = new Integer[listLength + 1];
+      Integer[] newChoiceList = new Integer[listLength];
       // Put the conflicting event numbers first and reverse the order
-      newChoiceList[0] = choices[currentChoice];
-      newChoiceList[1] = choices[conflictEventNumber];
+      newChoiceList[0] = refChoices[currentChoice];
+      newChoiceList[1] = refChoices[conflictEventNumber];
       // Put the rest of the event numbers into the array starting from the minimum to the upper bound
       for (int i = conflictEventNumber + 1, j = 2; j < listLength; i++) {
-        if (choices[i] != choices[currentChoice]) {
-          newChoiceList[j] = choices[i];
+        if (refChoices[i] != refChoices[currentChoice]) {
+          newChoiceList[j] = refChoices[i];
           j++;
         }
       }
-      // Set the last element to '-1' as the end of the sequence
-      newChoiceList[newChoiceList.length - 1] = -1;
       checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
       // The start index for the recursion is always 1 (from the main branch)
     } else { // This is a sub-graph
@@ -579,24 +645,22 @@ public class StateReducer extends ListenerAdapter {
       if (currCG != null && cgMap.containsKey(currCG)) {
         int backtrackListIndex = cgMap.get(currCG);
         backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
-        int listLength = choices.length;
+        int listLength = refChoices.length;
         Integer[] newChoiceList = new Integer[listLength];
         // Copy everything before the conflict number
         for (int i = 0; i < conflictEventNumber; i++) {
-          newChoiceList[i] = choices[i];
+          newChoiceList[i] = refChoices[i];
         }
         // Put the conflicting events
-        newChoiceList[conflictEventNumber] = choices[currentChoice];
-        newChoiceList[conflictEventNumber + 1] = choices[conflictEventNumber];
+        newChoiceList[conflictEventNumber] = refChoices[currentChoice];
+        newChoiceList[conflictEventNumber + 1] = refChoices[conflictEventNumber];
         // Copy the rest
         for (int i = conflictEventNumber + 1, j = conflictEventNumber + 2; j < listLength - 1; i++) {
-          if (choices[i] != choices[currentChoice]) {
-            newChoiceList[j] = choices[i];
+          if (refChoices[i] != refChoices[currentChoice]) {
+            newChoiceList[j] = refChoices[i];
             j++;
           }
         }
-        // Set the last element to '-1' as the end of the sequence
-        newChoiceList[newChoiceList.length - 1] = -1;
         checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
       }
     }
@@ -680,11 +744,11 @@ public class StateReducer extends ListenerAdapter {
   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
     if (stateReductionMode) {
       if (isInitialized) {
-        if (choiceCounter <= 0 || choiceCounter > choices.length - 1) {
+        int currentChoice = (choiceCounter % refChoices.length) - 1;
+        if (currentChoice < 0) {
           // We do not compute the conflicts for the choice '-1'
           return;
         }
-        int currentChoice = choiceCounter - 1;
         // Record accesses from executed instructions
         if (executedInsn instanceof JVMFieldInstruction) {
           // Analyze only after being initialized
@@ -708,10 +772,10 @@ public class StateReducer extends ListenerAdapter {
               // one by one as this recursively checks backward when backtrack set is revisited and executed.
               for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
                 // Skip if this event number does not have any Read/Write set
-                if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
+                if (!readWriteFieldsMap.containsKey(refChoices[eventNumber])) {
                   continue;
                 }
-                ReadWriteSet rwSet = readWriteFieldsMap.get(choices[eventNumber]);
+                ReadWriteSet rwSet = readWriteFieldsMap.get(refChoices[eventNumber]);
                 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
                 // 1) Check for conflicts with Write fields for both Read and Write instructions
                 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
@@ -722,8 +786,7 @@ public class StateReducer extends ListenerAdapter {
                   // If it has been serviced before, we just skip this
                   if (recordConflictPair(currentChoice, eventNumber)) {
                     // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
-                    if (vm.isNewState() ||
-                            (!vm.isNewState() && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
+                    if (vm.isNewState() || isReachableInVODGraph(refChoices[currentChoice], refChoices[currentChoice-1])) {
                       createBacktrackChoiceList(currentChoice, eventNumber);
                       // Break if a conflict is found!
                       break;