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