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