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;
30 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
32 import java.io.PrintWriter;
37 * Listener using data flow analysis to find conflicts between smartApps.
40 public class ConflictTracker extends ListenerAdapter {
42 private final PrintWriter out;
43 private final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
44 private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
45 private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
46 private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
47 private HashSet<Transition> transitions = new HashSet<Transition>();
48 private ArrayList<Update> currUpdates = new ArrayList<Update>();
50 private long startTime;
51 private Node parentNode = new Node(-2);
52 private String operation;
53 private String detail;
54 private String errorMessage;
57 private boolean manual = false;
58 private boolean conflictFound = false;
59 private int currentEvent = -1;
60 private boolean debugMode = false;
62 private final String SET_LOCATION_METHOD = "setLocationMode";
63 private final String LOCATION_VAR = "locationMode";
65 public ConflictTracker(Config config, JPF jpf) {
66 out = new PrintWriter(System.out, true);
67 debugMode = config.getBoolean("debug_mode", false);
69 String[] conflictVars = config.getStringArray("variables");
70 // We are not tracking anything if it is null
71 if (conflictVars != null) {
72 for (String var : conflictVars) {
76 String[] apps = config.getStringArray("apps");
77 // We are not tracking anything if it is null
79 for (String var : apps) {
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 this is debug mode, then we do not report any conflicts
133 if (!debugMode && confupdates != null && !u.isManual()) {
134 for(Update u2: confupdates) {
135 if (conflicts(u, u2)) {
136 //throw new RuntimeException(createErrorMessage(u, u2));
137 conflictFound = true;
138 errorMessage = createErrorMessage(u, u2);
142 lastupdate.put(io, u);
144 for(IndexObject io: srcUpdates.keySet()) {
145 //Only propagate src changes if the transition doesn't update the device attribute
146 if (!lastupdate.containsKey(io)) {
147 //Make sure destination has hashset in map
148 if (!dstUpdates.containsKey(io))
149 dstUpdates.put(io, new HashSet<Update>());
151 changed |= dstUpdates.get(io).addAll(srcUpdates.get(io));
154 for(IndexObject io: lastupdate.keySet()) {
155 //Make sure destination has hashset in map
156 if (!dstUpdates.containsKey(io))
157 dstUpdates.put(io, new HashSet<Update>());
159 changed |= dstUpdates.get(io).add(lastupdate.get(io));
164 //Method to check for conflicts between two updates
165 //Have conflict if same device, same attribute, different app, different vaalue
166 boolean conflicts(Update u, Update u2) {
167 return (!u.getApp().equals(u2.getApp())) &&
168 u.getDeviceId().equals(u2.getDeviceId()) &&
169 u.getAttribute().equals(u2.getAttribute()) &&
170 (!u.getValue().equals(u2.getValue()));
173 String createErrorMessage(Update u, Update u2) {
174 String message = "Conflict found between the two apps. "+u.getApp()+
175 " has written the value: "+u.getValue()+
176 " to the attribute: "+u.getAttribute()+" while "
177 +u2.getApp()+" is writing the value: "
178 +u2.getValue()+" to the same variable!";
179 System.out.println(message);
183 Edge createEdge(Node parent, Node current, Transition transition, int evtNum) {
184 //Check if this transition is explored. If so, just skip everything
185 if (transitions.contains(transition))
189 Edge e = new Edge(parent, current, transition, evtNum, currUpdates);
190 parent.addOutEdge(e);
192 //Mark transition as explored
193 transitions.add(transition);
199 Vector<Edge> outEdges = new Vector<Edge>();
200 HashMap<IndexObject, HashSet<Update>> lastUpdates = new HashMap<IndexObject, HashSet<Update>>();
210 Vector<Edge> getOutEdges() {
214 void addOutEdge(Edge e) {
218 HashMap<IndexObject, HashSet<Update>> getLastUpdates() {
223 //Each Edge corresponds to a transition
225 Node source, destination;
226 Transition transition;
228 ArrayList<Update> updates = new ArrayList<Update>();
230 Edge(Node src, Node dst, Transition t, int evtNum, ArrayList<Update> _updates) {
232 this.destination = dst;
234 this.eventNumber = evtNum;
235 this.updates.addAll(_updates);
246 Transition getTransition() {
250 int getEventNumber() { return eventNumber; }
252 ArrayList<Update> getUpdates() {
257 static class Update {
264 Update(String _appName, String _deviceId, String _attribute, String _value, boolean _ismanual) {
265 this.appName = _appName;
266 this.deviceId = _deviceId;
267 this.attribute = _attribute;
269 this.ismanual = _ismanual;
280 String getDeviceId() {
284 String getAttribute() {
292 //Gets an index object for indexing updates by just device and attribute
293 IndexObject getIndex() {
294 return new IndexObject(this);
297 public boolean equals(Object o) {
298 if (!(o instanceof Update))
301 return (getDeviceId().equals(u.getDeviceId()) &&
302 getAttribute().equals(u.getAttribute()) &&
303 getApp().equals(u.getApp()) &&
304 getValue().equals(u.getValue()));
307 public int hashCode() {
308 return (getDeviceId().hashCode() << 3) ^
309 (getAttribute().hashCode() << 2) ^
310 (getApp().hashCode() << 1) ^
311 getValue().hashCode();
314 public String toString() {
315 return "<"+getAttribute()+", "+getValue()+", "+getApp()+", "+ismanual+">";
319 static class IndexObject {
321 IndexObject(Update _u) {
325 public boolean equals(Object o) {
326 if (!(o instanceof IndexObject))
328 IndexObject io=(IndexObject)o;
329 return (u.getDeviceId().equals(io.u.getDeviceId()) &&
330 u.getAttribute().equals(io.u.getAttribute()));
332 public int hashCode() {
333 return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
338 public void stateRestored(Search search) {
339 id = search.getStateId();
340 depth = search.getDepth();
341 operation = "restored";
344 out.println("The state is restored to state with id: "+id+", depth: "+depth);
346 // Update the parent node
347 parentNode = getNode(id);
351 public void searchStarted(Search search) {
352 out.println("----------------------------------- search started");
355 private Node getNode(Integer id) {
356 if (!nodes.containsKey(id))
357 nodes.put(id, new Node(id));
358 return nodes.get(id);
361 public void printGraph() {
362 System.out.println("digraph testgraph {");
363 for(Integer i : nodes.keySet()) {
364 Node n = nodes.get(i);
365 System.out.print("N"+i+"[label=\"");
367 for(IndexObject io:n.lastUpdates.keySet()) {
368 for(Update u:n.lastUpdates.get(io)) {
369 System.out.print(u.toString().replace("\"", "\\\"")+", ");
372 System.out.println("\"];");
373 for(Edge e:n.outEdges) {
374 System.out.print("N"+e.getSrc().getId()+"->N"+e.getDst().getId()+"[label=\"");
375 for(Update u:e.getUpdates()) {
376 System.out.print(u.toString().replace("\"", "\\\"")+", ");
378 System.out.println("\"];");
382 System.out.println("}");
386 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
388 if (currentCG instanceof IntChoiceFromSet) {
389 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
390 currentEvent = icsCG.getNextChoice();
395 public void stateAdvanced(Search search) {
396 String theEnd = null;
397 Transition transition = search.getTransition();
398 id = search.getStateId();
399 depth = search.getDepth();
400 operation = "forward";
402 // Add the node to the list of nodes
403 Node currentNode = getNode(id);
405 // Create an edge based on the current transition
406 Edge newEdge = createEdge(parentNode, currentNode, transition, currentEvent);
408 // Reset the temporary variables and flags
412 // If we have a new Edge, check for conflicts
414 propagateChange(newEdge);
416 if (search.isNewState()) {
422 if (search.isEndState()) {
423 out.println("This is the last state!");
427 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
429 // Update the parent node
430 parentNode = currentNode;
434 public void stateBacktracked(Search search) {
435 id = search.getStateId();
436 depth = search.getDepth();
437 operation = "backtrack";
440 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
442 // Update the parent node
443 parentNode = getNode(id);
447 public void searchFinished(Search search) {
448 out.println("----------------------------------- search finished");
450 //Comment out the following line to print the explored graph
454 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
458 frame = ti.getTopFrame();
460 if ((inst instanceof JVMLocalVariableInstruction) ||
461 (inst instanceof JVMFieldInstruction))
463 if (frame.getTopPos() < 0)
467 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
469 // TODO: Fix for integer values (need to dig deeper into the stack frame to find the right value other than 0)
470 // TODO: Seems to be a problem since this is Groovy (not Java)
471 if (type == Types.T_INT || type == Types.T_LONG || type == Types.T_SHORT) {
474 lo = frame.peek(offset);
479 return(decodeValue(type, lo, hi));
482 if (inst instanceof JVMArrayElementInstruction)
483 return(getArrayValue(ti, type));
488 private final static String decodeValue(byte type, int lo, int hi) {
490 case Types.T_ARRAY: return(null);
491 case Types.T_VOID: return(null);
493 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
494 case Types.T_BYTE: return(String.valueOf(lo));
495 case Types.T_CHAR: return(String.valueOf((char) lo));
496 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
497 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
498 case Types.T_INT: return(String.valueOf(lo));
499 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
500 case Types.T_SHORT: return(String.valueOf(lo));
502 case Types.T_REFERENCE:
503 ElementInfo ei = VM.getVM().getHeap().get(lo);
507 ClassInfo ci = ei.getClassInfo();
511 if (ci.getName().equals("java.lang.String"))
512 return('"' + ei.asString() + '"');
514 return(ei.toString());
517 System.err.println("Unknown type: " + type);
522 private String getArrayValue(ThreadInfo ti, byte type) {
526 frame = ti.getTopFrame();
528 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
530 return(decodeValue(type, lo, hi));
533 private byte getType(ThreadInfo ti, Instruction inst) {
538 frame = ti.getTopFrame();
539 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
540 return (Types.T_REFERENCE);
545 if (inst instanceof JVMLocalVariableInstruction) {
546 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
547 } else if (inst instanceof JVMFieldInstruction){
548 fi = ((JVMFieldInstruction) inst).getFieldInfo();
552 if (inst instanceof JVMArrayElementInstruction) {
553 return (getTypeFromInstruction(inst));
557 return (Types.T_VOID);
560 return (decodeType(type));
563 private final static byte getTypeFromInstruction(Instruction inst) {
564 if (inst instanceof JVMArrayElementInstruction)
565 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
567 return(Types.T_VOID);
570 private final static byte decodeType(String type) {
571 if (type.charAt(0) == '?'){
572 return(Types.T_REFERENCE);
574 return Types.getBuiltinType(type);
578 // Find the variable writer
579 // It should be one of the apps listed in the .jpf file
580 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
581 // Start looking from the top of the stack backward
582 for(int i=sfList.size()-1; i>=0; i--) {
583 MethodInfo mi = sfList.get(i).getMethodInfo();
584 if(!mi.isJPFInternal()) {
585 String method = mi.getStackTraceName();
586 // Check against the writers in the writerSet
587 for(String writer : writerSet) {
588 if (method.contains(writer)) {
598 private void writeWriterAndValue(String writer, String attribute, String value) {
599 Update u = new Update(writer, "DEVICE", attribute, value, manual);
604 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
606 if (System.currentTimeMillis() - startTime > timeout) {
607 StringBuilder sbTimeOut = new StringBuilder();
608 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
609 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
610 ti.setNextPC(nextIns);
616 StringBuilder sb = new StringBuilder();
617 sb.append(errorMessage);
618 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
619 ti.setNextPC(nextIns);
622 if (executedInsn instanceof WriteInstruction) {
623 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
624 // Check if we have an update to isManualTransaction to update manual field
625 if (varId.contains("isManualTransaction")) {
626 byte type = getType(ti, executedInsn);
627 String value = getValue(ti, executedInsn, type);
628 System.out.println();
629 manual = (value.equals("true"))?true:false;
631 for (String var : conflictSet) {
632 if (varId.contains(var)) {
634 byte type = getType(ti, executedInsn);
635 String value = getValue(ti, executedInsn, type);
636 String writer = getWriter(ti.getStack(), appSet);
638 // Just return if the writer is not one of the listed apps in the .jpf file
642 // Update the current updates
643 writeWriterAndValue(writer, var, value);