rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeParser.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 10 Jul 2014 08:17:52 +0200
branchjdk8
changeset 1641 2111057af3b2
parent 1640 f61e9984adff
child 1642 c178e0bdce5d
permissions -rw-r--r--
Filling in the constant pool
     1 /*
     2  * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 package org.apidesign.vm4brwsr;
    26 
    27 import java.io.ByteArrayInputStream;
    28 import java.io.DataInputStream;
    29 import java.io.IOException;
    30 import java.io.InputStream;
    31 import java.util.Arrays;
    32 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    33 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
    34 
    35 /** This is a byte code parser heavily based on original code of JavaP utility.
    36  * As such I decided to keep the original Oracle's GPLv2 header.
    37  *
    38  * @author Jaroslav Tulach <jtulach@netbeans.org>
    39  */
    40 final class ByteCodeParser {
    41     private ByteCodeParser() {
    42     }
    43 
    44     /* Class File Constants */
    45     public static final int JAVA_MAGIC                   = 0xcafebabe;
    46     public static final int JAVA_VERSION                 = 45;
    47     public static final int JAVA_MINOR_VERSION           = 3;
    48 
    49     /* Constant table */
    50     public static final int CONSTANT_UTF8                = 1;
    51     public static final int CONSTANT_UNICODE             = 2;
    52     public static final int CONSTANT_INTEGER             = 3;
    53     public static final int CONSTANT_FLOAT               = 4;
    54     public static final int CONSTANT_LONG                = 5;
    55     public static final int CONSTANT_DOUBLE              = 6;
    56     public static final int CONSTANT_CLASS               = 7;
    57     public static final int CONSTANT_STRING              = 8;
    58     public static final int CONSTANT_FIELD               = 9;
    59     public static final int CONSTANT_METHOD              = 10;
    60     public static final int CONSTANT_INTERFACEMETHOD     = 11;
    61     public static final int CONSTANT_NAMEANDTYPE         = 12;
    62     public static final int CONSTANT_METHODHANDLE     = 15;
    63     public static final int CONSTANT_METHODTYPE     = 16;
    64     public static final int CONSTANT_INVOKEDYNAMIC     = 18;
    65 
    66     /* Access Flags */
    67     public static final int ACC_PUBLIC                   = 0x00000001;
    68     public static final int ACC_PRIVATE                  = 0x00000002;
    69     public static final int ACC_PROTECTED                = 0x00000004;
    70     public static final int ACC_STATIC                   = 0x00000008;
    71     public static final int ACC_FINAL                    = 0x00000010;
    72     public static final int ACC_SYNCHRONIZED             = 0x00000020;
    73     public static final int ACC_SUPER                        = 0x00000020;
    74     public static final int ACC_VOLATILE                 = 0x00000040;
    75     public static final int ACC_TRANSIENT                = 0x00000080;
    76     public static final int ACC_NATIVE                   = 0x00000100;
    77     public static final int ACC_INTERFACE                = 0x00000200;
    78     public static final int ACC_ABSTRACT                 = 0x00000400;
    79     public static final int ACC_STRICT                   = 0x00000800;
    80     public static final int ACC_EXPLICIT                 = 0x00001000;
    81     public static final int ACC_SYNTHETIC                = 0x00010000; // actually, this is an attribute
    82 
    83     /* Type codes for StackMap attribute */
    84     public static final int ITEM_Bogus      =0; // an unknown or uninitialized value
    85     public static final int ITEM_Integer    =1; // a 32-bit integer
    86     public static final int ITEM_Float      =2; // not used
    87     public static final int ITEM_Double     =3; // not used
    88     public static final int ITEM_Long       =4; // a 64-bit integer
    89     public static final int ITEM_Null       =5; // the type of null
    90     public static final int ITEM_InitObject =6; // "this" in constructor
    91     public static final int ITEM_Object     =7; // followed by 2-byte index of class name
    92     public static final int ITEM_NewObject  =8; // followed by 2-byte ref to "new"
    93 
    94     /* Constants used in StackMapTable attribute */
    95     public static final int SAME_FRAME_BOUND                  = 64;
    96     public static final int SAME_LOCALS_1_STACK_ITEM_BOUND    = 128;
    97     public static final int SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247;
    98     public static final int SAME_FRAME_EXTENDED               = 251;
    99     public static final int FULL_FRAME                        = 255;
   100 
   101     /* Opcodes */
   102     public static final int opc_dead                     = -2;
   103     public static final int opc_label                    = -1;
   104     public static final int opc_nop                      = 0;
   105     public static final int opc_aconst_null              = 1;
   106     public static final int opc_iconst_m1                = 2;
   107     public static final int opc_iconst_0                 = 3;
   108     public static final int opc_iconst_1                 = 4;
   109     public static final int opc_iconst_2                 = 5;
   110     public static final int opc_iconst_3                 = 6;
   111     public static final int opc_iconst_4                 = 7;
   112     public static final int opc_iconst_5                 = 8;
   113     public static final int opc_lconst_0                 = 9;
   114     public static final int opc_lconst_1                 = 10;
   115     public static final int opc_fconst_0                 = 11;
   116     public static final int opc_fconst_1                 = 12;
   117     public static final int opc_fconst_2                 = 13;
   118     public static final int opc_dconst_0                 = 14;
   119     public static final int opc_dconst_1                 = 15;
   120     public static final int opc_bipush                   = 16;
   121     public static final int opc_sipush                   = 17;
   122     public static final int opc_ldc                      = 18;
   123     public static final int opc_ldc_w                    = 19;
   124     public static final int opc_ldc2_w                   = 20;
   125     public static final int opc_iload                    = 21;
   126     public static final int opc_lload                    = 22;
   127     public static final int opc_fload                    = 23;
   128     public static final int opc_dload                    = 24;
   129     public static final int opc_aload                    = 25;
   130     public static final int opc_iload_0                  = 26;
   131     public static final int opc_iload_1                  = 27;
   132     public static final int opc_iload_2                  = 28;
   133     public static final int opc_iload_3                  = 29;
   134     public static final int opc_lload_0                  = 30;
   135     public static final int opc_lload_1                  = 31;
   136     public static final int opc_lload_2                  = 32;
   137     public static final int opc_lload_3                  = 33;
   138     public static final int opc_fload_0                  = 34;
   139     public static final int opc_fload_1                  = 35;
   140     public static final int opc_fload_2                  = 36;
   141     public static final int opc_fload_3                  = 37;
   142     public static final int opc_dload_0                  = 38;
   143     public static final int opc_dload_1                  = 39;
   144     public static final int opc_dload_2                  = 40;
   145     public static final int opc_dload_3                  = 41;
   146     public static final int opc_aload_0                  = 42;
   147     public static final int opc_aload_1                  = 43;
   148     public static final int opc_aload_2                  = 44;
   149     public static final int opc_aload_3                  = 45;
   150     public static final int opc_iaload                   = 46;
   151     public static final int opc_laload                   = 47;
   152     public static final int opc_faload                   = 48;
   153     public static final int opc_daload                   = 49;
   154     public static final int opc_aaload                   = 50;
   155     public static final int opc_baload                   = 51;
   156     public static final int opc_caload                   = 52;
   157     public static final int opc_saload                   = 53;
   158     public static final int opc_istore                   = 54;
   159     public static final int opc_lstore                   = 55;
   160     public static final int opc_fstore                   = 56;
   161     public static final int opc_dstore                   = 57;
   162     public static final int opc_astore                   = 58;
   163     public static final int opc_istore_0                 = 59;
   164     public static final int opc_istore_1                 = 60;
   165     public static final int opc_istore_2                 = 61;
   166     public static final int opc_istore_3                 = 62;
   167     public static final int opc_lstore_0                 = 63;
   168     public static final int opc_lstore_1                 = 64;
   169     public static final int opc_lstore_2                 = 65;
   170     public static final int opc_lstore_3                 = 66;
   171     public static final int opc_fstore_0                 = 67;
   172     public static final int opc_fstore_1                 = 68;
   173     public static final int opc_fstore_2                 = 69;
   174     public static final int opc_fstore_3                 = 70;
   175     public static final int opc_dstore_0                 = 71;
   176     public static final int opc_dstore_1                 = 72;
   177     public static final int opc_dstore_2                 = 73;
   178     public static final int opc_dstore_3                 = 74;
   179     public static final int opc_astore_0                 = 75;
   180     public static final int opc_astore_1                 = 76;
   181     public static final int opc_astore_2                 = 77;
   182     public static final int opc_astore_3                 = 78;
   183     public static final int opc_iastore                  = 79;
   184     public static final int opc_lastore                  = 80;
   185     public static final int opc_fastore                  = 81;
   186     public static final int opc_dastore                  = 82;
   187     public static final int opc_aastore                  = 83;
   188     public static final int opc_bastore                  = 84;
   189     public static final int opc_castore                  = 85;
   190     public static final int opc_sastore                  = 86;
   191     public static final int opc_pop                      = 87;
   192     public static final int opc_pop2                     = 88;
   193     public static final int opc_dup                      = 89;
   194     public static final int opc_dup_x1                   = 90;
   195     public static final int opc_dup_x2                   = 91;
   196     public static final int opc_dup2                     = 92;
   197     public static final int opc_dup2_x1                  = 93;
   198     public static final int opc_dup2_x2                  = 94;
   199     public static final int opc_swap                     = 95;
   200     public static final int opc_iadd                     = 96;
   201     public static final int opc_ladd                     = 97;
   202     public static final int opc_fadd                     = 98;
   203     public static final int opc_dadd                     = 99;
   204     public static final int opc_isub                     = 100;
   205     public static final int opc_lsub                     = 101;
   206     public static final int opc_fsub                     = 102;
   207     public static final int opc_dsub                     = 103;
   208     public static final int opc_imul                     = 104;
   209     public static final int opc_lmul                     = 105;
   210     public static final int opc_fmul                     = 106;
   211     public static final int opc_dmul                     = 107;
   212     public static final int opc_idiv                     = 108;
   213     public static final int opc_ldiv                     = 109;
   214     public static final int opc_fdiv                     = 110;
   215     public static final int opc_ddiv                     = 111;
   216     public static final int opc_irem                     = 112;
   217     public static final int opc_lrem                     = 113;
   218     public static final int opc_frem                     = 114;
   219     public static final int opc_drem                     = 115;
   220     public static final int opc_ineg                     = 116;
   221     public static final int opc_lneg                     = 117;
   222     public static final int opc_fneg                     = 118;
   223     public static final int opc_dneg                     = 119;
   224     public static final int opc_ishl                     = 120;
   225     public static final int opc_lshl                     = 121;
   226     public static final int opc_ishr                     = 122;
   227     public static final int opc_lshr                     = 123;
   228     public static final int opc_iushr                    = 124;
   229     public static final int opc_lushr                    = 125;
   230     public static final int opc_iand                     = 126;
   231     public static final int opc_land                     = 127;
   232     public static final int opc_ior                      = 128;
   233     public static final int opc_lor                      = 129;
   234     public static final int opc_ixor                     = 130;
   235     public static final int opc_lxor                     = 131;
   236     public static final int opc_iinc                     = 132;
   237     public static final int opc_i2l                      = 133;
   238     public static final int opc_i2f                      = 134;
   239     public static final int opc_i2d                      = 135;
   240     public static final int opc_l2i                      = 136;
   241     public static final int opc_l2f                      = 137;
   242     public static final int opc_l2d                      = 138;
   243     public static final int opc_f2i                      = 139;
   244     public static final int opc_f2l                      = 140;
   245     public static final int opc_f2d                      = 141;
   246     public static final int opc_d2i                      = 142;
   247     public static final int opc_d2l                      = 143;
   248     public static final int opc_d2f                      = 144;
   249     public static final int opc_i2b                      = 145;
   250     public static final int opc_int2byte                 = 145;
   251     public static final int opc_i2c                      = 146;
   252     public static final int opc_int2char                 = 146;
   253     public static final int opc_i2s                      = 147;
   254     public static final int opc_int2short                = 147;
   255     public static final int opc_lcmp                     = 148;
   256     public static final int opc_fcmpl                    = 149;
   257     public static final int opc_fcmpg                    = 150;
   258     public static final int opc_dcmpl                    = 151;
   259     public static final int opc_dcmpg                    = 152;
   260     public static final int opc_ifeq                     = 153;
   261     public static final int opc_ifne                     = 154;
   262     public static final int opc_iflt                     = 155;
   263     public static final int opc_ifge                     = 156;
   264     public static final int opc_ifgt                     = 157;
   265     public static final int opc_ifle                     = 158;
   266     public static final int opc_if_icmpeq                = 159;
   267     public static final int opc_if_icmpne                = 160;
   268     public static final int opc_if_icmplt                = 161;
   269     public static final int opc_if_icmpge                = 162;
   270     public static final int opc_if_icmpgt                = 163;
   271     public static final int opc_if_icmple                = 164;
   272     public static final int opc_if_acmpeq                = 165;
   273     public static final int opc_if_acmpne                = 166;
   274     public static final int opc_goto                     = 167;
   275     public static final int opc_jsr                      = 168;
   276     public static final int opc_ret                      = 169;
   277     public static final int opc_tableswitch              = 170;
   278     public static final int opc_lookupswitch             = 171;
   279     public static final int opc_ireturn                  = 172;
   280     public static final int opc_lreturn                  = 173;
   281     public static final int opc_freturn                  = 174;
   282     public static final int opc_dreturn                  = 175;
   283     public static final int opc_areturn                  = 176;
   284     public static final int opc_return                   = 177;
   285     public static final int opc_getstatic                = 178;
   286     public static final int opc_putstatic                = 179;
   287     public static final int opc_getfield                 = 180;
   288     public static final int opc_putfield                 = 181;
   289     public static final int opc_invokevirtual            = 182;
   290     public static final int opc_invokenonvirtual         = 183;
   291     public static final int opc_invokespecial            = 183;
   292     public static final int opc_invokestatic             = 184;
   293     public static final int opc_invokeinterface          = 185;
   294     public static final int opc_invokedynamic            = 186;
   295     public static final int opc_new                      = 187;
   296     public static final int opc_newarray                 = 188;
   297     public static final int opc_anewarray                = 189;
   298     public static final int opc_arraylength              = 190;
   299     public static final int opc_athrow                   = 191;
   300     public static final int opc_checkcast                = 192;
   301     public static final int opc_instanceof               = 193;
   302     public static final int opc_monitorenter             = 194;
   303     public static final int opc_monitorexit              = 195;
   304     public static final int opc_wide                     = 196;
   305     public static final int opc_multianewarray           = 197;
   306     public static final int opc_ifnull                   = 198;
   307     public static final int opc_ifnonnull                = 199;
   308     public static final int opc_goto_w                   = 200;
   309     public static final int opc_jsr_w                    = 201;
   310         /* Pseudo-instructions */
   311     public static final int opc_bytecode                 = 203;
   312     public static final int opc_try                      = 204;
   313     public static final int opc_endtry                   = 205;
   314     public static final int opc_catch                    = 206;
   315     public static final int opc_var                      = 207;
   316     public static final int opc_endvar                   = 208;
   317     public static final int opc_localsmap                = 209;
   318     public static final int opc_stackmap                 = 210;
   319         /* PicoJava prefixes */
   320     public static final int opc_nonpriv                  = 254;
   321     public static final int opc_priv                     = 255;
   322 
   323         /* Wide instructions *
   324     public static final int opc_iload_w         = (opc_wide<<8)|opc_iload;
   325     public static final int opc_lload_w         = (opc_wide<<8)|opc_lload;
   326     public static final int opc_fload_w         = (opc_wide<<8)|opc_fload;
   327     public static final int opc_dload_w         = (opc_wide<<8)|opc_dload;
   328     public static final int opc_aload_w         = (opc_wide<<8)|opc_aload;
   329     public static final int opc_istore_w        = (opc_wide<<8)|opc_istore;
   330     public static final int opc_lstore_w        = (opc_wide<<8)|opc_lstore;
   331     public static final int opc_fstore_w        = (opc_wide<<8)|opc_fstore;
   332     public static final int opc_dstore_w        = (opc_wide<<8)|opc_dstore;
   333     public static final int opc_astore_w        = (opc_wide<<8)|opc_astore;
   334     public static final int opc_ret_w           = (opc_wide<<8)|opc_ret;
   335     public static final int opc_iinc_w          = (opc_wide<<8)|opc_iinc;
   336 */
   337     static class AnnotationParser {
   338 
   339         private final boolean textual;
   340         private final boolean iterateArray;
   341 
   342         protected AnnotationParser(boolean textual, boolean iterateArray) {
   343             this.textual = textual;
   344             this.iterateArray = iterateArray;
   345         }
   346 
   347         protected void visitAnnotationStart(String type, boolean top) throws IOException {
   348         }
   349 
   350         protected void visitAnnotationEnd(String type, boolean top) throws IOException {
   351         }
   352 
   353         protected void visitValueStart(String attrName, char type) throws IOException {
   354         }
   355 
   356         protected void visitValueEnd(String attrName, char type) throws IOException {
   357         }
   358 
   359         protected void visitAttr(
   360             String annoType, String attr, String attrType, String value) throws IOException {
   361         }
   362 
   363         protected void visitEnumAttr(
   364             String annoType, String attr, String attrType, String value) throws IOException {
   365             visitAttr(annoType, attr, attrType, value);
   366         }
   367 
   368         /**
   369          * Initialize the parsing with constant pool from
   370          * <code>cd</code>.
   371          *
   372          * @param attr the attribute defining annotations
   373          * @param cd constant pool
   374          * @throws IOException in case I/O fails
   375          */
   376         public final void parse(byte[] attr, ClassData cd) throws IOException {
   377             ByteArrayInputStream is = new ByteArrayInputStream(attr);
   378             DataInputStream dis = new DataInputStream(is);
   379             try {
   380                 read(dis, cd);
   381             } finally {
   382                 is.close();
   383             }
   384         }
   385 
   386         private void read(DataInputStream dis, ClassData cd) throws IOException {
   387             int cnt = dis.readUnsignedShort();
   388             for (int i = 0; i < cnt; i++) {
   389                 readAnno(dis, cd, true);
   390             }
   391         }
   392 
   393         private void readAnno(DataInputStream dis, ClassData cd, boolean top) throws IOException {
   394             int type = dis.readUnsignedShort();
   395             String typeName = cd.StringValue(type);
   396             visitAnnotationStart(typeName, top);
   397             int cnt = dis.readUnsignedShort();
   398             for (int i = 0; i < cnt; i++) {
   399                 String attrName = cd.StringValue(dis.readUnsignedShort());
   400                 readValue(dis, cd, typeName, attrName);
   401             }
   402             visitAnnotationEnd(typeName, top);
   403             if (cnt == 0) {
   404                 visitAttr(typeName, null, null, null);
   405             }
   406         }
   407 
   408         private void readValue(
   409             DataInputStream dis, ClassData cd, String typeName, String attrName) throws IOException {
   410             char type = (char) dis.readByte();
   411             visitValueStart(attrName, type);
   412             if (type == '@') {
   413                 readAnno(dis, cd, false);
   414             } else if ("CFJZsSIDB".indexOf(type) >= 0) { // NOI18N
   415                 int primitive = dis.readUnsignedShort();
   416                 String val = cd.stringValue(primitive, textual);
   417                 String attrType;
   418                 if (type == 's') {
   419                     attrType = "Ljava_lang_String_2";
   420                     if (textual) {
   421                         val = '"' + val + '"';
   422                     }
   423                 } else {
   424                     attrType = "" + type;
   425                 }
   426                 visitAttr(typeName, attrName, attrType, val);
   427             } else if (type == 'c') {
   428                 int cls = dis.readUnsignedShort();
   429             } else if (type == '[') {
   430                 int cnt = dis.readUnsignedShort();
   431                 for (int i = 0; i < cnt; i++) {
   432                     readValue(dis, cd, typeName, iterateArray ? attrName : null);
   433                 }
   434             } else if (type == 'e') {
   435                 int enumT = dis.readUnsignedShort();
   436                 String attrType = cd.stringValue(enumT, textual);
   437                 int enumN = dis.readUnsignedShort();
   438                 String val = cd.stringValue(enumN, textual);
   439                 visitEnumAttr(typeName, attrName, attrType, val);
   440             } else {
   441                 throw new IOException("Unknown type " + type);
   442             }
   443             visitValueEnd(attrName, type);
   444         }
   445     }
   446     
   447     /**
   448      * Reads and stores attribute information.
   449      *
   450      * @author Sucheta Dambalkar (Adopted code from jdis)
   451      */
   452     private static class AttrData {
   453 
   454         ClassData cls;
   455         int name_cpx;
   456         int datalen;
   457         byte data[];
   458 
   459         public AttrData(ClassData cls) {
   460             this.cls = cls;
   461         }
   462 
   463         /**
   464          * Reads unknown attribute.
   465          */
   466         public void read(int name_cpx, DataInputStream in) throws IOException {
   467             this.name_cpx = name_cpx;
   468             datalen = in.readInt();
   469             data = new byte[datalen];
   470             in.readFully(data);
   471         }
   472 
   473         /**
   474          * Reads just the name of known attribute.
   475          */
   476         public void read(int name_cpx) {
   477             this.name_cpx = name_cpx;
   478         }
   479 
   480         /**
   481          * Returns attribute name.
   482          */
   483         public String getAttrName() {
   484             return cls.getString(name_cpx);
   485         }
   486 
   487         /**
   488          * Returns attribute data.
   489          */
   490         public byte[] getData() {
   491             return data;
   492         }
   493     }
   494 
   495     /**
   496      * Stores constant pool entry information with one field.
   497      *
   498      * @author Sucheta Dambalkar (Adopted code from jdis)
   499      */
   500     private static class CPX {
   501 
   502         int cpx;
   503 
   504         CPX(int cpx) {
   505             this.cpx = cpx;
   506         }
   507     }
   508 
   509     /**
   510      * Stores constant pool entry information with two fields.
   511      *
   512      * @author Sucheta Dambalkar (Adopted code from jdis)
   513      */
   514     private static class CPX2 {
   515 
   516         int cpx1, cpx2;
   517 
   518         CPX2(int cpx1, int cpx2) {
   519             this.cpx1 = cpx1;
   520             this.cpx2 = cpx2;
   521         }
   522     }
   523 
   524     /**
   525      * Central data repository of the Java Disassembler. Stores all the
   526      * information in java class file.
   527      *
   528      * @author Sucheta Dambalkar (Adopted code from jdis)
   529      */
   530     static final class ClassData {
   531 
   532         private int magic;
   533         private int minor_version;
   534         private int major_version;
   535         private int cpool_count;
   536         private Object cpool[];
   537         private int access;
   538         private int this_class = 0;
   539         private int super_class;
   540         private int interfaces_count;
   541         private int[] interfaces = new int[0];
   542         private FieldData[] fields;
   543         private MethodData[] methods;
   544         private InnerClassData[] innerClasses;
   545         private int attributes_count;
   546         private AttrData[] attrs;
   547         private int source_cpx = 0;
   548         private byte tags[];
   549         private Hashtable indexHashAscii = new Hashtable();
   550         private String pkgPrefix = "";
   551         private int pkgPrefixLen = 0;
   552 
   553         /**
   554          * Read classfile to disassemble.
   555          */
   556         public ClassData(InputStream infile) throws IOException {
   557             this.read(new DataInputStream(infile));
   558         }
   559 
   560         /**
   561          * Reads and stores class file information.
   562          */
   563         public void read(DataInputStream in) throws IOException {
   564             // Read the header
   565             magic = in.readInt();
   566             if (magic != JAVA_MAGIC) {
   567                 throw new ClassFormatError("wrong magic: "
   568                     + toHex(magic) + ", expected "
   569                     + toHex(JAVA_MAGIC));
   570             }
   571             minor_version = in.readShort();
   572             major_version = in.readShort();
   573             if (major_version != JAVA_VERSION) {
   574             }
   575 
   576             // Read the constant pool
   577             readCP(in);
   578             access = in.readUnsignedShort();
   579             this_class = in.readUnsignedShort();
   580             super_class = in.readUnsignedShort();
   581 
   582             //Read interfaces.
   583             interfaces_count = in.readUnsignedShort();
   584             if (interfaces_count > 0) {
   585                 interfaces = new int[interfaces_count];
   586             }
   587             for (int i = 0; i < interfaces_count; i++) {
   588                 interfaces[i] = in.readShort();
   589             }
   590 
   591             // Read the fields
   592             readFields(in);
   593 
   594             // Read the methods
   595             readMethods(in);
   596 
   597             // Read the attributes
   598             attributes_count = in.readUnsignedShort();
   599             attrs = new AttrData[attributes_count];
   600             for (int k = 0; k < attributes_count; k++) {
   601                 int name_cpx = in.readUnsignedShort();
   602                 if (getTag(name_cpx) == CONSTANT_UTF8
   603                     && getString(name_cpx).equals("SourceFile")) {
   604                     if (in.readInt() != 2) {
   605                         throw new ClassFormatError("invalid attr length");
   606                     }
   607                     source_cpx = in.readUnsignedShort();
   608                     AttrData attr = new AttrData(this);
   609                     attr.read(name_cpx);
   610                     attrs[k] = attr;
   611 
   612                 } else if (getTag(name_cpx) == CONSTANT_UTF8
   613                     && getString(name_cpx).equals("InnerClasses")) {
   614                     int length = in.readInt();
   615                     int num = in.readUnsignedShort();
   616                     if (2 + num * 8 != length) {
   617                         throw new ClassFormatError("invalid attr length");
   618                     }
   619                     innerClasses = new InnerClassData[num];
   620                     for (int j = 0; j < num; j++) {
   621                         InnerClassData innerClass = new InnerClassData(this);
   622                         innerClass.read(in);
   623                         innerClasses[j] = innerClass;
   624                     }
   625                     AttrData attr = new AttrData(this);
   626                     attr.read(name_cpx);
   627                     attrs[k] = attr;
   628                 } else if (getTag(name_cpx) == CONSTANT_UTF8
   629                     && getString(name_cpx).equals("BootstrapMethods")) {
   630                     AttrData attr = new AttrData(this);
   631                     readBootstrapMethods(in);
   632                     attr.read(name_cpx);
   633                     attrs[k] = attr;
   634                 } else {
   635                     AttrData attr = new AttrData(this);
   636                     attr.read(name_cpx, in);
   637                     attrs[k] = attr;
   638                 }
   639             }
   640             in.close();
   641         } // end ClassData.read()
   642 
   643         void readBootstrapMethods(DataInputStream in) throws IOException {
   644             int attr_len = in.readInt();  //attr_length
   645             int number = in.readShort();
   646             for (int i = 0; i < number; i++) {
   647                 int ref = in.readShort();
   648                 int len = in.readShort();
   649                 int[] args = new int[len];
   650                 for (int j = 0; j < len; j++) {
   651                     args[j] = in.readShort();
   652                 }
   653                 
   654                 System.err.print("ref: " + ref + " len: " + len + ":");
   655                 for (int j = 0; j < len; j++) {
   656                     System.err.print(" " + args[j]);
   657                 }
   658                 System.err.println();
   659             }
   660         }
   661         
   662         /**
   663          * Reads and stores constant pool info.
   664          */
   665         void readCP(DataInputStream in) throws IOException {
   666             cpool_count = in.readUnsignedShort();
   667             tags = new byte[cpool_count];
   668             cpool = new Object[cpool_count];
   669             for (int i = 1; i < cpool_count; i++) {
   670                 byte tag = in.readByte();
   671 
   672                 switch (tags[i] = tag) {
   673                     case CONSTANT_UTF8:
   674                         String str = in.readUTF();
   675                         indexHashAscii.put(cpool[i] = str, new Integer(i));
   676                         break;
   677                     case CONSTANT_INTEGER:
   678                         cpool[i] = new Integer(in.readInt());
   679                         break;
   680                     case CONSTANT_FLOAT:
   681                         cpool[i] = new Float(in.readFloat());
   682                         break;
   683                     case CONSTANT_LONG:
   684                         cpool[i++] = new Long(in.readLong());
   685                         break;
   686                     case CONSTANT_DOUBLE:
   687                         cpool[i++] = new Double(in.readDouble());
   688                         break;
   689                     case CONSTANT_CLASS:
   690                     case CONSTANT_STRING:
   691                         cpool[i] = new CPX(in.readUnsignedShort());
   692                         break;
   693 
   694                     case CONSTANT_FIELD:
   695                     case CONSTANT_METHOD:
   696                     case CONSTANT_INTERFACEMETHOD:
   697                     case CONSTANT_NAMEANDTYPE:
   698                         cpool[i] = new CPX2(in.readUnsignedShort(), in.readUnsignedShort());
   699                         break;
   700                     case CONSTANT_METHODHANDLE:
   701                         cpool[i] = new CPX2(in.readByte(), in.readUnsignedShort());
   702                         break;
   703                     case CONSTANT_METHODTYPE:
   704                         cpool[i] = new CPX(in.readUnsignedShort());
   705                         break;
   706                     case CONSTANT_INVOKEDYNAMIC:
   707                         cpool[i] = new CPX2(in.readUnsignedShort(), in.readUnsignedShort());
   708                         break;
   709                     case 0:
   710                     default:
   711                         throw new ClassFormatError("invalid constant type: " + (int) tags[i]);
   712                 }
   713             }
   714         }
   715 
   716         /**
   717          * Reads and strores field info.
   718          */
   719         protected void readFields(DataInputStream in) throws IOException {
   720             int fields_count = in.readUnsignedShort();
   721             fields = new FieldData[fields_count];
   722             for (int k = 0; k < fields_count; k++) {
   723                 FieldData field = new FieldData(this);
   724                 field.read(in);
   725                 fields[k] = field;
   726             }
   727         }
   728 
   729         /**
   730          * Reads and strores Method info.
   731          */
   732         protected void readMethods(DataInputStream in) throws IOException {
   733             int methods_count = in.readUnsignedShort();
   734             methods = new MethodData[methods_count];
   735             for (int k = 0; k < methods_count; k++) {
   736                 MethodData method = new MethodData(this);
   737                 method.read(in);
   738                 methods[k] = method;
   739             }
   740         }
   741 
   742         /**
   743          * get a string
   744          */
   745         public String getString(int n) {
   746             if (n == 0) {
   747                 return null;
   748             } else {
   749                 return (String) cpool[n];
   750             }
   751         }
   752 
   753         /**
   754          * get the type of constant given an index
   755          */
   756         public byte getTag(int n) {
   757             try {
   758                 return tags[n];
   759             } catch (ArrayIndexOutOfBoundsException e) {
   760                 return (byte) 100;
   761             }
   762         }
   763         static final String hexString = "0123456789ABCDEF";
   764         public static char hexTable[] = hexString.toCharArray();
   765 
   766         static String toHex(long val, int width) {
   767             StringBuffer s = new StringBuffer();
   768             for (int i = width - 1; i >= 0; i--) {
   769                 s.append(hexTable[((int) (val >> (4 * i))) & 0xF]);
   770             }
   771             return "0x" + s.toString();
   772         }
   773 
   774         static String toHex(long val) {
   775             int width;
   776             for (width = 16; width > 0; width--) {
   777                 if ((val >> (width - 1) * 4) != 0) {
   778                     break;
   779                 }
   780             }
   781             return toHex(val, width);
   782         }
   783 
   784         static String toHex(int val) {
   785             int width;
   786             for (width = 8; width > 0; width--) {
   787                 if ((val >> (width - 1) * 4) != 0) {
   788                     break;
   789                 }
   790             }
   791             return toHex(val, width);
   792         }
   793 
   794         /**
   795          * Returns the name of this class.
   796          */
   797         public String getClassName() {
   798             String res = null;
   799             if (this_class == 0) {
   800                 return res;
   801             }
   802             int tcpx;
   803             try {
   804                 if (tags[this_class] != CONSTANT_CLASS) {
   805                     return res; //"<CP["+cpx+"] is not a Class> ";
   806                 }
   807                 tcpx = ((CPX) cpool[this_class]).cpx;
   808             } catch (ArrayIndexOutOfBoundsException e) {
   809                 return res; // "#"+cpx+"// invalid constant pool index";
   810             } catch (Throwable e) {
   811                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   812             }
   813 
   814             try {
   815                 return (String) (cpool[tcpx]);
   816             } catch (ArrayIndexOutOfBoundsException e) {
   817                 return res; // "class #"+scpx+"// invalid constant pool index";
   818             } catch (ClassCastException e) {
   819                 return res; // "class #"+scpx+"// invalid constant pool reference";
   820             } catch (Throwable e) {
   821                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   822             }
   823 
   824         }
   825 
   826         /**
   827          * Returns the name of class at perticular index.
   828          */
   829         public String getClassName(int cpx) {
   830             String res = "#" + cpx;
   831             if (cpx == 0) {
   832                 return res;
   833             }
   834             int scpx;
   835             try {
   836                 if (tags[cpx] != CONSTANT_CLASS) {
   837                     return res; //"<CP["+cpx+"] is not a Class> ";
   838                 }
   839                 scpx = ((CPX) cpool[cpx]).cpx;
   840             } catch (ArrayIndexOutOfBoundsException e) {
   841                 return res; // "#"+cpx+"// invalid constant pool index";
   842             } catch (Throwable e) {
   843                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   844             }
   845             res = "#" + scpx;
   846             try {
   847                 return (String) (cpool[scpx]);
   848             } catch (ArrayIndexOutOfBoundsException e) {
   849                 return res; // "class #"+scpx+"// invalid constant pool index";
   850             } catch (ClassCastException e) {
   851                 return res; // "class #"+scpx+"// invalid constant pool reference";
   852             } catch (Throwable e) {
   853                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   854             }
   855         }
   856 
   857         public int getAccessFlags() {
   858             return access;
   859         }
   860 
   861         /**
   862          * Returns true if it is a class
   863          */
   864         public boolean isClass() {
   865             if ((access & ACC_INTERFACE) == 0) {
   866                 return true;
   867             }
   868             return false;
   869         }
   870 
   871         /**
   872          * Returns true if it is a interface.
   873          */
   874         public boolean isInterface() {
   875             if ((access & ACC_INTERFACE) != 0) {
   876                 return true;
   877             }
   878             return false;
   879         }
   880 
   881         /**
   882          * Returns true if this member is public, false otherwise.
   883          */
   884         public boolean isPublic() {
   885             return (access & ACC_PUBLIC) != 0;
   886         }
   887 
   888         /**
   889          * Returns the access of this class or interface.
   890          */
   891         public String[] getAccess() {
   892             Vector v = new Vector();
   893             if ((access & ACC_PUBLIC) != 0) {
   894                 v.addElement("public");
   895             }
   896             if ((access & ACC_FINAL) != 0) {
   897                 v.addElement("final");
   898             }
   899             if ((access & ACC_ABSTRACT) != 0) {
   900                 v.addElement("abstract");
   901             }
   902             String[] accflags = new String[v.size()];
   903             v.copyInto(accflags);
   904             return accflags;
   905         }
   906 
   907         /**
   908          * Returns list of innerclasses.
   909          */
   910         public InnerClassData[] getInnerClasses() {
   911             return innerClasses;
   912         }
   913 
   914         /**
   915          * Returns list of attributes.
   916          */
   917         final AttrData[] getAttributes() {
   918             return attrs;
   919         }
   920 
   921         public byte[] findAnnotationData(boolean classRetention) {
   922             String n = classRetention
   923                 ? "RuntimeInvisibleAnnotations" : // NOI18N
   924                 "RuntimeVisibleAnnotations"; // NOI18N
   925             return findAttr(n, attrs);
   926         }
   927 
   928         /**
   929          * Returns true if superbit is set.
   930          */
   931         public boolean isSuperSet() {
   932             if ((access & ACC_SUPER) != 0) {
   933                 return true;
   934             }
   935             return false;
   936         }
   937 
   938         /**
   939          * Returns super class name.
   940          */
   941         public String getSuperClassName() {
   942             String res = null;
   943             if (super_class == 0) {
   944                 return res;
   945             }
   946             int scpx;
   947             try {
   948                 if (tags[super_class] != CONSTANT_CLASS) {
   949                     return res; //"<CP["+cpx+"] is not a Class> ";
   950                 }
   951                 scpx = ((CPX) cpool[super_class]).cpx;
   952             } catch (ArrayIndexOutOfBoundsException e) {
   953                 return res; // "#"+cpx+"// invalid constant pool index";
   954             } catch (Throwable e) {
   955                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   956             }
   957 
   958             try {
   959                 return (String) (cpool[scpx]);
   960             } catch (ArrayIndexOutOfBoundsException e) {
   961                 return res; // "class #"+scpx+"// invalid constant pool index";
   962             } catch (ClassCastException e) {
   963                 return res; // "class #"+scpx+"// invalid constant pool reference";
   964             } catch (Throwable e) {
   965                 return res; // "#"+cpx+"// ERROR IN DISASSEMBLER";
   966             }
   967         }
   968 
   969         /**
   970          * Returns list of super interfaces.
   971          */
   972         public String[] getSuperInterfaces() {
   973             String interfacenames[] = new String[interfaces.length];
   974             int interfacecpx = -1;
   975             for (int i = 0; i < interfaces.length; i++) {
   976                 interfacecpx = ((CPX) cpool[interfaces[i]]).cpx;
   977                 interfacenames[i] = (String) (cpool[interfacecpx]);
   978             }
   979             return interfacenames;
   980         }
   981 
   982         /**
   983          * Returns string at prticular constant pool index.
   984          */
   985         public String getStringValue(int cpoolx) {
   986             try {
   987                 return ((String) cpool[cpoolx]);
   988             } catch (ArrayIndexOutOfBoundsException e) {
   989                 return "//invalid constant pool index:" + cpoolx;
   990             } catch (ClassCastException e) {
   991                 return "//invalid constant pool ref:" + cpoolx;
   992             }
   993         }
   994 
   995         /**
   996          * Returns list of field info.
   997          */
   998         public FieldData[] getFields() {
   999             return fields;
  1000         }
  1001 
  1002         /**
  1003          * Returns list of method info.
  1004          */
  1005         public MethodData[] getMethods() {
  1006             return methods;
  1007         }
  1008 
  1009         /**
  1010          * Returns constant pool entry at that index.
  1011          */
  1012         public CPX2 getCpoolEntry(int cpx) {
  1013             return ((CPX2) (cpool[cpx]));
  1014         }
  1015 
  1016         public Object getCpoolEntryobj(int cpx) {
  1017             return (cpool[cpx]);
  1018         }
  1019 
  1020         /**
  1021          * Returns index of this class.
  1022          */
  1023         public int getthis_cpx() {
  1024             return this_class;
  1025         }
  1026 
  1027         /**
  1028          * Returns string at that index.
  1029          */
  1030         public String StringValue(int cpx) {
  1031             return stringValue(cpx, false);
  1032         }
  1033 
  1034         public String stringValue(int cpx, boolean textual) {
  1035             return stringValue(cpx, textual, null);
  1036         }
  1037 
  1038         public String stringValue(int cpx, String[] classRefs) {
  1039             return stringValue(cpx, true, classRefs);
  1040         }
  1041 
  1042         private String stringValue(int cpx, boolean textual, String[] refs) {
  1043             if (cpx == 0) {
  1044                 return "#0";
  1045             }
  1046             int tag;
  1047             Object x;
  1048             String suffix = "";
  1049             try {
  1050                 tag = tags[cpx];
  1051                 x = cpool[cpx];
  1052             } catch (IndexOutOfBoundsException e) {
  1053                 return "<Incorrect CP index:" + cpx + ">";
  1054             }
  1055 
  1056             if (x == null) {
  1057                 return "<NULL>";
  1058             }
  1059             switch (tag) {
  1060                 case CONSTANT_UTF8: {
  1061                     if (!textual) {
  1062                         return (String) x;
  1063                     }
  1064                     StringBuilder sb = new StringBuilder();
  1065                     String s = (String) x;
  1066                     for (int k = 0; k < s.length(); k++) {
  1067                         char c = s.charAt(k);
  1068                         switch (c) {
  1069                             case '\\':
  1070                                 sb.append('\\').append('\\');
  1071                                 break;
  1072                             case '\t':
  1073                                 sb.append('\\').append('t');
  1074                                 break;
  1075                             case '\n':
  1076                                 sb.append('\\').append('n');
  1077                                 break;
  1078                             case '\r':
  1079                                 sb.append('\\').append('r');
  1080                                 break;
  1081                             case '\"':
  1082                                 sb.append('\\').append('\"');
  1083                                 break;
  1084                             case '\u2028':
  1085                                 sb.append("\\u2028");
  1086                                 break;
  1087                             case '\u2029':
  1088                                 sb.append("\\u2029");
  1089                                 break;
  1090                             default:
  1091                                 sb.append(c);
  1092                         }
  1093                     }
  1094                     return sb.toString();
  1095                 }
  1096                 case CONSTANT_DOUBLE: {
  1097                     Double d = (Double) x;
  1098                     String sd = d.toString();
  1099                     if (textual) {
  1100                         return sd;
  1101                     }
  1102                     return sd + "d";
  1103                 }
  1104                 case CONSTANT_FLOAT: {
  1105                     Float f = (Float) x;
  1106                     String sf = (f).toString();
  1107                     if (textual) {
  1108                         return sf;
  1109                     }
  1110                     return sf + "f";
  1111                 }
  1112                 case CONSTANT_LONG: {
  1113                     Long ln = (Long) x;
  1114                     if (textual) {
  1115                         return ln.toString();
  1116                     }
  1117                     return ln.toString() + 'l';
  1118                 }
  1119                 case CONSTANT_INTEGER: {
  1120                     Integer in = (Integer) x;
  1121                     return in.toString();
  1122                 }
  1123                 case CONSTANT_CLASS:
  1124                     String jn = getClassName(cpx);
  1125                     if (textual) {
  1126                         if (refs != null) {
  1127                             refs[0] = jn;
  1128                         }
  1129                         return jn;
  1130                     }
  1131                     return javaName(jn);
  1132                 case CONSTANT_STRING:
  1133                     String sv = stringValue(((CPX) x).cpx, textual);
  1134                     if (textual) {
  1135                         return '"' + sv + '"';
  1136                     } else {
  1137                         return sv;
  1138                     }
  1139                 case CONSTANT_FIELD:
  1140                 case CONSTANT_METHOD:
  1141                 case CONSTANT_INTERFACEMETHOD:
  1142                     //return getShortClassName(((CPX2)x).cpx1)+"."+StringValue(((CPX2)x).cpx2);
  1143                     return javaName(getClassName(((CPX2) x).cpx1)) + "." + StringValue(((CPX2) x).cpx2);
  1144 
  1145                 case CONSTANT_NAMEANDTYPE:
  1146                     return getName(((CPX2) x).cpx1) + ":" + StringValue(((CPX2) x).cpx2);
  1147                 default:
  1148                     return "UnknownTag"; //TBD
  1149             }
  1150         }
  1151 
  1152         /**
  1153          * Returns resolved java type name.
  1154          */
  1155         public String javaName(String name) {
  1156             if (name == null) {
  1157                 return "null";
  1158             }
  1159             int len = name.length();
  1160             if (len == 0) {
  1161                 return "\"\"";
  1162             }
  1163             int cc = '/';
  1164             fullname:
  1165             { // xxx/yyy/zzz
  1166                 int cp;
  1167                 for (int k = 0; k < len; k += Character.charCount(cp)) {
  1168                     cp = name.codePointAt(k);
  1169                     if (cc == '/') {
  1170                         if (!isJavaIdentifierStart(cp)) {
  1171                             break fullname;
  1172                         }
  1173                     } else if (cp != '/') {
  1174                         if (!isJavaIdentifierPart(cp)) {
  1175                             break fullname;
  1176                         }
  1177                     }
  1178                     cc = cp;
  1179                 }
  1180                 return name;
  1181             }
  1182             return "\"" + name + "\"";
  1183         }
  1184 
  1185         public String getName(int cpx) {
  1186             String res;
  1187             try {
  1188                 return javaName((String) cpool[cpx]); //.replace('/','.');
  1189             } catch (ArrayIndexOutOfBoundsException e) {
  1190                 return "<invalid constant pool index:" + cpx + ">";
  1191             } catch (ClassCastException e) {
  1192                 return "<invalid constant pool ref:" + cpx + ">";
  1193             }
  1194         }
  1195 
  1196         /**
  1197          * Returns unqualified class name.
  1198          */
  1199         public String getShortClassName(int cpx) {
  1200             String classname = javaName(getClassName(cpx));
  1201             pkgPrefixLen = classname.lastIndexOf("/") + 1;
  1202             if (pkgPrefixLen != 0) {
  1203                 pkgPrefix = classname.substring(0, pkgPrefixLen);
  1204                 if (classname.startsWith(pkgPrefix)) {
  1205                     return classname.substring(pkgPrefixLen);
  1206                 }
  1207             }
  1208             return classname;
  1209         }
  1210 
  1211         /**
  1212          * Returns source file name.
  1213          */
  1214         public String getSourceName() {
  1215             return getName(source_cpx);
  1216         }
  1217 
  1218         /**
  1219          * Returns package name.
  1220          */
  1221         public String getPkgName() {
  1222             String classname = getClassName(this_class);
  1223             pkgPrefixLen = classname.lastIndexOf("/") + 1;
  1224             if (pkgPrefixLen != 0) {
  1225                 pkgPrefix = classname.substring(0, pkgPrefixLen);
  1226                 return /* ("package  " + */ pkgPrefix.substring(0, pkgPrefixLen - 1) /* + ";\n") */;
  1227             } else {
  1228                 return null;
  1229             }
  1230         }
  1231 
  1232         /**
  1233          * Returns total constant pool entry count.
  1234          */
  1235         public int getCpoolCount() {
  1236             return cpool_count;
  1237         }
  1238 
  1239         /**
  1240          * Returns minor version of class file.
  1241          */
  1242         public int getMinor_version() {
  1243             return minor_version;
  1244         }
  1245 
  1246         /**
  1247          * Returns major version of class file.
  1248          */
  1249         public int getMajor_version() {
  1250             return major_version;
  1251         }
  1252 
  1253         private boolean isJavaIdentifierStart(int cp) {
  1254             return ('a' <= cp && cp <= 'z') || ('A' <= cp && cp <= 'Z');
  1255         }
  1256 
  1257         private boolean isJavaIdentifierPart(int cp) {
  1258             return isJavaIdentifierStart(cp) || ('0' <= cp && cp <= '9');
  1259         }
  1260 
  1261         public String[] getNameAndType(int indx) {
  1262             return getNameAndType(indx, 0, new String[2]);
  1263         }
  1264 
  1265         private String[] getNameAndType(int indx, int at, String[] arr) {
  1266             CPX2 c2 = getCpoolEntry(indx);
  1267             arr[at] = StringValue(c2.cpx1);
  1268             arr[at + 1] = StringValue(c2.cpx2);
  1269             return arr;
  1270         }
  1271 
  1272         public String[] getFieldInfoName(int indx) {
  1273             CPX2 c2 = getCpoolEntry(indx);
  1274             String[] arr = new String[3];
  1275             arr[0] = getClassName(c2.cpx1);
  1276             return getNameAndType(c2.cpx2, 1, arr);
  1277         }
  1278 
  1279         public MethodData findMethod(String name, String signature) {
  1280             for (MethodData md: methods) {
  1281                 if (md.getName().equals(name)
  1282                         && md.getInternalSig().equals(signature)) {
  1283                     return md;
  1284                 }
  1285             }
  1286 
  1287             // not found
  1288             return null;
  1289         }
  1290 
  1291         public FieldData findField(String name, String signature) {
  1292             for (FieldData fd: fields) {
  1293                 if (fd.getName().equals(name)
  1294                         && fd.getInternalSig().equals(signature)) {
  1295                     return fd;
  1296                 }
  1297             }
  1298 
  1299             // not found
  1300             return null;
  1301         }
  1302 
  1303         static byte[] findAttr(String n, AttrData[] attrs) {
  1304             for (AttrData ad : attrs) {
  1305                 if (n.equals(ad.getAttrName())) {
  1306                     return ad.getData();
  1307                 }
  1308             }
  1309             return null;
  1310         }
  1311     }
  1312 
  1313     /**
  1314      * Strores field data informastion.
  1315      *
  1316      * @author Sucheta Dambalkar (Adopted code from jdis)
  1317      */
  1318     static class FieldData {
  1319 
  1320         ClassData cls;
  1321         int access;
  1322         int name_index;
  1323         int descriptor_index;
  1324         int attributes_count;
  1325         int value_cpx = -1;
  1326         boolean isSynthetic = false;
  1327         boolean isDeprecated = false;
  1328         Vector attrs;
  1329 
  1330         public FieldData(ClassData cls) {
  1331             this.cls = cls;
  1332         }
  1333 
  1334         /**
  1335          * Read and store field info.
  1336          */
  1337         public void read(DataInputStream in) throws IOException {
  1338             access = in.readUnsignedShort();
  1339             name_index = in.readUnsignedShort();
  1340             descriptor_index = in.readUnsignedShort();
  1341             // Read the attributes
  1342             int attributes_count = in.readUnsignedShort();
  1343             attrs = new Vector(attributes_count);
  1344             for (int i = 0; i < attributes_count; i++) {
  1345                 int attr_name_index = in.readUnsignedShort();
  1346                 if (cls.getTag(attr_name_index) != CONSTANT_UTF8) {
  1347                     continue;
  1348                 }
  1349                 String attr_name = cls.getString(attr_name_index);
  1350                 if (attr_name.equals("ConstantValue")) {
  1351                     if (in.readInt() != 2) {
  1352                         throw new ClassFormatError("invalid ConstantValue attr length");
  1353                     }
  1354                     value_cpx = in.readUnsignedShort();
  1355                     AttrData attr = new AttrData(cls);
  1356                     attr.read(attr_name_index);
  1357                     attrs.addElement(attr);
  1358                 } else if (attr_name.equals("Synthetic")) {
  1359                     if (in.readInt() != 0) {
  1360                         throw new ClassFormatError("invalid Synthetic attr length");
  1361                     }
  1362                     isSynthetic = true;
  1363                     AttrData attr = new AttrData(cls);
  1364                     attr.read(attr_name_index);
  1365                     attrs.addElement(attr);
  1366                 } else if (attr_name.equals("Deprecated")) {
  1367                     if (in.readInt() != 0) {
  1368                         throw new ClassFormatError("invalid Synthetic attr length");
  1369                     }
  1370                     isDeprecated = true;
  1371                     AttrData attr = new AttrData(cls);
  1372                     attr.read(attr_name_index);
  1373                     attrs.addElement(attr);
  1374                 } else {
  1375                     AttrData attr = new AttrData(cls);
  1376                     attr.read(attr_name_index, in);
  1377                     attrs.addElement(attr);
  1378                 }
  1379             }
  1380 
  1381         }  // end read
  1382 
  1383         public boolean isStatic() {
  1384             return (access & ACC_STATIC) != 0;
  1385         }
  1386 
  1387         /**
  1388          * Returns access of a field.
  1389          */
  1390         public String[] getAccess() {
  1391             Vector v = new Vector();
  1392             if ((access & ACC_PUBLIC) != 0) {
  1393                 v.addElement("public");
  1394             }
  1395             if ((access & ACC_PRIVATE) != 0) {
  1396                 v.addElement("private");
  1397             }
  1398             if ((access & ACC_PROTECTED) != 0) {
  1399                 v.addElement("protected");
  1400             }
  1401             if ((access & ACC_STATIC) != 0) {
  1402                 v.addElement("static");
  1403             }
  1404             if ((access & ACC_FINAL) != 0) {
  1405                 v.addElement("final");
  1406             }
  1407             if ((access & ACC_VOLATILE) != 0) {
  1408                 v.addElement("volatile");
  1409             }
  1410             if ((access & ACC_TRANSIENT) != 0) {
  1411                 v.addElement("transient");
  1412             }
  1413             String[] accflags = new String[v.size()];
  1414             v.copyInto(accflags);
  1415             return accflags;
  1416         }
  1417 
  1418         /**
  1419          * Returns name of a field.
  1420          */
  1421         public String getName() {
  1422             return cls.getStringValue(name_index);
  1423         }
  1424 
  1425         /**
  1426          * Returns internal signature of a field
  1427          */
  1428         public String getInternalSig() {
  1429             return cls.getStringValue(descriptor_index);
  1430         }
  1431 
  1432         /**
  1433          * Returns true if field is synthetic.
  1434          */
  1435         public boolean isSynthetic() {
  1436             return isSynthetic;
  1437         }
  1438 
  1439         /**
  1440          * Returns true if field is deprecated.
  1441          */
  1442         public boolean isDeprecated() {
  1443             return isDeprecated;
  1444         }
  1445 
  1446         public boolean hasConstantValue() {
  1447             return value_cpx != -1;
  1448         }
  1449 
  1450         /**
  1451          * Returns list of attributes of field.
  1452          */
  1453         public Vector getAttributes() {
  1454             return attrs;
  1455         }
  1456 
  1457         public byte[] findAnnotationData(boolean classRetention) {
  1458             String n = classRetention
  1459                 ? "RuntimeInvisibleAnnotations" : // NOI18N
  1460                 "RuntimeVisibleAnnotations"; // NOI18N
  1461             AttrData[] arr = new AttrData[attrs.size()];
  1462             attrs.copyInto(arr);
  1463             return ClassData.findAttr(n, arr);
  1464         }
  1465     }
  1466 
  1467     /**
  1468      * A JavaScript optimized replacement for Hashtable.
  1469      *
  1470      * @author Jaroslav Tulach <jtulach@netbeans.org>
  1471      */
  1472     private static final class Hashtable {
  1473 
  1474         private Object[] keys;
  1475         private Object[] values;
  1476 
  1477         Hashtable(int i) {
  1478             this();
  1479         }
  1480 
  1481         Hashtable(int i, double d) {
  1482             this();
  1483         }
  1484 
  1485         Hashtable() {
  1486         }
  1487 
  1488         synchronized void put(Object key, Object val) {
  1489             int[] where = {-1, -1};
  1490             Object found = get(key, where);
  1491             if (where[0] != -1) {
  1492                 // key exists
  1493                 values[where[0]] = val;
  1494             } else {
  1495                 if (where[1] != -1) {
  1496                     // null found
  1497                     keys[where[1]] = key;
  1498                     values[where[1]] = val;
  1499                 } else {
  1500                     if (keys == null) {
  1501                         keys = new Object[11];
  1502                         values = new Object[11];
  1503                         keys[0] = key;
  1504                         values[0] = val;
  1505                     } else {
  1506                         Object[] newKeys = new Object[keys.length * 2];
  1507                         Object[] newValues = new Object[values.length * 2];
  1508                         for (int i = 0; i < keys.length; i++) {
  1509                             newKeys[i] = keys[i];
  1510                             newValues[i] = values[i];
  1511                         }
  1512                         newKeys[keys.length] = key;
  1513                         newValues[keys.length] = val;
  1514                         keys = newKeys;
  1515                         values = newValues;
  1516                     }
  1517                 }
  1518             }
  1519         }
  1520 
  1521         Object get(Object key) {
  1522             return get(key, null);
  1523         }
  1524 
  1525         private synchronized Object get(Object key, int[] foundAndNull) {
  1526             if (keys == null) {
  1527                 return null;
  1528             }
  1529             for (int i = 0; i < keys.length; i++) {
  1530                 if (keys[i] == null) {
  1531                     if (foundAndNull != null) {
  1532                         foundAndNull[1] = i;
  1533                     }
  1534                 } else if (keys[i].equals(key)) {
  1535                     if (foundAndNull != null) {
  1536                         foundAndNull[0] = i;
  1537                     }
  1538                     return values[i];
  1539                 }
  1540             }
  1541             return null;
  1542         }
  1543     }
  1544 
  1545     /**
  1546      * Strores InnerClass data informastion.
  1547      *
  1548      * @author Sucheta Dambalkar (Adopted code from jdis)
  1549      */
  1550     private static class InnerClassData {
  1551 
  1552         ClassData cls;
  1553         int inner_class_info_index, outer_class_info_index, inner_name_index, access;
  1554 
  1555         public InnerClassData(ClassData cls) {
  1556             this.cls = cls;
  1557 
  1558         }
  1559 
  1560         /**
  1561          * Read Innerclass attribute data.
  1562          */
  1563         public void read(DataInputStream in) throws IOException {
  1564             inner_class_info_index = in.readUnsignedShort();
  1565             outer_class_info_index = in.readUnsignedShort();
  1566             inner_name_index = in.readUnsignedShort();
  1567             access = in.readUnsignedShort();
  1568         }  // end read
  1569 
  1570         /**
  1571          * Returns the access of this class or interface.
  1572          */
  1573         public String[] getAccess() {
  1574             Vector v = new Vector();
  1575             if ((access & ACC_PUBLIC) != 0) {
  1576                 v.addElement("public");
  1577             }
  1578             if ((access & ACC_FINAL) != 0) {
  1579                 v.addElement("final");
  1580             }
  1581             if ((access & ACC_ABSTRACT) != 0) {
  1582                 v.addElement("abstract");
  1583             }
  1584             String[] accflags = new String[v.size()];
  1585             v.copyInto(accflags);
  1586             return accflags;
  1587         }
  1588     } // end InnerClassData
  1589 
  1590     /**
  1591      * Strores LineNumberTable data information.
  1592      *
  1593      * @author Sucheta Dambalkar (Adopted code from jdis)
  1594      */
  1595     private static class LineNumData {
  1596 
  1597         short start_pc, line_number;
  1598 
  1599         public LineNumData() {
  1600         }
  1601 
  1602         /**
  1603          * Read LineNumberTable attribute.
  1604          */
  1605         public LineNumData(DataInputStream in) throws IOException {
  1606             start_pc = in.readShort();
  1607             line_number = in.readShort();
  1608 
  1609         }
  1610     }
  1611 
  1612     /**
  1613      * Strores LocalVariableTable data information.
  1614      *
  1615      * @author Sucheta Dambalkar (Adopted code from jdis)
  1616      */
  1617     private static class LocVarData {
  1618 
  1619         short start_pc, length, name_cpx, sig_cpx, slot;
  1620 
  1621         public LocVarData() {
  1622         }
  1623 
  1624         /**
  1625          * Read LocalVariableTable attribute.
  1626          */
  1627         public LocVarData(DataInputStream in) throws IOException {
  1628             start_pc = in.readShort();
  1629             length = in.readShort();
  1630             name_cpx = in.readShort();
  1631             sig_cpx = in.readShort();
  1632             slot = in.readShort();
  1633 
  1634         }
  1635     }
  1636     /**
  1637      * Strores method data informastion.
  1638      *
  1639      * @author Sucheta Dambalkar (Adopted code from jdis)
  1640      */
  1641     static class MethodData {
  1642 
  1643         ClassData cls;
  1644         int access;
  1645         int name_index;
  1646         int descriptor_index;
  1647         int attributes_count;
  1648         byte[] code;
  1649         Vector exception_table = new Vector(0);
  1650         Vector lin_num_tb = new Vector(0);
  1651         Vector loc_var_tb = new Vector(0);
  1652         StackMapTableData[] stackMapTable;
  1653         StackMapData[] stackMap;
  1654         int[] exc_index_table = null;
  1655         Vector attrs = new Vector(0);
  1656         Vector code_attrs = new Vector(0);
  1657         int max_stack, max_locals;
  1658         boolean isSynthetic = false;
  1659         boolean isDeprecated = false;
  1660 
  1661         public MethodData(ClassData cls) {
  1662             this.cls = cls;
  1663         }
  1664 
  1665         /**
  1666          * Read method info.
  1667          */
  1668         public void read(DataInputStream in) throws IOException {
  1669             access = in.readUnsignedShort();
  1670             name_index = in.readUnsignedShort();
  1671             descriptor_index = in.readUnsignedShort();
  1672             int attributes_count = in.readUnsignedShort();
  1673             for (int i = 0; i < attributes_count; i++) {
  1674                 int attr_name_index = in.readUnsignedShort();
  1675 
  1676                 readAttr:
  1677                 {
  1678                     if (cls.getTag(attr_name_index) == CONSTANT_UTF8) {
  1679                         String attr_name = cls.getString(attr_name_index);
  1680                         if (attr_name.equals("Code")) {
  1681                             readCode(in);
  1682                             AttrData attr = new AttrData(cls);
  1683                             attr.read(attr_name_index);
  1684                             attrs.addElement(attr);
  1685                             break readAttr;
  1686                         } else if (attr_name.equals("Exceptions")) {
  1687                             readExceptions(in);
  1688                             AttrData attr = new AttrData(cls);
  1689                             attr.read(attr_name_index);
  1690                             attrs.addElement(attr);
  1691                             break readAttr;
  1692                         } else if (attr_name.equals("Synthetic")) {
  1693                             if (in.readInt() != 0) {
  1694                                 throw new ClassFormatError("invalid Synthetic attr length");
  1695                             }
  1696                             isSynthetic = true;
  1697                             AttrData attr = new AttrData(cls);
  1698                             attr.read(attr_name_index);
  1699                             attrs.addElement(attr);
  1700                             break readAttr;
  1701                         } else if (attr_name.equals("Deprecated")) {
  1702                             if (in.readInt() != 0) {
  1703                                 throw new ClassFormatError("invalid Synthetic attr length");
  1704                             }
  1705                             isDeprecated = true;
  1706                             AttrData attr = new AttrData(cls);
  1707                             attr.read(attr_name_index);
  1708                             attrs.addElement(attr);
  1709                             break readAttr;
  1710                         }
  1711                     }
  1712                     AttrData attr = new AttrData(cls);
  1713                     attr.read(attr_name_index, in);
  1714                     attrs.addElement(attr);
  1715                 }
  1716             }
  1717         }
  1718 
  1719         /**
  1720          * Read code attribute info.
  1721          */
  1722         public void readCode(DataInputStream in) throws IOException {
  1723 
  1724             int attr_length = in.readInt();
  1725             max_stack = in.readUnsignedShort();
  1726             max_locals = in.readUnsignedShort();
  1727             int codelen = in.readInt();
  1728 
  1729             code = new byte[codelen];
  1730             int totalread = 0;
  1731             while (totalread < codelen) {
  1732                 totalread += in.read(code, totalread, codelen - totalread);
  1733             }
  1734             //      in.read(code, 0, codelen);
  1735             int clen = 0;
  1736             readExceptionTable(in);
  1737             int code_attributes_count = in.readUnsignedShort();
  1738 
  1739             for (int k = 0; k < code_attributes_count; k++) {
  1740                 int table_name_index = in.readUnsignedShort();
  1741                 int table_name_tag = cls.getTag(table_name_index);
  1742                 AttrData attr = new AttrData(cls);
  1743                 if (table_name_tag == CONSTANT_UTF8) {
  1744                     String table_name_tstr = cls.getString(table_name_index);
  1745                     if (table_name_tstr.equals("LineNumberTable")) {
  1746                         readLineNumTable(in);
  1747                         attr.read(table_name_index);
  1748                     } else if (table_name_tstr.equals("LocalVariableTable")) {
  1749                         readLocVarTable(in);
  1750                         attr.read(table_name_index);
  1751                     } else if (table_name_tstr.equals("StackMapTable")) {
  1752                         readStackMapTable(in);
  1753                         attr.read(table_name_index);
  1754                     } else if (table_name_tstr.equals("StackMap")) {
  1755                         readStackMap(in);
  1756                         attr.read(table_name_index);
  1757                     } else {
  1758                         attr.read(table_name_index, in);
  1759                     }
  1760                     code_attrs.addElement(attr);
  1761                     continue;
  1762                 }
  1763 
  1764                 attr.read(table_name_index, in);
  1765                 code_attrs.addElement(attr);
  1766             }
  1767         }
  1768 
  1769         /**
  1770          * Read exception table info.
  1771          */
  1772         void readExceptionTable(DataInputStream in) throws IOException {
  1773             int exception_table_len = in.readUnsignedShort();
  1774             exception_table = new Vector(exception_table_len);
  1775             for (int l = 0; l < exception_table_len; l++) {
  1776                 exception_table.addElement(new TrapData(in, l));
  1777             }
  1778         }
  1779 
  1780         /**
  1781          * Read LineNumberTable attribute info.
  1782          */
  1783         void readLineNumTable(DataInputStream in) throws IOException {
  1784             int attr_len = in.readInt(); // attr_length
  1785             int lin_num_tb_len = in.readUnsignedShort();
  1786             lin_num_tb = new Vector(lin_num_tb_len);
  1787             for (int l = 0; l < lin_num_tb_len; l++) {
  1788                 lin_num_tb.addElement(new LineNumData(in));
  1789             }
  1790         }
  1791 
  1792         /**
  1793          * Read LocalVariableTable attribute info.
  1794          */
  1795         void readLocVarTable(DataInputStream in) throws IOException {
  1796             int attr_len = in.readInt(); // attr_length
  1797             int loc_var_tb_len = in.readUnsignedShort();
  1798             loc_var_tb = new Vector(loc_var_tb_len);
  1799             for (int l = 0; l < loc_var_tb_len; l++) {
  1800                 loc_var_tb.addElement(new LocVarData(in));
  1801             }
  1802         }
  1803 
  1804         /**
  1805          * Read Exception attribute info.
  1806          */
  1807         public void readExceptions(DataInputStream in) throws IOException {
  1808             int attr_len = in.readInt(); // attr_length in prog
  1809             int num_exceptions = in.readUnsignedShort();
  1810             exc_index_table = new int[num_exceptions];
  1811             for (int l = 0; l < num_exceptions; l++) {
  1812                 int exc = in.readShort();
  1813                 exc_index_table[l] = exc;
  1814             }
  1815         }
  1816 
  1817         /**
  1818          * Read StackMapTable attribute info.
  1819          */
  1820         void readStackMapTable(DataInputStream in) throws IOException {
  1821             int attr_len = in.readInt();  //attr_length
  1822             int stack_map_tb_len = in.readUnsignedShort();
  1823             stackMapTable = new StackMapTableData[stack_map_tb_len];
  1824             for (int i = 0; i < stack_map_tb_len; i++) {
  1825                 stackMapTable[i] = StackMapTableData.getInstance(in, this);
  1826             }
  1827         }
  1828 
  1829         /**
  1830          * Read StackMap attribute info.
  1831          */
  1832         void readStackMap(DataInputStream in) throws IOException {
  1833             int attr_len = in.readInt();  //attr_length
  1834             int stack_map_len = in.readUnsignedShort();
  1835             stackMap = new StackMapData[stack_map_len];
  1836             for (int i = 0; i < stack_map_len; i++) {
  1837                 stackMap[i] = new StackMapData(in, this);
  1838             }
  1839         }
  1840         
  1841         /**
  1842          * Return access of the method.
  1843          */
  1844         public int getAccess() {
  1845             return access;
  1846         }
  1847 
  1848         /**
  1849          * Return name of the method.
  1850          */
  1851         public String getName() {
  1852             return cls.getStringValue(name_index);
  1853         }
  1854 
  1855         /**
  1856          * Return internal siganature of the method.
  1857          */
  1858         public String getInternalSig() {
  1859             return cls.getStringValue(descriptor_index);
  1860         }
  1861 
  1862         /**
  1863          * Return code attribute data of a method.
  1864          */
  1865         public byte[] getCode() {
  1866             return code;
  1867         }
  1868 
  1869         /**
  1870          * Return LineNumberTable size.
  1871          */
  1872         public int getnumlines() {
  1873             return lin_num_tb.size();
  1874         }
  1875 
  1876         /**
  1877          * Return LineNumberTable
  1878          */
  1879         public Vector getlin_num_tb() {
  1880             return lin_num_tb;
  1881         }
  1882 
  1883         /**
  1884          * Return LocalVariableTable size.
  1885          */
  1886         public int getloc_var_tbsize() {
  1887             return loc_var_tb.size();
  1888         }
  1889 
  1890         /**
  1891          * Return LocalVariableTable.
  1892          */
  1893         public Vector getloc_var_tb() {
  1894             return loc_var_tb;
  1895         }
  1896 
  1897         /**
  1898          * Return StackMap.
  1899          */
  1900         public StackMapData[] getStackMap() {
  1901             return stackMap;
  1902         }
  1903 
  1904         /**
  1905          * Return StackMapTable.
  1906          */
  1907         public StackMapTableData[] getStackMapTable() {
  1908             return stackMapTable;
  1909         }
  1910 
  1911         public StackMapIterator createStackMapIterator() {
  1912             return new StackMapIterator(this);
  1913         }
  1914 
  1915         /**
  1916          * Return true if method is static
  1917          */
  1918         public boolean isStatic() {
  1919             if ((access & ACC_STATIC) != 0) {
  1920                 return true;
  1921             }
  1922             return false;
  1923         }
  1924 
  1925         /**
  1926          * Return max depth of operand stack.
  1927          */
  1928         public int getMaxStack() {
  1929             return max_stack;
  1930         }
  1931 
  1932         /**
  1933          * Return number of local variables.
  1934          */
  1935         public int getMaxLocals() {
  1936             return max_locals;
  1937         }
  1938 
  1939         /**
  1940          * Return exception index table in Exception attribute.
  1941          */
  1942         public int[] get_exc_index_table() {
  1943             return exc_index_table;
  1944         }
  1945 
  1946         /**
  1947          * Return exception table in code attributre.
  1948          */
  1949         public TrapDataIterator getTrapDataIterator() {
  1950             return new TrapDataIterator(exception_table);
  1951         }
  1952 
  1953         /**
  1954          * Return method attributes.
  1955          */
  1956         public Vector getAttributes() {
  1957             return attrs;
  1958         }
  1959 
  1960         /**
  1961          * Return code attributes.
  1962          */
  1963         public Vector getCodeAttributes() {
  1964             return code_attrs;
  1965         }
  1966 
  1967         /**
  1968          * Return true if method id synthetic.
  1969          */
  1970         public boolean isSynthetic() {
  1971             return isSynthetic;
  1972         }
  1973 
  1974         /**
  1975          * Return true if method is deprecated.
  1976          */
  1977         public boolean isDeprecated() {
  1978             return isDeprecated;
  1979         }
  1980 
  1981         public byte[] findAnnotationData(boolean classRetention) {
  1982             String n = classRetention
  1983                 ? "RuntimeInvisibleAnnotations" : // NOI18N
  1984                 "RuntimeVisibleAnnotations"; // NOI18N
  1985             AttrData[] arr = new AttrData[attrs.size()];
  1986             attrs.copyInto(arr);
  1987             return ClassData.findAttr(n, arr);
  1988         }
  1989 
  1990         public boolean isConstructor() {
  1991             return "<init>".equals(getName());
  1992         }
  1993     }
  1994 
  1995     /* represents one entry of StackMap attribute
  1996      */
  1997     private static class StackMapData {
  1998 
  1999         final int offset;
  2000         final int[] locals;
  2001         final int[] stack;
  2002 
  2003         StackMapData(int offset, int[] locals, int[] stack) {
  2004             this.offset = offset;
  2005             this.locals = locals;
  2006             this.stack = stack;
  2007         }
  2008 
  2009         StackMapData(DataInputStream in, MethodData method) throws IOException {
  2010             offset = in.readUnsignedShort();
  2011             int local_size = in.readUnsignedShort();
  2012             locals = readTypeArray(in, local_size, method);
  2013             int stack_size = in.readUnsignedShort();
  2014             stack = readTypeArray(in, stack_size, method);
  2015         }
  2016 
  2017         static final int[] readTypeArray(DataInputStream in, int length, MethodData method) throws IOException {
  2018             int[] types = new int[length];
  2019             for (int i = 0; i < length; i++) {
  2020                 types[i] = readType(in, method);
  2021             }
  2022             return types;
  2023         }
  2024 
  2025         static final int readType(DataInputStream in, MethodData method) throws IOException {
  2026             int type = in.readUnsignedByte();
  2027             if (type == ITEM_Object || type == ITEM_NewObject) {
  2028                 type = type | (in.readUnsignedShort() << 8);
  2029             }
  2030             return type;
  2031         }
  2032     }
  2033 
  2034     static final class StackMapIterator {
  2035 
  2036         private final StackMapTableData[] stackMapTable;
  2037         private final TypeArray argTypes;
  2038         private final TypeArray localTypes;
  2039         private final TypeArray stackTypes;
  2040         private int nextFrameIndex;
  2041         private int lastFrameByteCodeOffset;
  2042         private int byteCodeOffset;
  2043 
  2044         StackMapIterator(final MethodData methodData) {
  2045             this(methodData.getStackMapTable(),
  2046                 methodData.getInternalSig(),
  2047                 methodData.isStatic());
  2048         }
  2049 
  2050         StackMapIterator(final StackMapTableData[] stackMapTable,
  2051             final String methodSignature,
  2052             final boolean isStaticMethod) {
  2053             this.stackMapTable = (stackMapTable != null)
  2054                 ? stackMapTable
  2055                 : new StackMapTableData[0];
  2056 
  2057             argTypes = getArgTypes(methodSignature, isStaticMethod);
  2058             localTypes = new TypeArray();
  2059             stackTypes = new TypeArray();
  2060 
  2061             localTypes.addAll(argTypes);
  2062 
  2063             lastFrameByteCodeOffset = -1;
  2064             advanceBy(0);
  2065         }
  2066         
  2067         public boolean isEmpty() {
  2068             return stackMapTable.length == 0;
  2069         }
  2070 
  2071         public String getFrameAsString() {
  2072             return (nextFrameIndex == 0)
  2073                 ? StackMapTableData.toString("INITIAL", 0, null, null)
  2074                 : stackMapTable[nextFrameIndex - 1].toString();
  2075         }
  2076 
  2077         public int getFrameIndex() {
  2078             return nextFrameIndex;
  2079         }
  2080 
  2081         public TypeArray getFrameStack() {
  2082             return stackTypes;
  2083         }
  2084 
  2085         public TypeArray getFrameLocals() {
  2086             return localTypes;
  2087         }
  2088 
  2089         public TypeArray getArguments() {
  2090             return argTypes;
  2091         }
  2092 
  2093         public void advanceBy(final int numByteCodes) {
  2094             if (numByteCodes < 0) {
  2095                 throw new IllegalStateException("Forward only iterator");
  2096             }
  2097 
  2098             byteCodeOffset += numByteCodes;
  2099             while ((nextFrameIndex < stackMapTable.length)
  2100                 && ((byteCodeOffset - lastFrameByteCodeOffset)
  2101                 >= (stackMapTable[nextFrameIndex].offsetDelta
  2102                 + 1))) {
  2103                 final StackMapTableData nextFrame = stackMapTable[nextFrameIndex];
  2104 
  2105                 lastFrameByteCodeOffset += nextFrame.offsetDelta + 1;
  2106                 nextFrame.applyTo(localTypes, stackTypes);
  2107 
  2108                 ++nextFrameIndex;
  2109             }
  2110         }
  2111 
  2112         public void advanceTo(final int nextByteCodeOffset) {
  2113             advanceBy(nextByteCodeOffset - byteCodeOffset);
  2114         }
  2115 
  2116         private static TypeArray getArgTypes(final String methodSignature,
  2117             final boolean isStaticMethod) {
  2118             final TypeArray argTypes = new TypeArray();
  2119 
  2120             if (!isStaticMethod) {
  2121                 argTypes.add(ITEM_Object);
  2122             }
  2123 
  2124             if (methodSignature.charAt(0) != '(') {
  2125                 throw new IllegalArgumentException("Invalid method signature");
  2126             }
  2127 
  2128             final int length = methodSignature.length();
  2129             boolean skipType = false;
  2130             int argType;
  2131             for (int i = 1; i < length; ++i) {
  2132                 switch (methodSignature.charAt(i)) {
  2133                     case 'B':
  2134                     case 'C':
  2135                     case 'S':
  2136                     case 'Z':
  2137                     case 'I':
  2138                         argType = ITEM_Integer;
  2139                         break;
  2140                     case 'J':
  2141                         argType = ITEM_Long;
  2142                         break;
  2143                     case 'F':
  2144                         argType = ITEM_Float;
  2145                         break;
  2146                     case 'D':
  2147                         argType = ITEM_Double;
  2148                         break;
  2149                     case 'L': {
  2150                         i = methodSignature.indexOf(';', i + 1);
  2151                         if (i == -1) {
  2152                             throw new IllegalArgumentException(
  2153                                 "Invalid method signature");
  2154                         }
  2155                         argType = ITEM_Object;
  2156                         break;
  2157                     }
  2158                     case ')':
  2159                         // not interested in the return value type
  2160                         return argTypes;
  2161                     case '[':
  2162                         if (!skipType) {
  2163                             argTypes.add(ITEM_Object);
  2164                             skipType = true;
  2165                         }
  2166                         continue;
  2167 
  2168                     default:
  2169                         throw new IllegalArgumentException(
  2170                             "Invalid method signature");
  2171                 }
  2172 
  2173                 if (!skipType) {
  2174                     argTypes.add(argType);
  2175                 } else {
  2176                     skipType = false;
  2177                 }
  2178             }
  2179 
  2180             return argTypes;
  2181         }
  2182     }
  2183     /* represents one entry of StackMapTable attribute
  2184      */
  2185 
  2186     private static abstract class StackMapTableData {
  2187 
  2188         final int frameType;
  2189         int offsetDelta;
  2190 
  2191         StackMapTableData(int frameType) {
  2192             this.frameType = frameType;
  2193         }
  2194 
  2195         abstract void applyTo(TypeArray localTypes, TypeArray stackTypes);
  2196 
  2197         protected static String toString(
  2198             final String frameType,
  2199             final int offset,
  2200             final int[] localTypes,
  2201             final int[] stackTypes) {
  2202             final StringBuilder sb = new StringBuilder(frameType);
  2203 
  2204             sb.append("(off: +").append(offset);
  2205             if (localTypes != null) {
  2206                 sb.append(", locals: ");
  2207                 appendTypes(sb, localTypes);
  2208             }
  2209             if (stackTypes != null) {
  2210                 sb.append(", stack: ");
  2211                 appendTypes(sb, stackTypes);
  2212             }
  2213             sb.append(')');
  2214 
  2215             return sb.toString();
  2216         }
  2217 
  2218         private static void appendTypes(final StringBuilder sb, final int[] types) {
  2219             sb.append('[');
  2220             if (types.length > 0) {
  2221                 sb.append(TypeArray.typeString(types[0]));
  2222                 for (int i = 1; i < types.length; ++i) {
  2223                     sb.append(", ");
  2224                     sb.append(TypeArray.typeString(types[i]));
  2225                 }
  2226             }
  2227             sb.append(']');
  2228         }
  2229 
  2230         private static class SameFrame extends StackMapTableData {
  2231 
  2232             SameFrame(int frameType, int offsetDelta) {
  2233                 super(frameType);
  2234                 this.offsetDelta = offsetDelta;
  2235             }
  2236 
  2237             @Override
  2238             void applyTo(TypeArray localTypes, TypeArray stackTypes) {
  2239                 stackTypes.clear();
  2240             }
  2241 
  2242             @Override
  2243             public String toString() {
  2244                 return toString("SAME" + ((frameType == SAME_FRAME_EXTENDED)
  2245                     ? "_FRAME_EXTENDED" : ""),
  2246                     offsetDelta,
  2247                     null, null);
  2248             }
  2249         }
  2250 
  2251         private static class SameLocals1StackItem extends StackMapTableData {
  2252 
  2253             final int[] stack;
  2254 
  2255             SameLocals1StackItem(int frameType, int offsetDelta, int[] stack) {
  2256                 super(frameType);
  2257                 this.offsetDelta = offsetDelta;
  2258                 this.stack = stack;
  2259             }
  2260 
  2261             @Override
  2262             void applyTo(TypeArray localTypes, TypeArray stackTypes) {
  2263                 stackTypes.setAll(stack);
  2264             }
  2265 
  2266             @Override
  2267             public String toString() {
  2268                 return toString(
  2269                     "SAME_LOCALS_1_STACK_ITEM"
  2270                     + ((frameType == SAME_LOCALS_1_STACK_ITEM_EXTENDED)
  2271                     ? "_EXTENDED" : ""),
  2272                     offsetDelta,
  2273                     null, stack);
  2274             }
  2275         }
  2276 
  2277         private static class ChopFrame extends StackMapTableData {
  2278 
  2279             ChopFrame(int frameType, int offsetDelta) {
  2280                 super(frameType);
  2281                 this.offsetDelta = offsetDelta;
  2282             }
  2283 
  2284             @Override
  2285             void applyTo(TypeArray localTypes, TypeArray stackTypes) {
  2286                 localTypes.setSize(localTypes.getSize()
  2287                     - (SAME_FRAME_EXTENDED - frameType));
  2288                 stackTypes.clear();
  2289             }
  2290 
  2291             @Override
  2292             public String toString() {
  2293                 return toString("CHOP", offsetDelta, null, null);
  2294             }
  2295         }
  2296 
  2297         private static class AppendFrame extends StackMapTableData {
  2298 
  2299             final int[] locals;
  2300 
  2301             AppendFrame(int frameType, int offsetDelta, int[] locals) {
  2302                 super(frameType);
  2303                 this.offsetDelta = offsetDelta;
  2304                 this.locals = locals;
  2305             }
  2306 
  2307             @Override
  2308             void applyTo(TypeArray localTypes, TypeArray stackTypes) {
  2309                 localTypes.addAll(locals);
  2310                 stackTypes.clear();
  2311             }
  2312 
  2313             @Override
  2314             public String toString() {
  2315                 return toString("APPEND", offsetDelta, locals, null);
  2316             }
  2317         }
  2318 
  2319         private static class FullFrame extends StackMapTableData {
  2320 
  2321             final int[] locals;
  2322             final int[] stack;
  2323 
  2324             FullFrame(int offsetDelta, int[] locals, int[] stack) {
  2325                 super(FULL_FRAME);
  2326                 this.offsetDelta = offsetDelta;
  2327                 this.locals = locals;
  2328                 this.stack = stack;
  2329             }
  2330 
  2331             @Override
  2332             void applyTo(TypeArray localTypes, TypeArray stackTypes) {
  2333                 localTypes.setAll(locals);
  2334                 stackTypes.setAll(stack);
  2335             }
  2336 
  2337             @Override
  2338             public String toString() {
  2339                 return toString("FULL", offsetDelta, locals, stack);
  2340             }
  2341         }
  2342 
  2343         static StackMapTableData getInstance(DataInputStream in, MethodData method)
  2344             throws IOException {
  2345             int frameType = in.readUnsignedByte();
  2346 
  2347             if (frameType < SAME_FRAME_BOUND) {
  2348                 // same_frame
  2349                 return new SameFrame(frameType, frameType);
  2350             } else if (SAME_FRAME_BOUND <= frameType && frameType < SAME_LOCALS_1_STACK_ITEM_BOUND) {
  2351                 // same_locals_1_stack_item_frame
  2352                 // read additional single stack element
  2353                 return new SameLocals1StackItem(frameType,
  2354                     (frameType - SAME_FRAME_BOUND),
  2355                     StackMapData.readTypeArray(in, 1, method));
  2356             } else if (frameType == SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
  2357                 // same_locals_1_stack_item_extended
  2358                 return new SameLocals1StackItem(frameType,
  2359                     in.readUnsignedShort(),
  2360                     StackMapData.readTypeArray(in, 1, method));
  2361             } else if (SAME_LOCALS_1_STACK_ITEM_EXTENDED < frameType && frameType < SAME_FRAME_EXTENDED) {
  2362                 // chop_frame or same_frame_extended
  2363                 return new ChopFrame(frameType, in.readUnsignedShort());
  2364             } else if (frameType == SAME_FRAME_EXTENDED) {
  2365                 // chop_frame or same_frame_extended
  2366                 return new SameFrame(frameType, in.readUnsignedShort());
  2367             } else if (SAME_FRAME_EXTENDED < frameType && frameType < FULL_FRAME) {
  2368                 // append_frame
  2369                 return new AppendFrame(frameType, in.readUnsignedShort(),
  2370                     StackMapData.readTypeArray(in, frameType - SAME_FRAME_EXTENDED, method));
  2371             } else if (frameType == FULL_FRAME) {
  2372                 // full_frame
  2373                 int offsetDelta = in.readUnsignedShort();
  2374                 int locals_size = in.readUnsignedShort();
  2375                 int[] locals = StackMapData.readTypeArray(in, locals_size, method);
  2376                 int stack_size = in.readUnsignedShort();
  2377                 int[] stack = StackMapData.readTypeArray(in, stack_size, method);
  2378                 return new FullFrame(offsetDelta, locals, stack);
  2379             } else {
  2380                 throw new ClassFormatError("unrecognized frame_type in StackMapTable");
  2381             }
  2382         }
  2383     }
  2384 
  2385     /**
  2386      * Stores exception table data in code attribute.
  2387      *
  2388      * @author Sucheta Dambalkar (Adopted code from jdis)
  2389      */
  2390     static final class TrapData {
  2391 
  2392         public final short start_pc;
  2393         public final short end_pc;
  2394         public final short handler_pc;
  2395         public final short catch_cpx;
  2396         final int num;
  2397 
  2398         /**
  2399          * Read and store exception table data in code attribute.
  2400          */
  2401         TrapData(DataInputStream in, int num) throws IOException {
  2402             this.num = num;
  2403             start_pc = in.readShort();
  2404             end_pc = in.readShort();
  2405             handler_pc = in.readShort();
  2406             catch_cpx = in.readShort();
  2407         }
  2408 
  2409         /**
  2410          * returns recommended identifier
  2411          */
  2412         public String ident() {
  2413             return "t" + num;
  2414         }
  2415     }
  2416     /**
  2417      *
  2418      * @author Jaroslav Tulach <jtulach@netbeans.org>
  2419      */
  2420     static final class TrapDataIterator {
  2421 
  2422         private final Hashtable exStart = new Hashtable();
  2423         private final Hashtable exStop = new Hashtable();
  2424         private TrapData[] current = new TrapData[10];
  2425         private int currentCount;
  2426 
  2427         TrapDataIterator(Vector exceptionTable) {
  2428             for (int i = 0; i < exceptionTable.size(); i++) {
  2429                 final TrapData td = (TrapData) exceptionTable.elementAt(i);
  2430                 put(exStart, td.start_pc, td);
  2431                 put(exStop, td.end_pc, td);
  2432             }
  2433         }
  2434 
  2435         private static void put(Hashtable h, short key, TrapData td) {
  2436             Short s = Short.valueOf((short) key);
  2437             Vector v = (Vector) h.get(s);
  2438             if (v == null) {
  2439                 v = new Vector(1);
  2440                 h.put(s, v);
  2441             }
  2442             v.add(td);
  2443         }
  2444 
  2445         private boolean processAll(Hashtable h, Short key, boolean add) {
  2446             boolean change = false;
  2447             Vector v = (Vector) h.get(key);
  2448             if (v != null) {
  2449                 int s = v.size();
  2450                 for (int i = 0; i < s; i++) {
  2451                     TrapData td = (TrapData) v.elementAt(i);
  2452                     if (add) {
  2453                         add(td);
  2454                         change = true;
  2455                     } else {
  2456                         remove(td);
  2457                         change = true;
  2458                     }
  2459                 }
  2460             }
  2461             return change;
  2462         }
  2463 
  2464         public boolean advanceTo(int i) {
  2465             Short s = Short.valueOf((short) i);
  2466             boolean ch1 = processAll(exStart, s, true);
  2467             boolean ch2 = processAll(exStop, s, false);
  2468             return ch1 || ch2;
  2469         }
  2470 
  2471         public boolean useTry() {
  2472             return currentCount > 0;
  2473         }
  2474 
  2475         public TrapData[] current() {
  2476             TrapData[] copy = new TrapData[currentCount];
  2477             for (int i = 0; i < currentCount; i++) {
  2478                 copy[i] = current[i];
  2479             }
  2480             return copy;
  2481         }
  2482 
  2483         private void add(TrapData e) {
  2484             if (currentCount == current.length) {
  2485                 TrapData[] data = new TrapData[currentCount * 2];
  2486                 for (int i = 0; i < currentCount; i++) {
  2487                     data[i] = current[i];
  2488                 }
  2489                 current = data;
  2490             }
  2491             current[currentCount++] = e;
  2492         }
  2493 
  2494         private void remove(TrapData e) {
  2495             if (currentCount == 0) {
  2496                 return;
  2497             }
  2498             int from = 0;
  2499             while (from < currentCount) {
  2500                 if (e == current[from++]) {
  2501                     break;
  2502                 }
  2503             }
  2504             while (from < currentCount) {
  2505                 current[from - 1] = current[from];
  2506                 current[from] = null;
  2507                 from++;
  2508             }
  2509             currentCount--;
  2510         }
  2511     }
  2512     static final class TypeArray {
  2513 
  2514         private static final int CAPACITY_INCREMENT = 16;
  2515         private int[] types;
  2516         private int size;
  2517 
  2518         public TypeArray() {
  2519         }
  2520 
  2521         public TypeArray(final TypeArray initialTypes) {
  2522             setAll(initialTypes);
  2523         }
  2524 
  2525         public void add(final int newType) {
  2526             ensureCapacity(size + 1);
  2527             types[size++] = newType;
  2528         }
  2529 
  2530         public void addAll(final TypeArray newTypes) {
  2531             addAll(newTypes.types, 0, newTypes.size);
  2532         }
  2533 
  2534         public void addAll(final int[] newTypes) {
  2535             addAll(newTypes, 0, newTypes.length);
  2536         }
  2537 
  2538         public void addAll(final int[] newTypes,
  2539             final int offset,
  2540             final int count) {
  2541             if (count > 0) {
  2542                 ensureCapacity(size + count);
  2543                 arraycopy(newTypes, offset, types, size, count);
  2544                 size += count;
  2545             }
  2546         }
  2547 
  2548         public void set(final int index, final int newType) {
  2549             types[index] = newType;
  2550         }
  2551 
  2552         public void setAll(final TypeArray newTypes) {
  2553             setAll(newTypes.types, 0, newTypes.size);
  2554         }
  2555 
  2556         public void setAll(final int[] newTypes) {
  2557             setAll(newTypes, 0, newTypes.length);
  2558         }
  2559 
  2560         public void setAll(final int[] newTypes,
  2561             final int offset,
  2562             final int count) {
  2563             if (count > 0) {
  2564                 ensureCapacity(count);
  2565                 arraycopy(newTypes, offset, types, 0, count);
  2566                 size = count;
  2567             } else {
  2568                 clear();
  2569             }
  2570         }
  2571 
  2572         public void setSize(final int newSize) {
  2573             if (size != newSize) {
  2574                 ensureCapacity(newSize);
  2575 
  2576                 for (int i = size; i < newSize; ++i) {
  2577                     types[i] = 0;
  2578                 }
  2579                 size = newSize;
  2580             }
  2581         }
  2582 
  2583         public void clear() {
  2584             size = 0;
  2585         }
  2586 
  2587         public int getSize() {
  2588             return size;
  2589         }
  2590 
  2591         public int get(final int index) {
  2592             return types[index];
  2593         }
  2594 
  2595         public static String typeString(final int type) {
  2596             switch (type & 0xff) {
  2597                 case ITEM_Bogus:
  2598                     return "_top_";
  2599                 case ITEM_Integer:
  2600                     return "_int_";
  2601                 case ITEM_Float:
  2602                     return "_float_";
  2603                 case ITEM_Double:
  2604                     return "_double_";
  2605                 case ITEM_Long:
  2606                     return "_long_";
  2607                 case ITEM_Null:
  2608                     return "_null_";
  2609                 case ITEM_InitObject: // UninitializedThis
  2610                     return "_init_";
  2611                 case ITEM_Object:
  2612                     return "_object_";
  2613                 case ITEM_NewObject: // Uninitialized
  2614                     return "_new_";
  2615                 default:
  2616                     throw new IllegalArgumentException("Unknown type");
  2617             }
  2618         }
  2619 
  2620         @Override
  2621         public String toString() {
  2622             final StringBuilder sb = new StringBuilder("[");
  2623             if (size > 0) {
  2624                 sb.append(typeString(types[0]));
  2625                 for (int i = 1; i < size; ++i) {
  2626                     sb.append(", ");
  2627                     sb.append(typeString(types[i]));
  2628                 }
  2629             }
  2630 
  2631             return sb.append(']').toString();
  2632         }
  2633 
  2634         private void ensureCapacity(final int minCapacity) {
  2635             if ((minCapacity == 0)
  2636                 || (types != null) && (minCapacity <= types.length)) {
  2637                 return;
  2638             }
  2639 
  2640             final int newCapacity =
  2641                 ((minCapacity + CAPACITY_INCREMENT - 1) / CAPACITY_INCREMENT)
  2642                 * CAPACITY_INCREMENT;
  2643             final int[] newTypes = new int[newCapacity];
  2644 
  2645             if (size > 0) {
  2646                 arraycopy(types, 0, newTypes, 0, size);
  2647             }
  2648 
  2649             types = newTypes;
  2650         }
  2651 
  2652         // no System.arraycopy
  2653         private void arraycopy(final int[] src, final int srcPos,
  2654             final int[] dest, final int destPos,
  2655             final int length) {
  2656             for (int i = 0; i < length; ++i) {
  2657                 dest[destPos + i] = src[srcPos + i];
  2658             }
  2659         }
  2660     }
  2661     /**
  2662      * A JavaScript ready replacement for java.util.Vector
  2663      *
  2664      * @author Jaroslav Tulach <jtulach@netbeans.org>
  2665      */
  2666     @JavaScriptPrototype(prototype = "new Array")
  2667     private static final class Vector {
  2668 
  2669         private Object[] arr;
  2670 
  2671         Vector() {
  2672         }
  2673 
  2674         Vector(int i) {
  2675         }
  2676 
  2677         void add(Object objectType) {
  2678             addElement(objectType);
  2679         }
  2680 
  2681         @JavaScriptBody(args = {"obj"}, body =
  2682             "this.push(obj);")
  2683         void addElement(Object obj) {
  2684             final int s = size();
  2685             setSize(s + 1);
  2686             setElementAt(obj, s);
  2687         }
  2688 
  2689         @JavaScriptBody(args = {}, body =
  2690             "return this.length;")
  2691         int size() {
  2692             return arr == null ? 0 : arr.length;
  2693         }
  2694 
  2695         @JavaScriptBody(args = {"newArr"}, body =
  2696             "for (var i = 0; i < this.length; i++) {\n"
  2697             + "  newArr[i] = this[i];\n"
  2698             + "}\n")
  2699         void copyInto(Object[] newArr) {
  2700             if (arr == null) {
  2701                 return;
  2702             }
  2703             int min = Math.min(newArr.length, arr.length);
  2704             for (int i = 0; i < min; i++) {
  2705                 newArr[i] = arr[i];
  2706             }
  2707         }
  2708 
  2709         @JavaScriptBody(args = {"index"}, body =
  2710             "return this[index];")
  2711         Object elementAt(int index) {
  2712             return arr[index];
  2713         }
  2714 
  2715         private void setSize(int len) {
  2716             Object[] newArr = new Object[len];
  2717             copyInto(newArr);
  2718             arr = newArr;
  2719         }
  2720 
  2721         @JavaScriptBody(args = {"val", "index"}, body =
  2722             "this[index] = val;")
  2723         void setElementAt(Object val, int index) {
  2724             arr[index] = val;
  2725         }
  2726     }
  2727     
  2728 }