a0ecc4bb6721597ba8631d83deeb8929feb207f8
[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 ArrayList<NameValuePair> tempSetSet = new ArrayList<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 manual = 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     String[] manualClasses = config.getStringArray("manualClasses");
79     // We are not tracking anything if it is null
80     if (manualClasses != null) {
81       for (String var : manualClasses) {
82         manualSet.add(var);
83       }
84     }
85
86     // Timeout input from config is in minutes, so we need to convert into millis
87     timeout = config.getInt("timeout", 0) * 60 * 1000;
88     startTime = System.currentTimeMillis();
89   }
90
91   boolean propagateTheChange(Node currentNode) {
92         HashSet<Node> changed = new HashSet<Node>(currentNode.getSuccessors());
93
94         while(!changed.isEmpty()) {
95                 // Get the first element of HashSet and remove it from the changed set
96                 Node nodeToProcess = changed.iterator().next();
97                 changed.remove(nodeToProcess);
98
99                 // Update the edge
100                 boolean isChanged = updateEdge(currentNode, nodeToProcess);
101
102                 // Check for a conflict in this transition(currentNode -> nodeToProcess)
103                 if (checkForConflict(nodeToProcess))
104                         return true;
105
106                 // Checking if the out set has changed or not(Add its successors to the change list!)
107                 if (isChanged) {
108                         propagateTheChange(nodeToProcess);
109                 }
110       }
111
112       return false;
113   }
114
115   String createErrorMessage(NameValuePair pair, HashMap<String, String> valueMap, HashMap<String, Integer> writerMap) {
116         String message = "Conflict found between the two apps. App"+pair.getAppNum()+
117                          " has written the value: "+pair.getValue()+
118                          " to the variable: "+pair.getVarName()+" while App"+
119                          writerMap.get(pair.getVarName())+" is overwriting the value: "
120                          +valueMap.get(pair.getVarName())+" to the same variable!";
121         System.out.println(message);    
122         return message;
123   }
124
125   boolean checkForConflict(Node nodeToProcess) {
126         HashMap<String, String> valueMap = new HashMap<String, String>(); // HashMap from varName to value
127         HashMap<String, Integer> writerMap = new HashMap<String, Integer>(); // HashMap from varName to appNum
128
129         // Update the valueMap
130         for (int i = 0;i < nodeToProcess.getSetSet().size();i++) {
131                 NameValuePair nameValuePair = nodeToProcess.getSetSet().get(i);
132
133                 if (valueMap.containsKey(nameValuePair.getVarName())) {
134                         // Check if we have a same writer
135                         if (!writerMap.get(nameValuePair.getVarName()).equals(nameValuePair.getAppNum())) {
136                                 // Check if we have a conflict or not
137                                 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
138                                         errorMessage = createErrorMessage(nameValuePair, valueMap, writerMap);
139                                         return true;
140                                 } else { // We have two writers writing the same value
141                                         writerMap.put(nameValuePair.getVarName(), 3); // 3 represents both apps
142                                 }       
143                         } else {
144                                 // Check if we have more than one value with the same writer
145                                 if (!valueMap.get(nameValuePair.getVarName()).equals(nameValuePair.getValue())) {
146                                         valueMap.put(nameValuePair.getVarName(), "twoValue"); // We have one writer writing more than one value in a same event
147                                 }
148                         }       
149                 } else {
150                         valueMap.put(nameValuePair.getVarName(), nameValuePair.getValue());
151                         writerMap.put(nameValuePair.getVarName(), nameValuePair.getAppNum());
152                 }
153         }
154
155         // Comparing the outSet to setSet
156         for (NameValuePair i : nodeToProcess.getOutSet()) {
157                 if (valueMap.containsKey(i.getVarName())) {
158                         String value = valueMap.get(i.getVarName());
159                         Integer writer = writerMap.get(i.getVarName());
160                         if ((value != null)&&(writer != null)) {
161                                 if (!value.equals(i.getValue())&&!writer.equals(i.getAppNum())) { // We have different values
162                                         errorMessage = createErrorMessage(i, valueMap, writerMap);
163                                         return true;
164                                 }
165                         }
166                 }
167         }
168
169         return false;
170   }
171
172   boolean updateEdge(Node parentNode, Node currentNode) {
173         ArrayList<NameValuePair> setSet = currentNode.getSetSetMap().get(parentNode);
174         HashSet<String> updatedVarNames = new HashSet<String>();
175         HashMap<Integer, String> writerLastValue = new HashMap<Integer, String>();
176
177         boolean isChanged = false;
178         
179         if (setSet != null) {
180                 for (int i = 0;i < setSet.size();i++) {
181                         updatedVarNames.add(setSet.get(i).getVarName());
182                         writerLastValue.put(setSet.get(i).getAppNum(), setSet.get(i).getValue());
183                 }
184         }
185
186         for (NameValuePair i : parentNode.getOutSet()) {
187                 if (!updatedVarNames.contains(i.getVarName()))
188                         isChanged |= currentNode.getOutSet().add(i);
189         }
190
191         if (setSet != null) {
192                 for (int i = 0;i < setSet.size();i++) {
193                         if (setSet.get(i).getValue().equals(writerLastValue.get(setSet.get(i).getAppNum()))) {
194                                 isChanged |= currentNode.getOutSet().add(setSet.get(i));
195                         }
196                 }
197         }
198
199         return isChanged;
200   }
201
202   static class Node {
203         Integer id;
204         HashSet<Node> predecessors = new HashSet<Node>();
205         HashSet<Node> successors = new HashSet<Node>();
206         HashSet<NameValuePair> outSet = new HashSet<NameValuePair>();
207         ArrayList<NameValuePair> setSet = new ArrayList<NameValuePair>();
208         HashMap<Node, ArrayList<NameValuePair>> setSetMap = new HashMap<Node, ArrayList<NameValuePair>>();
209
210         Node(Integer id) {
211           this.id = id;
212         }
213
214         void addPredecessor(Node node) {
215           predecessors.add(node);
216         }
217
218         void addSuccessor(Node node) {
219           successors.add(node);
220         }
221
222         Integer getId() {
223                 return id;
224         }
225
226         HashSet<Node> getPredecessors() {
227                 return predecessors;
228         }
229
230         HashSet<Node> getSuccessors() {
231                 return successors;
232         }
233
234         HashSet<NameValuePair> getOutSet() {
235                 return outSet;
236         }
237
238         ArrayList<NameValuePair> getSetSet() {
239                 return setSet;
240         }
241
242         HashMap<Node, ArrayList<NameValuePair>> getSetSetMap() {
243                 return setSetMap;
244         }
245   }
246
247   static class NameValuePair {
248         Integer appNum;
249         String value;
250         String varName;
251         boolean isManual;
252
253         NameValuePair(Integer appNum, String value, String varName, boolean isManual) {
254                 this.appNum = appNum;
255                 this.value = value;
256                 this.varName = varName;
257                 this.isManual = isManual;
258         }
259
260         void setAppNum(Integer appNum) {
261                 this.appNum = appNum;
262         }
263
264         void setValue(String value) {
265                 this.value = value;
266         }
267
268         void setVarName(String varName) {
269                 this.varName = varName;
270         }
271
272         void setIsManual(String varName) {
273                 this.isManual = isManual;
274         }
275
276         Integer getAppNum() {
277                 return appNum;
278         }
279
280         String getValue() {
281                 return value;
282         }
283
284         String getVarName() {
285                 return varName;
286         }
287
288         boolean getIsManual() {
289                 return isManual;
290         }
291
292         @Override
293         public boolean equals(Object o) {
294       if (o instanceof NameValuePair) {
295         NameValuePair other = (NameValuePair) o;
296         if (varName.equals(other.getVarName()))
297           return appNum.equals(other.getAppNum());
298       }
299       return false;
300         }
301
302         @Override
303         public int hashCode() {
304                 return appNum.hashCode() * 31 + varName.hashCode();
305         }
306   }
307
308   @Override
309   public void stateRestored(Search search) {
310     id = search.getStateId();
311     depth = search.getDepth();
312     operation = "restored";
313     detail = null;
314
315     out.println("The state is restored to state with id: "+id+", depth: "+depth);
316   
317     // Update the parent node
318     if (nodes.containsKey(id)) {
319           parentNode = nodes.get(id);
320     } else {
321           parentNode = new Node(id);
322     }
323   }
324
325   @Override
326   public void searchStarted(Search search) {
327     out.println("----------------------------------- search started");
328   }
329  
330
331   @Override
332   public void stateAdvanced(Search search) {
333     String theEnd = null;
334     id = search.getStateId();
335     depth = search.getDepth();
336     operation = "forward";
337
338     // Add the node to the list of nodes
339     if (nodes.get(id) == null)
340         nodes.put(id, new Node(id));
341
342     Node currentNode = nodes.get(id);
343
344     if ((currentNode.getSetSetMap().get(parentNode) == null) || manual)
345         currentNode.getSetSetMap().put(parentNode, new ArrayList<NameValuePair>());
346
347     // Update the setSet for the edge
348     currentNode.getSetSetMap().get(parentNode).addAll(tempSetSet);
349     parentNode.getSetSet().addAll(tempSetSet);
350     tempSetSet = new ArrayList<NameValuePair>();
351     manual = false;
352
353     // Check for the conflict in this edge
354     conflictFound = checkForConflict(parentNode);
355
356     if (search.isNewState()) {
357       detail = "new";
358     } else {
359       detail = "visited";
360     }
361
362     if (search.isEndState()) {
363       out.println("This is the last state!");
364       theEnd = "end";
365     }
366
367     out.println("The state is forwarded to state with id: "+id+", depth: "+depth+" which is "+detail+" state: "+"% "+theEnd);
368     
369     // Updating the predecessors for this node
370     // Check if parent node is already in successors of the current node or not
371     if (!(currentNode.getPredecessors().contains(parentNode)))
372         currentNode.addPredecessor(parentNode);
373
374     // Update the successors for this node
375     // Check if current node is already in successors of the parent node or not
376     if (!(parentNode.getSuccessors().contains(currentNode)))
377         parentNode.addSuccessor(currentNode);
378
379     // Update the edge and check if the outset of the current node is changed or not to propagate the change
380     boolean isChanged = updateEdge(parentNode, currentNode);
381     
382     // Check if the outSet of this state has changed, update all of its successors' sets if any
383     if (isChanged)
384         conflictFound = conflictFound || propagateTheChange(currentNode);
385
386     // Update the parent node
387     if (nodes.containsKey(id)) {
388           parentNode = nodes.get(id);
389     } else {
390           parentNode = new Node(id);
391     }
392   }
393
394   @Override
395   public void stateBacktracked(Search search) {
396     id = search.getStateId();
397     depth = search.getDepth();
398     operation = "backtrack";
399     detail = null;
400
401     out.println("The state is backtracked to state with id: "+id+", depth: "+depth);
402
403     // Update the parent node
404     if (nodes.containsKey(id)) {
405           parentNode = nodes.get(id);
406     } else {
407           parentNode = new Node(id);
408     }
409   }
410
411   @Override
412   public void searchFinished(Search search) {
413     out.println("----------------------------------- search finished");
414   }
415
416   private String getValue(ThreadInfo ti, Instruction inst, byte type) {
417     StackFrame frame;
418     int lo, hi;
419
420     frame = ti.getTopFrame();
421
422     if ((inst instanceof JVMLocalVariableInstruction) ||
423         (inst instanceof JVMFieldInstruction))
424     {
425       if (frame.getTopPos() < 0)
426         return(null);
427
428       lo = frame.peek();
429       hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
430
431       return(decodeValue(type, lo, hi));
432     }
433
434     if (inst instanceof JVMArrayElementInstruction)
435       return(getArrayValue(ti, type));
436
437     return(null);
438   }
439
440   private final static String decodeValue(byte type, int lo, int hi) {
441     switch (type) {
442       case Types.T_ARRAY:   return(null);
443       case Types.T_VOID:    return(null);
444
445       case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
446       case Types.T_BYTE:    return(String.valueOf(lo));
447       case Types.T_CHAR:    return(String.valueOf((char) lo));
448       case Types.T_DOUBLE:  return(String.valueOf(Types.intsToDouble(lo, hi)));
449       case Types.T_FLOAT:   return(String.valueOf(Types.intToFloat(lo)));
450       case Types.T_INT:     return(String.valueOf(lo));
451       case Types.T_LONG:    return(String.valueOf(Types.intsToLong(lo, hi)));
452       case Types.T_SHORT:   return(String.valueOf(lo));
453
454       case Types.T_REFERENCE:
455         ElementInfo ei = VM.getVM().getHeap().get(lo);
456         if (ei == null)
457           return(null);
458
459         ClassInfo ci = ei.getClassInfo();
460         if (ci == null)
461           return(null);
462
463         if (ci.getName().equals("java.lang.String"))
464           return('"' + ei.asString() + '"');
465
466         return(ei.toString());
467
468       default:
469         System.err.println("Unknown type: " + type);
470         return(null);
471      }
472   }
473
474   private String getArrayValue(ThreadInfo ti, byte type) {
475     StackFrame frame;
476     int lo, hi;
477
478     frame = ti.getTopFrame();
479     lo    = frame.peek();
480     hi    = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
481
482     return(decodeValue(type, lo, hi));
483   }
484
485   private byte getType(ThreadInfo ti, Instruction inst) {
486     StackFrame frame;
487     FieldInfo fi;
488     String type;
489
490     frame = ti.getTopFrame();
491     if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
492       return (Types.T_REFERENCE);
493     }
494
495     type = null;
496
497     if (inst instanceof JVMLocalVariableInstruction) {
498       type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
499     } else if (inst instanceof JVMFieldInstruction){
500       fi = ((JVMFieldInstruction) inst).getFieldInfo();
501       type = fi.getType();
502     }
503
504     if (inst instanceof JVMArrayElementInstruction) {
505       return (getTypeFromInstruction(inst));
506     }
507
508     if (type == null) {
509       return (Types.T_VOID);
510     }
511
512     return (decodeType(type));
513   }
514
515   private final static byte getTypeFromInstruction(Instruction inst) {
516     if (inst instanceof JVMArrayElementInstruction)
517       return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
518
519     return(Types.T_VOID);
520   }
521
522   private final static byte decodeType(String type) {
523     if (type.charAt(0) == '?'){
524       return(Types.T_REFERENCE);
525     } else {
526       return Types.getBuiltinType(type);
527     }
528   }
529
530   // Find the variable writer
531   // It should be one of the apps listed in the .jpf file
532   private String getWriter(List<StackFrame> sfList, HashSet<String> writerSet) {
533     // Start looking from the top of the stack backward
534     for(int i=sfList.size()-1; i>=0; i--) {
535       MethodInfo mi = sfList.get(i).getMethodInfo();
536       if(!mi.isJPFInternal()) {
537         String method = mi.getStackTraceName();
538         // Check against the writers in the writerSet
539         for(String writer : writerSet) {
540           if (method.contains(writer)) {
541             return writer;
542           }
543         }
544       }
545     }
546
547     return null;
548   }
549
550   private void writeWriterAndValue(String writer, String value, String var) {
551     // Update the temporary Set set.
552     NameValuePair temp = new NameValuePair(1, value, var, manual);
553     if (writer.equals("App2"))
554         temp = new NameValuePair(2, value, var, manual);
555     
556     tempSetSet.add(temp);
557   }
558
559   @Override
560   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
561     if (timeout > 0) {
562       if (System.currentTimeMillis() - startTime > timeout) {
563         StringBuilder sbTimeOut = new StringBuilder();
564         sbTimeOut.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
565         Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sbTimeOut.toString());
566         ti.setNextPC(nextIns);
567       }
568     }
569
570     if (conflictFound) {
571       StringBuilder sb = new StringBuilder();
572       sb.append(errorMessage);
573       Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
574       ti.setNextPC(nextIns);
575     } else {
576       if (conflictSet.contains(LOCATION_VAR)) {
577         MethodInfo mi = executedInsn.getMethodInfo();
578         // Find the last load before return and get the value here
579         if (mi.getName().equals(SET_LOCATION_METHOD) &&
580                 executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
581           byte type  = getType(ti, executedInsn);
582           String value = getValue(ti, executedInsn, type);
583
584           // Extract the writer app name
585           ClassInfo ci = mi.getClassInfo();
586           String writer = ci.getName();
587
588           // Update the temporary Set set.
589           writeWriterAndValue(writer, value, LOCATION_VAR);
590         }
591       } else {
592         if (executedInsn instanceof WriteInstruction) {
593           String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
594
595           for (String var : conflictSet) {
596             if (varId.contains(var)) {
597               // Get variable info
598               byte type = getType(ti, executedInsn);
599               String value = getValue(ti, executedInsn, type);
600               String writer = getWriter(ti.getStack(), appSet);
601               // Just return if the writer is not one of the listed apps in the .jpf file
602               if (writer == null)
603                 return;
604
605               if (getWriter(ti.getStack(), manualSet) != null)
606                 manual = true;
607
608               // Update the temporary Set set.
609               writeWriterAndValue(writer, value, var);
610             }
611           }
612         }
613       }
614     }
615   }
616 }