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