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 boolean isChanged = false;
94 for (Node node : currentNode.getSuccessors()) {
96 isChanged = updateTheOutSet(currentNode, node);
101 while(!changed.isEmpty()) {
102 // Get the first element of the changed set and remove it
103 Node nodeToProcess = changed.iterator().next();
104 changed.remove(nodeToProcess);
106 // Update all the successors of the node
107 for (Node node : nodeToProcess.getSuccessors()) {
109 isChanged = updateTheOutSet(nodeToProcess, node);
112 if (checkAllSuccForConflict(node))
120 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
121 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
122 " has written the value: "+pair.getValue()+
123 " to the variable: "+pair.getVarName()+" while App"
124 +writerMap.get(pair.getVarName())+" is overwriting the value: "
125 +valueMap.get(pair.getVarName())+" to the same variable!";
126 System.out.println(message);
130 boolean checkAllSuccForConflict(Node currentNode) {
131 for (Node node : currentNode.getSuccessors()) {
132 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
133 for (Map.Entry mapElement : setSets.entrySet()) {
134 Transition transition = (Transition)mapElement.getKey();
135 if (checkForConflict(currentNode, node, transition))
142 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
143 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
144 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
145 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
146 HashMap<String, String> firstValueMap = new HashMap<String, String>(); // HashMap from varName to value - first instruction in transition
147 HashMap<String, Integer> firstWriterMap = new HashMap<String, Integer>(); // HashMap from varName to appNum - first instruction in transition
149 // Update the valueMap and writerMap + check for conflict between the elements of setSet
150 for (int i = 0;i < setSet.size();i++) {
151 NameValuePair nameValuePair = setSet.get(i);
152 String varName = nameValuePair.getVarName();
153 String value = nameValuePair.getValue();
154 Integer appNum = nameValuePair.getAppNum();
155 Boolean isManual = nameValuePair.getIsManual();
157 if (valueMap.containsKey(varName)) {
158 // Check if we have a same writer
159 if (!writerMap.get(varName).equals(appNum)) {
160 // Check if we have a conflict or not
161 if (!valueMap.get(varName).equals(value)) {
162 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
166 valueMap.put(varName, value);
167 writerMap.put(varName, appNum);
169 valueMap.put(varName, value);
170 writerMap.put(varName, appNum);
172 firstValueMap.put(varName, value);
173 firstWriterMap.put(varName, appNum);
178 // Check for conflict between outSet and this transition setSet
179 for (NameValuePair i : parentNode.getOutSet()) {
180 if (firstValueMap.containsKey(i.getVarName())) {
181 String value = firstValueMap.get(i.getVarName());
182 Integer writer = firstWriterMap.get(i.getVarName());
183 if ((value != null)&&(writer != null)) {
184 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
185 // We have different values and different writers
186 errorMessage = createErrorMessage(i, firstValueMap, firstWriterMap);
195 boolean updateTheOutSet(Node parentNode, Node currentNode) {
196 Edge edge = parentNode.getOutgoingEdges().get(currentNode);
197 HashMap<Transition, ArrayList<NameValuePair>> setSets = edge.getSetSetMap();
198 HashSet<String> updatedVarNames = new HashSet<String>();
199 HashSet<String> outSetVarMap = new HashSet<String>();
200 boolean isChanged = false;
202 for (Map.Entry mapElement : setSets.entrySet()) {
203 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
205 for (int i = 0;i < setSet.size();i++) {
206 updatedVarNames.add(setSet.get(i).getVarName());
210 for (NameValuePair i : parentNode.getOutSet()) {
211 outSetVarMap.add(i.getVarName());
212 if (!updatedVarNames.contains(i.getVarName()))
213 isChanged |= currentNode.getOutSet().add(i);
216 ArrayList<NameValuePair> lastSetSet = setSets.get(edge.getFinalTransition());
218 for (int i = 0;i < lastSetSet.size();i++) {
219 String var = lastSetSet.get(i).getVarName();
221 if (outSetVarMap.contains(var)) {
222 currentNode.getOutSet().remove(lastSetSet.get(i));
224 isChanged |= currentNode.getOutSet().add(lastSetSet.get(i));
229 void updateTheEdge(Node currentNode, Transition transition) {
230 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
231 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
232 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
234 currentEdge.getSetSetMap().put(transition, tempSetSet);
236 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
237 } else { // Add a new transition
238 currentEdge.getSetSetMap().put(transition, tempSetSet);
240 currentEdge.setFinalTransition(transition);
242 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
243 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
244 currentEdge.getSetSetMap().put(transition, tempSetSet);
245 currentEdge.setFinalTransition(transition);
251 HashSet<Node> predecessors = new HashSet<Node>();
252 HashSet<Node> successors = new HashSet<Node>();
253 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
254 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
264 HashSet<Node> getPredecessors() {
268 HashSet<Node> getSuccessors() {
272 HashSet<NameValuePair> getOutSet() {
276 HashMap<Node, Edge> getOutgoingEdges() {
277 return outgoingEdges;
282 Node source, destination;
283 Transition finalTransition;
284 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
285 HashMap<String, String> lastValue = new HashMap<String, String>();
286 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
288 Edge(Node source, Node destination) {
289 this.source = source;
290 this.destination = destination;
297 Node getDestination() {
301 Transition getFinalTransition() {
302 return finalTransition;
305 void setFinalTransition(Transition transition) {
306 finalTransition = transition;
309 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
313 HashMap<String, Integer> getLastWriter() {
317 HashMap<String, String> getLastValue() {
322 static class NameValuePair {
328 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
329 this.appNum = appNum;
331 this.varName = varName;
332 this.isManual = isManual;
335 void setAppNum(Integer appNum) {
336 this.appNum = appNum;
339 void setValue(String value) {
343 void setVarName(String varName) {
344 this.varName = varName;
347 void setIsManual(String varName) {
348 this.isManual = isManual;
351 Integer getAppNum() {
359 String getVarName() {
363 boolean getIsManual() {
368 public boolean equals(Object o) {
369 if (o instanceof NameValuePair) {
370 NameValuePair other = (NameValuePair) o;
371 if (varName.equals(other.getVarName()))
372 return appNum.equals(other.getAppNum());
378 public int hashCode() {
379 return appNum.hashCode() * 31 + varName.hashCode();
384 public void stateRestored(Search search) {
385 id = search.getStateId();
386 depth = search.getDepth();
387 operation = "restored";
390 out.println("The state is restored to state with id: "+id+", depth: "+depth);
392 // Update the parent node
393 if (nodes.containsKey(id)) {
394 parentNode = nodes.get(id);
396 parentNode = new Node(id);
401 public void searchStarted(Search search) {
402 out.println("----------------------------------- search started");
407 public void stateAdvanced(Search search) {
408 String theEnd = null;
409 Transition transition = search.getTransition();
410 id = search.getStateId();
411 depth = search.getDepth();
412 operation = "forward";
414 // Add the node to the list of nodes
415 if (nodes.get(id) == null)
416 nodes.put(id, new Node(id));
418 Node currentNode = nodes.get(id);
420 // Update the edge based on the current transition
421 updateTheEdge(currentNode, transition);
423 // Reset the temporary variables and flags
424 tempSetSet = new ArrayList<NameValuePair>();
427 // Check for the conflict in this transition
428 conflictFound = checkForConflict(parentNode, currentNode, transition);
430 if (search.isNewState()) {
436 if (search.isEndState()) {
437 out.println("This is the last state!");
441 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
443 // Updating the predecessors for this node
444 // Check if parent node is already in successors of the current node or not
445 if (!(currentNode.getPredecessors().contains(parentNode)))
446 currentNode.getPredecessors().add(parentNode);
448 // Update the successors for this node
449 // Check if current node is already in successors of the parent node or not
450 if (!(parentNode.getSuccessors().contains(currentNode)))
451 parentNode.getSuccessors().add(currentNode);
453 // Update the outset of the current node and check if it is changed or not to propagate the change
454 boolean isChanged = updateTheOutSet(parentNode, currentNode);
456 // Check if the outSet of this state has changed, update all of its successors' sets if any
458 conflictFound = conflictFound || checkAllSuccForConflict(currentNode) || propagateTheChange(currentNode);
460 // Update the parent node
461 if (nodes.containsKey(id)) {
462 parentNode = nodes.get(id);
464 parentNode = new Node(id);
469 public void stateBacktracked(Search search) {
470 id = search.getStateId();
471 depth = search.getDepth();
472 operation = "backtrack";
475 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
477 // Update the parent node
478 if (nodes.containsKey(id)) {
479 parentNode = nodes.get(id);
481 parentNode = new Node(id);
486 public void searchFinished(Search search) {
487 out.println("----------------------------------- search finished");
490 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
494 frame = ti.getTopFrame();
496 if ((inst instanceof JVMLocalVariableInstruction) ||
497 (inst instanceof JVMFieldInstruction))
499 if (frame.getTopPos() < 0)
503 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
505 return(decodeValue(type, lo, hi));
508 if (inst instanceof JVMArrayElementInstruction)
509 return(getArrayValue(ti, type));
514 private final static String decodeValue(byte type, int lo, int hi) {
516 case Types.T_ARRAY: return(null);
517 case Types.T_VOID: return(null);
519 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
520 case Types.T_BYTE: return(String.valueOf(lo));
521 case Types.T_CHAR: return(String.valueOf((char) lo));
522 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
523 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
524 case Types.T_INT: return(String.valueOf(lo));
525 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
526 case Types.T_SHORT: return(String.valueOf(lo));
528 case Types.T_REFERENCE:
529 ElementInfo ei = VM.getVM().getHeap().get(lo);
533 ClassInfo ci = ei.getClassInfo();
537 if (ci.getName().equals("java.lang.String"))
538 return('"' + ei.asString() + '"');
540 return(ei.toString());
543 System.err.println("Unknown type: " + type);
548 private String getArrayValue(ThreadInfo ti, byte type) {
552 frame = ti.getTopFrame();
554 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
556 return(decodeValue(type, lo, hi));
559 private byte getType(ThreadInfo ti, Instruction inst) {
564 frame = ti.getTopFrame();
565 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
566 return (Types.T_REFERENCE);
571 if (inst instanceof JVMLocalVariableInstruction) {
572 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
573 } else if (inst instanceof JVMFieldInstruction){
574 fi = ((JVMFieldInstruction) inst).getFieldInfo();
578 if (inst instanceof JVMArrayElementInstruction) {
579 return (getTypeFromInstruction(inst));
583 return (Types.T_VOID);
586 return (decodeType(type));
589 private final static byte getTypeFromInstruction(Instruction inst) {
590 if (inst instanceof JVMArrayElementInstruction)
591 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
593 return(Types.T_VOID);
596 private final static byte decodeType(String type) {
597 if (type.charAt(0) == '?'){
598 return(Types.T_REFERENCE);
600 return Types.getBuiltinType(type);
604 // Find the variable writer
605 // It should be one of the apps listed in the .jpf file
606 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
607 // Start looking from the top of the stack backward
608 for(int i=sfList.size()-1; i>=0; i--) {
609 MethodInfo mi = sfList.get(i).getMethodInfo();
610 if(!mi.isJPFInternal()) {
611 String method = mi.getStackTraceName();
612 // Check against the writers in the writerSet
613 for(String writer : writerSet) {
614 if (method.contains(writer)) {
624 private void writeWriterAndValue(String writer, String value, String var) {
625 // Update the temporary Set set.
626 NameValuePair temp = new NameValuePair(1, value, var, manual);
627 if (writer.equals("App2"))
628 temp = new NameValuePair(2, value, var, manual);
630 tempSetSet.add(temp);
634 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
636 if (System.currentTimeMillis() - startTime > timeout) {
637 StringBuilder sbTimeOut = new StringBuilder();
638 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
639 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
640 ti.setNextPC(nextIns);
645 StringBuilder sb = new StringBuilder();
646 sb.append(errorMessage);
647 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
648 ti.setNextPC(nextIns);
650 if (conflictSet.contains(LOCATION_VAR)) {
651 MethodInfo mi = executedInsn.getMethodInfo();
652 // Find the last load before return and get the value here
653 if (mi.getName().equals(SET_LOCATION_METHOD) &&
654 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
655 byte type = getType(ti, executedInsn);
656 String value = getValue(ti, executedInsn, type);
658 // Extract the writer app name
659 ClassInfo ci = mi.getClassInfo();
660 String writer = ci.getName();
662 // Update the temporary Set set.
663 writeWriterAndValue(writer, value, LOCATION_VAR);
666 if (executedInsn instanceof WriteInstruction) {
667 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
669 for (String var : conflictSet) {
670 if (varId.contains(var)) {
672 byte type = getType(ti, executedInsn);
673 String value = getValue(ti, executedInsn, type);
674 String writer = getWriter(ti.getStack(), appSet);
675 // Just return if the writer is not one of the listed apps in the .jpf file
679 if (getWriter(ti.getStack(), manualSet) != null)
682 // Update the temporary Set set.
683 writeWriterAndValue(writer, value, var);