1 /*
  2  * Copyright (c) 2003, 2023, 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 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
279      * throw exception depending on the configuration.
280      */
281     void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass);
282 
283     /**
284      * Returns the ServicesCatalog for the given Layer.
285      */
286     ServicesCatalog getServicesCatalog(ModuleLayer layer);
287 
288     /**
289      * Record that this layer has at least one module defined to the given
290      * class loader.
291      */
292     void bindToLoader(ModuleLayer layer, ClassLoader loader);
293 
294     /**
295      * Returns an ordered stream of layers. The first element is the
296      * given layer, the remaining elements are its parents, in DFS order.
297      */
298     Stream<ModuleLayer> layers(ModuleLayer layer);
299 
300     /**
301      * Returns a stream of the layers that have modules defined to the
302      * given class loader.
303      */
304     Stream<ModuleLayer> layers(ClassLoader loader);
305 
306     /**
307      * Count the number of leading positive bytes in the range.
308      */
309     int countPositives(byte[] ba, int off, int len);
310 
311     /**
312      * Constructs a new {@code String} by decoding the specified subarray of
313      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
314      *
315      * The caller of this method shall relinquish and transfer the ownership of
316      * the byte array to the callee since the later will not make a copy.
317      *
318      * @param bytes the byte array source
319      * @param cs the Charset
320      * @return the newly created string
321      * @throws CharacterCodingException for malformed or unmappable bytes
322      */
323     String newStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException;
324 
325     /**
326      * Encode the given string into a sequence of bytes using the specified Charset.
327      *
328      * This method avoids copying the String's internal representation if the input
329      * is ASCII.
330      *
331      * This method throws CharacterCodingException instead of replacing when
332      * malformed input or unmappable characters are encountered.
333      *
334      * @param s the string to encode
335      * @param cs the charset
336      * @return the encoded bytes
337      * @throws CharacterCodingException for malformed input or unmappable characters
338      */
339     byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException;
340 
341     /**
342      * Returns a new string by decoding from the given utf8 bytes array.
343      *
344      * @param off the index of the first byte to decode
345      * @param len the number of bytes to decode
346      * @return the newly created string
347      * @throws IllegalArgumentException for malformed or unmappable bytes.
348      */
349     String newStringUTF8NoRepl(byte[] bytes, int off, int len);
350 
351     /**
352      * Get the char at index in a byte[] in internal UTF-16 representation,
353      * with no bounds checks.
354      *
355      * @param bytes the UTF-16 encoded bytes
356      * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1)
357      * @return the char value
358      */
359     char getUTF16Char(byte[] bytes, int index);
360 
361     /**
362      * Encode the given string into a sequence of bytes using utf8.
363      *
364      * @param s the string to encode
365      * @return the encoded bytes in utf8
366      * @throws IllegalArgumentException for malformed surrogates
367      */
368     byte[] getBytesUTF8NoRepl(String s);
369 
370     /**
371      * Inflated copy from byte[] to char[], as defined by StringLatin1.inflate
372      */
373     void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len);
374 
375     /**
376      * Decodes ASCII from the source byte array into the destination
377      * char array.
378      *
379      * @return the number of bytes successfully decoded, at most len
380      */
381     int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len);
382 
383     /**
384      * Returns the initial `System.in` to determine if it is replaced
385      * with `System.setIn(newIn)` method
386      */
387     InputStream initialSystemIn();
388 
389     /**
390      * Encodes ASCII codepoints as possible from the source array into
391      * the destination byte array, assuming that the encoding is ASCII
392      * compatible
393      *
394      * @return the number of bytes successfully encoded, or 0 if none
395      */
396     int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len);
397 
398     /**
399      * Set the cause of Throwable
400      * @param cause set t's cause to new value
401      */
402     void setCause(Throwable t, Throwable cause);
403 
404     /**
405      * Get protection domain of the given Class
406      */
407     ProtectionDomain protectionDomain(Class<?> c);
408 
409     /**
410      * Get a method handle of string concat helper method
411      */
412     MethodHandle stringConcatHelper(String name, MethodType methodType);
413 
414     /**
415      * Get the string concat initial coder
416      */
417     long stringConcatInitialCoder();
418 
419     /**
420      * Update lengthCoder for constant
421      */
422     long stringConcatMix(long lengthCoder, String constant);
423 
424    /**
425     * Get the coder for the supplied character.
426     */
427    long stringConcatCoder(char value);
428 
429    /**
430     * Update lengthCoder for StringBuilder.
431     */
432    long stringBuilderConcatMix(long lengthCoder, StringBuilder sb);
433 
434     /**
435      * Prepend StringBuilder content.
436     */
437    long stringBuilderConcatPrepend(long lengthCoder, byte[] buf, StringBuilder sb);
438 
439     /**
440      * Join strings
441      */
442     String join(String prefix, String suffix, String delimiter, String[] elements, int size);
443 
444     /*
445      * Get the class data associated with the given class.
446      * @param c the class
447      * @see java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
448      */
449     Object classData(Class<?> c);
450 
451     long findNative(ClassLoader loader, String entry);
452 
453     /**
454      * Direct access to Shutdown.exit to avoid security manager checks
455      * @param statusCode the status code
456      */
457     void exit(int statusCode);
458 
459     /**
460      * Returns an array of all platform threads.
461      */
462     Thread[] getAllThreads();
463 
464     /**
465      * Returns the ThreadContainer for a thread, may be null.
466      */
467     ThreadContainer threadContainer(Thread thread);
468 
469     /**
470      * Starts a thread in the given ThreadContainer.
471      */
472     void start(Thread thread, ThreadContainer container);
473 
474     /**
475      * Returns the top of the given thread's stackable scope stack.
476      */
477     StackableScope headStackableScope(Thread thread);
478 
479     /**
480      * Sets the top of the current thread's stackable scope stack.
481      */
482     void setHeadStackableScope(StackableScope scope);
483 
484     /**
485      * Returns the Thread object for the current platform thread. If the
486      * current thread is a virtual thread then this method returns the carrier.
487      */
488     Thread currentCarrierThread();
489 
490     /**
491      * Executes the given value returning task on the current carrier thread.
492      */
493     <V> V executeOnCarrierThread(Callable<V> task) throws Exception;
494 
495     /**
496      * Returns the value of the current carrier thread's copy of a thread-local.
497      */
498     <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local);
499 
500     /**
501      * Sets the value of the current carrier thread's copy of a thread-local.
502      */
503     <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value);
504 
505     /**
506      * Removes the value of the current carrier thread's copy of a thread-local.
507      */
508     void removeCarrierThreadLocal(CarrierThreadLocal<?> local);
509 
510     /**
511      * Returns {@code true} if there is a value in the current carrier thread's copy of
512      * thread-local, even if that values is {@code null}.
513      */
514     boolean isCarrierThreadLocalPresent(CarrierThreadLocal<?> local);
515 
516     /**
517      * Returns the current thread's scoped values cache
518      */
519     Object[] scopedValueCache();
520 
521     /**
522      * Sets the current thread's scoped values cache
523      */
524     void setScopedValueCache(Object[] cache);
525 
526     /**
527      * Return the current thread's scoped value bindings.
528      */
529     Object scopedValueBindings();
530 
531     /**
532      * Returns the innermost mounted continuation
533      */
534     Continuation getContinuation(Thread thread);
535 
536     /**
537      * Sets the innermost mounted continuation
538      */
539     void setContinuation(Thread thread, Continuation continuation);
540 
541     /**
542      * The ContinuationScope of virtual thread continuations
543      */
544     ContinuationScope virtualThreadContinuationScope();
545 
546     /**
547      * Parks the current virtual thread.
548      * @throws WrongThreadException if the current thread is not a virtual thread
549      */
550     void parkVirtualThread();
551 
552     /**
553      * Parks the current virtual thread for up to the given waiting time.
554      * @param nanos the maximum number of nanoseconds to wait
555      * @throws WrongThreadException if the current thread is not a virtual thread
556      */
557     void parkVirtualThread(long nanos);
558 
559     /**
560      * Re-enables a virtual thread for scheduling. If the thread was parked then
561      * it will be unblocked, otherwise its next attempt to park will not block
562      * @param thread the virtual thread to unpark
563      * @throws IllegalArgumentException if the thread is not a virtual thread
564      * @throws RejectedExecutionException if the scheduler cannot accept a task
565      */
566     void unparkVirtualThread(Thread thread);
567 
568     /**
569      * Creates a new StackWalker
570      */
571     StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
572                                        ContinuationScope contScope,
573                                        Continuation continuation);
574     /**
575      * Returns '<loader-name>' @<id> if classloader has a name
576      * explicitly set otherwise <qualified-class-name> @<id>
577      */
578     String getLoaderNameID(ClassLoader loader);
579 
580     /**
581      * Copy the string bytes to an existing segment, avoiding intermediate copies.
582      */
583     void copyToSegmentRaw(String string, MemorySegment segment, long offset);
584 
585     /**
586      * Are the string bytes compatible with the given charset?
587      */
588     boolean bytesCompatible(String string, Charset charset);
589 }