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 current parents are propagated
116 parentQueueMap.get(nodeToProcess).clear();
118 // Check if the node has changed or not
120 // Check for a conflict in all the transition out of this node
121 if (checkAllSuccForConflict(nodeToProcess))
124 // Update the parents list for the successors of the current node
126 parents.add(nodeToProcess);
128 // For all the successors of the current node
129 for (Node i : nodeToProcess.getSuccessors()) {
130 if (!changed.contains(i))
133 // Update the list of updated parents for the current node
134 if (parentQueueMap.containsKey(i))
135 parentQueueMap.get(i).add(nodeToProcess);
137 parentQueueMap.put(i, parents);
144 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
145 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
146 " has written the value: "+pair.getValue()+
147 " to the variable: "+pair.getVarName()+" while App"
148 +writerMap.get(pair.getVarName())+" is overwriting the value: "
149 +valueMap.get(pair.getVarName())+" to the same variable!";
150 System.out.println(message);
154 boolean checkAllSuccForConflict(Node currentNode) {
155 for (Node node : currentNode.getSuccessors()) {
156 HashMap<Transition, ArrayList<NameValuePair>> setSets = currentNode.getOutgoingEdges().get(node).getSetSetMap();
157 for (Map.Entry mapElement : setSets.entrySet()) {
158 Transition transition = (Transition)mapElement.getKey();
159 if (checkForConflict(currentNode, node, transition))
166 boolean checkForConflict(Node parentNode, Node currentNode, Transition currentTransition) {
167 ArrayList<NameValuePair> setSet = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap().get(currentTransition);
168 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
169 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
170 HashMap<String, String> firstValueMap = new HashMap<String, String>(); // HashMap from varName to value - first instruction in transition
171 HashMap<String, Integer> firstWriterMap = new HashMap<String, Integer>(); // HashMap from varName to appNum - first instruction in transition
173 // Update the valueMap and writerMap + check for conflict between the elements of setSet
174 for (int i = 0;i < setSet.size();i++) {
175 NameValuePair nameValuePair = setSet.get(i);
176 String varName = nameValuePair.getVarName();
177 String value = nameValuePair.getValue();
178 Integer appNum = nameValuePair.getAppNum();
179 Boolean isManual = nameValuePair.getIsManual();
181 if (valueMap.containsKey(varName)) {
182 // Check if we have a same writer
183 if (!writerMap.get(varName).equals(appNum)) {
184 // Check if we have a conflict or not
185 if (!valueMap.get(varName).equals(value)) {
186 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
190 valueMap.put(varName, value);
191 writerMap.put(varName, appNum);
193 valueMap.put(varName, value);
194 writerMap.put(varName, appNum);
196 firstValueMap.put(varName, value);
197 firstWriterMap.put(varName, appNum);
202 // Check for conflict between outSet and this transition setSet
203 for (NameValuePair i : parentNode.getOutSet()) {
204 if (firstValueMap.containsKey(i.getVarName())) {
205 String value = firstValueMap.get(i.getVarName());
206 Integer writer = firstWriterMap.get(i.getVarName());
207 if ((value != null)&&(writer != null)) {
208 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) {
209 // We have different values and different writers
210 errorMessage = createErrorMessage(i, firstValueMap, firstWriterMap);
219 boolean updateTheOutSet(Node parentNode, Node currentNode) {
220 HashMap<Transition, ArrayList<NameValuePair>> setSets = parentNode.getOutgoingEdges().get(currentNode).getSetSetMap();
221 HashSet<String> updatedVarNames = new HashSet<String>();
222 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
223 HashMap<String, Integer> lastWriter = currentEdge.getLastWriter();
224 HashMap<String, String> lastValue = currentEdge.getLastValue();
225 HashMap<String, Integer> outSetVarMap = new HashMap<String, Integer>();
226 boolean isChanged = false;
228 for (Map.Entry mapElement : setSets.entrySet()) {
229 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
231 for (int i = 0;i < setSet.size();i++) {
232 updatedVarNames.add(setSet.get(i).getVarName());
236 for (NameValuePair i : parentNode.getOutSet()) {
237 outSetVarMap.put(i.getVarName(), i.getAppNum());
238 if (!updatedVarNames.contains(i.getVarName()))
239 isChanged |= currentNode.getOutSet().add(i);
243 for (Map.Entry mapElement : setSets.entrySet()) {
244 ArrayList<NameValuePair> setSet = (ArrayList<NameValuePair>)mapElement.getValue();
246 for (int i = 0;i < setSet.size();i++) {
247 String varName = setSet.get(i).getVarName();
248 Integer writer = lastWriter.get(varName);
249 String value = lastValue.get(varName);
251 if (setSet.get(i).getAppNum().equals(writer)
252 && setSet.get(i).getValue().equals(value)) {
253 if (outSetVarMap.containsKey(varName)) {
254 Integer hashCode = outSetVarMap.get(varName).hashCode() * 31 +
256 currentNode.getOutSet().remove(hashCode);
258 isChanged |= currentNode.getOutSet().add(setSet.get(i));
265 void updateTheEdge(Node currentNode, Transition transition) {
266 if (parentNode.getOutgoingEdges().containsKey(currentNode)) {
267 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
268 if (currentEdge.getSetSetMap().containsKey(transition)) { // Update the transition
270 currentEdge.getSetSetMap().put(transition, tempSetSet);
272 currentEdge.getSetSetMap().get(transition).addAll(tempSetSet);
273 } else { // Add a new transition
274 currentEdge.getSetSetMap().put(transition, tempSetSet);
277 parentNode.getOutgoingEdges().put(currentNode, new Edge(parentNode, currentNode));
278 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
279 currentEdge.getSetSetMap().put(transition, tempSetSet);
282 // Update the last writer and last value for this edge for each varName
283 Edge currentEdge = parentNode.getOutgoingEdges().get(currentNode);
284 ArrayList<NameValuePair> setSet = currentEdge.getSetSetMap().get(transition);
285 for (int i = 0;i < setSet.size();i++) {
286 NameValuePair nameValuePair = setSet.get(i);
287 currentEdge.getLastWriter().put(nameValuePair.getVarName(), nameValuePair.getAppNum());
288 currentEdge.getLastValue().put(nameValuePair.getVarName(), nameValuePair.getValue());
296 HashSet<Node> predecessors = new HashSet<Node>();
297 HashSet<Node> successors = new HashSet<Node>();
298 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
299 HashMap<Node, Edge> outgoingEdges = new HashMap<Node, Edge>();
309 HashSet<Node> getPredecessors() {
313 HashSet<Node> getSuccessors() {
317 HashSet<NameValuePair> getOutSet() {
321 HashMap<Node, Edge> getOutgoingEdges() {
322 return outgoingEdges;
327 Node source, destination;
328 HashMap<String, Integer> lastWriter = new HashMap<String, Integer>();
329 HashMap<String, String> lastValue = new HashMap<String, String>();
330 HashMap<Transition, ArrayList<NameValuePair>> setSetMap = new HashMap<Transition, ArrayList<NameValuePair>>();
332 Edge(Node source, Node destination) {
333 this.source = source;
334 this.destination = destination;
341 Node getDestination() {
345 HashMap<Transition, ArrayList<NameValuePair>> getSetSetMap() {
349 HashMap<String, Integer> getLastWriter() {
353 HashMap<String, String> getLastValue() {
358 static class NameValuePair {
364 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
365 this.appNum = appNum;
367 this.varName = varName;
368 this.isManual = isManual;
371 void setAppNum(Integer appNum) {
372 this.appNum = appNum;
375 void setValue(String value) {
379 void setVarName(String varName) {
380 this.varName = varName;
383 void setIsManual(String varName) {
384 this.isManual = isManual;
387 Integer getAppNum() {
395 String getVarName() {
399 boolean getIsManual() {
404 public boolean equals(Object o) {
405 if (o instanceof NameValuePair) {
406 NameValuePair other = (NameValuePair) o;
407 if (varName.equals(other.getVarName()))
408 return appNum.equals(other.getAppNum());
414 public int hashCode() {
415 return appNum.hashCode() * 31 + varName.hashCode();
420 public void stateRestored(Search search) {
421 id = search.getStateId();
422 depth = search.getDepth();
423 operation = "restored";
426 out.println("The state is restored to state with id: "+id+", depth: "+depth);
428 // Update the parent node
429 if (nodes.containsKey(id)) {
430 parentNode = nodes.get(id);
432 parentNode = new Node(id);
437 public void searchStarted(Search search) {
438 out.println("----------------------------------- search started");
443 public void stateAdvanced(Search search) {
444 String theEnd = null;
445 Transition transition = search.getTransition();
446 id = search.getStateId();
447 depth = search.getDepth();
448 operation = "forward";
450 // Add the node to the list of nodes
451 if (nodes.get(id) == null)
452 nodes.put(id, new Node(id));
454 Node currentNode = nodes.get(id);
456 // Update the edge based on the current transition
457 updateTheEdge(currentNode, transition);
459 // Reset the temporary variables and flags
460 tempSetSet = new ArrayList<NameValuePair>();
463 // Check for the conflict in this transition
464 conflictFound = checkForConflict(parentNode, currentNode, transition);
466 if (search.isNewState()) {
472 if (search.isEndState()) {
473 out.println("This is the last state!");
477 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
479 // Updating the predecessors for this node
480 // Check if parent node is already in successors of the current node or not
481 if (!(currentNode.getPredecessors().contains(parentNode)))
482 currentNode.getPredecessors().add(parentNode);
484 // Update the successors for this node
485 // Check if current node is already in successors of the parent node or not
486 if (!(parentNode.getSuccessors().contains(currentNode)))
487 parentNode.getSuccessors().add(currentNode);
489 // Update the outset of the current node and check if it is changed or not to propagate the change
490 boolean isChanged = updateTheOutSet(parentNode, currentNode);
492 // Check if the outSet of this state has changed, update all of its successors' sets if any
494 conflictFound = conflictFound || checkAllSuccForConflict(currentNode) || propagateTheChange(currentNode);
496 // Update the parent node
497 if (nodes.containsKey(id)) {
498 parentNode = nodes.get(id);
500 parentNode = new Node(id);
505 public void stateBacktracked(Search search) {
506 id = search.getStateId();
507 depth = search.getDepth();
508 operation = "backtrack";
511 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
513 // Update the parent node
514 if (nodes.containsKey(id)) {
515 parentNode = nodes.get(id);
517 parentNode = new Node(id);
522 public void searchFinished(Search search) {
523 out.println("----------------------------------- search finished");
526 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
530 frame = ti.getTopFrame();
532 if ((inst instanceof JVMLocalVariableInstruction) ||
533 (inst instanceof JVMFieldInstruction))
535 if (frame.getTopPos() < 0)
539 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
541 return(decodeValue(type, lo, hi));
544 if (inst instanceof JVMArrayElementInstruction)
545 return(getArrayValue(ti, type));
550 private final static String decodeValue(byte type, int lo, int hi) {
552 case Types.T_ARRAY: return(null);
553 case Types.T_VOID: return(null);
555 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
556 case Types.T_BYTE: return(String.valueOf(lo));
557 case Types.T_CHAR: return(String.valueOf((char) lo));
558 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
559 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
560 case Types.T_INT: return(String.valueOf(lo));
561 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
562 case Types.T_SHORT: return(String.valueOf(lo));
564 case Types.T_REFERENCE:
565 ElementInfo ei = VM.getVM().getHeap().get(lo);
569 ClassInfo ci = ei.getClassInfo();
573 if (ci.getName().equals("java.lang.String"))
574 return('"' + ei.asString() + '"');
576 return(ei.toString());
579 System.err.println("Unknown type: " + type);
584 private String getArrayValue(ThreadInfo ti, byte type) {
588 frame = ti.getTopFrame();
590 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
592 return(decodeValue(type, lo, hi));
595 private byte getType(ThreadInfo ti, Instruction inst) {
600 frame = ti.getTopFrame();
601 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
602 return (Types.T_REFERENCE);
607 if (inst instanceof JVMLocalVariableInstruction) {
608 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
609 } else if (inst instanceof JVMFieldInstruction){
610 fi = ((JVMFieldInstruction) inst).getFieldInfo();
614 if (inst instanceof JVMArrayElementInstruction) {
615 return (getTypeFromInstruction(inst));
619 return (Types.T_VOID);
622 return (decodeType(type));
625 private final static byte getTypeFromInstruction(Instruction inst) {
626 if (inst instanceof JVMArrayElementInstruction)
627 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
629 return(Types.T_VOID);
632 private final static byte decodeType(String type) {
633 if (type.charAt(0) == '?'){
634 return(Types.T_REFERENCE);
636 return Types.getBuiltinType(type);
640 // Find the variable writer
641 // It should be one of the apps listed in the .jpf file
642 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
643 // Start looking from the top of the stack backward
644 for(int i=sfList.size()-1; i>=0; i--) {
645 MethodInfo mi = sfList.get(i).getMethodInfo();
646 if(!mi.isJPFInternal()) {
647 String method = mi.getStackTraceName();
648 // Check against the writers in the writerSet
649 for(String writer : writerSet) {
650 if (method.contains(writer)) {
660 private void writeWriterAndValue(String writer, String value, String var) {
661 // Update the temporary Set set.
662 NameValuePair temp = new NameValuePair(1, value, var, manual);
663 if (writer.equals("App2"))
664 temp = new NameValuePair(2, value, var, manual);
666 tempSetSet.add(temp);
670 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
672 if (System.currentTimeMillis() - startTime > timeout) {
673 StringBuilder sbTimeOut = new StringBuilder();
674 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
675 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
676 ti.setNextPC(nextIns);
681 StringBuilder sb = new StringBuilder();
682 sb.append(errorMessage);
683 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
684 ti.setNextPC(nextIns);
686 if (conflictSet.contains(LOCATION_VAR)) {
687 MethodInfo mi = executedInsn.getMethodInfo();
688 // Find the last load before return and get the value here
689 if (mi.getName().equals(SET_LOCATION_METHOD) &&
690 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
691 byte type = getType(ti, executedInsn);
692 String value = getValue(ti, executedInsn, type);
694 // Extract the writer app name
695 ClassInfo ci = mi.getClassInfo();
696 String writer = ci.getName();
698 // Update the temporary Set set.
699 writeWriterAndValue(writer, value, LOCATION_VAR);
702 if (executedInsn instanceof WriteInstruction) {
703 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
705 for (String var : conflictSet) {
706 if (varId.contains(var)) {
708 byte type = getType(ti, executedInsn);
709 String value = getValue(ti, executedInsn, type);
710 String writer = getWriter(ti.getStack(), appSet);
711 // Just return if the writer is not one of the listed apps in the .jpf file
715 if (getWriter(ti.getStack(), manualSet) != null)
718 // Update the temporary Set set.
719 writeWriterAndValue(writer, value, var);