1 /*
   2  * Copyright (c) 2014, 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 package jdk.vm.ci.services;
  24 
  25 import java.lang.reflect.InvocationTargetException;
  26 import java.lang.reflect.Method;
  27 import java.util.Formatter;
  28 import java.util.Iterator;
  29 import java.util.ServiceConfigurationError;
  30 import java.util.ServiceLoader;
  31 
  32 /**
  33  * A mechanism for accessing service providers via JVMCI.
  34  */
  35 public final class Services {
  36 
  37     private Services() {
  38     }
  39 
  40     private static int getJavaSpecificationVersion() {
  41         String value = System.getProperty("java.specification.version");
  42         if (value.startsWith("1.")) {
  43             value = value.substring(2);
  44         }
  45         return Integer.parseInt(value);
  46     }
  47 
  48     /**
  49      * The integer value corresponding to the value of the {@code java.specification.version} system
  50      * property after any leading {@code "1."} has been stripped.
  51      */
  52     public static final int JAVA_SPECIFICATION_VERSION = getJavaSpecificationVersion();
  53 
  54     // Use reflection so that this compiles on Java 8
  55     private static final Method getModule;
  56     private static final Method getPackages;
  57     private static final Method addUses;
  58     private static final Method isExported;
  59     private static final Method addExports;
  60 
  61     static {
  62         if (JAVA_SPECIFICATION_VERSION >= 9) {
  63             try {
  64                 getModule = Class.class.getMethod("getModule");
  65                 Class<?> moduleClass = getModule.getReturnType();
  66                 getPackages = moduleClass.getMethod("getPackages");
  67                 addUses = moduleClass.getMethod("addUses", Class.class);
  68                 isExported = moduleClass.getMethod("isExported", String.class, moduleClass);
  69                 addExports = moduleClass.getMethod("addExports", String.class, moduleClass);
  70             } catch (NoSuchMethodException | SecurityException e) {
  71                 throw new InternalError(e);
  72             }
  73         } else {
  74             getModule = null;
  75             getPackages = null;
  76             addUses = null;
  77             isExported = null;
  78             addExports = null;
  79         }
  80     }
  81 
  82     @SuppressWarnings("unchecked")
  83     static <T> T invoke(Method method, Object receiver, Object... args) {
  84         try {
  85             return (T) method.invoke(receiver, args);
  86         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  87             throw new InternalError(e);
  88         }
  89     }
  90 
  91     /**
  92      * Performs any required security checks and dynamic reconfiguration to allow the module of a
  93      * given class to access the classes in the JVMCI module.
  94      *
  95      * Note: This API uses {@link Class} instead of {@code Module} to provide backwards
  96      * compatibility for JVMCI clients compiled against a JDK release earlier than 9.
  97      *
  98      * @param requestor a class requesting access to the JVMCI module for its module
  99      * @throws SecurityException if a security manager is present and it denies
 100      *             {@link JVMCIPermission}
 101      */
 102     public static void exportJVMCITo(Class<?> requestor) {
 103         SecurityManager sm = System.getSecurityManager();
 104         if (sm != null) {
 105             sm.checkPermission(new JVMCIPermission());
 106         }
 107         if (JAVA_SPECIFICATION_VERSION >= 9) {
 108             Object jvmci = invoke(getModule, Services.class);
 109             Object requestorModule = invoke(getModule, requestor);
 110             if (jvmci != requestorModule) {
 111                 String[] packages = invoke(getPackages, jvmci);
 112                 for (String pkg : packages) {
 113                     // Export all JVMCI packages dynamically instead
 114                     // of requiring a long list of --add-exports
 115                     // options on the JVM command line.
 116                     boolean exported = invoke(isExported, jvmci, pkg, requestorModule);
 117                     if (!exported) {
 118                         invoke(addExports, jvmci, pkg, requestorModule);
 119                     }
 120                 }
 121             }
 122         }
 123     }
 124 
 125     /**
 126      * Gets an {@link Iterable} of the JVMCI providers available for a given service.
 127      *
 128      * @throws SecurityException if a security manager is present and it denies
 129      *             {@link JVMCIPermission}
 130      */
 131     public static <S> Iterable<S> load(Class<S> service) {
 132         SecurityManager sm = System.getSecurityManager();
 133         if (sm != null) {
 134             sm.checkPermission(new JVMCIPermission());
 135         }
 136         if (JAVA_SPECIFICATION_VERSION >= 9) {
 137             Object jvmci = invoke(getModule, Services.class);
 138             invoke(addUses, jvmci, service);
 139         }
 140 
 141         // Restrict JVMCI clients to be on the class path or module path
 142         return ServiceLoader.load(service, ClassLoader.getSystemClassLoader());
 143     }
 144 
 145     /**
 146      * Gets the JVMCI provider for a given service for which at most one provider must be available.
 147      *
 148      * @param service the service whose provider is being requested
 149      * @param required specifies if an {@link InternalError} should be thrown if no provider of
 150      *            {@code service} is available
 151      * @throws SecurityException if a security manager is present and it denies
 152      *             {@link JVMCIPermission}
 153      */
 154     public static <S> S loadSingle(Class<S> service, boolean required) {
 155         SecurityManager sm = System.getSecurityManager();
 156         if (sm != null) {
 157             sm.checkPermission(new JVMCIPermission());
 158         }
 159         if (JAVA_SPECIFICATION_VERSION >= 9) {
 160             Object jvmci = invoke(getModule, Services.class);
 161             invoke(addUses, jvmci, service);
 162         }
 163         // Restrict JVMCI clients to be on the class path or module path
 164         Iterable<S> providers = ServiceLoader.load(service, ClassLoader.getSystemClassLoader());
 165         S singleProvider = null;
 166         try {
 167             for (Iterator<S> it = providers.iterator(); it.hasNext();) {
 168                 singleProvider = it.next();
 169                 if (it.hasNext()) {
 170                     throw new InternalError(String.format("Multiple %s providers found", service.getName()));
 171                 }
 172             }
 173         } catch (ServiceConfigurationError e) {
 174             // If the service is required we will bail out below.
 175         }
 176         if (singleProvider == null && required) {
 177             String javaHome = System.getProperty("java.home");
 178             String vmName = System.getProperty("java.vm.name");
 179             Formatter errorMessage = new Formatter();
 180             errorMessage.format("The VM does not expose required service %s.%n", service.getName());
 181             errorMessage.format("Currently used Java home directory is %s.%n", javaHome);
 182             errorMessage.format("Currently used VM configuration is: %s", vmName);
 183             throw new UnsupportedOperationException(errorMessage.toString());
 184         }
 185         return singleProvider;
 186     }
 187 }