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.LocalVariableInstruction;
27 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
28 import gov.nasa.jpf.vm.bytecode.StoreInstruction;
29 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
31 import java.io.PrintWriter;
36 * Listener using data flow analysis to find conflicts between smartApps.
39 public class ConflictTracker extends ListenerAdapter {
41 private final PrintWriter out;
42 private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
43 private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
44 private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
45 private final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
46 private HashSet<NameValuePair> tempSetSet = new HashSet<NameValuePair>();
48 private long startTime;
49 private Node parentNode = new Node(-2);
50 private String operation;
51 private String detail;
54 private boolean conflictFound = false;
55 private boolean isSet = false;
58 public ConflictTracker(Config config, JPF jpf) {
59 out = new PrintWriter(System.out, true);
61 String[] conflictVars = config.getStringArray("variables");
62 // We are not tracking anything if it is null
63 if (conflictVars != null) {
64 for (String var : conflictVars) {
68 String[] apps = config.getStringArray("apps");
69 // We are not tracking anything if it is null
71 for (String var : apps) {
75 String[] manualClasses = config.getStringArray("manualClasses");
76 // We are not tracking anything if it is null
77 if (manualClasses != null) {
78 for (String var : manualClasses) {
83 // Timeout input from config is in minutes, so we need to convert into millis
84 timeout = config.getInt("timeout", 0) * 60 * 1000;
85 startTime = System.currentTimeMillis();
88 boolean propagateTheChange(Node currentNode) {
89 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
91 while(!changed.isEmpty()) {
92 // Get the first element of HashSet and remove it from the changed set
93 Node nodeToProcess = changed.iterator().next();
94 changed.remove(nodeToProcess);
96 // Update the sets, store the outSet to temp before its changes
97 boolean isChanged = updateSets(nodeToProcess);
99 // Check for a conflict
100 if (checkForConflict(nodeToProcess))
103 // Checking if the out set has changed or not(Add its successors to the change list!)
105 for (Node i : nodeToProcess.getSuccessors()) {
106 if (!changed.contains(i))
115 boolean setOutSet(Node currentNode) {
116 boolean isChanged = false;
118 // Update based on inSet
119 for (NameValuePair i : currentNode.getInSet()) {
120 if (!currentNode.getOutSet().contains(i)) {
122 currentNode.getOutSet().add(i);
126 // Overwrite based on setSet
127 for (NameValuePair i : currentNode.getSetSet()) {
128 if (!currentNode.getOutSet().contains(i))
131 currentNode.getOutSet().remove(i);
132 currentNode.getOutSet().add(i);
138 //Is it ok to point to the same object? (Not passed by value?)
139 void setInSet(Node currentNode) {
140 for (Node i : currentNode.getPredecessors()) {
141 currentNode.getInSet().addAll(i.getOutSet());
145 boolean checkForConflict(Node currentNode) {
146 HashMap<String, String> valueMap = new HashMap<String, String>();
147 HashMap<String, Boolean> isManualMap = new HashMap<String, Boolean>();
149 for (NameValuePair i : currentNode.getOutSet()) {
150 if (valueMap.containsKey(i.getVarName())) {
151 if (!(isManualMap.get(i.getVarName())&&(i.getIsManual())))
152 if (!(valueMap.get(i.getVarName()).equals(i.getValue())))
155 valueMap.put(i.getVarName(), i.getValue());
156 isManualMap.put(i.getVarName(), i.getIsManual());
163 boolean updateSets(Node currentNode) {
164 // Set input set according to output set of pred states of current state
165 setInSet(currentNode);
167 // Set outSet according to inSet, and setSet of current node, check if there is a change
168 return setOutSet(currentNode);
173 HashSet<Node> predecessors = new HashSet<Node>();
174 HashSet<Node> successors = new HashSet<Node>();
175 HashSet<NameValuePair> inSet = new HashSet<NameValuePair>();
176 HashSet<NameValuePair> setSet = new HashSet<NameValuePair>();
177 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
183 void addPredecessor(Node node) {
184 predecessors.add(node);
187 void addSuccessor(Node node) {
188 successors.add(node);
191 void setSetSet(HashSet<NameValuePair> setSet) {
192 for (NameValuePair i : setSet) {
193 this.setSet.add(new NameValuePair(i.getAppNum(), i.getValue(), i.getVarName(), i.getIsManual()));
201 HashSet<Node> getPredecessors() {
205 HashSet<Node> getSuccessors() {
209 HashSet<NameValuePair> getInSet() {
213 HashSet<NameValuePair> getSetSet() {
217 HashSet<NameValuePair> getOutSet() {
222 static class NameValuePair {
228 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
229 this.appNum = appNum;
231 this.varName = varName;
232 this.isManual = isManual;
235 void setAppNum(Integer appNum) {
236 this.appNum = appNum;
239 void setValue(String value) {
243 void setVarName(String varName) {
244 this.varName = varName;
247 void setIsManual(String varName) {
248 this.isManual = isManual;
251 Integer getAppNum() {
259 String getVarName() {
263 boolean getIsManual() {
268 public boolean equals(Object o) {
269 if (o instanceof NameValuePair) {
270 NameValuePair other = (NameValuePair) o;
271 if (varName.equals(other.getVarName()))
272 return appNum.equals(other.getAppNum());
278 public int hashCode() {
279 return appNum.hashCode() * 31 + varName.hashCode();
284 public void stateRestored(Search search) {
285 id = search.getStateId();
286 depth = search.getDepth();
287 operation = "restored";
290 out.println("The state is restored to state with id: "+id+", depth: "+depth);
292 // Update the parent node
293 if (nodes.containsKey(id)) {
294 parentNode = nodes.get(id);
296 parentNode = new Node(id);
301 public void searchStarted(Search search) {
302 out.println("----------------------------------- search started");
307 public void stateAdvanced(Search search) {
308 String theEnd = null;
309 id = search.getStateId();
310 depth = search.getDepth();
311 operation = "forward";
313 // Add the node to the list of nodes
314 nodes.put(id, new Node(id));
315 Node currentNode = nodes.get(id);
317 // Update the setSet for this new node
319 currentNode.setSetSet(tempSetSet);
320 tempSetSet = new HashSet<NameValuePair>();
324 if (search.isNewState()) {
330 if (search.isEndState()) {
331 out.println("This is the last state!");
335 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
337 // Updating the predecessors for this node
338 // Check if parent node is already in successors of the current node or not
339 if (!(currentNode.getPredecessors().contains(parentNode)))
340 currentNode.addPredecessor(parentNode);
342 // Update the successors for this node
343 // Check if current node is already in successors of the parent node or not
344 if (!(parentNode.getSuccessors().contains(currentNode)))
345 parentNode.addSuccessor(currentNode);
347 // Update the sets, check if the outSet is changed or not
348 boolean isChanged = updateSets(currentNode);
350 // Check for a conflict
351 conflictFound = checkForConflict(currentNode);
353 // Check if the outSet of this state has changed, update all of its successors' sets if any
355 conflictFound = conflictFound || propagateTheChange(currentNode);
357 // Update the parent node
358 if (nodes.containsKey(id)) {
359 parentNode = nodes.get(id);
361 parentNode = new Node(id);
366 public void stateBacktracked(Search search) {
367 id = search.getStateId();
368 depth = search.getDepth();
369 operation = "backtrack";
372 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
374 // Update the parent node
375 if (nodes.containsKey(id)) {
376 parentNode = nodes.get(id);
378 parentNode = new Node(id);
383 public void searchFinished(Search search) {
384 out.println("----------------------------------- search finished");
387 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
391 frame = ti.getTopFrame();
393 if ((inst instanceof JVMLocalVariableInstruction) ||
394 (inst instanceof JVMFieldInstruction))
396 if (frame.getTopPos() < 0)
400 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
402 return(decodeValue(type, lo, hi));
405 if (inst instanceof JVMArrayElementInstruction)
406 return(getArrayValue(ti, type));
411 private final static String decodeValue(byte type, int lo, int hi) {
413 case Types.T_ARRAY: return(null);
414 case Types.T_VOID: return(null);
416 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
417 case Types.T_BYTE: return(String.valueOf(lo));
418 case Types.T_CHAR: return(String.valueOf((char) lo));
419 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
420 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
421 case Types.T_INT: return(String.valueOf(lo));
422 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
423 case Types.T_SHORT: return(String.valueOf(lo));
425 case Types.T_REFERENCE:
426 ElementInfo ei = VM.getVM().getHeap().get(lo);
430 ClassInfo ci = ei.getClassInfo();
434 if (ci.getName().equals("java.lang.String"))
435 return('"' + ei.asString() + '"');
437 return(ei.toString());
440 System.err.println("Unknown type: " + type);
445 private String getArrayValue(ThreadInfo ti, byte type) {
449 frame = ti.getTopFrame();
451 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
453 return(decodeValue(type, lo, hi));
456 private byte getType(ThreadInfo ti, Instruction inst) {
461 frame = ti.getTopFrame();
462 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
463 return (Types.T_REFERENCE);
468 if (inst instanceof JVMLocalVariableInstruction) {
469 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
470 } else if (inst instanceof JVMFieldInstruction){
471 fi = ((JVMFieldInstruction) inst).getFieldInfo();
475 if (inst instanceof JVMArrayElementInstruction) {
476 return (getTypeFromInstruction(inst));
480 return (Types.T_VOID);
483 return (decodeType(type));
486 private final static byte getTypeFromInstruction(Instruction inst) {
487 if (inst instanceof JVMArrayElementInstruction)
488 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
490 return(Types.T_VOID);
493 private final static byte decodeType(String type) {
494 if (type.charAt(0) == '?'){
495 return(Types.T_REFERENCE);
497 return Types.getBuiltinType(type);
501 // Find the variable writer
502 // It should be one of the apps listed in the .jpf file
503 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
504 // Start looking from the top of the stack backward
505 for(int i=sfList.size()-1; i>=0; i--) {
506 MethodInfo mi = sfList.get(i).getMethodInfo();
507 if(!mi.isJPFInternal()) {
508 String method = mi.getStackTraceName();
509 // Check against the writers in the writerSet
510 for(String writer : writerSet) {
511 if (method.contains(writer)) {
522 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
523 // Instantiate timeoutTimer
525 if (System.currentTimeMillis() - startTime > timeout) {
526 StringBuilder sbTimeOut = new StringBuilder();
527 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
528 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
529 ti.setNextPC(nextIns);
534 StringBuilder sb = new StringBuilder();
535 sb.append("Conflict found between two apps!");
536 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
537 ti.setNextPC(nextIns);
538 } else if (executedInsn instanceof WriteInstruction) {
539 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
540 for(String var : conflictSet) {
542 if (varId.contains(var)) {
544 byte type = getType(ti, executedInsn);
545 String value = getValue(ti, executedInsn, type);
546 String writer = getWriter(ti.getStack(), appSet);
547 boolean isManual = false;
548 // Just return if the writer is not one of the listed apps in the .jpf file
552 if (getWriter(ti.getStack(), manualSet) != null)
555 // Update the temporary Set set.
556 if (writer.equals("App1"))
557 tempSetSet.add(new NameValuePair(1, value, var, isManual));
558 else if (writer.equals("App2"))
559 tempSetSet.add(new NameValuePair(2, value, var, isManual));