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