1 /*
  2  * Copyright (c) 2014, 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_SYSTEMDICTIONARYSHARED_HPP
 26 #define SHARE_CLASSFILE_SYSTEMDICTIONARYSHARED_HPP
 27 
 28 #include "cds/cds_globals.hpp"
 29 #include "cds/filemap.hpp"
 30 #include "cds/dumpTimeClassInfo.hpp"
 31 #include "cds/lambdaProxyClassDictionary.hpp"
 32 #include "cds/runTimeClassInfo.hpp"
 33 #include "classfile/classLoaderData.hpp"
 34 #include "classfile/packageEntry.hpp"
 35 #include "classfile/systemDictionary.hpp"
 36 #include "oops/klass.hpp"
 37 #include "oops/oopHandle.hpp"
 38 #include "oops/trainingData.hpp"
 39 
 40 
 41 /*===============================================================================
 42 
 43     Handling of the classes in the AppCDS archive
 44 
 45     To ensure safety and to simplify the implementation, archived classes are
 46     "segregated" into 2 types. The following rules describe how they
 47     are stored and looked up.
 48 
 49 [1] Category of archived classes
 50 
 51     There are 2 disjoint groups of classes stored in the AppCDS archive:
 52 
 53     BUILTIN:              These classes may be defined ONLY by the BOOT/PLATFORM/APP
 54                           loaders.
 55 
 56     UNREGISTERED:         These classes may be defined ONLY by a ClassLoader
 57                           instance that's not listed above (using fingerprint matching)
 58 
 59 [2] How classes from different categories are specified in the classlist:
 60 
 61     Starting from JDK9, each class in the classlist may be specified with
 62     these keywords: "id", "super", "interfaces", "loader" and "source".
 63 
 64 
 65     BUILTIN               Only the "id" keyword may be (optionally) specified. All other
 66                           keywords are forbidden.
 67 
 68                           The named class is looked up from the jimage and from
 69                           Xbootclasspath/a and CLASSPATH.
 70 
 71     UNREGISTERED:         The "id", "super", and "source" keywords must all be
 72                           specified.
 73 
 74                           The "interfaces" keyword must be specified if the class implements
 75                           one or more local interfaces. The "interfaces" keyword must not be
 76                           specified if the class does not implement local interfaces.
 77 
 78                           The named class is looked up from the location specified in the
 79                           "source" keyword.
 80 
 81     Example classlist:
 82 
 83     # BUILTIN
 84     java/lang/Object id: 0
 85     java/lang/Cloneable id: 1
 86     java/lang/String
 87 
 88     # UNREGISTERED
 89     Bar id: 3 super: 0 interfaces: 1 source: /foo.jar
 90 
 91 
 92 [3] Identifying the category of archived classes
 93 
 94     BUILTIN:              (C->shared_classpath_index() >= 0)
 95     UNREGISTERED:         (C->shared_classpath_index() == UNREGISTERED_INDEX (-9999))
 96 
 97 [4] Lookup of archived classes at run time:
 98 
 99     (a) BUILTIN loaders:
100 
101         search _builtin_dictionary
102 
103     (b) UNREGISTERED loaders:
104 
105         search _unregistered_dictionary for an entry that matches the
106         (name, clsfile_len, clsfile_crc32).
107 
108 ===============================================================================*/
109 #define UNREGISTERED_INDEX -9999
110 
111 class BootstrapInfo;
112 class ClassFileStream;
113 class ConstantPoolCache;
114 class Dictionary;
115 class DumpTimeClassInfo;
116 class DumpTimeSharedClassTable;
117 class LambdaProxyClassDictionary;
118 class RunTimeClassInfo;
119 class RunTimeSharedDictionary;
120 class DumpTimeLambdaProxyClassDictionary;
121 class LambdaProxyClassKey;
122 
123 class SharedClassLoadingMark {
124  private:
125   Thread* THREAD;
126   InstanceKlass* _klass;
127  public:
128   SharedClassLoadingMark(Thread* current, InstanceKlass* ik) : THREAD(current), _klass(ik) {}
129   ~SharedClassLoadingMark() {
130     assert(THREAD != nullptr, "Current thread is nullptr");
131     assert(_klass != nullptr, "InstanceKlass is nullptr");
132     if (HAS_PENDING_EXCEPTION) {
133       if (_klass->is_shared()) {
134         _klass->set_shared_loading_failed();
135       }
136     }
137   }
138 };
139 
140 class SystemDictionaryShared: public SystemDictionary {
141   friend class ExcludeDumpTimeSharedClasses;
142   friend class CleanupDumpTimeLambdaProxyClassTable;
143 
144   struct ArchiveInfo {
145     RunTimeSharedDictionary _builtin_dictionary;
146     RunTimeSharedDictionary _unregistered_dictionary;
147     LambdaProxyClassDictionary _lambda_proxy_class_dictionary;
148 
149     const RunTimeLambdaProxyClassInfo* lookup_lambda_proxy_class(LambdaProxyClassKey* key) {
150       return _lambda_proxy_class_dictionary.lookup(key, key->hash(), 0);
151     }
152 
153     void print_on(const char* prefix, outputStream* st);
154     void print_table_statistics(const char* prefix, outputStream* st);
155   };
156 
157 public:
158   enum : char {
159     FROM_FIELD_IS_PROTECTED = 1 << 0,
160     FROM_IS_ARRAY           = 1 << 1,
161     FROM_IS_OBJECT          = 1 << 2
162   };
163 
164 private:
165 
166   static DumpTimeSharedClassTable* _dumptime_table;
167   static DumpTimeLambdaProxyClassDictionary* _dumptime_lambda_proxy_class_dictionary;
168 
169   static ArchiveInfo _static_archive;
170   static ArchiveInfo _dynamic_archive;
171 
172   static ArchiveInfo* get_archive(bool is_static_archive) {
173     return is_static_archive ? &_static_archive : &_dynamic_archive;
174   }
175 
176   static InstanceKlass* load_shared_class_for_builtin_loader(
177                                                Symbol* class_name,
178                                                Handle class_loader,
179                                                TRAPS);
180   static InstanceKlass* acquire_class_for_current_thread(
181                                  InstanceKlass *ik,
182                                  Handle class_loader,
183                                  Handle protection_domain,
184                                  const ClassFileStream* cfs,
185                                  TRAPS);
186 
187   static void find_all_archivable_classes_impl();
188   static void write_dictionary(RunTimeSharedDictionary* dictionary,
189                                bool is_builtin);
190   static void write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary* dictionary);
191   static void cleanup_lambda_proxy_class_dictionary();
192   static void reset_registered_lambda_proxy_class(InstanceKlass* ik);
193   static bool is_registered_lambda_proxy_class(InstanceKlass* ik);
194   static bool check_for_exclusion_impl(InstanceKlass* k);
195   static void remove_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN;
196   static InstanceKlass* retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) NOT_CDS_RETURN_(nullptr);
197   static void scan_constant_pool(InstanceKlass* k);
198   DEBUG_ONLY(static bool _class_loading_may_happen;)
199 
200 public:
201   // Guaranteed to return non-null value for non-shared classes.
202   // k must not be a shared class.
203   static DumpTimeClassInfo* get_info(InstanceKlass* k);
204   static DumpTimeClassInfo* get_info_locked(InstanceKlass* k);
205   static DumpTimeSharedClassTable* dumptime_table() { return _dumptime_table; }
206 
207   static bool should_hidden_class_be_archived(InstanceKlass* k);
208   static void mark_required_class(InstanceKlass* k);
209   static bool has_been_redefined(InstanceKlass* k);
210   static bool is_jfr_event_class(InstanceKlass *k);
211   static bool is_hidden_lambda_proxy(InstanceKlass* ik);
212   static bool is_early_klass(InstanceKlass* k);   // Was k loaded while JvmtiExport::is_early_phase()==true
213   static bool has_archived_enum_objs(InstanceKlass* ik);
214   static void set_has_archived_enum_objs(InstanceKlass* ik);
215 
216   static InstanceKlass* find_builtin_class(Symbol* class_name);
217 
218   static const RunTimeClassInfo* find_record(RunTimeSharedDictionary* static_dict,
219                                                    RunTimeSharedDictionary* dynamic_dict,
220                                                    Symbol* name);
221 
222   static bool has_platform_or_app_classes();
223 
224   // Called by PLATFORM/APP loader only
225   static InstanceKlass* find_or_load_shared_class(Symbol* class_name,
226                                                Handle class_loader,
227                                                TRAPS);
228 
229   static void preload_archived_classes(TRAPS);
230 
231   static void allocate_shared_data_arrays(int size, TRAPS);
232 
233   static bool is_builtin_loader(ClassLoaderData* loader_data);
234 
235   static InstanceKlass* lookup_super_for_unregistered_class(Symbol* class_name,
236                                                             Symbol* super_name,  bool is_superclass);
237 
238   static void initialize() NOT_CDS_RETURN;
239   static void init_dumptime_info(InstanceKlass* k) NOT_CDS_RETURN;
240   static void handle_class_unloading(InstanceKlass* k) NOT_CDS_RETURN;
241 
242   static bool can_be_preinited(InstanceKlass* ik);
243   static bool can_be_preinited_locked(InstanceKlass* ik);
244   static void reset_preinit_check();
245 
246   static Dictionary* boot_loader_dictionary() {
247     return ClassLoaderData::the_null_class_loader_data()->dictionary();
248   }
249 
250   static void update_shared_entry(InstanceKlass* klass, int id);
251   static void set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs);
252 
253   static InstanceKlass* lookup_from_stream(Symbol* class_name,
254                                            Handle class_loader,
255                                            Handle protection_domain,
256                                            const ClassFileStream* st,
257                                            TRAPS);
258   // "verification_constraints" are a set of checks performed by
259   // VerificationType::is_reference_assignable_from when verifying a shared class during
260   // dump time.
261   //
262   // With AppCDS, it is possible to override archived classes by calling
263   // ClassLoader.defineClass() directly. SystemDictionary::load_shared_class() already
264   // ensures that you cannot load a shared class if its super type(s) are changed. However,
265   // we need an additional check to ensure that the verification_constraints did not change
266   // between dump time and runtime.
267   static bool add_verification_constraint(InstanceKlass* k, Symbol* name,
268                   Symbol* from_name, bool from_field_is_protected,
269                   bool from_is_array, bool from_is_object) NOT_CDS_RETURN_(false);
270   static void check_verification_constraints(InstanceKlass* klass,
271                                              TRAPS) NOT_CDS_RETURN;
272   static void add_enum_klass_static_field(InstanceKlass* ik, int root_index);
273   static void set_class_has_failed_verification(InstanceKlass* ik) NOT_CDS_RETURN;
274   static bool has_class_failed_verification(InstanceKlass* ik) NOT_CDS_RETURN_(false);
275   static void add_lambda_proxy_class(InstanceKlass* caller_ik,
276                                      InstanceKlass* lambda_ik,
277                                      Symbol* invoked_name,
278                                      Symbol* invoked_type,
279                                      Symbol* method_type,
280                                      Method* member_method,
281                                      Symbol* instantiated_method_type, TRAPS) NOT_CDS_RETURN;
282   static void add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
283                                                              InstanceKlass* proxy_klass) NOT_CDS_RETURN;
284   static InstanceKlass* get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
285                                                       Symbol* invoked_name,
286                                                       Symbol* invoked_type,
287                                                       Symbol* method_type,
288                                                       Method* member_method,
289                                                       Symbol* instantiated_method_type) NOT_CDS_RETURN_(nullptr);
290   static InstanceKlass* get_shared_nest_host(InstanceKlass* lambda_ik) NOT_CDS_RETURN_(nullptr);
291   static InstanceKlass* prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
292                                                           InstanceKlass* caller_ik, TRAPS) NOT_CDS_RETURN_(nullptr);
293   static bool check_linking_constraints(Thread* current, InstanceKlass* klass) NOT_CDS_RETURN_(false);
294   static void record_linking_constraint(Symbol* name, InstanceKlass* klass,
295                                      Handle loader1, Handle loader2) NOT_CDS_RETURN;
296   static bool is_builtin(const InstanceKlass* k) {
297     return (k->shared_classpath_index() != UNREGISTERED_INDEX);
298   }
299   static bool add_unregistered_class(Thread* current, InstanceKlass* k);
300 
301   static void find_all_archivable_classes();
302   static bool check_for_exclusion(Klass* k);
303   static bool check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info);
304   static void validate_before_archiving(InstanceKlass* k);
305   static bool is_excluded_class(InstanceKlass* k);
306   static void set_excluded(InstanceKlass* k);
307   static void set_excluded_locked(InstanceKlass* k);
308   static bool warn_excluded(InstanceKlass* k, const char* reason);
309   static void dumptime_classes_do(class MetaspaceClosure* it);
310   static size_t estimate_size_for_archive();
311   static void write_to_archive(bool is_static_archive = true);
312   static void adjust_lambda_proxy_class_dictionary();
313 
314   static void serialize_dictionary_headers(class SerializeClosure* soc,
315                                            bool is_static_archive = true);
316   static void serialize_vm_classes(class SerializeClosure* soc);
317   static void print() { return print_on(tty); }
318   static void print_on(outputStream* st) NOT_CDS_RETURN;
319   static void print_shared_archive(outputStream* st, bool is_static = true) NOT_CDS_RETURN;
320   static void print_table_statistics(outputStream* st) NOT_CDS_RETURN;
321   static bool is_dumptime_table_empty() NOT_CDS_RETURN_(true);
322   static bool is_supported_invokedynamic(BootstrapInfo* bsi) NOT_CDS_RETURN_(false);
323   DEBUG_ONLY(static bool class_loading_may_happen() {return _class_loading_may_happen;})
324   // Do not archive any new InstanceKlasses that are loaded after this method is called.
325   // This avoids polluting the archive with classes that are only used by GenerateJLIClassesHelper.
326   static void ignore_new_classes();
327 
328 #ifdef ASSERT
329   // This object marks a critical period when writing the CDS archive. During this
330   // period, the JVM must not load any new classes, so as to avoid adding new
331   // items in the SystemDictionaryShared::_dumptime_table.
332   class NoClassLoadingMark: public StackObj {
333   public:
334     NoClassLoadingMark() {
335       assert(_class_loading_may_happen, "must not be nested");
336       _class_loading_may_happen = false;
337     }
338     ~NoClassLoadingMark() {
339       _class_loading_may_happen = true;
340     }
341   };
342 #endif
343 
344   template <typename T>
345   static unsigned int hash_for_shared_dictionary_quick(T* ptr) {
346     assert(MetaspaceObj::is_shared((const MetaspaceObj*)ptr), "must be");
347     assert(ptr > (T*)SharedBaseAddress, "must be");
348     uintx offset = uintx(ptr) - uintx(SharedBaseAddress);
349     return primitive_hash<uintx>(offset);
350   }
351 
352   static unsigned int hash_for_shared_dictionary(address ptr);
353   static const char* class_loader_name_for_shared(Klass* k);
354   static void create_loader_positive_lookup_cache(TRAPS);
355 };
356 
357 #endif // SHARE_CLASSFILE_SYSTEMDICTIONARYSHARED_HPP