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