51e34fc89f0c9a50b64244968c813f7ca1516d21
[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
41   private final PrintWriter out;
42   private final HashSet<String> conflictSet = new HashSet<String>(); // Variables we want to track
43   private final HashSet<String> appSet = new HashSet<String>(); // Apps we want to find their conflicts
44   private final HashSet<String> manualSet = new HashSet<String>(); // Writer classes with manual inputs to detect direct-direct(No Conflict) interactions
45   private final HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(); // Nodes of a graph
46   private HashSet<NameValuePair> tempSetSet = new HashSet<NameValuePair>();
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 conflictFound = false;
56   private boolean isSet = false;
57   private boolean manual = false;
58  
59   
60   public ConflictTracker(Config config, JPF jpf) {
61     out = new PrintWriter(System.out, true);
62
63     String[] conflictVars = config.getStringArray("variables");
64     // We are not tracking anything if it is null
65     if (conflictVars != null) {
66       for (String var : conflictVars) {
67         conflictSet.add(var);
68       }
69     }
70     String[] apps = config.getStringArray("apps");
71     // We are not tracking anything if it is null
72     if (apps != null) {
73       for (String var : apps) {
74         appSet.add(var);
75       }
76     }
77     String[] manualClasses = config.getStringArray("manualClasses");
78     // We are not tracking anything if it is null
79     if (manualClasses != null) {
80       for (String var : manualClasses) {
81         manualSet.add(var);
82       }
83     }
84
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();
88   }
89
90   boolean propagateTheChange(Node currentNode) {
91         HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
92
93         while(!changed.isEmpty()) {
94                 // Get the first element of HashSet and remove it from the changed set
95                 Node nodeToProcess = changed.iterator().next();
96                 changed.remove(nodeToProcess);
97                         
98                 // Update the sets, store the outSet to temp before its changes
99                 boolean isChanged = updateSets(nodeToProcess);
100
101                 // Check for a conflict
102                 if (checkForConflict(nodeToProcess))
103                         return true;
104                         
105                 // Checking if the out set has changed or not(Add its successors to the change list!)
106                 if (isChanged) {
107                         for (Node i : nodeToProcess.getSuccessors()) {
108                                 if (!changed.contains(i))
109                                         changed.add(i);
110                         }
111                 }
112         }
113
114         return false;
115   }
116
117   boolean setOutSet(Node currentNode) {
118         Integer prevSize = currentNode.getOutSet().size();
119
120         // Update based on setSet
121         for (NameValuePair i : currentNode.getSetSet()) {
122                 if (currentNode.getOutSet().contains(i))
123                         currentNode.getOutSet().remove(i);      
124                 currentNode.getOutSet().add(i);
125         }
126
127         // Add all the inSet
128         currentNode.getOutSet().addAll(currentNode.getInSet());
129
130         // Check if the outSet is changed
131         if (!prevSize.equals(currentNode.getOutSet().size()))
132                 return true;
133         
134         return false;
135   }
136
137   void setInSet(Node currentNode) {
138         for (Node i : currentNode.getPredecessors()) {
139                 currentNode.getInSet().addAll(i.getOutSet());
140         }
141   }
142
143   boolean checkForConflict(Node currentNode) {
144         HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
145         HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
146
147         for (NameValuePair i : currentNode.getSetSet()) {
148                 if (i.getIsManual()) // Manual input: we have no conflict
149                         continue;
150
151                 valueMap.put(i.getVarName(), i.getValue());
152                 if (writerMap.containsKey(i.getVarName()))
153                         writerMap.put(i.getVarName(), i.getAppNum()+writerMap.get(i.getVarName())); // We have two writers?
154                 else
155                         writerMap.put(i.getVarName(), i.getAppNum());
156         }
157
158         // Comparing the inSet and setSet to find the conflict
159         for (NameValuePair i : currentNode.getInSet()) {
160                 if (valueMap.containsKey(i.getVarName())) {
161                         String value = valueMap.get(i.getVarName());
162                         Integer writer = writerMap.get(i.getVarName());
163                         if ((value != null)&&(writer != null)) {
164                                 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
165                                         errorMessage = "Conflict found between the two apps. App"+i.getAppNum()+" has written the value: "+i.getValue()+
166                                                         " to the variable: "+i.getVarName()+" while App"+writerMap.get(i.getVarName())+" is overwriting the value: "
167                                                         +valueMap.get(i.getVarName())+" to the same variable!";
168                                         return true;
169                                 }
170                         }
171                 }
172         }
173
174         return false;
175   }
176
177   boolean updateSets(Node currentNode) {
178         // Set input set according to output set of pred states of current state
179         setInSet(currentNode);
180
181         // Set outSet according to inSet, and setSet of current node, check if there is a change
182         return setOutSet(currentNode);
183   }
184
185   static class Node {
186         Integer id;
187         HashSet<Node> predecessors = new HashSet<Node>();
188         HashSet<Node> successors = new HashSet<Node>();
189         HashSet<NameValuePair> inSet = new HashSet<NameValuePair>();
190         HashSet<NameValuePair> setSet = new HashSet<NameValuePair>();
191         HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
192
193         Node(Integer id) {
194                 this.id = id;
195         }
196
197         void addPredecessor(Node node) {
198                 predecessors.add(node);
199         }
200
201         void addSuccessor(Node node) {
202                 successors.add(node);
203         }
204
205         void setSetSet(HashSet<NameValuePair> setSet, boolean isManual) {
206                 if (isManual)
207                         this.setSet = new HashSet<NameValuePair>();
208                 for (NameValuePair i : setSet) {
209                         this.setSet.add(new NameValuePair(i.getAppNum(), i.getValue(), i.getVarName(), i.getIsManual()));
210                 }
211         }
212
213         Integer getId() {
214                 return id;
215         }
216
217         HashSet<Node> getPredecessors() {
218                 return predecessors;
219         }
220
221         HashSet<Node> getSuccessors() {
222                 return successors;
223         }
224
225         HashSet<NameValuePair> getInSet() {
226                 return inSet;
227         }
228
229         HashSet<NameValuePair> getSetSet() {
230                 return setSet;
231         }
232
233         HashSet<NameValuePair> getOutSet() {
234                 return outSet;
235         }
236   }
237
238   static class NameValuePair {
239         Integer appNum;
240         String value;
241         String varName;
242         boolean isManual;
243
244         NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
245                 this.appNum = appNum;
246                 this.value = value;
247                 this.varName = varName;
248                 this.isManual = isManual;
249         }
250
251         void setAppNum(Integer appNum) {
252                 this.appNum = appNum;
253         }
254
255         void setValue(String value) {
256                 this.value = value;
257         }
258
259         void setVarName(String varName) {
260                 this.varName = varName;
261         }
262
263         void setIsManual(String varName) {
264                 this.isManual = isManual;
265         }
266
267         Integer getAppNum() {
268                 return appNum;
269         }
270
271         String getValue() {
272                 return value;
273         }
274
275         String getVarName() {
276                 return varName;
277         }
278
279         boolean getIsManual() {
280                 return isManual;
281         }
282
283         @Override
284         public boolean equals(Object o) {
285                 if (o instanceof NameValuePair) {
286                         NameValuePair other = (NameValuePair) o;
287                         if (varName.equals(other.getVarName()))
288                                 return appNum.equals(other.getAppNum());
289                 }
290                 return false;
291         }
292
293         @Override
294         public int hashCode() {
295                 return appNum.hashCode() * 31 + varName.hashCode();
296         }
297   }
298
299   @Override
300   public void stateRestored(Search search) {
301     id = search.getStateId();
302     depth = search.getDepth();
303     operation = "restored";
304     detail = null;
305
306     out.println("The state is restored to state with id: "+id+", depth: "+depth);
307   
308     // Update the parent node
309     if (nodes.containsKey(id)) {
310         parentNode = nodes.get(id);
311     } else {
312         parentNode = new Node(id);
313     }
314   }
315
316   @Override
317   public void searchStarted(Search search) {
318     out.println("----------------------------------- search started");
319   }
320  
321
322   @Override
323   public void stateAdvanced(Search search) {
324     String theEnd = null;
325     id = search.getStateId();
326     depth = search.getDepth();
327     operation = "forward";
328
329     // Add the node to the list of nodes        
330     nodes.put(id, new Node(id));
331     Node currentNode = nodes.get(id);
332
333     // Update the setSet for this new node
334     if (isSet) {
335       currentNode.setSetSet(tempSetSet, manual);
336       tempSetSet = new HashSet<NameValuePair>(); 
337       isSet = false;
338       manual = false;
339     }
340
341     if (search.isNewState()) {
342       detail = "new";
343     } else {
344       detail = "visited";
345     }
346
347     if (search.isEndState()) {
348       out.println("This is the last state!");
349       theEnd = "end";
350     }
351
352     out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
353     
354     // Updating the predecessors for this node
355     // Check if parent node is already in successors of the current node or not
356     if (!(currentNode.getPredecessors().contains(parentNode)))
357         currentNode.addPredecessor(parentNode);
358
359     // Update the successors for this node
360     // Check if current node is already in successors of the parent node or not
361     if (!(parentNode.getSuccessors().contains(currentNode)))
362         parentNode.addSuccessor(currentNode);
363
364     // Update the sets, check if the outSet is changed or not
365     boolean isChanged = updateSets(currentNode);
366    
367     // Check for a conflict
368     conflictFound = checkForConflict(currentNode);
369
370     // Check if the outSet of this state has changed, update all of its successors' sets if any
371     if (isChanged)
372         conflictFound = conflictFound || propagateTheChange(currentNode);
373
374     // Update the parent node
375     if (nodes.containsKey(id)) {
376         parentNode = nodes.get(id);
377     } else {
378         parentNode = new Node(id);
379     }
380   }
381
382   @Override
383   public void stateBacktracked(Search search) {
384     id = search.getStateId();
385     depth = search.getDepth();
386     operation = "backtrack";
387     detail = null;
388
389     out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
390
391     // Update the parent node
392     if (nodes.containsKey(id)) {
393         parentNode = nodes.get(id);
394     } else {
395         parentNode = new Node(id);
396     }
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   @Override
539   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
540     // Instantiate timeoutTimer
541     if (timeout > 0) {
542       if (System.currentTimeMillis() - startTime > timeout) {
543         StringBuilder sbTimeOut = new StringBuilder();
544         sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
545         Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
546         ti.setNextPC(nextIns);
547       }
548     }
549
550     if (conflictFound) {
551       StringBuilder sb = new StringBuilder();
552       sb.append(errorMessage);
553       Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
554       ti.setNextPC(nextIns);
555     } else if (executedInsn instanceof WriteInstruction) {
556       String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
557       for(String var : conflictSet) {
558
559         if (varId.contains(var)) {
560           // Get variable info
561           byte type  = getType(ti, executedInsn);
562           String value = getValue(ti, executedInsn, type);
563           String writer = getWriter(ti.getStack(), appSet);
564           // Just return if the writer is not one of the listed apps in the .jpf file
565           if (writer == null)
566             return;
567
568           if (getWriter(ti.getStack(), manualSet) != null)
569                 manual = true;
570
571           // Update the temporary Set set.
572           if (writer.equals("App1"))
573                   tempSetSet.add(new NameValuePair(1, value, var, manual));
574           else if (writer.equals("App2"))
575                   tempSetSet.add(new NameValuePair(2, value, var, manual));
576           // Set isSet to true
577           isSet = true;
578                   
579        }
580      }
581
582       
583   }
584   
585  }
586
587 }