Classfile.java revision 12657:6ef01bd40ce2
1/*
2 * Copyright (c) 2016, 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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.graalvm.compiler.replacements.classfile;
24
25import java.io.DataInputStream;
26import java.io.IOException;
27import java.lang.reflect.Modifier;
28import java.util.ArrayList;
29import java.util.List;
30
31import org.graalvm.compiler.replacements.classfile.ClassfileConstant.Utf8;
32
33import jdk.vm.ci.meta.ResolvedJavaMethod;
34import jdk.vm.ci.meta.ResolvedJavaType;
35
36/**
37 * Container for objects representing the {@code Code} attributes parsed from a class file.
38 *
39 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.3">Code
40 *      attributes</a>
41 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4">Constant
42 *      Pool</a>
43 */
44public class Classfile {
45
46    private final ResolvedJavaType type;
47    private final List<ClassfileBytecode> codeAttributes;
48
49    private static final int MAJOR_VERSION_JAVA7 = 51;
50    private static final int MAJOR_VERSION_JAVA9 = 53;
51
52    /**
53     * Creates a {@link Classfile} by parsing the class file bytes for {@code type} loadable from
54     * {@code context}.
55     *
56     * @throws NoClassDefFoundError if there is an IO error while parsing the class file
57     */
58    public Classfile(ResolvedJavaType type, DataInputStream stream, ClassfileBytecodeProvider context) throws IOException {
59        this.type = type;
60
61        // magic
62        int magic = stream.readInt();
63        assert magic == 0xCAFEBABE;
64
65        int minor = stream.readUnsignedShort();
66        int major = stream.readUnsignedShort();
67        if (major < MAJOR_VERSION_JAVA7 || major > MAJOR_VERSION_JAVA9) {
68            throw new UnsupportedClassVersionError("Unsupported class file version: " + major + "." + minor);
69        }
70
71        ClassfileConstantPool cp = new ClassfileConstantPool(stream, context);
72
73        // access_flags, this_class, super_class
74        skipFully(stream, 6);
75
76        // interfaces
77        skipFully(stream, stream.readUnsignedShort() * 2);
78
79        // fields
80        skipFields(stream);
81
82        // methods
83        codeAttributes = readMethods(stream, cp);
84
85        // attributes
86        skipAttributes(stream);
87    }
88
89    public ClassfileBytecode getCode(String name, String descriptor) {
90        for (ClassfileBytecode code : codeAttributes) {
91            ResolvedJavaMethod method = code.getMethod();
92            if (method.getName().equals(name) && method.getSignature().toMethodDescriptor().equals(descriptor)) {
93                return code;
94            }
95        }
96        throw new NoSuchMethodError(type.toJavaName() + "." + name + descriptor);
97    }
98
99    private static void skipAttributes(DataInputStream stream) throws IOException {
100        int attributesCount;
101        attributesCount = stream.readUnsignedShort();
102        for (int i = 0; i < attributesCount; i++) {
103            skipFully(stream, 2); // name_index
104            int attributeLength = stream.readInt();
105            skipFully(stream, attributeLength);
106        }
107    }
108
109    static void skipFully(DataInputStream stream, int n) throws IOException {
110        long skipped = 0;
111        do {
112            long s = stream.skip(n - skipped);
113            skipped += s;
114            if (s == 0 && skipped != n) {
115                // Check for EOF (i.e., truncated class file)
116                if (stream.read() == -1) {
117                    throw new IOException("truncated stream");
118                }
119                skipped++;
120            }
121        } while (skipped != n);
122    }
123
124    private ClassfileBytecode findCodeAttribute(DataInputStream stream, ClassfileConstantPool cp, String name, String descriptor, boolean isStatic) throws IOException {
125        int attributesCount;
126        attributesCount = stream.readUnsignedShort();
127        ClassfileBytecode code = null;
128        for (int i = 0; i < attributesCount; i++) {
129            String attributeName = cp.get(Utf8.class, stream.readUnsignedShort()).value;
130            int attributeLength = stream.readInt();
131            if (code == null && attributeName.equals("Code")) {
132                ResolvedJavaMethod method = ClassfileBytecodeProvider.findMethod(type, name, descriptor, isStatic);
133                // Even if we will discard the Code attribute (see below), we still
134                // need to parse it to reach the following class file content.
135                code = new ClassfileBytecode(method, stream, cp);
136                if (method == null) {
137                    // This is a method hidden from reflection
138                    // (see sun.reflect.Reflection.filterMethods)
139                    code = null;
140                }
141            } else {
142                skipFully(stream, attributeLength);
143            }
144        }
145        return code;
146    }
147
148    private static void skipFields(DataInputStream stream) throws IOException {
149        int count = stream.readUnsignedShort();
150        for (int i = 0; i < count; i++) {
151            skipFully(stream, 6); // access_flags, name_index, descriptor_index
152            skipAttributes(stream);
153        }
154    }
155
156    private List<ClassfileBytecode> readMethods(DataInputStream stream, ClassfileConstantPool cp) throws IOException {
157        int count = stream.readUnsignedShort();
158        List<ClassfileBytecode> result = new ArrayList<>(count);
159        for (int i = 0; i < count; i++) {
160            int accessFlags = stream.readUnsignedShort();
161            boolean isStatic = Modifier.isStatic(accessFlags);
162            String name = cp.get(Utf8.class, stream.readUnsignedShort()).value;
163            String descriptor = cp.get(Utf8.class, stream.readUnsignedShort()).value;
164            ClassfileBytecode code = findCodeAttribute(stream, cp, name, descriptor, isStatic);
165            if (code != null) {
166                result.add(code);
167            }
168        }
169        return result;
170    }
171
172    @Override
173    public String toString() {
174        return getClass().getSimpleName() + "<" + type.toJavaName() + ">";
175    }
176}
177