aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/apache/bcel/generic/MethodGen.java
blob: 6833bc9e496d6d96b2c4b998f614b7e0f6f25a21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package org.apache.bcel.generic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Stack;

import org.apache.bcel.Const;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Annotations;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.ExceptionTable;
import org.apache.bcel.classfile.LineNumber;
import org.apache.bcel.classfile.LineNumberTable;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.LocalVariableTypeTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.ParameterAnnotationEntry;
import org.apache.bcel.classfile.ParameterAnnotations;
import org.apache.bcel.classfile.RuntimeVisibleParameterAnnotations;
import org.apache.bcel.classfile.Utility;
import org.apache.bcel.util.BCELComparator;

/**
 * Template class for building up a method. This is done by defining exception
 * handlers, adding thrown exceptions, local variables and attributes, whereas
 * the `LocalVariableTable' and `LineNumberTable' attributes will be set
 * automatically for the code. Use stripAttributes() if you don't like this.
 *
 * While generating code it may be necessary to insert NOP operations. You can
 * use the `removeNOPs' method to get rid off them.
 * The resulting method object can be obtained via the `getMethod()' method.
 *
 * @version $Id$
 * @see     InstructionList
 * @see     Method
 */
public class MethodGen extends FieldGenOrMethodGen {

    private String class_name;
    private Type[] arg_types;
    private String[] arg_names;
    private int max_locals;
    private int max_stack;
    private InstructionList il;
    private boolean strip_attributes;
    private LocalVariableTypeTable local_variable_type_table = null;
    private final List<LocalVariableGen> variable_vec = new ArrayList<>();
    private final List<LineNumberGen> line_number_vec = new ArrayList<>();
    private final List<CodeExceptionGen> exception_vec = new ArrayList<>();
    private final List<String> throws_vec = new ArrayList<>();
    private final List<Attribute> code_attrs_vec = new ArrayList<>();

    private List<AnnotationEntryGen>[] param_annotations; // Array of lists containing AnnotationGen objects
    private boolean hasParameterAnnotations = false;
    private boolean haveUnpackedParameterAnnotations = false;

    private static BCELComparator bcelComparator = new BCELComparator() {

        @Override
        public boolean equals( final Object o1, final Object o2 ) {
            final MethodGen THIS = (MethodGen) o1;
            final MethodGen THAT = (MethodGen) o2;
            return THIS.getName().equals(THAT.getName())
                    && THIS.getSignature().equals(THAT.getSignature());
        }


        @Override
        public int hashCode( final Object o ) {
            final MethodGen THIS = (MethodGen) o;
            return THIS.getSignature().hashCode() ^ THIS.getName().hashCode();
        }
    };


    /**
     * Declare method. If the method is non-static the constructor
     * automatically declares a local variable `$this' in slot 0. The
     * actual code is contained in the `il' parameter, which may further
     * manipulated by the user. But he must take care not to remove any
     * instruction (handles) that are still referenced from this object.
     *
     * For example one may not add a local variable and later remove the
     * instructions it refers to without causing havoc. It is safe
     * however if you remove that local variable, too.
     *
     * @param access_flags access qualifiers
     * @param return_type  method type
     * @param arg_types argument types
     * @param arg_names argument names (if this is null, default names will be provided
     * for them)
     * @param method_name name of method
     * @param class_name class name containing this method (may be null, if you don't care)
     * @param il instruction list associated with this method, may be null only for
     * abstract or native methods
     * @param cp constant pool
     */
    public MethodGen(final int access_flags, final Type return_type, final Type[] arg_types, String[] arg_names,
            final String method_name, final String class_name, final InstructionList il, final ConstantPoolGen cp) {
        super(access_flags);
        setType(return_type);
        setArgumentTypes(arg_types);
        setArgumentNames(arg_names);
        setName(method_name);
        setClassName(class_name);
        setInstructionList(il);
        setConstantPool(cp);
        final boolean abstract_ = isAbstract() || isNative();
        InstructionHandle start = null;
        InstructionHandle end = null;
        if (!abstract_) {
            start = il.getStart();
            end = il.getEnd();
            /* Add local variables, namely the implicit `this' and the arguments
             */
            if (!isStatic() && (class_name != null)) { // Instance method -> `this' is local var 0
                addLocalVariable("this",  ObjectType.getInstance(class_name), start, end);
            }
        }
        if (arg_types != null) {
            final int size = arg_types.length;
            for (final Type arg_type : arg_types) {
                if (Type.VOID == arg_type) {
                    throw new ClassGenException("'void' is an illegal argument type for a method");
                }
            }
            if (arg_names != null) { // Names for variables provided?
                if (size != arg_names.length) {
                    throw new ClassGenException("Mismatch in argument array lengths: " + size
                            + " vs. " + arg_names.length);
                }
            } else { // Give them dummy names
                arg_names = new String[size];
                for (int i = 0; i < size; i++) {
                    arg_names[i] = "arg" + i;
                }
                setArgumentNames(arg_names);
            }
            if (!abstract_) {
                for (int i = 0; i < size; i++) {
                    addLocalVariable(arg_names[i], arg_types[i], start, end);
                }
            }
        }
    }


    /**
     * Instantiate from existing method.
     *
     * @param m method
     * @param class_name class name containing this method
     * @param cp constant pool
     */
    public MethodGen(final Method m, final String class_name, final ConstantPoolGen cp) {
        this(m.getAccessFlags(), Type.getReturnType(m.getSignature()), Type.getArgumentTypes(m
                .getSignature()), null /* may be overridden anyway */
        , m.getName(), class_name,
                ((m.getAccessFlags() & (Const.ACC_ABSTRACT | Const.ACC_NATIVE)) == 0)
                        ? new InstructionList(m.getCode().getCode())
                        : null, cp);
        final Attribute[] attributes = m.getAttributes();
        for (final Attribute attribute : attributes) {
            Attribute a = attribute;
            if (a instanceof Code) {
                final Code c = (Code) a;
                setMaxStack(c.getMaxStack());
                setMaxLocals(c.getMaxLocals());
                final CodeException[] ces = c.getExceptionTable();
                if (ces != null) {
                    for (final CodeException ce : ces) {
                        final int type = ce.getCatchType();
                        ObjectType c_type = null;
                        if (type > 0) {
                            final String cen = m.getConstantPool().getConstantString(type,
                                    Const.CONSTANT_Class);
                            c_type =  ObjectType.getInstance(cen);
                        }
                        final int end_pc = ce.getEndPC();
                        final int length = m.getCode().getCode().length;
                        InstructionHandle end;
                        if (length == end_pc) { // May happen, because end_pc is exclusive
                            end = il.getEnd();
                        } else {
                            end = il.findHandle(end_pc);
                            end = end.getPrev(); // Make it inclusive
                        }
                        addExceptionHandler(il.findHandle(ce.getStartPC()), end, il.findHandle(ce
                                .getHandlerPC()), c_type);
                    }
                }
                final Attribute[] c_attributes = c.getAttributes();
                for (final Attribute c_attribute : c_attributes) {
                    a = c_attribute;
                    if (a instanceof LineNumberTable) {
                        final LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable();
                        for (final LineNumber l : ln) {
                            final InstructionHandle ih = il.findHandle(l.getStartPC());
                            if (ih != null) {
                                addLineNumber(ih, l.getLineNumber());
                            }
                        }
                    } else if (a instanceof LocalVariableTable) {
                        updateLocalVariableTable((LocalVariableTable) a);
                    } else if (a instanceof LocalVariableTypeTable) {
                        this.local_variable_type_table = (LocalVariableTypeTable) a.copy(cp.getConstantPool());
                    } else {
                        addCodeAttribute(a);
                    }
                }
            } else if (a instanceof ExceptionTable) {
                final String[] names = ((ExceptionTable) a).getExceptionNames();
                for (final String name2 : names) {
                    addException(name2);
                }
            } else if (a instanceof Annotations) {
                final Annotations runtimeAnnotations = (Annotations) a;
                final AnnotationEntry[] aes = runtimeAnnotations.getAnnotationEntries();
                for (final AnnotationEntry element : aes) {
                    addAnnotationEntry(new AnnotationEntryGen(element, cp, false));
                }
            } else {
                addAttribute(a);
            }
        }
    }

    /**
     * Adds a local variable to this method.
     *
     * @param name variable name
     * @param type variable type
     * @param slot the index of the local variable, if type is long or double, the next available
     * index is slot+2
     * @param start from where the variable is valid
     * @param end until where the variable is valid
     * @param orig_index the index of the local variable prior to any modifications
     * @return new local variable object
     * @see LocalVariable
     */
    public LocalVariableGen addLocalVariable( final String name, final Type type, final int slot,
            final InstructionHandle start, final InstructionHandle end, final int orig_index ) {
        final byte t = type.getType();
        if (t != Const.T_ADDRESS) {
            final int add = type.getSize();
            if (slot + add > max_locals) {
                max_locals = slot + add;
            }
            final LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end, orig_index);
            int i;
            if ((i = variable_vec.indexOf(l)) >= 0) {
                variable_vec.set(i, l);
            } else {
                variable_vec.add(l);
            }
            return l;
        }
        throw new IllegalArgumentException("Can not use " + type
                + " as type for local variable");
    }


    /**
     * Adds a local variable to this method.
     *
     * @param name variable name
     * @param type variable type
     * @param slot the index of the local variable, if type is long or double, the next available
     * index is slot+2
     * @param start from where the variable is valid
     * @param end until where the variable is valid
     * @return new local variable object
     * @see LocalVariable
     */
    public LocalVariableGen addLocalVariable( final String name, final Type type, final int slot,
            final InstructionHandle start, final InstructionHandle end ) {
        return addLocalVariable(name, type, slot, start, end, slot);
    }

    /**
     * Adds a local variable to this method and assigns an index automatically.
     *
     * @param name variable name
     * @param type variable type
     * @param start from where the variable is valid, if this is null,
     * it is valid from the start
     * @param end until where the variable is valid, if this is null,
     * it is valid to the end
     * @return new local variable object
     * @see LocalVariable
     */
    public LocalVariableGen addLocalVariable( final String name, final Type type, final InstructionHandle start,
            final InstructionHandle end ) {
        return addLocalVariable(name, type, max_locals, start, end);
    }


    /**
     * Remove a local variable, its slot will not be reused, if you do not use addLocalVariable
     * with an explicit index argument.
     */
    public void removeLocalVariable( final LocalVariableGen l ) {
        l.dispose();
        variable_vec.remove(l);
    }


    /**
     * Remove all local variables.
     */
    public void removeLocalVariables() {
        for (final LocalVariableGen lv : variable_vec) {
            lv.dispose();
        }
        variable_vec.clear();
    }


    /*
     * If the range of the variable has not been set yet, it will be set to be valid from
     * the start to the end of the instruction list.
     *
     * @return array of declared local variables sorted by index
     */
    public LocalVariableGen[] getLocalVariables() {
        final int size = variable_vec.size();
        final LocalVariableGen[] lg = new LocalVariableGen[size];
        variable_vec.toArray(lg);
        for (int i = 0; i < size; i++) {
            if ((lg[i].getStart() == null) && (il != null)) {
                lg[i].setStart(il.getStart());
            }
            if ((lg[i].getEnd() == null) && (il != null)) {
                lg[i].setEnd(il.getEnd());
            }
        }
        if (size > 1) {
            Arrays.sort(lg, new Comparator<LocalVariableGen>() {
                @Override
                public int compare(final LocalVariableGen o1, final LocalVariableGen o2) {
                    return o1.getIndex() - o2.getIndex();
                }
            });
        }
        return lg;
    }


    /**
     * @return `LocalVariableTable' attribute of all the local variables of this method.
     */
    public LocalVariableTable getLocalVariableTable( final ConstantPoolGen cp ) {
        final LocalVariableGen[] lg = getLocalVariables();
        final int size = lg.length;
        final LocalVariable[] lv = new LocalVariable[size];
        for (int i = 0; i < size; i++) {
            lv[i] = lg[i].getLocalVariable(cp);
        }
        return new LocalVariableTable(cp.addUtf8("LocalVariableTable"), 2 + lv.length * 10, lv, cp
                .getConstantPool());
    }

    /**
     * @return `LocalVariableTypeTable' attribute of this method.
     */
    public LocalVariableTypeTable getLocalVariableTypeTable() {
        return local_variable_type_table;
    }

    /**
     * Give an instruction a line number corresponding to the source code line.
     *
     * @param ih instruction to tag
     * @return new line number object
     * @see LineNumber
     */
    public LineNumberGen addLineNumber( final InstructionHandle ih, final int src_line ) {
        final LineNumberGen l = new LineNumberGen(ih, src_line);
        line_number_vec.add(l);
        return l;
    }


    /**
     * Remove a line number.
     */
    public void removeLineNumber( final LineNumberGen l ) {
        line_number_vec.remove(l);
    }


    /**
     * Remove all line numbers.
     */
    public void removeLineNumbers() {
        line_number_vec.clear();
    }


    /*
     * @return array of line numbers
     */
    public LineNumberGen[] getLineNumbers() {
        final LineNumberGen[] lg = new LineNumberGen[line_number_vec.size()];
        line_number_vec.toArray(lg);
        return lg;
    }


    /**
     * @return `LineNumberTable' attribute of all the local variables of this method.
     */
    public LineNumberTable getLineNumberTable( final ConstantPoolGen cp ) {
        final int size = line_number_vec.size();
        final LineNumber[] ln = new LineNumber[size];
        for (int i = 0; i < size; i++) {
            ln[i] = line_number_vec.get(i).getLineNumber();
        }
        return new LineNumberTable(cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp
                .getConstantPool());
    }


    /**
     * Add an exception handler, i.e., specify region where a handler is active and an
     * instruction where the actual handling is done.
     *
     * @param start_pc Start of region (inclusive)
     * @param end_pc End of region (inclusive)
     * @param handler_pc Where handling is done
     * @param catch_type class type of handled exception or null if any
     * exception is handled
     * @return new exception handler object
     */
    public CodeExceptionGen addExceptionHandler( final InstructionHandle start_pc,
            final InstructionHandle end_pc, final InstructionHandle handler_pc, final ObjectType catch_type ) {
        if ((start_pc == null) || (end_pc == null) || (handler_pc == null)) {
            throw new ClassGenException("Exception handler target is null instruction");
        }
        final CodeExceptionGen c = new CodeExceptionGen(start_pc, end_pc, handler_pc, catch_type);
        exception_vec.add(c);
        return c;
    }


    /**
     * Remove an exception handler.
     */
    public void removeExceptionHandler( final CodeExceptionGen c ) {
        exception_vec.remove(c);
    }


    /**
     * Remove all line numbers.
     */
    public void removeExceptionHandlers() {
        exception_vec.clear();
    }


    /*
     * @return array of declared exception handlers
     */
    public CodeExceptionGen[] getExceptionHandlers() {
        final CodeExceptionGen[] cg = new CodeExceptionGen[exception_vec.size()];
        exception_vec.toArray(cg);
        return cg;
    }


    /**
     * @return code exceptions for `Code' attribute
     */
    private CodeException[] getCodeExceptions() {
        final int size = exception_vec.size();
        final CodeException[] c_exc = new CodeException[size];
        for (int i = 0; i < size; i++) {
            final CodeExceptionGen c =  exception_vec.get(i);
            c_exc[i] = c.getCodeException(super.getConstantPool());
        }
        return c_exc;
    }


    /**
     * Add an exception possibly thrown by this method.
     *
     * @param class_name (fully qualified) name of exception
     */
    public void addException( final String class_name ) {
        throws_vec.add(class_name);
    }


    /**
     * Remove an exception.
     */
    public void removeException( final String c ) {
        throws_vec.remove(c);
    }


    /**
     * Remove all exceptions.
     */
    public void removeExceptions() {
        throws_vec.clear();
    }


    /*
     * @return array of thrown exceptions
     */
    public String[] getExceptions() {
        final String[] e = new String[throws_vec.size()];
        throws_vec.toArray(e);
        return e;
    }


    /**
     * @return `Exceptions' attribute of all the exceptions thrown by this method.
     */
    private ExceptionTable getExceptionTable( final ConstantPoolGen cp ) {
        final int size = throws_vec.size();
        final int[] ex = new int[size];
        for (int i = 0; i < size; i++) {
            ex[i] = cp.addClass(throws_vec.get(i));
        }
        return new ExceptionTable(cp.addUtf8("Exceptions"), 2 + 2 * size, ex, cp.getConstantPool());
    }


    /**
     * Add an attribute to the code. Currently, the JVM knows about the
     * LineNumberTable, LocalVariableTable and StackMap attributes,
     * where the former two will be generated automatically and the
     * latter is used for the MIDP only. Other attributes will be
     * ignored by the JVM but do no harm.
     *
     * @param a attribute to be added
     */
    public void addCodeAttribute( final Attribute a ) {
        code_attrs_vec.add(a);
    }


    /**
     * Remove the LocalVariableTypeTable
     */
    public void removeLocalVariableTypeTable( ) {
        local_variable_type_table = null;
    }

    /**
     * Remove a code attribute.
     */
    public void removeCodeAttribute( final Attribute a ) {
        code_attrs_vec.remove(a);
    }


    /**
     * Remove all code attributes.
     */
    public void removeCodeAttributes() {
        local_variable_type_table = null;
        code_attrs_vec.clear();
    }


    /**
     * @return all attributes of this method.
     */
    public Attribute[] getCodeAttributes() {
        final Attribute[] attributes = new Attribute[code_attrs_vec.size()];
        code_attrs_vec.toArray(attributes);
        return attributes;
    }

    /**
     * @since 6.0
     */
    public void addAnnotationsAsAttribute(final ConstantPoolGen cp) {
          final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries());
        for (final Attribute attr : attrs) {
            addAttribute(attr);
        }
      }

    /**
     * @since 6.0
     */
      public void addParameterAnnotationsAsAttribute(final ConstantPoolGen cp) {
          if (!hasParameterAnnotations) {
            return;
        }
          final Attribute[] attrs = AnnotationEntryGen.getParameterAnnotationAttributes(cp,param_annotations);
          if (attrs!=null) {
          for (final Attribute attr : attrs) {
              addAttribute(attr);
          }
          }
      }


    /**
     * Get method object. Never forget to call setMaxStack() or setMaxStack(max), respectively,
     * before calling this method (the same applies for max locals).
     *
     * @return method object
     */
    public Method getMethod() {
        final String signature = getSignature();
        final ConstantPoolGen _cp = super.getConstantPool();
        final int name_index = _cp.addUtf8(super.getName());
        final int signature_index = _cp.addUtf8(signature);
        /* Also updates positions of instructions, i.e., their indices
         */
        byte[] byte_code = null;
        if (il != null) {
            byte_code = il.getByteCode();
        }
        LineNumberTable lnt = null;
        LocalVariableTable lvt = null;
        /* Create LocalVariableTable and LineNumberTable attributes (for debuggers, e.g.)
         */
        if ((variable_vec.size() > 0) && !strip_attributes) {
            updateLocalVariableTable(getLocalVariableTable(_cp));
            addCodeAttribute(lvt = getLocalVariableTable(_cp));
        }
        if (local_variable_type_table != null) {
            // LocalVariable length in LocalVariableTypeTable is not updated automatically. It's a difference with LocalVariableTable.
            if (lvt != null) {
                adjustLocalVariableTypeTable(lvt);
            }
            addCodeAttribute(local_variable_type_table);
        }
        if ((line_number_vec.size() > 0) && !strip_attributes) {
            addCodeAttribute(lnt = getLineNumberTable(_cp));
        }
        final Attribute[] code_attrs = getCodeAttributes();
        /* Each attribute causes 6 additional header bytes
         */
        int attrs_len = 0;
        for (final Attribute code_attr : code_attrs) {
            attrs_len += code_attr.getLength() + 6;
        }
        final CodeException[] c_exc = getCodeExceptions();
        final int exc_len = c_exc.length * 8; // Every entry takes 8 bytes
        Code code = null;
        if ((il != null) && !isAbstract() && !isNative()) {
            // Remove any stale code attribute
            final Attribute[] attributes = getAttributes();
            for (final Attribute a : attributes) {
                if (a instanceof Code) {
                    removeAttribute(a);
                }
            }
            code = new Code(_cp.addUtf8("Code"), 8 + byte_code.length + // prologue byte code
                    2 + exc_len + // exceptions
                    2 + attrs_len, // attributes
                    max_stack, max_locals, byte_code, c_exc, code_attrs, _cp.getConstantPool());
            addAttribute(code);
        }
        addAnnotationsAsAttribute(_cp);
        addParameterAnnotationsAsAttribute(_cp);
        ExceptionTable et = null;
        if (throws_vec.size() > 0) {
            addAttribute(et = getExceptionTable(_cp));
            // Add `Exceptions' if there are "throws" clauses
        }
        final Method m = new Method(super.getAccessFlags(), name_index, signature_index, getAttributes(), _cp
                .getConstantPool());
        // Undo effects of adding attributes
        if (lvt != null) {
            removeCodeAttribute(lvt);
        }
        if (local_variable_type_table != null) {
            removeCodeAttribute(local_variable_type_table);
        }
        if (lnt != null) {
            removeCodeAttribute(lnt);
        }
        if (code != null) {
            removeAttribute(code);
        }
        if (et != null) {
            removeAttribute(et);
        }
        return m;
    }

    private void updateLocalVariableTable(final LocalVariableTable a) {
        final LocalVariable[] lv = a.getLocalVariableTable();
        removeLocalVariables();
        for (final LocalVariable l : lv) {
            InstructionHandle start = il.findHandle(l.getStartPC());
            InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength());
            // Repair malformed handles
            if (null == start) {
                start = il.getStart();
            }
            if (null == end) {
                end = il.getEnd();
            }
            // Since we are recreating the LocalVaraible, we must
            // propagate the orig_index to new copy.
            addLocalVariable(l.getName(), Type.getType(l.getSignature()), l
                    .getIndex(), start, end, l.getOrigIndex());
        }
    }

    private void adjustLocalVariableTypeTable(final LocalVariableTable lvt) {
        final LocalVariable[] lv = lvt.getLocalVariableTable();
        final LocalVariable[] lvg = local_variable_type_table.getLocalVariableTypeTable();

        for (final LocalVariable element : lvg) {
            for (final LocalVariable l : lv) {
                if (element.getName().equals(l.getName()) && element.getIndex() == l.getOrigIndex()) {
                    element.setLength(l.getLength());
                    element.setStartPC(l.getStartPC());
                    element.setIndex(l.getIndex());
                    break;
                }
            }
        }
    }


    /**
     * Remove all NOPs from the instruction list (if possible) and update every
     * object referring to them, i.e., branch instructions, local variables and
     * exception handlers.
     */
    public void removeNOPs() {
        if (il != null) {
            InstructionHandle next;
            /* Check branch instructions.
             */
            for (InstructionHandle ih = il.getStart(); ih != null; ih = next) {
                next = ih.getNext();
                if ((next != null) && (ih.getInstruction() instanceof NOP)) {
                    try {
                        il.delete(ih);
                    } catch (final TargetLostException e) {
                        for (final InstructionHandle target : e.getTargets()) {
                            for (final InstructionTargeter targeter : target.getTargeters()) {
                                targeter.updateTarget(target, next);
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * Set maximum number of local variables.
     */
    public void setMaxLocals( final int m ) {
        max_locals = m;
    }


    public int getMaxLocals() {
        return max_locals;
    }


    /**
     * Set maximum stack size for this method.
     */
    public void setMaxStack( final int m ) { // TODO could be package-protected?
        max_stack = m;
    }


    public int getMaxStack() {
        return max_stack;
    }


    /** @return class that contains this method
     */
    public String getClassName() {
        return class_name;
    }


    public void setClassName( final String class_name ) { // TODO could be package-protected?
        this.class_name = class_name;
    }


    public void setReturnType( final Type return_type ) {
        setType(return_type);
    }


    public Type getReturnType() {
        return getType();
    }


    public void setArgumentTypes( final Type[] arg_types ) {
        this.arg_types = arg_types;
    }


    public Type[] getArgumentTypes() {
        return arg_types.clone();
    }


    public void setArgumentType( final int i, final Type type ) {
        arg_types[i] = type;
    }


    public Type getArgumentType( final int i ) {
        return arg_types[i];
    }


    public void setArgumentNames( final String[] arg_names ) {
        this.arg_names = arg_names;
    }


    public String[] getArgumentNames() {
        return arg_names.clone();
    }


    public void setArgumentName( final int i, final String name ) {
        arg_names[i] = name;
    }


    public String getArgumentName( final int i ) {
        return arg_names[i];
    }


    public InstructionList getInstructionList() {
        return il;
    }


    public void setInstructionList( final InstructionList il ) { // TODO could be package-protected?
        this.il = il;
    }


    @Override
    public String getSignature() {
        return Type.getMethodSignature(super.getType(), arg_types);
    }


    /**
     * Computes max. stack size by performing control flow analysis.
     */
    public void setMaxStack() { // TODO could be package-protected? (some tests would need repackaging)
        if (il != null) {
            max_stack = getMaxStack(super.getConstantPool(), il, getExceptionHandlers());
        } else {
            max_stack = 0;
        }
    }


    /**
     * Compute maximum number of local variables.
     */
    public void setMaxLocals() { // TODO could be package-protected? (some tests would need repackaging)
        if (il != null) {
            int max = isStatic() ? 0 : 1;
            if (arg_types != null) {
                for (final Type arg_type : arg_types) {
                    max += arg_type.getSize();
                }
            }
            for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
                final Instruction ins = ih.getInstruction();
                if ((ins instanceof LocalVariableInstruction) || (ins instanceof RET)
                        || (ins instanceof IINC)) {
                    final int index = ((IndexedInstruction) ins).getIndex()
                            + ((TypedInstruction) ins).getType(super.getConstantPool()).getSize();
                    if (index > max) {
                        max = index;
                    }
                }
            }
            max_locals = max;
        } else {
            max_locals = 0;
        }
    }


    /** Do not/Do produce attributes code attributesLineNumberTable and
     * LocalVariableTable, like javac -O
     */
    public void stripAttributes( final boolean flag ) {
        strip_attributes = flag;
    }

    static final class BranchTarget {

        final InstructionHandle target;
        final int stackDepth;


        BranchTarget(final InstructionHandle target, final int stackDepth) {
            this.target = target;
            this.stackDepth = stackDepth;
        }
    }

    static final class BranchStack {

        private final Stack<BranchTarget> branchTargets = new Stack<>();
        private final Hashtable<InstructionHandle, BranchTarget> visitedTargets = new Hashtable<>();


        public void push( final InstructionHandle target, final int stackDepth ) {
            if (visited(target)) {
                return;
            }
            branchTargets.push(visit(target, stackDepth));
        }


        public BranchTarget pop() {
            if (!branchTargets.empty()) {
                final BranchTarget bt = branchTargets.pop();
                return bt;
            }
            return null;
        }


        private BranchTarget visit( final InstructionHandle target, final int stackDepth ) {
            final BranchTarget bt = new BranchTarget(target, stackDepth);
            visitedTargets.put(target, bt);
            return bt;
        }


        private boolean visited( final InstructionHandle target ) {
            return visitedTargets.get(target) != null;
        }
    }


    /**
     * Computes stack usage of an instruction list by performing control flow analysis.
     *
     * @return maximum stack depth used by method
     */
    public static int getMaxStack( final ConstantPoolGen cp, final InstructionList il, final CodeExceptionGen[] et ) {
        final BranchStack branchTargets = new BranchStack();
        /* Initially, populate the branch stack with the exception
         * handlers, because these aren't (necessarily) branched to
         * explicitly. in each case, the stack will have depth 1,
         * containing the exception object.
         */
        for (final CodeExceptionGen element : et) {
            final InstructionHandle handler_pc = element.getHandlerPC();
            if (handler_pc != null) {
                branchTargets.push(handler_pc, 1);
            }
        }
        int stackDepth = 0;
        int maxStackDepth = 0;
        InstructionHandle ih = il.getStart();
        while (ih != null) {
            final Instruction instruction = ih.getInstruction();
            final short opcode = instruction.getOpcode();
            final int delta = instruction.produceStack(cp) - instruction.consumeStack(cp);
            stackDepth += delta;
            if (stackDepth > maxStackDepth) {
                maxStackDepth = stackDepth;
            }
            // choose the next instruction based on whether current is a branch.
            if (instruction instanceof BranchInstruction) {
                final BranchInstruction branch = (BranchInstruction) instruction;
                if (instruction instanceof Select) {
                    // explore all of the select's targets. the default target is handled below.
                    final Select select = (Select) branch;
                    final InstructionHandle[] targets = select.getTargets();
                    for (final InstructionHandle target : targets) {
                        branchTargets.push(target, stackDepth);
                    }
                    // nothing to fall through to.
                    ih = null;
                } else if (!(branch instanceof IfInstruction)) {
                    // if an instruction that comes back to following PC,
                    // push next instruction, with stack depth reduced by 1.
                    if (opcode == Const.JSR || opcode == Const.JSR_W) {
                        branchTargets.push(ih.getNext(), stackDepth - 1);
                    }
                    ih = null;
                }
                // for all branches, the target of the branch is pushed on the branch stack.
                // conditional branches have a fall through case, selects don't, and
                // jsr/jsr_w return to the next instruction.
                branchTargets.push(branch.getTarget(), stackDepth);
            } else {
                // check for instructions that terminate the method.
                if (opcode == Const.ATHROW || opcode == Const.RET
                        || (opcode >= Const.IRETURN && opcode <= Const.RETURN)) {
                    ih = null;
                }
            }
            // normal case, go to the next instruction.
            if (ih != null) {
                ih = ih.getNext();
            }
            // if we have no more instructions, see if there are any deferred branches to explore.
            if (ih == null) {
                final BranchTarget bt = branchTargets.pop();
                if (bt != null) {
                    ih = bt.target;
                    stackDepth = bt.stackDepth;
                }
            }
        }
        return maxStackDepth;
    }

    private List<MethodObserver> observers;


    /** Add observer for this object.
     */
    public void addObserver( final MethodObserver o ) {
        if (observers == null) {
            observers = new ArrayList<>();
        }
        observers.add(o);
    }


    /** Remove observer for this object.
     */
    public void removeObserver( final MethodObserver o ) {
        if (observers != null) {
            observers.remove(o);
        }
    }


    /** Call notify() method on all observers. This method is not called
     * automatically whenever the state has changed, but has to be
     * called by the user after he has finished editing the object.
     */
    public void update() {
        if (observers != null) {
            for (final MethodObserver observer : observers) {
                observer.notify(this);
            }
        }
    }


    /**
     * Return string representation close to declaration format,
     * `public static void main(String[]) throws IOException', e.g.
     *
     * @return String representation of the method.
     */
    @Override
    public final String toString() {
        final String access = Utility.accessToString(super.getAccessFlags());
        String signature = Type.getMethodSignature(super.getType(), arg_types);
        signature = Utility.methodSignatureToString(signature, super.getName(), access, true,
                getLocalVariableTable(super.getConstantPool()));
        final StringBuilder buf = new StringBuilder(signature);
        for (final Attribute a : getAttributes()) {
            if (!((a instanceof Code) || (a instanceof ExceptionTable))) {
                buf.append(" [").append(a).append("]");
            }
        }

        if (throws_vec.size() > 0) {
            for (final String throwsDescriptor : throws_vec) {
                buf.append("\n\t\tthrows ").append(throwsDescriptor);
            }
        }
        return buf.toString();
    }


    /** @return deep copy of this method
     */
    public MethodGen copy( final String class_name, final ConstantPoolGen cp ) {
        final Method m = ((MethodGen) clone()).getMethod();
        final MethodGen mg = new MethodGen(m, class_name, super.getConstantPool());
        if (super.getConstantPool() != cp) {
            mg.setConstantPool(cp);
            mg.getInstructionList().replaceConstantPool(super.getConstantPool(), cp);
        }
        return mg;
    }

    //J5TODO: Should param_annotations be an array of arrays? Rather than an array of lists, this
    // is more likely to suggest to the caller it is readonly (which a List does not).
    /**
     * Return a list of AnnotationGen objects representing parameter annotations
     * @since 6.0
     */
    public List<AnnotationEntryGen> getAnnotationsOnParameter(final int i) {
        ensureExistingParameterAnnotationsUnpacked();
        if (!hasParameterAnnotations || i>arg_types.length) {
            return null;
        }
        return param_annotations[i];
    }

    /**
     * Goes through the attributes on the method and identifies any that are
     * RuntimeParameterAnnotations, extracting their contents and storing them
     * as parameter annotations. There are two kinds of parameter annotation -
     * visible and invisible. Once they have been unpacked, these attributes are
     * deleted. (The annotations will be rebuilt as attributes when someone
     * builds a Method object out of this MethodGen object).
     */
    private void ensureExistingParameterAnnotationsUnpacked()
    {
        if (haveUnpackedParameterAnnotations) {
            return;
        }
        // Find attributes that contain parameter annotation data
        final Attribute[] attrs = getAttributes();
        ParameterAnnotations paramAnnVisAttr = null;
        ParameterAnnotations paramAnnInvisAttr = null;
        for (final Attribute attribute : attrs) {
            if (attribute instanceof ParameterAnnotations)
            {
                // Initialize param_annotations
                if (!hasParameterAnnotations)
                {
                    @SuppressWarnings("unchecked") // OK
                    final List<AnnotationEntryGen>[] parmList = new List[arg_types.length];
                    param_annotations = parmList;
                    for (int j = 0; j < arg_types.length; j++) {
                        param_annotations[j] = new ArrayList<>();
                    }
                }
                hasParameterAnnotations = true;
                final ParameterAnnotations rpa = (ParameterAnnotations) attribute;
                if (rpa instanceof RuntimeVisibleParameterAnnotations) {
                    paramAnnVisAttr = rpa;
                } else {
                    paramAnnInvisAttr = rpa;
                }
                final ParameterAnnotationEntry[] parameterAnnotationEntries = rpa.getParameterAnnotationEntries();
                for (int j = 0; j < parameterAnnotationEntries.length; j++)
                {
                    // This returns Annotation[] ...
                    final ParameterAnnotationEntry immutableArray = rpa.getParameterAnnotationEntries()[j];
                    // ... which needs transforming into an AnnotationGen[] ...
                    final List<AnnotationEntryGen> mutable = makeMutableVersion(immutableArray.getAnnotationEntries());
                    // ... then add these to any we already know about
                    param_annotations[j].addAll(mutable);
                }
            }
        }
        if (paramAnnVisAttr != null) {
            removeAttribute(paramAnnVisAttr);
        }
        if (paramAnnInvisAttr != null) {
            removeAttribute(paramAnnInvisAttr);
        }
        haveUnpackedParameterAnnotations = true;
    }

    private List<AnnotationEntryGen> makeMutableVersion(final AnnotationEntry[] mutableArray)
    {
        final List<AnnotationEntryGen> result = new ArrayList<>();
        for (final AnnotationEntry element : mutableArray) {
            result.add(new AnnotationEntryGen(element, getConstantPool(),
                    false));
        }
        return result;
    }

    public void addParameterAnnotation(final int parameterIndex,
            final AnnotationEntryGen annotation)
    {
        ensureExistingParameterAnnotationsUnpacked();
        if (!hasParameterAnnotations)
        {
            @SuppressWarnings("unchecked") // OK
            final List<AnnotationEntryGen>[] parmList = new List[arg_types.length];
            param_annotations = parmList;
            hasParameterAnnotations = true;
        }
        final List<AnnotationEntryGen> existingAnnotations = param_annotations[parameterIndex];
        if (existingAnnotations != null)
        {
            existingAnnotations.add(annotation);
        }
        else
        {
            final List<AnnotationEntryGen> l = new ArrayList<>();
            l.add(annotation);
            param_annotations[parameterIndex] = l;
        }
    }




    /**
     * @return Comparison strategy object
     */
    public static BCELComparator getComparator() {
        return bcelComparator;
    }


    /**
     * @param comparator Comparison strategy object
     */
    public static void setComparator( final BCELComparator comparator ) {
        bcelComparator = comparator;
    }


    /**
     * Return value as defined by given BCELComparator strategy.
     * By default two MethodGen objects are said to be equal when
     * their names and signatures are equal.
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals( final Object obj ) {
        return bcelComparator.equals(this, obj);
    }


    /**
     * Return value as defined by given BCELComparator strategy.
     * By default return the hashcode of the method's name XOR signature.
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return bcelComparator.hashCode(this);
    }
}