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