1 /*
  2  * Copyright (c) 1997, 2021, 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 template <MEMFLAGS F> class HashtableBucket;
 74 class ResolutionErrorTable;
 75 class SymbolPropertyTable;
 76 class PackageEntry;
 77 class ProtectionDomainCacheTable;
 78 class ProtectionDomainCacheEntry;
 79 class GCTimer;
 80 class EventClassLoad;
 81 class Symbol;
 82 class TableStatistics;
 83 
 84 class SystemDictionary : AllStatic {
 85   friend class BootstrapInfo;
 86   friend class vmClasses;
 87   friend class VMStructs;
 88 
 89  public:
 90 
 91   // Returns a class with a given class name and class loader.  Loads the
 92   // class if needed. If not found a NoClassDefFoundError or a
 93   // ClassNotFoundException is thrown, depending on the value on the
 94   // throw_error flag.  For most uses the throw_error argument should be set
 95   // to true.
 96 
 97   static Klass* resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS);
 98   // Convenient call for null loader and protection domain.
 99   static Klass* resolve_or_fail(Symbol* class_name, bool throw_error, TRAPS) {
100     return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
101   }
102 
103   // Returns a class with a given class name and class loader.
104   // Loads the class if needed. If not found NULL is returned.
105   static Klass* resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS);
106   // Version with null loader and protection domain
107   static Klass* resolve_or_null(Symbol* class_name, TRAPS) {
108     return resolve_or_null(class_name, Handle(), Handle(), THREAD);
109   }
110 
111   // Resolve a superclass or superinterface. Called from ClassFileParser,
112   // parse_interfaces, resolve_instance_class_or_null, load_shared_class
113   // "class_name" is the class whose super class or interface is being resolved.
114   static InstanceKlass* resolve_super_or_fail(Symbol* class_name,
115                                               Symbol* super_name,
116                                               Handle class_loader,
117                                               Handle protection_domain,
118                                               bool is_superclass,
119                                               TRAPS);
120  private:
121   // Parse the stream to create a hidden class.
122   // Used by jvm_lookup_define_class.
123   static InstanceKlass* resolve_hidden_class_from_stream(ClassFileStream* st,
124                                                          Symbol* class_name,
125                                                          Handle class_loader,
126                                                          const ClassLoadInfo& cl_info,
127                                                          TRAPS);
128 
129   // Resolve a class from stream (called by jni_DefineClass and JVM_DefineClass)
130   // This class is added to the SystemDictionary.
131   static InstanceKlass* resolve_class_from_stream(ClassFileStream* st,
132                                                   Symbol* class_name,
133                                                   Handle class_loader,
134                                                   const ClassLoadInfo& cl_info,
135                                                   TRAPS);
136 
137  public:
138   // Resolve either a hidden or normal class from a stream of bytes, based on ClassLoadInfo
139   static InstanceKlass* resolve_from_stream(ClassFileStream* st,
140                                             Symbol* class_name,
141                                             Handle class_loader,
142                                             const ClassLoadInfo& cl_info,
143                                             TRAPS);
144 
145   // Lookup an already loaded class. If not found NULL is returned.
146   static InstanceKlass* find_instance_klass(Symbol* class_name, Handle class_loader, Handle protection_domain);
147 
148   // Lookup an already loaded instance or array class.
149   // Do not make any queries to class loaders; consult only the cache.
150   // If not found NULL is returned.
151   static Klass* find_instance_or_array_klass(Symbol* class_name,
152                                              Handle class_loader,
153                                              Handle protection_domain);
154 
155   // Lookup an instance or array class that has already been loaded
156   // either into the given class loader, or else into another class
157   // loader that is constrained (via loader constraints) to produce
158   // a consistent class.  Do not take protection domains into account.
159   // Do not make any queries to class loaders; consult only the cache.
160   // Return NULL if the class is not found.
161   //
162   // This function is a strict superset of find_instance_or_array_klass.
163   // This function (the unchecked version) makes a conservative prediction
164   // of the result of the checked version, assuming successful lookup.
165   // If both functions return non-null, they must return the same value.
166   // Also, the unchecked version may sometimes be non-null where the
167   // checked version is null.  This can occur in several ways:
168   //   1. No query has yet been made to the class loader.
169   //   2. The class loader was queried, but chose not to delegate.
170   //   3. ClassLoader.checkPackageAccess rejected a proposed protection domain.
171   //   4. Loading was attempted, but there was a linkage error of some sort.
172   // In all of these cases, the loader constraints on this type are
173   // satisfied, and it is safe for classes in the given class loader
174   // to manipulate strongly-typed values of the found class, subject
175   // to local linkage and access checks.
176   static Klass* find_constrained_instance_or_array_klass(Thread* current,
177                                                          Symbol* class_name,
178                                                          Handle class_loader);
179 
180   static void classes_do(MetaspaceClosure* it);
181   // Iterate over all methods in all klasses
182 
183   static void methods_do(void f(Method*));
184 
185   // Garbage collection support
186 
187   // Unload (that is, break root links to) all unmarked classes and
188   // loaders.  Returns "true" iff something was unloaded.
189   static bool do_unloading(GCTimer* gc_timer);
190 
191   // Protection Domain Table
192   static ProtectionDomainCacheTable* pd_cache_table() { return _pd_cache_table; }
193 
194   // Printing
195   static void print();
196   static void print_on(outputStream* st);
197   static void dump(outputStream* st, bool verbose);
198 
199   // Verification
200   static void verify();
201 
202   // Initialization
203   static void initialize(TRAPS);
204 
205 public:
206   // Returns java system loader
207   static oop java_system_loader();
208 
209   // Returns the class loader data to be used when looking up/updating the
210   // system dictionary.
211   static ClassLoaderData *class_loader_data(Handle class_loader);
212 
213   // Returns java platform loader
214   static oop java_platform_loader();
215 
216   // Compute the java system and platform loaders
217   static void compute_java_loaders(TRAPS);
218 
219   // Register a new class loader
220   static ClassLoaderData* register_loader(Handle class_loader, bool create_mirror_cld = false);
221 
222   static Symbol* check_signature_loaders(Symbol* signature, Klass* klass_being_linked,
223                                          Handle loader1, Handle loader2, bool is_method);
224 
225   // JSR 292
226   // find a java.lang.invoke.MethodHandle.invoke* method for a given signature
227   // (asks Java to compute it if necessary, except in a compiler thread)
228   static Method* find_method_handle_invoker(Klass* klass,
229                                             Symbol* name,
230                                             Symbol* signature,
231                                             Klass* accessing_klass,
232                                             Handle *appendix_result,
233                                             TRAPS);
234   // for a given signature, find the internal MethodHandle method (linkTo* or invokeBasic)
235   // (does not ask Java, since this is a low-level intrinsic defined by the JVM)
236   static Method* find_method_handle_intrinsic(vmIntrinsicID iid,
237                                               Symbol* signature,
238                                               TRAPS);
239 
240   // compute java_mirror (java.lang.Class instance) for a type ("I", "[[B", "LFoo;", etc.)
241   // Either the accessing_klass or the CL/PD can be non-null, but not both.
242   static Handle    find_java_mirror_for_type(Symbol* signature,
243                                              Klass* accessing_klass,
244                                              Handle class_loader,
245                                              Handle protection_domain,
246                                              SignatureStream::FailureMode failure_mode,
247                                              TRAPS);
248   static Handle    find_java_mirror_for_type(Symbol* signature,
249                                              Klass* accessing_klass,
250                                              SignatureStream::FailureMode failure_mode,
251                                              TRAPS) {
252     // callee will fill in CL/PD from AK, if they are needed
253     return find_java_mirror_for_type(signature, accessing_klass, Handle(), Handle(),
254                                      failure_mode, THREAD);
255   }
256 
257   // find a java.lang.invoke.MethodType object for a given signature
258   // (asks Java to compute it if necessary, except in a compiler thread)
259   static Handle    find_method_handle_type(Symbol* signature,
260                                            Klass* accessing_klass,
261                                            TRAPS);
262 
263   // find a java.lang.Class object for a given signature
264   static Handle    find_field_handle_type(Symbol* signature,
265                                           Klass* accessing_klass,
266                                           TRAPS);
267 
268   // ask Java to compute a java.lang.invoke.MethodHandle object for a given CP entry
269   static Handle    link_method_handle_constant(Klass* caller,
270                                                int ref_kind, //e.g., JVM_REF_invokeVirtual
271                                                Klass* callee,
272                                                Symbol* name,
273                                                Symbol* signature,
274                                                TRAPS);
275 
276   // ask Java to compute a constant by invoking a BSM given a Dynamic_info CP entry
277   static void      invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS);
278 
279   // Record the error when the first attempt to resolve a reference from a constant
280   // pool entry to a class fails.
281   static void add_resolution_error(const constantPoolHandle& pool, int which, Symbol* error,
282                                    Symbol* message, Symbol* cause = NULL, Symbol* cause_msg = NULL);
283   static void delete_resolution_error(ConstantPool* pool);
284   static Symbol* find_resolution_error(const constantPoolHandle& pool, int which,
285                                        Symbol** message, Symbol** cause, Symbol** cause_msg);
286 
287 
288   // Record a nest host resolution/validation error
289   static void add_nest_host_error(const constantPoolHandle& pool, int which,
290                                   const char* message);
291   static const char* find_nest_host_error(const constantPoolHandle& pool, int which);
292 
293  private:
294   // Static tables owned by the SystemDictionary
295 
296   // Resolution errors
297   static ResolutionErrorTable*   _resolution_errors;
298 
299   // Invoke methods (JSR 292)
300   static SymbolPropertyTable*    _invoke_method_table;
301 
302   // ProtectionDomain cache
303   static ProtectionDomainCacheTable*   _pd_cache_table;
304 
305 protected:
306   static InstanceKlass* _well_known_klasses[];
307 
308 private:
309   // table of box klasses (int_klass, etc.)
310   static InstanceKlass* _box_klasses[T_VOID+1];
311 
312   static OopHandle  _java_system_loader;
313   static OopHandle  _java_platform_loader;
314 
315   static ResolutionErrorTable* resolution_errors() { return _resolution_errors; }
316   static SymbolPropertyTable* invoke_method_table() { return _invoke_method_table; }
317 
318 private:
319   // Basic loading operations
320   static InstanceKlass* resolve_instance_class_or_null_helper(Symbol* name,
321                                                               Handle class_loader,
322                                                               Handle protection_domain,
323                                                               TRAPS);
324   static InstanceKlass* resolve_instance_class_or_null(Symbol* class_name,
325                                                        Handle class_loader,
326                                                        Handle protection_domain, TRAPS);
327   static Klass* resolve_array_class_or_null(Symbol* class_name,
328                                             Handle class_loader,
329                                             Handle protection_domain, TRAPS);
330   static InstanceKlass* handle_parallel_loading(JavaThread* current,
331                                                 unsigned int name_hash,
332                                                 Symbol* name,
333                                                 ClassLoaderData* loader_data,
334                                                 Handle lockObject,
335                                                 bool* throw_circularity_error);
336 
337   static void define_instance_class(InstanceKlass* k, Handle class_loader, TRAPS);
338   static InstanceKlass* find_or_define_helper(Symbol* class_name,
339                                               Handle class_loader,
340                                               InstanceKlass* k, TRAPS);
341   static InstanceKlass* load_instance_class_impl(Symbol* class_name, Handle class_loader, TRAPS);
342   static InstanceKlass* load_instance_class(unsigned int name_hash,
343                                             Symbol* class_name,
344                                             Handle class_loader, TRAPS);
345 
346   static bool is_shared_class_visible(Symbol* class_name, InstanceKlass* ik,
347                                       PackageEntry* pkg_entry,
348                                       Handle class_loader);
349   static bool is_shared_class_visible_impl(Symbol* class_name,
350                                            InstanceKlass* ik,
351                                            PackageEntry* pkg_entry,
352                                            Handle class_loader);
353   static bool check_shared_class_super_type(InstanceKlass* klass, InstanceKlass* super,
354                                             Handle class_loader,  Handle protection_domain,
355                                             bool is_superclass, TRAPS);
356   static bool check_shared_class_super_types(InstanceKlass* ik, Handle class_loader,
357                                                Handle protection_domain, TRAPS);
358   // Second part of load_shared_class
359   static void load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data) NOT_CDS_RETURN;
360 protected:
361   // Used by SystemDictionaryShared
362 
363   static bool add_loader_constraint(Symbol* name, Klass* klass_being_linked,  Handle loader1,
364                                     Handle loader2);
365   static void post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld);
366   static InstanceKlass* load_shared_lambda_proxy_class(InstanceKlass* ik,
367                                                        Handle class_loader,
368                                                        Handle protection_domain,
369                                                        PackageEntry* pkg_entry,
370                                                        TRAPS);
371   static InstanceKlass* load_shared_class(InstanceKlass* ik,
372                                           Handle class_loader,
373                                           Handle protection_domain,
374                                           const ClassFileStream *cfs,
375                                           PackageEntry* pkg_entry,
376                                           TRAPS);
377   static Handle get_loader_lock_or_null(Handle class_loader);
378   static InstanceKlass* find_or_define_instance_class(Symbol* class_name,
379                                                       Handle class_loader,
380                                                       InstanceKlass* k, TRAPS);
381 public:
382   static bool is_system_class_loader(oop class_loader);
383   static bool is_platform_class_loader(oop class_loader);
384   static bool is_boot_class_loader(oop class_loader) { return class_loader == NULL; }
385   static bool is_builtin_class_loader(oop class_loader) {
386     return is_boot_class_loader(class_loader)      ||
387            is_platform_class_loader(class_loader)  ||
388            is_system_class_loader(class_loader);
389   }
390   // Returns TRUE if the method is a non-public member of class java.lang.Object.
391   static bool is_nonpublic_Object_method(Method* m);
392 
393   // Return Symbol or throw exception if name given is can not be a valid Symbol.
394   static Symbol* class_name_symbol(const char* name, Symbol* exception, TRAPS);
395 
396   // Setup link to hierarchy
397   static void add_to_hierarchy(InstanceKlass* k);
398 protected:
399 
400   // Basic find on loaded classes
401   static InstanceKlass* find_class(Symbol* class_name, ClassLoaderData* loader_data);
402 
403   // Basic find on classes in the midst of being loaded
404   static Symbol* find_placeholder(Symbol* name, ClassLoaderData* loader_data);
405 
406   // Class loader constraints
407   static void check_constraints(unsigned int hash,
408                                 InstanceKlass* k, Handle loader,
409                                 bool defining, TRAPS);
410   static void update_dictionary(unsigned int hash,
411                                 InstanceKlass* k, Handle loader);
412 
413 public:
414   static TableStatistics placeholders_statistics();
415   static TableStatistics loader_constraints_statistics();
416   static TableStatistics protection_domain_cache_statistics();
417 };
418 
419 #endif // SHARE_CLASSFILE_SYSTEMDICTIONARY_HPP