Fix for a bug in finding the right integer values in the stack frame: need to find...
[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     public String toString() {
305       return "<"+getAttribute()+", "+getValue()+", "+getApp()+", "+ismanual+">";
306     }
307   }
308
309   static class IndexObject {
310     Update u;
311     IndexObject(Update _u) {
312       this.u = _u;
313     }
314     
315     public boolean equals(Object o) {
316       if (!(o instanceof IndexObject))
317         return false;
318       IndexObject io=(IndexObject)o;
319       return (u.getDeviceId().equals(io.u.getDeviceId()) &&
320               u.getAttribute().equals(io.u.getAttribute()));
321     }
322     public int hashCode() {
323       return (u.getDeviceId().hashCode() << 1) ^ u.getAttribute().hashCode();
324     }
325   }
326   
327   @Override
328   public void stateRestored(Search search) {
329     id = search.getStateId();
330     depth = search.getDepth();
331     operation = "restored";
332     detail = null;
333
334     out.println("The state is restored to state with id: "+id+", depth: "+depth);
335   
336     // Update the parent node
337     parentNode = getNode(id);
338   }
339
340   @Override
341   public void searchStarted(Search search) {
342     out.println("----------------------------------- search started");
343   }
344
345   private Node getNode(Integer id) {
346     if (!nodes.containsKey(id))
347       nodes.put(id, new Node(id));
348     return nodes.get(id);
349   }
350
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=\"");
356
357       for(IndexObject io:n.lastUpdates.keySet()) {
358         for(Update u:n.lastUpdates.get(io)) {
359           System.out.print(u.toString().replace("\"", "\\\"")+", ");
360         }
361       }
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("\"", "\\\"")+", ");
367         }
368         System.out.println("\"];");
369       }
370     }
371
372     System.out.println("}");
373   }
374   
375   @Override
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";
382
383     // Add the node to the list of nodes
384     Node currentNode = getNode(id);
385
386     // Create an edge based on the current transition
387     Edge newEdge = createEdge(parentNode, currentNode, transition);
388
389     // Reset the temporary variables and flags
390     currUpdates.clear();
391     manual = false;
392
393     // If we have a new Edge, check for conflicts
394     if (newEdge != null)
395       propagateChange(newEdge);
396
397     if (search.isNewState()) {
398       detail = "new";
399     } else {
400       detail = "visited";
401     }
402
403     if (search.isEndState()) {
404       out.println("This is the last state!");
405       theEnd = "end";
406     }
407
408     out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
409     
410     // Update the parent node
411     parentNode = currentNode;
412   }
413
414   @Override
415   public void stateBacktracked(Search search) {
416     id = search.getStateId();
417     depth = search.getDepth();
418     operation = "backtrack";
419     detail = null;
420
421     out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
422
423     // Update the parent node
424     parentNode = getNode(id);
425   }
426
427   @Override
428   public void searchFinished(Search search) {
429     out.println("----------------------------------- search finished");
430
431     //Comment out the following line to print the explored graph
432     printGraph();
433   }
434
435   private String getValue(ThreadInfo ti, Instruction inst, byte type) {
436     StackFrame frame;
437     int lo, hi;
438
439     frame = ti.getTopFrame();
440
441     if ((inst instanceof JVMLocalVariableInstruction) ||
442         (inst instanceof JVMFieldInstruction))
443     {
444       if (frame.getTopPos() < 0)
445         return(null);
446
447       lo = frame.peek();
448       hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
449
450       // TODO: Fix for integer values (need to dig deeper into the stack frame to find the right value other than 0)
451       // TODO: Seems to be a problem since this is Groovy (not Java)
452       if (type == Types.T_INT || type == Types.T_LONG || type == Types.T_SHORT) {
453         int offset = 0;
454         while (lo == 0) {
455           lo = frame.peek(offset);
456           offset++;
457         }
458       }
459
460       return(decodeValue(type, lo, hi));
461     }
462
463     if (inst instanceof JVMArrayElementInstruction)
464       return(getArrayValue(ti, type));
465
466     return(null);
467   }
468
469   private final static String decodeValue(byte type, int lo, int hi) {
470     switch (type) {
471       case Types.T_ARRAY:   return(null);
472       case Types.T_VOID:    return(null);
473
474       case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
475       case Types.T_BYTE:    return(String.valueOf(lo));
476       case Types.T_CHAR:    return(String.valueOf((char) lo));
477       case Types.T_DOUBLE:  return(String.valueOf(Types.intsToDouble(lo, hi)));
478       case Types.T_FLOAT:   return(String.valueOf(Types.intToFloat(lo)));
479       case Types.T_INT:     return(String.valueOf(lo));
480       case Types.T_LONG:    return(String.valueOf(Types.intsToLong(lo, hi)));
481       case Types.T_SHORT:   return(String.valueOf(lo));
482
483       case Types.T_REFERENCE:
484         ElementInfo ei = VM.getVM().getHeap().get(lo);
485         if (ei == null)
486           return(null);
487
488         ClassInfo ci = ei.getClassInfo();
489         if (ci == null)
490           return(null);
491
492         if (ci.getName().equals("java.lang.String"))
493           return('"' + ei.asString() + '"');
494         
495         return(ei.toString());
496
497       default:
498         System.err.println("Unknown type: " + type);
499         return(null);
500      }
501   }
502
503   private String getArrayValue(ThreadInfo ti, byte type) {
504     StackFrame frame;
505     int lo, hi;
506
507     frame = ti.getTopFrame();
508     lo    = frame.peek();
509     hi    = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
510
511     return(decodeValue(type, lo, hi));
512   }
513
514   private byte getType(ThreadInfo ti, Instruction inst) {
515     StackFrame frame;
516     FieldInfo fi;
517     String type;
518
519     frame = ti.getTopFrame();
520     if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
521       return (Types.T_REFERENCE);
522     }
523
524     type = null;
525
526     if (inst instanceof JVMLocalVariableInstruction) {
527       type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
528     } else if (inst instanceof JVMFieldInstruction){
529       fi = ((JVMFieldInstruction) inst).getFieldInfo();
530       type = fi.getType();
531     }
532
533     if (inst instanceof JVMArrayElementInstruction) {
534       return (getTypeFromInstruction(inst));
535     }
536
537     if (type == null) {
538       return (Types.T_VOID);
539     }
540
541     return (decodeType(type));
542   }
543
544   private final static byte getTypeFromInstruction(Instruction inst) {
545     if (inst instanceof JVMArrayElementInstruction)
546       return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
547
548     return(Types.T_VOID);
549   }
550
551   private final static byte decodeType(String type) {
552     if (type.charAt(0) == '?'){
553       return(Types.T_REFERENCE);
554     } else {
555       return Types.getBuiltinType(type);
556     }
557   }
558
559   // Find the variable writer
560   // It should be one of the apps listed in the .jpf file
561   private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
562     // Start looking from the top of the stack backward
563     for(int i=sfList.size()-1; i>=0; i--) {
564       MethodInfo mi = sfList.get(i).getMethodInfo();
565       if(!mi.isJPFInternal()) {
566         String method = mi.getStackTraceName();
567         // Check against the writers in the writerSet
568         for(String writer : writerSet) {
569           if (method.contains(writer)) {
570             return writer;
571           }
572         }
573       }
574     }
575
576     return null;
577   }
578
579   private void writeWriterAndValue(String writer, String attribute, String value) {
580     Update u = new Update(writer, "DEVICE", attribute, value, manual);
581     currUpdates.add(u);
582   }
583
584   @Override
585   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
586     if (timeout > 0) {
587       if (System.currentTimeMillis() - startTime > timeout) {
588         StringBuilder sbTimeOut = new StringBuilder();
589         sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
590         Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
591         ti.setNextPC(nextIns);
592       }
593     }
594     
595     if (conflictFound) {
596       StringBuilder sb = new StringBuilder();
597       sb.append(errorMessage);
598       Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
599       ti.setNextPC(nextIns);
600     } else if (conflictSet.contains(LOCATION_VAR)) {
601       MethodInfo mi = executedInsn.getMethodInfo();
602       // Find the last load before return and get the value here
603       if (mi.getName().equals(SET_LOCATION_METHOD) &&
604           executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
605         byte type  = getType(ti, executedInsn);
606         String value = getValue(ti, executedInsn, type);
607         
608         // Extract the writer app name
609         ClassInfo ci = mi.getClassInfo();
610         String writer = ci.getName();
611         
612         // Update the temporary Set set.
613         writeWriterAndValue(writer, LOCATION_VAR, value);
614       }
615     } else {
616       if (executedInsn instanceof WriteInstruction) {
617         String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
618          
619         // Check if we have an update to isManualTransaction to update manual field
620         if (varId.contains("isManualTransaction")) {
621                 byte type = getType(ti, executedInsn);
622                 String value = getValue(ti, executedInsn, type);
623             
624                 manual = (value.equals("true"))?true:false;
625         }
626  
627         for (String var : conflictSet) {
628           if (varId.contains(var)) {
629             // Get variable info
630             byte type = getType(ti, executedInsn);
631             String value = getValue(ti, executedInsn, type);
632             String writer = getWriter(ti.getStack(), appSet);
633
634             // Just return if the writer is not one of the listed apps in the .jpf file
635             if (writer == null)
636               return;
637             
638             // Update the current updates
639             writeWriterAndValue(writer, var, value);
640           }
641         }
642       }
643     }
644   }
645 }