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.invoke.MethodHandle;
 31 import java.lang.invoke.MethodType;
 32 import java.lang.module.ModuleDescriptor;
 33 import java.lang.reflect.ClassFileFormatVersion;
 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.javac.PreviewFeature;
 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 the constant pool for a class.
 71      */
 72     ConstantPool getConstantPool(Class<?> klass);
 73 
 74     /**
 75      * Compare-And-Set the AnnotationType instance corresponding to this class.
 76      * (This method only applies to annotation types.)
 77      */
 78     boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType);
 79 
 80     /**
 81      * Get the AnnotationType instance corresponding to this class.
 82      * (This method only applies to annotation types.)
 83      */
 84     AnnotationType getAnnotationType(Class<?> klass);
 85 
 86     /**
 87      * Get the declared annotations for a given class, indexed by their types.
 88      */
 89     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass);
 90 
 91     /**
 92      * Get the array of bytes that is the class-file representation
 93      * of this Class' annotations.
 94      */
 95     byte[] getRawClassAnnotations(Class<?> klass);
 96 
 97     /**
 98      * Get the array of bytes that is the class-file representation
 99      * of this Class' type annotations.
100      */
101     byte[] getRawClassTypeAnnotations(Class<?> klass);
102 
103     /**
104      * Get the array of bytes that is the class-file representation
105      * of this Executable's type annotations.
106      */
107     byte[] getRawExecutableTypeAnnotations(Executable executable);
108 
109     /**
110      * Returns the elements of an enum class or null if the
111      * Class object does not represent an enum type;
112      * the result is uncloned, cached, and shared by all callers.
113      */
114     <E extends Enum<E>> E[] getEnumConstantsShared(Class<E> klass);
115 
116     /**
117      * Set current thread's blocker field.
118      */
119     void blockedOn(Interruptible b);
120 
121     /**
122      * Registers a shutdown hook.
123      *
124      * It is expected that this method with registerShutdownInProgress=true
125      * is only used to register DeleteOnExitHook since the first file
126      * may be added to the delete on exit list by the application shutdown
127      * hooks.
128      *
129      * @param slot  the slot in the shutdown hook array, whose element
130      *              will be invoked in order during shutdown
131      * @param registerShutdownInProgress true to allow the hook
132      *        to be registered even if the shutdown is in progress.
133      * @param hook  the hook to be registered
134      *
135      * @throws IllegalStateException if shutdown is in progress and
136      *         the slot is not valid to register.
137      */
138     void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook);
139 
140     /**
141      * Returns a new Thread with the given Runnable and an
142      * inherited AccessControlContext.
143      */
144     Thread newThreadWithAcc(Runnable target, @SuppressWarnings("removal") AccessControlContext acc);
145 
146     /**
147      * Invokes the finalize method of the given object.
148      */
149     void invokeFinalize(Object o) throws Throwable;
150 
151     /**
152      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
153      * associated with the given class loader, creating it if it doesn't already exist.
154      */
155     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl);
156 
157     /**
158      * Defines a class with the given name to a class loader.
159      */
160     Class<?> defineClass(ClassLoader cl, String name, byte[] b, ProtectionDomain pd, String source);
161 
162     /**
163      * Defines a class with the given name to a class loader with
164      * the given flags and class data.
165      *
166      * @see java.lang.invoke.MethodHandles.Lookup#defineClass
167      */
168     Class<?> defineClass(ClassLoader cl, Class<?> lookup, String name, byte[] b, ProtectionDomain pd, boolean initialize, int flags, Object classData);
169 
170     /**
171      * Returns a class loaded by the bootstrap class loader.
172      */
173     Class<?> findBootstrapClassOrNull(String name);
174 
175     /**
176      * Define a Package of the given name and module by the given class loader.
177      */
178     Package definePackage(ClassLoader cl, String name, Module module);
179 
180     /**
181      * Invokes Long.fastUUID
182      */
183     String fastUUID(long lsb, long msb);
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 all unnamed modules to allow access to restricted methods.
275      */
276     void addEnableNativeAccessToAllUnnamed();
277 
278     /**
279      * Ensure that the given module has native access. If not, warn or
280      * throw exception depending on the configuration.
281      */
282     void ensureNativeAccess(Module m, Class<?> owner, String methodName);
283 
284     /**
285      * Returns the ServicesCatalog for the given Layer.
286      */
287     ServicesCatalog getServicesCatalog(ModuleLayer layer);
288 
289     /**
290      * Record that this layer has at least one module defined to the given
291      * class loader.
292      */
293     void bindToLoader(ModuleLayer layer, ClassLoader loader);
294 
295     /**
296      * Returns an ordered stream of layers. The first element is the
297      * given layer, the remaining elements are its parents, in DFS order.
298      */
299     Stream<ModuleLayer> layers(ModuleLayer layer);
300 
301     /**
302      * Returns a stream of the layers that have modules defined to the
303      * given class loader.
304      */
305     Stream<ModuleLayer> layers(ClassLoader loader);
306 
307     /**
308      * Count the number of leading positive bytes in the range.
309      */
310     int countPositives(byte[] ba, int off, int len);
311 
312     /**
313      * Constructs a new {@code String} by decoding the specified subarray of
314      * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
315      *
316      * The caller of this method shall relinquish and transfer the ownership of
317      * the byte array to the callee since the later will not make a copy.
318      *
319      * @param bytes the byte array source
320      * @param cs the Charset
321      * @return the newly created string
322      * @throws CharacterCodingException for malformed or unmappable bytes
323      */
324     String newStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException;
325 
326     /**
327      * Encode the given string into a sequence of bytes using the specified Charset.
328      *
329      * This method avoids copying the String's internal representation if the input
330      * is ASCII.
331      *
332      * This method throws CharacterCodingException instead of replacing when
333      * malformed input or unmappable characters are encountered.
334      *
335      * @param s the string to encode
336      * @param cs the charset
337      * @return the encoded bytes
338      * @throws CharacterCodingException for malformed input or unmappable characters
339      */
340     byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException;
341 
342     /**
343      * Returns a new string by decoding from the given utf8 bytes array.
344      *
345      * @param off the index of the first byte to decode
346      * @param len the number of bytes to decode
347      * @return the newly created string
348      * @throws IllegalArgumentException for malformed or unmappable bytes.
349      */
350     String newStringUTF8NoRepl(byte[] bytes, int off, int len);
351 
352     /**
353      * Get the char at index in a byte[] in internal UTF-16 representation,
354      * with no bounds checks.
355      *
356      * @param bytes the UTF-16 encoded bytes
357      * @param index of the char to retrieve, 0 <= index < (bytes.length >> 1)
358      * @return the char value
359      */
360     char getUTF16Char(byte[] bytes, int index);
361 
362     /**
363      * Encode the given string into a sequence of bytes using utf8.
364      *
365      * @param s the string to encode
366      * @return the encoded bytes in utf8
367      * @throws IllegalArgumentException for malformed surrogates
368      */
369     byte[] getBytesUTF8NoRepl(String s);
370 
371     /**
372      * Inflated copy from byte[] to char[], as defined by StringLatin1.inflate
373      */
374     void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len);
375 
376     /**
377      * Decodes ASCII from the source byte array into the destination
378      * char array.
379      *
380      * @return the number of bytes successfully decoded, at most len
381      */
382     int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len);
383 
384     /**
385      * Returns the initial `System.in` to determine if it is replaced
386      * with `System.setIn(newIn)` method
387      */
388     InputStream initialSystemIn();
389 
390     /**
391      * Encodes ASCII codepoints as possible from the source array into
392      * the destination byte array, assuming that the encoding is ASCII
393      * compatible
394      *
395      * @return the number of bytes successfully encoded, or 0 if none
396      */
397     int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len);
398 
399     /**
400      * Set the cause of Throwable
401      * @param cause set t's cause to new value
402      */
403     void setCause(Throwable t, Throwable cause);
404 
405     /**
406      * Get protection domain of the given Class
407      */
408     ProtectionDomain protectionDomain(Class<?> c);
409 
410     /**
411      * Get a method handle of string concat helper method
412      */
413     MethodHandle stringConcatHelper(String name, MethodType methodType);
414 
415     /**
416      * Get the string concat initial coder
417      */
418     long stringConcatInitialCoder();
419 
420     /**
421      * Update lengthCoder for constant
422      */
423     long stringConcatMix(long lengthCoder, String constant);
424 
425    /**
426     * Get the coder for the supplied character.
427     */
428    @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
429    long stringConcatCoder(char value);
430 
431    /**
432     * Update lengthCoder for StringBuilder.
433     */
434    @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
435    long stringBuilderConcatMix(long lengthCoder, StringBuilder sb);
436 
437     /**
438      * Prepend StringBuilder content.
439      */
440     @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES)
441    long stringBuilderConcatPrepend(long lengthCoder, byte[] buf, StringBuilder sb);
442 
443     /**
444      * Join strings
445      */
446     String join(String prefix, String suffix, String delimiter, String[] elements, int size);
447 
448     /*
449      * Get the class data associated with the given class.
450      * @param c the class
451      * @see java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
452      */
453     Object classData(Class<?> c);
454 
455     long findNative(ClassLoader loader, String entry);
456 
457     /**
458      * Direct access to Shutdown.exit to avoid security manager checks
459      * @param statusCode the status code
460      */
461     void exit(int statusCode);
462 
463     /**
464      * Returns an array of all platform threads.
465      */
466     Thread[] getAllThreads();
467 
468     /**
469      * Returns the ThreadContainer for a thread, may be null.
470      */
471     ThreadContainer threadContainer(Thread thread);
472 
473     /**
474      * Starts a thread in the given ThreadContainer.
475      */
476     void start(Thread thread, ThreadContainer container);
477 
478     /**
479      * Returns the top of the given thread's stackable scope stack.
480      */
481     StackableScope headStackableScope(Thread thread);
482 
483     /**
484      * Sets the top of the current thread's stackable scope stack.
485      */
486     void setHeadStackableScope(StackableScope scope);
487 
488     /**
489      * Returns the Thread object for the current platform thread. If the
490      * current thread is a virtual thread then this method returns the carrier.
491      */
492     Thread currentCarrierThread();
493 
494     /**
495      * Executes the given value returning task on the current carrier thread.
496      */
497     <V> V executeOnCarrierThread(Callable<V> task) throws Exception;
498 
499     /**
500      * Returns the value of the current carrier thread's copy of a thread-local.
501      */
502     <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local);
503 
504     /**
505      * Sets the value of the current carrier thread's copy of a thread-local.
506      */
507     <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value);
508 
509     /**
510      * Removes the value of the current carrier thread's copy of a thread-local.
511      */
512     void removeCarrierThreadLocal(CarrierThreadLocal<?> local);
513 
514     /**
515      * Returns {@code true} if there is a value in the current carrier thread's copy of
516      * thread-local, even if that values is {@code null}.
517      */
518     boolean isCarrierThreadLocalPresent(CarrierThreadLocal<?> local);
519 
520     /**
521      * Returns the current thread's scoped values cache
522      */
523     Object[] scopedValueCache();
524 
525     /**
526      * Sets the current thread's scoped values cache
527      */
528     void setScopedValueCache(Object[] cache);
529 
530     /**
531      * Return the current thread's scoped value bindings.
532      */
533     Object scopedValueBindings();
534 
535     /**
536      * Set the current thread's scoped value bindings.
537      */
538     void setScopedValueBindings(Object bindings);
539 
540     Object findScopedValueBindings();
541 
542     void ensureMaterializedForStackWalk(Object value);
543 
544     /**
545      * Returns the innermost mounted continuation
546      */
547     Continuation getContinuation(Thread thread);
548 
549     /**
550      * Sets the innermost mounted continuation
551      */
552     void setContinuation(Thread thread, Continuation continuation);
553 
554     /**
555      * The ContinuationScope of virtual thread continuations
556      */
557     ContinuationScope virtualThreadContinuationScope();
558 
559     /**
560      * Parks the current virtual thread.
561      * @throws WrongThreadException if the current thread is not a virtual thread
562      */
563     void parkVirtualThread();
564 
565     /**
566      * Parks the current virtual thread for up to the given waiting time.
567      * @param nanos the maximum number of nanoseconds to wait
568      * @throws WrongThreadException if the current thread is not a virtual thread
569      */
570     void parkVirtualThread(long nanos);
571 
572     /**
573      * Re-enables a virtual thread for scheduling. If the thread was parked then
574      * it will be unblocked, otherwise its next attempt to park will not block
575      * @param thread the virtual thread to unpark
576      * @throws IllegalArgumentException if the thread is not a virtual thread
577      * @throws RejectedExecutionException if the scheduler cannot accept a task
578      */
579     void unparkVirtualThread(Thread thread);
580 
581     /**
582      * Creates a new StackWalker
583      */
584     StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
585                                        ContinuationScope contScope,
586                                        Continuation continuation);
587 
588     /**
589      * {@return the primary class for a primitive class}
590      *
591      * @param klass a class
592      */
593     Class<?> asPrimaryType(Class<?> klass);
594 
595     /**
596      * {@return the value type of a primitive class}
597      *
598      * @param klass a class
599      */
600     Class<?> asValueType(Class<?> klass);
601 
602     /**
603      * {@return true if the class is the primary type of a primitive class}
604      *
605      * @param klass a class
606      */
607     boolean isPrimaryType(Class<?> klass);
608 
609     /**
610      * {@return true if the class is the primary type of a primitive class}
611      *
612      * @param klass a class
613      */
614     boolean isPrimitiveValueType(Class<?> klass);
615 
616     /**
617      * Returns {@code true} if this class is a primitive class.
618      */
619     boolean isPrimitiveClass(Class<?> klass);
620 
621     /**
622      * Returns the class file format version of the class.
623      */
624     int classFileFormatVersion(Class<?> klass);
625 
626     /**
627      * Returns '<loader-name>' @<id> if classloader has a name
628      * explicitly set otherwise <qualified-class-name> @<id>
629      */
630     String getLoaderNameID(ClassLoader loader);
631 }