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