Adding manual transactions to the conflict tracker
[jpf-core.git] / src / main / gov / nasa / jpf / listener / ConflictTracker.java
1 /*
2  * Copyright (C) 2014, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
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
9  * 
10  *        http://www.apache.org/licenses/LICENSE-2.0. 
11  *
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.
17  */
18 package gov.nasa.jpf.listener;
19
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
31 import java.io.PrintWriter;
32
33 import java.util.*;
34
35 /**
36  * Listener using data flow analysis to find conflicts between smartApps.
37  **/
38
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>();
47   private long timeout;
48   private long startTime;
49   private Node parentNode = new Node(-2);
50   private String operation;
51   private String detail;
52   private String errorMessage;
53   private int depth;
54   private int id;
55   private boolean manual = false;
56   private boolean conflictFound = false;
57
58   private final String SET_LOCATION_METHOD = "setLocationMode";
59   private final String LOCATION_VAR = "locationMode";
60
61   public ConflictTracker(Config config, JPF jpf) {
62     out = new PrintWriter(System.out, true);
63
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) {
68         conflictSet.add(var);
69       }
70     }
71     String[] apps = config.getStringArray("apps");
72     // We are not tracking anything if it is null
73     if (apps != null) {
74       for (String var : apps) {
75         appSet.add(var);
76       }
77     }
78
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();
82   }
83
84   void propagateChange(Edge newEdge) {
85     HashSet<Edge> changed = new HashSet<Edge>();
86
87     // Add the current node to the changed set
88     changed.add(newEdge);
89
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);
94
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()) {
99           changed.add(e);
100         }
101       }
102     }
103   }
104
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;
111     
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;
117
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);
124       }
125
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);
133           }
134         }
135       }
136       lastupdate.put(io, u);
137     }
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>());
144
145         changed |= dstUpdates.get(io).addAll(srcUpdates.get(io));
146       }
147     }
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>());
152       
153       changed |= dstUpdates.get(io).add(lastupdate.get(io));
154     }
155     return changed;
156   }
157
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()));
165   }
166   
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);        
174     return message;
175   }
176
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))
180       return null;
181
182     //Create edge
183     Edge e = new Edge(parent, current, transition, currUpdates);
184     parent.addOutEdge(e);
185
186     //Mark transition as explored
187     transitions.add(transition);
188     return e;
189   }
190
191   static class Node {
192     Integer id;
193     Vector<Edge> outEdges = new Vector<Edge>();
194     HashMap<IndexObject, HashSet<Update>> lastUpdates = new HashMap<IndexObject,  HashSet<Update>>();
195     
196     Node(Integer id) {
197       this.id = id;
198     }
199
200     Integer getId() {
201       return id;
202     }
203
204     Vector<Edge> getOutEdges() {
205       return outEdges;
206     }
207
208     void addOutEdge(Edge e) {
209       outEdges.add(e);
210     }
211     
212     HashMap<IndexObject, HashSet<Update>> getLastUpdates() {
213       return lastUpdates;
214     }
215   }
216
217   //Each Edge corresponds to a transition
218   static class Edge {
219     Node source, destination;
220     Transition transition;
221     ArrayList<Update> updates = new ArrayList<Update>();
222     
223     Edge(Node src, Node dst, Transition t, ArrayList<Update> _updates) {
224       this.source = src;
225       this.destination = dst;
226       this.transition = t;
227       this.updates.addAll(_updates);
228     }
229
230     Node getSrc() {
231       return source;
232     }
233
234     Node getDst() {
235       return destination;
236     }
237
238     Transition getTransition() {
239       return transition;
240     }
241
242     ArrayList<Update> getUpdates() {
243       return updates;
244     }
245   }
246
247   static class Update {
248     String appName;
249     String deviceId;
250     String attribute;
251     String value;
252     boolean ismanual;
253     
254     Update(String _appName, String _deviceId, String _attribute, String _value, boolean _ismanual) {
255       this.appName = _appName;
256       this.deviceId = _deviceId;
257       this.attribute = _attribute;
258       this.value = _value;
259       this.ismanual = _ismanual;
260     }
261
262     boolean isManual() {
263       return ismanual;
264     }
265     
266     String getApp() {
267       return appName;
268     }
269
270     String getDeviceId() {
271       return deviceId;
272     }
273
274     String getAttribute() {
275       return attribute;
276     }
277     
278     String getValue() {
279       return value;
280     }
281
282     //Gets an index object for indexing updates by just device and attribute
283     IndexObject getIndex() {
284       return new IndexObject(this);
285     }
286
287     public boolean equals(Object o) {
288       if (!(o instanceof Update))
289         return false;
290       Update u=(Update)o;
291       return (getDeviceId().equals(u.getDeviceId()) &&
292               getAttribute().equals(u.getAttribute()) &&
293               getApp().equals(u.getApp()) &&
294               getValue().equals(u.getValue()));
295     }
296
297     public int hashCode() {
298       return (getDeviceId().hashCode() << 3) ^
299         (getAttribute().hashCode() << 2) ^
300         (getApp().hashCode() << 1) ^
301         getValue().hashCode();
302     }
303   }
304
305   static class IndexObject {
306     Update u;
307     IndexObject(Update _u) {
308       this.u = _u;
309     }
310     
311     public boolean equals(Object o) {
312       if (!(o instanceof IndexObject))
313         return false;
314       IndexObject io=(IndexObject)o;
315       return (u.getDeviceId().equals(io.u.getDeviceId()) &&
316               u.getAttribute().equals(io.u.getAttribute()));
317     }
318     public int hashCode() {
319       return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
320     }
321   }
322   
323   @Override
324   public void stateRestored(Search search) {
325     id = search.getStateId();
326     depth = search.getDepth();
327     operation = "restored";
328     detail = null;
329
330     out.println("The state is restored to state with id: "+id+", depth: "+depth);
331   
332     // Update the parent node
333     parentNode = getNode(id);
334   }
335
336   @Override
337   public void searchStarted(Search search) {
338     out.println("----------------------------------- search started");
339   }
340
341   private Node getNode(Integer id) {
342     if (!nodes.containsKey(id))
343       nodes.put(id, new Node(id));
344     return nodes.get(id);
345   }
346
347   @Override
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";
354
355     // Add the node to the list of nodes
356     Node currentNode = getNode(id);
357
358     // Create an edge based on the current transition
359     Edge newEdge = createEdge(parentNode, currentNode, transition);
360
361     // Reset the temporary variables and flags
362     currUpdates.clear();
363     manual = false;
364
365     // If we have a new Edge, check for conflicts
366     if (newEdge != null)
367       propagateChange(newEdge);
368
369     if (search.isNewState()) {
370       detail = "new";
371     } else {
372       detail = "visited";
373     }
374
375     if (search.isEndState()) {
376       out.println("This is the last state!");
377       theEnd = "end";
378     }
379
380     out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
381     
382     // Update the parent node
383     parentNode = currentNode;
384   }
385
386   @Override
387   public void stateBacktracked(Search search) {
388     id = search.getStateId();
389     depth = search.getDepth();
390     operation = "backtrack";
391     detail = null;
392
393     out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
394
395     // Update the parent node
396     parentNode = getNode(id);
397   }
398
399   @Override
400   public void searchFinished(Search search) {
401     out.println("----------------------------------- search finished");
402   }
403
404   private String getValue(ThreadInfo ti, Instruction inst, byte type) {
405     StackFrame frame;
406     int lo, hi;
407
408     frame = ti.getTopFrame();
409
410     if ((inst instanceof JVMLocalVariableInstruction) ||
411         (inst instanceof JVMFieldInstruction))
412     {
413       if (frame.getTopPos() < 0)
414         return(null);
415
416       lo = frame.peek();
417       hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
418         
419       return(decodeValue(type, lo, hi));
420     }
421
422     if (inst instanceof JVMArrayElementInstruction)
423       return(getArrayValue(ti, type));
424
425     return(null);
426   }
427
428   private final static String decodeValue(byte type, int lo, int hi) {
429     switch (type) {
430       case Types.T_ARRAY:   return(null);
431       case Types.T_VOID:    return(null);
432
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));
441
442       case Types.T_REFERENCE:
443         ElementInfo ei = VM.getVM().getHeap().get(lo);
444         if (ei == null)
445           return(null);
446
447         ClassInfo ci = ei.getClassInfo();
448         if (ci == null)
449           return(null);
450
451         if (ci.getName().equals("java.lang.String"))
452           return('"' + ei.asString() + '"');
453         
454         return(ei.toString());
455
456       default:
457         System.err.println("Unknown type: " + type);
458         return(null);
459      }
460   }
461
462   private String getArrayValue(ThreadInfo ti, byte type) {
463     StackFrame frame;
464     int lo, hi;
465
466     frame = ti.getTopFrame();
467     lo    = frame.peek();
468     hi    = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
469
470     return(decodeValue(type, lo, hi));
471   }
472
473   private byte getType(ThreadInfo ti, Instruction inst) {
474     StackFrame frame;
475     FieldInfo fi;
476     String type;
477
478     frame = ti.getTopFrame();
479     if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
480       return (Types.T_REFERENCE);
481     }
482
483     type = null;
484
485     if (inst instanceof JVMLocalVariableInstruction) {
486       type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
487     } else if (inst instanceof JVMFieldInstruction){
488       fi = ((JVMFieldInstruction) inst).getFieldInfo();
489       type = fi.getType();
490     }
491
492     if (inst instanceof JVMArrayElementInstruction) {
493       return (getTypeFromInstruction(inst));
494     }
495
496     if (type == null) {
497       return (Types.T_VOID);
498     }
499
500     return (decodeType(type));
501   }
502
503   private final static byte getTypeFromInstruction(Instruction inst) {
504     if (inst instanceof JVMArrayElementInstruction)
505       return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
506
507     return(Types.T_VOID);
508   }
509
510   private final static byte decodeType(String type) {
511     if (type.charAt(0) == '?'){
512       return(Types.T_REFERENCE);
513     } else {
514       return Types.getBuiltinType(type);
515     }
516   }
517
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)) {
529             return writer;
530           }
531         }
532       }
533     }
534
535     return null;
536   }
537
538   private void writeWriterAndValue(String writer, String attribute, String value) {
539     Update u = new Update(writer, "DEVICE", attribute, value, manual);
540     currUpdates.add(u);
541   }
542
543   @Override
544   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
545     if (timeout > 0) {
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);
551       }
552     }
553     
554     if (conflictFound) {
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);
566         
567         // Extract the writer app name
568         ClassInfo ci = mi.getClassInfo();
569         String writer = ci.getName();
570         
571         // Update the temporary Set set.
572         writeWriterAndValue(writer, LOCATION_VAR, value);
573       }
574     } else {
575       if (executedInsn instanceof WriteInstruction) {
576         String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
577          
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);
582             
583                 manual = (value.equals("true"))?true:false;
584         }
585  
586         for (String var : conflictSet) {
587           if (varId.contains(var)) {
588             // Get variable info
589             byte type = getType(ti, executedInsn);
590             String value = getValue(ti, executedInsn, type);
591             String writer = getWriter(ti.getStack(), appSet);
592
593             // Just return if the writer is not one of the listed apps in the .jpf file
594             if (writer == null)
595               return;
596             
597             // Update the current updates
598             writeWriterAndValue(writer, var, value);
599           }
600         }
601       }
602     }
603   }
604 }