Fixing bugs: moving VOD-graph building into the CGAdvanced method to have the most...
[jpf-core.git] / src / main / gov / nasa / jpf / listener / StateReducer.java
index 2194ff160d3074b2a9325a2c75cab2b97f2d0d1f..532076b91d1418696ca8c31a96558b71a95ca542 100644 (file)
@@ -52,10 +52,10 @@ public class StateReducer extends ListenerAdapter {
   private boolean debugMode;
   private boolean stateReductionMode;
   private final PrintWriter out;
-  volatile private String detail;
-  volatile private int depth;
-  volatile private int id;
-  Transition transition;
+  private String detail;
+  private int depth;
+  private int id;
+  private Transition transition;
 
   // State reduction fields
   private Integer[] choices;
@@ -75,8 +75,6 @@ public class StateReducer extends ListenerAdapter {
   // Stores explored backtrack lists in the form of HashSet of Strings
   private HashSet<String> backtrackSet;
   private HashMap<Integer, HashSet<Integer>> conflictPairMap;
-  // Map choicelist with start index
-  //  private HashMap<Integer[],Integer> choiceListStartIndexMap;
 
   // Map that represents graph G
   // (i.e., visible operation dependency graph (VOD Graph)
@@ -84,9 +82,18 @@ public class StateReducer extends ListenerAdapter {
   // Set that represents hash table H
   // (i.e., hash table that records encountered states)
   // VOD graph is updated when the state has not yet been seen
-  private HashSet<Integer> visitedStateSet;
   // Current state
   private int stateId;
+  // 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;
+  // Visited states in the previous and current executions/traces for terminating condition
+  private HashSet<Integer> prevVisitedStates;
+  private HashSet<Integer> currVisitedStates;
 
   public StateReducer(Config config, JPF jpf) {
     debugMode = config.getBoolean("debug_state_transition", false);
@@ -102,8 +109,18 @@ public class StateReducer extends ListenerAdapter {
     transition = null;
     isBooleanCGFlipped = false;
     vodGraphMap = new HashMap<>();
-    visitedStateSet = new HashSet<>();
     stateId = -1;
+    prevChoiceValue = -1;
+    cgMap = new HashMap<>();
+    readWriteFieldsMap = new HashMap<>();
+    backtrackMap = new HashMap<>();
+    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;
+    prevVisitedStates = new HashSet<>();
+    currVisitedStates = new HashSet<>();
     initializeStateReduction();
   }
 
@@ -116,11 +133,11 @@ public class StateReducer extends ListenerAdapter {
       maxUpperBound = 0;
       isInitialized = false;
       isResetAfterAnalysis = false;
-      cgMap = new HashMap<>();
-      readWriteFieldsMap = new HashMap<>();
-      backtrackMap = new HashMap<>();
-      backtrackSet = new HashSet<>();
-      conflictPairMap = new HashMap<>();
+      cgMap.clear();
+      readWriteFieldsMap.clear();
+      backtrackMap.clear();
+      backtrackSet.clear();
+      conflictPairMap.clear();
     }
   }
 
@@ -158,28 +175,38 @@ public class StateReducer extends ListenerAdapter {
           isInitialized = true;
         }
         // Record the subsequent Integer CGs only until we hit the upper bound
-        if (!isResetAfterAnalysis && 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);
+        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);
           }
-          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]);
+          //choiceCounter = choiceCounter < choiceUpperBound ? choiceCounter + 1 : 0;
           choiceCounter++;
         } else {
-          // Set done the subsequent CGs
-          // We only need n CGs (n is event numbers)
+          // Set new CGs to done so that the search algorithm explores the existing CGs
           icsCG.setDone();
         }
       }
@@ -191,6 +218,10 @@ public class StateReducer extends ListenerAdapter {
     Set<Integer> eventSet = backtrackMap.keySet();
     // Return if there is no conflict at all (highly unlikely)
     if (eventSet.isEmpty()) {
+      // Set every CG to done!
+      for (IntChoiceFromSet cg : cgMap.keySet()) {
+        cg.setDone();
+      }
       return;
     }
     // Reset every CG with the first backtrack lists
@@ -206,6 +237,66 @@ public class StateReducer extends ListenerAdapter {
         cg.setDone();
       }
     }
+    // Set done every CG in the unused CG set
+    for (IntChoiceFromSet cg : unusedCG) {
+      cg.setDone();
+    }
+    unusedCG.clear();
+    saveVisitedStates();
+  }
+
+  // Detect cycles in the current execution/trace
+  // 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
+  private boolean containsCyclesWithAllEvents(int stId) {
+
+    HashSet<ConflictTracker.Node> visitingStates = new HashSet<>();
+    HashSet<Integer> visitedEvents = new HashSet<>();
+    boolean containsCyclesWithAllEvts = false;
+    ConflictTracker.Node currNode = stateGraph.get(stId);
+    dfsFindCycles(currNode, visitingStates, visitedEvents, new HashSet<>());
+    if (checkIfAllEventsInvolved(visitedEvents)) {
+      containsCyclesWithAllEvts = true;
+    }
+
+    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
+    // If not then this is not the terminating condition
+    for(int i=0; i<=choiceUpperBound; i++) {
+      if (!visitedEvents.contains(i)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private void saveVisitedStates() {
+    // CG is being reset
+    // Save all the visited states
+    prevVisitedStates.addAll(currVisitedStates);
+    currVisitedStates.clear();
   }
 
   @Override
@@ -233,35 +324,48 @@ public class StateReducer extends ListenerAdapter {
           readWriteFieldsMap.clear();
           choiceCounter = 0;
         }
-        // Traverse the sub-graphs
-        if (isResetAfterAnalysis) {
-          // Advance choice counter for sub-graphs
-          choiceCounter++;
-          // Do this for every CG after finishing each backtrack list
-          if (icsCG.getNextChoice() == -1 || visitedStateSet.contains(stateId)) {
-            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();
+        // 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;
           }
         }
-        // Update and reset the CG if needed (do this for the first time after the analysis)
-        if (!isResetAfterAnalysis && icsCG.getNextChoice() == -1) {
-          resetAllCGs();
-          isResetAfterAnalysis = true;
-        }
+        // Update the VOD graph always with the latest
+        updateVODGraph(icsCG.getNextChoice());
       }
     }
   }
 
-  public void updateVODGraph(int prevChoice, int currChoice) {
+  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)) {
@@ -295,23 +399,9 @@ public class StateReducer extends ListenerAdapter {
               " which is " + detail + " Transition: " + transition + "\n");
     }
     if (stateReductionMode) {
-      // Update vodGraph
-      int currChoice = choiceCounter - 1;
-      int prevChoice = currChoice - 1;
-      if (currChoice < 0) {
-        // Current choice has to be at least 0 (initial case can be -1)
-        visitedStateSet.add(stateId);
-        return;
-      }
-      // Current choice and previous choice values could be -1 (since we use -1 as the end-of-array condition)
-      int currChoiceValue = (choices[currChoice] == -1) ? 0 : choices[currChoice];
-      // When current choice is 0, previous choice could be -1
-      int prevChoiceValue = (prevChoice == -1) ? -1 : choices[prevChoice];
-      updateVODGraph(prevChoiceValue, currChoiceValue);
-      // Line 19 in the paper page 11 (see the heading note above)
+      // Update the state ID variables
       stateId = search.getStateId();
-      // Add state ID into the visited state set
-      visitedStateSet.add(stateId);
+      currVisitedStates.add(stateId);
     }
   }
 
@@ -323,6 +413,11 @@ 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");
     }
@@ -481,7 +576,7 @@ public class StateReducer extends ListenerAdapter {
       // The start index for the recursion is always 1 (from the main branch)
     } else { // This is a sub-graph
       // There is a case/bug that after a re-initialization, currCG is not yet initialized
-      if (currCG != null) {
+      if (currCG != null && cgMap.containsKey(currCG)) {
         int backtrackListIndex = cgMap.get(currCG);
         backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
         int listLength = choices.length;
@@ -569,6 +664,10 @@ public class StateReducer extends ListenerAdapter {
         if (currChoiceNextNodes != null) {
           // Add only if there is a mapping for next nodes
           for (Integer nextNode : currChoiceNextNodes) {
+            // Skip cycles
+            if (nextNode == currChoice) {
+              continue;
+            }
             nodesToVisit.addLast(nextNode);
           }
         }
@@ -581,7 +680,7 @@ public class StateReducer extends ListenerAdapter {
   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
     if (stateReductionMode) {
       if (isInitialized) {
-        if (choiceCounter > choices.length - 1) {
+        if (choiceCounter <= 0 || choiceCounter > choices.length - 1) {
           // We do not compute the conflicts for the choice '-1'
           return;
         }
@@ -623,8 +722,8 @@ 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 (!visitedStateSet.contains(stateId)||
-                            (visitedStateSet.contains(stateId) && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
+                    if (vm.isNewState() ||
+                            (!vm.isNewState() && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
                       createBacktrackChoiceList(currentChoice, eventNumber);
                       // Break if a conflict is found!
                       break;