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