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 HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
45 private final HashSet<NameValuePair> tempSetSet = new HashSet<NameValuePair>();
47 private long startTime;
48 private Node parentNode = new Node(-2);
49 private String operation;
50 private String detail;
53 private boolean conflictFound = false;
54 private boolean isSet = false;
57 public ConflictTracker(Config config, JPF jpf) {
58 out = new PrintWriter(System.out, true);
60 String[] conflictVars = config.getStringArray("variables");
61 // We are not tracking anything if it is null
62 if (conflictVars != null) {
63 for (String var : conflictVars) {
67 String[] apps = config.getStringArray("apps");
68 // We are not tracking anything if it is null
70 for (String var : apps) {
74 // Timeout input from config is in minutes, so we need to convert into millis
75 timeout = config.getInt("timeout", 0) * 60 * 1000;
76 startTime = System.currentTimeMillis();
79 void propagateTheChange(Node currentNode) {
80 HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
83 while(!changed.isEmpty()) {
84 // Get the first element of HashSet and remove it from the changed set
85 Node nodeToProcess = changed.iterator().next();
86 changed.remove(nodeToProcess);
88 // Update the sets, store the outSet to temp before its changes
89 isChanged = updateSets(nodeToProcess);
91 // Check for a conflict
92 conflictFound = checkForConflict(nodeToProcess);
94 // Checking if the out set has changed or not(Add its successors to the change list!)
96 for (Node i : nodeToProcess.getSuccessors()) {
97 if (!changed.contains(i))
104 boolean setOutSet(Node currentNode) {
105 boolean isChanged = false;
106 HashMap<NameValuePair, String> outSet = new HashMap<NameValuePair, String>();
108 // Store the outSet of current node to HashMap to help for the search in O(n)
109 for (NameValuePair i : currentNode.getOutSet()) {
110 outSet.put(i, i.getValue());
113 // Update based on inSet
114 for (NameValuePair i : currentNode.getInSet()) {
115 if (currentNode.getOutSet().contains(i)) {
116 if (outSet.get(i) != i.getValue())
118 currentNode.getOutSet().remove(i);
122 currentNode.getOutSet().add(i);
125 // Overwrite the outSet based on setSet if we have a writer
126 for (NameValuePair i : currentNode.getSetSet()) {
127 if (currentNode.getOutSet().contains(i)) {
128 if (outSet.get(i) != i.getValue())
130 currentNode.getOutSet().remove(i);
134 currentNode.getOutSet().add(i);
140 void setInSet(Node currentNode) {
141 for (Node i : currentNode.getPredecessors()) {
142 currentNode.getInSet().addAll(i.getOutSet());
146 boolean checkForConflict(Node currentNode) {
147 HashMap<String, String> varNameMap = new HashMap<String, String>();
149 for (NameValuePair i : currentNode.getOutSet()) {
150 if (varNameMap.containsKey(i.getVarName())) {
151 if (varNameMap.get(i) != i.getValue()) {
155 varNameMap.put(i.getVarName(), i.getValue());
162 boolean updateSets(Node currentNode) {
163 // Set input set according to output set of pred states of current state
164 setInSet(currentNode);
166 // Set outSet according to inSet, and setSet of current node, check if there is a change
167 return setOutSet(currentNode);
172 HashSet<Node> predecessors = new HashSet<Node>();
173 HashSet<Node> successors = new HashSet<Node>();
174 HashSet<NameValuePair> inSet = new HashSet<NameValuePair>();
175 HashSet<NameValuePair> setSet = new HashSet<NameValuePair>();
176 HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
182 void addPredecessor(Node node) {
183 predecessors.add(node);
186 void addSuccessor(Node node) {
187 successors.add(node);
190 void setSetSet(HashSet<NameValuePair> setSet) {
191 this.setSet.addAll(setSet);
198 HashSet<Node> getPredecessors() {
202 HashSet<Node> getSuccessors() {
206 HashSet<NameValuePair> getInSet() {
210 HashSet<NameValuePair> getSetSet() {
214 HashSet<NameValuePair> getOutSet() {
219 static class NameValuePair {
224 NameValuePair(Integer appNum, String value, String varName) {
225 this.appNum = appNum;
227 this.varName = varName;
230 void setAppNum(Integer appNum) {
231 this.appNum = appNum;
234 void setValue(String value) {
238 void setVarName(String varName) {
239 this.varName = varName;
242 Integer getAppNum() {
250 String getVarName() {
255 public boolean equals(Object o) {
256 if (o instanceof NameValuePair) {
257 NameValuePair other = (NameValuePair) o;
258 if (varName.equals(other.getVarName()))
259 return appNum.equals(other.getAppNum());
265 public int hashCode() {
266 return appNum.hashCode() * 31 + varName.hashCode();
271 public void stateRestored(Search search) {
272 id = search.getStateId();
273 depth = search.getDepth();
274 operation = "restored";
277 out.println("The state is restored to state with id: "+id+", depth: "+depth);
279 // Update the parent node
280 parentNode = new Node(id);
284 public void searchStarted(Search search) {
285 out.println("----------------------------------- search started");
290 public void stateAdvanced(Search search) {
291 String theEnd = null;
292 id = search.getStateId();
293 depth = search.getDepth();
294 operation = "forward";
296 // Add the node to the list of nodes
297 nodes.put(id, new Node(id));
298 Node currentNode = nodes.get(id);
300 // Update the setSet for this new node
302 currentNode.setSetSet(tempSetSet);
306 if (search.isNewState()) {
312 if (search.isEndState()) {
313 out.println("This is the last state!");
317 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
319 // Updating the predecessors for this node
320 // Check if parent node is already in successors of the current node or not
321 if (!(currentNode.getPredecessors().contains(parentNode)))
322 currentNode.addPredecessor(parentNode);
324 // Update the successors for this node
325 // Check if current node is already in successors of the parent node or not
326 if (!(parentNode.getSuccessors().contains(currentNode)))
327 parentNode.addSuccessor(currentNode);
329 // Update the sets, check if the outSet is changed or not
330 boolean isChanged = updateSets(currentNode);
332 // Check for a conflict
333 conflictFound = checkForConflict(currentNode);
335 // Check if the outSet of this state has changed, update all of its successors' sets if any
337 propagateTheChange(currentNode);
339 // Update the parent node
340 parentNode = new Node(id);
344 public void stateBacktracked(Search search) {
345 id = search.getStateId();
346 depth = search.getDepth();
347 operation = "backtrack";
350 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
352 // Update the parent node
353 parentNode = new Node(id);
357 public void searchFinished(Search search) {
358 out.println("----------------------------------- search finished");
361 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
365 frame = ti.getTopFrame();
367 if ((inst instanceof JVMLocalVariableInstruction) ||
368 (inst instanceof JVMFieldInstruction))
370 if (frame.getTopPos() < 0)
374 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
376 return(decodeValue(type, lo, hi));
379 if (inst instanceof JVMArrayElementInstruction)
380 return(getArrayValue(ti, type));
385 private final static String decodeValue(byte type, int lo, int hi) {
387 case Types.T_ARRAY: return(null);
388 case Types.T_VOID: return(null);
390 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
391 case Types.T_BYTE: return(String.valueOf(lo));
392 case Types.T_CHAR: return(String.valueOf((char) lo));
393 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
394 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
395 case Types.T_INT: return(String.valueOf(lo));
396 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
397 case Types.T_SHORT: return(String.valueOf(lo));
399 case Types.T_REFERENCE:
400 ElementInfo ei = VM.getVM().getHeap().get(lo);
404 ClassInfo ci = ei.getClassInfo();
408 if (ci.getName().equals("java.lang.String"))
409 return('"' + ei.asString() + '"');
411 return(ei.toString());
414 System.err.println("Unknown type: " + type);
419 private String getArrayValue(ThreadInfo ti, byte type) {
423 frame = ti.getTopFrame();
425 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
427 return(decodeValue(type, lo, hi));
430 private byte getType(ThreadInfo ti, Instruction inst) {
435 frame = ti.getTopFrame();
436 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
437 return (Types.T_REFERENCE);
442 if (inst instanceof JVMLocalVariableInstruction) {
443 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
444 } else if (inst instanceof JVMFieldInstruction){
445 fi = ((JVMFieldInstruction) inst).getFieldInfo();
449 if (inst instanceof JVMArrayElementInstruction) {
450 return (getTypeFromInstruction(inst));
454 return (Types.T_VOID);
457 return (decodeType(type));
460 private final static byte getTypeFromInstruction(Instruction inst) {
461 if (inst instanceof JVMArrayElementInstruction)
462 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
464 return(Types.T_VOID);
467 private final static byte decodeType(String type) {
468 if (type.charAt(0) == '?'){
469 return(Types.T_REFERENCE);
471 return Types.getBuiltinType(type);
475 // Find the variable writer
476 // It should be one of the apps listed in the .jpf file
477 private String getWriter(List<StackFrame> sfList) {
478 // Start looking from the top of the stack backward
479 for(int i=sfList.size()-1; i>=0; i--) {
480 MethodInfo mi = sfList.get(i).getMethodInfo();
481 if(!mi.isJPFInternal()) {
482 String method = mi.getStackTraceName();
483 // Check against the apps in the appSet
484 for(String app : appSet) {
485 // There is only one writer at a time but we need to always
486 // check all the potential writers in the list
487 if (method.contains(app)) {
498 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
499 // Instantiate timeoutTimer
501 if (System.currentTimeMillis() - startTime > timeout) {
502 StringBuilder sbTimeOut = new StringBuilder();
503 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
504 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
505 ti.setNextPC(nextIns);
510 StringBuilder sb = new StringBuilder();
511 sb.append("Conflict found between two apps!");
512 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
513 ti.setNextPC(nextIns);
514 } else if (executedInsn instanceof WriteInstruction) {
515 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
516 for(String var : conflictSet) {
518 if (varId.contains(var)) {
520 byte type = getType(ti, executedInsn);
521 String value = getValue(ti, executedInsn, type);
522 String writer = getWriter(ti.getStack());
523 // Just return if the writer is not one of the listed apps in the .jpf file
527 // Update the temporary Set set.
528 if (writer.equals("App1"))
529 tempSetSet.add(new NameValuePair(1, value, var));
530 else if (writer.equals("App2"))
531 tempSetSet.add(new NameValuePair(2, value, var));