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