rt/emul/compact/src/main/java/sun/invoke/anon/ConstantPoolParser.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 09 Aug 2014 11:11:13 +0200
branchjdk8-b132
changeset 1646 c880a8a8803b
permissions -rw-r--r--
Batch of classes necessary to implement invoke dynamic interfaces. Taken from JDK8 build 132
     1 /*
     2  * Copyright (c) 2008, 2011, 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 
    26 package sun.invoke.anon;
    27 
    28 import java.io.IOException;
    29 import java.io.OutputStream;
    30 import java.nio.BufferUnderflowException;
    31 import java.nio.ByteBuffer;
    32 
    33 import static sun.invoke.anon.ConstantPoolVisitor.*;
    34 
    35 /** A constant pool parser.
    36  */
    37 public class ConstantPoolParser {
    38     final byte[] classFile;
    39     final byte[] tags;
    40     final char[] firstHeader;  // maghi, maglo, minor, major, cplen
    41 
    42     // these are filled in on first parse:
    43     int endOffset;
    44     char[] secondHeader;       // flags, this_class, super_class, intlen
    45 
    46     // used to decode UTF8 array
    47     private char[] charArray = new char[80];
    48 
    49     /** Creates a constant pool parser.
    50      * @param classFile an array of bytes containing a class.
    51      * @throws InvalidConstantPoolFormatException if the header of the class has errors.
    52      */
    53     public ConstantPoolParser(byte[] classFile) throws InvalidConstantPoolFormatException {
    54         this.classFile = classFile;
    55         this.firstHeader = parseHeader(classFile);
    56         this.tags = new byte[firstHeader[4]];
    57     }
    58 
    59     /** Create a constant pool parser by loading the bytecodes of the
    60      *  class taken as argument.
    61      *
    62      * @param templateClass the class to parse.
    63      *
    64      * @throws IOException raised if an I/O occurs when loading
    65      *  the bytecode of the template class.
    66      * @throws InvalidConstantPoolFormatException if the header of the class has errors.
    67      *
    68      * @see #ConstantPoolParser(byte[])
    69      * @see AnonymousClassLoader#readClassFile(Class)
    70      */
    71     public ConstantPoolParser(Class<?> templateClass) throws IOException, InvalidConstantPoolFormatException {
    72         this(AnonymousClassLoader.readClassFile(templateClass));
    73     }
    74 
    75     /** Creates an empty patch to patch the class file
    76      *  used by the current parser.
    77      * @return a new class patch.
    78      */
    79     public ConstantPoolPatch createPatch() {
    80         return new ConstantPoolPatch(this);
    81     }
    82 
    83     /** Report the tag of the indicated CP entry.
    84      * @param index
    85      * @return one of {@link ConstantPoolVisitor#CONSTANT_Utf8}, etc.
    86      */
    87     public byte getTag(int index) {
    88         getEndOffset();  // trigger an exception if we haven't parsed yet
    89         return tags[index];
    90     }
    91 
    92     /** Report the length of the constant pool. */
    93     public int getLength() {
    94         return firstHeader[4];
    95     }
    96 
    97     /** Report the offset, within the class file, of the start of the constant pool. */
    98     public int getStartOffset() {
    99         return firstHeader.length * 2;
   100     }
   101 
   102     /** Report the offset, within the class file, of the end of the constant pool. */
   103     public int getEndOffset() {
   104         if (endOffset == 0)
   105             throw new IllegalStateException("class file has not yet been parsed");
   106         return endOffset;
   107     }
   108 
   109     /** Report the CP index of this class's own name. */
   110     public int getThisClassIndex() {
   111         getEndOffset();   // provoke exception if not yet parsed
   112         return secondHeader[1];
   113     }
   114 
   115     /** Report the total size of the class file. */
   116     public int getTailLength() {
   117         return classFile.length - getEndOffset();
   118     }
   119 
   120     /** Write the head (header plus constant pool)
   121      *  of the class file to the indicated stream.
   122      */
   123     public void writeHead(OutputStream out) throws IOException {
   124         out.write(classFile, 0, getEndOffset());
   125     }
   126 
   127     /** Write the head (header plus constant pool)
   128      *  of the class file to the indicated stream,
   129      *  incorporating the non-null entries of the given array
   130      *  as patches.
   131      */
   132     void writePatchedHead(OutputStream out, Object[] patchArray) {
   133         // this will be useful to partially emulate the class loader on old JVMs
   134         throw new UnsupportedOperationException("Not yet implemented");
   135     }
   136 
   137     /** Write the tail (everything after the constant pool)
   138      *  of the class file to the indicated stream.
   139      */
   140     public void writeTail(OutputStream out) throws IOException {
   141         out.write(classFile, getEndOffset(), getTailLength());
   142     }
   143 
   144     private static char[] parseHeader(byte[] classFile) throws InvalidConstantPoolFormatException {
   145         char[] result = new char[5];
   146         ByteBuffer buffer = ByteBuffer.wrap(classFile);
   147         for (int i = 0; i < result.length; i++)
   148             result[i] = (char) getUnsignedShort(buffer);
   149         int magic = result[0] << 16 | result[1] << 0;
   150         if (magic != 0xCAFEBABE)
   151             throw new InvalidConstantPoolFormatException("invalid magic number "+magic);
   152         // skip major, minor version
   153         int len = result[4];
   154         if (len < 1)
   155             throw new InvalidConstantPoolFormatException("constant pool length < 1");
   156         return result;
   157     }
   158 
   159     /** Parse the constant pool of the class
   160      *  calling a method visit* each time a constant pool entry is parsed.
   161      *
   162      *  The order of the calls to visit* is not guaranteed to be the same
   163      *  than the order of the constant pool entry in the bytecode array.
   164      *
   165      * @param visitor
   166      * @throws InvalidConstantPoolFormatException
   167      */
   168     public void parse(ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
   169         ByteBuffer buffer = ByteBuffer.wrap(classFile);
   170         buffer.position(getStartOffset()); //skip header
   171 
   172         Object[] values = new Object[getLength()];
   173         try {
   174             parseConstantPool(buffer, values, visitor);
   175         } catch(BufferUnderflowException e) {
   176             throw new InvalidConstantPoolFormatException(e);
   177         }
   178         if (endOffset == 0) {
   179             endOffset = buffer.position();
   180             secondHeader = new char[4];
   181             for (int i = 0; i < secondHeader.length; i++) {
   182                 secondHeader[i] = (char) getUnsignedShort(buffer);
   183             }
   184         }
   185         resolveConstantPool(values, visitor);
   186     }
   187 
   188     private char[] getCharArray(int utfLength) {
   189         if (utfLength <= charArray.length)
   190             return charArray;
   191         return charArray = new char[utfLength];
   192     }
   193 
   194     private void parseConstantPool(ByteBuffer buffer, Object[] values, ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
   195         for (int i = 1; i < tags.length; ) {
   196             byte tag = (byte) getUnsignedByte(buffer);
   197             assert(tags[i] == 0 || tags[i] == tag);
   198             tags[i] = tag;
   199             switch (tag) {
   200                 case CONSTANT_Utf8:
   201                     int utfLen = getUnsignedShort(buffer);
   202                     String value = getUTF8(buffer, utfLen, getCharArray(utfLen));
   203                     visitor.visitUTF8(i, CONSTANT_Utf8, value);
   204                     tags[i] = tag;
   205                     values[i++] = value;
   206                     break;
   207                 case CONSTANT_Integer:
   208                     visitor.visitConstantValue(i, tag, buffer.getInt());
   209                     i++;
   210                     break;
   211                 case CONSTANT_Float:
   212                     visitor.visitConstantValue(i, tag, buffer.getFloat());
   213                     i++;
   214                     break;
   215                 case CONSTANT_Long:
   216                     visitor.visitConstantValue(i, tag, buffer.getLong());
   217                     i+=2;
   218                     break;
   219                 case CONSTANT_Double:
   220                     visitor.visitConstantValue(i, tag, buffer.getDouble());
   221                     i+=2;
   222                     break;
   223 
   224                 case CONSTANT_Class:    // fall through:
   225                 case CONSTANT_String:
   226                     tags[i] = tag;
   227                     values[i++] = new int[] { getUnsignedShort(buffer) };
   228                     break;
   229 
   230                 case CONSTANT_Fieldref:           // fall through:
   231                 case CONSTANT_Methodref:          // fall through:
   232                 case CONSTANT_InterfaceMethodref: // fall through:
   233                 case CONSTANT_NameAndType:
   234                     tags[i] = tag;
   235                     values[i++] = new int[] { getUnsignedShort(buffer), getUnsignedShort(buffer) };
   236                     break;
   237                 default:
   238                     throw new AssertionError("invalid constant "+tag);
   239             }
   240         }
   241     }
   242 
   243     private void resolveConstantPool(Object[] values, ConstantPoolVisitor visitor) {
   244         // clean out the int[] values, which are temporary
   245         for (int beg = 1, end = values.length-1, beg2, end2;
   246              beg <= end;
   247              beg = beg2, end = end2) {
   248              beg2 = end; end2 = beg-1;
   249              //System.out.println("CP resolve pass: "+beg+".."+end);
   250              for (int i = beg; i <= end; i++) {
   251                   Object value = values[i];
   252                   if (!(value instanceof int[]))
   253                       continue;
   254                   int[] array = (int[]) value;
   255                   byte tag = tags[i];
   256                   switch (tag) {
   257                       case CONSTANT_String:
   258                           String stringBody = (String) values[array[0]];
   259                           visitor.visitConstantString(i, tag, stringBody, array[0]);
   260                           values[i] = null;
   261                           break;
   262                       case CONSTANT_Class: {
   263                           String className = (String) values[array[0]];
   264                           // use the external form favored by Class.forName:
   265                           className = className.replace('/', '.');
   266                           visitor.visitConstantString(i, tag, className, array[0]);
   267                           values[i] = className;
   268                           break;
   269                       }
   270                       case CONSTANT_NameAndType: {
   271                           String memberName = (String) values[array[0]];
   272                           String signature  = (String) values[array[1]];
   273                           visitor.visitDescriptor(i, tag, memberName, signature,
   274                                                   array[0], array[1]);
   275                           values[i] = new String[] {memberName, signature};
   276                           break;
   277                       }
   278                       case CONSTANT_Fieldref:           // fall through:
   279                       case CONSTANT_Methodref:          // fall through:
   280                       case CONSTANT_InterfaceMethodref: {
   281                               Object className   = values[array[0]];
   282                               Object nameAndType = values[array[1]];
   283                               if (!(className instanceof String) ||
   284                                   !(nameAndType instanceof String[])) {
   285                                    // one more pass is needed
   286                                    if (beg2 > i)  beg2 = i;
   287                                    if (end2 < i)  end2 = i;
   288                                    continue;
   289                               }
   290                               String[] nameAndTypeArray = (String[]) nameAndType;
   291                               visitor.visitMemberRef(i, tag,
   292                                   (String)className,
   293                                   nameAndTypeArray[0],
   294                                   nameAndTypeArray[1],
   295                                   array[0], array[1]);
   296                               values[i] = null;
   297                           }
   298                           break;
   299                       default:
   300                           continue;
   301                 }
   302             }
   303         }
   304     }
   305 
   306     private static int getUnsignedByte(ByteBuffer buffer) {
   307         return buffer.get() & 0xFF;
   308     }
   309 
   310     private static int getUnsignedShort(ByteBuffer buffer) {
   311         int b1 = getUnsignedByte(buffer);
   312         int b2 = getUnsignedByte(buffer);
   313         return (b1 << 8) + (b2 << 0);
   314     }
   315 
   316     private static String getUTF8(ByteBuffer buffer, int utfLen, char[] charArray) throws InvalidConstantPoolFormatException {
   317       int utfLimit = buffer.position() + utfLen;
   318       int index = 0;
   319       while (buffer.position() < utfLimit) {
   320           int c = buffer.get() & 0xff;
   321           if (c > 127) {
   322               buffer.position(buffer.position() - 1);
   323               return getUTF8Extended(buffer, utfLimit, charArray, index);
   324           }
   325           charArray[index++] = (char)c;
   326       }
   327       return new String(charArray, 0, index);
   328     }
   329 
   330     private static String getUTF8Extended(ByteBuffer buffer, int utfLimit, char[] charArray, int index) throws InvalidConstantPoolFormatException {
   331         int c, c2, c3;
   332         while (buffer.position() < utfLimit) {
   333             c = buffer.get() & 0xff;
   334             switch (c >> 4) {
   335                 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
   336                     /* 0xxxxxxx*/
   337                     charArray[index++] = (char)c;
   338                     break;
   339                 case 12: case 13:
   340                     /* 110x xxxx   10xx xxxx*/
   341                     c2 = buffer.get();
   342                     if ((c2 & 0xC0) != 0x80)
   343                         throw new InvalidConstantPoolFormatException(
   344                             "malformed input around byte " + buffer.position());
   345                      charArray[index++] = (char)(((c  & 0x1F) << 6) |
   346                                                   (c2 & 0x3F));
   347                     break;
   348                 case 14:
   349                     /* 1110 xxxx  10xx xxxx  10xx xxxx */
   350                     c2 = buffer.get();
   351                     c3 = buffer.get();
   352                     if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80))
   353                        throw new InvalidConstantPoolFormatException(
   354                           "malformed input around byte " + (buffer.position()));
   355                     charArray[index++] = (char)(((c  & 0x0F) << 12) |
   356                                                 ((c2 & 0x3F) << 6)  |
   357                                                 ((c3 & 0x3F) << 0));
   358                     break;
   359                 default:
   360                     /* 10xx xxxx,  1111 xxxx */
   361                     throw new InvalidConstantPoolFormatException(
   362                         "malformed input around byte " + buffer.position());
   363             }
   364         }
   365         // The number of chars produced may be less than utflen
   366         return new String(charArray, 0, index);
   367     }
   368 }