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