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