1 /*
  2  * Copyright (c) 1997, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_CLASSFILE_SYSTEMDICTIONARY_HPP
 26 #define SHARE_CLASSFILE_SYSTEMDICTIONARY_HPP
 27 
 28 #include "oops/oopHandle.hpp"
 29 #include "runtime/handles.hpp"
 30 #include "runtime/signature.hpp"
 31 #include "utilities/vmEnums.hpp"
 32 
 33 // The dictionary in each ClassLoaderData stores all loaded classes, either
 34 // initiatied by its class loader or defined by its class loader:
 35 //
 36 //   class loader -> ClassLoaderData -> [class, protection domain set]
 37 //
 38 // Classes are loaded lazily. The default VM class loader is
 39 // represented as null.
 40 
 41 // The underlying data structure is an open hash table (Dictionary) per
 42 // ClassLoaderData with a fixed number of buckets. During loading the
 43 // class loader object is locked, (for the VM loader a private lock object is used).
 44 // The global SystemDictionary_lock is held for all additions into the ClassLoaderData
 45 // dictionaries.  TODO: fix lock granularity so that class loading can
 46 // be done concurrently, but only by different loaders.
 47 //
 48 // During loading a placeholder (name, loader) is temporarily placed in
 49 // a side data structure, and is used to detect ClassCircularityErrors.
 50 //
 51 // When class loading is finished, a new entry is added to the dictionary
 52 // of the class loader and the placeholder is removed. Note that the protection
 53 // domain field of the dictionary entry has not yet been filled in when
 54 // the "real" dictionary entry is created.
 55 //
 56 // Clients of this class who are interested in finding if a class has
 57 // been completely loaded -- not classes in the process of being loaded --
 58 // can read the dictionary unlocked. This is safe because
 59 //    - entries are only deleted when the class loader is not alive, when the
 60 //      entire dictionary is deleted.
 61 //    - entries must be fully formed before they are available to concurrent
 62 //         readers (we must ensure write ordering)
 63 //
 64 // Note that placeholders are deleted at any time, as they are removed
 65 // when a class is completely loaded. Therefore, readers as well as writers
 66 // of placeholders must hold the SystemDictionary_lock.
 67 //
 68 
 69 class BootstrapInfo;
 70 class ClassFileStream;
 71 class ClassLoadInfo;
 72 class Dictionary;
 73 class PackageEntry;
 74 class GCTimer;
 75 class EventClassLoad;
 76 class Symbol;
 77 
 78 template <class E> class GrowableArray;
 79 
 80 class SystemDictionary : AllStatic {
 81   friend class AOTLinkedClassBulkLoader;
 82   friend class BootstrapInfo;
 83   friend class vmClasses;
 84   friend class VMStructs;
 85 
 86  public:
 87 
 88   // Returns a class with a given class name and class loader.  Loads the
 89   // class if needed. If not found a NoClassDefFoundError or a
 90   // ClassNotFoundException is thrown, depending on the value on the
 91   // throw_error flag.  For most uses the throw_error argument should be set
 92   // to true.
 93 
 94   static Klass* resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS);
 95   // Convenient call for null loader and protection domain.
 96   static Klass* resolve_or_fail(Symbol* class_name, bool throw_error, TRAPS) {
 97     return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
 98   }
 99 
100   // Returns a class with a given class name and class loader.
101   // Loads the class if needed. If not found null is returned.
102   static Klass* resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS);
103   // Version with null loader and protection domain
104   static Klass* resolve_or_null(Symbol* class_name, TRAPS) {
105     return resolve_or_null(class_name, Handle(), Handle(), THREAD);
106   }
107 
108   static InstanceKlass* resolve_with_circularity_detection(Symbol* class_name,
109                                                            Symbol* next_name,
110                                                            Handle class_loader,
111                                                            Handle protection_domain,
112                                                            bool is_superclass,
113                                                            TRAPS);
114 
115   // Resolve a superclass or superinterface. Called from ClassFileParser,
116   // parse_interfaces, resolve_instance_class_or_null, load_shared_class
117   // "class_name" is the class whose super class or interface is being resolved.
118   static InstanceKlass* resolve_super_or_fail(Symbol* class_name, Symbol* super_name,
119                                               Handle class_loader,
120                                               Handle protection_domain, bool is_superclass, TRAPS) {
121     return resolve_with_circularity_detection(class_name, super_name, class_loader, protection_domain,
122                                               is_superclass, THREAD);
123   }
124 
125  private:
126   // Parse the stream to create a hidden class.
127   // Used by jvm_lookup_define_class.
128   static InstanceKlass* resolve_hidden_class_from_stream(ClassFileStream* st,
129                                                          Symbol* class_name,
130                                                          Handle class_loader,
131                                                          const ClassLoadInfo& cl_info,
132                                                          TRAPS);
133 
134   // Resolve a class from stream (called by jni_DefineClass and JVM_DefineClass)
135   // This class is added to the SystemDictionary.
136   static InstanceKlass* resolve_class_from_stream(ClassFileStream* st,
137                                                   Symbol* class_name,
138                                                   Handle class_loader,
139                                                   const ClassLoadInfo& cl_info,
140                                                   TRAPS);
141 
142   static oop get_system_class_loader_impl(TRAPS);
143   static oop get_platform_class_loader_impl(TRAPS);
144 
145  public:
146   // Resolve either a hidden or normal class from a stream of bytes, based on ClassLoadInfo
147   static InstanceKlass* resolve_from_stream(ClassFileStream* st,
148                                             Symbol* class_name,
149                                             Handle class_loader,
150                                             const ClassLoadInfo& cl_info,
151                                             TRAPS);
152 
153   // Lookup an already loaded class. If not found null is returned.
154   static InstanceKlass* find_instance_klass(Thread* current, Symbol* class_name,
155                                             Handle class_loader, Handle protection_domain);
156 
157   // Lookup an already loaded instance or array class.
158   // Do not make any queries to class loaders; consult only the cache.
159   // If not found null is returned.
160   static Klass* find_instance_or_array_klass(Thread* current, Symbol* class_name,
161                                              Handle class_loader,
162                                              Handle protection_domain);
163 
164   // Lookup an instance or array class that has already been loaded
165   // either into the given class loader, or else into another class
166   // loader that is constrained (via loader constraints) to produce
167   // a consistent class.  Do not take protection domains into account.
168   // Do not make any queries to class loaders; consult only the cache.
169   // Return null if the class is not found.
170   //
171   // This function is a strict superset of find_instance_or_array_klass.
172   // This function (the unchecked version) makes a conservative prediction
173   // of the result of the checked version, assuming successful lookup.
174   // If both functions return non-null, they must return the same value.
175   // Also, the unchecked version may sometimes be non-null where the
176   // checked version is null.  This can occur in several ways:
177   //   1. No query has yet been made to the class loader.
178   //   2. The class loader was queried, but chose not to delegate.
179   //   3. ClassLoader.checkPackageAccess rejected a proposed protection domain.
180   //   4. Loading was attempted, but there was a linkage error of some sort.
181   // In all of these cases, the loader constraints on this type are
182   // satisfied, and it is safe for classes in the given class loader
183   // to manipulate strongly-typed values of the found class, subject
184   // to local linkage and access checks.
185   static Klass* find_constrained_instance_or_array_klass(Thread* current,
186                                                          Symbol* class_name,
187                                                          Handle class_loader);
188 
189   static void classes_do(MetaspaceClosure* it);
190   // Iterate over all methods in all klasses
191   // Will not keep metadata alive. See ClassLoaderDataGraph::methods_do.
192   static void methods_do(void f(Method*));
193 
194   // Garbage collection support
195 
196   // Unload (that is, break root links to) all unmarked classes and
197   // loaders.  Returns "true" iff something was unloaded.
198   static bool do_unloading(GCTimer* gc_timer);
199 
200   // Printing
201   static void print();
202   static void print_on(outputStream* st);
203   static void dump(outputStream* st, bool verbose);
204 
205   // Verification
206   static void verify();
207 
208   // Initialization
209   static void initialize(TRAPS);
210 
211 public:
212   // Returns java system loader
213   static oop java_system_loader();
214 
215   // Returns java platform loader
216   static oop java_platform_loader();
217 
218   // Compute the java system and platform loaders
219   static void compute_java_loaders(TRAPS);
220 
221   // Register a new class loader
222   static ClassLoaderData* register_loader(Handle class_loader, bool create_mirror_cld = false);
223 
224   static void set_system_loader(ClassLoaderData *cld);
225   static void set_platform_loader(ClassLoaderData *cld);
226 
227   static Symbol* check_signature_loaders(Symbol* signature, Klass* klass_being_linked,
228                                          Handle loader1, Handle loader2, bool is_method);
229 
230   // JSR 292
231   // find a java.lang.invoke.MethodHandle.invoke* method for a given signature
232   // (asks Java to compute it if necessary, except in a compiler thread)
233   static Method* find_method_handle_invoker(Klass* klass,
234                                             Symbol* name,
235                                             Symbol* signature,
236                                             Klass* accessing_klass,
237                                             Handle *appendix_result,
238                                             TRAPS);
239   // for a given signature, find the internal MethodHandle method (linkTo* or invokeBasic)
240   // (does not ask Java, since this is a low-level intrinsic defined by the JVM)
241   static Method* find_method_handle_intrinsic(vmIntrinsicID iid,
242                                               Symbol* signature,
243                                               TRAPS);
244 
245   static void get_all_method_handle_intrinsics(GrowableArray<Method*>* methods) NOT_CDS_RETURN;
246   static void restore_archived_method_handle_intrinsics() NOT_CDS_RETURN;
247 
248   // compute java_mirror (java.lang.Class instance) for a type ("I", "[[B", "LFoo;", etc.)
249   // Either the accessing_klass or the CL/PD can be non-null, but not both.
250   static Handle    find_java_mirror_for_type(Symbol* signature,
251                                              Klass* accessing_klass,
252                                              Handle class_loader,
253                                              Handle protection_domain,
254                                              SignatureStream::FailureMode failure_mode,
255                                              TRAPS);
256   static Handle    find_java_mirror_for_type(Symbol* signature,
257                                              Klass* accessing_klass,
258                                              SignatureStream::FailureMode failure_mode,
259                                              TRAPS) {
260     // callee will fill in CL/PD from AK, if they are needed
261     return find_java_mirror_for_type(signature, accessing_klass, Handle(), Handle(),
262                                      failure_mode, THREAD);
263   }
264 
265   // find a java.lang.invoke.MethodType object for a given signature
266   // (asks Java to compute it if necessary, except in a compiler thread)
267   static Handle    find_method_handle_type(Symbol* signature,
268                                            Klass* accessing_klass,
269                                            TRAPS);
270 
271   // find a java.lang.Class object for a given signature
272   static Handle    find_field_handle_type(Symbol* signature,
273                                           Klass* accessing_klass,
274                                           TRAPS);
275 
276   // ask Java to compute a java.lang.invoke.MethodHandle object for a given CP entry
277   static Handle    link_method_handle_constant(Klass* caller,
278                                                int ref_kind, //e.g., JVM_REF_invokeVirtual
279                                                Klass* callee,
280                                                Symbol* name,
281                                                Symbol* signature,
282                                                TRAPS);
283 
284   // ask Java to compute a constant by invoking a BSM given a Dynamic_info CP entry
285   static void      invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS);
286 
287   // Record the error when the first attempt to resolve a reference from a constant
288   // pool entry to a class fails.
289   static void add_resolution_error(const constantPoolHandle& pool, int which,
290                                    Symbol* error, const char* message,
291                                    Symbol* cause = nullptr, const char* cause_msg = nullptr);
292   static void delete_resolution_error(ConstantPool* pool);
293   static Symbol* find_resolution_error(const constantPoolHandle& pool, int which,
294                                        const char** message,
295                                        Symbol** cause, const char** cause_msg);
296 
297   // Record a nest host resolution/validation error
298   static void add_nest_host_error(const constantPoolHandle& pool, int which,
299                                   const char* message);
300   static const char* find_nest_host_error(const constantPoolHandle& pool, int which);
301 
302   static void add_to_initiating_loader(JavaThread* current, InstanceKlass* k,
303                                        ClassLoaderData* loader_data) NOT_CDS_RETURN;
304 protected:
305   static InstanceKlass* _well_known_klasses[];
306 
307 private:
308   // table of box klasses (int_klass, etc.)
309   static InstanceKlass* _box_klasses[T_VOID+1];
310 
311   static OopHandle  _java_system_loader;
312   static OopHandle  _java_platform_loader;
313 
314 private:
315   // Basic loading operations
316   static InstanceKlass* resolve_instance_class_or_null(Symbol* class_name,
317                                                        Handle class_loader,
318                                                        Handle protection_domain, TRAPS);
319   static Klass* resolve_array_class_or_null(Symbol* class_name,
320                                             Handle class_loader,
321                                             Handle protection_domain, TRAPS);
322   static void define_instance_class(InstanceKlass* k, Handle class_loader, TRAPS);
323   static InstanceKlass* find_or_define_helper(Symbol* class_name,
324                                               Handle class_loader,
325                                               InstanceKlass* k, TRAPS);
326   static InstanceKlass* load_instance_class_impl(Symbol* class_name, Handle class_loader, TRAPS);
327   static InstanceKlass* load_instance_class(Symbol* class_name,
328                                             Handle class_loader, TRAPS);
329 
330   // Class loader constraints
331   static void check_constraints(InstanceKlass* k, ClassLoaderData* loader,
332                                 bool defining, TRAPS);
333   static void update_dictionary(JavaThread* current, InstanceKlass* k, ClassLoaderData* loader_data);
334 
335   static bool is_shared_class_visible(Symbol* class_name, InstanceKlass* ik,
336                                       PackageEntry* pkg_entry,
337                                       Handle class_loader);
338   static bool is_shared_class_visible_impl(Symbol* class_name,
339                                            InstanceKlass* ik,
340                                            PackageEntry* pkg_entry,
341                                            Handle class_loader);
342   static bool check_shared_class_super_type(InstanceKlass* klass, InstanceKlass* super,
343                                             Handle class_loader,  Handle protection_domain,
344                                             bool is_superclass, TRAPS);
345   static bool check_shared_class_super_types(InstanceKlass* ik, Handle class_loader,
346                                                Handle protection_domain, TRAPS);
347   static void restore_archived_method_handle_intrinsics_impl(TRAPS);
348 
349 protected:
350   // Used by SystemDictionaryShared
351 
352   // Second part of load_shared_class
353   static void load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data) NOT_CDS_RETURN;
354 
355   static bool add_loader_constraint(Symbol* name, Klass* klass_being_linked,  Handle loader1,
356                                     Handle loader2);
357   static void post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld);
358   static InstanceKlass* load_shared_lambda_proxy_class(InstanceKlass* ik,
359                                                        Handle class_loader,
360                                                        Handle protection_domain,
361                                                        PackageEntry* pkg_entry,
362                                                        TRAPS);
363   static InstanceKlass* load_shared_class(InstanceKlass* ik,
364                                           Handle class_loader,
365                                           Handle protection_domain,
366                                           const ClassFileStream *cfs,
367                                           PackageEntry* pkg_entry,
368                                           TRAPS);
369   static Handle get_loader_lock_or_null(Handle class_loader);
370   static InstanceKlass* find_or_define_instance_class(Symbol* class_name,
371                                                       Handle class_loader,
372                                                       InstanceKlass* k, TRAPS);
373 public:
374   static bool is_system_class_loader(oop class_loader);
375   static bool is_platform_class_loader(oop class_loader);
376   static bool is_boot_class_loader(oop class_loader) { return class_loader == nullptr; }
377   static bool is_builtin_class_loader(oop class_loader) {
378     return is_boot_class_loader(class_loader)      ||
379            is_platform_class_loader(class_loader)  ||
380            is_system_class_loader(class_loader);
381   }
382   // Returns TRUE if the method is a non-public member of class java.lang.Object.
383   static bool is_nonpublic_Object_method(Method* m);
384 
385   // Return Symbol or throw exception if name given is can not be a valid Symbol.
386   static Symbol* class_name_symbol(const char* name, Symbol* exception, TRAPS);
387 };
388 
389 #endif // SHARE_CLASSFILE_SYSTEMDICTIONARY_HPP