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