1 /*
   2  * Copyright (c) 2016, 2018, 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.Iterator;
  32 import java.util.List;
  33 import java.util.ServiceConfigurationError;
  34 import java.util.ServiceLoader;
  35 import java.util.concurrent.atomic.AtomicLong;
  36 
  37 import jdk.vm.ci.runtime.JVMCI;
  38 import jdk.vm.ci.services.JVMCIPermission;
  39 import jdk.vm.ci.services.Services;
  40 
  41 /**
  42  * Interface to functionality that abstracts over which JDK version Graal is running on.
  43  */
  44 public final class GraalServices {
  45 
  46     private static int getJavaSpecificationVersion() {
  47         String value = System.getProperty("java.specification.version");
  48         if (value.startsWith("1.")) {
  49             value = value.substring(2);
  50         }
  51         return Integer.parseInt(value);
  52     }
  53 
  54     /**
  55      * The integer value corresponding to the value of the {@code java.specification.version} system
  56      * property after any leading {@code "1."} has been stripped.
  57      */
  58     public static final int JAVA_SPECIFICATION_VERSION = getJavaSpecificationVersion();
  59 
  60     /**
  61      * Determines if the Java runtime is version 8 or earlier.
  62      */
  63     public static final boolean Java8OrEarlier = JAVA_SPECIFICATION_VERSION <= 8;
  64 
  65     /**
  66      * Determines if the Java runtime is version 11 or earlier.
  67      */
  68     public static final boolean Java11OrEarlier = JAVA_SPECIFICATION_VERSION <= 11;
  69 
  70     private GraalServices() {
  71     }
  72 
  73     /**
  74      * Gets an {@link Iterable} of the providers available for a given service.
  75      *
  76      * @throws SecurityException if on JDK8 and a security manager is present and it denies
  77      *             {@link JVMCIPermission}
  78      */
  79     public static <S> Iterable<S> load(Class<S> service) {
  80         Iterable<S> iterable = ServiceLoader.load(service);
  81         return new Iterable<>() {
  82             @Override
  83             public Iterator<S> iterator() {
  84                 Iterator<S> iterator = iterable.iterator();
  85                 return new Iterator<>() {
  86                     @Override
  87                     public boolean hasNext() {
  88                         return iterator.hasNext();
  89                     }
  90 
  91                     @Override
  92                     public S next() {
  93                         S provider = iterator.next();
  94                         // Allow Graal extensions to access JVMCI
  95                         openJVMCITo(provider.getClass());
  96                         return provider;
  97                     }
  98 
  99                     @Override
 100                     public void remove() {
 101                         iterator.remove();
 102                     }
 103                 };
 104             }
 105         };
 106     }
 107 
 108     /**
 109      * Opens all JVMCI packages to the module of a given class. This relies on JVMCI already having
 110      * opened all its packages to the module defining {@link GraalServices}.
 111      *
 112      * @param other all JVMCI packages will be opened to the module defining this class
 113      */
 114     static void openJVMCITo(Class<?> other) {
 115         Module jvmciModule = JVMCI_MODULE;
 116         Module otherModule = other.getModule();
 117         if (jvmciModule != otherModule) {
 118             for (String pkg : jvmciModule.getPackages()) {
 119                 if (!jvmciModule.isOpen(pkg, otherModule)) {
 120                     // JVMCI initialization opens all JVMCI packages
 121                     // to Graal which is a prerequisite for Graal to
 122                     // open JVMCI packages to other modules.
 123                     JVMCI.initialize();
 124 
 125                     jvmciModule.addOpens(pkg, otherModule);
 126                 }
 127             }
 128         }
 129     }
 130 
 131     /**
 132      * Gets the provider for a given service for which at most one provider must be available.
 133      *
 134      * @param service the service whose provider is being requested
 135      * @param required specifies if an {@link InternalError} should be thrown if no provider of
 136      *            {@code service} is available
 137      * @return the requested provider if available else {@code null}
 138      * @throws SecurityException if on JDK8 and a security manager is present and it denies
 139      *             {@link JVMCIPermission}
 140      */
 141     public static <S> S loadSingle(Class<S> service, boolean required) {
 142         assert !service.getName().startsWith("jdk.vm.ci") : "JVMCI services must be loaded via " + Services.class.getName();
 143         Iterable<S> providers = load(service);
 144         S singleProvider = null;
 145         try {
 146             for (Iterator<S> it = providers.iterator(); it.hasNext();) {
 147                 singleProvider = it.next();
 148                 if (it.hasNext()) {
 149                     S other = it.next();
 150                     throw new InternalError(String.format("Multiple %s providers found: %s, %s", service.getName(), singleProvider.getClass().getName(), other.getClass().getName()));
 151                 }
 152             }
 153         } catch (ServiceConfigurationError e) {
 154             // If the service is required we will bail out below.
 155         }
 156         if (singleProvider == null) {
 157             if (required) {
 158                 throw new InternalError(String.format("No provider for %s found", service.getName()));
 159             }
 160         }
 161         return singleProvider;
 162     }
 163 
 164     /**
 165      * Gets the class file bytes for {@code c}.
 166      */
 167     public static InputStream getClassfileAsStream(Class<?> c) throws IOException {
 168         String classfilePath = c.getName().replace('.', '/') + ".class";
 169         return c.getModule().getResourceAsStream(classfilePath);
 170     }
 171 
 172     private static final Module JVMCI_MODULE = Services.class.getModule();
 173 
 174     /**
 175      * A JVMCI package dynamically exported to trusted modules.
 176      */
 177     private static final String JVMCI_RUNTIME_PACKAGE = "jdk.vm.ci.runtime";
 178     static {
 179         assert JVMCI_MODULE.getPackages().contains(JVMCI_RUNTIME_PACKAGE);
 180     }
 181 
 182     /**
 183      * Determines if invoking {@link Object#toString()} on an instance of {@code c} will only run
 184      * trusted code.
 185      */
 186     public static boolean isToStringTrusted(Class<?> c) {
 187         Module module = c.getModule();
 188         Module jvmciModule = JVMCI_MODULE;
 189         assert jvmciModule.getPackages().contains("jdk.vm.ci.runtime");
 190         if (module == jvmciModule || jvmciModule.isOpen(JVMCI_RUNTIME_PACKAGE, module)) {
 191             // Can access non-statically-exported package in JVMCI
 192             return true;
 193         }
 194         return false;
 195     }
 196 
 197     /**
 198      * Gets a unique identifier for this execution such as a process ID or a
 199      * {@linkplain #getGlobalTimeStamp() fixed timestamp}.
 200      */
 201     public static String getExecutionID() {
 202         return Long.toString(ProcessHandle.current().pid());
 203     }
 204 
 205     private static final AtomicLong globalTimeStamp = new AtomicLong();
 206 
 207     /**
 208      * Gets a time stamp for the current process. This method will always return the same value for
 209      * the current VM execution.
 210      */
 211     public static long getGlobalTimeStamp() {
 212         if (globalTimeStamp.get() == 0) {
 213             globalTimeStamp.compareAndSet(0, System.currentTimeMillis());
 214         }
 215         return globalTimeStamp.get();
 216     }
 217 
 218     /**
 219      * Returns an approximation of the total amount of memory, in bytes, allocated in heap memory
 220      * for the thread of the specified ID. The returned value is an approximation because some Java
 221      * virtual machine implementations may use object allocation mechanisms that result in a delay
 222      * between the time an object is allocated and the time its size is recorded.
 223      * <p>
 224      * If the thread of the specified ID is not alive or does not exist, this method returns
 225      * {@code -1}. If thread memory allocation measurement is disabled, this method returns
 226      * {@code -1}. A thread is alive if it has been started and has not yet died.
 227      * <p>
 228      * If thread memory allocation measurement is enabled after the thread has started, the Java
 229      * virtual machine implementation may choose any time up to and including the time that the
 230      * capability is enabled as the point where thread memory allocation measurement starts.
 231      *
 232      * @param id the thread ID of a thread
 233      * @return an approximation of the total memory allocated, in bytes, in heap memory for a thread
 234      *         of the specified ID if the thread of the specified ID exists, the thread is alive,
 235      *         and thread memory allocation measurement is enabled; {@code -1} otherwise.
 236      *
 237      * @throws IllegalArgumentException if {@code id} {@code <=} {@code 0}.
 238      * @throws UnsupportedOperationException if the Java virtual machine implementation does not
 239      *             {@linkplain #isThreadAllocatedMemorySupported() support} thread memory allocation
 240      *             measurement.
 241      */
 242     public static long getThreadAllocatedBytes(long id) {
 243         JMXService jmx = JMXService.instance;
 244         if (jmx == null) {
 245             throw new UnsupportedOperationException();
 246         }
 247         return jmx.getThreadAllocatedBytes(id);
 248     }
 249 
 250     /**
 251      * Convenience method for calling {@link #getThreadAllocatedBytes(long)} with the id of the
 252      * current thread.
 253      */
 254     public static long getCurrentThreadAllocatedBytes() {
 255         return getThreadAllocatedBytes(currentThread().getId());
 256     }
 257 
 258     /**
 259      * Returns the total CPU time for the current thread in nanoseconds. The returned value is of
 260      * nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation
 261      * distinguishes between user mode time and system mode time, the returned CPU time is the
 262      * amount of time that the current thread has executed in user mode or system mode.
 263      *
 264      * @return the total CPU time for the current thread if CPU time measurement is enabled;
 265      *         {@code -1} otherwise.
 266      *
 267      * @throws UnsupportedOperationException if the Java virtual machine does not
 268      *             {@linkplain #isCurrentThreadCpuTimeSupported() support} CPU time measurement for
 269      *             the current thread
 270      */
 271     public static long getCurrentThreadCpuTime() {
 272         JMXService jmx = JMXService.instance;
 273         if (jmx == null) {
 274             throw new UnsupportedOperationException();
 275         }
 276         return jmx.getCurrentThreadCpuTime();
 277     }
 278 
 279     /**
 280      * Determines if the Java virtual machine implementation supports thread memory allocation
 281      * measurement.
 282      */
 283     public static boolean isThreadAllocatedMemorySupported() {
 284         JMXService jmx = JMXService.instance;
 285         if (jmx == null) {
 286             return false;
 287         }
 288         return jmx.isThreadAllocatedMemorySupported();
 289     }
 290 
 291     /**
 292      * Determines if the Java virtual machine supports CPU time measurement for the current thread.
 293      */
 294     public static boolean isCurrentThreadCpuTimeSupported() {
 295         JMXService jmx = JMXService.instance;
 296         if (jmx == null) {
 297             return false;
 298         }
 299         return jmx.isCurrentThreadCpuTimeSupported();
 300     }
 301 
 302     /**
 303      * Gets the input arguments passed to the Java virtual machine which does not include the
 304      * arguments to the {@code main} method. This method returns an empty list if there is no input
 305      * argument to the Java virtual machine.
 306      * <p>
 307      * Some Java virtual machine implementations may take input arguments from multiple different
 308      * sources: for examples, arguments passed from the application that launches the Java virtual
 309      * machine such as the 'java' command, environment variables, configuration files, etc.
 310      * <p>
 311      * Typically, not all command-line options to the 'java' command are passed to the Java virtual
 312      * machine. Thus, the returned input arguments may not include all command-line options.
 313      *
 314      * @return the input arguments to the JVM or {@code null} if they are unavailable
 315      */
 316     public static List<String> getInputArguments() {
 317         JMXService jmx = JMXService.instance;
 318         if (jmx == null) {
 319             return null;
 320         }
 321         return jmx.getInputArguments();
 322     }
 323 }