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;
54 private boolean manual = false;
56 private final String SET_LOCATION_METHOD = "setLocationMode";
57 private final String LOCATION_VAR = "locationMode";
59 public ConflictTracker(Config config, JPF jpf) {
60 out = new PrintWriter(System.out, true);
62 String[] conflictVars = config.getStringArray("variables");
63 // We are not tracking anything if it is null
64 if (conflictVars != null) {
65 for (String var : conflictVars) {
69 String[] apps = config.getStringArray("apps");
70 // We are not tracking anything if it is null
72 for (String var : apps) {
76 String[] manualClasses = config.getStringArray("manualClasses");
77 // We are not tracking anything if it is null
78 if (manualClasses != null) {
79 for (String var : manualClasses) {
84 // Timeout input from config is in minutes, so we need to convert into millis
85 timeout = config.getInt("timeout", 0) * 60 * 1000;
86 startTime = System.currentTimeMillis();
89 void propagateChange(Edge newEdge) {
90 HashSet<Edge> changed = new HashSet<Edge>();
92 // Add the current node to the changed set
95 while(!changed.isEmpty()) {
96 // Get the first element of the changed set and remove it
97 Edge edgeToProcess = changed.iterator().next();
98 changed.remove(edgeToProcess);
100 //If propagating change on edge causes change, enqueue all the target node's out edges
101 if (propagateEdge(edgeToProcess)) {
102 Node dst = edgeToProcess.getDst();
103 for (Edge e : dst.getOutEdges()) {
110 boolean propagateEdge(Edge e) {
111 HashMap<IndexObject, HashSet<Update>> srcUpdates = e.getSrc().getLastUpdates();
112 HashMap<IndexObject, HashSet<Update>> dstUpdates = e.getDst().getLastUpdates();
113 ArrayList<Update> edgeUpdates = e.getUpdates();
114 HashMap<IndexObject, Update> lastupdate = new HashMap<IndexObject, Update>();
115 boolean changed = false;
117 //Go through each update on the current transition
118 for(int i=0; i<edgeUpdates.size(); i++) {
119 Update u = edgeUpdates.get(i);
120 IndexObject io = u.getIndex();
121 HashSet<Update> confupdates = null;
123 //See if we have already updated this device attribute
124 if (lastupdate.containsKey(io)) {
125 confupdates = new HashSet<Update>();
126 confupdates.add(lastupdate.get(io));
127 } else if (srcUpdates.containsKey(io)){
128 confupdates = srcUpdates.get(io);
131 //Check for conflict with the appropriate update set if we are not a manual transition
132 if (confupdates != null && !e.isManual()) {
133 for(Update u2: confupdates) {
134 if (conflicts(u, u2)) {
135 throw new RuntimeException(createErrorMessage(u, u2));
139 lastupdate.put(io, u);
141 for(IndexObject io: srcUpdates.keySet()) {
142 //Only propagate src changes if the transition doesn't update the device attribute
143 if (!lastupdate.containsKey(io)) {
144 //Make sure destination has hashset in map
145 if (!dstUpdates.containsKey(io))
146 dstUpdates.put(io, new HashSet<Update>());
148 changed |= dstUpdates.get(io).addAll(srcUpdates.get(io));
151 for(IndexObject io: lastupdate.keySet()) {
152 //Make sure destination has hashset in map
153 if (!dstUpdates.containsKey(io))
154 dstUpdates.put(io, new HashSet<Update>());
156 changed |= dstUpdates.get(io).add(lastupdate.get(io));
161 //Method to check for conflicts between two updates
162 //Have conflict if same device, same attribute, different app, different vaalue
163 boolean conflicts(Update u, Update u2) {
164 return (!u.getApp().equals(u2.getApp())) &&
165 u.getDeviceId().equals(u2.getDeviceId()) &&
166 u.getAttribute().equals(u2.getAttribute()) &&
167 (!u.getValue().equals(u2.getValue()));
170 String createErrorMessage(Update u, Update u2) {
171 String message = "Conflict found between the two apps. App"+u.getApp()+
172 " has written the value: "+u.getValue()+
173 " to the attribute: "+u.getAttribute()+" while App"
174 +u2.getApp()+" is writing the value: "
175 +u2.getValue()+" to the same variable!";
176 System.out.println(message);
180 Edge createEdge(Node parent, Node current, Transition transition, boolean ismanual) {
181 //Check if this transition is explored. If so, just skip everything
182 if (transitions.contains(transition))
186 Edge e = new Edge(parent, current, transition, currUpdates, ismanual);
187 parent.addOutEdge(e);
189 //Mark transition as explored
190 transitions.add(transition);
196 Vector<Edge> outEdges = new Vector<Edge>();
197 HashMap<IndexObject, HashSet<Update>> lastUpdates = new HashMap<IndexObject, HashSet<Update>>();
207 Vector<Edge> getOutEdges() {
211 void addOutEdge(Edge e) {
215 HashMap<IndexObject, HashSet<Update>> getLastUpdates() {
220 //Each Edge corresponds to a transition
222 Node source, destination;
223 Transition transition;
224 ArrayList<Update> updates = new ArrayList<Update>();
227 Edge(Node src, Node dst, Transition t, ArrayList<Update> _updates, boolean _ismanual) {
229 this.destination = dst;
231 this.ismanual = _ismanual;
232 this.updates.addAll(_updates);
247 Transition getTransition() {
251 ArrayList<Update> getUpdates() {
256 static class Update {
262 Update(String _appName, String _deviceId, String _attribute, String _value) {
263 this.appName = _appName;
264 this.deviceId = _deviceId;
265 this.attribute = _attribute;
273 String getDeviceId() {
277 String getAttribute() {
285 //Gets an index object for indexing updates by just device and attribute
286 IndexObject getIndex() {
287 return new IndexObject(this);
290 public boolean equals(Object o) {
291 if (!(o instanceof Update))
294 return (getDeviceId().equals(u.getDeviceId()) &&
295 getAttribute().equals(u.getAttribute()) &&
296 getApp().equals(u.getApp()) &&
297 getValue().equals(u.getValue()));
300 public int hashCode() {
301 return (getDeviceId().hashCode() << 3) ^
302 (getAttribute().hashCode() << 2) ^
303 (getApp().hashCode() << 1) ^
304 getValue().hashCode();
308 static class IndexObject {
310 IndexObject(Update _u) {
314 public boolean equals(Object o) {
315 if (!(o instanceof IndexObject))
317 IndexObject io=(IndexObject)o;
318 return (u.getDeviceId().equals(io.u.getDeviceId()) &&
319 u.getAttribute().equals(io.u.getAttribute()));
321 public int hashCode() {
322 return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
327 public void stateRestored(Search search) {
328 id = search.getStateId();
329 depth = search.getDepth();
330 operation = "restored";
333 out.println("The state is restored to state with id: "+id+", depth: "+depth);
335 // Update the parent node
336 parentNode = getNode(id);
340 public void searchStarted(Search search) {
341 out.println("----------------------------------- search started");
344 private Node getNode(Integer id) {
345 if (!nodes.containsKey(id))
346 nodes.put(id, new Node(id));
347 return nodes.get(id);
351 public void stateAdvanced(Search search) {
352 String theEnd = null;
353 Transition transition = search.getTransition();
354 id = search.getStateId();
355 depth = search.getDepth();
356 operation = "forward";
358 // Add the node to the list of nodes
359 Node currentNode = getNode(id);
361 // Create an edge based on the current transition
362 Edge newEdge = createEdge(parentNode, currentNode, transition, manual);
364 // Reset the temporary variables and flags
368 // If we have a new Edge, check for conflicts
370 propagateChange(newEdge);
372 if (search.isNewState()) {
378 if (search.isEndState()) {
379 out.println("This is the last state!");
383 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
385 // Update the parent node
386 parentNode = currentNode;
390 public void stateBacktracked(Search search) {
391 id = search.getStateId();
392 depth = search.getDepth();
393 operation = "backtrack";
396 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
398 // Update the parent node
399 parentNode = getNode(id);
403 public void searchFinished(Search search) {
404 out.println("----------------------------------- search finished");
407 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
411 frame = ti.getTopFrame();
413 if ((inst instanceof JVMLocalVariableInstruction) ||
414 (inst instanceof JVMFieldInstruction))
416 if (frame.getTopPos() < 0)
420 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
422 return(decodeValue(type, lo, hi));
425 if (inst instanceof JVMArrayElementInstruction)
426 return(getArrayValue(ti, type));
431 private final static String decodeValue(byte type, int lo, int hi) {
433 case Types.T_ARRAY: return(null);
434 case Types.T_VOID: return(null);
436 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
437 case Types.T_BYTE: return(String.valueOf(lo));
438 case Types.T_CHAR: return(String.valueOf((char) lo));
439 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
440 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
441 case Types.T_INT: return(String.valueOf(lo));
442 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
443 case Types.T_SHORT: return(String.valueOf(lo));
445 case Types.T_REFERENCE:
446 ElementInfo ei = VM.getVM().getHeap().get(lo);
450 ClassInfo ci = ei.getClassInfo();
454 if (ci.getName().equals("java.lang.String"))
455 return('"' + ei.asString() + '"');
457 return(ei.toString());
460 System.err.println("Unknown type: " + type);
465 private String getArrayValue(ThreadInfo ti, byte type) {
469 frame = ti.getTopFrame();
471 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
473 return(decodeValue(type, lo, hi));
476 private byte getType(ThreadInfo ti, Instruction inst) {
481 frame = ti.getTopFrame();
482 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
483 return (Types.T_REFERENCE);
488 if (inst instanceof JVMLocalVariableInstruction) {
489 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
490 } else if (inst instanceof JVMFieldInstruction){
491 fi = ((JVMFieldInstruction) inst).getFieldInfo();
495 if (inst instanceof JVMArrayElementInstruction) {
496 return (getTypeFromInstruction(inst));
500 return (Types.T_VOID);
503 return (decodeType(type));
506 private final static byte getTypeFromInstruction(Instruction inst) {
507 if (inst instanceof JVMArrayElementInstruction)
508 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
510 return(Types.T_VOID);
513 private final static byte decodeType(String type) {
514 if (type.charAt(0) == '?'){
515 return(Types.T_REFERENCE);
517 return Types.getBuiltinType(type);
521 // Find the variable writer
522 // It should be one of the apps listed in the .jpf file
523 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
524 // Start looking from the top of the stack backward
525 for(int i=sfList.size()-1; i>=0; i--) {
526 MethodInfo mi = sfList.get(i).getMethodInfo();
527 if(!mi.isJPFInternal()) {
528 String method = mi.getStackTraceName();
529 // Check against the writers in the writerSet
530 for(String writer : writerSet) {
531 if (method.contains(writer)) {
541 private void writeWriterAndValue(String writer, String attribute, String value) {
542 Update u = new Update(writer, "DEVICE", attribute, value);
547 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
549 if (System.currentTimeMillis() - startTime > timeout) {
550 StringBuilder sbTimeOut = new StringBuilder();
551 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
552 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
553 ti.setNextPC(nextIns);
557 if (conflictSet.contains(LOCATION_VAR)) {
558 MethodInfo mi = executedInsn.getMethodInfo();
559 // Find the last load before return and get the value here
560 if (mi.getName().equals(SET_LOCATION_METHOD) &&
561 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
562 byte type = getType(ti, executedInsn);
563 String value = getValue(ti, executedInsn, type);
565 // Extract the writer app name
566 ClassInfo ci = mi.getClassInfo();
567 String writer = ci.getName();
569 // Update the temporary Set set.
570 writeWriterAndValue(writer, LOCATION_VAR, value);
573 if (executedInsn instanceof WriteInstruction) {
574 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
576 for (String var : conflictSet) {
577 if (varId.contains(var)) {
579 byte type = getType(ti, executedInsn);
580 String value = getValue(ti, executedInsn, type);
581 String writer = getWriter(ti.getStack(), appSet);
582 // Just return if the writer is not one of the listed apps in the .jpf file
586 if (getWriter(ti.getStack(), manualSet) != null)
589 // Update the current updates
590 writeWriterAndValue(writer, var, value);