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 HashMap<Transition, ArrayList<NameValuePair>> setSets = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap();
197 HashSet<String> updatedVarNames = new HashSet<String>();
198 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
199 HashMap<String, Integer> lastWriter = currentEdge.getLastWriter();
200 HashMap<String, String> lastValue = currentEdge.getLastValue();
201 HashMap<String, Integer> outSetVarMap = new HashMap<String, Integer>();
202 boolean isChanged = false;
204 for (Map.Entry mapElement : setSets.entrySet()) {
205 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
207 for (int i = 0;i < setSet.size();i++) {
208 updatedVarNames.add(setSet.get(i).getVarName());
212 for (NameValuePair i : parentNode.getOutSet()) {
213 outSetVarMap.put(i.getVarName(), i.getAppNum());
214 if (!updatedVarNames.contains(i.getVarName()))
215 isChanged |= currentNode.getOutSet().add(i);
219 for (Map.Entry mapElement : setSets.entrySet()) {
220 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
222 for (int i = 0;i < setSet.size();i++) {
223 String varName = setSet.get(i).getVarName();
224 Integer writer = lastWriter.get(varName);
225 String value = lastValue.get(varName);
227 if (setSet.get(i).getAppNum().equals(writer)
228 && setSet.get(i).getValue().equals(value)) {
229 if (outSetVarMap.containsKey(varName)) {
230 Integer hashCode = outSetVarMap.get(varName).hashCode() * 31 +
232 currentNode.getOutSet().remove(hashCode);
234 isChanged |= currentNode.getOutSet().add(setSet.get(i));
241 void updateTheEdge(Node currentNode, Transition transition) {
242 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
243 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
244 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
246 currentEdge.getSetSetMap().put(transition, tempSetSet);
248 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
249 } else { // Add a new transition
250 currentEdge.getSetSetMap().put(transition, tempSetSet);
253 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
254 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
255 currentEdge.getSetSetMap().put(transition, tempSetSet);
258 // Update the last writer and last value for this edge for each varName
259 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
260 ArrayList<NameValuePair> setSet = currentEdge.getSetSetMap().get(transition);
261 for (int i = 0;i < setSet.size();i++) {
262 NameValuePair nameValuePair = setSet.get(i);
263 currentEdge.getLastWriter().put(nameValuePair.getVarName(), nameValuePair.getAppNum());
264 currentEdge.getLastValue().put(nameValuePair.getVarName(), nameValuePair.getValue());
272 HashSet<Node> predecessors = new HashSet<Node>();
273 HashSet<Node> successors = new HashSet<Node>();
274 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
275 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
285 HashSet<Node> getPredecessors() {
289 HashSet<Node> getSuccessors() {
293 HashSet<NameValuePair> getOutSet() {
297 HashMap<Node, Edge> getOutgoingEdges() {
298 return outgoingEdges;
303 Node source, destination;
304 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
305 HashMap<String, String> lastValue = new HashMap<String, String>();
306 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
308 Edge(Node source, Node destination) {
309 this.source = source;
310 this.destination = destination;
317 Node getDestination() {
321 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
325 HashMap<String, Integer> getLastWriter() {
329 HashMap<String, String> getLastValue() {
334 static class NameValuePair {
340 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
341 this.appNum = appNum;
343 this.varName = varName;
344 this.isManual = isManual;
347 void setAppNum(Integer appNum) {
348 this.appNum = appNum;
351 void setValue(String value) {
355 void setVarName(String varName) {
356 this.varName = varName;
359 void setIsManual(String varName) {
360 this.isManual = isManual;
363 Integer getAppNum() {
371 String getVarName() {
375 boolean getIsManual() {
380 public boolean equals(Object o) {
381 if (o instanceof NameValuePair) {
382 NameValuePair other = (NameValuePair) o;
383 if (varName.equals(other.getVarName()))
384 return appNum.equals(other.getAppNum());
390 public int hashCode() {
391 return appNum.hashCode() * 31 + varName.hashCode();
396 public void stateRestored(Search search) {
397 id = search.getStateId();
398 depth = search.getDepth();
399 operation = "restored";
402 out.println("The state is restored to state with id: "+id+", depth: "+depth);
404 if (id == 24 && depth == 5) {
405 System.out.println("*****************************************");
406 System.out.println("*****************************************");
407 System.out.println("*****************************************");
409 // Update the parent node
410 if (nodes.containsKey(id)) {
411 parentNode = nodes.get(id);
413 parentNode = new Node(id);
418 public void searchStarted(Search search) {
419 out.println("----------------------------------- search started");
424 public void stateAdvanced(Search search) {
425 String theEnd = null;
426 Transition transition = search.getTransition();
427 id = search.getStateId();
428 depth = search.getDepth();
429 operation = "forward";
431 // Add the node to the list of nodes
432 if (nodes.get(id) == null)
433 nodes.put(id, new Node(id));
435 Node currentNode = nodes.get(id);
437 // Update the edge based on the current transition
438 updateTheEdge(currentNode, transition);
440 // Reset the temporary variables and flags
441 tempSetSet = new ArrayList<NameValuePair>();
444 // Check for the conflict in this transition
445 conflictFound = checkForConflict(parentNode, currentNode, transition);
447 if (search.isNewState()) {
453 if (search.isEndState()) {
454 out.println("This is the last state!");
458 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
460 // Updating the predecessors for this node
461 // Check if parent node is already in successors of the current node or not
462 if (!(currentNode.getPredecessors().contains(parentNode)))
463 currentNode.getPredecessors().add(parentNode);
465 // Update the successors for this node
466 // Check if current node is already in successors of the parent node or not
467 if (!(parentNode.getSuccessors().contains(currentNode)))
468 parentNode.getSuccessors().add(currentNode);
470 // Update the outset of the current node and check if it is changed or not to propagate the change
471 boolean isChanged = updateTheOutSet(parentNode, currentNode);
474 System.out.println("######################### The outset is:");
475 for (NameValuePair nvp : currentNode.getOutSet()) {
476 System.out.println("writer: "+nvp.getAppNum());
477 System.out.println("value: "+nvp.getValue());
478 System.out.println("var : "+nvp.getVarName());
480 // Check if the outSet of this state has changed, update all of its successors' sets if any
482 conflictFound = conflictFound || checkAllSuccForConflict(currentNode) || propagateTheChange(currentNode);
484 // Update the parent node
485 if (nodes.containsKey(id)) {
486 parentNode = nodes.get(id);
488 parentNode = new Node(id);
493 public void stateBacktracked(Search search) {
494 id = search.getStateId();
495 depth = search.getDepth();
496 operation = "backtrack";
499 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
501 if (id == 24 && depth == 5) {
502 System.out.println("*****************************************");
503 System.out.println("*****************************************");
504 System.out.println("*****************************************");
507 // Update the parent node
508 if (nodes.containsKey(id)) {
509 parentNode = nodes.get(id);
511 parentNode = new Node(id);
516 public void searchFinished(Search search) {
517 out.println("----------------------------------- search finished");
520 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
524 frame = ti.getTopFrame();
526 if ((inst instanceof JVMLocalVariableInstruction) ||
527 (inst instanceof JVMFieldInstruction))
529 if (frame.getTopPos() < 0)
533 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
535 return(decodeValue(type, lo, hi));
538 if (inst instanceof JVMArrayElementInstruction)
539 return(getArrayValue(ti, type));
544 private final static String decodeValue(byte type, int lo, int hi) {
546 case Types.T_ARRAY: return(null);
547 case Types.T_VOID: return(null);
549 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
550 case Types.T_BYTE: return(String.valueOf(lo));
551 case Types.T_CHAR: return(String.valueOf((char) lo));
552 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
553 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
554 case Types.T_INT: return(String.valueOf(lo));
555 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
556 case Types.T_SHORT: return(String.valueOf(lo));
558 case Types.T_REFERENCE:
559 ElementInfo ei = VM.getVM().getHeap().get(lo);
563 ClassInfo ci = ei.getClassInfo();
567 if (ci.getName().equals("java.lang.String"))
568 return('"' + ei.asString() + '"');
570 return(ei.toString());
573 System.err.println("Unknown type: " + type);
578 private String getArrayValue(ThreadInfo ti, byte type) {
582 frame = ti.getTopFrame();
584 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
586 return(decodeValue(type, lo, hi));
589 private byte getType(ThreadInfo ti, Instruction inst) {
594 frame = ti.getTopFrame();
595 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
596 return (Types.T_REFERENCE);
601 if (inst instanceof JVMLocalVariableInstruction) {
602 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
603 } else if (inst instanceof JVMFieldInstruction){
604 fi = ((JVMFieldInstruction) inst).getFieldInfo();
608 if (inst instanceof JVMArrayElementInstruction) {
609 return (getTypeFromInstruction(inst));
613 return (Types.T_VOID);
616 return (decodeType(type));
619 private final static byte getTypeFromInstruction(Instruction inst) {
620 if (inst instanceof JVMArrayElementInstruction)
621 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
623 return(Types.T_VOID);
626 private final static byte decodeType(String type) {
627 if (type.charAt(0) == '?'){
628 return(Types.T_REFERENCE);
630 return Types.getBuiltinType(type);
634 // Find the variable writer
635 // It should be one of the apps listed in the .jpf file
636 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
637 // Start looking from the top of the stack backward
638 for(int i=sfList.size()-1; i>=0; i--) {
639 MethodInfo mi = sfList.get(i).getMethodInfo();
640 if(!mi.isJPFInternal()) {
641 String method = mi.getStackTraceName();
642 // Check against the writers in the writerSet
643 for(String writer : writerSet) {
644 if (method.contains(writer)) {
654 private void writeWriterAndValue(String writer, String value, String var) {
655 // Update the temporary Set set.
656 NameValuePair temp = new NameValuePair(1, value, var, manual);
657 if (writer.equals("App2"))
658 temp = new NameValuePair(2, value, var, manual);
660 tempSetSet.add(temp);
664 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
666 if (System.currentTimeMillis() - startTime > timeout) {
667 StringBuilder sbTimeOut = new StringBuilder();
668 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
669 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
670 ti.setNextPC(nextIns);
675 StringBuilder sb = new StringBuilder();
676 sb.append(errorMessage);
677 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
678 ti.setNextPC(nextIns);
680 if (conflictSet.contains(LOCATION_VAR)) {
681 MethodInfo mi = executedInsn.getMethodInfo();
682 // Find the last load before return and get the value here
683 if (mi.getName().equals(SET_LOCATION_METHOD) &&
684 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
685 byte type = getType(ti, executedInsn);
686 String value = getValue(ti, executedInsn, type);
688 // Extract the writer app name
689 ClassInfo ci = mi.getClassInfo();
690 String writer = ci.getName();
692 // Update the temporary Set set.
693 writeWriterAndValue(writer, value, LOCATION_VAR);
696 if (executedInsn instanceof WriteInstruction) {
697 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
699 for (String var : conflictSet) {
700 if (varId.contains(var)) {
702 byte type = getType(ti, executedInsn);
703 String value = getValue(ti, executedInsn, type);
704 String writer = getWriter(ti.getStack(), appSet);
705 // Just return if the writer is not one of the listed apps in the .jpf file
709 if (getWriter(ti.getStack(), manualSet) != null)
712 System.out.println("############################## writer: "+writer);
713 System.out.println("############################## value: "+value);
714 System.out.println("############################## var: "+var);
715 // Update the temporary Set set.
716 writeWriterAndValue(writer, value, var);