1 /*
   2  * Copyright (c) 2016, 2019, 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 
  24 
  25 package org.graalvm.compiler.serviceprovider;
  26 
  27 import static java.lang.Thread.currentThread;
  28 
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.util.Arrays;
  32 import java.util.ArrayList;
  33 import java.util.HashMap;
  34 import java.util.Iterator;
  35 import java.util.List;
  36 import java.util.Map;
  37 import java.util.ServiceConfigurationError;
  38 import java.util.ServiceLoader;
  39 import java.util.concurrent.atomic.AtomicLong;
  40 import java.util.function.Supplier;
  41 
  42 import org.graalvm.compiler.serviceprovider.SpeculationReasonGroup.SpeculationContextObject;
  43 
  44 import jdk.vm.ci.code.BytecodePosition;
  45 import jdk.vm.ci.code.VirtualObject;
  46 import jdk.vm.ci.meta.ResolvedJavaField;
  47 import jdk.vm.ci.meta.ResolvedJavaMethod;
  48 import jdk.vm.ci.meta.ResolvedJavaType;
  49 import jdk.vm.ci.meta.SpeculationLog.SpeculationReason;
  50 import jdk.vm.ci.meta.SpeculationLog.SpeculationReasonEncoding;
  51 import jdk.vm.ci.runtime.JVMCI;
  52 import jdk.vm.ci.services.JVMCIPermission;
  53 import jdk.vm.ci.services.Services;
  54 
  55 import static jdk.vm.ci.services.Services.IS_IN_NATIVE_IMAGE;
  56 import static jdk.vm.ci.services.Services.IS_BUILDING_NATIVE_IMAGE;
  57 
  58 /**
  59  * JDK 13+ version of {@link GraalServices}.
  60  */
  61 public final class GraalServices {
  62 
  63     private static final Map<Class<?>, List<?>> servicesCache = IS_BUILDING_NATIVE_IMAGE ? new HashMap<>() : null;
  64 
  65     private GraalServices() {
  66     }
  67 
  68     /**
  69      * Gets an {@link Iterable} of the providers available for a given service.
  70      *
  71      * @throws SecurityException if on JDK8 and a security manager is present and it denies
  72      *             {@link JVMCIPermission}
  73      */
  74     @SuppressWarnings("unchecked")
  75     public static <S> Iterable<S> load(Class<S> service) {
  76         if (IS_IN_NATIVE_IMAGE || IS_BUILDING_NATIVE_IMAGE) {
  77             List<?> list = servicesCache.get(service);
  78             if (list != null) {
  79                 return (Iterable<S>) list;
  80             }
  81             if (IS_IN_NATIVE_IMAGE) {
  82                 throw new InternalError(String.format("No %s providers found when building native image", service.getName()));
  83             }
  84         }
  85 
  86         Iterable<S> providers = load0(service);
  87 
  88         if (IS_BUILDING_NATIVE_IMAGE) {
  89             synchronized (servicesCache) {
  90                 ArrayList<S> providersList = new ArrayList<>();
  91                 for (S provider : providers) {
  92                     providersList.add(provider);
  93                 }
  94                 providers = providersList;
  95                 servicesCache.put(service, providersList);
  96                 return providers;
  97             }
  98         }
  99 
 100         return providers;
 101     }
 102 
 103     protected static <S> Iterable<S> load0(Class<S> service) {
 104         Iterable<S> iterable = ServiceLoader.load(service, GraalServices.class.getClassLoader());
 105         return new Iterable<>() {
 106             @Override
 107             public Iterator<S> iterator() {
 108                 Iterator<S> iterator = iterable.iterator();
 109                 return new Iterator<>() {
 110                     @Override
 111                     public boolean hasNext() {
 112                         return iterator.hasNext();
 113                     }
 114 
 115                     @Override
 116                     public S next() {
 117                         S provider = iterator.next();
 118                         // Allow Graal extensions to access JVMCI
 119                         openJVMCITo(provider.getClass());
 120                         return provider;
 121                     }
 122 
 123                     @Override
 124                     public void remove() {
 125                         iterator.remove();
 126                     }
 127                 };
 128             }
 129         };
 130     }
 131 
 132     /**
 133      * Opens all JVMCI packages to the module of a given class. This relies on JVMCI already having
 134      * opened all its packages to the module defining {@link GraalServices}.
 135      *
 136      * @param other all JVMCI packages will be opened to the module defining this class
 137      */
 138     static void openJVMCITo(Class<?> other) {
 139         if (IS_IN_NATIVE_IMAGE) return;
 140 
 141         Module jvmciModule = JVMCI_MODULE;
 142         Module otherModule = other.getModule();
 143         if (jvmciModule != otherModule) {
 144             for (String pkg : jvmciModule.getPackages()) {
 145                 if (!jvmciModule.isOpen(pkg, otherModule)) {
 146                     // JVMCI initialization opens all JVMCI packages
 147                     // to Graal which is a prerequisite for Graal to
 148                     // open JVMCI packages to other modules.
 149                     JVMCI.getRuntime();
 150 
 151                     jvmciModule.addOpens(pkg, otherModule);
 152                 }
 153             }
 154         }
 155     }
 156 
 157     /**
 158      * Gets the provider for a given service for which at most one provider must be available.
 159      *
 160      * @param service the service whose provider is being requested
 161      * @param required specifies if an {@link InternalError} should be thrown if no provider of
 162      *            {@code service} is available
 163      * @return the requested provider if available else {@code null}
 164      * @throws SecurityException if on JDK8 and a security manager is present and it denies
 165      *             {@link JVMCIPermission}
 166      */
 167     public static <S> S loadSingle(Class<S> service, boolean required) {
 168         assert !service.getName().startsWith("jdk.vm.ci") : "JVMCI services must be loaded via " + Services.class.getName();
 169         Iterable<S> providers = load(service);
 170         S singleProvider = null;
 171         try {
 172             for (Iterator<S> it = providers.iterator(); it.hasNext();) {
 173                 singleProvider = it.next();
 174                 if (it.hasNext()) {
 175                     S other = it.next();
 176                     throw new InternalError(String.format("Multiple %s providers found: %s, %s", service.getName(), singleProvider.getClass().getName(), other.getClass().getName()));
 177                 }
 178             }
 179         } catch (ServiceConfigurationError e) {
 180             // If the service is required we will bail out below.
 181         }
 182         if (singleProvider == null) {
 183             if (required) {
 184                 throw new InternalError(String.format("No provider for %s found", service.getName()));
 185             }
 186         }
 187         return singleProvider;
 188     }
 189 
 190     /**
 191      * Gets the class file bytes for {@code c}.
 192      */
 193     public static InputStream getClassfileAsStream(Class<?> c) throws IOException {
 194         String classfilePath = c.getName().replace('.', '/') + ".class";
 195         return c.getModule().getResourceAsStream(classfilePath);
 196     }
 197 
 198     private static final Module JVMCI_MODULE = Services.class.getModule();
 199 
 200     /**
 201      * A JVMCI package dynamically exported to trusted modules.
 202      */
 203     private static final String JVMCI_RUNTIME_PACKAGE = "jdk.vm.ci.runtime";
 204     static {
 205         assert JVMCI_MODULE.getPackages().contains(JVMCI_RUNTIME_PACKAGE);
 206     }
 207 
 208     /**
 209      * Determines if invoking {@link Object#toString()} on an instance of {@code c} will only run
 210      * trusted code.
 211      */
 212     public static boolean isToStringTrusted(Class<?> c) {
 213         Module module = c.getModule();
 214         Module jvmciModule = JVMCI_MODULE;
 215         assert jvmciModule.getPackages().contains("jdk.vm.ci.runtime");
 216         if (module == jvmciModule || jvmciModule.isOpen(JVMCI_RUNTIME_PACKAGE, module)) {
 217             // Can access non-statically-exported package in JVMCI
 218             return true;
 219         }
 220         return false;
 221     }
 222 
 223     /**
 224      * An implementation of {@link SpeculationReason} based on direct, unencoded values.
 225      */
 226     static final class DirectSpeculationReason implements SpeculationReason {
 227         final int groupId;
 228         final String groupName;
 229         final Object[] context;
 230         private SpeculationReasonEncoding encoding;
 231 
 232         DirectSpeculationReason(int groupId, String groupName, Object[] context) {
 233             this.groupId = groupId;
 234             this.groupName = groupName;
 235             this.context = context;
 236         }
 237 
 238         @Override
 239         public boolean equals(Object obj) {
 240             if (obj instanceof DirectSpeculationReason) {
 241                 DirectSpeculationReason that = (DirectSpeculationReason) obj;
 242                 return this.groupId == that.groupId && Arrays.equals(this.context, that.context);
 243             }
 244             return false;
 245         }
 246 
 247         @Override
 248         public int hashCode() {
 249             return groupId + Arrays.hashCode(this.context);
 250         }
 251 
 252         @Override
 253         public String toString() {
 254             return String.format("%s@%d%s", groupName, groupId, Arrays.toString(context));
 255         }
 256 
 257         @Override
 258         public SpeculationReasonEncoding encode(Supplier<SpeculationReasonEncoding> encodingSupplier) {
 259             if (encoding == null) {
 260                 encoding = encodingSupplier.get();
 261                 encoding.addInt(groupId);
 262                 for (Object o : context) {
 263                     if (o == null) {
 264                         encoding.addInt(0);
 265                     } else {
 266                         addNonNullObject(encoding, o);
 267                     }
 268                 }
 269             }
 270             return encoding;
 271         }
 272 
 273         static void addNonNullObject(SpeculationReasonEncoding encoding, Object o) {
 274             Class<? extends Object> c = o.getClass();
 275             if (c == String.class) {
 276                 encoding.addString((String) o);
 277             } else if (c == Byte.class) {
 278                 encoding.addByte((Byte) o);
 279             } else if (c == Short.class) {
 280                 encoding.addShort((Short) o);
 281             } else if (c == Character.class) {
 282                 encoding.addShort((Character) o);
 283             } else if (c == Integer.class) {
 284                 encoding.addInt((Integer) o);
 285             } else if (c == Long.class) {
 286                 encoding.addLong((Long) o);
 287             } else if (c == Float.class) {
 288                 encoding.addInt(Float.floatToRawIntBits((Float) o));
 289             } else if (c == Double.class) {
 290                 encoding.addLong(Double.doubleToRawLongBits((Double) o));
 291             } else if (o instanceof Enum) {
 292                 encoding.addInt(((Enum<?>) o).ordinal());
 293             } else if (o instanceof ResolvedJavaMethod) {
 294                 encoding.addMethod((ResolvedJavaMethod) o);
 295             } else if (o instanceof ResolvedJavaType) {
 296                 encoding.addType((ResolvedJavaType) o);
 297             } else if (o instanceof ResolvedJavaField) {
 298                 encoding.addField((ResolvedJavaField) o);
 299             } else if (o instanceof SpeculationContextObject) {
 300                 SpeculationContextObject sco = (SpeculationContextObject) o;
 301                 // These are compiler objects which all have the same class
 302                 // loader so the class name uniquely identifies the class.
 303                 encoding.addString(o.getClass().getName());
 304                 sco.accept(new EncodingAdapter(encoding));
 305             } else if (o.getClass() == BytecodePosition.class) {
 306                 BytecodePosition p = (BytecodePosition) o;
 307                 while (p != null) {
 308                     encoding.addInt(p.getBCI());
 309                     encoding.addMethod(p.getMethod());
 310                     p = p.getCaller();
 311                 }
 312             } else {
 313                 throw new IllegalArgumentException("Unsupported type for encoding: " + c.getName());
 314             }
 315         }
 316     }
 317 
 318     static class EncodingAdapter implements SpeculationContextObject.Visitor {
 319         private final SpeculationReasonEncoding encoding;
 320 
 321         EncodingAdapter(SpeculationReasonEncoding encoding) {
 322             this.encoding = encoding;
 323         }
 324 
 325         @Override
 326         public void visitBoolean(boolean v) {
 327             encoding.addByte(v ? 1 : 0);
 328         }
 329 
 330         @Override
 331         public void visitByte(byte v) {
 332             encoding.addByte(v);
 333         }
 334 
 335         @Override
 336         public void visitChar(char v) {
 337             encoding.addShort(v);
 338         }
 339 
 340         @Override
 341         public void visitShort(short v) {
 342             encoding.addInt(v);
 343         }
 344 
 345         @Override
 346         public void visitInt(int v) {
 347             encoding.addInt(v);
 348         }
 349 
 350         @Override
 351         public void visitLong(long v) {
 352             encoding.addLong(v);
 353         }
 354 
 355         @Override
 356         public void visitFloat(float v) {
 357             encoding.addInt(Float.floatToRawIntBits(v));
 358         }
 359 
 360         @Override
 361         public void visitDouble(double v) {
 362             encoding.addLong(Double.doubleToRawLongBits(v));
 363         }
 364 
 365         @Override
 366         public void visitObject(Object v) {
 367             if (v == null) {
 368                 encoding.addInt(0);
 369             } else {
 370                 DirectSpeculationReason.addNonNullObject(encoding, v);
 371             }
 372         }
 373     }
 374 
 375     static SpeculationReason createSpeculationReason(int groupId, String groupName, Object... context) {
 376         return new DirectSpeculationReason(groupId, groupName, context);
 377     }
 378 
 379     /**
 380      * Gets a unique identifier for this execution such as a process ID or a
 381      * {@linkplain #getGlobalTimeStamp() fixed timestamp}.
 382      */
 383     public static String getExecutionID() {
 384         return Long.toString(ProcessHandle.current().pid());
 385     }
 386 
 387     private static final AtomicLong globalTimeStamp = new AtomicLong();
 388 
 389     /**
 390      * Gets a time stamp for the current process. This method will always return the same value for
 391      * the current VM execution.
 392      */
 393     public static long getGlobalTimeStamp() {
 394         if (globalTimeStamp.get() == 0) {
 395             globalTimeStamp.compareAndSet(0, System.currentTimeMillis());
 396         }
 397         return globalTimeStamp.get();
 398     }
 399 
 400     /**
 401      * Returns an approximation of the total amount of memory, in bytes, allocated in heap memory
 402      * for the thread of the specified ID. The returned value is an approximation because some Java
 403      * virtual machine implementations may use object allocation mechanisms that result in a delay
 404      * between the time an object is allocated and the time its size is recorded.
 405      * <p>
 406      * If the thread of the specified ID is not alive or does not exist, this method returns
 407      * {@code -1}. If thread memory allocation measurement is disabled, this method returns
 408      * {@code -1}. A thread is alive if it has been started and has not yet died.
 409      * <p>
 410      * If thread memory allocation measurement is enabled after the thread has started, the Java
 411      * virtual machine implementation may choose any time up to and including the time that the
 412      * capability is enabled as the point where thread memory allocation measurement starts.
 413      *
 414      * @param id the thread ID of a thread
 415      * @return an approximation of the total memory allocated, in bytes, in heap memory for a thread
 416      *         of the specified ID if the thread of the specified ID exists, the thread is alive,
 417      *         and thread memory allocation measurement is enabled; {@code -1} otherwise.
 418      *
 419      * @throws IllegalArgumentException if {@code id} {@code <=} {@code 0}.
 420      * @throws UnsupportedOperationException if the Java virtual machine implementation does not
 421      *             {@linkplain #isThreadAllocatedMemorySupported() support} thread memory allocation
 422      *             measurement.
 423      */
 424     public static long getThreadAllocatedBytes(long id) {
 425         JMXService jmx = JMXService.instance;
 426         if (jmx == null) {
 427             throw new UnsupportedOperationException();
 428         }
 429         return jmx.getThreadAllocatedBytes(id);
 430     }
 431 
 432     /**
 433      * Convenience method for calling {@link #getThreadAllocatedBytes(long)} with the id of the
 434      * current thread.
 435      */
 436     public static long getCurrentThreadAllocatedBytes() {
 437         return getThreadAllocatedBytes(currentThread().getId());
 438     }
 439 
 440     /**
 441      * Returns the total CPU time for the current thread in nanoseconds. The returned value is of
 442      * nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation
 443      * distinguishes between user mode time and system mode time, the returned CPU time is the
 444      * amount of time that the current thread has executed in user mode or system mode.
 445      *
 446      * @return the total CPU time for the current thread if CPU time measurement is enabled;
 447      *         {@code -1} otherwise.
 448      *
 449      * @throws UnsupportedOperationException if the Java virtual machine does not
 450      *             {@linkplain #isCurrentThreadCpuTimeSupported() support} CPU time measurement for
 451      *             the current thread
 452      */
 453     public static long getCurrentThreadCpuTime() {
 454         JMXService jmx = JMXService.instance;
 455         if (jmx == null) {
 456             throw new UnsupportedOperationException();
 457         }
 458         return jmx.getCurrentThreadCpuTime();
 459     }
 460 
 461     /**
 462      * Determines if the Java virtual machine implementation supports thread memory allocation
 463      * measurement.
 464      */
 465     public static boolean isThreadAllocatedMemorySupported() {
 466         JMXService jmx = JMXService.instance;
 467         if (jmx == null) {
 468             return false;
 469         }
 470         return jmx.isThreadAllocatedMemorySupported();
 471     }
 472 
 473     /**
 474      * Determines if the Java virtual machine supports CPU time measurement for the current thread.
 475      */
 476     public static boolean isCurrentThreadCpuTimeSupported() {
 477         JMXService jmx = JMXService.instance;
 478         if (jmx == null) {
 479             return false;
 480         }
 481         return jmx.isCurrentThreadCpuTimeSupported();
 482     }
 483 
 484     /**
 485      * Gets the input arguments passed to the Java virtual machine which does not include the
 486      * arguments to the {@code main} method. This method returns an empty list if there is no input
 487      * argument to the Java virtual machine.
 488      * <p>
 489      * Some Java virtual machine implementations may take input arguments from multiple different
 490      * sources: for examples, arguments passed from the application that launches the Java virtual
 491      * machine such as the 'java' command, environment variables, configuration files, etc.
 492      * <p>
 493      * Typically, not all command-line options to the 'java' command are passed to the Java virtual
 494      * machine. Thus, the returned input arguments may not include all command-line options.
 495      *
 496      * @return the input arguments to the JVM or {@code null} if they are unavailable
 497      */
 498     public static List<String> getInputArguments() {
 499         JMXService jmx = JMXService.instance;
 500         if (jmx == null) {
 501             return null;
 502         }
 503         return jmx.getInputArguments();
 504     }
 505 
 506     /**
 507      * Returns the fused multiply add of the three arguments; that is, returns the exact product of
 508      * the first two arguments summed with the third argument and then rounded once to the nearest
 509      * {@code float}.
 510      */
 511     public static float fma(float a, float b, float c) {
 512         return Math.fma(a, b, c);
 513     }
 514 
 515     /**
 516      * Returns the fused multiply add of the three arguments; that is, returns the exact product of
 517      * the first two arguments summed with the third argument and then rounded once to the nearest
 518      * {@code double}.
 519      */
 520     public static double fma(double a, double b, double c) {
 521         return Math.fma(a, b, c);
 522     }
 523 
 524     /**
 525      * Set the flag in the {@link VirtualObject} that indicates that it is a boxed primitive that
 526      * was produced as a result of a call to a {@code valueOf} method.
 527      */
 528     public static void markVirtualObjectAsAutoBox(VirtualObject virtualObject) {
 529        virtualObject.setIsAutoBox(true);
 530     }
 531 }