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.function.BiFunction; 50 import java.util.stream.Stream; 51 52 import jdk.internal.loader.NativeLibraries; 53 import jdk.internal.misc.CarrierThreadLocal; 54 import jdk.internal.module.ServicesCatalog; 55 import jdk.internal.reflect.ConstantPool; 56 import jdk.internal.vm.Continuation; 57 import jdk.internal.vm.ContinuationScope; 58 import jdk.internal.vm.StackableScope; 59 import jdk.internal.vm.ThreadContainer; 60 import sun.reflect.annotation.AnnotationType; 61 import sun.nio.ch.Interruptible; 62 63 public interface JavaLangAccess { 64 65 /** 66 * Returns the list of {@code Method} objects for the declared public 67 * methods of this class or interface that have the specified method name 68 * and parameter types. 69 */ 70 List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes); 71 72 /** 73 * Return most specific method that matches name and parameterTypes. 74 */ 75 Method findMethod(Class<?> klass, boolean publicOnly, String name, Class<?>... parameterTypes); 76 77 /** 78 * Return the constant pool for a class. 79 */ 80 ConstantPool getConstantPool(Class<?> klass); 81 82 /** 83 * Compare-And-Set the AnnotationType instance corresponding to this class. 84 * (This method only applies to annotation types.) 85 */ 86 boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType); 87 88 /** 89 * Get the AnnotationType instance corresponding to this class. 90 * (This method only applies to annotation types.) 91 */ 92 AnnotationType getAnnotationType(Class<?> klass); 93 94 /** 95 * Get the declared annotations for a given class, indexed by their types. 96 */ 97 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass); 98 99 /** 100 * Get the array of bytes that is the class-file representation 101 * of this Class' annotations. 102 */ 103 byte[] getRawClassAnnotations(Class<?> klass); 104 105 /** 106 * Get the array of bytes that is the class-file representation 107 * of this Class' type annotations. 108 */ 109 byte[] getRawClassTypeAnnotations(Class<?> klass); 110 111 /** 112 * Get the array of bytes that is the class-file representation 113 * of this Executable's type annotations. 114 */ 115 byte[] getRawExecutableTypeAnnotations(Executable executable); 116 117 /** 118 * Get the int value of the Class's class-file access flags. 119 */ 120 int getClassFileAccessFlags(Class<?> klass); 121 122 /** 123 * Returns the elements of an enum class or null if the 124 * Class object does not represent an enum type; 125 * the result is uncloned, cached, and shared by all callers. 126 */ 127 <E extends Enum<E>> E[] getEnumConstantsShared(Class<E> klass); 128 129 /** 130 * Returns the big-endian packed minor-major version of the class file 131 * of this class. 132 */ 133 int classFileVersion(Class<?> clazz); 134 135 /** 136 * Set current thread's blocker field. 137 */ 138 void blockedOn(Interruptible b); 139 140 /** 141 * Registers a shutdown hook. 142 * 143 * It is expected that this method with registerShutdownInProgress=true 144 * is only used to register DeleteOnExitHook since the first file 145 * may be added to the delete on exit list by the application shutdown 146 * hooks. 147 * 148 * @param slot the slot in the shutdown hook array, whose element 149 * will be invoked in order during shutdown 150 * @param registerShutdownInProgress true to allow the hook 151 * to be registered even if the shutdown is in progress. 152 * @param hook the hook to be registered 153 * 154 * @throws IllegalStateException if shutdown is in progress and 155 * the slot is not valid to register. 156 */ 157 void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook); 158 159 /** 160 * Invokes the finalize method of the given object. 161 */ 162 void invokeFinalize(Object o) throws Throwable; 163 164 /** 165 * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s) 166 * associated with the given class loader, creating it if it doesn't already exist. 167 */ 168 ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl); 169 170 /** 171 * Defines a class with the given name to a class loader. 172 */ 173 Class<?> defineClass(ClassLoader cl, String name, byte[] b, ProtectionDomain pd, String source); 174 175 /** 176 * Defines a class with the given name to a class loader with 177 * the given flags and class data. 178 * 179 * @see java.lang.invoke.MethodHandles.Lookup#defineClass 180 */ 181 Class<?> defineClass(ClassLoader cl, Class<?> lookup, String name, byte[] b, ProtectionDomain pd, boolean initialize, int flags, Object classData); 182 183 /** 184 * Returns a class loaded by the bootstrap class loader. 185 */ 186 Class<?> findBootstrapClassOrNull(String name); 187 188 /** 189 * Define a Package of the given name and module by the given class loader. 190 */ 191 Package definePackage(ClassLoader cl, String name, Module module); 192 193 /** 194 * Defines a new module to the Java virtual machine. The module 195 * is defined to the given class loader. 196 * 197 * The URI is for information purposes only, it can be {@code null}. 198 */ 199 Module defineModule(ClassLoader loader, ModuleDescriptor descriptor, URI uri); 200 201 /** 202 * Defines the unnamed module for the given class loader. 203 */ 204 Module defineUnnamedModule(ClassLoader loader); 205 206 /** 207 * Updates the readability so that module m1 reads m2. The new read edge 208 * does not result in a strong reference to m2 (m2 can be GC'ed). 209 * 210 * This method is the same as m1.addReads(m2) but without a permission check. 211 */ 212 void addReads(Module m1, Module m2); 213 214 /** 215 * Updates module m to read all unnamed modules. 216 */ 217 void addReadsAllUnnamed(Module m); 218 219 /** 220 * Updates module m1 to export a package unconditionally. 221 */ 222 void addExports(Module m1, String pkg); 223 224 /** 225 * Updates module m1 to export a package to module m2. The export does 226 * not result in a strong reference to m2 (m2 can be GC'ed). 227 */ 228 void addExports(Module m1, String pkg, Module m2); 229 230 /** 231 * Updates a module m to export a package to all unnamed modules. 232 */ 233 void addExportsToAllUnnamed(Module m, String pkg); 234 235 /** 236 * Updates module m1 to open a package to module m2. Opening the 237 * package does not result in a strong reference to m2 (m2 can be GC'ed). 238 */ 239 void addOpens(Module m1, String pkg, Module m2); 240 241 /** 242 * Updates module m to open a package to all unnamed modules. 243 */ 244 void addOpensToAllUnnamed(Module m, String pkg); 245 246 /** 247 * Updates module m to use a service. 248 */ 249 void addUses(Module m, Class<?> service); 250 251 /** 252 * Returns true if module m reflectively exports a package to other 253 */ 254 boolean isReflectivelyExported(Module module, String pn, Module other); 255 256 /** 257 * Returns true if module m reflectively opens a package to other 258 */ 259 boolean isReflectivelyOpened(Module module, String pn, Module other); 260 261 /** 262 * Updates module m to allow access to restricted methods. 263 */ 264 Module addEnableNativeAccess(Module m); 265 266 /** 267 * Updates module named {@code name} in layer {@code layer} to allow access to restricted methods. 268 * Returns true iff the given module exists in the given layer. 269 */ 270 boolean addEnableNativeAccess(ModuleLayer layer, String name); 271 272 /** 273 * Updates all unnamed modules to allow access to restricted methods. 274 */ 275 void addEnableNativeAccessToAllUnnamed(); 276 277 /** 278 * Ensure that the given module has native access. If not, warn or throw exception 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 * Returns the ServicesCatalog for the given Layer. 289 */ 290 ServicesCatalog getServicesCatalog(ModuleLayer layer); 291 292 /** 293 * Record that this layer has at least one module defined to the given 294 * class loader. 295 */ 296 void bindToLoader(ModuleLayer layer, ClassLoader loader); 297 298 /** 299 * Returns an ordered stream of layers. The first element is the 300 * given layer, the remaining elements are its parents, in DFS order. 301 */ 302 Stream<ModuleLayer> layers(ModuleLayer layer); 303 304 /** 305 * Returns a stream of the layers that have modules defined to the 306 * given class loader. 307 */ 308 Stream<ModuleLayer> layers(ClassLoader loader); 309 310 /** 311 * Count the number of leading positive bytes in the range. 312 * 313 * @implSpec Implementations of this method must perform bounds checks. 314 */ 315 int countPositives(byte[] ba, int off, int len); 316 317 /** 318 * Count the number of leading non-zero ascii chars in the String. 319 */ 320 int countNonZeroAscii(String s); 321 322 /** 323 * Constructs a new {@code String} with the supplied Latin1 bytes. 324 * <p> 325 * <b>WARNING: The caller of this method shall relinquish and transfer the 326 * ownership of the byte array to the callee</b>, since the latter will not 327 * make a copy. 328 * 329 * @param bytes the byte array source 330 * @return the newly created string 331 */ 332 String uncheckedNewStringWithLatin1Bytes(byte[] bytes); 333 334 /** 335 * Constructs a new {@code String} by decoding the specified byte array 336 * using the specified {@linkplain java.nio.charset.Charset charset}. 337 * <p> 338 * <b>WARNING: The caller of this method shall relinquish and transfer the 339 * ownership of the byte array to the callee</b>, since the latter will not 340 * make a copy. 341 * 342 * @param bytes the byte array source 343 * @param cs the Charset 344 * @return the newly created string 345 * @throws CharacterCodingException for malformed or unmappable bytes 346 */ 347 String uncheckedNewStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException; 348 349 /** 350 * Encode the given string into a sequence of bytes using the specified 351 * {@linkplain java.nio.charset.Charset charset}. 352 * <p> 353 * <b>WARNING: This method returns the {@code byte[]} backing the provided 354 * {@code String}, if the input is ASCII. Hence, the returned byte array 355 * must not be modified.</b> 356 * <p> 357 * This method throws {@code CharacterCodingException} instead of replacing 358 * when malformed input or unmappable characters are encountered. 359 * 360 * @param s the string to encode 361 * @param cs the charset 362 * @return the encoded bytes 363 * @throws CharacterCodingException for malformed input or unmappable characters 364 */ 365 byte[] uncheckedGetBytesNoRepl(String s, Charset cs) throws CharacterCodingException; 366 367 /** 368 * Get the {@code char} at {@code index} in a {@code byte[]} in internal 369 * UTF-16 representation. 370 * <p> 371 * <b>WARNING: This method does not perform any bound checks.</b> 372 * 373 * @param bytes the UTF-16 encoded bytes 374 * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1) 375 * @return the char value 376 */ 377 char uncheckedGetUTF16Char(byte[] bytes, int index); 378 379 /** 380 * Put the {@code ch} at {@code index} in a {@code byte[]} in internal 381 * UTF-16 representation. 382 * <p> 383 * <b>WARNING: This method does not perform any bound checks.</b> 384 * 385 * @param bytes the UTF-16 encoded bytes 386 * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1) 387 */ 388 void uncheckedPutCharUTF16(byte[] bytes, int index, int ch); 389 390 /** 391 * Encode the given string into a sequence of bytes using utf8. 392 * 393 * @param s the string to encode 394 * @return the encoded bytes in utf8 395 * @throws IllegalArgumentException for malformed surrogates 396 */ 397 byte[] getBytesUTF8NoRepl(String s); 398 399 /** 400 * Inflated copy from {@code byte[]} to {@code char[]}, as defined by 401 * {@code StringLatin1.inflate}. 402 * 403 * @implSpec Implementations of this method must perform bounds checks. 404 */ 405 void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len); 406 407 /** 408 * Decodes ASCII from the source byte array into the destination 409 * char array. 410 * 411 * @implSpec Implementations of this method must perform bounds checks. 412 * 413 * @return the number of bytes successfully decoded, at most len 414 */ 415 int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len); 416 417 /** 418 * Returns the initial `System.in` to determine if it is replaced 419 * with `System.setIn(newIn)` method 420 */ 421 InputStream initialSystemIn(); 422 423 /** 424 * Returns the initial value of System.err. 425 */ 426 PrintStream initialSystemErr(); 427 428 /** 429 * Encodes as many ASCII codepoints as possible from the source 430 * character array into the destination byte array, assuming that 431 * the encoding is ASCII compatible. 432 * 433 * @param sa the source character array 434 * @param sp the index of the source array to start reading from 435 * @param da the target byte array 436 * @param dp the index of the target array to start writing to 437 * @param len the total number of characters to be encoded 438 * @return the total number of characters successfully encoded 439 * @throws NullPointerException if any of the provided arrays is null 440 */ 441 int encodeASCII(char[] sa, int sp, byte[] da, int dp, int len); 442 443 /** 444 * Set the cause of Throwable 445 * @param cause set t's cause to new value 446 */ 447 void setCause(Throwable t, Throwable cause); 448 449 /** 450 * Get protection domain of the given Class 451 */ 452 ProtectionDomain protectionDomain(Class<?> c); 453 454 /** 455 * Get a method handle of string concat helper method 456 */ 457 MethodHandle stringConcatHelper(String name, MethodType methodType); 458 459 /** 460 * Get the string concat initial coder 461 */ 462 long stringConcatInitialCoder(); 463 464 /** 465 * Update lengthCoder for constant 466 */ 467 long stringConcatMix(long lengthCoder, String constant); 468 469 /** 470 * Mix value length and coder into current length and coder. 471 */ 472 long stringConcatMix(long lengthCoder, char value); 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 innermost mounted continuation 579 */ 580 Continuation getContinuation(Thread thread); 581 582 /** 583 * Sets the innermost mounted continuation 584 */ 585 void setContinuation(Thread thread, Continuation continuation); 586 587 /** 588 * The ContinuationScope of virtual thread continuations 589 */ 590 ContinuationScope virtualThreadContinuationScope(); 591 592 /** 593 * Parks the current virtual thread. 594 * @throws WrongThreadException if the current thread is not a virtual thread 595 */ 596 void parkVirtualThread(); 597 598 /** 599 * Parks the current virtual thread for up to the given waiting time. 600 * @param nanos the maximum number of nanoseconds to wait 601 * @throws WrongThreadException if the current thread is not a virtual thread 602 */ 603 void parkVirtualThread(long nanos); 604 605 /** 606 * Re-enables a virtual thread for scheduling. If the thread was parked then 607 * it will be unblocked, otherwise its next attempt to park will not block 608 * @param thread the virtual thread to unpark 609 * @throws IllegalArgumentException if the thread is not a virtual thread 610 * @throws RejectedExecutionException if the scheduler cannot accept a task 611 */ 612 void unparkVirtualThread(Thread thread); 613 614 /** 615 * Returns the virtual thread default scheduler. 616 */ 617 Executor virtualThreadDefaultScheduler(); 618 619 /** 620 * Creates a new StackWalker 621 */ 622 StackWalker newStackWalkerInstance(Set<StackWalker.Option> options, 623 ContinuationScope contScope, 624 Continuation continuation); 625 626 /** 627 * Returns the class file format version of the class. 628 */ 629 int classFileFormatVersion(Class<?> klass); 630 631 /** 632 * Returns '<loader-name>' @<id> if classloader has a name 633 * explicitly set otherwise <qualified-class-name> @<id> 634 */ 635 String getLoaderNameID(ClassLoader loader); 636 637 /** 638 * Copy the string bytes to an existing segment, avoiding intermediate copies. 639 */ 640 void copyToSegmentRaw(String string, MemorySegment segment, long offset); 641 642 /** 643 * Are the string bytes compatible with the given charset? 644 */ 645 boolean bytesCompatible(String string, Charset charset); 646 }