1 /*
2 * Copyright (c) 2022, 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 #include "cds/aotClassInitializer.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/cdsHeapVerifier.hpp"
28 #include "classfile/classLoaderDataGraph.hpp"
29 #include "classfile/javaClasses.inline.hpp"
30 #include "classfile/moduleEntry.hpp"
31 #include "classfile/systemDictionaryShared.hpp"
32 #include "classfile/vmSymbols.hpp"
33 #include "logging/log.hpp"
34 #include "logging/logStream.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "oops/fieldStreams.inline.hpp"
37 #include "oops/klass.inline.hpp"
38 #include "oops/oop.inline.hpp"
39 #include "oops/oopHandle.inline.hpp"
40 #include "runtime/fieldDescriptor.inline.hpp"
41
42 #if INCLUDE_CDS_JAVA_HEAP
43
44 // CDSHeapVerifier is used to check for problems where an archived object references a
45 // static field that may be get a different value at runtime.
46 //
47 // *Please see comments in aotClassInitializer.cpp for how to avoid such problems*,
48 //
49 // In the following example,
50 // Foo.get.test()
51 // correctly returns true when CDS disabled, but incorrectly returns false when CDS is enabled,
52 // because the archived archivedFoo.bar value is different than Bar.bar.
53 //
54 // class Foo {
55 // static final Foo archivedFoo; // this field is archived by CDS
56 // Bar bar;
57 // static {
58 // CDS.initializeFromArchive(Foo.class);
59 // if (archivedFoo == null) {
60 // archivedFoo = new Foo();
61 // archivedFoo.bar = Bar.bar;
62 // }
63 // }
64 // static Foo get() { return archivedFoo; }
65 // boolean test() {
66 // return bar == Bar.bar;
67 // }
68 // }
69 //
70 // class Bar {
71 // // this field is initialized in both CDS dump time and runtime.
72 // static final Bar bar = new Bar();
73 // }
74 //
75 // The check itself is simple:
76 // [1] CDSHeapVerifier::do_klass() collects all static fields
77 // [2] CDSHeapVerifier::do_entry() checks all the archived objects. None of them
78 // should be in [1]
79 //
80 // However, it's legal for *some* static fields to be referenced. The reasons are explained
81 // in the table of ADD_EXCL below.
82 //
83 // [A] In most of the cases, the module bootstrap code will update the static field
84 // to point to part of the archived module graph. E.g.,
85 // - java/lang/System::bootLayer
86 // - jdk/internal/loader/ClassLoaders::BOOT_LOADER
87 // [B] A final static String that's explicitly initialized inside <clinit>, but
88 // its value is deterministic and is always the same string literal.
89 // [C] A non-final static string that is assigned a string literal during class
90 // initialization; this string is never changed during -Xshare:dump.
91 // [D] Simple caches whose value doesn't matter.
92 // [E] Other cases (see comments in-line below).
93
94 CDSHeapVerifier::CDSHeapVerifier() : _archived_objs(0), _problems(0)
95 {
96 # define ADD_EXCL(...) { static const char* e[] = {__VA_ARGS__, nullptr}; add_exclusion(e); }
97
98 // Unfortunately this needs to be manually maintained. If
99 // test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchivedEnumTest.java fails,
100 // you might need to fix the core library code, or fix the ADD_EXCL entries below.
101 //
102 // class field type
103 ADD_EXCL("java/lang/ClassLoader$Holder", "scl"); // A
104 ADD_EXCL("java/lang/Module", "ALL_UNNAMED_MODULE", // A
105 "ALL_UNNAMED_MODULE_SET", // A
106 "EVERYONE_MODULE", // A
107 "EVERYONE_SET"); // A
108
109 // This is the same as java/util/ImmutableCollections::EMPTY_SET, which is archived
110 ADD_EXCL("java/lang/reflect/AccessFlag$Location", "EMPTY_SET"); // E
111
112 ADD_EXCL("java/lang/System", "bootLayer"); // A
113
114 ADD_EXCL("java/util/Collections", "EMPTY_LIST"); // E
115
116 // A dummy object used by HashSet. The value doesn't matter and it's never
117 // tested for equality.
118 ADD_EXCL("java/util/HashSet", "PRESENT"); // E
119
120 ADD_EXCL("jdk/internal/loader/BootLoader", "UNNAMED_MODULE"); // A
121 ADD_EXCL("jdk/internal/loader/BuiltinClassLoader", "packageToModule"); // A
122 ADD_EXCL("jdk/internal/loader/ClassLoaders", "BOOT_LOADER", // A
123 "APP_LOADER", // A
124 "PLATFORM_LOADER"); // A
125 ADD_EXCL("jdk/internal/module/Builder", "cachedVersion"); // D
126 ADD_EXCL("jdk/internal/module/ModuleLoaderMap$Mapper", "APP_CLASSLOADER", // A
127 "APP_LOADER_INDEX", // A
128 "PLATFORM_CLASSLOADER", // A
129 "PLATFORM_LOADER_INDEX"); // A
130 ADD_EXCL("jdk/internal/module/ServicesCatalog", "CLV"); // A
131
132 // This just points to an empty Map
133 ADD_EXCL("jdk/internal/reflect/Reflection", "methodFilterMap"); // E
134
135 // Integer for 0 and 1 are in java/lang/Integer$IntegerCache and are archived
136 ADD_EXCL("sun/invoke/util/ValueConversions", "ONE_INT", // E
137 "ZERO_INT"); // E
138
139 if (CDSConfig::is_dumping_method_handles()) {
140 ADD_EXCL("java/lang/invoke/InvokerBytecodeGenerator", "MEMBERNAME_FACTORY", // D
141 "CD_Object_array", // E same as <...>ConstantUtils.CD_Object_array::CD_Object
142 "INVOKER_SUPER_DESC"); // E same as java.lang.constant.ConstantDescs::CD_Object
143
144 ADD_EXCL("java/lang/runtime/ObjectMethods", "CLASS_IS_INSTANCE", // D
145 "FALSE", // D
146 "TRUE", // D
147 "ZERO"); // D
148 }
149
150 if (CDSConfig::is_dumping_aot_linked_classes()) {
151 ADD_EXCL("java/lang/Package$VersionInfo", "NULL_VERSION_INFO"); // D
152 }
153
154 if (CDSConfig::is_dumping_dynamic_proxies()) {
155 ADD_EXCL("java/lang/reflect/ProxyGenerator", "CD_Object_array"); // D
156 }
157
158 // These are used by BuiltinClassLoader::negativeLookupCache, etc but seem to be
159 // OK. TODO - we should completely disable the caching unless ArchiveLoaderLookupCache
160 // is enabled
161 ADD_EXCL("java/lang/Boolean", "TRUE", // E
162 "FALSE"); // E
163
164 # undef ADD_EXCL
165
166 ClassLoaderDataGraph::classes_do(this);
167 }
168
169 CDSHeapVerifier::~CDSHeapVerifier() {
170 if (_problems > 0) {
171 log_error(aot, heap)("Scanned %d objects. Found %d case(s) where "
172 "an object points to a static field that "
173 "may hold a different value at runtime.", _archived_objs, _problems);
174 log_error(aot, heap)("Please see cdsHeapVerifier.cpp and aotClassInitializer.cpp for details");
175 AOTMetaspace::unrecoverable_writing_error();
176 }
177 }
178
179 class CDSHeapVerifier::CheckStaticFields : public FieldClosure {
180 CDSHeapVerifier* _verifier;
181 InstanceKlass* _ik; // The class whose static fields are being checked.
182 const char** _exclusions;
183 public:
184 CheckStaticFields(CDSHeapVerifier* verifier, InstanceKlass* ik)
185 : _verifier(verifier), _ik(ik) {
186 _exclusions = _verifier->find_exclusion(_ik);
187 }
188
189 void do_field(fieldDescriptor* fd) {
190 if (fd->field_type() != T_OBJECT) {
191 return;
192 }
193
194 if (fd->signature()->equals("Ljdk/internal/access/JavaLangAccess;") ||
195 fd->signature()->equals("Ljdk/internal/access/JavaLangReflectAccess;")) {
196 // A few classes have static fields that point to SharedSecrets.get???Access().
197 // This object carries no state and we can create a new one in the production run.
198 return;
199 }
200 if (fd->signature()->equals("Ljdk/internal/reflect/ReflectionFactory;")) {
201 return;
202 }
203 oop static_obj_field = _ik->java_mirror()->obj_field(fd->offset());
204 if (static_obj_field != nullptr) {
205 Klass* field_type = static_obj_field->klass();
206 if (_exclusions != nullptr) {
207 for (const char** p = _exclusions; *p != nullptr; p++) {
208 if (fd->name()->equals(*p)) {
209 return;
210 }
211 }
212 }
213
214 if (fd->is_final() && java_lang_String::is_instance(static_obj_field) && fd->has_initial_value()) {
215 // This field looks like like this in the Java source:
216 // static final SOME_STRING = "a string literal";
217 // This string literal has been stored in the shared string table, so it's OK
218 // for the archived objects to refer to it.
219 return;
220 }
221 if (fd->is_final() && java_lang_Class::is_instance(static_obj_field)) {
222 // This field points to an archived mirror.
223 return;
224 }
225
226 if (field_type->is_instance_klass()) {
227 InstanceKlass* field_ik = InstanceKlass::cast(field_type);
228 if (field_ik->is_enum_subclass()) {
229 if (field_ik->has_archived_enum_objs() || ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
230 // This field is an Enum. If any instance of this Enum has been archived, we will archive
231 // all static fields of this Enum as well.
232 return;
233 }
234 }
235
236 if (field_ik->is_hidden() && ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
237 // We have a static field in a core-library class that points to a method reference, which
238 // are safe to archive.
239 guarantee(_ik->module()->name() == vmSymbols::java_base(), "sanity");
240 return;
241 }
242
243 if (field_ik == vmClasses::MethodType_klass()) {
244 // The identity of MethodTypes are preserved between assembly phase and production runs
245 // (by MethodType::AOTHolder::archivedMethodTypes). No need to check.
246 return;
247 }
248
249 if (ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
250 if (field_ik == vmClasses::internal_Unsafe_klass()) {
251 // There's only a single instance of jdk/internal/misc/Unsafe, so all references will
252 // be pointing to this singleton, which has been archived.
253 return;
254 }
255 if (field_ik == vmClasses::Boolean_klass()) {
256 // TODO: check if is TRUE or FALSE
257 return;
258 }
259 }
260 }
261
262 // This field *may* be initialized to a different value at runtime. Remember it
263 // and check later if it appears in the archived object graph.
264 _verifier->add_static_obj_field(_ik, static_obj_field, fd->name());
265 }
266 }
267 };
268
269 // Remember all the static object fields of every class that are currently
270 // loaded. Later, we will check if any archived objects reference one of
271 // these fields.
272 void CDSHeapVerifier::do_klass(Klass* k) {
273 if (k->is_instance_klass()) {
274 InstanceKlass* ik = InstanceKlass::cast(k);
275
276 if (HeapShared::is_subgraph_root_class(ik)) {
277 // ik is inside one of the ArchivableStaticFieldInfo tables
278 // in heapShared.cpp. We assume such classes are programmed to
279 // update their static fields correctly at runtime.
280 return;
281 }
282
283 if (ArchiveUtils::has_aot_initialized_mirror(ik)) {
284 // ik's <clinit> won't be executed at runtime, the static fields in
285 // ik will carry their values to runtime.
286 return;
287 }
288
289 CheckStaticFields csf(this, ik);
290 ik->do_local_static_fields(&csf);
291 }
292 }
293
294 void CDSHeapVerifier::add_static_obj_field(InstanceKlass* ik, oop field, Symbol* name) {
295 StaticFieldInfo info = {ik, name};
296 _table.put(field, info);
297 }
298
299 // This function is called once for every archived heap object. Warn if this object is referenced by
300 // a static field of a class that's not aot-initialized.
301 inline bool CDSHeapVerifier::do_entry(OopHandle& orig_obj_handle, HeapShared::CachedOopInfo& value) {
302 oop orig_obj = orig_obj_handle.resolve();
303 _archived_objs++;
304
305 if (java_lang_String::is_instance(orig_obj) && HeapShared::is_dumped_interned_string(orig_obj)) {
306 // It's quite often for static fields to have interned strings. These are most likely not
307 // problematic (and are hard to filter). So we will ignore them.
308 return true; /* keep on iterating */
309 }
310
311 StaticFieldInfo* info = _table.get(orig_obj);
312 if (info != nullptr) {
313 ResourceMark rm;
314 char* class_name = info->_holder->name()->as_C_string();
315 char* field_name = info->_name->as_C_string();
316 LogStream ls(Log(aot, heap)::warning());
317 ls.print_cr("Archive heap points to a static field that may hold a different value at runtime:");
318 ls.print_cr("Field: %s::%s", class_name, field_name);
319 ls.print("Value: ");
320 orig_obj->print_on(&ls);
321 ls.print_cr("--- trace begin ---");
322 trace_to_root(&ls, orig_obj, nullptr, &value);
323 ls.print_cr("--- trace end ---");
324 ls.cr();
325 _problems ++;
326 }
327
328 return true; /* keep on iterating */
329 }
330
331 class CDSHeapVerifier::TraceFields : public FieldClosure {
332 oop _orig_obj;
333 oop _orig_field;
334 outputStream* _st;
335
336 public:
337 TraceFields(oop orig_obj, oop orig_field, outputStream* st)
338 : _orig_obj(orig_obj), _orig_field(orig_field), _st(st) {}
339
340 void do_field(fieldDescriptor* fd) {
341 if (fd->field_type() == T_OBJECT || fd->field_type() == T_ARRAY) {
342 oop obj_field = _orig_obj->obj_field(fd->offset());
343 if (obj_field == _orig_field) {
344 _st->print("::%s (offset = %d)", fd->name()->as_C_string(), fd->offset());
345 }
346 }
347 }
348 };
349
350 // Call this function (from gdb, etc) if you want to know why an object is archived.
351 void CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj) {
352 HeapShared::CachedOopInfo* info = HeapShared::get_cached_oop_info(orig_obj);
353 if (info != nullptr) {
354 trace_to_root(st, orig_obj, nullptr, info);
355 } else {
356 st->print_cr("Not an archived object??");
357 }
358 }
359
360 const char* static_field_name(oop mirror, oop field) {
361 Klass* k = java_lang_Class::as_Klass(mirror);
362 if (k->is_instance_klass()) {
363 for (JavaFieldStream fs(InstanceKlass::cast(k)); !fs.done(); fs.next()) {
364 if (fs.access_flags().is_static()) {
365 fieldDescriptor& fd = fs.field_descriptor();
366 switch (fd.field_type()) {
367 case T_OBJECT:
368 case T_ARRAY:
369 if (mirror->obj_field(fd.offset()) == field) {
370 return fs.name()->as_C_string();
371 }
372 break;
373 default:
374 break;
375 }
376 }
377 }
378 }
379
380 return "<unknown>";
381 }
382
383 int CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj, oop orig_field, HeapShared::CachedOopInfo* info) {
384 int level = 0;
385 if (info->orig_referrer() != nullptr) {
386 HeapShared::CachedOopInfo* ref = HeapShared::get_cached_oop_info(info->orig_referrer());
387 assert(ref != nullptr, "sanity");
388 level = trace_to_root(st, info->orig_referrer(), orig_obj, ref) + 1;
389 } else if (java_lang_String::is_instance(orig_obj)) {
390 st->print_cr("[%2d] (shared string table)", level++);
391 }
392 Klass* k = orig_obj->klass();
393 ResourceMark rm;
394 st->print("[%2d] ", level);
395 orig_obj->print_address_on(st);
396 st->print(" %s", k->internal_name());
397 if (java_lang_Class::is_instance(orig_obj)) {
398 st->print(" (%s::%s)", java_lang_Class::as_Klass(orig_obj)->external_name(), static_field_name(orig_obj, orig_field));
399 }
400 if (orig_field != nullptr) {
401 if (k->is_instance_klass()) {
402 TraceFields clo(orig_obj, orig_field, st);
403 InstanceKlass::cast(k)->do_nonstatic_fields(&clo);
404 } else {
405 assert(orig_obj->is_objArray(), "must be");
406 objArrayOop array = (objArrayOop)orig_obj;
407 for (int i = 0; i < array->length(); i++) {
408 if (array->obj_at(i) == orig_field) {
409 st->print(" @[%d]", i);
410 break;
411 }
412 }
413 }
414 }
415 st->cr();
416
417 return level;
418 }
419
420 void CDSHeapVerifier::verify() {
421 CDSHeapVerifier verf;
422 HeapShared::archived_object_cache()->iterate(&verf);
423 }
424
425 #endif // INCLUDE_CDS_JAVA_HEAP