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;
59 private final String SET_LOCATION_METHOD = "setLocationMode";
60 private final String LOCATION_VAR = "locationMode";
62 public ConflictTracker(Config config, JPF jpf) {
63 out = new PrintWriter(System.out, true);
65 String[] conflictVars = config.getStringArray("variables");
66 // We are not tracking anything if it is null
67 if (conflictVars != null) {
68 for (String var : conflictVars) {
72 String[] apps = config.getStringArray("apps");
73 // We are not tracking anything if it is null
75 for (String var : apps) {
79 String[] manualClasses = config.getStringArray("manualClasses");
80 // We are not tracking anything if it is null
81 if (manualClasses != null) {
82 for (String var : manualClasses) {
87 // Timeout input from config is in minutes, so we need to convert into millis
88 timeout = config.getInt("timeout", 0) * 60 * 1000;
89 startTime = System.currentTimeMillis();
92 boolean propagateTheChange(Node currentNode) {
93 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
95 while(!changed.isEmpty()) {
96 // Get the first element of HashSet and remove it from the changed set
97 Node nodeToProcess = changed.iterator().next();
98 changed.remove(nodeToProcess);
100 // Update the sets, store the outSet to temp before its changes
101 boolean isChanged = updateSets(nodeToProcess);
103 // Check for a conflict
104 if (checkForConflict(nodeToProcess))
107 // Checking if the out set has changed or not(Add its successors to the change list!)
109 for (Node i : nodeToProcess.getSuccessors()) {
110 if (!changed.contains(i))
119 boolean setOutSet(Node currentNode) {
120 Integer prevSize = currentNode.getOutSet().size();
122 // Update based on setSet
123 for (NameValuePair i : currentNode.getSetSet()) {
124 if (currentNode.getOutSet().contains(i))
125 currentNode.getOutSet().remove(i);
126 currentNode.getOutSet().add(i);
130 currentNode.getOutSet().addAll(currentNode.getInSet());
132 // Check if the outSet is changed
133 if (!prevSize.equals(currentNode.getOutSet().size()))
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>(); // HashMap from varName to value
147 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
149 for (NameValuePair i : currentNode.getSetSet()) {
150 if (i.getIsManual()) // Manual input: we have no conflict
153 valueMap.put(i.getVarName(), i.getValue());
154 if (writerMap.containsKey(i.getVarName()))
155 writerMap.put(i.getVarName(), i.getAppNum()+writerMap.get(i.getVarName())); // We have two writers?
157 writerMap.put(i.getVarName(), i.getAppNum());
160 // Comparing the inSet and setSet to find the conflict
161 for (NameValuePair i : currentNode.getInSet()) {
162 if (valueMap.containsKey(i.getVarName())) {
163 String value = valueMap.get(i.getVarName());
164 Integer writer = writerMap.get(i.getVarName());
165 if ((value != null)&&(writer != null)) {
166 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
167 errorMessage = "Conflict found between the two apps. App"+i.getAppNum()+" has written the value: "+i.getValue()+
168 " to the variable: "+i.getVarName()+" while App"+writerMap.get(i.getVarName())+" is overwriting the value: "
169 +valueMap.get(i.getVarName())+" to the same variable!";
179 boolean updateSets(Node currentNode) {
180 // Set input set according to output set of pred states of current state
181 setInSet(currentNode);
183 // Set outSet according to inSet, and setSet of current node, check if there is a change
184 return setOutSet(currentNode);
189 HashSet<Node> predecessors = new HashSet<Node>();
190 HashSet<Node> successors = new HashSet<Node>();
191 HashSet<NameValuePair> inSet = new HashSet<NameValuePair>();
192 HashSet<NameValuePair> setSet = new HashSet<NameValuePair>();
193 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
199 void addPredecessor(Node node) {
200 predecessors.add(node);
203 void addSuccessor(Node node) {
204 successors.add(node);
207 void setSetSet(HashSet<NameValuePair> setSet, boolean isManual) {
209 this.setSet = new HashSet<NameValuePair>();
210 for (NameValuePair i : setSet) {
211 this.setSet.add(new NameValuePair(i.getAppNum(), i.getValue(), i.getVarName(), i.getIsManual()));
219 HashSet<Node> getPredecessors() {
223 HashSet<Node> getSuccessors() {
227 HashSet<NameValuePair> getInSet() {
231 HashSet<NameValuePair> getSetSet() {
235 HashSet<NameValuePair> getOutSet() {
240 static class NameValuePair {
246 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
247 this.appNum = appNum;
249 this.varName = varName;
250 this.isManual = isManual;
253 void setAppNum(Integer appNum) {
254 this.appNum = appNum;
257 void setValue(String value) {
261 void setVarName(String varName) {
262 this.varName = varName;
265 void setIsManual(String varName) {
266 this.isManual = isManual;
269 Integer getAppNum() {
277 String getVarName() {
281 boolean getIsManual() {
286 public boolean equals(Object o) {
287 if (o instanceof NameValuePair) {
288 NameValuePair other = (NameValuePair) o;
289 if (varName.equals(other.getVarName()))
290 return appNum.equals(other.getAppNum());
296 public int hashCode() {
297 return appNum.hashCode() * 31 + varName.hashCode();
302 public void stateRestored(Search search) {
303 id = search.getStateId();
304 depth = search.getDepth();
305 operation = "restored";
308 out.println("The state is restored to state with id: "+id+", depth: "+depth);
310 // Update the parent node
311 if (nodes.containsKey(id)) {
312 parentNode = nodes.get(id);
314 parentNode = new Node(id);
319 public void searchStarted(Search search) {
320 out.println("----------------------------------- search started");
325 public void stateAdvanced(Search search) {
326 String theEnd = null;
327 id = search.getStateId();
328 depth = search.getDepth();
329 operation = "forward";
331 // Add the node to the list of nodes
332 nodes.put(id, new Node(id));
333 Node currentNode = nodes.get(id);
335 // Update the setSet for this new node
337 currentNode.setSetSet(tempSetSet, manual);
338 tempSetSet = new HashSet<NameValuePair>();
343 if (search.isNewState()) {
349 if (search.isEndState()) {
350 out.println("This is the last state!");
354 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
356 // Updating the predecessors for this node
357 // Check if parent node is already in successors of the current node or not
358 if (!(currentNode.getPredecessors().contains(parentNode)))
359 currentNode.addPredecessor(parentNode);
361 // Update the successors for this node
362 // Check if current node is already in successors of the parent node or not
363 if (!(parentNode.getSuccessors().contains(currentNode)))
364 parentNode.addSuccessor(currentNode);
366 // Update the sets, check if the outSet is changed or not
367 boolean isChanged = updateSets(currentNode);
369 // Check for a conflict
370 conflictFound = checkForConflict(currentNode);
372 // Check if the outSet of this state has changed, update all of its successors' sets if any
374 conflictFound = conflictFound || propagateTheChange(currentNode);
376 // Update the parent node
377 if (nodes.containsKey(id)) {
378 parentNode = nodes.get(id);
380 parentNode = new Node(id);
385 public void stateBacktracked(Search search) {
386 id = search.getStateId();
387 depth = search.getDepth();
388 operation = "backtrack";
391 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
393 // Update the parent node
394 if (nodes.containsKey(id)) {
395 parentNode = nodes.get(id);
397 parentNode = new Node(id);
402 public void searchFinished(Search search) {
403 out.println("----------------------------------- search finished");
406 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
410 frame = ti.getTopFrame();
412 if ((inst instanceof JVMLocalVariableInstruction) ||
413 (inst instanceof JVMFieldInstruction))
415 if (frame.getTopPos() < 0)
419 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
421 return(decodeValue(type, lo, hi));
424 if (inst instanceof JVMArrayElementInstruction)
425 return(getArrayValue(ti, type));
430 private final static String decodeValue(byte type, int lo, int hi) {
432 case Types.T_ARRAY: return(null);
433 case Types.T_VOID: return(null);
435 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
436 case Types.T_BYTE: return(String.valueOf(lo));
437 case Types.T_CHAR: return(String.valueOf((char) lo));
438 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
439 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
440 case Types.T_INT: return(String.valueOf(lo));
441 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
442 case Types.T_SHORT: return(String.valueOf(lo));
444 case Types.T_REFERENCE:
445 ElementInfo ei = VM.getVM().getHeap().get(lo);
449 ClassInfo ci = ei.getClassInfo();
453 if (ci.getName().equals("java.lang.String"))
454 return('"' + ei.asString() + '"');
456 return(ei.toString());
459 System.err.println("Unknown type: " + type);
464 private String getArrayValue(ThreadInfo ti, byte type) {
468 frame = ti.getTopFrame();
470 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
472 return(decodeValue(type, lo, hi));
475 private byte getType(ThreadInfo ti, Instruction inst) {
480 frame = ti.getTopFrame();
481 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
482 return (Types.T_REFERENCE);
487 if (inst instanceof JVMLocalVariableInstruction) {
488 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
489 } else if (inst instanceof JVMFieldInstruction){
490 fi = ((JVMFieldInstruction) inst).getFieldInfo();
494 if (inst instanceof JVMArrayElementInstruction) {
495 return (getTypeFromInstruction(inst));
499 return (Types.T_VOID);
502 return (decodeType(type));
505 private final static byte getTypeFromInstruction(Instruction inst) {
506 if (inst instanceof JVMArrayElementInstruction)
507 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
509 return(Types.T_VOID);
512 private final static byte decodeType(String type) {
513 if (type.charAt(0) == '?'){
514 return(Types.T_REFERENCE);
516 return Types.getBuiltinType(type);
520 // Find the variable writer
521 // It should be one of the apps listed in the .jpf file
522 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
523 // Start looking from the top of the stack backward
524 for(int i=sfList.size()-1; i>=0; i--) {
525 MethodInfo mi = sfList.get(i).getMethodInfo();
526 if(!mi.isJPFInternal()) {
527 String method = mi.getStackTraceName();
528 // Check against the writers in the writerSet
529 for(String writer : writerSet) {
530 if (method.contains(writer)) {
540 private void writeWriterAndValue(String writer, String value, String var) {
541 // Update the temporary Set set.
542 NameValuePair temp = new NameValuePair(1, value, var, manual);
543 if (writer.equals("App2"))
544 temp = new NameValuePair(2, value, var, manual);
546 if (tempSetSet.contains(temp))
547 tempSetSet.remove(temp);
548 tempSetSet.add(temp);
554 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
555 // Instantiate timeoutTimer
557 if (System.currentTimeMillis() - startTime > timeout) {
558 StringBuilder sbTimeOut = new StringBuilder();
559 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
560 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
561 ti.setNextPC(nextIns);
566 StringBuilder sb = new StringBuilder();
567 sb.append(errorMessage);
568 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
569 ti.setNextPC(nextIns);
571 if (conflictSet.contains(LOCATION_VAR)) {
572 MethodInfo mi = executedInsn.getMethodInfo();
573 // Find the last load before return and get the value here
574 if (mi.getName().equals(SET_LOCATION_METHOD) &&
575 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
576 byte type = getType(ti, executedInsn);
577 String value = getValue(ti, executedInsn, type);
579 // Extract the writer app name
580 ClassInfo ci = mi.getClassInfo();
581 String writer = ci.getName();
583 // Update the temporary Set set.
584 writeWriterAndValue(writer, value, LOCATION_VAR);
587 if (executedInsn instanceof WriteInstruction) {
588 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
589 for (String var : conflictSet) {
590 if (varId.contains(var)) {
592 byte type = getType(ti, executedInsn);
593 String value = getValue(ti, executedInsn, type);
594 String writer = getWriter(ti.getStack(), appSet);
595 // Just return if the writer is not one of the listed apps in the .jpf file
599 if (getWriter(ti.getStack(), manualSet) != null)
602 // Update the temporary Set set.
603 writeWriterAndValue(writer, value, var);