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