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