1 /*
  2  * Copyright (c) 2003, 2025, 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.io.InputStream;
 29 import java.io.PrintStream;
 30 import java.lang.annotation.Annotation;
 31 import java.lang.foreign.MemorySegment;
 32 import java.lang.foreign.SymbolLookup;
 33 import java.lang.invoke.MethodHandle;
 34 import java.lang.invoke.MethodType;
 35 import java.lang.module.ModuleDescriptor;
 36 import java.lang.reflect.Executable;
 37 import java.lang.reflect.Method;
 38 import java.net.URI;
 39 import java.nio.charset.CharacterCodingException;
 40 import java.nio.charset.Charset;
 41 import java.security.ProtectionDomain;
 42 import java.util.List;
 43 import java.util.Map;
 44 import java.util.Set;
 45 import java.util.concurrent.ConcurrentHashMap;
 46 import java.util.concurrent.Executor;
 47 import java.util.concurrent.RejectedExecutionException;
 48 import java.util.stream.Stream;
 49 
 50 import jdk.internal.loader.NativeLibraries;
 51 import jdk.internal.misc.CarrierThreadLocal;
 52 import jdk.internal.module.ServicesCatalog;
 53 import jdk.internal.reflect.ConstantPool;
 54 import jdk.internal.vm.Continuation;
 55 import jdk.internal.vm.ContinuationScope;
 56 import jdk.internal.vm.StackableScope;
 57 import jdk.internal.vm.ThreadContainer;
 58 import sun.reflect.annotation.AnnotationType;
 59 import sun.nio.ch.Interruptible;
 60 
 61 public interface JavaLangAccess {
 62 
 63     /**
 64      * Returns the list of {@code Method} objects for the declared public
 65      * methods of this class or interface that have the specified method name
 66      * and parameter types.
 67      */
 68     List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes);
 69 
 70     /**
 71      * Return most specific method that matches name and parameterTypes.
 72      */
 73     Method findMethod(Class<?> klass, boolean publicOnly, String name, Class<?>... parameterTypes);
 74 
 75     /**
 76      * Return the constant pool for a class.
 77      */
 78     ConstantPool getConstantPool(Class<?> klass);
 79 
 80     /**
 81      * Compare-And-Set the AnnotationType instance corresponding to this class.
 82      * (This method only applies to annotation types.)
 83      */
 84     boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType);
 85 
 86     /**
 87      * Get the AnnotationType instance corresponding to this class.
 88      * (This method only applies to annotation types.)
 89      */
 90     AnnotationType getAnnotationType(Class<?> klass);
 91 
 92     /**
 93      * Get the declared annotations for a given class, indexed by their types.
 94      */
 95     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass);
 96 
 97     /**
 98      * Get the array of bytes that is the class-file representation
 99      * of this Class' annotations.
100      */
101     byte[] getRawClassAnnotations(Class<?> klass);
102 
103     /**
104      * Get the array of bytes that is the class-file representation
105      * of this Class' type annotations.
106      */
107     byte[] getRawClassTypeAnnotations(Class<?> klass);
108 
109     /**
110      * Get the array of bytes that is the class-file representation
111      * of this Executable's type annotations.
112      */
113     byte[] getRawExecutableTypeAnnotations(Executable executable);
114 
115     /**
116      * Returns the elements of an enum class or null if the
117      * Class object does not represent an enum type;
118      * the result is uncloned, cached, and shared by all callers.
119      */
120     <E extends Enum<E>> E[] getEnumConstantsShared(Class<E> klass);
121 
122     /**
123      * Set current thread's blocker field.
124      */
125     void blockedOn(Interruptible b);
126 
127     /**
128      * Registers a shutdown hook.
129      *
130      * It is expected that this method with registerShutdownInProgress=true
131      * is only used to register DeleteOnExitHook since the first file
132      * may be added to the delete on exit list by the application shutdown
133      * hooks.
134      *
135      * @param slot  the slot in the shutdown hook array, whose element
136      *              will be invoked in order during shutdown
137      * @param registerShutdownInProgress true to allow the hook
138      *        to be registered even if the shutdown is in progress.
139      * @param hook  the hook to be registered
140      *
141      * @throws IllegalStateException if shutdown is in progress and
142      *         the slot is not valid to register.
143      */
144     void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook);
145 
146     /**
147      * Invokes the finalize method of the given object.
148      */
149     void invokeFinalize(Object o) throws Throwable;
150 
151     /**
152      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
153      * associated with the given class loader, creating it if it doesn't already exist.
154      */
155     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl);
156 
157     /**
158      * Defines a class with the given name to a class loader.
159      */
160     Class<?> defineClass(ClassLoader cl, String name, byte[] b, ProtectionDomain pd, String source);
161 
162     /**
163      * Defines a class with the given name to a class loader with
164      * the given flags and class data.
165      *
166      * @see java.lang.invoke.MethodHandles.Lookup#defineClass
167      */
168     Class<?> defineClass(ClassLoader cl, Class<?> lookup, String name, byte[] b, ProtectionDomain pd, boolean initialize, int flags, Object classData);
169 
170     /**
171      * Returns a class loaded by the bootstrap class loader.
172      */
173     Class<?> findBootstrapClassOrNull(String name);
174 
175     /**
176      * Define a Package of the given name and module by the given class loader.
177      */
178     Package definePackage(ClassLoader cl, String name, Module module);
179 
180     /**
181      * Defines a new module to the Java virtual machine. The module
182      * is defined to the given class loader.
183      *
184      * The URI is for information purposes only, it can be {@code null}.
185      */
186     Module defineModule(ClassLoader loader, ModuleDescriptor descriptor, URI uri);
187 
188     /**
189      * Defines the unnamed module for the given class loader.
190      */
191     Module defineUnnamedModule(ClassLoader loader);
192 
193     /**
194      * Updates the readability so that module m1 reads m2. The new read edge
195      * does not result in a strong reference to m2 (m2 can be GC'ed).
196      *
197      * This method is the same as m1.addReads(m2) but without a permission check.
198      */
199     void addReads(Module m1, Module m2);
200 
201     /**
202      * Updates module m to read all unnamed modules.
203      */
204     void addReadsAllUnnamed(Module m);
205 
206     /**
207      * Updates module m1 to export a package unconditionally.
208      */
209     void addExports(Module m1, String pkg);
210 
211     /**
212      * Updates module m1 to export a package to module m2. The export does
213      * not result in a strong reference to m2 (m2 can be GC'ed).
214      */
215     void addExports(Module m1, String pkg, Module m2);
216 
217     /**
218      * Updates a module m to export a package to all unnamed modules.
219      */
220     void addExportsToAllUnnamed(Module m, String pkg);
221 
222     /**
223      * Updates module m1 to open a package to module m2. Opening the
224      * package does not result in a strong reference to m2 (m2 can be GC'ed).
225      */
226     void addOpens(Module m1, String pkg, Module m2);
227 
228     /**
229      * Updates module m to open a package to all unnamed modules.
230      */
231     void addOpensToAllUnnamed(Module m, String pkg);
232 
233     /**
234      * Updates module m to open all packages in the given sets.
235      */
236     void addOpensToAllUnnamed(Module m, Set<String> concealedPkgs, Set<String> exportedPkgs);
237 
238     /**
239      * Updates module m to use a service.
240      */
241     void addUses(Module m, Class<?> service);
242 
243     /**
244      * Returns true if module m reflectively exports a package to other
245      */
246     boolean isReflectivelyExported(Module module, String pn, Module other);
247 
248     /**
249      * Returns true if module m reflectively opens a package to other
250      */
251     boolean isReflectivelyOpened(Module module, String pn, Module other);
252 
253     /**
254      * Updates module m to allow access to restricted methods.
255      */
256     Module addEnableNativeAccess(Module m);
257 
258     /**
259      * Updates module named {@code name} in layer {@code layer} to allow access to restricted methods.
260      * Returns true iff the given module exists in the given layer.
261      */
262     boolean addEnableNativeAccess(ModuleLayer layer, String name);
263 
264     /**
265      * Updates all unnamed modules to allow access to restricted methods.
266      */
267     void addEnableNativeAccessToAllUnnamed();
268 
269     /**
270      * Ensure that the given module has native access. If not, warn or throw exception depending on the configuration.
271      * @param m the module in which native access occurred
272      * @param owner the owner of the restricted method being called (or the JNI method being bound)
273      * @param methodName the name of the restricted method being called (or the JNI method being bound)
274      * @param currentClass the class calling the restricted method (for JNI, this is the same as {@code owner})
275      * @param jni {@code true}, if this event is related to a JNI method being bound
276      */
277     void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass, boolean jni);
278 
279     /**
280      * Returns the ServicesCatalog for the given Layer.
281      */
282     ServicesCatalog getServicesCatalog(ModuleLayer layer);
283 
284     /**
285      * Record that this layer has at least one module defined to the given
286      * class loader.
287      */
288     void bindToLoader(ModuleLayer layer, ClassLoader loader);
289 
290     /**
291      * Returns an ordered stream of layers. The first element is the
292      * given layer, the remaining elements are its parents, in DFS order.
293      */
294     Stream<ModuleLayer> layers(ModuleLayer layer);
295 
296     /**
297      * Returns a stream of the layers that have modules defined to the
298      * given class loader.
299      */
300     Stream<ModuleLayer> layers(ClassLoader loader);
301 
302     /**
303      * Count the number of leading positive bytes in the range.
304      */
305     int countPositives(byte[] ba, int off, int len);
306 
307     /**
308      * Count the number of leading non-zero ascii chars in the String.
309      */
310     int countNonZeroAscii(String s);
311 
312     /**
313      * Constructs a new {@code String} by decoding the specified subarray of
314      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
315      *
316      * The caller of this method shall relinquish and transfer the ownership of
317      * the byte array to the callee since the later will not make a copy.
318      *
319      * @param bytes the byte array source
320      * @param cs the Charset
321      * @return the newly created string
322      * @throws CharacterCodingException for malformed or unmappable bytes
323      */
324     String newStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException;
325 
326     /**
327      * Encode the given string into a sequence of bytes using the specified Charset.
328      *
329      * This method avoids copying the String's internal representation if the input
330      * is ASCII.
331      *
332      * This method throws CharacterCodingException instead of replacing when
333      * malformed input or unmappable characters are encountered.
334      *
335      * @param s the string to encode
336      * @param cs the charset
337      * @return the encoded bytes
338      * @throws CharacterCodingException for malformed input or unmappable characters
339      */
340     byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException;
341 
342     /**
343      * Returns a new string by decoding from the given utf8 bytes array.
344      *
345      * @param off the index of the first byte to decode
346      * @param len the number of bytes to decode
347      * @return the newly created string
348      * @throws IllegalArgumentException for malformed or unmappable bytes.
349      */
350     String newStringUTF8NoRepl(byte[] bytes, int off, int len);
351 
352     /**
353      * Get the char at index in a byte[] in internal UTF-16 representation,
354      * with no bounds checks.
355      *
356      * @param bytes the UTF-16 encoded bytes
357      * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1)
358      * @return the char value
359      */
360     char getUTF16Char(byte[] bytes, int index);
361 
362     /**
363      * Put the char at index in a byte[] in internal UTF-16 representation,
364      * with no bounds checks.
365      *
366      * @param bytes the UTF-16 encoded bytes
367      * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1)
368      */
369     void putCharUTF16(byte[] bytes, int index, int ch);
370 
371     /**
372      * Encode the given string into a sequence of bytes using utf8.
373      *
374      * @param s the string to encode
375      * @return the encoded bytes in utf8
376      * @throws IllegalArgumentException for malformed surrogates
377      */
378     byte[] getBytesUTF8NoRepl(String s);
379 
380     /**
381      * Inflated copy from byte[] to char[], as defined by StringLatin1.inflate
382      */
383     void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len);
384 
385     /**
386      * Decodes ASCII from the source byte array into the destination
387      * char array.
388      *
389      * @return the number of bytes successfully decoded, at most len
390      */
391     int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len);
392 
393     /**
394      * Returns the initial `System.in` to determine if it is replaced
395      * with `System.setIn(newIn)` method
396      */
397     InputStream initialSystemIn();
398 
399     /**
400      * Returns the initial value of System.err.
401      */
402     PrintStream initialSystemErr();
403 
404     /**
405      * Encodes ASCII codepoints as possible from the source array into
406      * the destination byte array, assuming that the encoding is ASCII
407      * compatible
408      *
409      * @return the number of bytes successfully encoded, or 0 if none
410      */
411     int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len);
412 
413     /**
414      * Set the cause of Throwable
415      * @param cause set t's cause to new value
416      */
417     void setCause(Throwable t, Throwable cause);
418 
419     /**
420      * Get protection domain of the given Class
421      */
422     ProtectionDomain protectionDomain(Class<?> c);
423 
424     /**
425      * Get a method handle of string concat helper method
426      */
427     MethodHandle stringConcatHelper(String name, MethodType methodType);
428 
429     /**
430      * Get the string concat initial coder
431      */
432     long stringConcatInitialCoder();
433 
434     /**
435      * Update lengthCoder for constant
436      */
437     long stringConcatMix(long lengthCoder, String constant);
438 
439     /**
440      * Mix value length and coder into current length and coder.
441      */
442     long stringConcatMix(long lengthCoder, char value);
443 
444     Object stringConcat1(String[] constants);
445 
446     /**
447      * Get the string initial coder, When COMPACT_STRINGS is on, it returns 0, and when it is off, it returns 1.
448      */
449     byte stringInitCoder();
450 
451     /**
452      * Get the Coder of String, which is used by StringConcatFactory to calculate the initCoder of constants
453      */
454     byte stringCoder(String str);
455 
456     /**
457      * Join strings
458      */
459     String join(String prefix, String suffix, String delimiter, String[] elements, int size);
460 
461     /**
462      * Concatenation of prefix and suffix characters to a String for early bootstrap
463      */
464     String concat(String prefix, Object value, String suffix);
465 
466     /*
467      * Get the class data associated with the given class.
468      * @param c the class
469      * @see java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
470      */
471     Object classData(Class<?> c);
472 
473     /**
474      * Returns the {@link NativeLibraries} object associated with the provided class loader.
475      * This is used by {@link SymbolLookup#loaderLookup()}.
476      */
477     NativeLibraries nativeLibrariesFor(ClassLoader loader);
478 
479     /**
480      * Returns an array of all platform threads.
481      */
482     Thread[] getAllThreads();
483 
484     /**
485      * Returns the ThreadContainer for a thread, may be null.
486      */
487     ThreadContainer threadContainer(Thread thread);
488 
489     /**
490      * Starts a thread in the given ThreadContainer.
491      */
492     void start(Thread thread, ThreadContainer container);
493 
494     /**
495      * Returns the top of the given thread's stackable scope stack.
496      */
497     StackableScope headStackableScope(Thread thread);
498 
499     /**
500      * Sets the top of the current thread's stackable scope stack.
501      */
502     void setHeadStackableScope(StackableScope scope);
503 
504     /**
505      * Returns the Thread object for the current platform thread. If the
506      * current thread is a virtual thread then this method returns the carrier.
507      */
508     Thread currentCarrierThread();
509 
510     /**
511      * Returns the value of the current carrier thread's copy of a thread-local.
512      */
513     <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local);
514 
515     /**
516      * Sets the value of the current carrier thread's copy of a thread-local.
517      */
518     <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value);
519 
520     /**
521      * Removes the value of the current carrier thread's copy of a thread-local.
522      */
523     void removeCarrierThreadLocal(CarrierThreadLocal<?> local);
524 
525     /**
526      * Returns {@code true} if there is a value in the current carrier thread's copy of
527      * thread-local, even if that values is {@code null}.
528      */
529     boolean isCarrierThreadLocalPresent(CarrierThreadLocal<?> local);
530 
531     /**
532      * Returns the current thread's scoped values cache
533      */
534     Object[] scopedValueCache();
535 
536     /**
537      * Sets the current thread's scoped values cache
538      */
539     void setScopedValueCache(Object[] cache);
540 
541     /**
542      * Return the current thread's scoped value bindings.
543      */
544     Object scopedValueBindings();
545 
546     /**
547      * Returns the innermost mounted continuation
548      */
549     Continuation getContinuation(Thread thread);
550 
551     /**
552      * Sets the innermost mounted continuation
553      */
554     void setContinuation(Thread thread, Continuation continuation);
555 
556     /**
557      * The ContinuationScope of virtual thread continuations
558      */
559     ContinuationScope virtualThreadContinuationScope();
560 
561     /**
562      * Parks the current virtual thread.
563      * @throws WrongThreadException if the current thread is not a virtual thread
564      */
565     void parkVirtualThread();
566 
567     /**
568      * Parks the current virtual thread for up to the given waiting time.
569      * @param nanos the maximum number of nanoseconds to wait
570      * @throws WrongThreadException if the current thread is not a virtual thread
571      */
572     void parkVirtualThread(long nanos);
573 
574     /**
575      * Re-enables a virtual thread for scheduling. If the thread was parked then
576      * it will be unblocked, otherwise its next attempt to park will not block
577      * @param thread the virtual thread to unpark
578      * @throws IllegalArgumentException if the thread is not a virtual thread
579      * @throws RejectedExecutionException if the scheduler cannot accept a task
580      */
581     void unparkVirtualThread(Thread thread);
582 
583     /**
584      * Returns the virtual thread default scheduler.
585      */
586     Executor virtualThreadDefaultScheduler();
587 
588     /**
589      * Creates a new StackWalker
590      */
591     StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
592                                        ContinuationScope contScope,
593                                        Continuation continuation);
594     /**
595      * Returns '<loader-name>' @<id> if classloader has a name
596      * explicitly set otherwise <qualified-class-name> @<id>
597      */
598     String getLoaderNameID(ClassLoader loader);
599 
600     /**
601      * Copy the string bytes to an existing segment, avoiding intermediate copies.
602      */
603     void copyToSegmentRaw(String string, MemorySegment segment, long offset);
604 
605     /**
606      * Are the string bytes compatible with the given charset?
607      */
608     boolean bytesCompatible(String string, Charset charset);
609 }