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 ArrayList<NameValuePair> tempSetSet = new ArrayList<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 manual = false;
58 private final String SET_LOCATION_METHOD = "setLocationMode";
59 private final String LOCATION_VAR = "locationMode";
61 public ConflictTracker(Config config, JPF jpf) {
62 out = new PrintWriter(System.out, true);
64 String[] conflictVars = config.getStringArray("variables");
65 // We are not tracking anything if it is null
66 if (conflictVars != null) {
67 for (String var : conflictVars) {
71 String[] apps = config.getStringArray("apps");
72 // We are not tracking anything if it is null
74 for (String var : apps) {
78 String[] manualClasses = config.getStringArray("manualClasses");
79 // We are not tracking anything if it is null
80 if (manualClasses != null) {
81 for (String var : manualClasses) {
86 // Timeout input from config is in minutes, so we need to convert into millis
87 timeout = config.getInt("timeout", 0) * 60 * 1000;
88 startTime = System.currentTimeMillis();
91 boolean propagateTheChange(Node currentNode) {
92 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
94 while(!changed.isEmpty()) {
95 // Get the first element of HashSet and remove it from the changed set
96 Node nodeToProcess = changed.iterator().next();
97 changed.remove(nodeToProcess);
100 boolean isChanged = updateEdge(currentNode, nodeToProcess);
102 // Check for a conflict in this transition(currentNode -> nodeToProcess)
103 if (checkForConflict(nodeToProcess))
106 // Checking if the out set has changed or not(Add its successors to the change list!)
108 propagateTheChange(nodeToProcess);
115 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
116 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
117 " has written the value: "+pair.getValue()+
118 " to the variable: "+pair.getVarName()+" while App"+
119 writerMap.get(pair.getVarName())+" is overwriting the value: "
120 +valueMap.get(pair.getVarName())+" to the same variable!";
121 System.out.println(message);
125 boolean checkForConflict(Node nodeToProcess) {
126 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
127 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
129 // Update the valueMap
130 for (int i = 0;i < nodeToProcess.getSetSet().size();i++) {
131 NameValuePair nameValuePair = nodeToProcess.getSetSet().get(i);
133 if (valueMap.containsKey(nameValuePair.getVarName())) {
134 // Check if we have a same writer
135 if (!writerMap.get(nameValuePair.getVarName()).equals(nameValuePair.getAppNum())) {
136 // Check if we have a conflict or not
137 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
138 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
140 } else { // We have two writers writing the same value
141 writerMap.put(nameValuePair.getVarName(), 3); // 3 represents both apps
144 // Check if we have more than one value with the same writer
145 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
146 valueMap.put(nameValuePair.getVarName(), "twoValue"); // We have one writer writing more than one value in a same event
150 valueMap.put(nameValuePair.getVarName(), nameValuePair.getValue());
151 writerMap.put(nameValuePair.getVarName(), nameValuePair.getAppNum());
155 // Comparing the outSet to setSet
156 for (NameValuePair i : nodeToProcess.getOutSet()) {
157 if (valueMap.containsKey(i.getVarName())) {
158 String value = valueMap.get(i.getVarName());
159 Integer writer = writerMap.get(i.getVarName());
160 if ((value != null)&&(writer != null)) {
161 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
162 errorMessage = createErrorMessage(i, valueMap, writerMap);
172 boolean updateEdge(Node parentNode, Node currentNode) {
173 ArrayList<NameValuePair> setSet = currentNode.getSetSetMap().get(parentNode);
174 HashSet<String> updatedVarNames = new HashSet<String>();
175 HashMap<Integer, String> writerLastValue = new HashMap<Integer, String>();
177 boolean isChanged = false;
179 if (setSet != null) {
180 for (int i = 0;i < setSet.size();i++) {
181 updatedVarNames.add(setSet.get(i).getVarName());
182 writerLastValue.put(setSet.get(i).getAppNum(), setSet.get(i).getValue());
186 for (NameValuePair i : parentNode.getOutSet()) {
187 if (!updatedVarNames.contains(i.getVarName()))
188 isChanged |= currentNode.getOutSet().add(i);
191 if (setSet != null) {
192 for (int i = 0;i < setSet.size();i++) {
193 if (setSet.get(i).getValue().equals(writerLastValue.get(setSet.get(i).getAppNum()))) {
194 isChanged |= currentNode.getOutSet().add(setSet.get(i));
204 HashSet<Node> predecessors = new HashSet<Node>();
205 HashSet<Node> successors = new HashSet<Node>();
206 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
207 HashMap<Node, ArrayList<NameValuePair>> setSetMap = new HashMap<Node, ArrayList<NameValuePair>>();
208 ArrayList<NameValuePair> setSet = new ArrayList<NameValuePair>();
215 void addPredecessor(Node node) {
216 predecessors.add(node);
219 void addSuccessor(Node node) {
220 successors.add(node);
223 void setSetSet(ArrayList<NameValuePair> setSet, boolean isManual) {
225 this.setSet = new ArrayList<NameValuePair>();
227 for (int i = 0;i < setSet.size();i++) {
228 this.setSet.add(new NameValuePair(setSet.get(i).getAppNum(), setSet.get(i).getValue(),
229 setSet.get(i).getVarName(), setSet.get(i).getIsManual()));
237 HashSet<Node> getPredecessors() {
241 HashSet<Node> getSuccessors() {
245 ArrayList<NameValuePair> getSetSet() {
249 HashSet<NameValuePair> getOutSet() {
253 HashMap<Node, ArrayList<NameValuePair>> getSetSetMap() {
258 static class NameValuePair {
264 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
265 this.appNum = appNum;
267 this.varName = varName;
268 this.isManual = isManual;
271 void setAppNum(Integer appNum) {
272 this.appNum = appNum;
275 void setValue(String value) {
279 void setVarName(String varName) {
280 this.varName = varName;
283 void setIsManual(String varName) {
284 this.isManual = isManual;
287 Integer getAppNum() {
295 String getVarName() {
299 boolean getIsManual() {
304 public boolean equals(Object o) {
305 if (o instanceof NameValuePair) {
306 NameValuePair other = (NameValuePair) o;
307 if (varName.equals(other.getVarName()))
308 return appNum.equals(other.getAppNum());
314 public int hashCode() {
315 return appNum.hashCode() * 31 + varName.hashCode();
320 public void stateRestored(Search search) {
321 id = search.getStateId();
322 depth = search.getDepth();
323 operation = "restored";
326 out.println("The state is restored to state with id: "+id+", depth: "+depth);
328 // Update the parent node
329 if (nodes.containsKey(id)) {
330 parentNode = nodes.get(id);
332 parentNode = new Node(id);
337 public void searchStarted(Search search) {
338 out.println("----------------------------------- search started");
343 public void stateAdvanced(Search search) {
344 String theEnd = null;
345 id = search.getStateId();
346 depth = search.getDepth();
347 operation = "forward";
349 // Add the node to the list of nodes
350 if (nodes.get(id) == null)
351 nodes.put(id, new Node(id));
353 Node currentNode = nodes.get(id);
355 // Update the setSet for this new node
356 currentNode.setSetSet(tempSetSet, manual);
357 tempSetSet = new ArrayList<NameValuePair>();
360 if (search.isNewState()) {
366 if (search.isEndState()) {
367 out.println("This is the last state!");
371 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
373 // Updating the predecessors for this node
374 // Check if parent node is already in successors of the current node or not
375 if (!(currentNode.getPredecessors().contains(parentNode)))
376 currentNode.addPredecessor(parentNode);
378 // Update the successors for this node
379 // Check if current node is already in successors of the parent node or not
380 if (!(parentNode.getSuccessors().contains(currentNode)))
381 parentNode.addSuccessor(currentNode);
384 // Update the setSetMap of the current node
385 for (Node i : currentNode.getPredecessors()) {
386 currentNode.getSetSetMap().put(i, i.getSetSet());
389 // Update the edge and check if the outset of the current node is changed or not to propagate the change
390 boolean isChanged = updateEdge(parentNode, currentNode);
392 // Check for the conflict in this edge
393 conflictFound = checkForConflict(currentNode);
395 // Check if the outSet of this state has changed, update all of its successors' sets if any
397 conflictFound = conflictFound || propagateTheChange(currentNode);
399 // Update the parent node
400 if (nodes.containsKey(id)) {
401 parentNode = nodes.get(id);
403 parentNode = new Node(id);
408 public void stateBacktracked(Search search) {
409 id = search.getStateId();
410 depth = search.getDepth();
411 operation = "backtrack";
414 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
416 // Update the parent node
417 if (nodes.containsKey(id)) {
418 parentNode = nodes.get(id);
420 parentNode = new Node(id);
425 public void searchFinished(Search search) {
426 out.println("----------------------------------- search finished");
429 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
433 frame = ti.getTopFrame();
435 if ((inst instanceof JVMLocalVariableInstruction) ||
436 (inst instanceof JVMFieldInstruction))
438 if (frame.getTopPos() < 0)
442 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
444 return(decodeValue(type, lo, hi));
447 if (inst instanceof JVMArrayElementInstruction)
448 return(getArrayValue(ti, type));
453 private final static String decodeValue(byte type, int lo, int hi) {
455 case Types.T_ARRAY: return(null);
456 case Types.T_VOID: return(null);
458 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
459 case Types.T_BYTE: return(String.valueOf(lo));
460 case Types.T_CHAR: return(String.valueOf((char) lo));
461 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
462 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
463 case Types.T_INT: return(String.valueOf(lo));
464 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
465 case Types.T_SHORT: return(String.valueOf(lo));
467 case Types.T_REFERENCE:
468 ElementInfo ei = VM.getVM().getHeap().get(lo);
472 ClassInfo ci = ei.getClassInfo();
476 if (ci.getName().equals("java.lang.String"))
477 return('"' + ei.asString() + '"');
479 return(ei.toString());
482 System.err.println("Unknown type: " + type);
487 private String getArrayValue(ThreadInfo ti, byte type) {
491 frame = ti.getTopFrame();
493 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
495 return(decodeValue(type, lo, hi));
498 private byte getType(ThreadInfo ti, Instruction inst) {
503 frame = ti.getTopFrame();
504 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
505 return (Types.T_REFERENCE);
510 if (inst instanceof JVMLocalVariableInstruction) {
511 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
512 } else if (inst instanceof JVMFieldInstruction){
513 fi = ((JVMFieldInstruction) inst).getFieldInfo();
517 if (inst instanceof JVMArrayElementInstruction) {
518 return (getTypeFromInstruction(inst));
522 return (Types.T_VOID);
525 return (decodeType(type));
528 private final static byte getTypeFromInstruction(Instruction inst) {
529 if (inst instanceof JVMArrayElementInstruction)
530 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
532 return(Types.T_VOID);
535 private final static byte decodeType(String type) {
536 if (type.charAt(0) == '?'){
537 return(Types.T_REFERENCE);
539 return Types.getBuiltinType(type);
543 // Find the variable writer
544 // It should be one of the apps listed in the .jpf file
545 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
546 // Start looking from the top of the stack backward
547 for(int i=sfList.size()-1; i>=0; i--) {
548 MethodInfo mi = sfList.get(i).getMethodInfo();
549 if(!mi.isJPFInternal()) {
550 String method = mi.getStackTraceName();
551 // Check against the writers in the writerSet
552 for(String writer : writerSet) {
553 if (method.contains(writer)) {
563 private void writeWriterAndValue(String writer, String value, String var) {
564 // Update the temporary Set set.
565 NameValuePair temp = new NameValuePair(1, value, var, manual);
566 if (writer.equals("App2"))
567 temp = new NameValuePair(2, value, var, manual);
569 tempSetSet.add(temp);
573 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
575 if (System.currentTimeMillis() - startTime > timeout) {
576 StringBuilder sbTimeOut = new StringBuilder();
577 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
578 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
579 ti.setNextPC(nextIns);
584 StringBuilder sb = new StringBuilder();
585 sb.append(errorMessage);
586 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
587 ti.setNextPC(nextIns);
589 if (conflictSet.contains(LOCATION_VAR)) {
590 MethodInfo mi = executedInsn.getMethodInfo();
591 // Find the last load before return and get the value here
592 if (mi.getName().equals(SET_LOCATION_METHOD) &&
593 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
594 byte type = getType(ti, executedInsn);
595 String value = getValue(ti, executedInsn, type);
597 // Extract the writer app name
598 ClassInfo ci = mi.getClassInfo();
599 String writer = ci.getName();
601 // Update the temporary Set set.
602 writeWriterAndValue(writer, value, LOCATION_VAR);
605 if (executedInsn instanceof WriteInstruction) {
606 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
608 for (String var : conflictSet) {
609 if (varId.contains(var)) {
611 byte type = getType(ti, executedInsn);
612 String value = getValue(ti, executedInsn, type);
613 String writer = getWriter(ti.getStack(), appSet);
614 // Just return if the writer is not one of the listed apps in the .jpf file
618 if (getWriter(ti.getStack(), manualSet) != null)
621 // Update the temporary Set set.
622 writeWriterAndValue(writer, value, var);