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
106 parents = parentQueueMap.get(nodeToProcess);
107 boolean isChanged = false;
109 for (Node node : parents) {
111 isChanged |= updateTheOutSet(node, nodeToProcess);
114 // Check for a conflict if the outSet of nodeToProcess is changed
116 for (Node node : nodeToProcess.getSuccessors()) {
117 HashMap<Transition, ArrayList<NameValuePair>> setSets = nodeToProcess.getOutgoingEdges().get(node).getSetSetMap();
118 for (Map.Entry mapElement : setSets.entrySet()) {
119 Transition transition = (Transition)mapElement.getKey();
120 if (checkForConflict(nodeToProcess, node, transition))
126 // Update the parents list for the successors of the current node
127 parents = new HashSet<Node>();
128 parents.add(nodeToProcess);
130 // Checking if the out set has changed or not(Add its successors to the change list!)
132 for (Node i : nodeToProcess.getSuccessors()) {
133 if (!changed.contains(i))
136 // Update the list of updated parents for the current node
137 if (parentQueueMap.containsKey(i))
138 parentQueueMap.get(i).add(nodeToProcess);
140 parentQueueMap.put(i, parents);
148 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
149 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
150 " has written the value: "+pair.getValue()+
151 " to the variable: "+pair.getVarName()+" while App"
152 +writerMap.get(pair.getVarName())+" is overwriting the value: "
153 +valueMap.get(pair.getVarName())+" to the same variable!";
154 System.out.println(message);
158 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
159 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
160 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
161 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
164 System.out.println("#########################Set Set:");
165 for (int i = 0;i < setSet.size();i++) {
166 NameValuePair nameValuePair = setSet.get(i);
167 String varName = nameValuePair.getVarName();
168 String value = nameValuePair.getValue();
169 Integer appNum = nameValuePair.getAppNum();
171 System.out.println("varName="+varName+", value="+value+", appNum="+appNum);
173 System.out.println("+++++++++++++++++++++++++Out Set:");
174 for (NameValuePair nameValuePair : currentNode.getOutSet()) {
175 String varName = nameValuePair.getVarName();
176 String value = nameValuePair.getValue();
177 Integer appNum = nameValuePair.getAppNum();
179 System.out.println("varName="+varName+", value="+value+", appNum="+appNum);
182 // Update the valueMap and writerMap + check for conflict between the elements of setSet
183 for (int i = 0;i < setSet.size();i++) {
184 NameValuePair nameValuePair = setSet.get(i);
185 String varName = nameValuePair.getVarName();
186 String value = nameValuePair.getValue();
187 Integer appNum = nameValuePair.getAppNum();
189 if (valueMap.containsKey(varName)) {
190 // Check if we have a same writer
191 if (!writerMap.get(varName).equals(appNum)) {
192 // Check if we have a conflict or not
193 if (!valueMap.get(varName).equals(value)) {
194 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
196 } else { // We have two writers writing the same value
197 writerMap.put(varName, 3); // 3 represents both apps
200 // Check if we have more than one value with the same writer
201 if (!valueMap.get(varName).equals(value)) {
202 // We have one writer writing more than one value in a same event
203 valueMap.put(varName, "twoValue");
207 valueMap.put(varName, value);
208 writerMap.put(varName, appNum);
212 // Check for conflict between outSet and this transition setSet
213 for (NameValuePair i : currentNode.getOutSet()) {
214 if (valueMap.containsKey(i.getVarName())) {
215 String value = valueMap.get(i.getVarName());
216 Integer writer = writerMap.get(i.getVarName());
217 if ((value != null)&&(writer != null)) {
218 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
219 // We have different values and different writers
220 errorMessage = createErrorMessage(i, valueMap, writerMap);
230 boolean updateTheOutSet(Node parentNode, Node currentNode) {
231 HashMap<Transition, ArrayList<NameValuePair>> setSets = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap();
232 HashSet<String> updatedVarNames = new HashSet<String>();
233 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
234 HashMap<String, Integer> lastWriter = currentEdge.getLastWriter();
235 HashMap<String, String> lastValue = currentEdge.getLastValue();
236 HashMap<String, Integer> outSetVarMap = new HashMap<String, Integer>();
237 boolean isChanged = false;
239 for (Map.Entry mapElement : setSets.entrySet()) {
240 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
242 for (int i = 0;i < setSet.size();i++) {
243 updatedVarNames.add(setSet.get(i).getVarName());
248 for (NameValuePair i : parentNode.getOutSet()) {
249 outSetVarMap.put(i.getVarName(), i.getAppNum());
250 if (!updatedVarNames.contains(i.getVarName()))
251 isChanged |= currentNode.getOutSet().add(i);
255 for (Map.Entry mapElement : setSets.entrySet()) {
256 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
258 for (int i = 0;i < setSet.size();i++) {
259 String varName = setSet.get(i).getVarName();
260 Integer writer = lastWriter.get(varName);
261 String value = lastValue.get(varName);
263 if (setSet.get(i).getAppNum().equals(writer)
264 && setSet.get(i).getValue().equals(value)) {
265 if (outSetVarMap.containsKey(varName)) {
266 Integer hashCode = outSetVarMap.get(varName).hashCode() * 31 +
268 currentNode.getOutSet().remove(hashCode);
270 isChanged |= currentNode.getOutSet().add(setSet.get(i));
278 void updateTheEdge(Node currentNode, Transition transition) {
279 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
280 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
281 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
283 currentEdge.getSetSetMap().put(transition, tempSetSet);
285 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
286 } else { // Add a new transition
287 currentEdge.getSetSetMap().put(transition, tempSetSet);
290 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
291 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
292 currentEdge.getSetSetMap().put(transition, tempSetSet);
295 // Update the last writer and last value for this edge for each varName
296 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
297 ArrayList<NameValuePair> setSet = currentEdge.getSetSetMap().get(transition);
298 for (int i = 0;i < setSet.size();i++) {
299 NameValuePair nameValuePair = setSet.get(i);
300 currentEdge.getLastWriter().put(nameValuePair.getVarName(), nameValuePair.getAppNum());
301 currentEdge.getLastValue().put(nameValuePair.getVarName(), nameValuePair.getValue());
309 HashSet<Node> predecessors = new HashSet<Node>();
310 HashSet<Node> successors = new HashSet<Node>();
311 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
312 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
322 HashSet<Node> getPredecessors() {
326 HashSet<Node> getSuccessors() {
330 HashSet<NameValuePair> getOutSet() {
334 HashMap<Node, Edge> getOutgoingEdges() {
335 return outgoingEdges;
340 Node source, destination;
341 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
342 HashMap<String, String> lastValue = new HashMap<String, String>();
343 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
345 Edge(Node source, Node destination) {
346 this.source = source;
347 this.destination = destination;
354 Node getDestination() {
358 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
362 HashMap<String, Integer> getLastWriter() {
366 HashMap<String, String> getLastValue() {
371 static class NameValuePair {
377 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
378 this.appNum = appNum;
380 this.varName = varName;
381 this.isManual = isManual;
384 void setAppNum(Integer appNum) {
385 this.appNum = appNum;
388 void setValue(String value) {
392 void setVarName(String varName) {
393 this.varName = varName;
396 void setIsManual(String varName) {
397 this.isManual = isManual;
400 Integer getAppNum() {
408 String getVarName() {
412 boolean getIsManual() {
417 public boolean equals(Object o) {
418 if (o instanceof NameValuePair) {
419 NameValuePair other = (NameValuePair) o;
420 if (varName.equals(other.getVarName()))
421 return appNum.equals(other.getAppNum());
427 public int hashCode() {
428 return appNum.hashCode() * 31 + varName.hashCode();
433 public void stateRestored(Search search) {
434 id = search.getStateId();
435 depth = search.getDepth();
436 operation = "restored";
439 out.println("The state is restored to state with id: "+id+", depth: "+depth);
441 // Update the parent node
442 if (nodes.containsKey(id)) {
443 parentNode = nodes.get(id);
445 parentNode = new Node(id);
450 public void searchStarted(Search search) {
451 out.println("----------------------------------- search started");
456 public void stateAdvanced(Search search) {
457 String theEnd = null;
458 Transition transition = search.getTransition();
459 id = search.getStateId();
460 depth = search.getDepth();
461 operation = "forward";
463 // Add the node to the list of nodes
464 if (nodes.get(id) == null)
465 nodes.put(id, new Node(id));
467 Node currentNode = nodes.get(id);
469 // Update the edge based on the current transition
470 updateTheEdge(currentNode, transition);
472 // Reset the temporary variables and flags
473 tempSetSet = new ArrayList<NameValuePair>();
476 // Check for the conflict in this transition
477 conflictFound = checkForConflict(parentNode, currentNode, transition);
479 if (search.isNewState()) {
485 if (search.isEndState()) {
486 out.println("This is the last state!");
490 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
492 // Updating the predecessors for this node
493 // Check if parent node is already in successors of the current node or not
494 if (!(currentNode.getPredecessors().contains(parentNode)))
495 currentNode.getPredecessors().add(parentNode);
497 // Update the successors for this node
498 // Check if current node is already in successors of the parent node or not
499 if (!(parentNode.getSuccessors().contains(currentNode)))
500 parentNode.getSuccessors().add(currentNode);
502 // Update the outset of the current node and check if it is changed or not to propagate the change
503 boolean isChanged = updateTheOutSet(parentNode, currentNode);
505 // Check if the outSet of this state has changed, update all of its successors' sets if any
507 for (Node node : currentNode.getSuccessors()) {
508 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
509 for (Map.Entry mapElement : setSets.entrySet()) {
510 Transition currentTransition = (Transition)mapElement.getKey();
511 conflictFound = conflictFound || checkForConflict(currentNode, node, currentTransition);
514 conflictFound = conflictFound || propagateTheChange(currentNode);
516 // Update the parent node
517 if (nodes.containsKey(id)) {
518 parentNode = nodes.get(id);
520 parentNode = new Node(id);
525 public void stateBacktracked(Search search) {
526 id = search.getStateId();
527 depth = search.getDepth();
528 operation = "backtrack";
531 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
533 // Update the parent node
534 if (nodes.containsKey(id)) {
535 parentNode = nodes.get(id);
537 parentNode = new Node(id);
542 public void searchFinished(Search search) {
543 out.println("----------------------------------- search finished");
546 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
550 frame = ti.getTopFrame();
552 if ((inst instanceof JVMLocalVariableInstruction) ||
553 (inst instanceof JVMFieldInstruction))
555 if (frame.getTopPos() < 0)
559 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
561 return(decodeValue(type, lo, hi));
564 if (inst instanceof JVMArrayElementInstruction)
565 return(getArrayValue(ti, type));
570 private final static String decodeValue(byte type, int lo, int hi) {
572 case Types.T_ARRAY: return(null);
573 case Types.T_VOID: return(null);
575 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
576 case Types.T_BYTE: return(String.valueOf(lo));
577 case Types.T_CHAR: return(String.valueOf((char) lo));
578 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
579 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
580 case Types.T_INT: return(String.valueOf(lo));
581 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
582 case Types.T_SHORT: return(String.valueOf(lo));
584 case Types.T_REFERENCE:
585 ElementInfo ei = VM.getVM().getHeap().get(lo);
589 ClassInfo ci = ei.getClassInfo();
593 if (ci.getName().equals("java.lang.String"))
594 return('"' + ei.asString() + '"');
596 return(ei.toString());
599 System.err.println("Unknown type: " + type);
604 private String getArrayValue(ThreadInfo ti, byte type) {
608 frame = ti.getTopFrame();
610 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
612 return(decodeValue(type, lo, hi));
615 private byte getType(ThreadInfo ti, Instruction inst) {
620 frame = ti.getTopFrame();
621 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
622 return (Types.T_REFERENCE);
627 if (inst instanceof JVMLocalVariableInstruction) {
628 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
629 } else if (inst instanceof JVMFieldInstruction){
630 fi = ((JVMFieldInstruction) inst).getFieldInfo();
634 if (inst instanceof JVMArrayElementInstruction) {
635 return (getTypeFromInstruction(inst));
639 return (Types.T_VOID);
642 return (decodeType(type));
645 private final static byte getTypeFromInstruction(Instruction inst) {
646 if (inst instanceof JVMArrayElementInstruction)
647 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
649 return(Types.T_VOID);
652 private final static byte decodeType(String type) {
653 if (type.charAt(0) == '?'){
654 return(Types.T_REFERENCE);
656 return Types.getBuiltinType(type);
660 // Find the variable writer
661 // It should be one of the apps listed in the .jpf file
662 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
663 // Start looking from the top of the stack backward
664 for(int i=sfList.size()-1; i>=0; i--) {
665 MethodInfo mi = sfList.get(i).getMethodInfo();
666 if(!mi.isJPFInternal()) {
667 String method = mi.getStackTraceName();
668 // Check against the writers in the writerSet
669 for(String writer : writerSet) {
670 if (method.contains(writer)) {
680 private void writeWriterAndValue(String writer, String value, String var) {
681 // Update the temporary Set set.
682 NameValuePair temp = new NameValuePair(1, value, var, manual);
683 if (writer.equals("App2"))
684 temp = new NameValuePair(2, value, var, manual);
686 tempSetSet.add(temp);
690 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
692 if (System.currentTimeMillis() - startTime > timeout) {
693 StringBuilder sbTimeOut = new StringBuilder();
694 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
695 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
696 ti.setNextPC(nextIns);
701 StringBuilder sb = new StringBuilder();
702 sb.append(errorMessage);
703 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
704 ti.setNextPC(nextIns);
706 if (conflictSet.contains(LOCATION_VAR)) {
707 MethodInfo mi = executedInsn.getMethodInfo();
708 // Find the last load before return and get the value here
709 if (mi.getName().equals(SET_LOCATION_METHOD) &&
710 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
711 byte type = getType(ti, executedInsn);
712 String value = getValue(ti, executedInsn, type);
714 // Extract the writer app name
715 ClassInfo ci = mi.getClassInfo();
716 String writer = ci.getName();
718 // Update the temporary Set set.
719 writeWriterAndValue(writer, value, LOCATION_VAR);
722 if (executedInsn instanceof WriteInstruction) {
723 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
725 for (String var : conflictSet) {
726 if (varId.contains(var)) {
728 byte type = getType(ti, executedInsn);
729 String value = getValue(ti, executedInsn, type);
730 String writer = getWriter(ti.getStack(), appSet);
731 // Just return if the writer is not one of the listed apps in the .jpf file
735 if (getWriter(ti.getStack(), manualSet) != null)
738 // Update the temporary Set set.
739 writeWriterAndValue(writer, value, var);