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