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  */
  23 package org.graalvm.compiler.replacements.classfile;
  24 
  25 import java.io.DataInputStream;
  26 import java.io.IOException;
  27 import java.lang.reflect.Modifier;
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 
  31 import org.graalvm.compiler.replacements.classfile.ClassfileConstant.Utf8;
  32 
  33 import jdk.vm.ci.meta.ResolvedJavaMethod;
  34 import 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  */
  44 public 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_JAVA10 = 54;
  51     private static final int MAGIC = 0xCAFEBABE;
  52 
  53     /**
  54      * Creates a {@link Classfile} by parsing the class file bytes for {@code type} loadable from
  55      * {@code context}.
  56      *
  57      * @throws NoClassDefFoundError if there is an IO error while parsing the class file
  58      */
  59     public Classfile(ResolvedJavaType type, DataInputStream stream, ClassfileBytecodeProvider context) throws IOException {
  60         this.type = type;
  61 
  62         // magic
  63         int magic = stream.readInt();
  64         assert magic == MAGIC;
  65 
  66         int minor = stream.readUnsignedShort();
  67         int major = stream.readUnsignedShort();
  68         if (major < MAJOR_VERSION_JAVA7 || major > MAJOR_VERSION_JAVA10) {
  69             throw new UnsupportedClassVersionError("Unsupported class file version: " + major + "." + minor);
  70         }
  71 
  72         ClassfileConstantPool cp = new ClassfileConstantPool(stream, context);
  73 
  74         // access_flags, this_class, super_class
  75         skipFully(stream, 6);
  76 
  77         // interfaces
  78         skipFully(stream, stream.readUnsignedShort() * 2);
  79 
  80         // fields
  81         skipFields(stream);
  82 
  83         // methods
  84         codeAttributes = readMethods(stream, cp);
  85 
  86         // attributes
  87         skipAttributes(stream);
  88     }
  89 
  90     public ClassfileBytecode getCode(String name, String descriptor) {
  91         for (ClassfileBytecode code : codeAttributes) {
  92             ResolvedJavaMethod method = code.getMethod();
  93             if (method.getName().equals(name) && method.getSignature().toMethodDescriptor().equals(descriptor)) {
  94                 return code;
  95             }
  96         }
  97         throw new NoSuchMethodError(type.toJavaName() + "." + name + descriptor);
  98     }
  99 
 100     private static void skipAttributes(DataInputStream stream) throws IOException {
 101         int attributesCount;
 102         attributesCount = stream.readUnsignedShort();
 103         for (int i = 0; i < attributesCount; i++) {
 104             skipFully(stream, 2); // name_index
 105             int attributeLength = stream.readInt();
 106             skipFully(stream, attributeLength);
 107         }
 108     }
 109 
 110     static void skipFully(DataInputStream stream, int n) throws IOException {
 111         long skipped = 0;
 112         do {
 113             long s = stream.skip(n - skipped);
 114             skipped += s;
 115             if (s == 0 && skipped != n) {
 116                 // Check for EOF (i.e., truncated class file)
 117                 if (stream.read() == -1) {
 118                     throw new IOException("truncated stream");
 119                 }
 120                 skipped++;
 121             }
 122         } while (skipped != n);
 123     }
 124 
 125     private ClassfileBytecode findCodeAttribute(DataInputStream stream, ClassfileConstantPool cp, String name, String descriptor, boolean isStatic) throws IOException {
 126         int attributesCount;
 127         attributesCount = stream.readUnsignedShort();
 128         ClassfileBytecode code = null;
 129         for (int i = 0; i < attributesCount; i++) {
 130             String attributeName = cp.get(Utf8.class, stream.readUnsignedShort()).value;
 131             int attributeLength = stream.readInt();
 132             if (code == null && attributeName.equals("Code")) {
 133                 ResolvedJavaMethod method = cp.context.findMethod(type, name, descriptor, isStatic);
 134                 // Even if we will discard the Code attribute (see below), we still
 135                 // need to parse it to reach the following class file content.
 136                 code = new ClassfileBytecode(method, stream, cp);
 137                 if (method == null) {
 138                     // This is a method hidden from reflection
 139                     // (see sun.reflect.Reflection.filterMethods)
 140                     code = null;
 141                 }
 142             } else {
 143                 skipFully(stream, attributeLength);
 144             }
 145         }
 146         return code;
 147     }
 148 
 149     private static void skipFields(DataInputStream stream) throws IOException {
 150         int count = stream.readUnsignedShort();
 151         for (int i = 0; i < count; i++) {
 152             skipFully(stream, 6); // access_flags, name_index, descriptor_index
 153             skipAttributes(stream);
 154         }
 155     }
 156 
 157     private List<ClassfileBytecode> readMethods(DataInputStream stream, ClassfileConstantPool cp) throws IOException {
 158         int count = stream.readUnsignedShort();
 159         List<ClassfileBytecode> result = new ArrayList<>(count);
 160         for (int i = 0; i < count; i++) {
 161             int accessFlags = stream.readUnsignedShort();
 162             boolean isStatic = Modifier.isStatic(accessFlags);
 163             String name = cp.get(Utf8.class, stream.readUnsignedShort()).value;
 164             String descriptor = cp.get(Utf8.class, stream.readUnsignedShort()).value;
 165             ClassfileBytecode code = findCodeAttribute(stream, cp, name, descriptor, isStatic);
 166             if (code != null) {
 167                 result.add(code);
 168             }
 169         }
 170         return result;
 171     }
 172 
 173     @Override
 174     public String toString() {
 175         return getClass().getSimpleName() + "<" + type.toJavaName() + ">";
 176     }
 177 }