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