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