1 /*
   2  * Copyright (c) 2012, 2015, 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.meta;
  24 
  25 import java.io.PrintStream;
  26 import java.lang.reflect.Field;
  27 import java.lang.reflect.Modifier;
  28 import java.util.ArrayDeque;
  29 import java.util.ArrayList;
  30 import java.util.Collections;
  31 import java.util.Comparator;
  32 import java.util.Deque;
  33 import java.util.HashMap;
  34 import java.util.HashSet;
  35 import java.util.Set;
  36 
  37 /**
  38  * Miscellaneous collection of utility methods used by {@code jdk.vm.ci.meta} and its clients.
  39  */
  40 public class MetaUtil {
  41 
  42     private static class ClassInfo {
  43         public long totalSize;
  44         public long instanceCount;
  45 
  46         @Override
  47         public String toString() {
  48             return "totalSize=" + totalSize + ", instanceCount=" + instanceCount;
  49         }
  50     }
  51 
  52     /**
  53      * Returns the number of bytes occupied by this constant value or constant object and
  54      * recursively all values reachable from this value.
  55      *
  56      * @param constant the constant whose bytes should be measured
  57      * @param printTopN print total size and instance count of the top n classes is desired
  58      * @return the number of bytes occupied by this constant
  59      */
  60     public static long getMemorySizeRecursive(MetaAccessProvider access, ConstantReflectionProvider constantReflection, JavaConstant constant, PrintStream out, int printTopN) {
  61         Set<JavaConstant> marked = new HashSet<>();
  62         Deque<JavaConstant> stack = new ArrayDeque<>();
  63         if (constant.getJavaKind() == JavaKind.Object && constant.isNonNull()) {
  64             marked.add(constant);
  65         }
  66         final HashMap<ResolvedJavaType, ClassInfo> histogram = new HashMap<>();
  67         stack.push(constant);
  68         long sum = 0;
  69         while (!stack.isEmpty()) {
  70             JavaConstant c = stack.pop();
  71             long memorySize = access.getMemorySize(constant);
  72             sum += memorySize;
  73             if (c.getJavaKind() == JavaKind.Object && c.isNonNull()) {
  74                 ResolvedJavaType clazz = access.lookupJavaType(c);
  75                 if (!histogram.containsKey(clazz)) {
  76                     histogram.put(clazz, new ClassInfo());
  77                 }
  78                 ClassInfo info = histogram.get(clazz);
  79                 info.instanceCount++;
  80                 info.totalSize += memorySize;
  81                 ResolvedJavaType type = access.lookupJavaType(c);
  82                 if (type.isArray()) {
  83                     if (!type.getComponentType().isPrimitive()) {
  84                         int length = constantReflection.readArrayLength(c);
  85                         for (int i = 0; i < length; i++) {
  86                             JavaConstant value = constantReflection.readArrayElement(c, i);
  87                             pushConstant(marked, stack, value);
  88                         }
  89                     }
  90                 } else {
  91                     ResolvedJavaField[] instanceFields = type.getInstanceFields(true);
  92                     for (ResolvedJavaField f : instanceFields) {
  93                         if (f.getJavaKind() == JavaKind.Object) {
  94                             JavaConstant value = constantReflection.readFieldValue(f, c);
  95                             pushConstant(marked, stack, value);
  96                         }
  97                     }
  98                 }
  99             }
 100         }
 101         ArrayList<ResolvedJavaType> clazzes = new ArrayList<>();
 102         clazzes.addAll(histogram.keySet());
 103         Collections.sort(clazzes, new Comparator<ResolvedJavaType>() {
 104 
 105             @Override
 106             public int compare(ResolvedJavaType o1, ResolvedJavaType o2) {
 107                 long l1 = histogram.get(o1).totalSize;
 108                 long l2 = histogram.get(o2).totalSize;
 109                 if (l1 > l2) {
 110                     return -1;
 111                 } else if (l1 == l2) {
 112                     return 0;
 113                 } else {
 114                     return 1;
 115                 }
 116             }
 117         });
 118 
 119         int z = 0;
 120         for (ResolvedJavaType c : clazzes) {
 121             if (z > printTopN) {
 122                 break;
 123             }
 124             out.println("Class " + c + ", " + histogram.get(c));
 125             ++z;
 126         }
 127 
 128         return sum;
 129     }
 130 
 131     private static void pushConstant(Set<JavaConstant> marked, Deque<JavaConstant> stack, JavaConstant value) {
 132         if (value.isNonNull()) {
 133             if (!marked.contains(value)) {
 134                 marked.add(value);
 135                 stack.push(value);
 136             }
 137         }
 138     }
 139 
 140     /**
 141      * Calls {@link JavaType#resolve(ResolvedJavaType)} on an array of types.
 142      */
 143     public static ResolvedJavaType[] resolveJavaTypes(JavaType[] types, ResolvedJavaType accessingClass) {
 144         ResolvedJavaType[] result = new ResolvedJavaType[types.length];
 145         for (int i = 0; i < result.length; i++) {
 146             result[i] = types[i].resolve(accessingClass);
 147         }
 148         return result;
 149     }
 150 
 151     /**
 152      * Extends the functionality of {@link Class#getSimpleName()} to include a non-empty string for
 153      * anonymous and local classes.
 154      *
 155      * @param clazz the class for which the simple name is being requested
 156      * @param withEnclosingClass specifies if the returned name should be qualified with the name(s)
 157      *            of the enclosing class/classes of {@code clazz} (if any). This option is ignored
 158      *            if {@code clazz} denotes an anonymous or local class.
 159      * @return the simple name
 160      */
 161     public static String getSimpleName(Class<?> clazz, boolean withEnclosingClass) {
 162         final String simpleName = clazz.getSimpleName();
 163         if (simpleName.length() != 0) {
 164             if (withEnclosingClass) {
 165                 String prefix = "";
 166                 Class<?> enclosingClass = clazz;
 167                 while ((enclosingClass = enclosingClass.getEnclosingClass()) != null) {
 168                     prefix = enclosingClass.getSimpleName() + "." + prefix;
 169                 }
 170                 return prefix + simpleName;
 171             }
 172             return simpleName;
 173         }
 174         // Must be an anonymous or local class
 175         final String name = clazz.getName();
 176         int index = name.indexOf('$');
 177         if (index == -1) {
 178             return name;
 179         }
 180         index = name.lastIndexOf('.', index);
 181         if (index == -1) {
 182             return name;
 183         }
 184         return name.substring(index + 1);
 185     }
 186 
 187     static String internalNameToJava(String name, boolean qualified, boolean classForNameCompatible) {
 188         switch (name.charAt(0)) {
 189             case 'L': {
 190                 String result = name.substring(1, name.length() - 1).replace('/', '.');
 191                 if (!qualified) {
 192                     final int lastDot = result.lastIndexOf('.');
 193                     if (lastDot != -1) {
 194                         result = result.substring(lastDot + 1);
 195                     }
 196                 }
 197                 return result;
 198             }
 199             case '[':
 200                 return classForNameCompatible ? name.replace('/', '.') : internalNameToJava(name.substring(1), qualified, classForNameCompatible) + "[]";
 201             default:
 202                 if (name.length() != 1) {
 203                     throw new IllegalArgumentException("Illegal internal name: " + name);
 204                 }
 205                 return JavaKind.fromPrimitiveOrVoidTypeChar(name.charAt(0)).getJavaName();
 206         }
 207     }
 208 
 209     /**
 210      * Turns an class name in internal format into a resolved Java type.
 211      */
 212     public static ResolvedJavaType classForName(String internal, MetaAccessProvider metaAccess, ClassLoader cl) {
 213         JavaKind k = JavaKind.fromTypeString(internal);
 214         try {
 215             String n = internalNameToJava(internal, true, true);
 216             return metaAccess.lookupJavaType(k.isPrimitive() ? k.toJavaClass() : Class.forName(n, true, cl));
 217         } catch (ClassNotFoundException cnfe) {
 218             throw new IllegalArgumentException("could not instantiate class described by " + internal, cnfe);
 219         }
 220     }
 221 
 222     /**
 223      * Convenient shortcut for calling
 224      * {@link #appendLocation(StringBuilder, ResolvedJavaMethod, int)} without having to supply a
 225      * {@link StringBuilder} instance and convert the result to a string.
 226      */
 227     public static String toLocation(ResolvedJavaMethod method, int bci) {
 228         return appendLocation(new StringBuilder(), method, bci).toString();
 229     }
 230 
 231     /**
 232      * Appends a string representation of a location specified by a given method and bci to a given
 233      * {@link StringBuilder}. If a stack trace element with a non-null file name and non-negative
 234      * line number is {@linkplain ResolvedJavaMethod#asStackTraceElement(int) available} for the
 235      * given method, then the string returned is the {@link StackTraceElement#toString()} value of
 236      * the stack trace element, suffixed by the bci location. For example:
 237      *
 238      * <pre>
 239      *     java.lang.String.valueOf(String.java:2930) [bci: 12]
 240      * </pre>
 241      *
 242      * Otherwise, the string returned is the value of applying {@link JavaMethod#format(String)}
 243      * with the format string {@code "%H.%n(%p)"}, suffixed by the bci location. For example:
 244      *
 245      * <pre>
 246      *     java.lang.String.valueOf(int) [bci: 12]
 247      * </pre>
 248      *
 249      * @param sb
 250      * @param method
 251      * @param bci
 252      */
 253     public static StringBuilder appendLocation(StringBuilder sb, ResolvedJavaMethod method, int bci) {
 254         if (method != null) {
 255             StackTraceElement ste = method.asStackTraceElement(bci);
 256             if (ste.getFileName() != null && ste.getLineNumber() > 0) {
 257                 sb.append(ste);
 258             } else {
 259                 sb.append(method.format("%H.%n(%p)"));
 260             }
 261         } else {
 262             sb.append("Null method");
 263         }
 264         return sb.append(" [bci: ").append(bci).append(']');
 265     }
 266 
 267     static void appendProfile(StringBuilder buf, AbstractJavaProfile<?, ?> profile, int bci, String type, String sep) {
 268         if (profile != null) {
 269             AbstractProfiledItem<?>[] pitems = profile.getItems();
 270             if (pitems != null) {
 271                 buf.append(String.format("%s@%d:", type, bci));
 272                 for (int j = 0; j < pitems.length; j++) {
 273                     AbstractProfiledItem<?> pitem = pitems[j];
 274                     buf.append(String.format(" %.6f (%s)%s", pitem.getProbability(), pitem.getItem(), sep));
 275                 }
 276                 if (profile.getNotRecordedProbability() != 0) {
 277                     buf.append(String.format(" %.6f <other %s>%s", profile.getNotRecordedProbability(), type, sep));
 278                 } else {
 279                     buf.append(String.format(" <no other %s>%s", type, sep));
 280                 }
 281             }
 282         }
 283     }
 284 
 285     /**
 286      * Converts a Java source-language class name into the internal form.
 287      *
 288      * @param className the class name
 289      * @return the internal name form of the class name
 290      */
 291     public static String toInternalName(String className) {
 292         if (className.startsWith("[")) {
 293             /* Already in the correct array style. */
 294             return className.replace('.', '/');
 295         }
 296 
 297         StringBuilder result = new StringBuilder();
 298         String base = className;
 299         while (base.endsWith("[]")) {
 300             result.append("[");
 301             base = base.substring(0, base.length() - 2);
 302         }
 303 
 304         switch (base) {
 305             case "boolean":
 306                 result.append("Z");
 307                 break;
 308             case "byte":
 309                 result.append("B");
 310                 break;
 311             case "short":
 312                 result.append("S");
 313                 break;
 314             case "char":
 315                 result.append("C");
 316                 break;
 317             case "int":
 318                 result.append("I");
 319                 break;
 320             case "float":
 321                 result.append("F");
 322                 break;
 323             case "long":
 324                 result.append("J");
 325                 break;
 326             case "double":
 327                 result.append("D");
 328                 break;
 329             case "void":
 330                 result.append("V");
 331                 break;
 332             default:
 333                 result.append("L").append(base.replace('.', '/')).append(";");
 334                 break;
 335         }
 336         return result.toString();
 337     }
 338 
 339     /**
 340      * Prepends the String {@code indentation} to every line in String {@code lines}, including a
 341      * possibly non-empty line following the final newline.
 342      */
 343     public static String indent(String lines, String indentation) {
 344         if (lines.length() == 0) {
 345             return lines;
 346         }
 347         final String newLine = "\n";
 348         if (lines.endsWith(newLine)) {
 349             return indentation + (lines.substring(0, lines.length() - 1)).replace(newLine, newLine + indentation) + newLine;
 350         }
 351         return indentation + lines.replace(newLine, newLine + indentation);
 352     }
 353 
 354     /**
 355      * Gets a string representation of an object based soley on its class and its
 356      * {@linkplain System#identityHashCode(Object) identity hash code}. This avoids and calls to
 357      * virtual methods on the object such as {@link Object#hashCode()}.
 358      */
 359     public static String identityHashCodeString(Object obj) {
 360         if (obj == null) {
 361             return "null";
 362         }
 363         return obj.getClass().getName() + "@" + System.identityHashCode(obj);
 364     }
 365 
 366     /**
 367      * Used to lookup constants from {@link Modifier} that are not public (VARARGS, SYNTHETIC etc.).
 368      */
 369     static int getNonPublicModifierStaticField(String name) {
 370         try {
 371             Field field = Modifier.class.getDeclaredField(name);
 372             field.setAccessible(true);
 373             return field.getInt(null);
 374         } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
 375             throw new InternalError(e);
 376         }
 377     }
 378 }