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;
30 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 create a graph G
43 * (i.e., visible operation dependency graph)
44 * that maps inter-related threads/sub-programs that trigger state changes.
45 * The key to this approach is that we evaluate graph G in every iteration/recursion to
46 * only update the backtrack sets of the threads/sub-programs that are reachable in graph G
47 * from the currently running thread/sub-program.
49 public class StateReducer extends ListenerAdapter {
52 private boolean debugMode;
53 private boolean stateReductionMode;
54 private final PrintWriter out;
55 volatile private String detail;
56 volatile private int depth;
57 volatile private int id;
58 Transition transition;
60 // State reduction fields
61 private Integer[] choices;
62 private IntChoiceFromSet currCG;
63 private int choiceCounter;
64 private Integer choiceUpperBound;
65 private Integer maxUpperBound;
66 private boolean isInitialized;
67 private boolean isResetAfterAnalysis;
68 private boolean isBooleanCGFlipped;
69 private HashMap<IntChoiceFromSet, Integer> cgMap;
70 // Record the mapping between event number and field accesses (Read and Write)
71 private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;
72 // The following is the backtrack map (set) that stores all the backtrack information
73 // e.g., event number 1 can have two backtrack sequences: {3,1,2,4,...} and {2,1,3,4,...}
74 private HashMap<Integer, LinkedList<Integer[]>> backtrackMap;
75 // Stores explored backtrack lists in the form of HashSet of Strings
76 private HashSet<String> backtrackSet;
77 private HashMap<Integer, HashSet<Integer>> conflictPairMap;
78 // Map choicelist with start index
79 // private HashMap<Integer[],Integer> choiceListStartIndexMap;
81 // Map that represents graph G
82 // (i.e., visible operation dependency graph (VOD Graph)
83 private HashMap<Integer, HashSet<Integer>> vodGraphMap;
84 // Set that represents hash table H
85 // (i.e., hash table that records encountered states)
86 // VOD graph is updated when the state has not yet been seen
87 private HashSet<Integer> visitedStateSet;
90 // Previous choice number
91 private int prevChoiceValue;
93 public StateReducer(Config config, JPF jpf) {
94 debugMode = config.getBoolean("debug_state_transition", false);
95 stateReductionMode = config.getBoolean("activate_state_reduction", true);
97 out = new PrintWriter(System.out, true);
105 isBooleanCGFlipped = false;
106 vodGraphMap = new HashMap<>();
107 visitedStateSet = new HashSet<>();
109 prevChoiceValue = -1;
110 initializeStateReduction();
113 private void initializeStateReduction() {
114 if (stateReductionMode) {
118 choiceUpperBound = 0;
120 isInitialized = false;
121 isResetAfterAnalysis = false;
122 cgMap = new HashMap<>();
123 readWriteFieldsMap = new HashMap<>();
124 backtrackMap = new HashMap<>();
125 backtrackSet = new HashSet<>();
126 conflictPairMap = new HashMap<>();
131 public void stateRestored(Search search) {
133 id = search.getStateId();
134 depth = search.getDepth();
135 transition = search.getTransition();
137 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
138 " and depth: " + depth + "\n");
142 //--- the ones we are interested in
144 public void searchStarted(Search search) {
146 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
151 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
152 if (stateReductionMode) {
153 // Initialize with necessary information from the CG
154 if (nextCG instanceof IntChoiceFromSet) {
155 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
156 // Check if CG has been initialized, otherwise initialize it
157 Integer[] cgChoices = icsCG.getAllChoices();
158 if (!isInitialized) {
159 // Get the upper bound from the last element of the choices
160 choiceUpperBound = cgChoices[cgChoices.length - 1];
161 isInitialized = true;
163 // Record the subsequent Integer CGs only until we hit the upper bound
164 if (!isResetAfterAnalysis && choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
165 // Update the choices of the first CG and add '-1'
166 if (choices == null) {
167 // Initialize backtrack set that stores all the explored backtrack lists
168 maxUpperBound = cgChoices.length;
169 // All the choices are always the same so we only need to update it once
170 choices = new Integer[cgChoices.length + 1];
171 System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
172 choices[choices.length - 1] = -1;
173 String firstChoiceListString = buildStringFromChoiceList(choices);
174 backtrackSet.add(firstChoiceListString);
176 icsCG.setNewValues(choices);
178 // Advance the current Integer CG
179 // This way we explore all the event numbers in the first pass
180 icsCG.advance(choices[choiceCounter]);
181 cgMap.put(icsCG, choices[choiceCounter]);
184 // Set done the subsequent CGs
185 // We only need n CGs (n is event numbers)
192 private void resetAllCGs() {
193 // Extract the event numbers that have backtrack lists
194 Set<Integer> eventSet = backtrackMap.keySet();
195 // Return if there is no conflict at all (highly unlikely)
196 if (eventSet.isEmpty()) {
199 // Reset every CG with the first backtrack lists
200 for (IntChoiceFromSet cg : cgMap.keySet()) {
201 int event = cgMap.get(cg);
202 LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
203 if (choiceLists != null && choiceLists.peekFirst() != null) {
204 Integer[] choiceList = choiceLists.removeFirst();
205 // Deploy the new choice list for this CG
206 cg.setNewValues(choiceList);
215 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
217 if (stateReductionMode) {
218 // Check the boolean CG and if it is flipped, we are resetting the analysis
219 if (currentCG instanceof BooleanChoiceGenerator) {
220 if (!isBooleanCGFlipped) {
221 isBooleanCGFlipped = true;
223 initializeStateReduction();
226 // Check every choice generated and make sure that all the available choices
227 // are chosen first before repeating the same choice of value twice!
228 if (currentCG instanceof IntChoiceFromSet) {
229 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
230 // Update the current pointer to the current set of choices
231 if (choices == null || choices != icsCG.getAllChoices()) {
233 choices = icsCG.getAllChoices();
234 // Reset a few things for the sub-graph
235 conflictPairMap.clear();
236 readWriteFieldsMap.clear();
239 // Traverse the sub-graphs
240 if (isResetAfterAnalysis) {
241 // Advance choice counter for sub-graphs
243 // Do this for every CG after finishing each backtrack list
244 if (icsCG.getNextChoice() == -1 || visitedStateSet.contains(stateId)) {
245 int event = cgMap.get(icsCG);
246 LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
247 if (choiceLists != null && choiceLists.peekFirst() != null) {
248 Integer[] choiceList = choiceLists.removeFirst();
249 // Deploy the new choice list for this CG
250 icsCG.setNewValues(choiceList);
253 // Set done if this was the last backtrack list
258 // Update and reset the CG if needed (do this for the first time after the analysis)
259 if (!isResetAfterAnalysis && icsCG.getNextChoice() == -1) {
261 isResetAfterAnalysis = true;
267 public void updateVODGraph(int prevChoice, int currChoice) {
269 HashSet<Integer> choiceSet;
270 if (vodGraphMap.containsKey(prevChoice)) {
271 // If the key already exists, just retrieve it
272 choiceSet = vodGraphMap.get(prevChoice);
274 // Create a new entry
275 choiceSet = new HashSet<>();
276 vodGraphMap.put(prevChoice, choiceSet);
278 choiceSet.add(currChoice);
282 public void stateAdvanced(Search search) {
284 id = search.getStateId();
285 depth = search.getDepth();
286 transition = search.getTransition();
287 if (search.isNewState()) {
293 if (search.isEndState()) {
294 out.println("\n==> DEBUG: This is the last state!\n");
297 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
298 " which is " + detail + " Transition: " + transition + "\n");
300 if (stateReductionMode) {
302 int currChoice = choiceCounter - 1;
303 if (currChoice < 0 || currChoice > choices.length - 1 || choices[currChoice] == -1 || prevChoiceValue == choices[currChoice]) {
304 // Handle all corner cases (e.g., out of bound values)
307 // When current choice is 0, previous choice could be -1
308 updateVODGraph(prevChoiceValue, choices[currChoice]);
309 // Current choice becomes previous choice in the next iteration
310 prevChoiceValue = choices[currChoice];
311 // Line 19 in the paper page 11 (see the heading note above)
312 stateId = search.getStateId();
313 // Add state ID into the visited state set
314 visitedStateSet.add(stateId);
319 public void stateBacktracked(Search search) {
321 id = search.getStateId();
322 depth = search.getDepth();
323 transition = search.getTransition();
326 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
327 " and depth: " + depth + "\n");
332 public void searchFinished(Search search) {
334 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
338 // This class compactly stores Read and Write field sets
339 // We store the field name and its object ID
340 // Sharing the same field means the same field name and object ID
341 private class ReadWriteSet {
342 private HashMap<String, Integer> readSet;
343 private HashMap<String, Integer> writeSet;
345 public ReadWriteSet() {
346 readSet = new HashMap<>();
347 writeSet = new HashMap<>();
350 public void addReadField(String field, int objectId) {
351 readSet.put(field, objectId);
354 public void addWriteField(String field, int objectId) {
355 writeSet.put(field, objectId);
358 public boolean readFieldExists(String field) {
359 return readSet.containsKey(field);
362 public boolean writeFieldExists(String field) {
363 return writeSet.containsKey(field);
366 public int readFieldObjectId(String field) {
367 return readSet.get(field);
370 public int writeFieldObjectId(String field) {
371 return writeSet.get(field);
375 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
376 // Do the analysis to get Read and Write accesses to fields
378 // We already have an entry
379 if (readWriteFieldsMap.containsKey(choices[currentChoice])) {
380 rwSet = readWriteFieldsMap.get(choices[currentChoice]);
381 } else { // We need to create a new entry
382 rwSet = new ReadWriteSet();
383 readWriteFieldsMap.put(choices[currentChoice], rwSet);
385 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
386 // Record the field in the map
387 if (executedInsn instanceof WriteInstruction) {
388 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
389 for (String str : EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
390 if (fieldClass.startsWith(str)) {
394 rwSet.addWriteField(fieldClass, objectId);
395 } else if (executedInsn instanceof ReadInstruction) {
396 rwSet.addReadField(fieldClass, objectId);
400 private boolean recordConflictPair(int currentEvent, int eventNumber) {
401 HashSet<Integer> conflictSet;
402 if (!conflictPairMap.containsKey(currentEvent)) {
403 conflictSet = new HashSet<>();
404 conflictPairMap.put(currentEvent, conflictSet);
406 conflictSet = conflictPairMap.get(currentEvent);
408 // If this conflict has been recorded before, we return false because
409 // we don't want to service this backtrack point twice
410 if (conflictSet.contains(eventNumber)) {
413 // If it hasn't been recorded, then do otherwise
414 conflictSet.add(eventNumber);
418 private String buildStringFromChoiceList(Integer[] newChoiceList) {
420 // When we see a choice list shorter than the upper bound, e.g., [3,2] for choices 0,1,2, and 3,
421 // then we have to pad the beginning before we store it, because [3,2] actually means [0,1,3,2]
422 // First, calculate the difference between this choice list and the upper bound
423 // The actual list doesn't include '-1' at the end
424 int actualListLength = newChoiceList.length - 1;
425 int diff = maxUpperBound - actualListLength;
426 StringBuilder sb = new StringBuilder();
427 // Pad the beginning if necessary
428 for (int i = 0; i < diff; i++) {
431 // Then continue with the actual choice list
432 // We don't include the '-1' at the end
433 for (int i = 0; i < newChoiceList.length - 1; i++) {
434 sb.append(newChoiceList[i]);
436 return sb.toString();
439 private void checkAndAddBacktrackList(LinkedList<Integer[]> backtrackChoiceLists, Integer[] newChoiceList) {
441 String newChoiceListString = buildStringFromChoiceList(newChoiceList);
442 // Add only if we haven't seen this combination before
443 if (!backtrackSet.contains(newChoiceListString)) {
444 backtrackSet.add(newChoiceListString);
445 backtrackChoiceLists.addLast(newChoiceList);
449 private void createBacktrackChoiceList(int currentChoice, int conflictEventNumber) {
451 LinkedList<Integer[]> backtrackChoiceLists;
452 // Create a new list of choices for backtrack based on the current choice and conflicting event number
453 // If we have a conflict between 1 and 3, then we create the list {3, 1, 2, 4, 5} for backtrack
454 // The backtrack point is the CG for event number 1 and the list length is one less than the original list
455 // (originally of length 6) since we don't start from event number 0
456 if (!isResetAfterAnalysis) {
457 // Check if we have a list for this choice number
458 // If not we create a new one for it
459 if (!backtrackMap.containsKey(conflictEventNumber)) {
460 backtrackChoiceLists = new LinkedList<>();
461 backtrackMap.put(conflictEventNumber, backtrackChoiceLists);
463 backtrackChoiceLists = backtrackMap.get(conflictEventNumber);
465 int maxListLength = choiceUpperBound + 1;
466 int listLength = maxListLength - conflictEventNumber;
467 Integer[] newChoiceList = new Integer[listLength + 1];
468 // Put the conflicting event numbers first and reverse the order
469 newChoiceList[0] = choices[currentChoice];
470 newChoiceList[1] = choices[conflictEventNumber];
471 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
472 for (int i = conflictEventNumber + 1, j = 2; j < listLength; i++) {
473 if (choices[i] != choices[currentChoice]) {
474 newChoiceList[j] = choices[i];
478 // Set the last element to '-1' as the end of the sequence
479 newChoiceList[newChoiceList.length - 1] = -1;
480 checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
481 // The start index for the recursion is always 1 (from the main branch)
482 } else { // This is a sub-graph
483 // There is a case/bug that after a re-initialization, currCG is not yet initialized
484 if (currCG != null) {
485 int backtrackListIndex = cgMap.get(currCG);
486 backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
487 int listLength = choices.length;
488 Integer[] newChoiceList = new Integer[listLength];
489 // Copy everything before the conflict number
490 for (int i = 0; i < conflictEventNumber; i++) {
491 newChoiceList[i] = choices[i];
493 // Put the conflicting events
494 newChoiceList[conflictEventNumber] = choices[currentChoice];
495 newChoiceList[conflictEventNumber + 1] = choices[conflictEventNumber];
497 for (int i = conflictEventNumber + 1, j = conflictEventNumber + 2; j < listLength - 1; i++) {
498 if (choices[i] != choices[currentChoice]) {
499 newChoiceList[j] = choices[i];
503 // Set the last element to '-1' as the end of the sequence
504 newChoiceList[newChoiceList.length - 1] = -1;
505 checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
510 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
511 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
512 // Java and Groovy libraries
513 { "java", "org", "sun", "com", "gov", "groovy"};
514 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
515 // Groovy library created fields
516 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
518 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
519 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
520 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
521 private final static String[] EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
523 private boolean isFieldExcluded(String field) {
524 // Check against "starts-with" list
525 for(String str : EXCLUDED_FIELDS_STARTS_WITH_LIST) {
526 if (field.startsWith(str)) {
530 // Check against "ends-with" list
531 for(String str : EXCLUDED_FIELDS_ENDS_WITH_LIST) {
532 if (field.endsWith(str)) {
536 // Check against "contains" list
537 for(String str : EXCLUDED_FIELDS_CONTAINS_LIST) {
538 if (field.contains(str)) {
546 // This method checks whether a choice is reachable in the VOD graph from a reference choice
547 // This is a BFS search
548 private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
549 // Record visited choices as we search in the graph
550 HashSet<Integer> visitedChoice = new HashSet<>();
551 visitedChoice.add(referenceChoice);
552 LinkedList<Integer> nodesToVisit = new LinkedList<>();
553 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
554 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
555 if (vodGraphMap.containsKey(referenceChoice)) {
556 nodesToVisit.addAll(vodGraphMap.get(referenceChoice));
557 while(!nodesToVisit.isEmpty()) {
558 int currChoice = nodesToVisit.getFirst();
559 if (currChoice == checkedChoice) {
562 if (visitedChoice.contains(currChoice)) {
563 // If there is a loop then we don't find it
566 // Continue searching
567 visitedChoice.add(currChoice);
568 HashSet<Integer> currChoiceNextNodes = vodGraphMap.get(currChoice);
569 if (currChoiceNextNodes != null) {
570 // Add only if there is a mapping for next nodes
571 for (Integer nextNode : currChoiceNextNodes) {
572 nodesToVisit.addLast(nextNode);
581 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
582 if (stateReductionMode) {
584 if (choiceCounter > choices.length - 1) {
585 // We do not compute the conflicts for the choice '-1'
588 int currentChoice = choiceCounter - 1;
589 // Record accesses from executed instructions
590 if (executedInsn instanceof JVMFieldInstruction) {
591 // Analyze only after being initialized
592 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
593 // We don't care about libraries
594 if (!isFieldExcluded(fieldClass)) {
595 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
598 // Analyze conflicts from next instructions
599 if (nextInsn instanceof JVMFieldInstruction) {
600 // The constructor is only called once when the object is initialized
601 // It does not have shared access with other objects
602 MethodInfo mi = nextInsn.getMethodInfo();
603 if (!mi.getName().equals("<init>")) {
604 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
605 // We don't care about libraries
606 if (!isFieldExcluded(fieldClass)) {
607 // Check for conflict (go backward from currentChoice and get the first conflict)
608 // If the current event has conflicts with multiple events, then these will be detected
609 // one by one as this recursively checks backward when backtrack set is revisited and executed.
610 for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
611 // Skip if this event number does not have any Read/Write set
612 if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
615 ReadWriteSet rwSet = readWriteFieldsMap.get(choices[eventNumber]);
616 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
617 // 1) Check for conflicts with Write fields for both Read and Write instructions
618 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
619 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
620 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
621 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
622 // We do not record and service the same backtrack pair/point twice!
623 // If it has been serviced before, we just skip this
624 if (recordConflictPair(currentChoice, eventNumber)) {
625 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
626 if (!visitedStateSet.contains(stateId)||
627 (visitedStateSet.contains(stateId) && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
628 createBacktrackChoiceList(currentChoice, eventNumber);
629 // Break if a conflict is found!