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 {
41 // Public graph: to allow the StateReducer class to access it
42 public static final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
44 private final PrintWriter out;
45 private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
46 private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
47 private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
48 private HashSet<Transition> transitions = new HashSet<Transition>();
49 private ArrayList<Update> currUpdates = new ArrayList<Update>();
51 private long startTime;
52 private Node parentNode = new Node(-2);
53 private String operation;
54 private String detail;
55 private String errorMessage;
58 private boolean manual = false;
59 private boolean conflictFound = false;
60 private int currentEvent = -1;
61 private boolean debugMode = false;
63 private final String SET_LOCATION_METHOD = "setLocationMode";
64 private final String LOCATION_VAR = "locationMode";
66 public ConflictTracker(Config config, JPF jpf) {
67 out = new PrintWriter(System.out, true);
68 debugMode = config.getBoolean("debug_mode", false);
70 String[] conflictVars = config.getStringArray("variables");
71 // We are not tracking anything if it is null
72 if (conflictVars != null) {
73 for (String var : conflictVars) {
77 String[] apps = config.getStringArray("apps");
78 // We are not tracking anything if it is null
80 for (String var : apps) {
85 // Timeout input from config is in minutes, so we need to convert into millis
86 timeout = config.getInt("timeout", 0) * 60 * 1000;
87 startTime = System.currentTimeMillis();
90 void propagateChange(Edge newEdge) {
91 HashSet<Edge> changed = new HashSet<Edge>();
93 // Add the current node to the changed set
96 while(!changed.isEmpty()) {
97 // Get the first element of the changed set and remove it
98 Edge edgeToProcess = changed.iterator().next();
99 changed.remove(edgeToProcess);
101 //If propagating change on edge causes change, enqueue all the target node's out edges
102 if (propagateEdge(edgeToProcess)) {
103 Node dst = edgeToProcess.getDst();
104 for (Edge e : dst.getOutEdges()) {
111 boolean propagateEdge(Edge e) {
112 HashMap<IndexObject, HashSet<Update>> srcUpdates = e.getSrc().getLastUpdates();
113 HashMap<IndexObject, HashSet<Update>> dstUpdates = e.getDst().getLastUpdates();
114 ArrayList<Update> edgeUpdates = e.getUpdates();
115 HashMap<IndexObject, Update> lastupdate = new HashMap<IndexObject, Update>();
116 boolean changed = false;
118 //Go through each update on the current transition
119 for(int i=0; i<edgeUpdates.size(); i++) {
120 Update u = edgeUpdates.get(i);
121 IndexObject io = u.getIndex();
122 HashSet<Update> confupdates = null;
124 //See if we have already updated this device attribute
125 if (lastupdate.containsKey(io)) {
126 confupdates = new HashSet<Update>();
127 confupdates.add(lastupdate.get(io));
128 } else if (srcUpdates.containsKey(io)){
129 confupdates = srcUpdates.get(io);
132 //Check for conflict with the appropriate update set if we are not a manual transition
133 //If this is debug mode, then we do not report any conflicts
134 if (!debugMode && confupdates != null && !u.isManual()) {
135 for(Update u2: confupdates) {
136 if (conflicts(u, u2)) {
137 //throw new RuntimeException(createErrorMessage(u, u2));
138 conflictFound = true;
139 errorMessage = createErrorMessage(u, u2);
143 lastupdate.put(io, u);
145 for(IndexObject io: srcUpdates.keySet()) {
146 //Only propagate src changes if the transition doesn't update the device attribute
147 if (!lastupdate.containsKey(io)) {
148 //Make sure destination has hashset in map
149 if (!dstUpdates.containsKey(io))
150 dstUpdates.put(io, new HashSet<Update>());
152 changed |= dstUpdates.get(io).addAll(srcUpdates.get(io));
155 for(IndexObject io: lastupdate.keySet()) {
156 //Make sure destination has hashset in map
157 if (!dstUpdates.containsKey(io))
158 dstUpdates.put(io, new HashSet<Update>());
160 changed |= dstUpdates.get(io).add(lastupdate.get(io));
165 //Method to check for conflicts between two updates
166 //Have conflict if same device, same attribute, different app, different vaalue
167 boolean conflicts(Update u, Update u2) {
168 return (!u.getApp().equals(u2.getApp())) &&
169 u.getDeviceId().equals(u2.getDeviceId()) &&
170 u.getAttribute().equals(u2.getAttribute()) &&
171 (!u.getValue().equals(u2.getValue()));
174 String createErrorMessage(Update u, Update u2) {
175 String message = "Conflict found between the two apps. "+u.getApp()+
176 " has written the value: "+u.getValue()+
177 " to the attribute: "+u.getAttribute()+" while "
178 +u2.getApp()+" is writing the value: "
179 +u2.getValue()+" to the same variable!";
180 System.out.println(message);
184 Edge createEdge(Node parent, Node current, Transition transition, int evtNum) {
185 //Check if this transition is explored. If so, just skip everything
186 if (transitions.contains(transition))
190 Edge e = new Edge(parent, current, transition, evtNum, currUpdates);
191 parent.addOutEdge(e);
193 //Mark transition as explored
194 transitions.add(transition);
200 Vector<Edge> outEdges = new Vector<Edge>();
201 HashMap<IndexObject, HashSet<Update>> lastUpdates = new HashMap<IndexObject, HashSet<Update>>();
211 Vector<Edge> getOutEdges() {
215 void addOutEdge(Edge e) {
219 HashMap<IndexObject, HashSet<Update>> getLastUpdates() {
224 //Each Edge corresponds to a transition
226 Node source, destination;
227 Transition transition;
229 ArrayList<Update> updates = new ArrayList<Update>();
231 Edge(Node src, Node dst, Transition t, int evtNum, ArrayList<Update> _updates) {
233 this.destination = dst;
235 this.eventNumber = evtNum;
236 this.updates.addAll(_updates);
247 Transition getTransition() {
251 int getEventNumber() { return eventNumber; }
253 ArrayList<Update> getUpdates() {
258 static class Update {
265 Update(String _appName, String _deviceId, String _attribute, String _value, boolean _ismanual) {
266 this.appName = _appName;
267 this.deviceId = _deviceId;
268 this.attribute = _attribute;
270 this.ismanual = _ismanual;
281 String getDeviceId() {
285 String getAttribute() {
293 //Gets an index object for indexing updates by just device and attribute
294 IndexObject getIndex() {
295 return new IndexObject(this);
298 public boolean equals(Object o) {
299 if (!(o instanceof Update))
302 return (getDeviceId().equals(u.getDeviceId()) &&
303 getAttribute().equals(u.getAttribute()) &&
304 getApp().equals(u.getApp()) &&
305 getValue().equals(u.getValue()));
308 public int hashCode() {
309 return (getDeviceId().hashCode() << 3) ^
310 (getAttribute().hashCode() << 2) ^
311 (getApp().hashCode() << 1) ^
312 getValue().hashCode();
315 public String toString() {
316 return "<"+getAttribute()+", "+getValue()+", "+getApp()+", "+ismanual+">";
320 static class IndexObject {
322 IndexObject(Update _u) {
326 public boolean equals(Object o) {
327 if (!(o instanceof IndexObject))
329 IndexObject io=(IndexObject)o;
330 return (u.getDeviceId().equals(io.u.getDeviceId()) &&
331 u.getAttribute().equals(io.u.getAttribute()));
333 public int hashCode() {
334 return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
339 public void stateRestored(Search search) {
340 id = search.getStateId();
341 depth = search.getDepth();
342 operation = "restored";
345 out.println("The state is restored to state with id: "+id+", depth: "+depth);
347 // Update the parent node
348 parentNode = getNode(id);
352 public void searchStarted(Search search) {
353 out.println("----------------------------------- search started");
356 private Node getNode(Integer id) {
357 if (!nodes.containsKey(id))
358 nodes.put(id, new Node(id));
359 return nodes.get(id);
362 public void printGraph() {
363 System.out.println("digraph testgraph {");
364 for(Integer i : nodes.keySet()) {
365 Node n = nodes.get(i);
366 System.out.print("N"+i+"[label=\"");
368 for(IndexObject io:n.lastUpdates.keySet()) {
369 for(Update u:n.lastUpdates.get(io)) {
370 System.out.print(u.toString().replace("\"", "\\\"")+", ");
373 System.out.println("\"];");
374 for(Edge e:n.outEdges) {
375 System.out.print("N"+e.getSrc().getId()+"->N"+e.getDst().getId()+"[label=\"");
376 for(Update u:e.getUpdates()) {
377 System.out.print(u.toString().replace("\"", "\\\"")+", ");
379 System.out.println("\"];");
383 System.out.println("}");
387 public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
389 if (currentCG instanceof IntChoiceFromSet) {
390 IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
391 currentEvent = icsCG.getNextChoice();
396 public void stateAdvanced(Search search) {
397 String theEnd = null;
398 Transition transition = search.getTransition();
399 id = search.getStateId();
400 depth = search.getDepth();
401 operation = "forward";
403 // Add the node to the list of nodes
404 Node currentNode = getNode(id);
406 // Create an edge based on the current transition
407 Edge newEdge = createEdge(parentNode, currentNode, transition, currentEvent);
409 // Reset the temporary variables and flags
413 // If we have a new Edge, check for conflicts
415 propagateChange(newEdge);
417 if (search.isNewState()) {
423 if (search.isEndState()) {
424 out.println("This is the last state!");
428 out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
430 // Update the parent node
431 parentNode = currentNode;
435 public void stateBacktracked(Search search) {
436 id = search.getStateId();
437 depth = search.getDepth();
438 operation = "backtrack";
441 out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
443 // Update the parent node
444 parentNode = getNode(id);
448 public void searchFinished(Search search) {
449 out.println("----------------------------------- search finished");
451 //Comment out the following line to print the explored graph
455 private String getValue(ThreadInfo ti, Instruction inst, byte type) {
459 frame = ti.getTopFrame();
461 if ((inst instanceof JVMLocalVariableInstruction) ||
462 (inst instanceof JVMFieldInstruction))
464 if (frame.getTopPos() < 0)
468 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
470 // TODO: Fix for integer values (need to dig deeper into the stack frame to find the right value other than 0)
471 // TODO: Seems to be a problem since this is Groovy (not Java)
472 if (type == Types.T_INT || type == Types.T_LONG || type == Types.T_SHORT) {
475 lo = frame.peek(offset);
480 return(decodeValue(type, lo, hi));
483 if (inst instanceof JVMArrayElementInstruction)
484 return(getArrayValue(ti, type));
489 private final static String decodeValue(byte type, int lo, int hi) {
491 case Types.T_ARRAY: return(null);
492 case Types.T_VOID: return(null);
494 case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
495 case Types.T_BYTE: return(String.valueOf(lo));
496 case Types.T_CHAR: return(String.valueOf((char) lo));
497 case Types.T_DOUBLE: return(String.valueOf(Types.intsToDouble(lo, hi)));
498 case Types.T_FLOAT: return(String.valueOf(Types.intToFloat(lo)));
499 case Types.T_INT: return(String.valueOf(lo));
500 case Types.T_LONG: return(String.valueOf(Types.intsToLong(lo, hi)));
501 case Types.T_SHORT: return(String.valueOf(lo));
503 case Types.T_REFERENCE:
504 ElementInfo ei = VM.getVM().getHeap().get(lo);
508 ClassInfo ci = ei.getClassInfo();
512 if (ci.getName().equals("java.lang.String"))
513 return('"' + ei.asString() + '"');
515 return(ei.toString());
518 System.err.println("Unknown type: " + type);
523 private String getArrayValue(ThreadInfo ti, byte type) {
527 frame = ti.getTopFrame();
529 hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
531 return(decodeValue(type, lo, hi));
534 private byte getType(ThreadInfo ti, Instruction inst) {
539 frame = ti.getTopFrame();
540 if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
541 return (Types.T_REFERENCE);
546 if (inst instanceof JVMLocalVariableInstruction) {
547 type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
548 } else if (inst instanceof JVMFieldInstruction){
549 fi = ((JVMFieldInstruction) inst).getFieldInfo();
553 if (inst instanceof JVMArrayElementInstruction) {
554 return (getTypeFromInstruction(inst));
558 return (Types.T_VOID);
561 return (decodeType(type));
564 private final static byte getTypeFromInstruction(Instruction inst) {
565 if (inst instanceof JVMArrayElementInstruction)
566 return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
568 return(Types.T_VOID);
571 private final static byte decodeType(String type) {
572 if (type.charAt(0) == '?'){
573 return(Types.T_REFERENCE);
575 return Types.getBuiltinType(type);
579 // Find the variable writer
580 // It should be one of the apps listed in the .jpf file
581 private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
582 // Start looking from the top of the stack backward
583 for(int i=sfList.size()-1; i>=0; i--) {
584 MethodInfo mi = sfList.get(i).getMethodInfo();
585 if(!mi.isJPFInternal()) {
586 String method = mi.getStackTraceName();
587 // Check against the writers in the writerSet
588 for(String writer : writerSet) {
589 if (method.contains(writer)) {
599 private void writeWriterAndValue(String writer, String attribute, String value) {
600 Update u = new Update(writer, "DEVICE", attribute, value, manual);
605 public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
607 if (System.currentTimeMillis() - startTime > timeout) {
608 StringBuilder sbTimeOut = new StringBuilder();
609 sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
610 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
611 ti.setNextPC(nextIns);
617 StringBuilder sb = new StringBuilder();
618 sb.append(errorMessage);
619 Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
620 ti.setNextPC(nextIns);
623 if (executedInsn instanceof WriteInstruction) {
624 String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
625 // Check if we have an update to isManualTransaction to update manual field
626 if (varId.contains("isManualTransaction")) {
627 byte type = getType(ti, executedInsn);
628 String value = getValue(ti, executedInsn, type);
629 System.out.println();
630 manual = (value.equals("true"))?true:false;
632 for (String var : conflictSet) {
633 if (varId.contains(var)) {
635 byte type = getType(ti, executedInsn);
636 String value = getValue(ti, executedInsn, type);
637 String writer = getWriter(ti.getStack(), appSet);
639 // Just return if the writer is not one of the listed apps in the .jpf file
643 // Update the current updates
644 writeWriterAndValue(writer, var, value);