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 boolean isChanged = false;
197 for (Map.Entry mapElement : setSets.entrySet()) {
198 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
200 for (int i = 0;i < setSet.size();i++) {
201 updatedVarNames.add(setSet.get(i).getVarName());
205 for (NameValuePair i : parentNode.getOutSet()) {
206 if (!updatedVarNames.contains(i.getVarName()))
207 isChanged |= currentNode.getOutSet().add(i);
210 ArrayList<NameValuePair> lastSetSet = setSets.get(edge.getFinalTransition());
212 for (int i = 0;i < lastSetSet.size();i++) {
213 isChanged |= currentNode.getOutSet().add(lastSetSet.get(i));
218 void updateTheEdge(Node currentNode, Transition transition) {
219 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
220 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
221 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
223 currentEdge.getSetSetMap().put(transition, tempSetSet);
225 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
226 } else { // Add a new transition
227 currentEdge.getSetSetMap().put(transition, tempSetSet);
229 currentEdge.setFinalTransition(transition);
231 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
232 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
233 currentEdge.getSetSetMap().put(transition, tempSetSet);
234 currentEdge.setFinalTransition(transition);
240 HashSet<Node> predecessors = new HashSet<Node>();
241 HashSet<Node> successors = new HashSet<Node>();
242 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
243 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
253 HashSet<Node> getPredecessors() {
257 HashSet<Node> getSuccessors() {
261 HashSet<NameValuePair> getOutSet() {
265 HashMap<Node, Edge> getOutgoingEdges() {
266 return outgoingEdges;
271 Node source, destination;
272 Transition finalTransition;
273 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
274 HashMap<String, String> lastValue = new HashMap<String, String>();
275 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
277 Edge(Node source, Node destination) {
278 this.source = source;
279 this.destination = destination;
286 Node getDestination() {
290 Transition getFinalTransition() {
291 return finalTransition;
294 void setFinalTransition(Transition transition) {
295 finalTransition = transition;
298 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
302 HashMap<String, Integer> getLastWriter() {
306 HashMap<String, String> getLastValue() {
311 static class NameValuePair {
317 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
318 this.appNum = appNum;
320 this.varName = varName;
321 this.isManual = isManual;
324 void setAppNum(Integer appNum) {
325 this.appNum = appNum;
328 void setValue(String value) {
332 void setVarName(String varName) {
333 this.varName = varName;
336 void setIsManual(String varName) {
337 this.isManual = isManual;
340 Integer getAppNum() {
348 String getVarName() {
352 boolean getIsManual() {
357 public boolean equals(Object o) {
358 if (o instanceof NameValuePair) {
359 NameValuePair other = (NameValuePair) o;
360 if (varName.equals(other.getVarName()))
361 return appNum.equals(other.getAppNum());
367 public int hashCode() {
368 return appNum.hashCode() * 31 + varName.hashCode();
373 public void stateRestored(Search search) {
374 id = search.getStateId();
375 depth = search.getDepth();
376 operation = "restored";
379 out.println("The state is restored to state with id: "+id+", depth: "+depth);
381 // Update the parent node
382 if (nodes.containsKey(id)) {
383 parentNode = nodes.get(id);
385 parentNode = new Node(id);
390 public void searchStarted(Search search) {
391 out.println("----------------------------------- search started");
396 public void stateAdvanced(Search search) {
397 String theEnd = null;
398 Transition transition = search.getTransition();
399 id = search.getStateId();
400 depth = search.getDepth();
401 operation = "forward";
403 // Add the node to the list of nodes
404 if (nodes.get(id) == null)
405 nodes.put(id, new Node(id));
407 Node currentNode = nodes.get(id);
409 // Update the edge based on the current transition
410 updateTheEdge(currentNode, transition);
412 // Reset the temporary variables and flags
413 tempSetSet = new ArrayList<NameValuePair>();
416 // Check for the conflict in this transition
417 conflictFound = checkForConflict(parentNode, currentNode, transition);
419 if (search.isNewState()) {
425 if (search.isEndState()) {
426 out.println("This is the last state!");
430 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
432 // Updating the predecessors for this node
433 // Check if parent node is already in successors of the current node or not
434 if (!(currentNode.getPredecessors().contains(parentNode)))
435 currentNode.getPredecessors().add(parentNode);
437 // Update the successors for this node
438 // Check if current node is already in successors of the parent node or not
439 if (!(parentNode.getSuccessors().contains(currentNode)))
440 parentNode.getSuccessors().add(currentNode);
442 // Update the outset of the current node and check if it is changed or not to propagate the change
443 boolean isChanged = updateTheOutSet(parentNode, currentNode);
445 // Check if the outSet of this state has changed, update all of its successors' sets if any
447 conflictFound = conflictFound || checkAllSuccForConflict(currentNode) || propagateTheChange(currentNode);
449 // Update the parent node
450 if (nodes.containsKey(id)) {
451 parentNode = nodes.get(id);
453 parentNode = new Node(id);
458 public void stateBacktracked(Search search) {
459 id = search.getStateId();
460 depth = search.getDepth();
461 operation = "backtrack";
464 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
466 // Update the parent node
467 if (nodes.containsKey(id)) {
468 parentNode = nodes.get(id);
470 parentNode = new Node(id);
475 public void searchFinished(Search search) {
476 out.println("----------------------------------- search finished");
479 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
483 frame = ti.getTopFrame();
485 if ((inst instanceof JVMLocalVariableInstruction) ||
486 (inst instanceof JVMFieldInstruction))
488 if (frame.getTopPos() < 0)
492 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
494 return(decodeValue(type, lo, hi));
497 if (inst instanceof JVMArrayElementInstruction)
498 return(getArrayValue(ti, type));
503 private final static String decodeValue(byte type, int lo, int hi) {
505 case Types.T_ARRAY: return(null);
506 case Types.T_VOID: return(null);
508 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
509 case Types.T_BYTE: return(String.valueOf(lo));
510 case Types.T_CHAR: return(String.valueOf((char) lo));
511 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
512 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
513 case Types.T_INT: return(String.valueOf(lo));
514 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
515 case Types.T_SHORT: return(String.valueOf(lo));
517 case Types.T_REFERENCE:
518 ElementInfo ei = VM.getVM().getHeap().get(lo);
522 ClassInfo ci = ei.getClassInfo();
526 if (ci.getName().equals("java.lang.String"))
527 return('"' + ei.asString() + '"');
529 return(ei.toString());
532 System.err.println("Unknown type: " + type);
537 private String getArrayValue(ThreadInfo ti, byte type) {
541 frame = ti.getTopFrame();
543 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
545 return(decodeValue(type, lo, hi));
548 private byte getType(ThreadInfo ti, Instruction inst) {
553 frame = ti.getTopFrame();
554 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
555 return (Types.T_REFERENCE);
560 if (inst instanceof JVMLocalVariableInstruction) {
561 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
562 } else if (inst instanceof JVMFieldInstruction){
563 fi = ((JVMFieldInstruction) inst).getFieldInfo();
567 if (inst instanceof JVMArrayElementInstruction) {
568 return (getTypeFromInstruction(inst));
572 return (Types.T_VOID);
575 return (decodeType(type));
578 private final static byte getTypeFromInstruction(Instruction inst) {
579 if (inst instanceof JVMArrayElementInstruction)
580 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
582 return(Types.T_VOID);
585 private final static byte decodeType(String type) {
586 if (type.charAt(0) == '?'){
587 return(Types.T_REFERENCE);
589 return Types.getBuiltinType(type);
593 // Find the variable writer
594 // It should be one of the apps listed in the .jpf file
595 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
596 // Start looking from the top of the stack backward
597 for(int i=sfList.size()-1; i>=0; i--) {
598 MethodInfo mi = sfList.get(i).getMethodInfo();
599 if(!mi.isJPFInternal()) {
600 String method = mi.getStackTraceName();
601 // Check against the writers in the writerSet
602 for(String writer : writerSet) {
603 if (method.contains(writer)) {
613 private void writeWriterAndValue(String writer, String value, String var) {
614 // Update the temporary Set set.
615 NameValuePair temp = new NameValuePair(1, value, var, manual);
616 if (writer.equals("App2"))
617 temp = new NameValuePair(2, value, var, manual);
619 tempSetSet.add(temp);
623 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
625 if (System.currentTimeMillis() - startTime > timeout) {
626 StringBuilder sbTimeOut = new StringBuilder();
627 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
628 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
629 ti.setNextPC(nextIns);
634 StringBuilder sb = new StringBuilder();
635 sb.append(errorMessage);
636 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
637 ti.setNextPC(nextIns);
639 if (conflictSet.contains(LOCATION_VAR)) {
640 MethodInfo mi = executedInsn.getMethodInfo();
641 // Find the last load before return and get the value here
642 if (mi.getName().equals(SET_LOCATION_METHOD) &&
643 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
644 byte type = getType(ti, executedInsn);
645 String value = getValue(ti, executedInsn, type);
647 // Extract the writer app name
648 ClassInfo ci = mi.getClassInfo();
649 String writer = ci.getName();
651 // Update the temporary Set set.
652 writeWriterAndValue(writer, value, LOCATION_VAR);
655 if (executedInsn instanceof WriteInstruction) {
656 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
658 for (String var : conflictSet) {
659 if (varId.contains(var)) {
661 byte type = getType(ti, executedInsn);
662 String value = getValue(ti, executedInsn, type);
663 String writer = getWriter(ti.getStack(), appSet);
664 // Just return if the writer is not one of the listed apps in the .jpf file
668 if (getWriter(ti.getStack(), manualSet) != null)
671 // Update the temporary Set set.
672 writeWriterAndValue(writer, value, var);