4176f686ee88b4339c8080f64be06016dfa8dad2
[jpf-core.git] / src / main / gov / nasa / jpf / vm / MethodInfo.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.vm;
19
20 import gov.nasa.jpf.Config;
21 import gov.nasa.jpf.JPF;
22 import gov.nasa.jpf.JPFException;
23 import gov.nasa.jpf.util.JPFLogger;
24 import gov.nasa.jpf.util.LocationSpec;
25 import gov.nasa.jpf.vm.bytecode.ReturnInstruction;
26 import java.lang.reflect.Modifier;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.List;
30
31
32 /**
33  * information associated with a method. Each method in JPF
34  * is represented by a MethodInfo object
35  */
36 public class MethodInfo extends InfoObject implements GenericSignatureHolder  {
37
38   static JPFLogger logger = JPF.getLogger("gov.nasa.jpf.vm.MethodInfo");
39   
40   static final int INIT_MTH_SIZE = 4096;
41   protected static final ArrayList<MethodInfo> mthTable = new ArrayList<MethodInfo>(INIT_MTH_SIZE);
42   
43   // special globalIds
44   static final int DIRECT_CALL = -1;
45
46   static final LocalVarInfo[] EMPTY = new LocalVarInfo[0];
47   
48   static final int[] EMPTY_INT = new int[0];
49   
50   /**
51    * Used to warn about local variable information.
52    */
53   protected static boolean warnedLocalInfo = false;
54   
55   //--- various JPF method attributes
56   static final int  EXEC_ATOMIC = 0x10000; // method executed atomically
57   static final int  EXEC_HIDDEN = 0x20000; // method hidden from path
58   static final int  FIREWALL    = 0x40000; // firewall any unhandled exceptionHandlers
59                                            // (turn into UnhandledException throws)
60   static final int  IS_CLINIT   = 0x80000;
61   static final int  IS_INIT     = 0x100000;
62   
63   static final int  IS_REFLECTION = 0x200000; // this is a reflection direct call
64   static final int  IS_DIRECT_CALL = 0x400000;
65   
66   /** a unique int assigned to this method */
67   protected int globalId = -1;
68
69   /**
70    * this is a lazy evaluated mangled name consisting of the name and
71    * arg type signature
72    */
73   protected String uniqueName;
74
75   /** Name of the method */
76   protected String name;
77
78   /** Signature of the method */
79   protected String signature;
80
81   /** Generic signature of the method */
82   protected String genericSignature;
83
84   /** Class the method belongs to */
85   protected ClassInfo ci;
86
87   /** Instructions associated with the method */
88   protected Instruction[] code;
89
90   /** JPFConfigException handlers */
91   protected ExceptionHandler[] exceptionHandlers;
92
93   /** classnames of checked exception thrown by the method */
94   protected String[] thrownExceptionClassNames;
95
96   /** Table used for line numbers 
97    * this assigns a line number to every instruction index, instead of 
98    * using an array of ranges. Assuming we have 2-3 insns per line on average,
99    * this should still require less memory than a reference array with associated
100    * range objects, and allows faster access of instruction line numbers, which
101    * we might need for location specs
102    */
103   protected int[] lineNumbers;
104   
105   /** Local variable information */
106   protected LocalVarInfo localVars[] = null;
107
108   /** Maximum number of local variables */
109   protected int maxLocals;
110
111   /** Maximum number of elements on the stack */
112   protected int maxStack;
113
114   /** null if we don't have any */
115   AnnotationInfo[][] parameterAnnotations;
116
117   //--- a batch of attributes
118   
119   /** the standard Java modifier attributes */
120   protected int modifiers;
121    
122   /** a batch of execution related JPF attributes */
123   protected int attributes;
124       
125
126   //--- all the stuff we need for native methods
127   // <2do> pcm - turn this into a derived class
128
129   /**  the number of stack slots for the arguments (incl. 'this'), lazy eval */
130   protected int argSize = -1;
131
132   /** number of arguments (excl. 'this'), lazy eval */
133   protected int nArgs = -1;
134
135   /** what return type do we have (again, lazy evaluated) */
136   protected byte returnType = -1;
137
138   /** number of stack slots for return value */
139   protected int retSize = -1;
140
141   /** used for native method parameter conversion (lazy evaluated) */
142   protected byte[] argTypes = null;
143   
144   static boolean init (Config config) {
145     mthTable.clear();    
146     return true;
147   }
148
149   public static MethodInfo getMethodInfo (int globalId){
150     if (globalId >=0 && globalId <mthTable.size()){
151       return mthTable.get(globalId);
152     } else {
153       return null;
154     }
155   }
156   
157   public static MethodInfo create (String name, String signature, int modifiers){
158     return new MethodInfo( name, signature, modifiers);
159   }
160   
161   public static MethodInfo create (ClassInfo ci, String name, String signature, int modifiers){
162     return new MethodInfo( ci, name, signature, modifiers);
163   }
164   
165   static MethodInfo create (ClassInfo ci, String name, String signature, int modifiers, int maxLocals, int maxStack){
166     return new MethodInfo( ci, name, signature, modifiers, maxLocals, maxStack);
167   }
168
169   /**
170    * for direct call construction
171    * Note: this is only a partial initialization, the code still has to be created/installed by the caller
172    */
173   public MethodInfo (MethodInfo callee, int nLocals, int nOperands) {
174     globalId = DIRECT_CALL;
175     // we don't want direct call methods in the mthTable (would be a memory leak) so don't register
176     
177     ci = callee.ci;
178     name = "[" + callee.name + ']'; // it doesn't allocate anything, so we don't have to be unique
179     signature = "()V";
180     genericSignature = "";
181     maxLocals = nLocals;
182     maxStack = nOperands;  // <2do> cache for optimization
183     localVars = EMPTY;
184     lineNumbers = null;
185     exceptionHandlers = null;
186     thrownExceptionClassNames = null;
187     uniqueName = name;
188     
189     // we need to preserve the ClassInfo so that class resolution for static method calls works
190     ci = callee.ci;
191     
192     attributes |= IS_DIRECT_CALL;
193     modifiers = Modifier.STATIC;   // always treated as static
194     
195     // code still has to be installed by caller
196   }
197   
198   /**
199    * This is used to create synthetic methods of function object types
200    */
201   public MethodInfo(String name, String signature, int modifiers, int nLocals, int nOperands) {
202     this( name, signature, modifiers);
203     maxLocals = nLocals;
204     maxStack = nOperands;
205     localVars = EMPTY;
206   }
207   
208   /**
209    * for NativeMethodInfo creation 
210    */
211   public MethodInfo (MethodInfo mi) {
212     globalId = mi.globalId;
213     uniqueName = mi.uniqueName;
214     name = mi.name;
215     signature = mi.signature;
216     genericSignature = mi.genericSignature;
217     ci = mi.ci;
218     modifiers = mi.modifiers;
219     attributes = mi.attributes;
220     thrownExceptionClassNames = mi.thrownExceptionClassNames;
221     parameterAnnotations = mi.parameterAnnotations;
222
223     annotations = mi.annotations;
224     
225     localVars = null; // there are no StackFrame localVarInfos, this is native
226     // code still has to be installed by caller
227   }
228   
229   // <2do> this is going away
230   public MethodInfo (ClassInfo ci, String name, String signature, int modifiers, int maxLocals, int maxStack){
231     this.ci = ci;
232     this.name = name;
233     this.signature = signature;
234     this.uniqueName = getUniqueName(name, signature);
235     this.genericSignature = "";
236     this.maxLocals = maxLocals;
237     this.maxStack = maxStack;
238     this.modifiers = modifiers;
239
240     this.lineNumbers = null;
241     this.exceptionHandlers = null;
242     this.thrownExceptionClassNames = null;
243
244     // set attributes we can deduce from the name and the ClassInfo
245     if (ci != null){
246       if (name.equals("<init>")) {
247         attributes |= IS_INIT;
248       } else if (name.equals("<clinit>")) {
249         this.modifiers |= Modifier.SYNCHRONIZED;
250         attributes |= IS_CLINIT | FIREWALL;
251       }
252       if (ci.isInterface()) { // all interface methods are public
253         this.modifiers |= Modifier.PUBLIC;
254       }
255     }
256
257     this.globalId = mthTable.size();
258     mthTable.add(this);
259   }
260
261   
262   public MethodInfo (String name, String signature, int modifiers){
263     this.name = name;
264     this.signature = signature;
265     this.modifiers = modifiers;
266     this.uniqueName = getUniqueName(name, signature);
267     this.genericSignature = "";
268
269     if (name.equals("<init>")) {
270       attributes |= IS_INIT;
271     } else if (name.equals("<clinit>")) {
272       // for some reason clinits don't have the synchronized modifier, but they are synchronized
273       // we keep it consistent so that we don't have to implement special lock acquisition/release for clinits
274       this.modifiers |= Modifier.SYNCHRONIZED;
275       attributes |= IS_CLINIT | FIREWALL;
276     }
277     
278     this.globalId = mthTable.size();
279     mthTable.add(this);    
280   }
281
282   public MethodInfo (ClassInfo ci, String name, String signature, int modifiers){
283     this(name, signature, modifiers);
284     
285     this.ci = ci;
286   }
287   
288   //--- setters used during construction
289   
290   public void linkToClass (ClassInfo ci){
291     this.ci = ci;
292     
293     if (ci.isInterface()) { // all interface methods are public
294       this.modifiers |= Modifier.PUBLIC;
295     }
296   }
297   
298   public void setMaxLocals(int maxLocals){
299     this.maxLocals = maxLocals;
300   }
301
302   public void setMaxStack(int maxStack){
303     this.maxStack = maxStack;
304   }
305   
306   public void setCode (Instruction[] code){
307     for (int i=0; i<code.length; i++){
308       code[i].setMethodInfo(this);
309     }
310     this.code = code;
311   }
312   
313   
314   public boolean hasParameterAnnotations() {
315     return (parameterAnnotations != null);
316   }
317
318   // since some listeners might call this on every method invocation, we should do a little optimization
319   static AnnotationInfo[][] NO_PARAMETER_ANNOTATIONS_0 = new AnnotationInfo[0][];
320   static AnnotationInfo[][] NO_PARAMETER_ANNOTATIONS_1 = { new AnnotationInfo[0] };
321   static AnnotationInfo[][] NO_PARAMETER_ANNOTATIONS_2 = { new AnnotationInfo[0], new AnnotationInfo[0] };
322   static AnnotationInfo[][] NO_PARAMETER_ANNOTATIONS_3 = { new AnnotationInfo[0], new AnnotationInfo[0], new AnnotationInfo[0] };  
323   
324   public AnnotationInfo[][] getParameterAnnotations() {
325     if (parameterAnnotations == null){ // keep this similar to getAnnotations()
326       int n = getNumberOfArguments();
327       switch (n){
328       case 0: return NO_PARAMETER_ANNOTATIONS_0;
329       case 1: return NO_PARAMETER_ANNOTATIONS_1;
330       case 2: return NO_PARAMETER_ANNOTATIONS_2;
331       case 3: return NO_PARAMETER_ANNOTATIONS_3;
332       default:
333         AnnotationInfo[][] pai = new AnnotationInfo[n][];
334         for (int i=0; i<n; i++){
335           pai[i] = new AnnotationInfo[0];
336         }
337         return pai;
338       }
339       
340     } else {
341       return parameterAnnotations;
342     }
343   }
344
345   /**
346    * return annotations for parameterIndex
347    */
348   public AnnotationInfo[] getParameterAnnotations(int parameterIndex){
349     if (parameterAnnotations == null){
350       return null;
351     } else {
352       if (parameterIndex >= getNumberOfArguments()){
353         return null;
354       } else {
355         return parameterAnnotations[parameterIndex];
356       }
357     }
358   }
359
360
361   
362   public static int getNumberOfLoadedMethods () {
363     return mthTable.size();
364   }
365
366   void setAtomic (boolean isAtomic) {
367     if (isAtomic) {
368       attributes |= EXEC_ATOMIC;
369     } else {
370       attributes &= ~EXEC_ATOMIC;
371     }
372   }
373   public boolean isAtomic () {
374     return ((attributes & EXEC_ATOMIC) != 0);
375   }
376   
377   void setHidden (boolean isHidden) {
378     if (isHidden) {
379       attributes |= EXEC_HIDDEN;
380     } else {
381       attributes &= ~EXEC_HIDDEN;
382     }
383   }
384   public boolean isHidden () {
385     return ((attributes & EXEC_HIDDEN) != 0);    
386   }
387   
388   /**
389    * turn unhandled exceptionHandlers at the JPF execution level
390    * into UnhandledException throws at the host VM level
391    * this is useful to implement firewalls for direct calls
392    * which should not let exceptionHandlers permeate into bytecode/
393    * application code
394    */
395   public void setFirewall (boolean isFirewalled) {
396     if (isFirewalled) {
397       attributes |= FIREWALL;
398     } else {
399       attributes &= ~FIREWALL;
400     }
401   }
402   public boolean isFirewall () {
403     return ((attributes & FIREWALL) != 0);    
404   }
405   
406   
407   
408   @Override
409   public Object clone() {
410     try {
411       return super.clone();
412     } catch (CloneNotSupportedException cnx) {
413       return null;
414     }
415   }
416   
417   public int getGlobalId() {
418     return globalId;
419   }
420
421   public DirectCallStackFrame createRunStartStackFrame (ThreadInfo ti){
422     return ci.createRunStartStackFrame( ti, this);
423   }
424
425   public DirectCallStackFrame createDirectCallStackFrame (ThreadInfo ti, int nLocals){
426     return ci.createDirectCallStackFrame(ti, this, nLocals);
427   }
428
429   public boolean isSyncRelevant () {
430     return (name.charAt(0) != '<');
431   }
432   
433   public boolean isInitOrClinit (){
434     return ((attributes & (IS_CLINIT | IS_INIT)) != 0);
435   }
436   
437   public boolean isClinit () {
438     return ((attributes & IS_CLINIT) != 0);
439   }
440
441   public boolean isClinit (ClassInfo ci) {
442     return (((attributes & IS_CLINIT) != 0) && (this.ci == ci));
443   }
444
445   public boolean isInit() {
446     return ((attributes & IS_INIT) != 0);
447   }
448   
449   public boolean isDirectCallStub(){
450     return ((attributes & IS_DIRECT_CALL) != 0);    
451   }
452   
453   /**
454    * yet another name - this time with a non-mangled, but abbreviated signature
455    * and without return type (e.g. like "main(String[])"
456    */
457   public String getLongName () {
458     StringBuilder sb = new StringBuilder();
459     sb.append(name);
460     
461     sb.append('(');
462     String[] argTypeNames = getArgumentTypeNames();
463     for (int i=0; i<argTypeNames.length; i++) {
464       String a = argTypeNames[i];
465       int idx = a.lastIndexOf('.');
466       if (idx > 0) {
467         a = a.substring(idx+1);
468       }
469       if (i>0) {
470         sb.append(',');
471       }
472       sb.append(a);
473     }
474     sb.append(')');
475     
476     return sb.toString();
477   }
478   
479   /**
480    * return the minimal name that has to be unique for overloading
481    * used as a lookup key
482    * NOTE: with the silent introduction of covariant return types
483    * in Java 5.0, we have to use the full signature to be unique
484    */
485   public static String getUniqueName (String mname, String signature) {
486     return (mname + signature);
487   }
488
489   public String getStackTraceSource() {
490     return getSourceFileName();
491   }
492
493   public byte[] getArgumentTypes () {
494     if (argTypes == null) {
495       argTypes = Types.getArgumentTypes(signature);
496       nArgs = argTypes.length;
497     }
498
499     return argTypes;
500   }
501
502   public String[] getArgumentTypeNames () {
503     return Types.getArgumentTypeNames(signature);
504   }
505
506   // TODO: Fix for Groovy's model-checking
507   public String[] getArgumentGenericTypeNames () {
508     // TODO: We need to double check but for some reason Groovy has a type of generic signature with "<*>"
509     // TODO: in the class file.
510     if (genericSignature == null || genericSignature.equals("") || genericSignature.contains("<*>"))
511       return getArgumentTypeNames();
512     // We need to first find the start of the method parameters in the signature
513     String methodParameters = genericSignature.substring(genericSignature.indexOf('('));
514     return Types.getArgumentTypeNames(methodParameters);
515   }
516
517   public int getArgumentsSize () {
518     if (argSize < 0) {
519       argSize = Types.getArgumentsSize(signature);
520
521       if (!isStatic()) {
522         argSize++;
523       }
524     }
525
526     return argSize;
527   }
528   
529   /**
530    * return only the LocalVarInfos for arguments, in order of definition
531    * or null if there are no localVarInfos.
532    * throw a JPFException if there are more immediately in scope vars than args
533    * 
534    * NOTE - it is perfectly legal for a method to have arguments but no LocalVarInfos,
535    * which are code attributes, clients have to check for a non-null return value
536    * even if the method has arguments.
537    * Note also that abstract / interface methods don't have code and hence no
538    * LocalVarInfos
539    */
540   public LocalVarInfo[] getArgumentLocalVars(){
541     if (localVars == null){ // shortcut in case we don't have args or localVars;
542       return null;
543     }
544     
545     int nArgs = getNumberOfStackArguments(); // we want 'this'
546     if (nArgs == 0){
547       return new LocalVarInfo[0]; // rare enough so that we don't use a static
548     }
549
550     LocalVarInfo[] argLvis = new LocalVarInfo[nArgs];
551     int n = 0; // how many args we've got so far
552     
553     for (LocalVarInfo lvi : localVars){
554       // arguments are the only ones that are immediately in scope
555       if (lvi.getStartPC() == 0){
556         if (n == nArgs){ // ARGH - more in-scope vars than args
557           throw new JPFException("inconsistent localVar table for method " + getFullName());
558         }
559         
560         // order with respect to slot index - since this might get called
561         // frequently, we don't use java.util.Arrays.sort() but sort in
562         // on-the-fly. Note that we can have several localVar entries for the
563         // same name, but only one can be immediately in scope
564         int slotIdx = lvi.getSlotIndex();
565
566         int i;
567         for (i = 0; i < n; i++) {
568           if (slotIdx < argLvis[i].getSlotIndex()) {
569             for (int j=n; j>i; j--){
570               argLvis[j] = argLvis[j-1];
571             }
572             argLvis[i] = lvi;
573             n++;
574             break;
575           }
576         }
577         if (i == n) { // append
578           argLvis[n++] = lvi;
579         }
580       }
581     }
582     
583     return argLvis;
584   }
585   
586   public String getReturnType () {
587     return Types.getReturnTypeSignature(signature);
588   }
589
590   public String getReturnTypeName () {
591     return Types.getReturnTypeName(signature);
592   }
593
594   public String getGenericReturnTypeName () {
595     // TODO: We need to double check but for some reason Groovy has a type of generic signature with "<*>"
596     // TODO: in the class file.
597     if (genericSignature == null || genericSignature.equals("") || genericSignature.contains("<*>"))
598       return Types.getReturnTypeName(signature);
599     return Types.getGenericReturnTypeName(genericSignature);
600   }
601
602   public String getSourceFileName () {
603     if (ci != null) {
604       return ci.getSourceFileName();
605     } else {
606       return "[VM]";
607     }
608   }
609
610   public String getClassName () {
611     if (ci != null) {
612       return ci.getName();
613     } else {
614       return "[VM]";
615     }
616   }
617   
618   /**
619    * Returns the class the method belongs to.
620    */
621   public ClassInfo getClassInfo () {
622     return ci;
623   }
624
625   /**
626    * @deprecated - use getFullName
627    */
628   @Deprecated
629 public String getCompleteName () {
630     return getFullName();
631   }
632
633   /**
634    * return classname.name (but w/o signature)
635    */
636   public String getBaseName() {
637     return getClassName() + '.' + name;
638   }
639     
640   public boolean isCtor () {
641     return (name.equals("<init>"));
642   }
643   
644   public boolean isInternalMethod () {
645     // <2do> pcm - should turn this into an attribute for efficiency reasons
646     return (name.equals("<clinit>") || uniqueName.equals("finalize()V"));
647   }
648   
649   public boolean isThreadEntry (ThreadInfo ti) {
650     return (uniqueName.equals("run()V") && (ti.countStackFrames() == 1));
651   }
652   
653   /**
654    * Returns the full classname (if any) + name + signature.
655    */
656   public String getFullName () {
657     if (ci != null) {
658       return ci.getName() + '.' + getUniqueName();
659     } else {
660       return getUniqueName();
661     }
662   }
663
664   /**
665    * returns stack trace name: classname (if any) + name
666    */
667   public String getStackTraceName(){
668     if (ci != null) {
669       return ci.getName() + '.' + name;
670     } else {
671       return name;
672     }
673   }
674   
675   /**
676    * return number of instructions
677    */
678   public int getNumberOfInstructions() {
679     if (code == null){
680       return 0;
681     }
682     
683     return code.length;
684   }
685   
686   /**
687    * Returns a specific instruction.
688    */
689   public Instruction getInstruction (int i) {
690     if (code == null) {
691       return null;
692     }
693
694     if ((i < 0) || (i >= code.length)) {
695       return null;
696     }
697
698     return code[i];
699   }
700
701   /**
702    * Returns the instruction at a certain position.
703    */
704   public Instruction getInstructionAt (int position) {
705     if (code == null) {
706       return null;
707     }
708
709     for (int i = 0, l = code.length; i < l; i++) {
710       if ((code[i] != null) && (code[i].getPosition() == position)) {
711         return code[i];
712       }
713     }
714
715     throw new JPFException("instruction not found");
716   }
717
718   /**
719    * Returns the instructions of the method.
720    */
721   public Instruction[] getInstructions () {
722     return code;
723   }
724   
725   public boolean includesLine (int line){
726     int len = code.length;
727     return (code[0].getLineNumber() <= line) && (code[len].getLineNumber() >= line);
728   }
729
730   public Instruction[] getInstructionsForLine (int line){
731     return getInstructionsForLineInterval(line,line);
732   }
733
734   public Instruction[] getInstructionsForLineInterval (int l1, int l2){
735     Instruction[] c = code;
736        
737     // instruction line numbers don't have to be monotonic (they can decrease for loops)
738     // hence we cannot easily check for overlapping ranges
739     
740     if (c != null){
741        ArrayList<Instruction> matchingInsns = null;
742        
743        for (int i = 0; i < c.length; i++) {
744         Instruction insn = c[i];
745         int line = insn.getLineNumber();
746         if (line == l1 || line == l2 || (line > l1 && line < l2)) {
747           if (matchingInsns == null) {
748             matchingInsns = new ArrayList<Instruction>();
749           }
750           matchingInsns.add(insn);
751         }
752       }
753       
754       if (matchingInsns == null) {
755         return null;
756       } else {
757         return matchingInsns.toArray(new Instruction[matchingInsns.size()]);
758       }
759             
760     } else {
761       return null;
762     }
763   }
764
765   public Instruction[] getMatchingInstructions (LocationSpec lspec){
766     return getInstructionsForLineInterval(lspec.getFromLine(), lspec.getToLine());
767   }
768
769
770   /**
771    * Returns the line number for a given position.
772    */
773   public int getLineNumber (Instruction pc) {
774     if (lineNumbers == null) {
775       if (pc == null)
776         return -1;
777       else
778         return pc.getPosition();
779     }
780
781     if (pc != null) {
782       int idx = pc.getInstructionIndex();
783       if (idx < 0) idx = 0;
784       return lineNumbers[idx];
785     } else {
786       return -1;
787     }
788   }
789
790   /**
791    * Returns a table to translate positions into line numbers.
792    */
793   public int[] getLineNumbers () {
794     return lineNumbers;
795   }
796
797   public boolean containsLineNumber (int n){
798     if (lineNumbers != null){
799       return (lineNumbers[0] <= n) && (lineNumbers[lineNumbers.length-1] <= n);
800     }
801     
802     return false;
803   }
804   
805   public boolean intersectsLineNumbers( int first, int last){
806     if (lineNumbers != null){
807       if ((last < lineNumbers[0]) || (first > lineNumbers[lineNumbers.length-1])){
808         return false;
809       }
810       return true;
811     }
812     
813     return false;
814   }
815   
816   public ExceptionHandler getHandlerFor (ClassInfo ciException, Instruction insn){
817     if (exceptionHandlers != null){
818       int position = insn.getPosition();
819       for (int i=0; i<exceptionHandlers.length; i++){
820         ExceptionHandler handler = exceptionHandlers[i];
821         if ((position >= handler.getBegin()) && (position < handler.getEnd())) {
822           // checks if this type of exception is caught here (null means 'any')
823           String handledType = handler.getName();
824           if ((handledType == null)   // a catch-all handler
825                   || ciException.isInstanceOf(handledType)) {
826             return handler;
827           }
828         }          
829       }      
830     }
831     
832     return null;
833   }
834   
835   public boolean isMJI () {
836     return false;
837   }
838
839   public int getMaxLocals () {
840     return maxLocals;
841   }
842
843   public int getMaxStack () {
844     return maxStack;
845   }
846
847   public ExceptionHandler[] getExceptions () {
848     return exceptionHandlers;
849   }
850
851   public String[] getThrownExceptionClassNames () {
852     return thrownExceptionClassNames;
853   }
854
855
856   public LocalVarInfo getLocalVar(String name, int pc){
857     LocalVarInfo[] vars = localVars;
858     if (vars != null){
859       for (int i = 0; i < vars.length; i++) {
860         LocalVarInfo lv = vars[i];
861         if (lv.matches(name, pc)) {
862           return lv;
863         }
864       }
865     }
866
867     return null;
868
869   }
870
871   public LocalVarInfo getLocalVar (int slotIdx, int pc){
872     LocalVarInfo[] vars = localVars;
873
874     if (vars != null){
875       for (int i = 0; i < vars.length; i++) {
876         LocalVarInfo lv = vars[i];
877         if (lv.matches(slotIdx, pc)) {
878           return lv;
879         }
880       }
881     }
882
883     return null;
884   }
885
886   public LocalVarInfo[] getLocalVars() {
887     return localVars; 
888   }
889
890
891   /**
892    * note that this might contain duplicates for variables with multiple
893    * scope entries
894    */
895   public String[] getLocalVariableNames() {
896     String[] names = new String[localVars.length];
897
898     for (int i=0; i<localVars.length; i++){
899       names[i] = localVars[i].getName();
900     }
901
902     return names;
903   }
904
905
906   public MethodInfo getOverriddenMethodInfo(){
907     MethodInfo smi = null;
908     
909     if (ci != null) {
910       ClassInfo sci = ci.getSuperClass();
911       if (sci != null){
912         smi = sci.getMethod(getUniqueName(), true);
913       }
914     }
915     
916     return smi;
917   }
918   
919   /**
920    * Returns the name of the method.
921    */
922   public String getName () {
923     return name;
924   }
925
926   public String getJNIName () {
927     return Types.getJNIMangledMethodName(null, name, signature);
928   }
929   
930   public int getModifiers () {
931     return modifiers;
932   }
933   
934   /**
935    * Returns true if the method is native
936    */
937   public boolean isNative () {
938     return ((modifiers & Modifier.NATIVE) != 0);
939   }
940
941   public boolean isAbstract () {
942     return ((modifiers & Modifier.ABSTRACT) != 0);
943   }
944   
945   // overridden by NativeMethodInfo
946   public boolean isUnresolvedNativeMethod(){
947     return ((modifiers & Modifier.NATIVE) != 0);
948   }
949
950   // overridden by NativeMethodInfo
951   public boolean isJPFExecutable (){
952     return !hasAttr(NoJPFExec.class);
953   }
954
955   public int getNumberOfArguments () {
956     if (nArgs < 0) {
957       nArgs = Types.getNumberOfArguments(signature);
958     }
959
960     return nArgs;
961   }
962
963   /**
964    * Returns the size of the arguments.
965    * This returns the number of parameters passed on the stack, incl. 'this'
966    */
967   public int getNumberOfStackArguments () {
968     int n = getNumberOfArguments();
969
970     return isStatic() ? n : n + 1;
971   }
972
973   public int getNumberOfCallerStackSlots () {
974     return Types.getNumberOfStackSlots(signature, isStatic()); // includes return type
975   }
976
977   public Instruction getFirstInsn(){
978     if (code != null){
979       return code[0];
980     }
981     return null;    
982   }
983   
984   public Instruction getLastInsn() {
985     if (code != null){
986       return code[code.length-1];
987     }
988     return null;
989   }
990
991   /**
992    * do we return Object references?
993    */
994   public boolean isReferenceReturnType () {
995     int r = getReturnTypeCode();
996
997     return ((r == Types.T_REFERENCE) || (r == Types.T_ARRAY));
998   }
999
1000   public byte getReturnTypeCode () {
1001     if (returnType < 0) {
1002       returnType = Types.getReturnBuiltinType(signature);
1003     }
1004
1005     return returnType;
1006   }
1007
1008   /**
1009    * what is the slot size of the return value
1010    */
1011   public int getReturnSize() {
1012     if (retSize == -1){
1013       switch (getReturnTypeCode()) {
1014         case Types.T_VOID:
1015           retSize = 0;
1016           break;
1017
1018         case Types.T_LONG:
1019         case Types.T_DOUBLE:
1020           retSize = 2;
1021           break;
1022
1023         default:
1024           retSize = 1;
1025           break;
1026       }
1027     }
1028
1029     return retSize;
1030   }
1031
1032   public Class<? extends ChoiceGenerator<?>> getReturnChoiceGeneratorType (){
1033     switch (getReturnTypeCode()){
1034       case Types.T_BOOLEAN:
1035         return BooleanChoiceGenerator.class;
1036
1037       case Types.T_BYTE:
1038       case Types.T_CHAR:
1039       case Types.T_SHORT:
1040       case Types.T_INT:
1041         return IntChoiceGenerator.class;
1042
1043       case Types.T_LONG:
1044         return LongChoiceGenerator.class;
1045
1046       case Types.T_FLOAT:
1047         return FloatChoiceGenerator.class;
1048
1049       case Types.T_DOUBLE:
1050         return DoubleChoiceGenerator.class;
1051
1052       case Types.T_ARRAY:
1053       case Types.T_REFERENCE:
1054       case Types.T_VOID:
1055         return ReferenceChoiceGenerator.class;
1056     }
1057
1058     return null;
1059   }
1060
1061   /**
1062    * Returns the signature of the method.
1063    */
1064   public String getSignature () {
1065     return signature;
1066   }
1067
1068   @Override
1069   public String getGenericSignature() {
1070     return genericSignature;
1071   }
1072
1073   @Override
1074   public void setGenericSignature(String sig){
1075     genericSignature = sig;
1076   }
1077
1078   /**
1079    * Returns true if the method is static.
1080    */
1081   public boolean isStatic () {
1082     return ((modifiers & Modifier.STATIC) != 0);
1083   }
1084
1085   /**
1086    * is this a public method
1087    */
1088   public boolean isPublic() {
1089     return ((modifiers & Modifier.PUBLIC) != 0);
1090   }
1091   
1092   public boolean isPrivate() {
1093     return ((modifiers & Modifier.PRIVATE) != 0);
1094   }
1095   
1096   public boolean isProtected() {
1097     return ((modifiers & Modifier.PROTECTED) != 0);
1098   }
1099
1100   /**
1101    * Returns true if the method is synchronized.
1102    */
1103   public boolean isSynchronized () {
1104     return ((modifiers & Modifier.SYNCHRONIZED) != 0);
1105   }
1106
1107   // <2do> these modifiers are still java.lang.reflect internal and not
1108   // supported by public Modifier methods, but since we want to keep this 
1109   // similar to the Method reflection and we get the modifiers from the
1110   // classfile we implement this with explicit values
1111   
1112   public boolean isSynthetic(){
1113     return ((modifiers & 0x00001000) != 0);    
1114   } 
1115   public boolean isVarargs(){
1116     return ((modifiers & 0x00000080) != 0);        
1117   }
1118   
1119   /*
1120    * is this from a classfile or was it created by JPF (and hence should not
1121    * be visible in stacktraces etc)
1122    */
1123   public boolean isJPFInternal(){
1124     // note this has a different meaning than Method.isSynthetic(), which
1125     // is defined in VM spec 4.7.8. What we mean here is that this MethodInfo
1126     // is not associated with any class (such as direct call MethodInfos), but
1127     // there might be more in the future
1128     return (ci == null);
1129   }
1130   
1131   public String getUniqueName () {
1132     return uniqueName;
1133   }
1134   
1135   public boolean hasCode(){
1136     return (code != null);
1137   }
1138   
1139   public boolean hasEmptyBody (){
1140     // only instruction is a return
1141     return (code.length == 1 && (code[0] instanceof ReturnInstruction));
1142   }
1143
1144
1145   //--- parameter annotations
1146   //<2do> these are going away
1147   protected void startParameterAnnotations(int annotationCount){
1148     parameterAnnotations = new AnnotationInfo[annotationCount][];
1149   }
1150   protected void setParameterAnnotations(int index, AnnotationInfo[] ai){
1151     parameterAnnotations[index] = ai;
1152   }
1153   protected void finishParameterAnnotations(){
1154     // nothing
1155   }
1156
1157   public void setParameterAnnotations (AnnotationInfo[][] parameterAnnotations){
1158     this.parameterAnnotations = parameterAnnotations;
1159   }
1160   
1161   //--- thrown exceptions
1162   //<2do> these are going away
1163   protected void startTrownExceptions (int exceptionCount){
1164     thrownExceptionClassNames = new String[exceptionCount];
1165   }
1166   protected void setException (int index, String exceptionType){
1167     thrownExceptionClassNames[index] = Types.getClassNameFromTypeName(exceptionType);
1168   }
1169   protected void finishThrownExceptions(){
1170     // nothing
1171   }
1172
1173   public void setThrownExceptions (String[] exceptions){
1174     thrownExceptionClassNames = exceptions;
1175   }
1176   
1177
1178   //--- exception handler table initialization
1179   //<2do> these are going away
1180   protected void startExceptionHandlerTable (int handlerCount){
1181     exceptionHandlers = new ExceptionHandler[handlerCount];
1182   }
1183   protected void setExceptionHandler (int index, int startPc, int endPc, int handlerPc, String catchType){
1184     exceptionHandlers[index] = new ExceptionHandler(catchType, startPc, endPc, handlerPc);
1185   }
1186   protected void finishExceptionHandlerTable(){
1187     // nothing
1188   }
1189
1190   public void setExceptionHandlers (ExceptionHandler[] handlers){
1191     exceptionHandlers = handlers;
1192   }
1193   
1194   //--- local var table initialization
1195   // <2do> these are going away
1196   protected void startLocalVarTable (int localVarCount){
1197     localVars = new LocalVarInfo[localVarCount];
1198   }
1199   protected void setLocalVar(int index, String varName, String descriptor, int scopeStartPc, int scopeEndPc, int slotIndex){
1200     localVars[index] = new LocalVarInfo(varName, descriptor, "", scopeStartPc, scopeEndPc, slotIndex);
1201   }
1202   protected void finishLocalVarTable(){
1203     // nothing to do
1204   }
1205
1206   public void setLocalVarTable (LocalVarInfo[] locals){
1207     localVars = locals;
1208   }
1209   
1210   public void setLocalVarAnnotations (){
1211     if (localVars != null){
1212       for (VariableAnnotationInfo ai : getTargetTypeAnnotations(VariableAnnotationInfo.class)){
1213         for (int i = 0; i < ai.getNumberOfScopeEntries(); i++) {
1214           for (LocalVarInfo lv : localVars) {
1215             if (lv.getStartPC() == ai.getStartPC(i) && lv.getSlotIndex() == ai.getSlotIndex(i)) {
1216               lv.addTypeAnnotation(ai);
1217             }
1218           }
1219         }
1220       }
1221     }
1222   }
1223   
1224   public boolean hasTypeAnnotatedLocalVars (){
1225     if (localVars != null){
1226       for (LocalVarInfo lv : localVars){
1227         if (lv.hasTypeAnnotations()){
1228           return true;
1229         }
1230       }
1231     }
1232     
1233     return false;
1234   }
1235   
1236   public List<LocalVarInfo> getTypeAnnotatedLocalVars (){
1237     List<LocalVarInfo> list = null;
1238     
1239     if (localVars != null){
1240       for (LocalVarInfo lv : localVars){
1241         if (lv.hasTypeAnnotations()){
1242           if (list == null){
1243             list = new ArrayList<LocalVarInfo>();
1244           }
1245           list.add(lv);
1246         }
1247       }
1248     }
1249     
1250     if (list == null){
1251       list = Collections.emptyList();
1252     }
1253     
1254     return list;
1255   }
1256   
1257   public List<LocalVarInfo> getTypeAnnotatedLocalVars (String annotationClsName){
1258     List<LocalVarInfo> list = null;
1259     
1260     if (localVars != null){
1261       for (LocalVarInfo lv : localVars){
1262         AbstractTypeAnnotationInfo tai = lv.getTypeAnnotation(annotationClsName);
1263         if (tai != null){
1264           if (list == null){
1265             list = new ArrayList<LocalVarInfo>();
1266           }
1267           list.add(lv);
1268         }
1269       }
1270     }
1271     
1272     if (list == null){
1273       list = Collections.emptyList();
1274     }
1275     
1276     return list;
1277   }
1278   
1279   
1280   //--- line number table initialization
1281   // <2do> these are going away
1282   protected void startLineNumberTable(int lineNumberCount){
1283     int len = code.length;
1284     int[] ln = new int[len];
1285
1286     lineNumbers = ln;
1287   }
1288   protected void setLineNumber(int index, int lineNumber, int startPc){
1289     int len = code.length;
1290     int[] ln = lineNumbers;
1291
1292     for (int i=0; i<len; i++){
1293       Instruction insn = code[i];
1294       int pc = insn.getPosition();
1295
1296       if (pc == startPc){ // this is the first insn with this line number
1297         ln[i] = lineNumber;
1298         return;
1299       }
1300     }
1301   }
1302   protected void finishLineNumberTable (){
1303     int len = code.length;
1304     int[] ln = lineNumbers;
1305     int lastLine = ln[0];
1306
1307     for (int i=1; i<len; i++){
1308       if (ln[i] == 0){
1309         ln[i] = lastLine;
1310       } else {
1311         lastLine = ln[i];
1312       }
1313     }
1314   }
1315
1316   /**
1317    * note - this depends on that we already have a code array
1318    * and that the lines/startPcs are sorted (monotonic increasing)
1319    */
1320   public void setLineNumbers (int[] lines, int[] startPcs){
1321     int j=0;
1322     int lastLine = -1;
1323     
1324     int len = code.length;
1325     int[] ln = new int[len];
1326
1327     for (int i=0; i<len; i++){
1328       Instruction insn = code[i];
1329       int pc = insn.getPosition();
1330       
1331       if ((j < startPcs.length) && pc == startPcs[j]){
1332         lastLine = lines[j];
1333         j++;
1334       }
1335       
1336       ln[i] = lastLine;
1337     }
1338     
1339     lineNumbers = ln;
1340   }
1341
1342   /**
1343    * this version takes an already expanded line number array which has to be of
1344    * the same size as the code array
1345    */
1346   public void setLineNumbers (int[] lines){
1347     if (lines.length != code.length){
1348       throw new JPFException("inconsitent code/line number size");
1349     }
1350     lineNumbers = lines;
1351   }
1352   
1353   @Override
1354   public String toString() {
1355     return "MethodInfo[" + getFullName() + ']';
1356   }
1357   
1358   // for debugging purposes
1359   public void dump(){
1360     System.out.println("--- " + this);
1361     for (int i = 0; i < code.length; i++) {
1362       System.out.printf("%2d [%d]: %s\n", i, code[i].getPosition(), code[i].toString());
1363     }
1364   }
1365
1366   /**
1367    * Creates a method for a given class, by cloning this MethodInfo
1368    * and all the instructions belong to the method
1369    */
1370   public MethodInfo getInstanceFor(ClassInfo ci) {
1371     MethodInfo clone;
1372
1373     try {
1374       clone = (MethodInfo)super.clone();
1375       clone.ci = ci;
1376
1377       clone.globalId = mthTable.size();
1378       mthTable.add(this);
1379
1380       if(code == null) {
1381         clone.code = null;
1382       } else {
1383         clone.code = new Instruction[code.length];
1384
1385         for(int i=0; i<code.length; i++) {
1386           clone.code[i] = code[i].typeSafeClone(clone);
1387         }
1388       }
1389
1390     } catch (CloneNotSupportedException cnsx){
1391       cnsx.printStackTrace();
1392       return null;
1393     }
1394
1395     return clone;
1396   }
1397 }