Batch of classes necessary to implement invoke dynamic interfaces. Taken from JDK8 build 132
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.
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.
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).
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.
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
26 package sun.invoke.anon;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.nio.BufferUnderflowException;
31 import java.nio.ByteBuffer;
33 import static sun.invoke.anon.ConstantPoolVisitor.*;
35 /** A constant pool parser.
37 public class ConstantPoolParser {
38 final byte[] classFile;
40 final char[] firstHeader; // maghi, maglo, minor, major, cplen
42 // these are filled in on first parse:
44 char[] secondHeader; // flags, this_class, super_class, intlen
46 // used to decode UTF8 array
47 private char[] charArray = new char[80];
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.
53 public ConstantPoolParser(byte[] classFile) throws InvalidConstantPoolFormatException {
54 this.classFile = classFile;
55 this.firstHeader = parseHeader(classFile);
56 this.tags = new byte[firstHeader[4]];
59 /** Create a constant pool parser by loading the bytecodes of the
60 * class taken as argument.
62 * @param templateClass the class to parse.
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.
68 * @see #ConstantPoolParser(byte[])
69 * @see AnonymousClassLoader#readClassFile(Class)
71 public ConstantPoolParser(Class<?> templateClass) throws IOException, InvalidConstantPoolFormatException {
72 this(AnonymousClassLoader.readClassFile(templateClass));
75 /** Creates an empty patch to patch the class file
76 * used by the current parser.
77 * @return a new class patch.
79 public ConstantPoolPatch createPatch() {
80 return new ConstantPoolPatch(this);
83 /** Report the tag of the indicated CP entry.
85 * @return one of {@link ConstantPoolVisitor#CONSTANT_Utf8}, etc.
87 public byte getTag(int index) {
88 getEndOffset(); // trigger an exception if we haven't parsed yet
92 /** Report the length of the constant pool. */
93 public int getLength() {
94 return firstHeader[4];
97 /** Report the offset, within the class file, of the start of the constant pool. */
98 public int getStartOffset() {
99 return firstHeader.length * 2;
102 /** Report the offset, within the class file, of the end of the constant pool. */
103 public int getEndOffset() {
105 throw new IllegalStateException("class file has not yet been parsed");
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];
115 /** Report the total size of the class file. */
116 public int getTailLength() {
117 return classFile.length - getEndOffset();
120 /** Write the head (header plus constant pool)
121 * of the class file to the indicated stream.
123 public void writeHead(OutputStream out) throws IOException {
124 out.write(classFile, 0, getEndOffset());
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
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");
137 /** Write the tail (everything after the constant pool)
138 * of the class file to the indicated stream.
140 public void writeTail(OutputStream out) throws IOException {
141 out.write(classFile, getEndOffset(), getTailLength());
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
155 throw new InvalidConstantPoolFormatException("constant pool length < 1");
159 /** Parse the constant pool of the class
160 * calling a method visit* each time a constant pool entry is parsed.
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.
166 * @throws InvalidConstantPoolFormatException
168 public void parse(ConstantPoolVisitor visitor) throws InvalidConstantPoolFormatException {
169 ByteBuffer buffer = ByteBuffer.wrap(classFile);
170 buffer.position(getStartOffset()); //skip header
172 Object[] values = new Object[getLength()];
174 parseConstantPool(buffer, values, visitor);
175 } catch(BufferUnderflowException e) {
176 throw new InvalidConstantPoolFormatException(e);
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);
185 resolveConstantPool(values, visitor);
188 private char[] getCharArray(int utfLength) {
189 if (utfLength <= charArray.length)
191 return charArray = new char[utfLength];
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);
201 int utfLen = getUnsignedShort(buffer);
202 String value = getUTF8(buffer, utfLen, getCharArray(utfLen));
203 visitor.visitUTF8(i, CONSTANT_Utf8, value);
207 case CONSTANT_Integer:
208 visitor.visitConstantValue(i, tag, buffer.getInt());
212 visitor.visitConstantValue(i, tag, buffer.getFloat());
216 visitor.visitConstantValue(i, tag, buffer.getLong());
219 case CONSTANT_Double:
220 visitor.visitConstantValue(i, tag, buffer.getDouble());
224 case CONSTANT_Class: // fall through:
225 case CONSTANT_String:
227 values[i++] = new int[] { getUnsignedShort(buffer) };
230 case CONSTANT_Fieldref: // fall through:
231 case CONSTANT_Methodref: // fall through:
232 case CONSTANT_InterfaceMethodref: // fall through:
233 case CONSTANT_NameAndType:
235 values[i++] = new int[] { getUnsignedShort(buffer), getUnsignedShort(buffer) };
238 throw new AssertionError("invalid constant "+tag);
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;
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[]))
254 int[] array = (int[]) value;
257 case CONSTANT_String:
258 String stringBody = (String) values[array[0]];
259 visitor.visitConstantString(i, tag, stringBody, array[0]);
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;
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,
275 values[i] = new String[] {memberName, signature};
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;
290 String[] nameAndTypeArray = (String[]) nameAndType;
291 visitor.visitMemberRef(i, tag,
306 private static int getUnsignedByte(ByteBuffer buffer) {
307 return buffer.get() & 0xFF;
310 private static int getUnsignedShort(ByteBuffer buffer) {
311 int b1 = getUnsignedByte(buffer);
312 int b2 = getUnsignedByte(buffer);
313 return (b1 << 8) + (b2 << 0);
316 private static String getUTF8(ByteBuffer buffer, int utfLen, char[] charArray) throws InvalidConstantPoolFormatException {
317 int utfLimit = buffer.position() + utfLen;
319 while (buffer.position() < utfLimit) {
320 int c = buffer.get() & 0xff;
322 buffer.position(buffer.position() - 1);
323 return getUTF8Extended(buffer, utfLimit, charArray, index);
325 charArray[index++] = (char)c;
327 return new String(charArray, 0, index);
330 private static String getUTF8Extended(ByteBuffer buffer, int utfLimit, char[] charArray, int index) throws InvalidConstantPoolFormatException {
332 while (buffer.position() < utfLimit) {
333 c = buffer.get() & 0xff;
335 case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
337 charArray[index++] = (char)c;
340 /* 110x xxxx 10xx xxxx*/
342 if ((c2 & 0xC0) != 0x80)
343 throw new InvalidConstantPoolFormatException(
344 "malformed input around byte " + buffer.position());
345 charArray[index++] = (char)(((c & 0x1F) << 6) |
349 /* 1110 xxxx 10xx xxxx 10xx xxxx */
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) |
360 /* 10xx xxxx, 1111 xxxx */
361 throw new InvalidConstantPoolFormatException(
362 "malformed input around byte " + buffer.position());
365 // The number of chars produced may be less than utflen
366 return new String(charArray, 0, index);