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