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