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 {
40 private final PrintWriter out;
41 private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
42 private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
43 private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
44 private final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
45 private ArrayList<NameValuePair> tempSetSet = new ArrayList<NameValuePair>();
47 private long startTime;
48 private Node parentNode = new Node(-2);
49 private String operation;
50 private String detail;
51 private String errorMessage;
54 private boolean conflictFound = false;
55 private boolean manual = false;
57 private final String SET_LOCATION_METHOD = "setLocationMode";
58 private final String LOCATION_VAR = "locationMode";
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());
92 HashMap<Node, HashSet<Node>> parentQueueMap = new HashMap<Node, HashSet<Node>>();
93 HashSet<Node> parents = new HashSet<Node>();
94 parents.add(currentNode);
96 for (Node node : currentNode.getSuccessors()) {
97 parentQueueMap.put(node, parents);
100 while(!changed.isEmpty()) {
101 // Get the first element of the changed set and remove it
102 Node nodeToProcess = changed.iterator().next();
103 changed.remove(nodeToProcess);
105 // Update the changed parents
107 parents = parentQueueMap.get(nodeToProcess);
108 boolean isChanged = false;
110 for (Node node : parents) {
112 isChanged |= updateTheOutSet(node, nodeToProcess);
115 // Check for a conflict if the outSet of nodeToProcess is changed
117 for (Node node : nodeToProcess.getSuccessors()) {
118 HashMap<Transition, ArrayList<NameValuePair>> setSets = nodeToProcess.getOutgoingEdges().get(node).getSetSetMap();
119 for (Map.Entry mapElement : setSets.entrySet()) {
120 Transition transition = (Transition)mapElement.getKey();
121 if (checkForConflict(nodeToProcess, node, transition))
127 // Update the parents list for the successors of the current node
129 parents.add(nodeToProcess);
131 // Checking if the out set has changed or not(Add its successors to the change list!)
133 for (Node i : nodeToProcess.getSuccessors()) {
134 if (!changed.contains(i))
137 // Update the list of updated parents for the current node
138 if (parentQueueMap.containsKey(i))
139 parentQueueMap.get(i).add(nodeToProcess);
141 parentQueueMap.put(i, parents);
149 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
150 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
151 " has written the value: "+pair.getValue()+
152 " to the variable: "+pair.getVarName()+" while App"
153 +writerMap.get(pair.getVarName())+" is overwriting the value: "
154 +valueMap.get(pair.getVarName())+" to the same variable!";
155 System.out.println(message);
159 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
160 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
161 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
162 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
165 // Update the valueMap and writerMap + check for conflict between the elements of setSet
166 for (int i = 0;i < setSet.size();i++) {
167 NameValuePair nameValuePair = setSet.get(i);
168 String varName = nameValuePair.getVarName();
169 String value = nameValuePair.getValue();
170 Integer appNum = nameValuePair.getAppNum();
172 if (valueMap.containsKey(varName)) {
173 // Check if we have a same writer
174 if (!writerMap.get(varName).equals(appNum)) {
175 // Check if we have a conflict or not
176 if (!valueMap.get(varName).equals(value)) {
177 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
179 } else { // We have two writers writing the same value
180 writerMap.put(varName, 3); // 3 represents both apps
183 // Check if we have more than one value with the same writer
184 if (!valueMap.get(varName).equals(value)) {
185 // We have one writer writing more than one value in a same event
186 valueMap.put(varName, "twoValue");
190 valueMap.put(varName, value);
191 writerMap.put(varName, appNum);
195 // Check for conflict between outSet and this transition setSet
196 for (NameValuePair i : parentNode.getOutSet()) {
197 if (valueMap.containsKey(i.getVarName())) {
198 String value = valueMap.get(i.getVarName());
199 Integer writer = writerMap.get(i.getVarName());
200 if ((value != null)&&(writer != null)) {
201 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
202 // We have different values and different writers
203 errorMessage = createErrorMessage(i, valueMap, writerMap);
213 boolean updateTheOutSet(Node parentNode, Node currentNode) {
214 HashMap<Transition, ArrayList<NameValuePair>> setSets = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap();
215 HashSet<String> updatedVarNames = new HashSet<String>();
216 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
217 HashMap<String, Integer> lastWriter = currentEdge.getLastWriter();
218 HashMap<String, String> lastValue = currentEdge.getLastValue();
219 HashMap<String, Integer> outSetVarMap = new HashMap<String, Integer>();
220 boolean isChanged = false;
222 for (Map.Entry mapElement : setSets.entrySet()) {
223 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
225 for (int i = 0;i < setSet.size();i++) {
226 updatedVarNames.add(setSet.get(i).getVarName());
231 for (NameValuePair i : parentNode.getOutSet()) {
232 outSetVarMap.put(i.getVarName(), i.getAppNum());
233 if (!updatedVarNames.contains(i.getVarName()))
234 isChanged |= currentNode.getOutSet().add(i);
238 for (Map.Entry mapElement : setSets.entrySet()) {
239 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
241 for (int i = 0;i < setSet.size();i++) {
242 String varName = setSet.get(i).getVarName();
243 Integer writer = lastWriter.get(varName);
244 String value = lastValue.get(varName);
246 if (setSet.get(i).getAppNum().equals(writer)
247 && setSet.get(i).getValue().equals(value)) {
248 if (outSetVarMap.containsKey(varName)) {
249 Integer hashCode = outSetVarMap.get(varName).hashCode() * 31 +
251 currentNode.getOutSet().remove(hashCode);
253 isChanged |= currentNode.getOutSet().add(setSet.get(i));
261 void updateTheEdge(Node currentNode, Transition transition) {
262 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
263 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
264 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
266 currentEdge.getSetSetMap().put(transition, tempSetSet);
268 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
269 } else { // Add a new transition
270 currentEdge.getSetSetMap().put(transition, tempSetSet);
273 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
274 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
275 currentEdge.getSetSetMap().put(transition, tempSetSet);
278 // Update the last writer and last value for this edge for each varName
279 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
280 ArrayList<NameValuePair> setSet = currentEdge.getSetSetMap().get(transition);
281 for (int i = 0;i < setSet.size();i++) {
282 NameValuePair nameValuePair = setSet.get(i);
283 currentEdge.getLastWriter().put(nameValuePair.getVarName(), nameValuePair.getAppNum());
284 currentEdge.getLastValue().put(nameValuePair.getVarName(), nameValuePair.getValue());
292 HashSet<Node> predecessors = new HashSet<Node>();
293 HashSet<Node> successors = new HashSet<Node>();
294 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
295 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
305 HashSet<Node> getPredecessors() {
309 HashSet<Node> getSuccessors() {
313 HashSet<NameValuePair> getOutSet() {
317 HashMap<Node, Edge> getOutgoingEdges() {
318 return outgoingEdges;
323 Node source, destination;
324 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
325 HashMap<String, String> lastValue = new HashMap<String, String>();
326 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
328 Edge(Node source, Node destination) {
329 this.source = source;
330 this.destination = destination;
337 Node getDestination() {
341 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
345 HashMap<String, Integer> getLastWriter() {
349 HashMap<String, String> getLastValue() {
354 static class NameValuePair {
360 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
361 this.appNum = appNum;
363 this.varName = varName;
364 this.isManual = isManual;
367 void setAppNum(Integer appNum) {
368 this.appNum = appNum;
371 void setValue(String value) {
375 void setVarName(String varName) {
376 this.varName = varName;
379 void setIsManual(String varName) {
380 this.isManual = isManual;
383 Integer getAppNum() {
391 String getVarName() {
395 boolean getIsManual() {
400 public boolean equals(Object o) {
401 if (o instanceof NameValuePair) {
402 NameValuePair other = (NameValuePair) o;
403 if (varName.equals(other.getVarName()))
404 return appNum.equals(other.getAppNum());
410 public int hashCode() {
411 return appNum.hashCode() * 31 + varName.hashCode();
416 public void stateRestored(Search search) {
417 id = search.getStateId();
418 depth = search.getDepth();
419 operation = "restored";
422 out.println("The state is restored to state with id: "+id+", depth: "+depth);
424 // Update the parent node
425 if (nodes.containsKey(id)) {
426 parentNode = nodes.get(id);
428 parentNode = new Node(id);
433 public void searchStarted(Search search) {
434 out.println("----------------------------------- search started");
439 public void stateAdvanced(Search search) {
440 String theEnd = null;
441 Transition transition = search.getTransition();
442 id = search.getStateId();
443 depth = search.getDepth();
444 operation = "forward";
446 // Add the node to the list of nodes
447 if (nodes.get(id) == null)
448 nodes.put(id, new Node(id));
450 Node currentNode = nodes.get(id);
452 // Update the edge based on the current transition
453 updateTheEdge(currentNode, transition);
455 // Reset the temporary variables and flags
456 tempSetSet = new ArrayList<NameValuePair>();
459 // Check for the conflict in this transition
460 conflictFound = checkForConflict(parentNode, currentNode, transition);
462 if (search.isNewState()) {
468 if (search.isEndState()) {
469 out.println("This is the last state!");
473 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
475 // Updating the predecessors for this node
476 // Check if parent node is already in successors of the current node or not
477 if (!(currentNode.getPredecessors().contains(parentNode)))
478 currentNode.getPredecessors().add(parentNode);
480 // Update the successors for this node
481 // Check if current node is already in successors of the parent node or not
482 if (!(parentNode.getSuccessors().contains(currentNode)))
483 parentNode.getSuccessors().add(currentNode);
485 // Update the outset of the current node and check if it is changed or not to propagate the change
486 boolean isChanged = updateTheOutSet(parentNode, currentNode);
488 // Check if the outSet of this state has changed, update all of its successors' sets if any
490 for (Node node : currentNode.getSuccessors()) {
491 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
492 for (Map.Entry mapElement : setSets.entrySet()) {
493 Transition currentTransition = (Transition)mapElement.getKey();
494 conflictFound = conflictFound || checkForConflict(currentNode, node, currentTransition);
497 conflictFound = conflictFound || propagateTheChange(currentNode);
499 // Update the parent node
500 if (nodes.containsKey(id)) {
501 parentNode = nodes.get(id);
503 parentNode = new Node(id);
508 public void stateBacktracked(Search search) {
509 id = search.getStateId();
510 depth = search.getDepth();
511 operation = "backtrack";
514 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
516 // Update the parent node
517 if (nodes.containsKey(id)) {
518 parentNode = nodes.get(id);
520 parentNode = new Node(id);
525 public void searchFinished(Search search) {
526 out.println("----------------------------------- search finished");
529 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
533 frame = ti.getTopFrame();
535 if ((inst instanceof JVMLocalVariableInstruction) ||
536 (inst instanceof JVMFieldInstruction))
538 if (frame.getTopPos() < 0)
542 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
544 return(decodeValue(type, lo, hi));
547 if (inst instanceof JVMArrayElementInstruction)
548 return(getArrayValue(ti, type));
553 private final static String decodeValue(byte type, int lo, int hi) {
555 case Types.T_ARRAY: return(null);
556 case Types.T_VOID: return(null);
558 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
559 case Types.T_BYTE: return(String.valueOf(lo));
560 case Types.T_CHAR: return(String.valueOf((char) lo));
561 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
562 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
563 case Types.T_INT: return(String.valueOf(lo));
564 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
565 case Types.T_SHORT: return(String.valueOf(lo));
567 case Types.T_REFERENCE:
568 ElementInfo ei = VM.getVM().getHeap().get(lo);
572 ClassInfo ci = ei.getClassInfo();
576 if (ci.getName().equals("java.lang.String"))
577 return('"' + ei.asString() + '"');
579 return(ei.toString());
582 System.err.println("Unknown type: " + type);
587 private String getArrayValue(ThreadInfo ti, byte type) {
591 frame = ti.getTopFrame();
593 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
595 return(decodeValue(type, lo, hi));
598 private byte getType(ThreadInfo ti, Instruction inst) {
603 frame = ti.getTopFrame();
604 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
605 return (Types.T_REFERENCE);
610 if (inst instanceof JVMLocalVariableInstruction) {
611 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
612 } else if (inst instanceof JVMFieldInstruction){
613 fi = ((JVMFieldInstruction) inst).getFieldInfo();
617 if (inst instanceof JVMArrayElementInstruction) {
618 return (getTypeFromInstruction(inst));
622 return (Types.T_VOID);
625 return (decodeType(type));
628 private final static byte getTypeFromInstruction(Instruction inst) {
629 if (inst instanceof JVMArrayElementInstruction)
630 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
632 return(Types.T_VOID);
635 private final static byte decodeType(String type) {
636 if (type.charAt(0) == '?'){
637 return(Types.T_REFERENCE);
639 return Types.getBuiltinType(type);
643 // Find the variable writer
644 // It should be one of the apps listed in the .jpf file
645 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
646 // Start looking from the top of the stack backward
647 for(int i=sfList.size()-1; i>=0; i--) {
648 MethodInfo mi = sfList.get(i).getMethodInfo();
649 if(!mi.isJPFInternal()) {
650 String method = mi.getStackTraceName();
651 // Check against the writers in the writerSet
652 for(String writer : writerSet) {
653 if (method.contains(writer)) {
663 private void writeWriterAndValue(String writer, String value, String var) {
664 // Update the temporary Set set.
665 NameValuePair temp = new NameValuePair(1, value, var, manual);
666 if (writer.equals("App2"))
667 temp = new NameValuePair(2, value, var, manual);
669 tempSetSet.add(temp);
673 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
675 if (System.currentTimeMillis() - startTime > timeout) {
676 StringBuilder sbTimeOut = new StringBuilder();
677 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
678 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
679 ti.setNextPC(nextIns);
684 StringBuilder sb = new StringBuilder();
685 sb.append(errorMessage);
686 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
687 ti.setNextPC(nextIns);
689 if (conflictSet.contains(LOCATION_VAR)) {
690 MethodInfo mi = executedInsn.getMethodInfo();
691 // Find the last load before return and get the value here
692 if (mi.getName().equals(SET_LOCATION_METHOD) &&
693 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
694 byte type = getType(ti, executedInsn);
695 String value = getValue(ti, executedInsn, type);
697 // Extract the writer app name
698 ClassInfo ci = mi.getClassInfo();
699 String writer = ci.getName();
701 // Update the temporary Set set.
702 writeWriterAndValue(writer, value, LOCATION_VAR);
705 if (executedInsn instanceof WriteInstruction) {
706 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
708 for (String var : conflictSet) {
709 if (varId.contains(var)) {
711 byte type = getType(ti, executedInsn);
712 String value = getValue(ti, executedInsn, type);
713 String writer = getWriter(ti.getStack(), appSet);
714 // Just return if the writer is not one of the listed apps in the .jpf file
718 if (getWriter(ti.getStack(), manualSet) != null)
721 // Update the temporary Set set.
722 writeWriterAndValue(writer, value, var);