Adding a condition to not check for timeout when it is 0.
[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
152       VarChange change = new VarChange(writer, value);
153       writeMap.put(var, change);
154     }
155   }
156
157   class VarChange {
158     String writer;
159     String value;
160     
161     VarChange(String writer, String value) {
162       this.writer = writer;
163       this.value = value;
164     }
165   }
166
167   // Find the variable writer
168   // It should be one of the apps listed in the .jpf file
169   private String getWriter(List<StackFrame> sfList) {
170     // Start looking from the top of the stack backward
171     for(int i=sfList.size()-1; i>=0; i--) {
172       MethodInfo mi = sfList.get(i).getMethodInfo();
173       if(!mi.isJPFInternal()) {
174         String method = mi.getStackTraceName();
175         // Check against the apps in the appSet
176         for(String app : appSet) {
177           // There is only one writer at a time but we need to always
178           // check all the potential writers in the list
179           if (method.contains(app)) {
180             return app;
181           }
182         }
183       }
184     }
185
186     return null;
187   }
188
189   private byte getType(ThreadInfo ti, Instruction inst) {
190     StackFrame frame;
191     FieldInfo fi;
192     String type;
193
194     frame = ti.getTopFrame();
195     if ((frame.getTopPos() >= 0) && (frame.isOperandRef())) {
196       return (Types.T_REFERENCE);
197     }
198
199     type = null;
200
201     if (inst instanceof JVMLocalVariableInstruction) {
202       type = ((JVMLocalVariableInstruction) inst).getLocalVariableType();
203     } else if (inst instanceof JVMFieldInstruction){
204       fi = ((JVMFieldInstruction) inst).getFieldInfo();
205       type = fi.getType();
206     }
207
208     if (inst instanceof JVMArrayElementInstruction) {
209       return (getTypeFromInstruction(inst));
210     }
211
212     if (type == null) {
213       return (Types.T_VOID);
214     }
215
216     return (decodeType(type));
217   }
218
219   private final static byte getTypeFromInstruction(Instruction inst) {
220     if (inst instanceof JVMArrayElementInstruction)
221       return(getTypeFromInstruction((JVMArrayElementInstruction) inst));
222
223     return(Types.T_VOID);
224   }
225
226   private final static byte getTypeFromInstruction(JVMArrayElementInstruction inst) {
227     String name;
228
229     name = inst.getClass().getName();
230     name = name.substring(name.lastIndexOf('.') + 1);
231
232     switch (name.charAt(0)) {
233       case 'A': return(Types.T_REFERENCE);
234       case 'B': return(Types.T_BYTE);      // Could be a boolean but it is better to assume a byte.
235       case 'C': return(Types.T_CHAR);
236       case 'F': return(Types.T_FLOAT);
237       case 'I': return(Types.T_INT);
238       case 'S': return(Types.T_SHORT);
239       case 'D': return(Types.T_DOUBLE);
240       case 'L': return(Types.T_LONG);
241     }
242
243     return(Types.T_VOID);
244   }
245
246   private final static String encodeType(byte type) {
247     switch (type) {
248       case Types.T_BYTE:    return("B");
249       case Types.T_CHAR:    return("C");
250       case Types.T_DOUBLE:  return("D");
251       case Types.T_FLOAT:   return("F");
252       case Types.T_INT:     return("I");
253       case Types.T_LONG:    return("J");
254       case Types.T_REFERENCE:  return("L");
255       case Types.T_SHORT:   return("S");
256       case Types.T_VOID:    return("V");
257       case Types.T_BOOLEAN: return("Z");
258       case Types.T_ARRAY:   return("[");
259     }
260
261     return("?");
262   }
263
264   private final static byte decodeType(String type) {
265     if (type.charAt(0) == '?'){
266       return(Types.T_REFERENCE);
267     } else {
268       return Types.getBuiltinType(type);
269     }
270   }
271
272   private String getName(ThreadInfo ti, Instruction inst, byte type) {
273     String name;
274     int index;
275     boolean store;
276
277     if ((inst instanceof JVMLocalVariableInstruction) ||
278             (inst instanceof JVMFieldInstruction)) {
279       name = ((LocalVariableInstruction) inst).getVariableId();
280       name = name.substring(name.lastIndexOf('.') + 1);
281
282       return(name);
283     }
284
285     if (inst instanceof JVMArrayElementInstruction) {
286       store  = inst instanceof StoreInstruction;
287       name   = getArrayName(ti, type, store);
288       index  = getArrayIndex(ti, type, store);
289       return(name + '[' + index + ']');
290     }
291
292     return(null);
293   }
294
295   private String getValue(ThreadInfo ti, Instruction inst, byte type) {
296     StackFrame frame;
297     int lo, hi;
298
299     frame = ti.getTopFrame();
300
301     if ((inst instanceof JVMLocalVariableInstruction) ||
302         (inst instanceof JVMFieldInstruction))
303     {
304        if (frame.getTopPos() < 0)
305          return(null);
306
307        lo = frame.peek();
308        hi = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
309
310        return(decodeValue(type, lo, hi));
311     }
312
313     if (inst instanceof JVMArrayElementInstruction)
314       return(getArrayValue(ti, type));
315
316     return(null);
317   }
318
319   private String getArrayName(ThreadInfo ti, byte type, boolean store) {
320     String attr;
321     int offset;
322
323     offset = calcOffset(type, store) + 1;
324     // <2do> String is really not a good attribute type to retrieve!
325     StackFrame frame = ti.getTopFrame();
326     attr   = frame.getOperandAttr( offset, String.class);
327
328     if (attr != null) {
329       return(attr);
330     }
331
332     return("?");
333   }
334
335   private int getArrayIndex(ThreadInfo ti, byte type, boolean store) {
336     int offset;
337
338     offset = calcOffset(type, store);
339
340     return(ti.getTopFrame().peek(offset));
341   }
342
343   private final static int calcOffset(byte type, boolean store) {
344     if (!store)
345       return(0);
346
347     return(Types.getTypeSize(type));
348   }
349
350   private String getArrayValue(ThreadInfo ti, byte type) {
351     StackFrame frame;
352     int lo, hi;
353
354     frame = ti.getTopFrame();
355     lo    = frame.peek();
356     hi    = frame.getTopPos() >= 1 ? frame.peek(1) : 0;
357
358     return(decodeValue(type, lo, hi));
359   }
360
361   private final static String decodeValue(byte type, int lo, int hi) {
362     switch (type) {
363       case Types.T_ARRAY:   return(null);
364       case Types.T_VOID:    return(null);
365
366       case Types.T_BOOLEAN: return(String.valueOf(Types.intToBoolean(lo)));
367       case Types.T_BYTE:    return(String.valueOf(lo));
368       case Types.T_CHAR:    return(String.valueOf((char) lo));
369       case Types.T_DOUBLE:  return(String.valueOf(Types.intsToDouble(lo, hi)));
370       case Types.T_FLOAT:   return(String.valueOf(Types.intToFloat(lo)));
371       case Types.T_INT:     return(String.valueOf(lo));
372       case Types.T_LONG:    return(String.valueOf(Types.intsToLong(lo, hi)));
373       case Types.T_SHORT:   return(String.valueOf(lo));
374
375       case Types.T_REFERENCE:
376         ElementInfo ei = VM.getVM().getHeap().get(lo);
377         if (ei == null)
378           return(null);
379
380         ClassInfo ci = ei.getClassInfo();
381         if (ci == null)
382           return(null);
383
384         if (ci.getName().equals("java.lang.String"))
385           return('"' + ei.asString() + '"');
386
387         return(ei.toString());
388
389       default:
390         System.err.println("Unknown type: " + type);
391         return(null);
392      }
393   }
394 }