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 // All the changes in parents are propagated
116 parentQueueMap.get(nodeToProcess).clear();
118 // Check for a conflict if the outSet of nodeToProcess is changed
120 for (Node node : nodeToProcess.getSuccessors()) {
121 HashMap<Transition, ArrayList<NameValuePair>> setSets = nodeToProcess.getOutgoingEdges().get(node).getSetSetMap();
122 for (Map.Entry mapElement : setSets.entrySet()) {
123 Transition transition = (Transition)mapElement.getKey();
124 if (checkForConflict(nodeToProcess, node, transition))
130 // Update the parents list for the successors of the current node
132 parents.add(nodeToProcess);
134 // Checking if the out set has changed or not(Add its successors to the change list!)
136 for (Node i : nodeToProcess.getSuccessors()) {
137 if (!changed.contains(i))
140 // Update the list of updated parents for the current node
141 if (parentQueueMap.containsKey(i))
142 parentQueueMap.get(i).add(nodeToProcess);
144 parentQueueMap.put(i, parents);
151 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
152 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
153 " has written the value: "+pair.getValue()+
154 " to the variable: "+pair.getVarName()+" while App"
155 +writerMap.get(pair.getVarName())+" is overwriting the value: "
156 +valueMap.get(pair.getVarName())+" to the same variable!";
157 System.out.println(message);
161 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
162 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
163 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
164 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
165 HashMap<String, String> firstValueMap = new HashMap<String, String>(); // HashMap from varName to value - first instruction in transition
166 HashMap<String, Integer> firstWriterMap = new HashMap<String, Integer>(); // HashMap from varName to appNum - first instruction in transition
168 // Update the valueMap and writerMap + check for conflict between the elements of setSet
169 for (int i = 0;i < setSet.size();i++) {
170 NameValuePair nameValuePair = setSet.get(i);
171 String varName = nameValuePair.getVarName();
172 String value = nameValuePair.getValue();
173 Integer appNum = nameValuePair.getAppNum();
174 Boolean isManual = nameValuePair.getIsManual();
176 if (valueMap.containsKey(varName)) {
177 // Check if we have a same writer
178 if (!writerMap.get(varName).equals(appNum)) {
179 // Check if we have a conflict or not
180 if (!valueMap.get(varName).equals(value)) {
181 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
185 valueMap.put(varName, value);
186 writerMap.put(varName, appNum);
188 valueMap.put(varName, value);
189 writerMap.put(varName, appNum);
191 firstValueMap.put(varName, value);
192 firstWriterMap.put(varName, appNum);
197 // Check for conflict between outSet and this transition setSet
198 for (NameValuePair i : parentNode.getOutSet()) {
199 if (firstValueMap.containsKey(i.getVarName())) {
200 String value = firstValueMap.get(i.getVarName());
201 Integer writer = firstWriterMap.get(i.getVarName());
202 if ((value != null)&&(writer != null)) {
203 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
204 // We have different values and different writers
205 errorMessage = createErrorMessage(i, firstValueMap, firstWriterMap);
214 boolean updateTheOutSet(Node parentNode, Node currentNode) {
215 HashMap<Transition, ArrayList<NameValuePair>> setSets = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap();
216 HashSet<String> updatedVarNames = new HashSet<String>();
217 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
218 HashMap<String, Integer> lastWriter = currentEdge.getLastWriter();
219 HashMap<String, String> lastValue = currentEdge.getLastValue();
220 HashMap<String, Integer> outSetVarMap = new HashMap<String, Integer>();
221 boolean isChanged = false;
223 for (Map.Entry mapElement : setSets.entrySet()) {
224 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
226 for (int i = 0;i < setSet.size();i++) {
227 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));
260 void updateTheEdge(Node currentNode, Transition transition) {
261 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
262 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
263 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
265 currentEdge.getSetSetMap().put(transition, tempSetSet);
267 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
268 } else { // Add a new transition
269 currentEdge.getSetSetMap().put(transition, tempSetSet);
272 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
273 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
274 currentEdge.getSetSetMap().put(transition, tempSetSet);
277 // Update the last writer and last value for this edge for each varName
278 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
279 ArrayList<NameValuePair> setSet = currentEdge.getSetSetMap().get(transition);
280 for (int i = 0;i < setSet.size();i++) {
281 NameValuePair nameValuePair = setSet.get(i);
282 currentEdge.getLastWriter().put(nameValuePair.getVarName(), nameValuePair.getAppNum());
283 currentEdge.getLastValue().put(nameValuePair.getVarName(), nameValuePair.getValue());
291 HashSet<Node> predecessors = new HashSet<Node>();
292 HashSet<Node> successors = new HashSet<Node>();
293 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
294 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
304 HashSet<Node> getPredecessors() {
308 HashSet<Node> getSuccessors() {
312 HashSet<NameValuePair> getOutSet() {
316 HashMap<Node, Edge> getOutgoingEdges() {
317 return outgoingEdges;
322 Node source, destination;
323 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
324 HashMap<String, String> lastValue = new HashMap<String, String>();
325 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
327 Edge(Node source, Node destination) {
328 this.source = source;
329 this.destination = destination;
336 Node getDestination() {
340 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
344 HashMap<String, Integer> getLastWriter() {
348 HashMap<String, String> getLastValue() {
353 static class NameValuePair {
359 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
360 this.appNum = appNum;
362 this.varName = varName;
363 this.isManual = isManual;
366 void setAppNum(Integer appNum) {
367 this.appNum = appNum;
370 void setValue(String value) {
374 void setVarName(String varName) {
375 this.varName = varName;
378 void setIsManual(String varName) {
379 this.isManual = isManual;
382 Integer getAppNum() {
390 String getVarName() {
394 boolean getIsManual() {
399 public boolean equals(Object o) {
400 if (o instanceof NameValuePair) {
401 NameValuePair other = (NameValuePair) o;
402 if (varName.equals(other.getVarName()))
403 return appNum.equals(other.getAppNum());
409 public int hashCode() {
410 return appNum.hashCode() * 31 + varName.hashCode();
415 public void stateRestored(Search search) {
416 id = search.getStateId();
417 depth = search.getDepth();
418 operation = "restored";
421 out.println("The state is restored to state with id: "+id+", depth: "+depth);
423 // Update the parent node
424 if (nodes.containsKey(id)) {
425 parentNode = nodes.get(id);
427 parentNode = new Node(id);
432 public void searchStarted(Search search) {
433 out.println("----------------------------------- search started");
438 public void stateAdvanced(Search search) {
439 String theEnd = null;
440 Transition transition = search.getTransition();
441 id = search.getStateId();
442 depth = search.getDepth();
443 operation = "forward";
445 // Add the node to the list of nodes
446 if (nodes.get(id) == null)
447 nodes.put(id, new Node(id));
449 Node currentNode = nodes.get(id);
451 // Update the edge based on the current transition
452 updateTheEdge(currentNode, transition);
454 // Reset the temporary variables and flags
455 tempSetSet = new ArrayList<NameValuePair>();
458 // Check for the conflict in this transition
459 conflictFound = checkForConflict(parentNode, currentNode, transition);
461 if (search.isNewState()) {
467 if (search.isEndState()) {
468 out.println("This is the last state!");
472 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
474 // Updating the predecessors for this node
475 // Check if parent node is already in successors of the current node or not
476 if (!(currentNode.getPredecessors().contains(parentNode)))
477 currentNode.getPredecessors().add(parentNode);
479 // Update the successors for this node
480 // Check if current node is already in successors of the parent node or not
481 if (!(parentNode.getSuccessors().contains(currentNode)))
482 parentNode.getSuccessors().add(currentNode);
484 // Update the outset of the current node and check if it is changed or not to propagate the change
485 boolean isChanged = updateTheOutSet(parentNode, currentNode);
487 // Check if the outSet of this state has changed, update all of its successors' sets if any
489 for (Node node : currentNode.getSuccessors()) {
490 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
491 for (Map.Entry mapElement : setSets.entrySet()) {
492 Transition currentTransition = (Transition)mapElement.getKey();
493 conflictFound = conflictFound || checkForConflict(currentNode, node, currentTransition);
496 conflictFound = conflictFound || propagateTheChange(currentNode);
498 // Update the parent node
499 if (nodes.containsKey(id)) {
500 parentNode = nodes.get(id);
502 parentNode = new Node(id);
507 public void stateBacktracked(Search search) {
508 id = search.getStateId();
509 depth = search.getDepth();
510 operation = "backtrack";
513 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
515 // Update the parent node
516 if (nodes.containsKey(id)) {
517 parentNode = nodes.get(id);
519 parentNode = new Node(id);
524 public void searchFinished(Search search) {
525 out.println("----------------------------------- search finished");
528 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
532 frame = ti.getTopFrame();
534 if ((inst instanceof JVMLocalVariableInstruction) ||
535 (inst instanceof JVMFieldInstruction))
537 if (frame.getTopPos() < 0)
541 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
543 return(decodeValue(type, lo, hi));
546 if (inst instanceof JVMArrayElementInstruction)
547 return(getArrayValue(ti, type));
552 private final static String decodeValue(byte type, int lo, int hi) {
554 case Types.T_ARRAY: return(null);
555 case Types.T_VOID: return(null);
557 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
558 case Types.T_BYTE: return(String.valueOf(lo));
559 case Types.T_CHAR: return(String.valueOf((char) lo));
560 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
561 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
562 case Types.T_INT: return(String.valueOf(lo));
563 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
564 case Types.T_SHORT: return(String.valueOf(lo));
566 case Types.T_REFERENCE:
567 ElementInfo ei = VM.getVM().getHeap().get(lo);
571 ClassInfo ci = ei.getClassInfo();
575 if (ci.getName().equals("java.lang.String"))
576 return('"' + ei.asString() + '"');
578 return(ei.toString());
581 System.err.println("Unknown type: " + type);
586 private String getArrayValue(ThreadInfo ti, byte type) {
590 frame = ti.getTopFrame();
592 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
594 return(decodeValue(type, lo, hi));
597 private byte getType(ThreadInfo ti, Instruction inst) {
602 frame = ti.getTopFrame();
603 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
604 return (Types.T_REFERENCE);
609 if (inst instanceof JVMLocalVariableInstruction) {
610 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
611 } else if (inst instanceof JVMFieldInstruction){
612 fi = ((JVMFieldInstruction) inst).getFieldInfo();
616 if (inst instanceof JVMArrayElementInstruction) {
617 return (getTypeFromInstruction(inst));
621 return (Types.T_VOID);
624 return (decodeType(type));
627 private final static byte getTypeFromInstruction(Instruction inst) {
628 if (inst instanceof JVMArrayElementInstruction)
629 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
631 return(Types.T_VOID);
634 private final static byte decodeType(String type) {
635 if (type.charAt(0) == '?'){
636 return(Types.T_REFERENCE);
638 return Types.getBuiltinType(type);
642 // Find the variable writer
643 // It should be one of the apps listed in the .jpf file
644 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
645 // Start looking from the top of the stack backward
646 for(int i=sfList.size()-1; i>=0; i--) {
647 MethodInfo mi = sfList.get(i).getMethodInfo();
648 if(!mi.isJPFInternal()) {
649 String method = mi.getStackTraceName();
650 // Check against the writers in the writerSet
651 for(String writer : writerSet) {
652 if (method.contains(writer)) {
662 private void writeWriterAndValue(String writer, String value, String var) {
663 // Update the temporary Set set.
664 NameValuePair temp = new NameValuePair(1, value, var, manual);
665 if (writer.equals("App2"))
666 temp = new NameValuePair(2, value, var, manual);
668 tempSetSet.add(temp);
672 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
674 if (System.currentTimeMillis() - startTime > timeout) {
675 StringBuilder sbTimeOut = new StringBuilder();
676 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
677 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
678 ti.setNextPC(nextIns);
683 StringBuilder sb = new StringBuilder();
684 sb.append(errorMessage);
685 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
686 ti.setNextPC(nextIns);
688 if (conflictSet.contains(LOCATION_VAR)) {
689 MethodInfo mi = executedInsn.getMethodInfo();
690 // Find the last load before return and get the value here
691 if (mi.getName().equals(SET_LOCATION_METHOD) &&
692 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
693 byte type = getType(ti, executedInsn);
694 String value = getValue(ti, executedInsn, type);
696 // Extract the writer app name
697 ClassInfo ci = mi.getClassInfo();
698 String writer = ci.getName();
700 // Update the temporary Set set.
701 writeWriterAndValue(writer, value, LOCATION_VAR);
704 if (executedInsn instanceof WriteInstruction) {
705 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
707 for (String var : conflictSet) {
708 if (varId.contains(var)) {
710 byte type = getType(ti, executedInsn);
711 String value = getValue(ti, executedInsn, type);
712 String writer = getWriter(ti.getStack(), appSet);
713 // Just return if the writer is not one of the listed apps in the .jpf file
717 if (getWriter(ti.getStack(), manualSet) != null)
720 // Update the temporary Set set.
721 writeWriterAndValue(writer, value, var);