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;
52 private String errorMessage;
55 private boolean conflictFound = false;
56 private boolean isSet = false;
57 private boolean manual = false;
60 public ConflictTracker(Config config, JPF jpf) {
61 out = new PrintWriter(System.out, true);
63 String[] conflictVars = config.getStringArray("variables");
64 // We are not tracking anything if it is null
65 if (conflictVars != null) {
66 for (String var : conflictVars) {
70 String[] apps = config.getStringArray("apps");
71 // We are not tracking anything if it is null
73 for (String var : apps) {
77 String[] manualClasses = config.getStringArray("manualClasses");
78 // We are not tracking anything if it is null
79 if (manualClasses != null) {
80 for (String var : manualClasses) {
85 // Timeout input from config is in minutes, so we need to convert into millis
86 timeout = config.getInt("timeout", 0) * 60 * 1000;
87 startTime = System.currentTimeMillis();
90 boolean propagateTheChange(Node currentNode) {
91 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
93 while(!changed.isEmpty()) {
94 // Get the first element of HashSet and remove it from the changed set
95 Node nodeToProcess = changed.iterator().next();
96 changed.remove(nodeToProcess);
98 // Update the sets, store the outSet to temp before its changes
99 boolean isChanged = updateSets(nodeToProcess);
101 // Check for a conflict
102 if (checkForConflict(nodeToProcess))
105 // Checking if the out set has changed or not(Add its successors to the change list!)
107 for (Node i : nodeToProcess.getSuccessors()) {
108 if (!changed.contains(i))
117 boolean setOutSet(Node currentNode) {
118 Integer prevSize = currentNode.getOutSet().size();
120 // Update based on setSet
121 for (NameValuePair i : currentNode.getSetSet()) {
122 if (currentNode.getOutSet().contains(i))
123 currentNode.getOutSet().remove(i);
124 currentNode.getOutSet().add(i);
128 currentNode.getOutSet().addAll(currentNode.getInSet());
130 // Check if the outSet is changed
131 if (!prevSize.equals(currentNode.getOutSet().size()))
137 void setInSet(Node currentNode) {
138 for (Node i : currentNode.getPredecessors()) {
139 currentNode.getInSet().addAll(i.getOutSet());
143 boolean checkForConflict(Node currentNode) {
144 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
145 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
147 for (NameValuePair i : currentNode.getSetSet()) {
148 if (i.getIsManual()) // Manual input: we have no conflict
151 valueMap.put(i.getVarName(), i.getValue());
152 if (writerMap.containsKey(i.getVarName()))
153 writerMap.put(i.getVarName(), i.getAppNum()+writerMap.get(i.getVarName())); // We have two writers?
155 writerMap.put(i.getVarName(), i.getAppNum());
158 // Comparing the inSet and setSet to find the conflict
159 for (NameValuePair i : currentNode.getInSet()) {
160 if (valueMap.containsKey(i.getVarName())) {
161 String value = valueMap.get(i.getVarName());
162 Integer writer = writerMap.get(i.getVarName());
163 if ((value != null)&&(writer != null)) {
164 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
165 errorMessage = "Conflict found between the two apps. App"+i.getAppNum()+" has written the value: "+i.getValue()+
166 " to the variable: "+i.getVarName()+" while App"+writerMap.get(i.getVarName())+" is overwriting the value: "
167 +valueMap.get(i.getVarName())+" to the same variable!";
177 boolean updateSets(Node currentNode) {
178 // Set input set according to output set of pred states of current state
179 setInSet(currentNode);
181 // Set outSet according to inSet, and setSet of current node, check if there is a change
182 return setOutSet(currentNode);
187 HashSet<Node> predecessors = new HashSet<Node>();
188 HashSet<Node> successors = new HashSet<Node>();
189 HashSet<NameValuePair> inSet = new HashSet<NameValuePair>();
190 HashSet<NameValuePair> setSet = new HashSet<NameValuePair>();
191 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
197 void addPredecessor(Node node) {
198 predecessors.add(node);
201 void addSuccessor(Node node) {
202 successors.add(node);
205 void setSetSet(HashSet<NameValuePair> setSet, boolean isManual) {
207 this.setSet = new HashSet<NameValuePair>();
208 for (NameValuePair i : setSet) {
209 this.setSet.add(new NameValuePair(i.getAppNum(), i.getValue(), i.getVarName(), i.getIsManual()));
217 HashSet<Node> getPredecessors() {
221 HashSet<Node> getSuccessors() {
225 HashSet<NameValuePair> getInSet() {
229 HashSet<NameValuePair> getSetSet() {
233 HashSet<NameValuePair> getOutSet() {
238 static class NameValuePair {
244 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
245 this.appNum = appNum;
247 this.varName = varName;
248 this.isManual = isManual;
251 void setAppNum(Integer appNum) {
252 this.appNum = appNum;
255 void setValue(String value) {
259 void setVarName(String varName) {
260 this.varName = varName;
263 void setIsManual(String varName) {
264 this.isManual = isManual;
267 Integer getAppNum() {
275 String getVarName() {
279 boolean getIsManual() {
284 public boolean equals(Object o) {
285 if (o instanceof NameValuePair) {
286 NameValuePair other = (NameValuePair) o;
287 if (varName.equals(other.getVarName()))
288 return appNum.equals(other.getAppNum());
294 public int hashCode() {
295 return appNum.hashCode() * 31 + varName.hashCode();
300 public void stateRestored(Search search) {
301 id = search.getStateId();
302 depth = search.getDepth();
303 operation = "restored";
306 out.println("The state is restored to state with id: "+id+", depth: "+depth);
308 // Update the parent node
309 if (nodes.containsKey(id)) {
310 parentNode = nodes.get(id);
312 parentNode = new Node(id);
317 public void searchStarted(Search search) {
318 out.println("----------------------------------- search started");
323 public void stateAdvanced(Search search) {
324 String theEnd = null;
325 id = search.getStateId();
326 depth = search.getDepth();
327 operation = "forward";
329 // Add the node to the list of nodes
330 nodes.put(id, new Node(id));
331 Node currentNode = nodes.get(id);
333 // Update the setSet for this new node
335 currentNode.setSetSet(tempSetSet, manual);
336 tempSetSet = new HashSet<NameValuePair>();
341 if (search.isNewState()) {
347 if (search.isEndState()) {
348 out.println("This is the last state!");
352 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
354 // Updating the predecessors for this node
355 // Check if parent node is already in successors of the current node or not
356 if (!(currentNode.getPredecessors().contains(parentNode)))
357 currentNode.addPredecessor(parentNode);
359 // Update the successors for this node
360 // Check if current node is already in successors of the parent node or not
361 if (!(parentNode.getSuccessors().contains(currentNode)))
362 parentNode.addSuccessor(currentNode);
364 // Update the sets, check if the outSet is changed or not
365 boolean isChanged = updateSets(currentNode);
367 // Check for a conflict
368 conflictFound = checkForConflict(currentNode);
370 // Check if the outSet of this state has changed, update all of its successors' sets if any
372 conflictFound = conflictFound || propagateTheChange(currentNode);
374 // Update the parent node
375 if (nodes.containsKey(id)) {
376 parentNode = nodes.get(id);
378 parentNode = new Node(id);
383 public void stateBacktracked(Search search) {
384 id = search.getStateId();
385 depth = search.getDepth();
386 operation = "backtrack";
389 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
391 // Update the parent node
392 if (nodes.containsKey(id)) {
393 parentNode = nodes.get(id);
395 parentNode = new Node(id);
400 public void searchFinished(Search search) {
401 out.println("----------------------------------- search finished");
404 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
408 frame = ti.getTopFrame();
410 if ((inst instanceof JVMLocalVariableInstruction) ||
411 (inst instanceof JVMFieldInstruction))
413 if (frame.getTopPos() < 0)
417 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
419 return(decodeValue(type, lo, hi));
422 if (inst instanceof JVMArrayElementInstruction)
423 return(getArrayValue(ti, type));
428 private final static String decodeValue(byte type, int lo, int hi) {
430 case Types.T_ARRAY: return(null);
431 case Types.T_VOID: return(null);
433 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
434 case Types.T_BYTE: return(String.valueOf(lo));
435 case Types.T_CHAR: return(String.valueOf((char) lo));
436 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
437 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
438 case Types.T_INT: return(String.valueOf(lo));
439 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
440 case Types.T_SHORT: return(String.valueOf(lo));
442 case Types.T_REFERENCE:
443 ElementInfo ei = VM.getVM().getHeap().get(lo);
447 ClassInfo ci = ei.getClassInfo();
451 if (ci.getName().equals("java.lang.String"))
452 return('"' + ei.asString() + '"');
454 return(ei.toString());
457 System.err.println("Unknown type: " + type);
462 private String getArrayValue(ThreadInfo ti, byte type) {
466 frame = ti.getTopFrame();
468 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
470 return(decodeValue(type, lo, hi));
473 private byte getType(ThreadInfo ti, Instruction inst) {
478 frame = ti.getTopFrame();
479 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
480 return (Types.T_REFERENCE);
485 if (inst instanceof JVMLocalVariableInstruction) {
486 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
487 } else if (inst instanceof JVMFieldInstruction){
488 fi = ((JVMFieldInstruction) inst).getFieldInfo();
492 if (inst instanceof JVMArrayElementInstruction) {
493 return (getTypeFromInstruction(inst));
497 return (Types.T_VOID);
500 return (decodeType(type));
503 private final static byte getTypeFromInstruction(Instruction inst) {
504 if (inst instanceof JVMArrayElementInstruction)
505 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
507 return(Types.T_VOID);
510 private final static byte decodeType(String type) {
511 if (type.charAt(0) == '?'){
512 return(Types.T_REFERENCE);
514 return Types.getBuiltinType(type);
518 // Find the variable writer
519 // It should be one of the apps listed in the .jpf file
520 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
521 // Start looking from the top of the stack backward
522 for(int i=sfList.size()-1; i>=0; i--) {
523 MethodInfo mi = sfList.get(i).getMethodInfo();
524 if(!mi.isJPFInternal()) {
525 String method = mi.getStackTraceName();
526 // Check against the writers in the writerSet
527 for(String writer : writerSet) {
528 if (method.contains(writer)) {
539 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
540 // Instantiate timeoutTimer
542 if (System.currentTimeMillis() - startTime > timeout) {
543 StringBuilder sbTimeOut = new StringBuilder();
544 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
545 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
546 ti.setNextPC(nextIns);
551 StringBuilder sb = new StringBuilder();
552 sb.append(errorMessage);
553 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
554 ti.setNextPC(nextIns);
555 } else if (executedInsn instanceof WriteInstruction) {
556 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
557 for(String var : conflictSet) {
559 if (varId.contains(var)) {
561 byte type = getType(ti, executedInsn);
562 String value = getValue(ti, executedInsn, type);
563 String writer = getWriter(ti.getStack(), appSet);
564 // Just return if the writer is not one of the listed apps in the .jpf file
568 if (getWriter(ti.getStack(), manualSet) != null)
571 // Update the temporary Set set.
572 if (writer.equals("App1"))
573 tempSetSet.add(new NameValuePair(1, value, var, manual));
574 else if (writer.equals("App2"))
575 tempSetSet.add(new NameValuePair(2, value, var, manual));