Fixing a few bugs in the statistics printout.
[jpf-core.git] / src / main / gov / nasa / jpf / listener / VariableConflictTracker.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.ListenerAdapter;
22 import gov.nasa.jpf.jvm.bytecode.*;
23 import gov.nasa.jpf.vm.*;
24 import gov.nasa.jpf.vm.bytecode.LocalVariableInstruction;
25 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
26 import gov.nasa.jpf.vm.bytecode.StoreInstruction;
27 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
28
29 import java.util.*;
30
31 // TODO: Fix for Groovy's model-checking
32 // TODO: This is a listener created to detect device conflicts and global variable conflicts
33 /**
34  * Simple listener tool to track conflicts between 2 apps.
35  * A conflict is defined as one app trying to change the state of a variable
36  * into its opposite value after being set by the other app,
37  * e.g., app1 attempts to change variable A to false after A has been set by app2 to true earlier.
38  */
39 public class VariableConflictTracker extends ListenerAdapter {
40
41   private final HashMap<String, VarChange> writeMap = new HashMap<>();
42   private final HashMap<String, VarChange> readMap = new HashMap<>();
43   private final HashSet<String> conflictSet = new HashSet<>();
44   private final HashSet<String> appSet = new HashSet<>();
45   private boolean trackLocationVar;
46   private long timeout;
47   private long startTime;
48
49   private final String SET_LOCATION_METHOD = "setLocationMode";
50   private final String LOCATION_VAR = "location.mode";
51
52   public VariableConflictTracker(Config config) {
53     String[] conflictVars = config.getStringArray("variables");
54     // We are not tracking anything if it is null
55     if (conflictVars != null) {
56       for (String var : conflictVars) {
57         conflictSet.add(var);
58       }
59     }
60     String[] apps = config.getStringArray("apps");
61     // We are not tracking anything if it is null
62     if (apps != null) {
63       for (String var : apps) {
64         appSet.add(var);
65       }
66     }
67     trackLocationVar = config.getBoolean("track_location_var_conflict", false);
68     // Timeout input from config is in minutes, so we need to convert into millis
69     timeout = config.getInt("timeout", 0) * 60 * 1000;
70     startTime = System.currentTimeMillis();
71   }
72
73   @Override
74   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
75     // Instantiate timeoutTimer
76     if (timeout > 0) {
77       if (System.currentTimeMillis() - startTime > timeout) {
78         StringBuilder sb = new StringBuilder();
79         sb.append("Execution timeout: " + (timeout / (60 * 1000)) + " minutes have passed!");
80         Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
81         ti.setNextPC(nextIns);
82       }
83     }
84
85     // CASE #1: Detecting variable write-after-write conflict
86     if (executedInsn instanceof WriteInstruction) {
87       // Check for write-after-write conflict
88       String varId = ((WriteInstruction) executedInsn).getFieldInfo().getFullName();
89       for(String var : conflictSet) {
90
91         if (varId.contains(var)) {
92           // Get variable info
93           byte type  = getType(ti, executedInsn);
94           String value = getValue(ti, executedInsn, type);
95           //System.out.println("\n\n" + ti.getStackTrace() + "\n\n");
96           String writer = getWriter(ti.getStack());         
97           // Just return if the writer is not one of the listed apps in the .jpf file
98           if (writer == null)
99             return;
100
101           // Check and throw error if conflict is detected
102           checkWriteMapAndThrowError(var, value, writer, ti);
103         }
104       }
105     }
106
107     // CASE #2: Detecting global variable location.mode write-after-write conflict
108     if (trackLocationVar) {
109       MethodInfo mi = executedInsn.getMethodInfo();
110       // Find the last load before return and get the value here
111       if (mi.getName().equals(SET_LOCATION_METHOD) &&
112               executedInsn instanceof ALOAD && nextInsn instanceof ARETURN) {
113         byte type  = getType(ti, executedInsn);
114         String value = getValue(ti, executedInsn, type);
115
116         // Extract the writer app name
117         ClassInfo ci = mi.getClassInfo();
118         String writer = ci.getName();
119
120         // Check and throw error if conflict is detected
121         checkWriteMapAndThrowError(LOCATION_VAR, value, writer, ti);
122       }
123     }
124   }
125
126   private void checkWriteMapAndThrowError(String var, String value, String writer, ThreadInfo ti) {
127
128     if (writeMap.containsKey(var)) {
129       // Subsequent writes to the variable
130       VarChange current = writeMap.get(var);
131       if (current.writer != writer) {
132         // Conflict is declared when:
133         // 1) Current writer != previous writer, e.g., App1 vs. App2
134         // 2) Current value != previous value, e.g., "locked" vs. "unlocked"
135         if (!current.value.equals(value)) {
136
137           StringBuilder sb = new StringBuilder();
138           sb.append("Conflict between apps " + current.writer + " and " + writer + ": ");
139           sb.append(writer + " has attempted to write the value " + value + " into ");
140           sb.append("variable " + var + " that had already had the value " + current.value);
141           sb.append(" previously written by " + current.writer);
142           Instruction nextIns = ti.createAndThrowException("java.lang.RuntimeException", sb.toString());
143           ti.setNextPC(nextIns);
144         }
145       } else {
146         // No conflict is declared if this variable is written subsequently by the same writer
147         current.writer = writer;
148         current.value = value;
149       }
150     } else {
151       // First write to the variable only if it is not null
152                         if (value != null) {
153                                 VarChange change = new VarChange(writer, value);
154                                 writeMap.put(var, change);
155                         }
156     }
157   }
158
159   class VarChange {
160     String writer;
161     String value;
162     
163     VarChange(String writer, String value) {
164       this.writer = writer;
165       this.value = value;
166     }
167   }
168
169   // Find the variable writer
170   // It should be one of the apps listed in the .jpf file
171   private String getWriter(List<StackFrame> sfList) {
172     // Start looking from the top of the stack backward
173     for(int i=sfList.size()-1; i>=0; i--) {
174       MethodInfo mi = sfList.get(i).getMethodInfo();
175       if(!mi.isJPFInternal()) {
176         String method = mi.getStackTraceName();
177         // Check against the apps in the appSet
178         for(String app : appSet) {
179           // There is only one writer at a time but we need to always
180           // check all the potential writers in the list
181           if (method.contains(app)) {
182             return app;
183           }
184         }
185       }
186     }
187
188     return null;
189   }
190
191   private byte getType(ThreadInfo ti, Instruction inst) {
192     StackFrame frame;
193     FieldInfo fi;
194     String type;
195
196     frame = ti.getTopFrame();
197     if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
198       return (Types.T_REFERENCE);
199     }
200
201     type = null;
202
203     if (inst instanceof JVMLocalVariableInstruction) {
204       type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
205     } else if (inst instanceof JVMFieldInstruction){
206       fi = ((JVMFieldInstruction) inst).getFieldInfo();
207       type = fi.getType();
208     }
209
210     if (inst instanceof JVMArrayElementInstruction) {
211       return (getTypeFromInstruction(inst));
212     }
213
214     if (type == null) {
215       return (Types.T_VOID);
216     }
217
218     return (decodeType(type));
219   }
220
221   private final static byte getTypeFromInstruction(Instruction inst) {
222     if (inst instanceof JVMArrayElementInstruction)
223       return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
224
225     return(Types.T_VOID);
226   }
227
228   private final static byte getTypeFromInstruction(JVMArrayElementInstruction inst) {
229     String name;
230
231     name = inst.getClass().getName();
232     name = name.substring(name.lastIndexOf('.') + 1);
233
234     switch (name.charAt(0)) {
235       case 'A': return(Types.T_REFERENCE);
236       case 'B': return(Types.T_BYTE);      // Could be a boolean but it is better to assume a byte.
237       case 'C': return(Types.T_CHAR);
238       case 'F': return(Types.T_FLOAT);
239       case 'I': return(Types.T_INT);
240       case 'S': return(Types.T_SHORT);
241       case 'D': return(Types.T_DOUBLE);
242       case 'L': return(Types.T_LONG);
243     }
244
245     return(Types.T_VOID);
246   }
247
248   private final static String encodeType(byte type) {
249     switch (type) {
250       case Types.T_BYTE:    return("B");
251       case Types.T_CHAR:    return("C");
252       case Types.T_DOUBLE:  return("D");
253       case Types.T_FLOAT:   return("F");
254       case Types.T_INT:     return("I");
255       case Types.T_LONG:    return("J");
256       case Types.T_REFERENCE:  return("L");
257       case Types.T_SHORT:   return("S");
258       case Types.T_VOID:    return("V");
259       case Types.T_BOOLEAN: return("Z");
260       case Types.T_ARRAY:   return("[");
261     }
262
263     return("?");
264   }
265
266   private final static byte decodeType(String type) {
267     if (type.charAt(0) == '?'){
268       return(Types.T_REFERENCE);
269     } else {
270       return Types.getBuiltinType(type);
271     }
272   }
273
274   private String getName(ThreadInfo ti, Instruction inst, byte type) {
275     String name;
276     int index;
277     boolean store;
278
279     if ((inst instanceof JVMLocalVariableInstruction) ||
280             (inst instanceof JVMFieldInstruction)) {
281       name = ((LocalVariableInstruction) inst).getVariableId();
282       name = name.substring(name.lastIndexOf('.') + 1);
283
284       return(name);
285     }
286
287     if (inst instanceof JVMArrayElementInstruction) {
288       store  = inst instanceof StoreInstruction;
289       name   = getArrayName(ti, type, store);
290       index  = getArrayIndex(ti, type, store);
291       return(name + '[' + index + ']');
292     }
293
294     return(null);
295   }
296
297   private String getValue(ThreadInfo ti, Instruction inst, byte type) {
298     StackFrame frame;
299     int lo, hi;
300
301     frame = ti.getTopFrame();
302
303     if ((inst instanceof JVMLocalVariableInstruction) ||
304         (inst instanceof JVMFieldInstruction))
305     {
306        if (frame.getTopPos() < 0)
307          return(null);
308
309        lo = frame.peek();
310        hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
311
312        return(decodeValue(type, lo, hi));
313     }
314
315     if (inst instanceof JVMArrayElementInstruction)
316       return(getArrayValue(ti, type));
317
318     return(null);
319   }
320
321   private String getArrayName(ThreadInfo ti, byte type, boolean store) {
322     String attr;
323     int offset;
324
325     offset = calcOffset(type, store) + 1;
326     // <2do> String is really not a good attribute type to retrieve!
327     StackFrame frame = ti.getTopFrame();
328     attr   = frame.getOperandAttr( offset, String.class);
329
330     if (attr != null) {
331       return(attr);
332     }
333
334     return("?");
335   }
336
337   private int getArrayIndex(ThreadInfo ti, byte type, boolean store) {
338     int offset;
339
340     offset = calcOffset(type, store);
341
342     return(ti.getTopFrame().peek(offset));
343   }
344
345   private final static int calcOffset(byte type, boolean store) {
346     if (!store)
347       return(0);
348
349     return(Types.getTypeSize(type));
350   }
351
352   private String getArrayValue(ThreadInfo ti, byte type) {
353     StackFrame frame;
354     int lo, hi;
355
356     frame = ti.getTopFrame();
357     lo    = frame.peek();
358     hi    = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
359
360     return(decodeValue(type, lo, hi));
361   }
362
363   private final static String decodeValue(byte type, int lo, int hi) {
364     switch (type) {
365       case Types.T_ARRAY:   return(null);
366       case Types.T_VOID:    return(null);
367
368       case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
369       case Types.T_BYTE:    return(String.valueOf(lo));
370       case Types.T_CHAR:    return(String.valueOf((char) lo));
371       case Types.T_DOUBLE:  return(String.valueOf(Types.intsToDouble(lo, hi)));
372       case Types.T_FLOAT:   return(String.valueOf(Types.intToFloat(lo)));
373       case Types.T_INT:     return(String.valueOf(lo));
374       case Types.T_LONG:    return(String.valueOf(Types.intsToLong(lo, hi)));
375       case Types.T_SHORT:   return(String.valueOf(lo));
376
377       case Types.T_REFERENCE:
378         ElementInfo ei = VM.getVM().getHeap().get(lo);
379         if (ei == null)
380           return(null);
381
382         ClassInfo ci = ei.getClassInfo();
383         if (ci == null)
384           return(null);
385
386         if (ci.getName().equals("java.lang.String"))
387           return('"' + ei.asString() + '"');
388
389         return(ei.toString());
390
391       default:
392         System.err.println("Unknown type: " + type);
393         return(null);
394      }
395   }
396 }