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 void SystemDictionaryShared::link_all_exclusion_check_candidates(InstanceKlass* ik) {
859 bool need_to_link = false;
860 {
861 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
862 ExclusionCheckCandidates candidates(ik);
863
864 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) {
865 if (!k->is_linked()) {
866 need_to_link = true;
867 }
868 });
869 }
870 if (need_to_link) {
871 JavaThread* THREAD = JavaThread::current();
872 if (log_is_enabled(Info, aot, link)) {
873 ResourceMark rm(THREAD);
874 log_info(aot, link)("Link all loaded classes for %s", ik->external_name());
875 }
876 AOTMetaspace::link_all_loaded_classes(THREAD);
877 }
878 }
879
880 // Returns true if the class should be excluded. This can be called by
881 // AOTConstantPoolResolver before or after we enter the CDS safepoint.
882 // When called before the safepoint, we need to link the class so that
883 // it can be checked by should_be_excluded_impl().
884 bool SystemDictionaryShared::should_be_excluded(Klass* k) {
885 assert(CDSConfig::is_dumping_archive(), "sanity");
886 assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity");
887
888 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) {
889 // We have reached a super type that's already in the base archive. Treat it
890 // as "not excluded".
891 return false;
892 }
893
894 if (k->is_objArray_klass()) {
895 return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass());
896 } else if (!k->is_instance_klass()) {
897 assert(k->is_typeArray_klass(), "must be");
898 return false;
899 } else {
900 InstanceKlass* ik = InstanceKlass::cast(k);
901
902 if (!SafepointSynchronize::is_at_safepoint()) {
903 {
904 // fast path
905 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
906 DumpTimeClassInfo* p = get_info_locked(ik);
907 if (p->has_checked_exclusion()) {
908 return p->is_excluded();
909 }
910 }
911
912 link_all_exclusion_check_candidates(ik);
913
914 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
915 DumpTimeClassInfo* p = get_info_locked(ik);
916 return should_be_excluded_impl(ik, p);
917 } else {
918 // When called within the CDS safepoint, the correctness of this function
919 // relies on the call to AOTMetaspace::link_all_loaded_classes()
920 // that happened right before we enter the CDS safepoint.
921 //
922 // Do not call this function in other types of safepoints. For example, if this
923 // is called in a GC safepoint, a klass may be improperly excluded because some
924 // of its verification constraints have not yet been linked.
925 assert(CDSConfig::is_at_aot_safepoint(), "Do not call this function in any other safepoint");
926
927 // No need to check for is_linked() as all eligible classes should have
928 // already been linked in AOTMetaspace::link_class_for_cds().
929 // Don't take DumpTimeTable_lock as we are in safepoint.
930 DumpTimeClassInfo* p = _dumptime_table->get(ik);
931 if (p->is_excluded()) {
932 return true;
933 }
934 return should_be_excluded_impl(ik, p);
935 }
936 }
937 }
938
939 void SystemDictionaryShared::finish_exclusion_checks() {
940 assert_at_safepoint();
941 if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
942 // Do this first -- if a base class is excluded due to duplication,
943 // all of its subclasses will also be excluded.
944 ResourceMark rm;
945 UnregisteredClassesDuplicationChecker dup_checker;
946 _dumptime_table->iterate_all_live_classes(&dup_checker);
947 dup_checker.mark_duplicated_classes();
948 }
949
950 _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) {
951 SystemDictionaryShared::should_be_excluded_impl(k, &info);
952 });
953
954 _dumptime_table->update_counts();
955 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
956 LambdaProxyClassDictionary::cleanup_dumptime_table();
957 }
958 }
959
960 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
961 assert(!class_loading_may_happen(), "class loading must be disabled");
962 assert_lock_strong(DumpTimeTable_lock);
963 assert(CDSConfig::is_dumping_archive(), "sanity");
964 DumpTimeClassInfo* p = get_info_locked(k);
965 return p->is_excluded();
966 }
967
968 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
969 assert_lock_strong(DumpTimeTable_lock);
970 assert(CDSConfig::is_dumping_archive(), "sanity");
971 DumpTimeClassInfo* info = get_info_locked(k);
972 info->set_excluded();
973 }
974
975 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
976 assert(CDSConfig::is_dumping_archive(), "sanity");
977 DumpTimeClassInfo* info = get_info(k);
978 info->set_excluded();
979 }
980
981 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
982 assert(CDSConfig::is_dumping_archive(), "sanity");
983 DumpTimeClassInfo* p = get_info(ik);
984 p->set_failed_verification();
985 }
986
987 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
988 assert(CDSConfig::is_dumping_archive(), "sanity");
989 DumpTimeClassInfo* p = _dumptime_table->get(ik);
990 return (p == nullptr) ? false : p->failed_verification();
991 }
992
993 void SystemDictionaryShared::set_from_class_file_load_hook(InstanceKlass* ik) {
994 log_exclusion(ik, "From ClassFileLoadHook");
995 set_excluded(ik);
996 }
997
998 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) {
999 assert_lock_strong(DumpTimeTable_lock);
1000
1001 auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
1002 if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) {
1003 assert(k->defined_by_other_loaders(), "must be");
1004 info.metaspace_pointers_do(it);
1005 } else if (k->is_loader_alive() && !info.is_excluded()) {
1006 info.metaspace_pointers_do(it);
1007 }
1008 };
1009 _dumptime_table->iterate_all_live_classes(do_klass);
1010
1011 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1012 LambdaProxyClassDictionary::dumptime_classes_do(it);
1013 }
1014 }
1015
1016 // Called from VerificationType::is_reference_assignable_from() before performing the assignability check of
1017 // T1 must be assignable from T2
1018 // Where:
1019 // L is the class loader of <k>
1020 // T1 is the type resolved by L using the name <name>
1021 // T2 is the type resolved by L using the name <from_name>
1022 //
1023 // The meaning of (*skip_assignability_check):
1024 // true: is_reference_assignable_from() should SKIP the assignability check
1025 // false: is_reference_assignable_from() should COMPLETE the assignability check
1026 void SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1027 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object,
1028 bool* skip_assignability_check) {
1029 assert(CDSConfig::is_dumping_archive(), "sanity");
1030 DumpTimeClassInfo* info = get_info(k);
1031 info->add_verification_constraint(name, from_name, from_field_is_protected,
1032 from_is_array, from_is_object);
1033
1034 if (CDSConfig::is_dumping_classic_static_archive() && !is_builtin(k)) {
1035 // This applies ONLY to the "classic" CDS static dump, which reads the list of
1036 // unregistered classes (those intended for custom class loaders) from the classlist
1037 // and loads them using jdk.internal.misc.CDS$UnregisteredClassLoader.
1038 //
1039 // When the classlist contains an unregistered class k, the supertypes of k are also
1040 // recorded in the classlist. However, the classlist does not contain information about
1041 // any class X that's not a supertype of k but is needed in the verification of k.
1042 // As a result, CDS$UnregisteredClassLoader will not know how to resolve X.
1043 //
1044 // Therefore, we tell the verifier to refrain from resolving X. Instead, X is recorded
1045 // (symbolically) in the verification constraints of k. In the production run,
1046 // when k is loaded, we will go through its verification constraints and resolve X to complete
1047 // the is_reference_assignable_from() checks.
1048 *skip_assignability_check = true;
1049 } else {
1050 // In all other cases, we are using an *actual* class loader to load k, so it should be able
1051 // to resolve any types that are needed for the verification of k.
1052 *skip_assignability_check = false;
1053 }
1054 }
1055
1056 // When the old verifier is verifying the class <ik> at dump time, it tries to resolve a
1057 // class with the given <name>. For the verification result to be valid at run time, we must
1058 // ensure that <name> resolves to the exact same Klass as in dump time.
1059 void SystemDictionaryShared::add_old_verification_constraint(Thread* current, InstanceKlass* ik, Symbol* name) {
1060 precond(CDSConfig::is_preserving_verification_constraints());
1061 DumpTimeClassInfo* info = get_info(ik);
1062 info->add_verification_constraint(name);
1063 }
1064
1065 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
1066 assert(CDSConfig::is_dumping_heap(), "sanity");
1067 DumpTimeClassInfo* info = get_info_locked(ik);
1068 info->add_enum_klass_static_field(root_index);
1069 }
1070
1071 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1072 TRAPS) {
1073 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1074 RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
1075
1076 int length = record->num_verifier_constraints();
1077 if (length > 0) {
1078 for (int i = 0; i < length; i++) {
1079 RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1080 Symbol* name = vc->name();
1081 Symbol* from_name = vc->from_name();
1082
1083 if (from_name == nullptr) {
1084 // This is for old verifier. No need to check, as we can guarantee that all classes checked by
1085 // the old verifier during AOT training phase cannot be replaced in the asembly phase.
1086 precond(CDSConfig::is_dumping_final_static_archive());
1087 continue;
1088 }
1089
1090 if (log_is_enabled(Trace, aot, verification)) {
1091 ResourceMark rm(THREAD);
1092 log_trace(aot, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1093 klass->external_name(), from_name->as_klass_external_name(),
1094 name->as_klass_external_name(), record->verifier_constraint_flag(i));
1095 }
1096
1097 bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name,
1098 record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK);
1099 if (!ok) {
1100 ResourceMark rm(THREAD);
1101 stringStream ss;
1102
1103 ss.print_cr("Bad type on operand stack");
1104 ss.print_cr("Exception Details:");
1105 ss.print_cr(" Location:\n %s", klass->name()->as_C_string());
1106 ss.print_cr(" Reason:\n Type '%s' is not assignable to '%s'",
1107 from_name->as_quoted_ascii(), name->as_quoted_ascii());
1108 THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1109 }
1110 }
1111 }
1112 }
1113
1114 void SystemDictionaryShared::copy_verification_info_from_preimage(InstanceKlass* klass) {
1115 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1116 DumpTimeClassInfo* dt_info = get_info(klass);
1117 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1118
1119 int length = rt_info->num_verifier_constraints();
1120 if (length > 0) {
1121 for (int i = 0; i < length; i++) {
1122 RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i);
1123 Symbol* name = vc->name();
1124 Symbol* from_name = vc->from_name();
1125
1126 dt_info->add_verification_constraint(name, from_name,
1127 rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i));
1128 }
1129 }
1130 }
1131
1132 static oop get_class_loader_by(char type) {
1133 if (type == (char)ClassLoader::BOOT_LOADER) {
1134 return (oop)nullptr;
1135 } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1136 return SystemDictionary::java_platform_loader();
1137 } else {
1138 assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1139 return SystemDictionary::java_system_loader();
1140 }
1141 }
1142
1143 // Record class loader constraints that are checked inside
1144 // InstanceKlass::link_class(), so that these can be checked quickly
1145 // at runtime without laying out the vtable/itables.
1146 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1147 Handle loader1, Handle loader2) {
1148 // A linking constraint check is executed when:
1149 // - klass extends or implements type S
1150 // - klass overrides method S.M(...) with X.M
1151 // - If klass defines the method M, X is
1152 // the same as klass.
1153 // - If klass does not define the method M,
1154 // X must be a supertype of klass and X.M is
1155 // a default method defined by X.
1156 // - loader1 = X->class_loader()
1157 // - loader2 = S->class_loader()
1158 // - loader1 != loader2
1159 // - M's parameter(s) include an object type T
1160 // We require that
1161 // - whenever loader1 and loader2 try to
1162 // resolve the type T, they must always resolve to
1163 // the same InstanceKlass.
1164 // NOTE: type T may or may not be currently resolved in
1165 // either of these two loaders. The check itself does not
1166 // try to resolve T.
1167 oop klass_loader = klass->class_loader();
1168
1169 if (!is_system_class_loader(klass_loader) &&
1170 !is_platform_class_loader(klass_loader)) {
1171 // If klass is loaded by system/platform loaders, we can
1172 // guarantee that klass and S must be loaded by the same
1173 // respective loader between dump time and run time, and
1174 // the exact same check on (name, loader1, loader2) will
1175 // be executed. Hence, we can cache this check and execute
1176 // it at runtime without walking the vtable/itables.
1177 //
1178 // This cannot be guaranteed for classes loaded by other
1179 // loaders, so we bail.
1180 return;
1181 }
1182
1183 assert(is_builtin(klass), "must be");
1184 assert(klass_loader != nullptr, "should not be called for boot loader");
1185 assert(loader1 != loader2, "must be");
1186
1187 if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
1188 // We are re-laying out the vtable/itables of the *copy* of
1189 // a class during the final stage of dynamic dumping. The
1190 // linking constraints for this class has already been recorded.
1191 return;
1192 }
1193 assert(!Thread::current()->is_VM_thread(), "must be");
1194
1195 assert(CDSConfig::is_dumping_archive(), "sanity");
1196 DumpTimeClassInfo* info = get_info(klass);
1197 info->record_linking_constraint(name, loader1, loader2);
1198 }
1199
1200 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1201 // the purpose of checking class loader constraints.
1202 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1203 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1204 LogTarget(Info, class, loader, constraints) log;
1205 if (klass->defined_by_boot_loader()) {
1206 // No class loader constraint check performed for boot classes.
1207 return true;
1208 }
1209 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1210 RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1211 assert(info != nullptr, "Sanity");
1212 if (info->num_loader_constraints() > 0) {
1213 HandleMark hm(current);
1214 for (int i = 0; i < info->num_loader_constraints(); i++) {
1215 RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1216 Symbol* name = lc->constraint_name();
1217 Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1218 Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1219 if (log.is_enabled()) {
1220 ResourceMark rm(current);
1221 log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1222 klass->external_name(), name->as_C_string(),
1223 ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1224 ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1225 }
1226 if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1227 // Loader constraint violation has been found. The caller
1228 // will re-layout the vtable/itables to produce the correct
1229 // exception.
1230 if (log.is_enabled()) {
1231 log.print(" failed]");
1232 }
1233 return false;
1234 }
1235 if (log.is_enabled()) {
1236 log.print(" succeeded]");
1237 }
1238 }
1239 return true; // for all recorded constraints added successfully.
1240 }
1241 }
1242 if (log.is_enabled()) {
1243 ResourceMark rm(current);
1244 log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1245 }
1246 return false;
1247 }
1248
1249 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) {
1250 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1251 JavaThread* current = JavaThread::current();
1252 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) {
1253 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage
1254
1255 if (rt_info->num_loader_constraints() > 0) {
1256 for (int i = 0; i < rt_info->num_loader_constraints(); i++) {
1257 RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i);
1258 Symbol* name = lc->constraint_name();
1259 Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1260 Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1261 record_linking_constraint(name, klass, loader1, loader2);
1262 }
1263 }
1264 }
1265 }
1266
1267 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1268 if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
1269 uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1270 unsigned int hash = primitive_hash<uintx>(offset);
1271 DEBUG_ONLY({
1272 if (MetaspaceObj::in_aot_cache((const MetaspaceObj*)ptr)) {
1273 assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1274 }
1275 });
1276 return hash;
1277 } else {
1278 return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1279 }
1280 }
1281
1282 class CopySharedClassInfoToArchive : StackObj {
1283 CompactHashtableWriter* _writer;
1284 bool _is_builtin;
1285 ArchiveBuilder *_builder;
1286 public:
1287 CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1288 bool is_builtin)
1289 : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
1290
1291 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1292 if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1293 size_t byte_size = info.runtime_info_bytesize();
1294 RunTimeClassInfo* record;
1295 record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1296 record->init(info);
1297
1298 unsigned int hash;
1299 Symbol* name = info._klass->name();
1300 name = ArchiveBuilder::current()->get_buffered_addr(name);
1301 hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1302 u4 delta = _builder->buffer_to_offset_u4((address)record);
1303 if (_is_builtin && info._klass->is_hidden()) {
1304 // skip
1305 } else {
1306 _writer->add(hash, delta);
1307 }
1308 if (log_is_enabled(Trace, aot, hashtables)) {
1309 ResourceMark rm;
1310 log_trace(aot, hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1311 }
1312
1313 // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1314 InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1315 RunTimeClassInfo::set_for(buffered_klass, record);
1316 }
1317 }
1318 };
1319
1320 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1321 bool is_builtin) {
1322 CompactHashtableStats stats;
1323 dictionary->reset();
1324 CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1325 CopySharedClassInfoToArchive copy(&writer, is_builtin);
1326 assert_lock_strong(DumpTimeTable_lock);
1327 _dumptime_table->iterate_all_live_classes(©);
1328 writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1329 }
1330
1331 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1332 ArchiveInfo* archive = get_archive(is_static_archive);
1333
1334 write_dictionary(&archive->_builtin_dictionary, true);
1335 write_dictionary(&archive->_unregistered_dictionary, false);
1336 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
1337 LambdaProxyClassDictionary::write_dictionary(is_static_archive);
1338 } else {
1339 LambdaProxyClassDictionary::reset_dictionary(is_static_archive);
1340 }
1341 }
1342
1343 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1344 bool is_static_archive) {
1345 ArchiveInfo* archive = get_archive(is_static_archive);
1346
1347 archive->_builtin_dictionary.serialize_header(soc);
1348 archive->_unregistered_dictionary.serialize_header(soc);
1349 LambdaProxyClassDictionary::serialize(soc, is_static_archive);
1350 }
1351
1352 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1353 for (auto id : EnumRange<vmClassID>{}) {
1354 soc->do_ptr(vmClasses::klass_addr_at(id));
1355 }
1356 }
1357
1358 const RunTimeClassInfo*
1359 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1360 if (!CDSConfig::is_using_archive() || !name->in_aot_cache()) {
1361 // The names of all shared classes must also be a shared Symbol.
1362 return nullptr;
1363 }
1364
1365 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1366 const RunTimeClassInfo* record = nullptr;
1367 if (DynamicArchive::is_mapped()) {
1368 // Use the regenerated holder classes in the dynamic archive as they
1369 // have more methods than those in the base archive.
1370 if (LambdaFormInvokers::may_be_regenerated_class(name)) {
1371 record = dynamic_dict->lookup(name, hash, 0);
1372 if (record != nullptr) {
1373 return record;
1374 }
1375 }
1376 }
1377
1378 if (!AOTMetaspace::in_aot_cache_dynamic_region(name)) {
1379 // The names of all shared classes in the static dict must also be in the
1380 // static archive
1381 record = static_dict->lookup(name, hash, 0);
1382 }
1383
1384 if (record == nullptr && DynamicArchive::is_mapped()) {
1385 record = dynamic_dict->lookup(name, hash, 0);
1386 }
1387
1388 return record;
1389 }
1390
1391 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1392 const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1393 &_dynamic_archive._builtin_dictionary,
1394 name);
1395 if (record != nullptr) {
1396 assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name");
1397 DEBUG_ONLY(check_klass_after_loading(record->klass());)
1398 // We did not save the classfile data of the generated LambdaForm invoker classes,
1399 // so we cannot support CLFH for such classes.
1400 if (record->klass()->is_aot_generated_class() && JvmtiExport::should_post_class_file_load_hook()) {
1401 return nullptr;
1402 }
1403 return record->klass();
1404 } else {
1405 return nullptr;
1406 }
1407 }
1408
1409 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1410 assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1411 DumpTimeClassInfo* info = get_info(k);
1412 info->_id = id;
1413 }
1414
1415 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) {
1416 assert(k != nullptr, "Sanity");
1417 assert(k->in_aot_cache(), "Must be");
1418 assert(k->is_instance_klass(), "Must be");
1419 InstanceKlass* ik = InstanceKlass::cast(k);
1420 if (ik->defined_by_boot_loader()) {
1421 return "boot_loader";
1422 } else if (ik->defined_by_platform_loader()) {
1423 return "platform_loader";
1424 } else if (ik->defined_by_app_loader()) {
1425 return "app_loader";
1426 } else if (ik->defined_by_other_loaders()) {
1427 return "unregistered_loader";
1428 } else {
1429 return "unknown loader";
1430 }
1431 }
1432
1433 void SystemDictionaryShared::get_all_archived_classes(bool is_static_archive, GrowableArray<Klass*>* classes) {
1434 get_archive(is_static_archive)->_builtin_dictionary.iterate([&] (const RunTimeClassInfo* record) {
1435 classes->append(record->klass());
1436 });
1437
1438 get_archive(is_static_archive)->_unregistered_dictionary.iterate([&] (const RunTimeClassInfo* record) {
1439 classes->append(record->klass());
1440 });
1441 }
1442
1443 class SharedDictionaryPrinter : StackObj {
1444 outputStream* _st;
1445 int _index;
1446 public:
1447 SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1448
1449 void do_value(const RunTimeClassInfo* record) {
1450 ResourceMark rm;
1451 _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(),
1452 SystemDictionaryShared::loader_type_for_shared_class(record->klass()));
1453 if (record->klass()->array_klasses() != nullptr) {
1454 record->klass()->array_klasses()->cds_print_value_on(_st);
1455 _st->cr();
1456 }
1457 }
1458 int index() const { return _index; }
1459 };
1460
1461 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1462 outputStream* st,
1463 bool is_static_archive) {
1464 st->print_cr("%sShared Dictionary", prefix);
1465 SharedDictionaryPrinter p(st);
1466 st->print_cr("%sShared Builtin Dictionary", prefix);
1467 _builtin_dictionary.iterate(&p);
1468 st->print_cr("%sShared Unregistered Dictionary", prefix);
1469 _unregistered_dictionary.iterate(&p);
1470 LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive);
1471 }
1472
1473 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1474 outputStream* st,
1475 bool is_static_archive) {
1476 st->print_cr("%sArchve Statistics", prefix);
1477 _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1478 _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1479 LambdaProxyClassDictionary::print_statistics(st, is_static_archive);
1480 }
1481
1482 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1483 if (CDSConfig::is_using_archive()) {
1484 if (is_static) {
1485 _static_archive.print_on("", st, true);
1486 } else {
1487 if (DynamicArchive::is_mapped()) {
1488 _dynamic_archive.print_on("Dynamic ", st, false);
1489 }
1490 }
1491 }
1492 }
1493
1494 void SystemDictionaryShared::print_on(outputStream* st) {
1495 print_shared_archive(st, true);
1496 print_shared_archive(st, false);
1497 }
1498
1499 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1500 if (CDSConfig::is_using_archive()) {
1501 _static_archive.print_table_statistics("Static ", st, true);
1502 if (DynamicArchive::is_mapped()) {
1503 _dynamic_archive.print_table_statistics("Dynamic ", st, false);
1504 }
1505 }
1506 }
1507
1508 bool SystemDictionaryShared::is_dumptime_table_empty() {
1509 assert_lock_strong(DumpTimeTable_lock);
1510 _dumptime_table->update_counts();
1511 if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1512 return true;
1513 }
1514 return false;
1515 }