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