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