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