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;
91 public StateReducer(Config config, JPF jpf) {
92 debugMode = config.getBoolean("debug_state_transition", false);
93 stateReductionMode = config.getBoolean("activate_state_reduction", true);
95 out = new PrintWriter(System.out, true);
103 isBooleanCGFlipped = false;
104 vodGraphMap = new HashMap<>();
105 visitedStateSet = new HashSet<>();
107 initializeStateReduction();
110 private void initializeStateReduction() {
111 if (stateReductionMode) {
115 choiceUpperBound = 0;
117 isInitialized = false;
118 isResetAfterAnalysis = false;
119 cgMap = new HashMap<>();
120 readWriteFieldsMap = new HashMap<>();
121 backtrackMap = new HashMap<>();
122 backtrackSet = new HashSet<>();
123 conflictPairMap = new HashMap<>();
128 public void stateRestored(Search search) {
130 id = search.getStateId();
131 depth = search.getDepth();
132 transition = search.getTransition();
134 out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
135 " and depth: " + depth + "\n");
139 //--- the ones we are interested in
141 public void searchStarted(Search search) {
143 out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
148 public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
149 if (stateReductionMode) {
150 // Initialize with necessary information from the CG
151 if (nextCG instanceof IntChoiceFromSet) {
152 IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
153 // Check if CG has been initialized, otherwise initialize it
154 Integer[] cgChoices = icsCG.getAllChoices();
155 if (!isInitialized) {
156 // Get the upper bound from the last element of the choices
157 choiceUpperBound = cgChoices[cgChoices.length - 1];
158 isInitialized = true;
160 // Record the subsequent Integer CGs only until we hit the upper bound
161 if (!isResetAfterAnalysis && choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
162 // Update the choices of the first CG and add '-1'
163 if (choices == null) {
164 // Initialize backtrack set that stores all the explored backtrack lists
165 maxUpperBound = cgChoices.length;
166 // All the choices are always the same so we only need to update it once
167 choices = new Integer[cgChoices.length + 1];
168 System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
169 choices[choices.length - 1] = -1;
170 String firstChoiceListString = buildStringFromChoiceList(choices);
171 backtrackSet.add(firstChoiceListString);
173 icsCG.setNewValues(choices);
175 // Advance the current Integer CG
176 // This way we explore all the event numbers in the first pass
177 icsCG.advance(choices[choiceCounter]);
178 cgMap.put(icsCG, choices[choiceCounter]);
181 // Set done the subsequent CGs
182 // We only need n CGs (n is event numbers)
189 private void resetAllCGs() {
190 // Extract the event numbers that have backtrack lists
191 Set<Integer> eventSet = backtrackMap.keySet();
192 // Return if there is no conflict at all (highly unlikely)
193 if (eventSet.isEmpty()) {
196 // Reset every CG with the first backtrack lists
197 for (IntChoiceFromSet cg : cgMap.keySet()) {
198 int event = cgMap.get(cg);
199 LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
200 if (choiceLists != null && choiceLists.peekFirst() != null) {
201 Integer[] choiceList = choiceLists.removeFirst();
202 // Deploy the new choice list for this CG
203 cg.setNewValues(choiceList);
212 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
214 if (stateReductionMode) {
215 // Check the boolean CG and if it is flipped, we are resetting the analysis
216 if (currentCG instanceof BooleanChoiceGenerator) {
217 if (!isBooleanCGFlipped) {
218 isBooleanCGFlipped = true;
220 initializeStateReduction();
223 // Check every choice generated and make sure that all the available choices
224 // are chosen first before repeating the same choice of value twice!
225 if (currentCG instanceof IntChoiceFromSet) {
226 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
227 // Update the current pointer to the current set of choices
228 if (choices == null || choices != icsCG.getAllChoices()) {
230 choices = icsCG.getAllChoices();
231 // Reset a few things for the sub-graph
232 conflictPairMap.clear();
233 readWriteFieldsMap.clear();
236 // Traverse the sub-graphs
237 if (isResetAfterAnalysis) {
238 // Advance choice counter for sub-graphs
240 // Do this for every CG after finishing each backtrack list
241 if (icsCG.getNextChoice() == -1) {
242 int event = cgMap.get(icsCG);
243 LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
244 if (choiceLists != null && choiceLists.peekFirst() != null) {
245 Integer[] choiceList = choiceLists.removeFirst();
246 // Deploy the new choice list for this CG
247 icsCG.setNewValues(choiceList);
250 // Set done if this was the last backtrack list
255 // Update and reset the CG if needed (do this for the first time after the analysis)
256 if (!isResetAfterAnalysis && icsCG.getNextChoice() == -1) {
258 isResetAfterAnalysis = true;
264 public void updateVODGraph(int prevChoice, int currChoice) {
266 HashSet<Integer> choiceSet;
267 if (vodGraphMap.containsKey(prevChoice)) {
268 // If the key already exists, just retrieve it
269 choiceSet = vodGraphMap.get(prevChoice);
271 // Create a new entry
272 choiceSet = new HashSet<>();
273 vodGraphMap.put(prevChoice, choiceSet);
275 choiceSet.add(currChoice);
279 public void stateAdvanced(Search search) {
281 id = search.getStateId();
282 depth = search.getDepth();
283 transition = search.getTransition();
284 if (search.isNewState()) {
290 if (search.isEndState()) {
291 out.println("\n==> DEBUG: This is the last state!\n");
294 out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
295 " which is " + detail + " Transition: " + transition + "\n");
297 if (stateReductionMode) {
298 // Line 19 in the paper page 11 (see the heading note above)
299 stateId = search.getStateId();
300 if (visitedStateSet.contains(stateId)) {
301 // VOD graph is not updated if the "new" state has been seen earlier
304 // Add state ID into the visited state set
305 visitedStateSet.add(stateId);
307 int currChoice = choiceCounter - 1;
308 int prevChoice = currChoice - 1;
309 if (currChoice < 0) {
310 // Current choice has to be at least 0 (initial case can be -1)
313 // Current choice and previous choice values could be -1 (since we use -1 as the end-of-array condition)
314 int currChoiceValue = (choices[currChoice] == -1) ? 0 : choices[currChoice];
315 // When current choice is 0, previous choice could be -1
316 int prevChoiceValue = (prevChoice == -1) ? -1 : choices[prevChoice];
317 updateVODGraph(prevChoiceValue, currChoiceValue);
322 public void stateBacktracked(Search search) {
324 id = search.getStateId();
325 depth = search.getDepth();
326 transition = search.getTransition();
329 out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
330 " and depth: " + depth + "\n");
335 public void searchFinished(Search search) {
337 out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
341 // This class compactly stores Read and Write field sets
342 // We store the field name and its object ID
343 // Sharing the same field means the same field name and object ID
344 private class ReadWriteSet {
345 private HashMap<String, Integer> readSet;
346 private HashMap<String, Integer> writeSet;
348 public ReadWriteSet() {
349 readSet = new HashMap<>();
350 writeSet = new HashMap<>();
353 public void addReadField(String field, int objectId) {
354 readSet.put(field, objectId);
357 public void addWriteField(String field, int objectId) {
358 writeSet.put(field, objectId);
361 public boolean readFieldExists(String field) {
362 return readSet.containsKey(field);
365 public boolean writeFieldExists(String field) {
366 return writeSet.containsKey(field);
369 public int readFieldObjectId(String field) {
370 return readSet.get(field);
373 public int writeFieldObjectId(String field) {
374 return writeSet.get(field);
378 private void analyzeReadWriteAccesses(Instruction executedInsn, String fieldClass, int currentChoice) {
379 // Do the analysis to get Read and Write accesses to fields
381 // We already have an entry
382 if (readWriteFieldsMap.containsKey(choices[currentChoice])) {
383 rwSet = readWriteFieldsMap.get(choices[currentChoice]);
384 } else { // We need to create a new entry
385 rwSet = new ReadWriteSet();
386 readWriteFieldsMap.put(choices[currentChoice], rwSet);
388 int objectId = ((JVMFieldInstruction) executedInsn).getFieldInfo().getClassInfo().getClassObjectRef();
389 // Record the field in the map
390 if (executedInsn instanceof WriteInstruction) {
391 // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
392 for (String str : EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
393 if (fieldClass.startsWith(str)) {
397 rwSet.addWriteField(fieldClass, objectId);
398 } else if (executedInsn instanceof ReadInstruction) {
399 rwSet.addReadField(fieldClass, objectId);
403 private boolean recordConflictPair(int currentEvent, int eventNumber) {
404 HashSet<Integer> conflictSet;
405 if (!conflictPairMap.containsKey(currentEvent)) {
406 conflictSet = new HashSet<>();
407 conflictPairMap.put(currentEvent, conflictSet);
409 conflictSet = conflictPairMap.get(currentEvent);
411 // If this conflict has been recorded before, we return false because
412 // we don't want to service this backtrack point twice
413 if (conflictSet.contains(eventNumber)) {
416 // If it hasn't been recorded, then do otherwise
417 conflictSet.add(eventNumber);
421 private String buildStringFromChoiceList(Integer[] newChoiceList) {
423 // When we see a choice list shorter than the upper bound, e.g., [3,2] for choices 0,1,2, and 3,
424 // then we have to pad the beginning before we store it, because [3,2] actually means [0,1,3,2]
425 // First, calculate the difference between this choice list and the upper bound
426 // The actual list doesn't include '-1' at the end
427 int actualListLength = newChoiceList.length - 1;
428 int diff = maxUpperBound - actualListLength;
429 StringBuilder sb = new StringBuilder();
430 // Pad the beginning if necessary
431 for (int i = 0; i < diff; i++) {
434 // Then continue with the actual choice list
435 // We don't include the '-1' at the end
436 for (int i = 0; i < newChoiceList.length - 1; i++) {
437 sb.append(newChoiceList[i]);
439 return sb.toString();
442 private void checkAndAddBacktrackList(LinkedList<Integer[]> backtrackChoiceLists, Integer[] newChoiceList) {
444 String newChoiceListString = buildStringFromChoiceList(newChoiceList);
445 // Add only if we haven't seen this combination before
446 if (!backtrackSet.contains(newChoiceListString)) {
447 backtrackSet.add(newChoiceListString);
448 backtrackChoiceLists.addLast(newChoiceList);
452 private void createBacktrackChoiceList(int currentChoice, int conflictEventNumber) {
454 LinkedList<Integer[]> backtrackChoiceLists;
455 // Create a new list of choices for backtrack based on the current choice and conflicting event number
456 // If we have a conflict between 1 and 3, then we create the list {3, 1, 2, 4, 5} for backtrack
457 // The backtrack point is the CG for event number 1 and the list length is one less than the original list
458 // (originally of length 6) since we don't start from event number 0
459 if (!isResetAfterAnalysis) {
460 // Check if we have a list for this choice number
461 // If not we create a new one for it
462 if (!backtrackMap.containsKey(conflictEventNumber)) {
463 backtrackChoiceLists = new LinkedList<>();
464 backtrackMap.put(conflictEventNumber, backtrackChoiceLists);
466 backtrackChoiceLists = backtrackMap.get(conflictEventNumber);
468 int maxListLength = choiceUpperBound + 1;
469 int listLength = maxListLength - conflictEventNumber;
470 Integer[] newChoiceList = new Integer[listLength + 1];
471 // Put the conflicting event numbers first and reverse the order
472 newChoiceList[0] = choices[currentChoice];
473 newChoiceList[1] = choices[conflictEventNumber];
474 // Put the rest of the event numbers into the array starting from the minimum to the upper bound
475 for (int i = conflictEventNumber + 1, j = 2; j < listLength; i++) {
476 if (choices[i] != choices[currentChoice]) {
477 newChoiceList[j] = choices[i];
481 // Set the last element to '-1' as the end of the sequence
482 newChoiceList[newChoiceList.length - 1] = -1;
483 checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
484 // The start index for the recursion is always 1 (from the main branch)
485 } else { // This is a sub-graph
486 // There is a case/bug that after a re-initialization, currCG is not yet initialized
487 if (currCG != null) {
488 int backtrackListIndex = cgMap.get(currCG);
489 backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
490 int listLength = choices.length;
491 Integer[] newChoiceList = new Integer[listLength];
492 // Copy everything before the conflict number
493 for (int i = 0; i < conflictEventNumber; i++) {
494 newChoiceList[i] = choices[i];
496 // Put the conflicting events
497 newChoiceList[conflictEventNumber] = choices[currentChoice];
498 newChoiceList[conflictEventNumber + 1] = choices[conflictEventNumber];
500 for (int i = conflictEventNumber + 1, j = conflictEventNumber + 2; j < listLength - 1; i++) {
501 if (choices[i] != choices[currentChoice]) {
502 newChoiceList[j] = choices[i];
506 // Set the last element to '-1' as the end of the sequence
507 newChoiceList[newChoiceList.length - 1] = -1;
508 checkAndAddBacktrackList(backtrackChoiceLists, newChoiceList);
513 // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
514 private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
515 // Java and Groovy libraries
516 { "java", "org", "sun", "com", "gov", "groovy"};
517 private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
518 // Groovy library created fields
519 {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
521 "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
522 "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
523 private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
524 private final static String[] EXCLUDED_FIELDS_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
526 private boolean isFieldExcluded(String field) {
527 // Check against "starts-with" list
528 for(String str : EXCLUDED_FIELDS_STARTS_WITH_LIST) {
529 if (field.startsWith(str)) {
533 // Check against "ends-with" list
534 for(String str : EXCLUDED_FIELDS_ENDS_WITH_LIST) {
535 if (field.endsWith(str)) {
539 // Check against "contains" list
540 for(String str : EXCLUDED_FIELDS_CONTAINS_LIST) {
541 if (field.contains(str)) {
549 // This method checks whether a choice is reachable in the VOD graph from a reference choice
550 // This is a BFS search
551 private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
552 // Record visited choices as we search in the graph
553 HashSet<Integer> visitedChoice = new HashSet<>();
554 visitedChoice.add(referenceChoice);
555 LinkedList<Integer> nodesToVisit = new LinkedList<>();
556 // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
557 // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
558 if (vodGraphMap.containsKey(referenceChoice)) {
559 nodesToVisit.addAll(vodGraphMap.get(referenceChoice));
560 while(!nodesToVisit.isEmpty()) {
561 int currChoice = nodesToVisit.getFirst();
562 if (currChoice == checkedChoice) {
565 if (visitedChoice.contains(currChoice)) {
566 // If there is a loop then we don't find it
569 // Continue searching
570 visitedChoice.add(currChoice);
571 HashSet<Integer> currChoiceNextNodes = vodGraphMap.get(currChoice);
572 if (currChoiceNextNodes != null) {
573 // Add only if there is a mapping for next nodes
574 for (Integer nextNode : currChoiceNextNodes) {
575 nodesToVisit.addLast(nextNode);
584 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
585 if (stateReductionMode) {
587 if (choiceCounter > choices.length - 1) {
588 // We do not compute the conflicts for the choice '-1'
591 int currentChoice = choiceCounter - 1;
592 // Record accesses from executed instructions
593 if (executedInsn instanceof JVMFieldInstruction) {
594 // Analyze only after being initialized
595 String fieldClass = ((JVMFieldInstruction) executedInsn).getFieldInfo().getFullName();
596 // We don't care about libraries
597 if (!isFieldExcluded(fieldClass)) {
598 analyzeReadWriteAccesses(executedInsn, fieldClass, currentChoice);
601 // Analyze conflicts from next instructions
602 if (nextInsn instanceof JVMFieldInstruction) {
603 // The constructor is only called once when the object is initialized
604 // It does not have shared access with other objects
605 MethodInfo mi = nextInsn.getMethodInfo();
606 if (!mi.getName().equals("<init>")) {
607 String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
608 // We don't care about libraries
609 if (!isFieldExcluded(fieldClass)) {
610 // Check for conflict (go backward from currentChoice and get the first conflict)
611 // If the current event has conflicts with multiple events, then these will be detected
612 // one by one as this recursively checks backward when backtrack set is revisited and executed.
613 for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
614 // Skip if this event number does not have any Read/Write set
615 if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
618 ReadWriteSet rwSet = readWriteFieldsMap.get(choices[eventNumber]);
619 int currObjId = ((JVMFieldInstruction) nextInsn).getFieldInfo().getClassInfo().getClassObjectRef();
620 // 1) Check for conflicts with Write fields for both Read and Write instructions
621 if (((nextInsn instanceof WriteInstruction || nextInsn instanceof ReadInstruction) &&
622 rwSet.writeFieldExists(fieldClass) && rwSet.writeFieldObjectId(fieldClass) == currObjId) ||
623 (nextInsn instanceof WriteInstruction && rwSet.readFieldExists(fieldClass) &&
624 rwSet.readFieldObjectId(fieldClass) == currObjId)) {
625 // We do not record and service the same backtrack pair/point twice!
626 // If it has been serviced before, we just skip this
627 if (recordConflictPair(currentChoice, eventNumber)) {
628 // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
629 if (!visitedStateSet.contains(stateId)||
630 (visitedStateSet.contains(stateId) && isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1]))) {
631 createBacktrackChoiceList(currentChoice, eventNumber);
632 // Break if a conflict is found!