1 /*
2 * Copyright (c) 2014, 2026, 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
26 #include "cds/aotClassFilter.hpp"
27 #include "cds/aotClassLocation.hpp"
28 #include "cds/aotCompressedPointers.hpp"
29 #include "cds/aotLogging.hpp"
30 #include "cds/aotMetaspace.hpp"
31 #include "cds/archiveBuilder.hpp"
32 #include "cds/archiveUtils.hpp"
33 #include "cds/cdsConfig.hpp"
34 #include "cds/cdsProtectionDomain.hpp"
35 #include "cds/classListParser.hpp"
36 #include "cds/classListWriter.hpp"
37 #include "cds/dumpTimeClassInfo.inline.hpp"
38 #include "cds/dynamicArchive.hpp"
39 #include "cds/filemap.hpp"
40 #include "cds/heapShared.hpp"
41 #include "cds/lambdaFormInvokers.inline.hpp"
42 #include "cds/lambdaProxyClassDictionary.hpp"
43 #include "cds/runTimeClassInfo.hpp"
44 #include "cds/unregisteredClasses.hpp"
45 #include "classfile/classFileStream.hpp"
46 #include "classfile/classLoader.hpp"
47 #include "classfile/classLoaderData.inline.hpp"
48 #include "classfile/classLoaderDataGraph.hpp"
49 #include "classfile/dictionary.hpp"
50 #include "classfile/javaClasses.inline.hpp"
51 #include "classfile/symbolTable.hpp"
52 #include "classfile/systemDictionary.hpp"
53 #include "classfile/systemDictionaryShared.hpp"
54 #include "classfile/verificationType.hpp"
55 #include "classfile/vmClasses.hpp"
56 #include "classfile/vmSymbols.hpp"
57 #include "jfr/jfrEvents.hpp"
58 #include "logging/log.hpp"
59 #include "logging/logStream.hpp"
60 #include "memory/allocation.hpp"
61 #include "memory/metadataFactory.hpp"
62 #include "memory/metaspaceClosure.hpp"
63 #include "memory/oopFactory.hpp"
64 #include "memory/resourceArea.hpp"
65 #include "memory/universe.hpp"
66 #include "oops/compressedKlass.inline.hpp"
67 #include "oops/instanceKlass.hpp"
68 #include "oops/klass.inline.hpp"
69 #include "oops/objArrayKlass.hpp"
70 #include "oops/objArrayOop.inline.hpp"
71 #include "oops/oop.inline.hpp"
72 #include "oops/oopHandle.inline.hpp"
73 #include "oops/typeArrayOop.inline.hpp"
74 #include "runtime/arguments.hpp"
75 #include "runtime/handles.inline.hpp"
76 #include "runtime/java.hpp"
77 #include "runtime/javaCalls.hpp"
78 #include "runtime/mutexLocker.hpp"
79 #include "utilities/hashTable.hpp"
80 #include "utilities/stringUtils.hpp"
81
82 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_info_for_static_archive;
83 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_info_for_dynamic_archive;
84 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_info_for_dumping;
85
86 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
87
88 // Used by NoClassLoadingMark
89 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
90
91 #ifdef ASSERT
92 static void check_klass_after_loading(const Klass* k) {
93 if (k != nullptr) {
94 CompressedKlassPointers::check_encodable(k);
95 }
96 }
97 #endif
98
99 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
100 Symbol* class_name, Handle class_loader, TRAPS) {
101 assert(CDSConfig::is_using_archive(), "must be");
102 InstanceKlass* ik = find_builtin_class(class_name);
103
104 if (ik != nullptr && !ik->shared_loading_failed()) {
105 if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->defined_by_app_loader()) ||
106 (SystemDictionary::is_platform_class_loader(class_loader()) && ik->defined_by_platform_loader())) {
107 SharedClassLoadingMark slm(THREAD, ik);
108 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
109 Handle protection_domain =
110 CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
111 return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
112 }
113 }
114 return nullptr;
115 }
116
117 // This function is called for loading only UNREGISTERED classes
118 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
119 Handle class_loader,
120 Handle protection_domain,
121 const ClassFileStream* cfs,
122 TRAPS) {
123 if (!CDSConfig::is_using_archive()) {
124 return nullptr;
125 }
126 if (class_name == nullptr) { // don't do this for hidden classes
127 return nullptr;
128 }
129 if (class_loader.is_null() ||
130 SystemDictionary::is_system_class_loader(class_loader()) ||
131 SystemDictionary::is_platform_class_loader(class_loader())) {
132 // Do nothing for the BUILTIN loaders.
133 return nullptr;
134 }
135
136 const RunTimeClassInfo* record = find_record(&_info_for_static_archive._unregistered_dictionary,
137 &_info_for_dynamic_archive._unregistered_dictionary,
138 class_name);
139 if (record == nullptr) {
140 return nullptr;
141 }
142
143 int clsfile_size = cfs->length();
144 int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
145
146 if (!record->matches(clsfile_size, clsfile_crc32)) {
147 return nullptr;
148 }
149
150 return acquire_class_for_current_thread(record->klass(), class_loader,
151 protection_domain, cfs,
152 THREAD);
153 }
154
155 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
156 InstanceKlass *ik,
157 Handle class_loader,
158 Handle protection_domain,
159 const ClassFileStream *cfs,
160 TRAPS) {
161 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
162
163 {
164 MutexLocker mu(THREAD, SharedDictionary_lock);
165 if (ik->class_loader_data() != nullptr) {
166 // ik is already loaded (by this loader or by a different loader)
167 // or ik is being loaded by a different thread (by this loader or by a different loader)
168 return nullptr;
169 }
170
171 // No other thread has acquired this yet, so give it to *this thread*
172 ik->set_class_loader_data(loader_data);
173 }
174
175 // No longer holding SharedDictionary_lock
176 // No need to lock, as <ik> can be held only by a single thread.
177
178 // Get the package entry.
179 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
180
181 // Load and check super/interfaces, restore unshareable info
182 InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
183 cfs, pkg_entry, THREAD);
184 if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
185 // TODO: clean up <ik> so it can be used again
186 return nullptr;
187 }
188
189 return shared_klass;
190 }
191
192 // Guaranteed to return non-null value for non-shared classes.
193 // k must not be a shared class.
194 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
195 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
196 return get_info_locked(k);
197 }
198
199 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
200 assert_lock_strong(DumpTimeTable_lock);
201 DumpTimeClassInfo* info = _dumptime_table->get_info(k);
202 assert(info != nullptr, "must be");
203 return info;
204 }
205
206 void SystemDictionaryShared::check_code_source(InstanceKlass* ik, const ClassFileStream* cfs) {
207 if (CDSConfig::is_dumping_preimage_static_archive() && !is_builtin_loader(ik->class_loader_data())) {
208 if (cfs == nullptr || cfs->source() == nullptr || strncmp(cfs->source(), "file:", 5) != 0) {
209 // AOT cache filtering:
210 // For non-built-in loaders, cache only the classes that have a file: code source, so
211 // we can avoid caching dynamically generated classes that are likely to change from
212 // run to run. This is similar to the filtering in ClassListWriter::write_to_stream()
213 // for the classic CDS static archive.
214 SystemDictionaryShared::log_exclusion(ik, "Not loaded from \"file:\" code source");
215 SystemDictionaryShared::set_excluded(ik);
216 }
217 }
218 }
219
220 bool SystemDictionaryShared::should_be_excluded_impl(InstanceKlass* k, DumpTimeClassInfo* info) {
221 assert_lock_strong(DumpTimeTable_lock);
222
223 if (!info->has_checked_exclusion()) {
224 check_exclusion_for_self_and_dependencies(k);
225 assert(info->has_checked_exclusion(), "must be");
226 }
227
228 return info->is_excluded();
229 }
230
231 // <func> returns bool and takes a single parameter of Symbol*
232 // The return value indicates whether we want to keep on iterating or not.
233 template<typename Function>
234 void SystemDictionaryShared::iterate_verification_constraint_names(InstanceKlass* k, DumpTimeClassInfo* info, Function func) {
235 int n = info->num_verifier_constraints();
236 bool cont; // continue iterating?
237 for (int i = 0; i < n; i++) {
238 cont = func(info->verifier_constraint_name_at(i));
239 if (!cont) {
240 return; // early termination
241 }
242 Symbol* from_name = info->verifier_constraint_from_name_at(i);
243 if (from_name != nullptr) {
244 cont = func(from_name);
245 if (!cont) {
246 return; // early termination
247 }
248 }
249 }
250 }
251
252 // This is a table of classes that need to be checked for exclusion.
253 class SystemDictionaryShared::ExclusionCheckCandidates
254 : public HashTable<InstanceKlass*, DumpTimeClassInfo*, 15889> {
255 void add_candidate(InstanceKlass* k) {
256 if (contains(k)) {
257 return;
258 }
259 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) {
260 return;
261 }
262
263 DumpTimeClassInfo* info = SystemDictionaryShared::get_info_locked(k);
264 if (info->has_checked_exclusion()) {
265 // We have check exclusion of k and all of its dependencies, so there's no need to check again.
266 return;
267 }
268
269 put(k, info);
270
271 if (!k->is_loaded()) {
272 // super types are not yet initialized for k.
273 return;
274 }
275
276 InstanceKlass* super = k->java_super();
277 if (super != nullptr) {
278 add_candidate(super);
279 }
280
281 Array<InstanceKlass*>* interfaces = k->local_interfaces();
282 int len = interfaces->length();
283 for (int i = 0; i < len; i++) {
284 add_candidate(interfaces->at(i));
285 }
286
287 InstanceKlass* nest_host = k->nest_host_or_null();
288 if (nest_host != nullptr && nest_host != k) {
289 add_candidate(nest_host);
290 }
291
292 if (CDSConfig::is_preserving_verification_constraints()) {
293 SystemDictionaryShared::iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) {
294 Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name);
295 if (constraint_bottom_class != nullptr && constraint_bottom_class->is_instance_klass()) {
296 add_candidate(InstanceKlass::cast(constraint_bottom_class));
297 }
298 return true; // Keep iterating.
299 });
300 }
301 }
302
303 public:
304 ExclusionCheckCandidates(InstanceKlass* k) {
305 add_candidate(k);
306 }
307 };
308
309 // A class X is excluded if check_self_exclusion() returns true for X or any of
310 // X's "exclusion dependency" classes, which include:
311 // - ik's super types
312 // - ik's nest host (if any)
313 //
314 // plus, if CDSConfig::is_preserving_verification_constraints()==true:
315 // - ik's verification constraints. These are the classes used in assignability checks
316 // when verifying ik's bytecodes.
317 //
318 // This method ensure that exclusion check is performed on X and all of its exclusion dependencies.
319 void SystemDictionaryShared::check_exclusion_for_self_and_dependencies(InstanceKlass* ik) {
320 assert_lock_strong(DumpTimeTable_lock);
321 ResourceMark rm;
322
323 // This will recursively find ik and all of its exclusion dependencies that have not yet been checked.
324 ExclusionCheckCandidates candidates(ik);
325
326 // (1) Check each class to see if it should be excluded due to its own problems
327 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
328 if (check_self_exclusion(k)) {
329 info->set_excluded();
330 }
331 });
332
333 // (2) Check each class to see if it should be excluded because of problems in a depeendency class
334 while (true) {
335 bool found_new_exclusion = false;
336
337 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
338 if (!info->is_excluded() && check_dependencies_exclusion(k, info)) {
339 info->set_excluded();
340 found_new_exclusion = true;
341 }
342 });
343
344 // Algorithm notes:
345 //
346 // The dependencies form a directed graph, possibly cyclic. Class X is excluded
347 // if it has at least one directed path that reaches class Y, where
348 // check_self_exclusion(Y) returns true.
349 //
350 // Because of the possibility of cycles in the graph, we cannot use simple
351 // recursion. Otherwise we will either never terminate, or will miss some paths.
352 //
353 // Hence, we keep doing a linear scan of the candidates until we stop finding
354 // new exclusions.
355 //
356 // In the worst case, we find one exclusion per iteration of the while loop,
357 // so the while loop gets executed O(N^2) times. However, in reality we have
358 // very few exclusions, so in most cases the while loop executes only once, and we
359 // walk each edge in the dependencies graph exactly once.
360 if (!found_new_exclusion) {
361 break;
362 }
363 }
364 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
365 // All candidates have been fully checked, so we don't need to check them again.
366 info->set_has_checked_exclusion();
367 });
368 }
369
370 void SystemDictionaryShared::log_exclusion(InstanceKlass* k, const char* reason, bool is_warning) {
371 ResourceMark rm;
372 if (is_warning) {
373 aot_log_warning(aot)("Skipping %s: %s", k->name()->as_C_string(), reason);
374 } else {
375 aot_log_info(aot)("Skipping %s: %s", k->name()->as_C_string(), reason);
376 }
377 }
378
379 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
380 while (k) {
381 if (k->name()->equals("jdk/internal/event/Event")) {
382 return true;
383 }
384 k = k->super();
385 }
386 return false;
387 }
388
389 bool SystemDictionaryShared::check_self_exclusion(InstanceKlass* k) {
390 bool log_warning = false;
391 const char* error = check_self_exclusion_helper(k, log_warning);
392 if (error != nullptr) {
393 log_exclusion(k, error, log_warning);
394 return true; // Should be excluded
395 } else {
396 return false; // Should not be excluded
397 }
398 }
399
400 const char* SystemDictionaryShared::check_self_exclusion_helper(InstanceKlass* k, bool& log_warning) {
401 assert_lock_strong(DumpTimeTable_lock);
402 if (CDSConfig::is_dumping_final_static_archive() && k->defined_by_other_loaders()
403 && k->in_aot_cache()) {
404 return nullptr; // Do not exclude: unregistered classes are passed from preimage to final image.
405 }
406
407 if (k->is_in_error_state()) {
408 log_warning = true;
409 return "In error state";
410 }
411 if (k->is_scratch_class()) {
412 return "A scratch class";
413 }
414 if (!k->is_loaded()) {
415 return "Not in loaded state";
416 }
417 if (has_been_redefined(k)) {
418 return "Has been redefined";
419 }
420 if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
421 if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) {
422 // This class is dynamically generated by the JDK
423 if (CDSConfig::is_dumping_method_handles()) {
424 k->set_shared_classpath_index(0);
425 } else {
426 return "dynamically generated";
427 }
428 } else {
429 // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
430 // agent during dump time).
431 return "Unsupported location";
432 }
433 }
434 if (k->signers() != nullptr) {
435 // We cannot include signed classes in the archive because the certificates
436 // used during dump time may be different than those used during
437 // runtime (due to expiration, etc).
438 return "Signed JAR";
439 }
440 if (is_jfr_event_class(k)) {
441 // We cannot include JFR event classes because they need runtime-specific
442 // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
443 // There are only a small number of these classes, so it's not worthwhile to
444 // support them and make CDS more complicated.
445 return "JFR event class";
446 }
447
448 if (!k->is_linked()) {
449 if (has_class_failed_verification(k)) {
450 log_warning = true;
451 return "Failed verification";
452 } else if (CDSConfig::is_dumping_aot_linked_classes()) {
453 // Most loaded classes should have been speculatively linked by AOTMetaspace::link_class_for_cds().
454 // Old classes may not be linked if CDSConfig::is_preserving_verification_constraints()==false.
455 // An unlinked class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(),
456 // causing the JVM to fail at bootstrap.
457 return "Unlinked class not supported by AOTClassLinking";
458 } else if (CDSConfig::is_dumping_preimage_static_archive()) {
459 // When dumping the final static archive, we will unconditionally load and link all
460 // classes from the preimage. We don't want to get a VerifyError when linking this class.
461 return "Unlinked class not supported by AOTConfiguration";
462 }
463 } else {
464 if (!k->can_be_verified_at_dumptime()) {
465 // We have an old class that has been linked (e.g., it's been executed during
466 // dump time). This class has been verified using the old verifier, which
467 // doesn't save the verification constraints, so check_verification_constraints()
468 // won't work at runtime.
469 // As a result, we cannot store this class. It must be loaded and fully verified
470 // at runtime.
471 return "Old class has been linked";
472 }
473 }
474
475 if (UnregisteredClasses::check_for_exclusion(k)) {
476 return "used only when dumping CDS archive";
477 }
478
479 return nullptr;
480 }
481
482 // Returns true if DumpTimeClassInfo::is_excluded() is true for at least one of k's exclusion dependencies.
483 bool SystemDictionaryShared::check_dependencies_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
484 InstanceKlass* super = k->java_super();
485 if (super != nullptr && is_dependency_excluded(k, super, "super")) {
486 return true;
487 }
488
489 Array<InstanceKlass*>* interfaces = k->local_interfaces();
490 int len = interfaces->length();
491 for (int i = 0; i < len; i++) {
492 InstanceKlass* intf = interfaces->at(i);
493 if (is_dependency_excluded(k, intf, "interface")) {
494 return true;
495 }
496 }
497
498 InstanceKlass* nest_host = k->nest_host_or_null();
499 if (nest_host != nullptr && nest_host != k && is_dependency_excluded(k, nest_host, "nest host class")) {
500 return true;
501 }
502
503 if (CDSConfig::is_preserving_verification_constraints()) {
504 bool excluded = false;
505
506 iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) {
507 if (check_verification_constraint_exclusion(k, constraint_class_name)) {
508 // If one of the verification constraint class has been excluded, the assignability checks
509 // by the verifier may no longer be valid in the production run. For safety, exclude this class.
510 excluded = true;
511 return false; // terminate iteration; k will be excluded
512 } else {
513 return true; // keep iterating
514 }
515 });
516
517 if (excluded) {
518 // At least one verification constraint class has been excluded
519 return true;
520 }
521 }
522
523 return false;
524 }
525
526 bool SystemDictionaryShared::is_dependency_excluded(InstanceKlass* k, InstanceKlass* dependency, const char* type) {
527 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(dependency)) {
528 return false;
529 }
530 DumpTimeClassInfo* dependency_info = get_info_locked(dependency);
531 if (dependency_info->is_excluded()) {
532 ResourceMark rm;
533 aot_log_info(aot)("Skipping %s: %s %s is excluded", k->name()->as_C_string(), type, dependency->name()->as_C_string());
534 return true;
535 }
536 return false;
537 }
538
539 bool SystemDictionaryShared::check_verification_constraint_exclusion(InstanceKlass* k, Symbol* constraint_class_name) {
540 Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name);
541 if (constraint_bottom_class == nullptr) {
542 // We don't have a bottom class (constraint_class_name is a type array), or constraint_class_name
543 // has not been loaded. The latter case happens when the new verifier was checking
544 // if constraint_class_name is assignable to an interface, and found the answer without resolving
545 // constraint_class_name.
546 //
547 // Since this class is not even loaded, it surely cannot be excluded.
548 return false;
549 } else if (constraint_bottom_class->is_instance_klass()) {
550 if (is_dependency_excluded(k, InstanceKlass::cast(constraint_bottom_class), "verification constraint")) {
551 return true;
552 }
553 } else {
554 assert(constraint_bottom_class->is_typeArray_klass(), "must be");
555 }
556
557 return false;
558 }
559
560 Klass* SystemDictionaryShared::find_verification_constraint_bottom_class(InstanceKlass* k, Symbol* constraint_class_name) {
561 Thread* current = Thread::current();
562 Handle loader(current, k->class_loader());
563 Klass* constraint_class = SystemDictionary::find_instance_or_array_klass(current, constraint_class_name, loader);
564 if (constraint_class == nullptr) {
565 return nullptr;
566 }
567
568 if (constraint_class->is_objArray_klass()) {
569 constraint_class = ObjArrayKlass::cast(constraint_class)->bottom_klass();
570 }
571
572 precond(constraint_class->is_typeArray_klass() || constraint_class->is_instance_klass());
573 return constraint_class;
574 }
575
576 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
577 oop class_loader = loader_data->class_loader();
578 return (class_loader == nullptr ||
579 SystemDictionary::is_system_class_loader(class_loader) ||
580 SystemDictionary::is_platform_class_loader(class_loader));
581 }
582
583 bool SystemDictionaryShared::has_platform_or_app_classes() {
584 if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
585 return true;
586 }
587 if (DynamicArchive::is_mapped() &&
588 FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
589 return true;
590 }
591 return false;
592 }
593
594 // The following stack shows how this code is reached:
595 //
596 // [0] SystemDictionaryShared::find_or_load_shared_class()
597 // [1] JVM_FindLoadedClass
598 // [2] java.lang.ClassLoader.findLoadedClass0()
599 // [3] java.lang.ClassLoader.findLoadedClass()
600 // [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
601 // [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
602 // [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
603 // jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
604 //
605 // AppCDS supports fast class loading for these 2 built-in class loaders:
606 // jdk.internal.loader.ClassLoaders$PlatformClassLoader
607 // jdk.internal.loader.ClassLoaders$AppClassLoader
608 // with the following assumptions (based on the JDK core library source code):
609 //
610 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
611 // load the named class.
612 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
613 // [c] At this point, if we can find the named class inside the
614 // shared_dictionary, we can perform further checks (see
615 // SystemDictionary::is_shared_class_visible) to ensure that this class
616 // was loaded by the same class loader during dump time.
617 //
618 // Given these assumptions, we intercept the findLoadedClass() call to invoke
619 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
620 // the archive for the 2 built-in class loaders. This way,
621 // we can improve start-up because we avoid decoding the classfile,
622 // and avoid delegating to the parent loader.
623 //
624 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
625 // needs to be redesigned.
626
627 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
628 Symbol* name, Handle class_loader, TRAPS) {
629 InstanceKlass* k = nullptr;
630 if (CDSConfig::is_using_archive()) {
631 if (!has_platform_or_app_classes()) {
632 return nullptr;
633 }
634
635 if (SystemDictionary::is_system_class_loader(class_loader()) ||
636 SystemDictionary::is_platform_class_loader(class_loader())) {
637 ClassLoaderData *loader_data = register_loader(class_loader);
638 Dictionary* dictionary = loader_data->dictionary();
639
640 // Note: currently, find_or_load_shared_class is called only from
641 // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
642 // which are parallel-capable loaders, so a lock here is NOT taken.
643 assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
644 {
645 MutexLocker mu(THREAD, SystemDictionary_lock);
646 InstanceKlass* check = dictionary->find_class(THREAD, name);
647 if (check != nullptr) {
648 return check;
649 }
650 }
651
652 k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
653 if (k != nullptr) {
654 SharedClassLoadingMark slm(THREAD, k);
655 k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
656 }
657 }
658 }
659
660 DEBUG_ONLY(check_klass_after_loading(k);)
661
662 return k;
663 }
664
665 class UnregisteredClassesTable : public HashTable<
666 Symbol*, InstanceKlass*,
667 15889, // prime number
668 AnyObj::C_HEAP> {};
669
670 static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
671
672 // true == class was successfully added; false == a duplicated class (with the same name) already exists.
673 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
674 // We don't allow duplicated unregistered classes with the same name.
675 // We only archive the first class with that name that succeeds putting
676 // itself into the table.
677 assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
678 MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
679 Symbol* name = klass->name();
680 if (_unregistered_classes_table == nullptr) {
681 _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
682 }
683 bool created;
684 InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
685 if (created) {
686 name->increment_refcount();
687 }
688 return (klass == *v);
689 }
690
691 InstanceKlass* SystemDictionaryShared::get_unregistered_class(Symbol* name) {
692 assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
693 if (_unregistered_classes_table == nullptr) {
694 return nullptr;
695 }
696 InstanceKlass** k = _unregistered_classes_table->get(name);
697 return k != nullptr ? *k : nullptr;
698 }
699
700 void SystemDictionaryShared::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) {
701 precond(CDSConfig::is_dumping_final_static_archive());
702 precond(klass->in_aot_cache());
703
704 // A shared class must have a RunTimeClassInfo record
705 const RunTimeClassInfo* record = find_record(&_info_for_static_archive._unregistered_dictionary,
706 nullptr, klass->name());
707 precond(record != nullptr);
708 precond(record->klass() == klass);
709
710 DumpTimeClassInfo* info = get_info(klass);
711 info->_clsfile_size = record->crc()->_clsfile_size;
712 info->_clsfile_crc32 = record->crc()->_clsfile_crc32;
713 }
714
715 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
716 assert(CDSConfig::is_dumping_archive(), "sanity");
717 assert(!is_builtin(k), "must be unregistered class");
718 DumpTimeClassInfo* info = get_info(k);
719 info->_clsfile_size = cfs->length();
720 info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
721 }
722
723 void SystemDictionaryShared::initialize() {
724 if (CDSConfig::is_dumping_archive()) {
725 _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
726 LambdaProxyClassDictionary::dumptime_init();
727 if (CDSConfig::is_dumping_heap()) {
728 HeapShared::init_dumping();
729 }
730 }
731 }
732
733 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
734 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
735 assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
736 DumpTimeClassInfo* info = _dumptime_table->allocate_info(k);
737 if (AOTClassFilter::is_aot_tooling_class(k)) {
738 info->set_is_aot_tooling_class();
739 }
740 }
741
742 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
743 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
744 _dumptime_table->remove(k);
745 }
746
747 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
748 if (CDSConfig::is_dumping_archive()) {
749 remove_dumptime_info(klass);
750 }
751
752 if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
753 MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
754 if (_unregistered_classes_table != nullptr) {
755 // Remove the class from _unregistered_classes_table: keep the entry but
756 // set it to null. This ensure no classes with the same name can be
757 // added again.
758 InstanceKlass** v = _unregistered_classes_table->get(klass->name());
759 if (v != nullptr) {
760 *v = nullptr;
761 }
762 }
763 } else {
764 assert(_unregistered_classes_table == nullptr, "must not be used");
765 }
766
767 if (ClassListWriter::is_enabled()) {
768 ClassListWriter cw;
769 cw.handle_class_unloading((const InstanceKlass*)klass);
770 }
771 }
772
773 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) {
774 init_dumptime_info(k);
775 copy_verification_info_from_preimage(k);
776 copy_linking_constraints_from_preimage(k);
777
778 if (SystemDictionary::is_platform_class_loader(k->class_loader())) {
779 AOTClassLocationConfig::dumptime_set_has_platform_classes();
780 } else if (SystemDictionary::is_system_class_loader(k->class_loader())) {
781 AOTClassLocationConfig::dumptime_set_has_app_classes();
782 }
783 }
784
785 // Check if a class or any of its supertypes has been redefined.
786 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
787 if (k->has_been_redefined()) {
788 return true;
789 }
790 if (k->super() != nullptr && has_been_redefined(k->super())) {
791 return true;
792 }
793 Array<InstanceKlass*>* interfaces = k->local_interfaces();
794 int len = interfaces->length();
795 for (int i = 0; i < len; i++) {
796 if (has_been_redefined(interfaces->at(i))) {
797 return true;
798 }
799 }
800 return false;
801 }
802
803 // k is a class before relocating by ArchiveBuilder
804 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
805 ResourceMark rm;
806 const char* name = k->name()->as_C_string();
807 DumpTimeClassInfo* info = _dumptime_table->get(k);
808 assert(!class_loading_may_happen(), "class loading must be disabled");
809 guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
810 guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
811 if (is_builtin(k)) {
812 if (k->is_hidden()) {
813 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
814 assert(LambdaProxyClassDictionary::is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
815 }
816 }
817 guarantee(!k->defined_by_other_loaders(),
818 "Class loader type must be set for BUILTIN class %s", name);
819
820 } else {
821 guarantee(k->defined_by_other_loaders(),
822 "Class loader type must not be set for UNREGISTERED class %s", name);
823 }
824 }
825
826 class UnregisteredClassesDuplicationChecker : StackObj {
827 GrowableArray<InstanceKlass*> _list;
828 Thread* _thread;
829 public:
830 UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
831
832 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
833 if (!SystemDictionaryShared::is_builtin(k)) {
834 _list.append(k);
835 }
836 }
837
838 static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
839 ClassLoaderData* loader_a = a[0]->class_loader_data();
840 ClassLoaderData* loader_b = b[0]->class_loader_data();
841
842 if (loader_a != loader_b) {
843 return primitive_compare(loader_a, loader_b);
844 } else {
845 return primitive_compare(a[0], b[0]);
846 }
847 }
848
849 void mark_duplicated_classes() {
850 // Two loaders may load two identical or similar hierarchies of classes. If we
851 // check for duplication in random order, we may end up excluding important base classes
852 // in both hierarchies, causing most of the classes to be excluded.
853 // We sort the classes by their loaders. This way we're likely to archive
854 // all classes in the one of the two hierarchies.
855 _list.sort(compare_by_loader);
856 for (int i = 0; i < _list.length(); i++) {
857 InstanceKlass* k = _list.at(i);
858 bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
859 if (!i_am_first) {
860 SystemDictionaryShared::log_exclusion(k, "Duplicated unregistered class");
861 SystemDictionaryShared::set_excluded_locked(k);
862 }
863 }
864 }
865 };
866
867 void SystemDictionaryShared::link_all_exclusion_check_candidates(InstanceKlass* ik) {
868 bool need_to_link = false;
869 {
870 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
871 ExclusionCheckCandidates candidates(ik);
872
873 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
874 if (!k->is_linked()) {
875 need_to_link = true;
876 }
877 });
878 }
879 if (need_to_link) {
880 JavaThread* THREAD = JavaThread::current();
881 if (log_is_enabled(Info, aot, link)) {
882 ResourceMark rm(THREAD);
883 log_info(aot, link)("Link all loaded classes for %s", ik->external_name());
884 }
885 AOTMetaspace::link_all_loaded_classes(THREAD);
886 }
887 }
888
889 // Returns true if the class should be excluded. This can be called by
890 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
891 // When called before the safepoint, we need to link the class so that
892 // it can be checked by should_be_excluded_impl().
893 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
894 assert(CDSConfig::is_dumping_archive(), "sanity");
895 assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
896
897 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) {
898 // We have reached a super type that's already in the base archive. Treat it
899 // as "not excluded".
900 return false;
901 }
902
903 if (k->is_objArray_klass()) {
904 return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
905 } else if (!k->is_instance_klass()) {
906 assert(k->is_typeArray_klass(), "must be");
907 return false;
908 } else {
909 InstanceKlass* ik = InstanceKlass::cast(k);
910
911 if (!SafepointSynchronize::is_at_safepoint()) {
912 {
913 // fast path
914 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
915 DumpTimeClassInfo* p = get_info_locked(ik);
916 if (p->has_checked_exclusion()) {
917 return p->is_excluded();
918 }
919 }
920
921 link_all_exclusion_check_candidates(ik);
922
923 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
924 DumpTimeClassInfo* p = get_info_locked(ik);
925 return should_be_excluded_impl(ik, p);
926 } else {
927 // When called within the CDS safepoint, the correctness of this function
928 // relies on the call to AOTMetaspace::link_all_loaded_classes()
929 // that happened right before we enter the CDS safepoint.
930 //
931 // Do not call this function in other types of safepoints. For example, if this
932 // is called in a GC safepoint, a klass may be improperly excluded because some
933 // of its verification constraints have not yet been linked.
934 assert(CDSConfig::is_at_aot_safepoint(), "Do not call this function in any other safepoint");
935
936 // No need to check for is_linked() as all eligible classes should have
937 // already been linked in AOTMetaspace::link_class_for_cds().
938 // Don't take DumpTimeTable_lock as we are in safepoint.
939 DumpTimeClassInfo* p = _dumptime_table->get(ik);
940 if (p->is_excluded()) {
941 return true;
942 }
943 return should_be_excluded_impl(ik, p);
944 }
945 }
946 }
947
948 void SystemDictionaryShared::finish_exclusion_checks() {
949 assert_at_safepoint();
950 if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
951 // Do this first -- if a base class is excluded due to duplication,
952 // all of its subclasses will also be excluded.
953 ResourceMark rm;
954 UnregisteredClassesDuplicationChecker dup_checker;
955 _dumptime_table->iterate_all_live_classes(&dup_checker);
956 dup_checker.mark_duplicated_classes();
957 }
958
959 _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
960 SystemDictionaryShared::should_be_excluded_impl(k, &info);
961 });
962
963 _dumptime_table->update_counts();
964 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
965 LambdaProxyClassDictionary::cleanup_dumptime_table();
966 }
967 }
968
969 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
970 assert(!class_loading_may_happen(), "class loading must be disabled");
971 assert_lock_strong(DumpTimeTable_lock);
972 assert(CDSConfig::is_dumping_archive(), "sanity");
973 DumpTimeClassInfo* p = get_info_locked(k);
974 return p->is_excluded();
975 }
976
977 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
978 assert_lock_strong(DumpTimeTable_lock);
979 assert(CDSConfig::is_dumping_archive(), "sanity");
980 DumpTimeClassInfo* info = get_info_locked(k);
981 info->set_excluded();
982 }
983
984 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
985 assert(CDSConfig::is_dumping_archive(), "sanity");
986 DumpTimeClassInfo* info = get_info(k);
987 info->set_excluded();
988 }
989
990 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
991 assert(CDSConfig::is_dumping_archive(), "sanity");
992 DumpTimeClassInfo* p = get_info(ik);
993 p->set_failed_verification();
994 }
995
996 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
997 assert(CDSConfig::is_dumping_archive(), "sanity");
998 DumpTimeClassInfo* p = _dumptime_table->get(ik);
999 return (p == nullptr) ? false : p->failed_verification();
1000 }
1001
1002 void SystemDictionaryShared::set_from_class_file_load_hook(InstanceKlass* ik) {
1003 log_exclusion(ik, "From ClassFileLoadHook");
1004 set_excluded(ik);
1005 }
1006
1007 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) {
1008 assert_lock_strong(DumpTimeTable_lock);
1009
1010 auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
1011 if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
1012 assert(k->defined_by_other_loaders(), "must be");
1013 info.metaspace_pointers_do(it);
1014 } else if (k->is_loader_alive() && !info.is_excluded()) {
1015 info.metaspace_pointers_do(it);
1016 }
1017 };
1018 _dumptime_table->iterate_all_live_classes(do_klass);
1019
1020 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1021 LambdaProxyClassDictionary::dumptime_classes_do(it);
1022 }
1023 }
1024
1025 // Called from VerificationType::is_reference_assignable_from() before performing the assignability check of
1026 // T1 must be assignable from T2
1027 // Where:
1028 // L is the class loader of <k>
1029 // T1 is the type resolved by L using the name <name>
1030 // T2 is the type resolved by L using the name <from_name>
1031 //
1032 // The meaning of (*skip_assignability_check):
1033 // true: is_reference_assignable_from() should SKIP the assignability check
1034 // false: is_reference_assignable_from() should COMPLETE the assignability check
1035 void SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1036 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object,
1037 bool* skip_assignability_check) {
1038 assert(CDSConfig::is_dumping_archive(), "sanity");
1039 DumpTimeClassInfo* info = get_info(k);
1040 info->add_verification_constraint(name, from_name, from_field_is_protected,
1041 from_is_array, from_is_object);
1042
1043 if (CDSConfig::is_dumping_classic_static_archive() && !is_builtin(k)) {
1044 // This applies ONLY to the "classic" CDS static dump, which reads the list of
1045 // unregistered classes (those intended for custom class loaders) from the classlist
1046 // and loads them using jdk.internal.misc.CDS$UnregisteredClassLoader.
1047 //
1048 // When the classlist contains an unregistered class k, the supertypes of k are also
1049 // recorded in the classlist. However, the classlist does not contain information about
1050 // any class X that's not a supertype of k but is needed in the verification of k.
1051 // As a result, CDS$UnregisteredClassLoader will not know how to resolve X.
1052 //
1053 // Therefore, we tell the verifier to refrain from resolving X. Instead, X is recorded
1054 // (symbolically) in the verification constraints of k. In the production run,
1055 // when k is loaded, we will go through its verification constraints and resolve X to complete
1056 // the is_reference_assignable_from() checks.
1057 *skip_assignability_check = true;
1058 } else {
1059 // In all other cases, we are using an *actual* class loader to load k, so it should be able
1060 // to resolve any types that are needed for the verification of k.
1061 *skip_assignability_check = false;
1062 }
1063 }
1064
1065 // When the old verifier is verifying the class <ik> at dump time, it tries to resolve a
1066 // class with the given <name>. For the verification result to be valid at run time, we must
1067 // ensure that <name> resolves to the exact same Klass as in dump time.
1068 void SystemDictionaryShared::add_old_verification_constraint(Thread* current, InstanceKlass* ik, Symbol* name) {
1069 precond(CDSConfig::is_preserving_verification_constraints());
1070 DumpTimeClassInfo* info = get_info(ik);
1071 info->add_verification_constraint(name);
1072 }
1073
1074 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
1075 assert(CDSConfig::is_dumping_heap(), "sanity");
1076 DumpTimeClassInfo* info = get_info_locked(ik);
1077 info->add_enum_klass_static_field(root_index);
1078 }
1079
1080 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1081 TRAPS) {
1082 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1083 RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
1084
1085 int length = record->num_verifier_constraints();
1086 if (length > 0) {
1087 for (int i = 0; i < length; i++) {
1088 RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1089 Symbol* name = vc->name();
1090 Symbol* from_name = vc->from_name();
1091
1092 if (from_name == nullptr) {
1093 // This is for old verifier. No need to check, as we can guarantee that all classes checked by
1094 // the old verifier during AOT training phase cannot be replaced in the asembly phase.
1095 precond(CDSConfig::is_dumping_final_static_archive());
1096 continue;
1097 }
1098
1099 if (log_is_enabled(Trace, aot, verification)) {
1100 ResourceMark rm(THREAD);
1101 log_trace(aot, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1102 klass->external_name(), from_name->as_klass_external_name(),
1103 name->as_klass_external_name(), record->verifier_constraint_flag(i));
1104 }
1105
1106 bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
1107 record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
1108 if (!ok) {
1109 ResourceMark rm(THREAD);
1110 stringStream ss;
1111
1112 ss.print_cr("Bad type on operand stack");
1113 ss.print_cr("Exception Details:");
1114 ss.print_cr(" Location:\n %s", klass->name()->as_C_string());
1115 ss.print_cr(" Reason:\n Type '%s' is not assignable to '%s'",
1116 from_name->as_quoted_ascii(), name->as_quoted_ascii());
1117 THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1118 }
1119 }
1120 }
1121 }
1122
1123 void SystemDictionaryShared::copy_verification_info_from_preimage(InstanceKlass* klass) {
1124 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1125 DumpTimeClassInfo* dt_info = get_info(klass);
1126 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1127
1128 int length = rt_info->num_verifier_constraints();
1129 if (length > 0) {
1130 for (int i = 0; i < length; i++) {
1131 RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
1132 Symbol* name = vc->name();
1133 Symbol* from_name = vc->from_name();
1134
1135 dt_info->add_verification_constraint(name, from_name,
1136 rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
1137 }
1138 }
1139 }
1140
1141 static oop get_class_loader_by(char type) {
1142 if (type == (char)ClassLoader::BOOT_LOADER) {
1143 return (oop)nullptr;
1144 } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1145 return SystemDictionary::java_platform_loader();
1146 } else {
1147 assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1148 return SystemDictionary::java_system_loader();
1149 }
1150 }
1151
1152 // Record class loader constraints that are checked inside
1153 // InstanceKlass::link_class(), so that these can be checked quickly
1154 // at runtime without laying out the vtable/itables.
1155 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1156 Handle loader1, Handle loader2) {
1157 // A linking constraint check is executed when:
1158 // - klass extends or implements type S
1159 // - klass overrides method S.M(...) with X.M
1160 // - If klass defines the method M, X is
1161 // the same as klass.
1162 // - If klass does not define the method M,
1163 // X must be a supertype of klass and X.M is
1164 // a default method defined by X.
1165 // - loader1 = X->class_loader()
1166 // - loader2 = S->class_loader()
1167 // - loader1 != loader2
1168 // - M's parameter(s) include an object type T
1169 // We require that
1170 // - whenever loader1 and loader2 try to
1171 // resolve the type T, they must always resolve to
1172 // the same InstanceKlass.
1173 // NOTE: type T may or may not be currently resolved in
1174 // either of these two loaders. The check itself does not
1175 // try to resolve T.
1176 oop klass_loader = klass->class_loader();
1177
1178 if (!is_system_class_loader(klass_loader) &&
1179 !is_platform_class_loader(klass_loader)) {
1180 // If klass is loaded by system/platform loaders, we can
1181 // guarantee that klass and S must be loaded by the same
1182 // respective loader between dump time and run time, and
1183 // the exact same check on (name, loader1, loader2) will
1184 // be executed. Hence, we can cache this check and execute
1185 // it at runtime without walking the vtable/itables.
1186 //
1187 // This cannot be guaranteed for classes loaded by other
1188 // loaders, so we bail.
1189 return;
1190 }
1191
1192 assert(is_builtin(klass), "must be");
1193 assert(klass_loader != nullptr, "should not be called for boot loader");
1194 assert(loader1 != loader2, "must be");
1195
1196 if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
1197 // We are re-laying out the vtable/itables of the *copy* of
1198 // a class during the final stage of dynamic dumping. The
1199 // linking constraints for this class has already been recorded.
1200 return;
1201 }
1202 assert(!Thread::current()->is_VM_thread(), "must be");
1203
1204 assert(CDSConfig::is_dumping_archive(), "sanity");
1205 DumpTimeClassInfo* info = get_info(klass);
1206 info->record_linking_constraint(name, loader1, loader2);
1207 }
1208
1209 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1210 // the purpose of checking class loader constraints.
1211 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1212 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1213 LogTarget(Info, class, loader, constraints) log;
1214 if (klass->defined_by_boot_loader()) {
1215 // No class loader constraint check performed for boot classes.
1216 return true;
1217 }
1218 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1219 RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1220 assert(info != nullptr, "Sanity");
1221 if (info->num_loader_constraints() > 0) {
1222 HandleMark hm(current);
1223 for (int i = 0; i < info->num_loader_constraints(); i++) {
1224 RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1225 Symbol* name = lc->constraint_name();
1226 Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1227 Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1228 if (log.is_enabled()) {
1229 ResourceMark rm(current);
1230 log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1231 klass->external_name(), name->as_C_string(),
1232 ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1233 ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1234 }
1235 if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1236 // Loader constraint violation has been found. The caller
1237 // will re-layout the vtable/itables to produce the correct
1238 // exception.
1239 if (log.is_enabled()) {
1240 log.print(" failed]");
1241 }
1242 return false;
1243 }
1244 if (log.is_enabled()) {
1245 log.print(" succeeded]");
1246 }
1247 }
1248 return true; // for all recorded constraints added successfully.
1249 }
1250 }
1251 if (log.is_enabled()) {
1252 ResourceMark rm(current);
1253 log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1254 }
1255 return false;
1256 }
1257
1258 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
1259 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1260 JavaThread* current = JavaThread::current();
1261 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1262 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1263
1264 if (rt_info->num_loader_constraints() > 0) {
1265 for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
1266 RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
1267 Symbol* name = lc->constraint_name();
1268 Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1269 Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1270 record_linking_constraint(name, klass, loader1, loader2);
1271 }
1272 }
1273 }
1274 }
1275
1276 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1277 if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1278 uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1279 unsigned int hash = primitive_hash<uintx>(offset);
1280 DEBUG_ONLY({
1281 if (AOTMetaspace::in_aot_cache(ptr)) {
1282 assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1283 }
1284 });
1285 return hash;
1286 } else {
1287 return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1288 }
1289 }
1290
1291 class CopySharedClassInfoToArchive : StackObj {
1292 CompactHashtableWriter* _writer;
1293 bool _is_builtin;
1294 public:
1295 CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1296 bool is_builtin)
1297 : _writer(writer), _is_builtin(is_builtin) {}
1298
1299 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1300 if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1301 size_t byte_size = info.runtime_info_bytesize();
1302 RunTimeClassInfo* record;
1303 record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1304 record->init(info);
1305
1306 unsigned int hash;
1307 Symbol* name = info._klass->name();
1308 name = ArchiveBuilder::current()->get_buffered_addr(name);
1309 hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1310 if (_is_builtin && info._klass->is_hidden()) {
1311 // skip
1312 } else {
1313 _writer->add(hash, AOTCompressedPointers::encode_not_null(record));
1314 }
1315 if (log_is_enabled(Trace, aot, hashtables)) {
1316 ResourceMark rm;
1317 log_trace(aot, hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1318 }
1319
1320 // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1321 InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1322 RunTimeClassInfo::set_for(buffered_klass, record);
1323 }
1324 }
1325 };
1326
1327 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1328 bool is_builtin) {
1329 CompactHashtableStats stats;
1330 dictionary->reset();
1331 CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1332 CopySharedClassInfoToArchive copy(&writer, is_builtin);
1333 assert_lock_strong(DumpTimeTable_lock);
1334 _dumptime_table->iterate_all_live_classes(©);
1335 writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1336 }
1337
1338 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1339 ArchiveInfo* archive = get_archive(is_static_archive, /*is_dumping=*/true);
1340
1341 write_dictionary(&archive->_builtin_dictionary, true);
1342 write_dictionary(&archive->_unregistered_dictionary, false);
1343 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1344 LambdaProxyClassDictionary::write_dictionary(is_static_archive);
1345 } else {
1346 LambdaProxyClassDictionary::reset_dictionary(is_static_archive);
1347 }
1348 }
1349
1350 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1351 bool is_static_archive) {
1352 ArchiveInfo* archive = get_archive(is_static_archive, soc->writing());
1353
1354 archive->_builtin_dictionary.serialize_header(soc);
1355 archive->_unregistered_dictionary.serialize_header(soc);
1356 LambdaProxyClassDictionary::serialize(soc, is_static_archive);
1357 }
1358
1359 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1360 for (auto id : EnumRange<vmClassID>{}) {
1361 soc->do_ptr(vmClasses::klass_addr_at(id));
1362 }
1363 }
1364
1365 const RunTimeClassInfo*
1366 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1367 if (!CDSConfig::is_using_archive() || !name->in_aot_cache()) {
1368 // The names of all shared classes must also be a shared Symbol.
1369 return nullptr;
1370 }
1371
1372 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1373 const RunTimeClassInfo* record = nullptr;
1374 if (DynamicArchive::is_mapped()) {
1375 // Use the regenerated holder classes in the dynamic archive as they
1376 // have more methods than those in the base archive.
1377 if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1378 record = dynamic_dict->lookup(name, hash, 0);
1379 if (record != nullptr) {
1380 return record;
1381 }
1382 }
1383 }
1384
1385 if (!AOTMetaspace::in_aot_cache_dynamic_region(name)) {
1386 // The names of all shared classes in the static dict must also be in the
1387 // static archive
1388 record = static_dict->lookup(name, hash, 0);
1389 }
1390
1391 if (record == nullptr && DynamicArchive::is_mapped()) {
1392 record = dynamic_dict->lookup(name, hash, 0);
1393 }
1394
1395 return record;
1396 }
1397
1398 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1399 const RunTimeClassInfo* record = find_record(&_info_for_static_archive._builtin_dictionary,
1400 &_info_for_dynamic_archive._builtin_dictionary,
1401 name);
1402 if (record != nullptr) {
1403 assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1404 DEBUG_ONLY(check_klass_after_loading(record->klass());)
1405 // We did not save the classfile data of the generated LambdaForm invoker classes,
1406 // so we cannot support CLFH for such classes.
1407 if (record->klass()->is_aot_generated_class() && JvmtiExport::should_post_class_file_load_hook()) {
1408 return nullptr;
1409 }
1410 return record->klass();
1411 } else {
1412 return nullptr;
1413 }
1414 }
1415
1416 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1417 assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1418 DumpTimeClassInfo* info = get_info(k);
1419 info->_id = id;
1420 }
1421
1422 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) {
1423 assert(k != nullptr, "Sanity");
1424 assert(k->in_aot_cache(), "Must be");
1425 assert(k->is_instance_klass(), "Must be");
1426 InstanceKlass* ik = InstanceKlass::cast(k);
1427 if (ik->defined_by_boot_loader()) {
1428 return "boot_loader";
1429 } else if (ik->defined_by_platform_loader()) {
1430 return "platform_loader";
1431 } else if (ik->defined_by_app_loader()) {
1432 return "app_loader";
1433 } else if (ik->defined_by_other_loaders()) {
1434 return "unregistered_loader";
1435 } else {
1436 return "unknown loader";
1437 }
1438 }
1439
1440 void SystemDictionaryShared::get_all_archived_classes(bool is_static_archive, GrowableArray<Klass*>* classes) {
1441 ArchiveInfo* archive = get_archive(is_static_archive, /*is_dumping=*/false);
1442 archive->_builtin_dictionary.iterate_all([&] (const RunTimeClassInfo* record) {
1443 classes->append(record->klass());
1444 });
1445
1446 archive->_unregistered_dictionary.iterate_all([&] (const RunTimeClassInfo* record) {
1447 classes->append(record->klass());
1448 });
1449 }
1450
1451 class SharedDictionaryPrinter : StackObj {
1452 outputStream* _st;
1453 int _index;
1454 public:
1455 SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1456
1457 void do_value(const RunTimeClassInfo* record) {
1458 ResourceMark rm;
1459 _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1460 SystemDictionaryShared::loader_type_for_shared_class(record->klass()));
1461 if (record->klass()->array_klasses() != nullptr) {
1462 record->klass()->array_klasses()->cds_print_value_on(_st);
1463 _st->cr();
1464 }
1465 }
1466 int index() const { return _index; }
1467 };
1468
1469 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1470 outputStream* st,
1471 bool is_static_archive) {
1472 st->print_cr("%sShared Dictionary", prefix);
1473 SharedDictionaryPrinter p(st);
1474 st->print_cr("%sShared Builtin Dictionary", prefix);
1475 _builtin_dictionary.iterate_all(&p);
1476 st->print_cr("%sShared Unregistered Dictionary", prefix);
1477 _unregistered_dictionary.iterate_all(&p);
1478 LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive);
1479 }
1480
1481 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1482 outputStream* st,
1483 bool is_static_archive) {
1484 st->print_cr("%sArchve Statistics", prefix);
1485 _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1486 _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1487 LambdaProxyClassDictionary::print_statistics(st, is_static_archive);
1488 }
1489
1490 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1491 if (CDSConfig::is_using_archive()) {
1492 if (is_static) {
1493 _info_for_static_archive.print_on("", st, true);
1494 } else {
1495 if (DynamicArchive::is_mapped()) {
1496 _info_for_dynamic_archive.print_on("Dynamic ", st, false);
1497 }
1498 }
1499 }
1500 }
1501
1502 void SystemDictionaryShared::print_on(outputStream* st) {
1503 print_shared_archive(st, true);
1504 print_shared_archive(st, false);
1505 }
1506
1507 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1508 if (CDSConfig::is_using_archive()) {
1509 _info_for_static_archive.print_table_statistics("Static ", st, true);
1510 if (DynamicArchive::is_mapped()) {
1511 _info_for_dynamic_archive.print_table_statistics("Dynamic ", st, false);
1512 }
1513 }
1514 }
1515
1516 bool SystemDictionaryShared::is_dumptime_table_empty() {
1517 assert_lock_strong(DumpTimeTable_lock);
1518 _dumptime_table->update_counts();
1519 if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1520 return true;
1521 }
1522 return false;
1523 }