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();
304 public String toString() {
305 return "<"+getAttribute()+", "+getValue()+", "+getApp()+", "+ismanual+">";
309 static class IndexObject {
311 IndexObject(Update _u) {
315 public boolean equals(Object o) {
316 if (!(o instanceof IndexObject))
318 IndexObject io=(IndexObject)o;
319 return (u.getDeviceId().equals(io.u.getDeviceId()) &&
320 u.getAttribute().equals(io.u.getAttribute()));
322 public int hashCode() {
323 return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
328 public void stateRestored(Search search) {
329 id = search.getStateId();
330 depth = search.getDepth();
331 operation = "restored";
334 out.println("The state is restored to state with id: "+id+", depth: "+depth);
336 // Update the parent node
337 parentNode = getNode(id);
341 public void searchStarted(Search search) {
342 out.println("----------------------------------- search started");
345 private Node getNode(Integer id) {
346 if (!nodes.containsKey(id))
347 nodes.put(id, new Node(id));
348 return nodes.get(id);
351 public void printGraph() {
352 System.out.println("digraph testgraph {");
353 for(Integer i : nodes.keySet()) {
354 Node n = nodes.get(i);
355 System.out.print("N"+i+"[label=\"");
357 for(IndexObject io:n.lastUpdates.keySet()) {
358 for(Update u:n.lastUpdates.get(io)) {
359 System.out.print(u.toString().replace("\"", "\\\"")+", ");
362 System.out.println("\"];");
363 for(Edge e:n.outEdges) {
364 System.out.print("N"+e.getSrc().getId()+"->N"+e.getDst().getId()+"[label=\"");
365 for(Update u:e.getUpdates()) {
366 System.out.print(u.toString().replace("\"", "\\\"")+", ");
368 System.out.println("\"];");
372 System.out.println("}");
376 public void stateAdvanced(Search search) {
377 String theEnd = null;
378 Transition transition = search.getTransition();
379 id = search.getStateId();
380 depth = search.getDepth();
381 operation = "forward";
383 // Add the node to the list of nodes
384 Node currentNode = getNode(id);
386 // Create an edge based on the current transition
387 Edge newEdge = createEdge(parentNode, currentNode, transition);
389 // Reset the temporary variables and flags
393 // If we have a new Edge, check for conflicts
395 propagateChange(newEdge);
397 if (search.isNewState()) {
403 if (search.isEndState()) {
404 out.println("This is the last state!");
408 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
410 // Update the parent node
411 parentNode = currentNode;
415 public void stateBacktracked(Search search) {
416 id = search.getStateId();
417 depth = search.getDepth();
418 operation = "backtrack";
421 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
423 // Update the parent node
424 parentNode = getNode(id);
428 public void searchFinished(Search search) {
429 out.println("----------------------------------- search finished");
431 //Comment out the following line to print the explored graph
435 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
439 frame = ti.getTopFrame();
441 if ((inst instanceof JVMLocalVariableInstruction) ||
442 (inst instanceof JVMFieldInstruction))
444 if (frame.getTopPos() < 0)
448 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
450 return(decodeValue(type, lo, hi));
453 if (inst instanceof JVMArrayElementInstruction)
454 return(getArrayValue(ti, type));
459 private final static String decodeValue(byte type, int lo, int hi) {
461 case Types.T_ARRAY: return(null);
462 case Types.T_VOID: return(null);
464 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
465 case Types.T_BYTE: return(String.valueOf(lo));
466 case Types.T_CHAR: return(String.valueOf((char) lo));
467 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
468 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
469 case Types.T_INT: return(String.valueOf(lo));
470 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
471 case Types.T_SHORT: return(String.valueOf(lo));
473 case Types.T_REFERENCE:
474 ElementInfo ei = VM.getVM().getHeap().get(lo);
478 ClassInfo ci = ei.getClassInfo();
482 if (ci.getName().equals("java.lang.String"))
483 return('"' + ei.asString() + '"');
485 return(ei.toString());
488 System.err.println("Unknown type: " + type);
493 private String getArrayValue(ThreadInfo ti, byte type) {
497 frame = ti.getTopFrame();
499 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
501 return(decodeValue(type, lo, hi));
504 private byte getType(ThreadInfo ti, Instruction inst) {
509 frame = ti.getTopFrame();
510 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
511 return (Types.T_REFERENCE);
516 if (inst instanceof JVMLocalVariableInstruction) {
517 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
518 } else if (inst instanceof JVMFieldInstruction){
519 fi = ((JVMFieldInstruction) inst).getFieldInfo();
523 if (inst instanceof JVMArrayElementInstruction) {
524 return (getTypeFromInstruction(inst));
528 return (Types.T_VOID);
531 return (decodeType(type));
534 private final static byte getTypeFromInstruction(Instruction inst) {
535 if (inst instanceof JVMArrayElementInstruction)
536 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
538 return(Types.T_VOID);
541 private final static byte decodeType(String type) {
542 if (type.charAt(0) == '?'){
543 return(Types.T_REFERENCE);
545 return Types.getBuiltinType(type);
549 // Find the variable writer
550 // It should be one of the apps listed in the .jpf file
551 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
552 // Start looking from the top of the stack backward
553 for(int i=sfList.size()-1; i>=0; i--) {
554 MethodInfo mi = sfList.get(i).getMethodInfo();
555 if(!mi.isJPFInternal()) {
556 String method = mi.getStackTraceName();
557 // Check against the writers in the writerSet
558 for(String writer : writerSet) {
559 if (method.contains(writer)) {
569 private void writeWriterAndValue(String writer, String attribute, String value) {
570 Update u = new Update(writer, "DEVICE", attribute, value, manual);
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);
590 } else if (conflictSet.contains(LOCATION_VAR)) {
591 MethodInfo mi = executedInsn.getMethodInfo();
592 // Find the last load before return and get the value here
593 if (mi.getName().equals(SET_LOCATION_METHOD) &&
594 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
595 byte type = getType(ti, executedInsn);
596 String value = getValue(ti, executedInsn, type);
598 // Extract the writer app name
599 ClassInfo ci = mi.getClassInfo();
600 String writer = ci.getName();
602 // Update the temporary Set set.
603 writeWriterAndValue(writer, LOCATION_VAR, value);
606 if (executedInsn instanceof WriteInstruction) {
607 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
609 // Check if we have an update to isManualTransaction to update manual field
610 if (varId.contains("isManualTransaction")) {
611 byte type = getType(ti, executedInsn);
612 String value = getValue(ti, executedInsn, type);
614 manual = (value.equals("true"))?true:false;
617 for (String var : conflictSet) {
618 if (varId.contains(var)) {
620 byte type = getType(ti, executedInsn);
621 String value = getValue(ti, executedInsn, type);
622 String writer = getWriter(ti.getStack(), appSet);
624 // Just return if the writer is not one of the listed apps in the .jpf file
628 // Update the current updates
629 writeWriterAndValue(writer, var, value);