1 /*
   2  * Copyright (c) 2013, 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 jdk.vm.ci.runtime.test;
  24 
  25 import static java.lang.reflect.Modifier.isFinal;
  26 import static java.lang.reflect.Modifier.isStatic;
  27 
  28 import java.io.Serializable;
  29 import java.lang.reflect.Array;
  30 import java.lang.reflect.Field;
  31 import java.lang.reflect.Method;
  32 import java.util.AbstractCollection;
  33 import java.util.AbstractList;
  34 import java.util.ArrayDeque;
  35 import java.util.ArrayList;
  36 import java.util.Collection;
  37 import java.util.Collections;
  38 import java.util.HashMap;
  39 import java.util.HashSet;
  40 import java.util.IdentityHashMap;
  41 import java.util.LinkedHashMap;
  42 import java.util.LinkedList;
  43 import java.util.List;
  44 import java.util.Map;
  45 import java.util.Queue;
  46 import java.util.Set;
  47 import java.util.TreeMap;
  48 import java.util.stream.Collectors;
  49 
  50 import jdk.vm.ci.meta.ConstantReflectionProvider;
  51 import jdk.vm.ci.meta.JavaConstant;
  52 import jdk.vm.ci.meta.MetaAccessProvider;
  53 import jdk.vm.ci.meta.ResolvedJavaField;
  54 import jdk.vm.ci.meta.ResolvedJavaType;
  55 import jdk.vm.ci.runtime.JVMCI;
  56 
  57 import org.junit.Test;
  58 
  59 import jdk.internal.misc.Unsafe;
  60 
  61 //JaCoCo Exclude
  62 
  63 /**
  64  * Context for type related tests.
  65  */
  66 public class TypeUniverse {
  67 
  68     public static final Unsafe unsafe;
  69     public static final double JAVA_VERSION = Double.valueOf(System.getProperty("java.specification.version"));
  70 
  71     public static final MetaAccessProvider metaAccess = JVMCI.getRuntime().getHostJVMCIBackend().getMetaAccess();
  72     public static final ConstantReflectionProvider constantReflection = JVMCI.getRuntime().getHostJVMCIBackend().getConstantReflection();
  73     public static final Collection<Class<?>> classes = new HashSet<>();
  74     public static final Set<ResolvedJavaType> javaTypes;
  75     public static final Map<Class<?>, Class<?>> arrayClasses = new HashMap<>();
  76 
  77     private static List<ConstantValue> constants;
  78 
  79     public class InnerClass {
  80 
  81     }
  82 
  83     public static class InnerStaticClass {
  84 
  85     }
  86 
  87     public static final class InnerStaticFinalClass {
  88 
  89     }
  90 
  91     private class PrivateInnerClass {
  92 
  93     }
  94 
  95     protected class ProtectedInnerClass {
  96 
  97     }
  98 
  99     static {
 100         Unsafe theUnsafe = null;
 101         try {
 102             theUnsafe = Unsafe.getUnsafe();
 103         } catch (Exception e) {
 104             try {
 105                 Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
 106                 theUnsafeField.setAccessible(true);
 107                 theUnsafe = (Unsafe) theUnsafeField.get(null);
 108             } catch (Exception e1) {
 109                 throw (InternalError) new InternalError("unable to initialize unsafe").initCause(e1);
 110             }
 111         }
 112         unsafe = theUnsafe;
 113 
 114         Class<?>[] initialClasses = {void.class, boolean.class, byte.class, short.class, char.class, int.class, float.class, long.class, double.class, Object.class, Class.class, boolean[].class,
 115                         byte[].class, short[].class, char[].class, int[].class, float[].class, long[].class, double[].class, Object[].class, Class[].class, List[].class, boolean[][].class,
 116                         byte[][].class, short[][].class, char[][].class, int[][].class, float[][].class, long[][].class, double[][].class, Object[][].class, Class[][].class, List[][].class,
 117                         ClassLoader.class, String.class, Serializable.class, Cloneable.class, Test.class, TestMetaAccessProvider.class, List.class, Collection.class, Map.class, Queue.class,
 118                         HashMap.class, LinkedHashMap.class, IdentityHashMap.class, AbstractCollection.class, AbstractList.class, ArrayList.class, InnerClass.class, InnerStaticClass.class,
 119                         InnerStaticFinalClass.class, PrivateInnerClass.class, ProtectedInnerClass.class};
 120         for (Class<?> c : initialClasses) {
 121             addClass(c);
 122         }
 123 
 124         javaTypes = Collections.unmodifiableSet(classes.stream().map(c -> metaAccess.lookupJavaType(c)).collect(Collectors.toSet()));
 125     }
 126 
 127     static class ConstantsUniverse {
 128         static final Object[] ARRAYS = classes.stream().map(c -> c != void.class && !c.isArray() ? Array.newInstance(c, 42) : null).filter(o -> o != null).collect(Collectors.toList()).toArray();
 129         static final Object CONST1 = new ArrayList<>();
 130         static final Object CONST2 = new ArrayList<>();
 131         static final Object CONST3 = new IdentityHashMap<>();
 132         static final Object CONST4 = new LinkedHashMap<>();
 133         static final Object CONST5 = new TreeMap<>();
 134         static final Object CONST6 = new ArrayDeque<>();
 135         static final Object CONST7 = new LinkedList<>();
 136         static final Object CONST8 = "a string";
 137         static final Object CONST9 = 42;
 138         static final Object CONST10 = String.class;
 139         static final Object CONST11 = String[].class;
 140     }
 141 
 142     public static List<ConstantValue> constants() {
 143         if (constants == null) {
 144             List<ConstantValue> res = readConstants(JavaConstant.class);
 145             res.addAll(readConstants(ConstantsUniverse.class));
 146             constants = res;
 147         }
 148         return constants;
 149     }
 150 
 151     public static class ConstantValue {
 152         public final String name;
 153         public final JavaConstant value;
 154         public final Object boxed;
 155 
 156         public ConstantValue(String name, JavaConstant value, Object boxed) {
 157             this.name = name;
 158             this.value = value;
 159             this.boxed = boxed;
 160         }
 161 
 162         @Override
 163         public String toString() {
 164             return name + "=" + value;
 165         }
 166 
 167         public String getSimpleName() {
 168             return name.substring(name.lastIndexOf('.') + 1);
 169         }
 170     }
 171 
 172     /**
 173      * Reads the value of all {@code static final} fields from a given class into an array of
 174      * {@link ConstantValue}s.
 175      */
 176     public static List<ConstantValue> readConstants(Class<?> fromClass) {
 177         try {
 178             List<ConstantValue> res = new ArrayList<>();
 179             for (Field field : fromClass.getDeclaredFields()) {
 180                 if (isStatic(field.getModifiers()) && isFinal(field.getModifiers())) {
 181                     ResolvedJavaField javaField = metaAccess.lookupJavaField(field);
 182                     Object boxed = field.get(null);
 183                     if (boxed instanceof JavaConstant) {
 184                         res.add(new ConstantValue(javaField.format("%H.%n"), (JavaConstant) boxed, boxed));
 185                     } else {
 186                         JavaConstant value = constantReflection.readFieldValue(javaField, null);
 187                         if (value != null) {
 188                             res.add(new ConstantValue(javaField.format("%H.%n"), value, boxed));
 189                             if (boxed instanceof Object[]) {
 190                                 Object[] arr = (Object[]) boxed;
 191                                 for (int i = 0; i < arr.length; i++) {
 192                                     JavaConstant element = constantReflection.readArrayElement(value, i);
 193                                     if (element != null) {
 194                                         res.add(new ConstantValue(javaField.format("%H.%n[" + i + "]"), element, arr[i]));
 195                                     }
 196                                 }
 197                             }
 198                         }
 199                     }
 200                 }
 201             }
 202             return res;
 203         } catch (Exception e) {
 204             throw new AssertionError(e);
 205         }
 206     }
 207 
 208     public synchronized Class<?> getArrayClass(Class<?> componentType) {
 209         Class<?> arrayClass = arrayClasses.get(componentType);
 210         if (arrayClass == null) {
 211             arrayClass = Array.newInstance(componentType, 0).getClass();
 212             arrayClasses.put(componentType, arrayClass);
 213         }
 214         return arrayClass;
 215     }
 216 
 217     public static int dimensions(Class<?> c) {
 218         if (c.getComponentType() != null) {
 219             return 1 + dimensions(c.getComponentType());
 220         }
 221         return 0;
 222     }
 223 
 224     private static void addClass(Class<?> c) {
 225         if (classes.add(c)) {
 226             if (c.getSuperclass() != null) {
 227                 addClass(c.getSuperclass());
 228             }
 229             for (Class<?> sc : c.getInterfaces()) {
 230                 addClass(sc);
 231             }
 232             for (Class<?> dc : c.getDeclaredClasses()) {
 233                 addClass(dc);
 234             }
 235             for (Method m : c.getDeclaredMethods()) {
 236                 addClass(m.getReturnType());
 237                 for (Class<?> p : m.getParameterTypes()) {
 238                     addClass(p);
 239                 }
 240             }
 241 
 242             if (c != void.class && dimensions(c) < 2) {
 243                 Class<?> arrayClass = Array.newInstance(c, 0).getClass();
 244                 arrayClasses.put(c, arrayClass);
 245                 addClass(arrayClass);
 246             }
 247         }
 248     }
 249 }