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 HashSet<Transition> transitions = new HashSet<Transition>();
46 private ArrayList<Update> currUpdates = new ArrayList<Update>();
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 manual = false;
56 private boolean conflictFound = 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) {
79 // Timeout input from config is in minutes, so we need to convert into millis
80 timeout = config.getInt("timeout", 0) * 60 * 1000;
81 startTime = System.currentTimeMillis();
84 void propagateChange(Edge newEdge) {
85 HashSet<Edge> changed = new HashSet<Edge>();
87 // Add the current node to the changed set
90 while(!changed.isEmpty()) {
91 // Get the first element of the changed set and remove it
92 Edge edgeToProcess = changed.iterator().next();
93 changed.remove(edgeToProcess);
95 //If propagating change on edge causes change, enqueue all the target node's out edges
96 if (propagateEdge(edgeToProcess)) {
97 Node dst = edgeToProcess.getDst();
98 for (Edge e : dst.getOutEdges()) {
105 boolean propagateEdge(Edge e) {
106 HashMap<IndexObject, HashSet<Update>> srcUpdates = e.getSrc().getLastUpdates();
107 HashMap<IndexObject, HashSet<Update>> dstUpdates = e.getDst().getLastUpdates();
108 ArrayList<Update> edgeUpdates = e.getUpdates();
109 HashMap<IndexObject, Update> lastupdate = new HashMap<IndexObject, Update>();
110 boolean changed = false;
112 //Go through each update on the current transition
113 for(int i=0; i<edgeUpdates.size(); i++) {
114 Update u = edgeUpdates.get(i);
115 IndexObject io = u.getIndex();
116 HashSet<Update> confupdates = null;
118 //See if we have already updated this device attribute
119 if (lastupdate.containsKey(io)) {
120 confupdates = new HashSet<Update>();
121 confupdates.add(lastupdate.get(io));
122 } else if (srcUpdates.containsKey(io)){
123 confupdates = srcUpdates.get(io);
126 //Check for conflict with the appropriate update set if we are not a manual transition
127 if (confupdates != null && !u.isManual()) {
128 for(Update u2: confupdates) {
129 if (conflicts(u, u2)) {
130 //throw new RuntimeException(createErrorMessage(u, u2));
131 conflictFound = true;
132 errorMessage = createErrorMessage(u, u2);
136 lastupdate.put(io, u);
138 for(IndexObject io: srcUpdates.keySet()) {
139 //Only propagate src changes if the transition doesn't update the device attribute
140 if (!lastupdate.containsKey(io)) {
141 //Make sure destination has hashset in map
142 if (!dstUpdates.containsKey(io))
143 dstUpdates.put(io, new HashSet<Update>());
145 changed |= dstUpdates.get(io).addAll(srcUpdates.get(io));
148 for(IndexObject io: lastupdate.keySet()) {
149 //Make sure destination has hashset in map
150 if (!dstUpdates.containsKey(io))
151 dstUpdates.put(io, new HashSet<Update>());
153 changed |= dstUpdates.get(io).add(lastupdate.get(io));
158 //Method to check for conflicts between two updates
159 //Have conflict if same device, same attribute, different app, different vaalue
160 boolean conflicts(Update u, Update u2) {
161 return (!u.getApp().equals(u2.getApp())) &&
162 u.getDeviceId().equals(u2.getDeviceId()) &&
163 u.getAttribute().equals(u2.getAttribute()) &&
164 (!u.getValue().equals(u2.getValue()));
167 String createErrorMessage(Update u, Update u2) {
168 String message = "Conflict found between the two apps. "+u.getApp()+
169 " has written the value: "+u.getValue()+
170 " to the attribute: "+u.getAttribute()+" while "
171 +u2.getApp()+" is writing the value: "
172 +u2.getValue()+" to the same variable!";
173 System.out.println(message);
177 Edge createEdge(Node parent, Node current, Transition transition) {
178 //Check if this transition is explored. If so, just skip everything
179 if (transitions.contains(transition))
183 Edge e = new Edge(parent, current, transition, currUpdates);
184 parent.addOutEdge(e);
186 //Mark transition as explored
187 transitions.add(transition);
193 Vector<Edge> outEdges = new Vector<Edge>();
194 HashMap<IndexObject, HashSet<Update>> lastUpdates = new HashMap<IndexObject, HashSet<Update>>();
204 Vector<Edge> getOutEdges() {
208 void addOutEdge(Edge e) {
212 HashMap<IndexObject, HashSet<Update>> getLastUpdates() {
217 //Each Edge corresponds to a transition
219 Node source, destination;
220 Transition transition;
221 ArrayList<Update> updates = new ArrayList<Update>();
223 Edge(Node src, Node dst, Transition t, ArrayList<Update> _updates) {
225 this.destination = dst;
227 this.updates.addAll(_updates);
238 Transition getTransition() {
242 ArrayList<Update> getUpdates() {
247 static class Update {
254 Update(String _appName, String _deviceId, String _attribute, String _value, boolean _ismanual) {
255 this.appName = _appName;
256 this.deviceId = _deviceId;
257 this.attribute = _attribute;
259 this.ismanual = _ismanual;
270 String getDeviceId() {
274 String getAttribute() {
282 //Gets an index object for indexing updates by just device and attribute
283 IndexObject getIndex() {
284 return new IndexObject(this);
287 public boolean equals(Object o) {
288 if (!(o instanceof Update))
291 return (getDeviceId().equals(u.getDeviceId()) &&
292 getAttribute().equals(u.getAttribute()) &&
293 getApp().equals(u.getApp()) &&
294 getValue().equals(u.getValue()));
297 public int hashCode() {
298 return (getDeviceId().hashCode() << 3) ^
299 (getAttribute().hashCode() << 2) ^
300 (getApp().hashCode() << 1) ^
301 getValue().hashCode();
305 static class IndexObject {
307 IndexObject(Update _u) {
311 public boolean equals(Object o) {
312 if (!(o instanceof IndexObject))
314 IndexObject io=(IndexObject)o;
315 return (u.getDeviceId().equals(io.u.getDeviceId()) &&
316 u.getAttribute().equals(io.u.getAttribute()));
318 public int hashCode() {
319 return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
324 public void stateRestored(Search search) {
325 id = search.getStateId();
326 depth = search.getDepth();
327 operation = "restored";
330 out.println("The state is restored to state with id: "+id+", depth: "+depth);
332 // Update the parent node
333 parentNode = getNode(id);
337 public void searchStarted(Search search) {
338 out.println("----------------------------------- search started");
341 private Node getNode(Integer id) {
342 if (!nodes.containsKey(id))
343 nodes.put(id, new Node(id));
344 return nodes.get(id);
348 public void stateAdvanced(Search search) {
349 String theEnd = null;
350 Transition transition = search.getTransition();
351 id = search.getStateId();
352 depth = search.getDepth();
353 operation = "forward";
355 // Add the node to the list of nodes
356 Node currentNode = getNode(id);
358 // Create an edge based on the current transition
359 Edge newEdge = createEdge(parentNode, currentNode, transition);
361 // Reset the temporary variables and flags
365 // If we have a new Edge, check for conflicts
367 propagateChange(newEdge);
369 if (search.isNewState()) {
375 if (search.isEndState()) {
376 out.println("This is the last state!");
380 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
382 // Update the parent node
383 parentNode = currentNode;
387 public void stateBacktracked(Search search) {
388 id = search.getStateId();
389 depth = search.getDepth();
390 operation = "backtrack";
393 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
395 // Update the parent node
396 parentNode = getNode(id);
400 public void searchFinished(Search search) {
401 out.println("----------------------------------- search finished");
404 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
408 frame = ti.getTopFrame();
410 if ((inst instanceof JVMLocalVariableInstruction) ||
411 (inst instanceof JVMFieldInstruction))
413 if (frame.getTopPos() < 0)
417 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
419 return(decodeValue(type, lo, hi));
422 if (inst instanceof JVMArrayElementInstruction)
423 return(getArrayValue(ti, type));
428 private final static String decodeValue(byte type, int lo, int hi) {
430 case Types.T_ARRAY: return(null);
431 case Types.T_VOID: return(null);
433 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
434 case Types.T_BYTE: return(String.valueOf(lo));
435 case Types.T_CHAR: return(String.valueOf((char) lo));
436 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
437 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
438 case Types.T_INT: return(String.valueOf(lo));
439 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
440 case Types.T_SHORT: return(String.valueOf(lo));
442 case Types.T_REFERENCE:
443 ElementInfo ei = VM.getVM().getHeap().get(lo);
447 ClassInfo ci = ei.getClassInfo();
451 if (ci.getName().equals("java.lang.String"))
452 return('"' + ei.asString() + '"');
454 return(ei.toString());
457 System.err.println("Unknown type: " + type);
462 private String getArrayValue(ThreadInfo ti, byte type) {
466 frame = ti.getTopFrame();
468 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
470 return(decodeValue(type, lo, hi));
473 private byte getType(ThreadInfo ti, Instruction inst) {
478 frame = ti.getTopFrame();
479 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
480 return (Types.T_REFERENCE);
485 if (inst instanceof JVMLocalVariableInstruction) {
486 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
487 } else if (inst instanceof JVMFieldInstruction){
488 fi = ((JVMFieldInstruction) inst).getFieldInfo();
492 if (inst instanceof JVMArrayElementInstruction) {
493 return (getTypeFromInstruction(inst));
497 return (Types.T_VOID);
500 return (decodeType(type));
503 private final static byte getTypeFromInstruction(Instruction inst) {
504 if (inst instanceof JVMArrayElementInstruction)
505 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
507 return(Types.T_VOID);
510 private final static byte decodeType(String type) {
511 if (type.charAt(0) == '?'){
512 return(Types.T_REFERENCE);
514 return Types.getBuiltinType(type);
518 // Find the variable writer
519 // It should be one of the apps listed in the .jpf file
520 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
521 // Start looking from the top of the stack backward
522 for(int i=sfList.size()-1; i>=0; i--) {
523 MethodInfo mi = sfList.get(i).getMethodInfo();
524 if(!mi.isJPFInternal()) {
525 String method = mi.getStackTraceName();
526 // Check against the writers in the writerSet
527 for(String writer : writerSet) {
528 if (method.contains(writer)) {
538 private void writeWriterAndValue(String writer, String attribute, String value) {
539 Update u = new Update(writer, "DEVICE", attribute, value, manual);
544 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
546 if (System.currentTimeMillis() - startTime > timeout) {
547 StringBuilder sbTimeOut = new StringBuilder();
548 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
549 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
550 ti.setNextPC(nextIns);
555 StringBuilder sb = new StringBuilder();
556 sb.append(errorMessage);
557 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
558 ti.setNextPC(nextIns);
559 } else if (conflictSet.contains(LOCATION_VAR)) {
560 MethodInfo mi = executedInsn.getMethodInfo();
561 // Find the last load before return and get the value here
562 if (mi.getName().equals(SET_LOCATION_METHOD) &&
563 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
564 byte type = getType(ti, executedInsn);
565 String value = getValue(ti, executedInsn, type);
567 // Extract the writer app name
568 ClassInfo ci = mi.getClassInfo();
569 String writer = ci.getName();
571 // Update the temporary Set set.
572 writeWriterAndValue(writer, LOCATION_VAR, value);
575 if (executedInsn instanceof WriteInstruction) {
576 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
578 // Check if we have an update to isManualTransaction to update manual field
579 if (varId.contains("isManualTransaction")) {
580 byte type = getType(ti, executedInsn);
581 String value = getValue(ti, executedInsn, type);
583 manual = (value.equals("true"))?true:false;
586 for (String var : conflictSet) {
587 if (varId.contains(var)) {
589 byte type = getType(ti, executedInsn);
590 String value = getValue(ti, executedInsn, type);
591 String writer = getWriter(ti.getStack(), appSet);
593 // Just return if the writer is not one of the listed apps in the .jpf file
597 // Update the current updates
598 writeWriterAndValue(writer, var, value);