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