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