1 /*
  2  * Copyright (c) 2003, 2022, 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package jdk.internal.access;
 27 
 28 import java.lang.annotation.Annotation;
 29 import java.lang.invoke.MethodHandle;
 30 import java.lang.invoke.MethodType;
 31 import java.lang.module.ModuleDescriptor;
 32 import java.lang.reflect.Executable;
 33 import java.lang.reflect.Method;
 34 import java.net.URI;
 35 import java.nio.charset.CharacterCodingException;
 36 import java.nio.charset.Charset;
 37 import java.security.AccessControlContext;
 38 import java.security.ProtectionDomain;
 39 import java.util.List;
 40 import java.util.Map;
 41 import java.util.Set;
 42 import java.util.concurrent.Callable;
 43 import java.util.concurrent.ConcurrentHashMap;
 44 import java.util.concurrent.RejectedExecutionException;
 45 import java.util.stream.Stream;
 46 
 47 import jdk.internal.misc.CarrierThreadLocal;
 48 import jdk.internal.module.ServicesCatalog;
 49 import jdk.internal.reflect.ConstantPool;
 50 import jdk.internal.vm.Continuation;
 51 import jdk.internal.vm.ContinuationScope;
 52 import jdk.internal.vm.StackableScope;
 53 import jdk.internal.vm.ThreadContainer;
 54 import sun.reflect.annotation.AnnotationType;
 55 import sun.nio.ch.Interruptible;
 56 
 57 public interface JavaLangAccess {
 58 
 59     /**
 60      * Returns the list of {@code Method} objects for the declared public
 61      * methods of this class or interface that have the specified method name
 62      * and parameter types.
 63      */
 64     List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes);
 65 
 66     /**
 67      * Return the constant pool for a class.
 68      */
 69     ConstantPool getConstantPool(Class<?> klass);
 70 
 71     /**
 72      * Compare-And-Set the AnnotationType instance corresponding to this class.
 73      * (This method only applies to annotation types.)
 74      */
 75     boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType);
 76 
 77     /**
 78      * Get the AnnotationType instance corresponding to this class.
 79      * (This method only applies to annotation types.)
 80      */
 81     AnnotationType getAnnotationType(Class<?> klass);
 82 
 83     /**
 84      * Get the declared annotations for a given class, indexed by their types.
 85      */
 86     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass);
 87 
 88     /**
 89      * Get the array of bytes that is the class-file representation
 90      * of this Class' annotations.
 91      */
 92     byte[] getRawClassAnnotations(Class<?> klass);
 93 
 94     /**
 95      * Get the array of bytes that is the class-file representation
 96      * of this Class' type annotations.
 97      */
 98     byte[] getRawClassTypeAnnotations(Class<?> klass);
 99 
100     /**
101      * Get the array of bytes that is the class-file representation
102      * of this Executable's type annotations.
103      */
104     byte[] getRawExecutableTypeAnnotations(Executable executable);
105 
106     /**
107      * Returns the elements of an enum class or null if the
108      * Class object does not represent an enum type;
109      * the result is uncloned, cached, and shared by all callers.
110      */
111     <E extends Enum<E>> E[] getEnumConstantsShared(Class<E> klass);
112 
113     /**
114      * Set current thread's blocker field.
115      */
116     void blockedOn(Interruptible b);
117 
118     /**
119      * Registers a shutdown hook.
120      *
121      * It is expected that this method with registerShutdownInProgress=true
122      * is only used to register DeleteOnExitHook since the first file
123      * may be added to the delete on exit list by the application shutdown
124      * hooks.
125      *
126      * @param slot  the slot in the shutdown hook array, whose element
127      *              will be invoked in order during shutdown
128      * @param registerShutdownInProgress true to allow the hook
129      *        to be registered even if the shutdown is in progress.
130      * @param hook  the hook to be registered
131      *
132      * @throws IllegalStateException if shutdown is in progress and
133      *         the slot is not valid to register.
134      */
135     void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook);
136 
137     /**
138      * Returns a new Thread with the given Runnable and an
139      * inherited AccessControlContext.
140      */
141     Thread newThreadWithAcc(Runnable target, @SuppressWarnings("removal") AccessControlContext acc);
142 
143     /**
144      * Invokes the finalize method of the given object.
145      */
146     void invokeFinalize(Object o) throws Throwable;
147 
148     /**
149      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
150      * associated with the given class loader, creating it if it doesn't already exist.
151      */
152     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl);
153 
154     /**
155      * Defines a class with the given name to a class loader.
156      */
157     Class<?> defineClass(ClassLoader cl, String name, byte[] b, ProtectionDomain pd, String source);
158 
159     /**
160      * Defines a class with the given name to a class loader with
161      * the given flags and class data.
162      *
163      * @see java.lang.invoke.MethodHandles.Lookup#defineClass
164      */
165     Class<?> defineClass(ClassLoader cl, Class<?> lookup, String name, byte[] b, ProtectionDomain pd, boolean initialize, int flags, Object classData);
166 
167     /**
168      * Returns a class loaded by the bootstrap class loader.
169      */
170     Class<?> findBootstrapClassOrNull(String name);
171 
172     /**
173      * Define a Package of the given name and module by the given class loader.
174      */
175     Package definePackage(ClassLoader cl, String name, Module module);
176 
177     /**
178      * Invokes Long.fastUUID
179      */
180     String fastUUID(long lsb, long msb);
181 
182     /**
183      * Record the non-exported packages of the modules in the given layer
184      */
185     void addNonExportedPackages(ModuleLayer layer);
186 
187     /**
188      * Invalidate package access cache
189      */
190     void invalidatePackageAccessCache();
191 
192     /**
193      * Defines a new module to the Java virtual machine. The module
194      * is defined to the given class loader.
195      *
196      * The URI is for information purposes only, it can be {@code null}.
197      */
198     Module defineModule(ClassLoader loader, ModuleDescriptor descriptor, URI uri);
199 
200     /**
201      * Defines the unnamed module for the given class loader.
202      */
203     Module defineUnnamedModule(ClassLoader loader);
204 
205     /**
206      * Updates the readability so that module m1 reads m2. The new read edge
207      * does not result in a strong reference to m2 (m2 can be GC'ed).
208      *
209      * This method is the same as m1.addReads(m2) but without a permission check.
210      */
211     void addReads(Module m1, Module m2);
212 
213     /**
214      * Updates module m to read all unnamed modules.
215      */
216     void addReadsAllUnnamed(Module m);
217 
218     /**
219      * Updates module m1 to export a package unconditionally.
220      */
221     void addExports(Module m1, String pkg);
222 
223     /**
224      * Updates module m1 to export a package to module m2. The export does
225      * not result in a strong reference to m2 (m2 can be GC'ed).
226      */
227     void addExports(Module m1, String pkg, Module m2);
228 
229     /**
230      * Updates a module m to export a package to all unnamed modules.
231      */
232     void addExportsToAllUnnamed(Module m, String pkg);
233 
234     /**
235      * Updates module m1 to open a package to module m2. Opening the
236      * package does not result in a strong reference to m2 (m2 can be GC'ed).
237      */
238     void addOpens(Module m1, String pkg, Module m2);
239 
240     /**
241      * Updates module m to open a package to all unnamed modules.
242      */
243     void addOpensToAllUnnamed(Module m, String pkg);
244 
245     /**
246      * Updates module m to open all packages in the given sets.
247      */
248     void addOpensToAllUnnamed(Module m, Set<String> concealedPkgs, Set<String> exportedPkgs);
249 
250     /**
251      * Updates module m to use a service.
252      */
253     void addUses(Module m, Class<?> service);
254 
255     /**
256      * Returns true if module m reflectively exports a package to other
257      */
258     boolean isReflectivelyExported(Module module, String pn, Module other);
259 
260     /**
261      * Returns true if module m reflectively opens a package to other
262      */
263     boolean isReflectivelyOpened(Module module, String pn, Module other);
264 
265     /**
266      * Updates module m to allow access to restricted methods.
267      */
268     Module addEnableNativeAccess(Module m);
269 
270     /**
271      * Updates all unnamed modules to allow access to restricted methods.
272      */
273     void addEnableNativeAccessAllUnnamed();
274 
275     /**
276      * Returns true if module m can access restricted methods.
277      */
278     boolean isEnableNativeAccess(Module m);
279 
280     /**
281      * Returns the ServicesCatalog for the given Layer.
282      */
283     ServicesCatalog getServicesCatalog(ModuleLayer layer);
284 
285     /**
286      * Record that this layer has at least one module defined to the given
287      * class loader.
288      */
289     void bindToLoader(ModuleLayer layer, ClassLoader loader);
290 
291     /**
292      * Returns an ordered stream of layers. The first element is the
293      * given layer, the remaining elements are its parents, in DFS order.
294      */
295     Stream<ModuleLayer> layers(ModuleLayer layer);
296 
297     /**
298      * Returns a stream of the layers that have modules defined to the
299      * given class loader.
300      */
301     Stream<ModuleLayer> layers(ClassLoader loader);
302 
303     /**
304      * Constructs a new {@code String} by decoding the specified subarray of
305      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
306      *
307      * The caller of this method shall relinquish and transfer the ownership of
308      * the byte array to the callee since the later will not make a copy.
309      *
310      * @param bytes the byte array source
311      * @param cs the Charset
312      * @return the newly created string
313      * @throws CharacterCodingException for malformed or unmappable bytes
314      */
315     String newStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException;
316 
317     /**
318      * Encode the given string into a sequence of bytes using the specified Charset.
319      *
320      * This method avoids copying the String's internal representation if the input
321      * is ASCII.
322      *
323      * This method throws CharacterCodingException instead of replacing when
324      * malformed input or unmappable characters are encountered.
325      *
326      * @param s the string to encode
327      * @param cs the charset
328      * @return the encoded bytes
329      * @throws CharacterCodingException for malformed input or unmappable characters
330      */
331     byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException;
332 
333     /**
334      * Returns a new string by decoding from the given utf8 bytes array.
335      *
336      * @param off the index of the first byte to decode
337      * @param len the number of bytes to decode
338      * @return the newly created string
339      * @throws IllegalArgumentException for malformed or unmappable bytes.
340      */
341     String newStringUTF8NoRepl(byte[] bytes, int off, int len);
342 
343     /**
344      * Encode the given string into a sequence of bytes using utf8.
345      *
346      * @param s the string to encode
347      * @return the encoded bytes in utf8
348      * @throws IllegalArgumentException for malformed surrogates
349      */
350     byte[] getBytesUTF8NoRepl(String s);
351 
352     /**
353      * Inflated copy from byte[] to char[], as defined by StringLatin1.inflate
354      */
355     void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len);
356 
357     /**
358      * Decodes ASCII from the source byte array into the destination
359      * char array.
360      *
361      * @return the number of bytes successfully decoded, at most len
362      */
363     int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len);
364 
365     /**
366      * Encodes ASCII codepoints as possible from the source array into
367      * the destination byte array, assuming that the encoding is ASCII
368      * compatible
369      *
370      * @return the number of bytes successfully encoded, or 0 if none
371      */
372     int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len);
373 
374     /**
375      * Set the cause of Throwable
376      * @param cause set t's cause to new value
377      */
378     void setCause(Throwable t, Throwable cause);
379 
380     /**
381      * Get protection domain of the given Class
382      */
383     ProtectionDomain protectionDomain(Class<?> c);
384 
385     /**
386      * Get a method handle of string concat helper method
387      */
388     MethodHandle stringConcatHelper(String name, MethodType methodType);
389 
390     /**
391      * Get the string concat initial coder
392      */
393     long stringConcatInitialCoder();
394 
395     /**
396      * Update lengthCoder for constant
397      */
398     long stringConcatMix(long lengthCoder, String constant);
399 
400     /**
401      * Join strings
402      */
403     String join(String prefix, String suffix, String delimiter, String[] elements, int size);
404 
405     /*
406      * Get the class data associated with the given class.
407      * @param c the class
408      * @see java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
409      */
410     Object classData(Class<?> c);
411 
412     long findNative(ClassLoader loader, String entry);
413 
414     /**
415      * Direct access to Shutdown.exit to avoid security manager checks
416      * @param statusCode the status code
417      */
418     void exit(int statusCode);
419 
420     /**
421      * Returns an array of all platform threads.
422      */
423     Thread[] getAllThreads();
424 
425     /**
426      * Returns the ThreadContainer for a thread, may be null.
427      */
428     ThreadContainer threadContainer(Thread thread);
429 
430     /**
431      * Starts a thread in the given ThreadContainer.
432      */
433     void start(Thread thread, ThreadContainer container);
434 
435     /**
436      * Returns the top of the given thread's stackable scope stack.
437      */
438     StackableScope headStackableScope(Thread thread);
439 
440     /**
441      * Sets the top of the current thread's stackable scope stack.
442      */
443     void setHeadStackableScope(StackableScope scope);
444 
445     /**
446      * Returns the Thread object for the current platform thread. If the
447      * current thread is a virtual thread then this method returns the carrier.
448      */
449     Thread currentCarrierThread();
450 
451     /**
452      * Executes the given value returning task on the current carrier thread.
453      */
454     <V> V executeOnCarrierThread(Callable<V> task) throws Exception;
455 
456     /**
457      * Returns the value of the current carrier thread's copy of a thread-local.
458      */
459     <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local);
460 
461     /**
462      * Sets the value of the current carrier thread's copy of a thread-local.
463      */
464     <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value);
465 
466     /**
467      * Removes the value of the current carrier thread's copy of a thread-local.
468      */
469     void removeCarrierThreadLocal(CarrierThreadLocal<?> local);
470 
471     /**
472      * Returns {@code true} if there is a value in the current carrier thread's copy of
473      * thread-local, even if that values is {@code null}.
474      */
475     boolean isCarrierThreadLocalPresent(CarrierThreadLocal<?> local);
476 
477     /**
478      * Returns the current thread's extent locals cache
479      */
480     Object[] extentLocalCache();
481 
482     /**
483      * Sets the current thread's extent locals cache
484      */
485     void setExtentLocalCache(Object[] cache);
486 
487     /**
488      * Return the current thread's extent local bindings.
489      */
490     Object extentLocalBindings();
491 
492     /**
493      * Set the current thread's extent local bindings.
494      */
495     void setExtentLocalBindings(Object bindings);
496 
497     /**
498      * Returns the innermost mounted continuation
499      */
500     Continuation getContinuation(Thread thread);
501 
502     /**
503      * Sets the innermost mounted continuation
504      */
505     void setContinuation(Thread thread, Continuation continuation);
506 
507     /**
508      * The ContinuationScope of virtual thread continuations
509      */
510     ContinuationScope virtualThreadContinuationScope();
511 
512     /**
513      * Parks the current virtual thread.
514      * @throws WrongThreadException if the current thread is not a virtual thread
515      */
516     void parkVirtualThread();
517 
518     /**
519      * Parks the current virtual thread for up to the given waiting time.
520      * @param nanos the maximum number of nanoseconds to wait
521      * @throws WrongThreadException if the current thread is not a virtual thread
522      */
523     void parkVirtualThread(long nanos);
524 
525     /**
526      * Re-enables a virtual thread for scheduling. If the thread was parked then
527      * it will be unblocked, otherwise its next attempt to park will not block
528      * @param thread the virtual thread to unpark
529      * @throws IllegalArgumentException if the thread is not a virtual thread
530      * @throws RejectedExecutionException if the scheduler cannot accept a task
531      */
532     void unparkVirtualThread(Thread thread);
533 
534     /**
535      * Creates a new StackWalker
536      */
537     StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
538                                        ContinuationScope contScope,
539                                        Continuation continuation);
540 
541     /**
542      * {@return the primary class for a primitive class}
543      *
544      * @param klass a class
545      */
546     Class<?> asPrimaryType(Class<?> klass);
547 
548     /**
549      * {@return the value type of a primitive class}
550      *
551      * @param klass a class
552      */
553     Class<?> asValueType(Class<?> klass);
554 
555     /**
556      * {@return true if the class is the primary type of a primitive class}
557      *
558      * @param klass a class
559      */
560     boolean isPrimaryType(Class<?> klass);
561 
562     /**
563      * {@return true if the class is the primary type of a primitive class}
564      *
565      * @param klass a class
566      */
567     boolean isPrimitiveValueType(Class<?> klass);
568 
569     /**
570      * Returns {@code true} if this class is a primitive class.
571      */
572     boolean isPrimitiveClass(Class<?> klass);
573 
574 }