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>();
92 boolean isChanged = false;
94 // Add the current node to the changed set
95 changed.add(currentNode);
97 while(!changed.isEmpty()) {
98 // Get the first element of the changed set and remove it
99 Node nodeToProcess = changed.iterator().next();
100 changed.remove(nodeToProcess);
102 // Update all the successors of the node
103 for (Node node : nodeToProcess.getSuccessors()) {
105 isChanged = updateTheOutSet(nodeToProcess, node);
108 if (checkAllSuccForConflict(node))
116 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
117 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
118 " has written the value: "+pair.getValue()+
119 " to the variable: "+pair.getVarName()+" while App"
120 +writerMap.get(pair.getVarName())+" is overwriting the value: "
121 +valueMap.get(pair.getVarName())+" to the same variable!";
122 System.out.println(message);
126 boolean checkAllSuccForConflict(Node currentNode) {
127 for (Node node : currentNode.getSuccessors()) {
128 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
129 for (Map.Entry mapElement : setSets.entrySet()) {
130 Transition transition = (Transition)mapElement.getKey();
131 if (checkForConflict(currentNode, node, transition))
138 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
139 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
140 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
141 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
142 HashMap<String, String> firstValueMap = new HashMap<String, String>(); // HashMap from varName to value - first instruction in transition
143 HashMap<String, Integer> firstWriterMap = new HashMap<String, Integer>(); // HashMap from varName to appNum - first instruction in transition
145 // Update the valueMap and writerMap + check for conflict between the elements of setSet
146 for (int i = 0;i < setSet.size();i++) {
147 NameValuePair nameValuePair = setSet.get(i);
148 String varName = nameValuePair.getVarName();
149 String value = nameValuePair.getValue();
150 Integer appNum = nameValuePair.getAppNum();
151 Boolean isManual = nameValuePair.getIsManual();
153 if (valueMap.containsKey(varName)) {
154 // Check if we have a same writer
155 if (!writerMap.get(varName).equals(appNum)) {
156 // Check if we have a conflict or not
157 if (!valueMap.get(varName).equals(value)) {
158 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
162 valueMap.put(varName, value);
163 writerMap.put(varName, appNum);
165 valueMap.put(varName, value);
166 writerMap.put(varName, appNum);
168 firstValueMap.put(varName, value);
169 firstWriterMap.put(varName, appNum);
174 // Check for conflict between outSet and this transition setSet
175 for (NameValuePair i : parentNode.getOutSet()) {
176 if (firstValueMap.containsKey(i.getVarName())) {
177 String value = firstValueMap.get(i.getVarName());
178 Integer writer = firstWriterMap.get(i.getVarName());
179 if ((value != null)&&(writer != null)) {
180 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
181 // We have different values and different writers
182 errorMessage = createErrorMessage(i, firstValueMap, firstWriterMap);
191 boolean updateTheOutSet(Node parentNode, Node currentNode) {
192 Edge edge = parentNode.getOutgoingEdges().get(currentNode);
193 HashMap<Transition, ArrayList<NameValuePair>> setSets = edge.getSetSetMap();
194 HashSet<String> updatedVarNames = new HashSet<String>();
195 HashSet<String> outSetVarMap = new HashSet<String>();
196 boolean isChanged = false;
198 for (Map.Entry mapElement : setSets.entrySet()) {
199 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
201 for (int i = 0;i < setSet.size();i++) {
202 updatedVarNames.add(setSet.get(i).getVarName());
206 for (NameValuePair i : parentNode.getOutSet()) {
207 outSetVarMap.add(i.getVarName());
208 if (!updatedVarNames.contains(i.getVarName()))
209 isChanged |= currentNode.getOutSet().add(i);
212 ArrayList<NameValuePair> lastSetSet = setSets.get(edge.getFinalTransition());
214 for (int i = 0;i < lastSetSet.size();i++) {
215 String var = lastSetSet.get(i).getVarName();
217 if (outSetVarMap.contains(var)) {
218 currentNode.getOutSet().remove(lastSetSet.get(i));
220 isChanged |= currentNode.getOutSet().add(lastSetSet.get(i));
225 void updateTheEdge(Node currentNode, Transition transition) {
226 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
227 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
228 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
230 currentEdge.getSetSetMap().put(transition, tempSetSet);
232 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
233 } else { // Add a new transition
234 currentEdge.getSetSetMap().put(transition, tempSetSet);
236 currentEdge.setFinalTransition(transition);
238 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
239 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
240 currentEdge.getSetSetMap().put(transition, tempSetSet);
241 currentEdge.setFinalTransition(transition);
247 HashSet<Node> predecessors = new HashSet<Node>();
248 HashSet<Node> successors = new HashSet<Node>();
249 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
250 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
260 HashSet<Node> getPredecessors() {
264 HashSet<Node> getSuccessors() {
268 HashSet<NameValuePair> getOutSet() {
272 HashMap<Node, Edge> getOutgoingEdges() {
273 return outgoingEdges;
278 Node source, destination;
279 Transition finalTransition;
280 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
281 HashMap<String, String> lastValue = new HashMap<String, String>();
282 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
284 Edge(Node source, Node destination) {
285 this.source = source;
286 this.destination = destination;
293 Node getDestination() {
297 Transition getFinalTransition() {
298 return finalTransition;
301 void setFinalTransition(Transition transition) {
302 finalTransition = transition;
305 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
309 HashMap<String, Integer> getLastWriter() {
313 HashMap<String, String> getLastValue() {
318 static class NameValuePair {
324 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
325 this.appNum = appNum;
327 this.varName = varName;
328 this.isManual = isManual;
331 void setAppNum(Integer appNum) {
332 this.appNum = appNum;
335 void setValue(String value) {
339 void setVarName(String varName) {
340 this.varName = varName;
343 void setIsManual(String varName) {
344 this.isManual = isManual;
347 Integer getAppNum() {
355 String getVarName() {
359 boolean getIsManual() {
364 public boolean equals(Object o) {
365 if (o instanceof NameValuePair) {
366 NameValuePair other = (NameValuePair) o;
367 if (varName.equals(other.getVarName()))
368 return appNum.equals(other.getAppNum());
374 public int hashCode() {
375 return appNum.hashCode() * 31 + varName.hashCode();
380 public void stateRestored(Search search) {
381 id = search.getStateId();
382 depth = search.getDepth();
383 operation = "restored";
386 out.println("The state is restored to state with id: "+id+", depth: "+depth);
388 // Update the parent node
389 if (nodes.containsKey(id)) {
390 parentNode = nodes.get(id);
392 parentNode = new Node(id);
397 public void searchStarted(Search search) {
398 out.println("----------------------------------- search started");
403 public void stateAdvanced(Search search) {
404 String theEnd = null;
405 Transition transition = search.getTransition();
406 id = search.getStateId();
407 depth = search.getDepth();
408 operation = "forward";
410 // Add the node to the list of nodes
411 if (nodes.get(id) == null)
412 nodes.put(id, new Node(id));
414 Node currentNode = nodes.get(id);
416 // Update the edge based on the current transition
417 updateTheEdge(currentNode, transition);
419 // Reset the temporary variables and flags
420 tempSetSet = new ArrayList<NameValuePair>();
423 // Check for the conflict in this transition
424 conflictFound = checkForConflict(parentNode, currentNode, transition);
426 if (search.isNewState()) {
432 if (search.isEndState()) {
433 out.println("This is the last state!");
437 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
439 // Updating the predecessors for this node
440 // Check if parent node is already in successors of the current node or not
441 if (!(currentNode.getPredecessors().contains(parentNode)))
442 currentNode.getPredecessors().add(parentNode);
444 // Update the successors for this node
445 // Check if current node is already in successors of the parent node or not
446 if (!(parentNode.getSuccessors().contains(currentNode)))
447 parentNode.getSuccessors().add(currentNode);
449 // Update the outset of the current node and check if it is changed or not to propagate the change
450 boolean isChanged = updateTheOutSet(parentNode, currentNode);
452 // Check if the outSet of this state has changed, update all of its successors' sets if any
454 conflictFound = conflictFound || checkAllSuccForConflict(currentNode) || propagateTheChange(currentNode);
456 // Update the parent node
457 if (nodes.containsKey(id)) {
458 parentNode = nodes.get(id);
460 parentNode = new Node(id);
465 public void stateBacktracked(Search search) {
466 id = search.getStateId();
467 depth = search.getDepth();
468 operation = "backtrack";
471 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
473 // Update the parent node
474 if (nodes.containsKey(id)) {
475 parentNode = nodes.get(id);
477 parentNode = new Node(id);
482 public void searchFinished(Search search) {
483 out.println("----------------------------------- search finished");
486 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
490 frame = ti.getTopFrame();
492 if ((inst instanceof JVMLocalVariableInstruction) ||
493 (inst instanceof JVMFieldInstruction))
495 if (frame.getTopPos() < 0)
499 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
501 return(decodeValue(type, lo, hi));
504 if (inst instanceof JVMArrayElementInstruction)
505 return(getArrayValue(ti, type));
510 private final static String decodeValue(byte type, int lo, int hi) {
512 case Types.T_ARRAY: return(null);
513 case Types.T_VOID: return(null);
515 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
516 case Types.T_BYTE: return(String.valueOf(lo));
517 case Types.T_CHAR: return(String.valueOf((char) lo));
518 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
519 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
520 case Types.T_INT: return(String.valueOf(lo));
521 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
522 case Types.T_SHORT: return(String.valueOf(lo));
524 case Types.T_REFERENCE:
525 ElementInfo ei = VM.getVM().getHeap().get(lo);
529 ClassInfo ci = ei.getClassInfo();
533 if (ci.getName().equals("java.lang.String"))
534 return('"' + ei.asString() + '"');
536 return(ei.toString());
539 System.err.println("Unknown type: " + type);
544 private String getArrayValue(ThreadInfo ti, byte type) {
548 frame = ti.getTopFrame();
550 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
552 return(decodeValue(type, lo, hi));
555 private byte getType(ThreadInfo ti, Instruction inst) {
560 frame = ti.getTopFrame();
561 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
562 return (Types.T_REFERENCE);
567 if (inst instanceof JVMLocalVariableInstruction) {
568 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
569 } else if (inst instanceof JVMFieldInstruction){
570 fi = ((JVMFieldInstruction) inst).getFieldInfo();
574 if (inst instanceof JVMArrayElementInstruction) {
575 return (getTypeFromInstruction(inst));
579 return (Types.T_VOID);
582 return (decodeType(type));
585 private final static byte getTypeFromInstruction(Instruction inst) {
586 if (inst instanceof JVMArrayElementInstruction)
587 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
589 return(Types.T_VOID);
592 private final static byte decodeType(String type) {
593 if (type.charAt(0) == '?'){
594 return(Types.T_REFERENCE);
596 return Types.getBuiltinType(type);
600 // Find the variable writer
601 // It should be one of the apps listed in the .jpf file
602 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
603 // Start looking from the top of the stack backward
604 for(int i=sfList.size()-1; i>=0; i--) {
605 MethodInfo mi = sfList.get(i).getMethodInfo();
606 if(!mi.isJPFInternal()) {
607 String method = mi.getStackTraceName();
608 // Check against the writers in the writerSet
609 for(String writer : writerSet) {
610 if (method.contains(writer)) {
620 private void writeWriterAndValue(String writer, String value, String var) {
621 // Update the temporary Set set.
622 NameValuePair temp = new NameValuePair(1, value, var, manual);
623 if (writer.equals("App2"))
624 temp = new NameValuePair(2, value, var, manual);
626 tempSetSet.add(temp);
630 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
632 if (System.currentTimeMillis() - startTime > timeout) {
633 StringBuilder sbTimeOut = new StringBuilder();
634 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
635 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
636 ti.setNextPC(nextIns);
641 StringBuilder sb = new StringBuilder();
642 sb.append(errorMessage);
643 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
644 ti.setNextPC(nextIns);
646 if (conflictSet.contains(LOCATION_VAR)) {
647 MethodInfo mi = executedInsn.getMethodInfo();
648 // Find the last load before return and get the value here
649 if (mi.getName().equals(SET_LOCATION_METHOD) &&
650 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
651 byte type = getType(ti, executedInsn);
652 String value = getValue(ti, executedInsn, type);
654 // Extract the writer app name
655 ClassInfo ci = mi.getClassInfo();
656 String writer = ci.getName();
658 // Update the temporary Set set.
659 writeWriterAndValue(writer, value, LOCATION_VAR);
662 if (executedInsn instanceof WriteInstruction) {
663 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
665 for (String var : conflictSet) {
666 if (varId.contains(var)) {
668 byte type = getType(ti, executedInsn);
669 String value = getValue(ti, executedInsn, type);
670 String writer = getWriter(ti.getStack(), appSet);
671 // Just return if the writer is not one of the listed apps in the .jpf file
675 if (getWriter(ti.getStack(), manualSet) != null)
678 // Update the temporary Set set.
679 writeWriterAndValue(writer, value, var);