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 {
41 private final PrintWriter out;
42 private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
43 private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
44 private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
45 private final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
46 private ArrayList<NameValuePair> tempSetSet = new ArrayList<NameValuePair>();
48 private long startTime;
49 private Node parentNode = new Node(-2);
50 private String operation;
51 private String detail;
52 private String errorMessage;
55 private boolean conflictFound = false;
56 private boolean manual = false;
58 private final String SET_LOCATION_METHOD = "setLocationMode";
59 private final String LOCATION_VAR = "locationMode";
61 public ConflictTracker(Config config, JPF jpf) {
62 out = new PrintWriter(System.out, true);
64 String[] conflictVars = config.getStringArray("variables");
65 // We are not tracking anything if it is null
66 if (conflictVars != null) {
67 for (String var : conflictVars) {
71 String[] apps = config.getStringArray("apps");
72 // We are not tracking anything if it is null
74 for (String var : apps) {
78 String[] manualClasses = config.getStringArray("manualClasses");
79 // We are not tracking anything if it is null
80 if (manualClasses != null) {
81 for (String var : manualClasses) {
86 // Timeout input from config is in minutes, so we need to convert into millis
87 timeout = config.getInt("timeout", 0) * 60 * 1000;
88 startTime = System.currentTimeMillis();
91 boolean propagateTheChange(Node currentNode) {
92 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
93 HashSet<Node> parentSet = new HashSet<Node>();
95 while(!changed.isEmpty()) {
96 // Get the first element of HashSet and remove it from the changed set
97 Node nodeToProcess = changed.iterator().next();
98 changed.remove(nodeToProcess);
100 // Change the parent node
101 if (!currentNode.getSuccessors().contains(nodeToProcess)) {
102 currentNode = parentSet.iterator().next();
103 parentSet.remove(currentNode);
108 boolean isChanged = updateEdge(currentNode, nodeToProcess);
110 // Check for a conflict in this transition(currentNode -> nodeToProcess)
111 if (checkForConflict(nodeToProcess))
114 // Checking if the out set has changed or not(Add its successors to the change list!)
116 parentSet.add(nodeToProcess);
117 for (Node i : nodeToProcess.getSuccessors()) {
126 String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
127 String message = "Conflict found between the two apps. App"+pair.getAppNum()+
128 " has written the value: "+pair.getValue()+
129 " to the variable: "+pair.getVarName()+" while App"+
130 writerMap.get(pair.getVarName())+" is overwriting the value: "
131 +valueMap.get(pair.getVarName())+" to the same variable!";
135 boolean checkForConflict(Node nodeToProcess) {
136 HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
137 HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
139 // Update the valueMap
140 for (int i = 0;i < nodeToProcess.getSetSet().size();i++) {
141 NameValuePair nameValuePair = nodeToProcess.getSetSet().get(i);
143 if (valueMap.containsKey(nameValuePair.getVarName())) {
144 // Check if we have a same writer
145 if (!writerMap.get(nameValuePair.getVarName()).equals(nameValuePair.getAppNum())) {
146 // Check if we have a conflict or not
147 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
148 errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
150 } else { // We have two writers writing the same value
151 writerMap.put(nameValuePair.getVarName(), 3); // 3 represents both apps
154 // Check if we have more than one value with the same writer
155 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
156 valueMap.put(nameValuePair.getVarName(), "twoValue"); // We have one writer writing more than one value in a same event
160 valueMap.put(nameValuePair.getVarName(), nameValuePair.getValue());
161 writerMap.put(nameValuePair.getVarName(), nameValuePair.getAppNum());
165 // Comparing the outSet to setSet
166 for (NameValuePair i : nodeToProcess.getOutSet()) {
167 if (valueMap.containsKey(i.getVarName())) {
168 String value = valueMap.get(i.getVarName());
169 Integer writer = writerMap.get(i.getVarName());
170 if ((value != null)&&(writer != null)) {
171 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
172 System.out.println("we are here!!!!");
173 errorMessage = createErrorMessage(i, valueMap, writerMap);
183 boolean updateEdge(Node parentNode, Node currentNode) {
184 ArrayList<NameValuePair> setSet = currentNode.getSetSetMap().get(parentNode);
185 HashSet<String> updatedVarNames = new HashSet<String>();
186 boolean isChanged = false;
188 for (int i = 0;i < setSet.size();i++) {
189 updatedVarNames.add(setSet.get(i).getVarName());
192 for (NameValuePair i : parentNode.getOutSet()) {
193 if (!updatedVarNames.contains(i.getVarName()))
194 isChanged |= currentNode.getOutSet().add(i);
197 for (int i = 0;i < setSet.size();i++) {
198 isChanged |= currentNode.getOutSet().add(setSet.get(i));
206 HashSet<Node> predecessors = new HashSet<Node>();
207 HashSet<Node> successors = new HashSet<Node>();
208 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
209 HashMap<Node, ArrayList<NameValuePair>> setSetMap = new HashMap<Node, ArrayList<NameValuePair>>();
210 ArrayList<NameValuePair> setSet = new ArrayList<NameValuePair>();
217 void addPredecessor(Node node) {
218 predecessors.add(node);
221 void addSuccessor(Node node) {
222 successors.add(node);
225 void setSetSet(ArrayList<NameValuePair> setSet, boolean isManual) {
227 this.setSet = new ArrayList<NameValuePair>();
229 for (int i = 0;i < setSet.size();i++) {
230 this.setSet.add(new NameValuePair(setSet.get(i).getAppNum(), setSet.get(i).getValue(),
231 setSet.get(i).getVarName(), setSet.get(i).getIsManual()));
239 HashSet<Node> getPredecessors() {
243 HashSet<Node> getSuccessors() {
247 ArrayList<NameValuePair> getSetSet() {
251 HashSet<NameValuePair> getOutSet() {
255 HashMap<Node, ArrayList<NameValuePair>> getSetSetMap() {
260 static class NameValuePair {
266 NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
267 this.appNum = appNum;
269 this.varName = varName;
270 this.isManual = isManual;
273 void setAppNum(Integer appNum) {
274 this.appNum = appNum;
277 void setValue(String value) {
281 void setVarName(String varName) {
282 this.varName = varName;
285 void setIsManual(String varName) {
286 this.isManual = isManual;
289 Integer getAppNum() {
297 String getVarName() {
301 boolean getIsManual() {
306 public boolean equals(Object o) {
307 if (o instanceof NameValuePair) {
308 NameValuePair other = (NameValuePair) o;
309 if (varName.equals(other.getVarName()))
310 return appNum.equals(other.getAppNum());
316 public int hashCode() {
317 return appNum.hashCode() * 31 + varName.hashCode();
322 public void stateRestored(Search search) {
323 id = search.getStateId();
324 depth = search.getDepth();
325 operation = "restored";
328 out.println("The state is restored to state with id: "+id+", depth: "+depth);
330 // Update the parent node
331 if (nodes.containsKey(id)) {
332 parentNode = nodes.get(id);
334 parentNode = new Node(id);
339 public void searchStarted(Search search) {
340 out.println("----------------------------------- search started");
345 public void stateAdvanced(Search search) {
346 String theEnd = null;
347 id = search.getStateId();
348 depth = search.getDepth();
349 operation = "forward";
351 // Add the node to the list of nodes
352 if (nodes.get(id) == null)
353 nodes.put(id, new Node(id));
355 Node currentNode = nodes.get(id);
357 // Update the setSet for this new node
358 currentNode.setSetSet(tempSetSet, manual);
359 tempSetSet = new ArrayList<NameValuePair>();
362 if (search.isNewState()) {
368 if (search.isEndState()) {
369 out.println("This is the last state!");
373 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
375 // Updating the predecessors for this node
376 // Check if parent node is already in successors of the current node or not
377 if (!(currentNode.getPredecessors().contains(parentNode)))
378 currentNode.addPredecessor(parentNode);
380 // Update the successors for this node
381 // Check if current node is already in successors of the parent node or not
382 if (!(parentNode.getSuccessors().contains(currentNode)))
383 parentNode.addSuccessor(currentNode);
386 // Update the setSetMap of the current node
387 for (Node i : currentNode.getPredecessors()) {
388 currentNode.getSetSetMap().put(i, i.getSetSet());
391 // Update the edge and check if the outset of the current node is changed or not to propagate the change
392 boolean isChanged = updateEdge(parentNode, currentNode);
394 // Check for the conflict in this edge
395 conflictFound = checkForConflict(currentNode);
397 // Check if the outSet of this state has changed, update all of its successors' sets if any
399 conflictFound = conflictFound || propagateTheChange(currentNode);
401 // Update the parent node
402 if (nodes.containsKey(id)) {
403 parentNode = nodes.get(id);
405 parentNode = new Node(id);
410 public void stateBacktracked(Search search) {
411 id = search.getStateId();
412 depth = search.getDepth();
413 operation = "backtrack";
416 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
418 // Update the parent node
419 if (nodes.containsKey(id)) {
420 parentNode = nodes.get(id);
422 parentNode = new Node(id);
427 public void searchFinished(Search search) {
428 out.println("----------------------------------- search finished");
431 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
435 frame = ti.getTopFrame();
437 if ((inst instanceof JVMLocalVariableInstruction) ||
438 (inst instanceof JVMFieldInstruction))
440 if (frame.getTopPos() < 0)
444 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
446 return(decodeValue(type, lo, hi));
449 if (inst instanceof JVMArrayElementInstruction)
450 return(getArrayValue(ti, type));
455 private final static String decodeValue(byte type, int lo, int hi) {
457 case Types.T_ARRAY: return(null);
458 case Types.T_VOID: return(null);
460 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
461 case Types.T_BYTE: return(String.valueOf(lo));
462 case Types.T_CHAR: return(String.valueOf((char) lo));
463 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
464 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
465 case Types.T_INT: return(String.valueOf(lo));
466 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
467 case Types.T_SHORT: return(String.valueOf(lo));
469 case Types.T_REFERENCE:
470 ElementInfo ei = VM.getVM().getHeap().get(lo);
474 ClassInfo ci = ei.getClassInfo();
478 if (ci.getName().equals("java.lang.String"))
479 return('"' + ei.asString() + '"');
481 return(ei.toString());
484 System.err.println("Unknown type: " + type);
489 private String getArrayValue(ThreadInfo ti, byte type) {
493 frame = ti.getTopFrame();
495 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
497 return(decodeValue(type, lo, hi));
500 private byte getType(ThreadInfo ti, Instruction inst) {
505 frame = ti.getTopFrame();
506 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
507 return (Types.T_REFERENCE);
512 if (inst instanceof JVMLocalVariableInstruction) {
513 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
514 } else if (inst instanceof JVMFieldInstruction){
515 fi = ((JVMFieldInstruction) inst).getFieldInfo();
519 if (inst instanceof JVMArrayElementInstruction) {
520 return (getTypeFromInstruction(inst));
524 return (Types.T_VOID);
527 return (decodeType(type));
530 private final static byte getTypeFromInstruction(Instruction inst) {
531 if (inst instanceof JVMArrayElementInstruction)
532 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
534 return(Types.T_VOID);
537 private final static byte decodeType(String type) {
538 if (type.charAt(0) == '?'){
539 return(Types.T_REFERENCE);
541 return Types.getBuiltinType(type);
545 // Find the variable writer
546 // It should be one of the apps listed in the .jpf file
547 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
548 // Start looking from the top of the stack backward
549 for(int i=sfList.size()-1; i>=0; i--) {
550 MethodInfo mi = sfList.get(i).getMethodInfo();
551 if(!mi.isJPFInternal()) {
552 String method = mi.getStackTraceName();
553 // Check against the writers in the writerSet
554 for(String writer : writerSet) {
555 if (method.contains(writer)) {
565 private void writeWriterAndValue(String writer, String value, String var) {
566 // Update the temporary Set set.
567 NameValuePair temp = new NameValuePair(1, value, var, manual);
568 if (writer.equals("App2"))
569 temp = new NameValuePair(2, value, var, manual);
571 tempSetSet.add(temp);
575 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
577 if (System.currentTimeMillis() - startTime > timeout) {
578 StringBuilder sbTimeOut = new StringBuilder();
579 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
580 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
581 ti.setNextPC(nextIns);
586 StringBuilder sb = new StringBuilder();
587 sb.append(errorMessage);
588 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
589 ti.setNextPC(nextIns);
591 if (conflictSet.contains(LOCATION_VAR)) {
592 MethodInfo mi = executedInsn.getMethodInfo();
593 // Find the last load before return and get the value here
594 if (mi.getName().equals(SET_LOCATION_METHOD) &&
595 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
596 byte type = getType(ti, executedInsn);
597 String value = getValue(ti, executedInsn, type);
599 // Extract the writer app name
600 ClassInfo ci = mi.getClassInfo();
601 String writer = ci.getName();
603 // Update the temporary Set set.
604 writeWriterAndValue(writer, value, LOCATION_VAR);
607 if (executedInsn instanceof WriteInstruction) {
608 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
609 for (String var : conflictSet) {
610 if (varId.contains(var)) {
612 byte type = getType(ti, executedInsn);
613 String value = getValue(ti, executedInsn, type);
614 String writer = getWriter(ti.getStack(), appSet);
615 // Just return if the writer is not one of the listed apps in the .jpf file
619 if (getWriter(ti.getStack(), manualSet) != null)
622 // Update the temporary Set set.
623 writeWriterAndValue(writer, value, var);