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.  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 package valhalla.shady;
  26 
  27 import jdk.experimental.bytecode.BasicClassBuilder;
  28 import jdk.internal.misc.Unsafe;
  29 import jdk.internal.misc.VM;
  30 import sun.security.action.GetPropertyAction;
  31 
  32 import java.io.BufferedOutputStream;
  33 import java.io.File;
  34 import java.io.IOException;
  35 import java.io.OutputStream;
  36 import java.nio.file.Files;
  37 import java.nio.file.Path;
  38 import java.nio.file.Paths;
  39 import java.security.ProtectionDomain;
  40 import java.util.Properties;
  41 
  42 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  43 
  44 import jdk.internal.misc.JavaLangAccess;
  45 import jdk.internal.misc.SharedSecrets;
  46 public class MinimalValueTypes_1_0 {
  47 
  48     public static final int V53_1 = 1 << 16 | 53;
  49     public static final int ACC_VALUE = ACC_NATIVE;
  50     public static final String OBJECT_CLASS_DESC = "java/lang/Object";
  51     public static final String VALUE_CLASS_DESC = "java/lang/__Value";
  52 
  53     public static final String DERIVE_VALUE_TYPE_DESC = "Ljvm/internal/value/ValueCapableClass;";
  54     public static final String DERIVE_VT_CLASSNAME_POSTFIX = "$Value";
  55     public static final int    DERIVE_VT_CLASS_ACCESS = ACC_PUBLIC|ACC_SUPER|ACC_FINAL|ACC_VALUE|ACC_SYNTHETIC;
  56 
  57     public static final boolean DUMP_CLASS_FILES;
  58     private static final boolean VALUE_TYPE_ENABLED;
  59     private static final JavaLangAccess JLA;
  60 
  61     static {
  62         // Use same property as in j.l.invoke.MethodHandleStatics
  63         Properties props = GetPropertyAction.privilegedGetProperties();
  64         DUMP_CLASS_FILES = Boolean.parseBoolean(
  65             props.getProperty("java.lang.invoke.MethodHandle.DUMP_CLASS_FILES"));
  66 
  67         VALUE_TYPE_ENABLED = Boolean.parseBoolean(
  68             props.getProperty("valhalla.enableValueType"));
  69 
  70         JLA = SharedSecrets.getJavaLangAccess();
  71     }
  72 
  73     public static String getValueTypeClassName(ValueTypeDesc valueTypeDesc) {
  74         return getValueTypeClassName(valueTypeDesc.getName());
  75     }
  76 
  77     public static String getValueTypeClassName(String vccName) {
  78         return vccName + DERIVE_VT_CLASSNAME_POSTFIX;
  79     }
  80 
  81     public static String getValueCapableClassName(String valName) {
  82         return valName.substring(0, valName.length() - DERIVE_VT_CLASSNAME_POSTFIX.length());
  83     }
  84 
  85     public static boolean isValueType(Class<?> dvt) {
  86         return (dvt.getModifiers() & ACC_VALUE) != 0;
  87     }
  88 
  89     public static boolean isValueCapable(Class<?> vcc) {
  90         return vcc.getDeclaredAnnotation(jvm.internal.value.ValueCapableClass.class) != null;
  91     }
  92 
  93     public static Class<?> getValueCapableClass(Class<?> dvt) {
  94         if (!isValueType(dvt)) {
  95             throw new IllegalArgumentException(dvt + " is not a derived value type");
  96         }
  97 
  98         Class<?> c = Class.forName(dvt.getModule(), getValueCapableClassName(dvt.getName()));
  99         if (c == null || !isValueCapable(c)) {
 100             throw new InternalError(dvt + " not bound to ValueType");
 101         }
 102         return c;
 103     }
 104 
 105     public static Class<?> getValueTypeClass(Class<?> vcc) {
 106         if (!isValueCapable(vcc)) {
 107             throw new IllegalArgumentException(vcc + " is not a value capable class");
 108         }
 109         return loadValueTypeClass(vcc, getValueTypeClassName(vcc.getName()));
 110     }
 111 
 112     public static Class<?> loadValueTypeClass(Class<?> vcc, String className) {
 113         if (!isValueCapable(vcc)) {
 114             throw new IllegalArgumentException(vcc.getName() + " is not a value capable class");
 115         }
 116         return JLA.loadValueTypeClass(vcc.getModule(), vcc.getClassLoader(), className);
 117     }
 118 
 119     /**
 120      * This method is invoked by the VM.
 121      *
 122      * @param fds   : name/sig pairs
 123      * @param fmods : field modifiers
 124      */
 125     public static String createDerivedValueType(String vccInternalClassName,
 126                                                 ClassLoader cl,
 127                                                 ProtectionDomain pd,
 128                                                 String[] fds,
 129                                                 int[] fmods) {
 130         String vtInternalClassName = getValueTypeClassName(vccInternalClassName);
 131         ValueTypeDesc valueTypeDesc = new ValueTypeDesc(vccInternalClassName, fds, fmods);
 132         byte[] valueTypeBytes = createValueType(valueTypeDesc);
 133         Class<?> vtClass = Unsafe.getUnsafe().defineClass(vtInternalClassName, valueTypeBytes, 0, valueTypeBytes.length, cl, pd);
 134         return vtInternalClassName;
 135     }
 136 
 137     public static byte[] createValueType(ValueTypeDesc valueTypeDesc) {
 138 
 139         String valueTypeClassName = getValueTypeClassName(valueTypeDesc);
 140 
 141         BasicClassBuilder builder = new BasicClassBuilder(mangleValueClassName(valueTypeClassName), 53, 1)
 142             .withFlags(DERIVE_VT_CLASS_ACCESS)
 143             .withSuperclass(mangleValueClassName(VALUE_CLASS_DESC));
 144 
 145         ValueTypeDesc.Field[] fields = valueTypeDesc.getFields();
 146         for (ValueTypeDesc.Field field : fields) {
 147             builder.withField(field.name, field.type, F -> F.withFlags(field.modifiers));
 148         }
 149 
 150         byte[] newBytes = builder.build();
 151         maybeDump(valueTypeClassName, newBytes);
 152         return newBytes;
 153     }
 154 
 155     /** debugging flag for saving generated class files */
 156     private static final Path DUMP_CLASS_FILES_DIR;
 157 
 158     static {
 159         if (DUMP_CLASS_FILES) {
 160             try {
 161                 Path dumpDir = Paths.get("DUMP_CLASS_FILES");
 162                 Files.createDirectories(dumpDir);
 163                 DUMP_CLASS_FILES_DIR = dumpDir;
 164             } catch (Exception e) {
 165                 throw new InternalError(e);
 166             }
 167         } else {
 168             DUMP_CLASS_FILES_DIR = null;
 169         }
 170     }
 171 
 172     public static void maybeDump(final String className, final byte[] classFile) {
 173         if (DUMP_CLASS_FILES_DIR != null) {
 174             java.security.AccessController.doPrivileged(
 175                 new java.security.PrivilegedAction<>() {
 176                     public Void run() {
 177                         String dumpName = className;
 178                         //dumpName = dumpName.replace('/', '-');
 179                         Path dumpFile = DUMP_CLASS_FILES_DIR.resolve(dumpName + ".class");
 180                         File root = dumpFile.getParent().toFile();
 181                         if (!root.exists() && !root.mkdirs()) {
 182                             throw new IllegalStateException("Could not create dump file directory: " + root);
 183                         }
 184                         System.out.println("dump: " + dumpFile);
 185                         try (OutputStream os = Files.newOutputStream(dumpFile);
 186                              BufferedOutputStream bos = new BufferedOutputStream(os)) {
 187                             bos.write(classFile);
 188                         } catch (IOException ex) {
 189                             throw new InternalError(ex);
 190                         }
 191                         return null;
 192                     }
 193                 });
 194 
 195         }
 196     }
 197 
 198     private final native Class<?> getDerivedValueType(Class<?> ofClass);
 199 
 200     public static Class<?> getValueClass() {
 201         return VALUE_TYPE_ENABLED ? ValueClassHolder.CLASS_OBJECT : null;
 202     }
 203 
 204     public static String mangleValueClassName(String name) {
 205         return ";Q" + name + ";";
 206     }
 207 
 208     /*
 209      * A holder class that references __Value to be loaded only when MVT is enabled.
 210      *
 211      * This holder class would fail verification if loaded if MVT is not enabled.
 212      */
 213     private static class ValueClassHolder {
 214          static final Class<?> CLASS_OBJECT =
 215              (Class<?>)(Object)__Value.class; //hack around static type-system checks
 216     }
 217 }