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