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