1 /*
  2  * Copyright (c) 2022, 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 #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/stringTable.hpp"
 32 #include "classfile/symbolTable.hpp"
 33 #include "classfile/systemDictionary.hpp"
 34 #include "classfile/systemDictionaryShared.hpp"
 35 #include "classfile/vmSymbols.hpp"
 36 #include "logging/log.hpp"
 37 #include "logging/logStream.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/fieldStreams.inline.hpp"
 40 #include "oops/klass.inline.hpp"
 41 #include "oops/oop.inline.hpp"
 42 #include "oops/oopCast.inline.hpp"
 43 #include "oops/oopHandle.inline.hpp"
 44 #include "runtime/fieldDescriptor.inline.hpp"
 45 
 46 #if INCLUDE_CDS_JAVA_HEAP
 47 
 48 // CDSHeapVerifier is used to check for problems where an archived object references a
 49 // static field that may be get a different value at runtime.
 50 //
 51 // *Please see comments in aotClassInitializer.cpp for how to avoid such problems*,
 52 //
 53 // In the following example,
 54 //      Foo.get.test()
 55 // correctly returns true when CDS disabled, but incorrectly returns false when CDS is enabled,
 56 // because the archived archivedFoo.bar value is different than Bar.bar.
 57 //
 58 // class Foo {
 59 //     static final Foo archivedFoo; // this field is archived by CDS
 60 //     Bar bar;
 61 //     static {
 62 //         CDS.initializeFromArchive(Foo.class);
 63 //         if (archivedFoo == null) {
 64 //             archivedFoo = new Foo();
 65 //             archivedFoo.bar = Bar.bar;
 66 //         }
 67 //     }
 68 //     static Foo get() { return archivedFoo; }
 69 //     boolean test() {
 70 //         return bar == Bar.bar;
 71 //     }
 72 // }
 73 //
 74 // class Bar {
 75 //     // this field is initialized in both CDS dump time and runtime.
 76 //     static final Bar bar = new Bar();
 77 // }
 78 //
 79 // The check itself is simple:
 80 // [1] CDSHeapVerifier::do_klass() collects all static fields
 81 // [2] CDSHeapVerifier::do_entry() checks all the archived objects. None of them
 82 //     should be in [1]
 83 //
 84 // However, it's legal for *some* static fields to be referenced. The reasons are explained
 85 // in the table of ADD_EXCL below.
 86 //
 87 // [A] In most of the cases, the module bootstrap code will update the static field
 88 //     to point to part of the archived module graph. E.g.,
 89 //     - java/lang/System::bootLayer
 90 //     - jdk/internal/loader/ClassLoaders::BOOT_LOADER
 91 // [B] A final static String that's explicitly initialized inside <clinit>, but
 92 //     its value is deterministic and is always the same string literal.
 93 // [C] A non-final static string that is assigned a string literal during class
 94 //     initialization; this string is never changed during -Xshare:dump.
 95 // [D] Simple caches whose value doesn't matter.
 96 // [E] Other cases (see comments in-line below).
 97 //
 98 // LIMITATION:
 99 //
100 // CDSHeapVerifier can only check for problems with object identity. In the example above,
101 // if the Bar type has identity, the program's correctness requires that the identity
102 // of Foo.bar and Bar.bar to be equal. This requirement can be checked by CDSHeapVerifier.
103 //
104 // However, if Bar does not have identity (e.g., it's a value class, or is a primitive type),
105 // the program's correctness no longer requires that the identity of Foo.bar and Bar.bar
106 // to be equal (since they don't have an identity anymore). While the program's
107 // correctness may still have certain assumptions about Foo.bar and Bar.bar (such as the
108 // internal fields of these two values), such assumptions cannot be checked by CDSHeapVerifier.
109 
110 CDSHeapVerifier::CDSHeapVerifier() : _archived_objs(0), _problems(0)
111 {
112 # define ADD_EXCL(...) { static const char* e[] = {__VA_ARGS__, nullptr}; add_exclusion(e); }
113 
114   // Unfortunately this needs to be manually maintained. If
115   // test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchivedEnumTest.java fails,
116   // you might need to fix the core library code, or fix the ADD_EXCL entries below.
117   //
118   //       class                                         field                     type
119   ADD_EXCL("java/lang/ClassLoader$Holder",               "scl");                   // A
120   ADD_EXCL("java/lang/Module",                           "ALL_UNNAMED_MODULE",     // A
121                                                          "ALL_UNNAMED_MODULE_SET", // A
122                                                          "EVERYONE_MODULE",        // A
123                                                          "EVERYONE_SET");          // A
124 
125   // This is the same as java/util/ImmutableCollections::EMPTY_SET, which is archived
126   ADD_EXCL("java/lang/reflect/AccessFlag$Location",      "EMPTY_SET");             // E
127 
128   ADD_EXCL("java/lang/System",                           "bootLayer");             // A
129 
130   ADD_EXCL("java/util/Collections",                      "EMPTY_LIST");            // E
131 
132   // A dummy object used by HashSet. The value doesn't matter and it's never
133   // tested for equality.
134   ADD_EXCL("java/util/HashSet",                          "PRESENT");               // E
135 
136   ADD_EXCL("jdk/internal/loader/BootLoader",             "UNNAMED_MODULE");        // A
137   ADD_EXCL("jdk/internal/loader/BuiltinClassLoader",     "packageToModule");       // A
138   ADD_EXCL("jdk/internal/loader/ClassLoaders",           "BOOT_LOADER",            // A
139                                                          "APP_LOADER",             // A
140                                                          "PLATFORM_LOADER");       // A
141   ADD_EXCL("jdk/internal/module/Builder",                "cachedVersion");         // D
142   ADD_EXCL("jdk/internal/module/ModuleLoaderMap$Mapper", "APP_CLASSLOADER",        // A
143                                                          "APP_LOADER_INDEX",       // A
144                                                          "PLATFORM_CLASSLOADER",   // A
145                                                          "PLATFORM_LOADER_INDEX"); // A
146   ADD_EXCL("jdk/internal/module/ServicesCatalog",        "CLV");                   // A
147 
148   // This just points to an empty Map
149   ADD_EXCL("jdk/internal/reflect/Reflection",            "methodFilterMap");       // E
150 
151   // Integer for 0 and 1 are in java/lang/Integer$IntegerCache and are archived
152   ADD_EXCL("sun/invoke/util/ValueConversions",           "ONE_INT",                // E
153                                                          "ZERO_INT");              // E
154 
155   if (CDSConfig::is_dumping_method_handles()) {
156     ADD_EXCL("java/lang/invoke/InvokerBytecodeGenerator", "MEMBERNAME_FACTORY",    // D
157                                                           "CD_Object_array",       // E same as <...>ConstantUtils.CD_Object_array::CD_Object
158                                                           "INVOKER_SUPER_DESC");   // E same as java.lang.constant.ConstantDescs::CD_Object
159 
160     ADD_EXCL("java/lang/runtime/ObjectMethods",           "CLASS_IS_INSTANCE",     // D
161                                                           "FALSE",                 // D
162                                                           "TRUE",                  // D
163                                                           "ZERO");                 // D
164   }
165 
166   if (CDSConfig::is_dumping_aot_linked_classes()) {
167     ADD_EXCL("java/lang/Package$VersionInfo",             "NULL_VERSION_INFO");    // D
168   }
169 
170 # undef ADD_EXCL
171 
172   if (CDSConfig::is_dumping_aot_linked_classes()) {
173     add_shared_secret_accessors();
174   }
175   ClassLoaderDataGraph::classes_do(this);
176 }
177 
178 // We allow only "stateless" accessors in the SharedSecrets class to be AOT-initialized, for example,
179 // in the following pattern:
180 //
181 // class URL {
182 //     static {
183 //         SharedSecrets.setJavaNetURLAccess(
184 //              new JavaNetURLAccess() { ... });
185 //     }
186 //
187 // This initializes the field SharedSecrets::javaNetUriAccess, whose type (the inner case in the
188 // above example) has no fields (static or otherwise) and is not a hidden class, so it cannot possibly
189 // capture any transient state from the assembly phase that might become invalid in the production run.
190 //
191 class CDSHeapVerifier::SharedSecretsAccessorFinder : public FieldClosure {
192   CDSHeapVerifier* _verifier;
193   InstanceKlass* _ik;
194 public:
195   SharedSecretsAccessorFinder(CDSHeapVerifier* verifier, InstanceKlass* ik)
196     : _verifier(verifier), _ik(ik) {}
197 
198   void do_field(fieldDescriptor* fd) {
199     if (fd->field_type() == T_OBJECT) {
200       oop static_obj_field = _ik->java_mirror()->obj_field(fd->offset());
201       if (static_obj_field != nullptr) {
202         Klass* field_type = static_obj_field->klass();
203 
204         if (!field_type->is_instance_klass()) {
205           ResourceMark rm;
206           log_error(aot, heap)("jdk.internal.access.SharedSecrets::%s must not be an array",
207                                fd->name()->as_C_string());
208           AOTMetaspace::unrecoverable_writing_error();
209         }
210 
211         InstanceKlass* field_type_ik = InstanceKlass::cast(field_type);
212         if (has_any_fields(field_type_ik) || field_type_ik->is_hidden()) {
213           // If field_type_ik is a hidden class, the accessor is probably initialized using a
214           // Lambda, which may contain transient states.
215           ResourceMark rm;
216           log_error(aot, heap)("jdk.internal.access.SharedSecrets::%s (%s) must be stateless",
217                                fd->name()->as_C_string(), field_type_ik->external_name());
218           AOTMetaspace::unrecoverable_writing_error();
219         }
220 
221         _verifier->add_shared_secret_accessor(static_obj_field);
222       }
223     }
224   }
225 
226   // Does k (or any of its supertypes) have at least one (static or non-static) field?
227   static bool has_any_fields(InstanceKlass* k) {
228     if (k->static_field_size() != 0 || k->nonstatic_field_size() != 0) {
229       return true;
230     }
231 
232     if (k->super() != nullptr && has_any_fields(k->super())) {
233       return true;
234     }
235 
236     Array<InstanceKlass*>* interfaces = k->local_interfaces();
237     int num_interfaces = interfaces->length();
238     for (int index = 0; index < num_interfaces; index++) {
239       if (has_any_fields(interfaces->at(index))) {
240         return true;
241       }
242     }
243 
244     return false;
245   }
246 };
247 
248 // This function is for allowing the following pattern in the core libraries:
249 //
250 //     public class URLClassPath {
251 //          private static final JavaNetURLAccess JNUA = SharedSecrets.getJavaNetURLAccess();
252 //
253 // SharedSecrets::javaNetUriAccess has no states so it can be safely AOT-initialized. During
254 // the production run, even if URLClassPath.<clinit> is re-executed, it will get back the same
255 // instance of javaNetUriAccess as it did during the assembly phase.
256 //
257 // Note: this will forbid complex accessors such as SharedSecrets::javaObjectInputFilterAccess
258 // to be initialized during the AOT assembly phase.
259 void CDSHeapVerifier::add_shared_secret_accessors() {
260   TempNewSymbol klass_name = SymbolTable::new_symbol("jdk/internal/access/SharedSecrets");
261   InstanceKlass* ik = SystemDictionary::find_instance_klass(Thread::current(), klass_name,
262                                                            Handle());
263   assert(ik != nullptr, "must have been loaded");
264 
265   SharedSecretsAccessorFinder finder(this, ik);
266   ik->do_local_static_fields(&finder);
267 }
268 
269 CDSHeapVerifier::~CDSHeapVerifier() {
270   if (_problems > 0) {
271     log_error(aot, heap)("Scanned %zu objects. Found %d case(s) where "
272                          "an object points to a static field that "
273                          "may hold a different value at runtime.", _archived_objs, _problems);
274     log_error(aot, heap)("Please see cdsHeapVerifier.cpp and aotClassInitializer.cpp for details");
275     AOTMetaspace::unrecoverable_writing_error();
276   }
277 }
278 
279 class CDSHeapVerifier::CheckStaticFields : public FieldClosure {
280   CDSHeapVerifier* _verifier;
281   InstanceKlass* _ik; // The class whose static fields are being checked.
282   const char** _exclusions;
283 public:
284   CheckStaticFields(CDSHeapVerifier* verifier, InstanceKlass* ik)
285     : _verifier(verifier), _ik(ik) {
286     _exclusions = _verifier->find_exclusion(_ik);
287   }
288 
289   void do_field(fieldDescriptor* fd) {
290     if (fd->field_type() != T_OBJECT) {
291       return;
292     }
293 
294     oop static_obj_field = _ik->java_mirror()->obj_field(fd->offset());
295     if (static_obj_field != nullptr) {
296       if (_verifier->is_shared_secret_accessor(static_obj_field)) {
297         return;
298       }
299 
300       Klass* field_type = static_obj_field->klass();
301       if (_exclusions != nullptr) {
302         for (const char** p = _exclusions; *p != nullptr; p++) {
303           if (fd->name()->equals(*p)) {
304             return;
305           }
306         }
307       }
308 
309       if (!field_type->is_identity_class()) {
310         // See comment of LIMITATION above
311         // Any concrete value class will have a field ".null_reset" which holds an
312         // all-zero instance of the value class so it will not change between
313         // dump time and runtime.
314         return;
315       }
316 
317       if (fd->is_final() && java_lang_String::is_instance(static_obj_field) && fd->has_initial_value()) {
318         // This field looks like like this in the Java source:
319         //    static final SOME_STRING = "a string literal";
320         // This string literal has been stored in the shared string table, so it's OK
321         // for the archived objects to refer to it.
322         return;
323       }
324       if (fd->is_final() && java_lang_Class::is_instance(static_obj_field)) {
325         // This field points to an archived mirror.
326         return;
327       }
328 
329       if (field_type->is_instance_klass()) {
330         InstanceKlass* field_ik = InstanceKlass::cast(field_type);
331         if (field_ik->is_enum_subclass()) {
332           if (field_ik->has_archived_enum_objs() || ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
333             // This field is an Enum. If any instance of this Enum has been archived, we will archive
334             // all static fields of this Enum as well.
335             return;
336           }
337         }
338 
339         if (field_ik->is_hidden() && ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
340           // We have a static field in a core-library class that points to a method reference, which
341           // are safe to archive.
342           guarantee(_ik->module()->name() == vmSymbols::java_base(), "sanity");
343           return;
344         }
345 
346         if (field_ik == vmClasses::MethodType_klass()) {
347           // The identity of MethodTypes are preserved between assembly phase and production runs
348           // (by MethodType::AOTHolder::archivedMethodTypes). No need to check.
349           return;
350         }
351 
352         if (ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
353           if (field_ik == vmClasses::internal_Unsafe_klass()) {
354             // There's only a single instance of jdk/internal/misc/Unsafe, so all references will
355             // be pointing to this singleton, which has been archived.
356             return;
357           }
358           if (field_ik == vmClasses::Boolean_klass()) {
359             // TODO: check if is TRUE or FALSE
360             return;
361           }
362         }
363       }
364 
365       // This field *may* be initialized to a different value at runtime. Remember it
366       // and check later if it appears in the archived object graph.
367       _verifier->add_static_obj_field(_ik, static_obj_field, fd->name());
368     }
369   }
370 };
371 
372 // Remember all the static object fields of every class that are currently
373 // loaded. Later, we will check if any archived objects reference one of
374 // these fields.
375 void CDSHeapVerifier::do_klass(Klass* k) {
376   if (k->is_instance_klass()) {
377     InstanceKlass* ik = InstanceKlass::cast(k);
378 
379     if (HeapShared::is_subgraph_root_class(ik)) {
380       // ik is inside one of the ArchivableStaticFieldInfo tables
381       // in heapShared.cpp. We assume such classes are programmed to
382       // update their static fields correctly at runtime.
383       return;
384     }
385 
386     if (ArchiveUtils::has_aot_initialized_mirror(ik)) {
387       // ik's <clinit> won't be executed at runtime, the static fields in
388       // ik will carry their values to runtime.
389       return;
390     }
391 
392     CheckStaticFields csf(this, ik);
393     ik->do_local_static_fields(&csf);
394   }
395 }
396 
397 void CDSHeapVerifier::add_static_obj_field(InstanceKlass* ik, oop field, Symbol* name) {
398   StaticFieldInfo info = {ik, name};
399   _table.put(field, info);
400 }
401 
402 // This function is called once for every archived heap object. Warn if this object is referenced by
403 // a static field of a class that's not aot-initialized.
404 inline bool CDSHeapVerifier::do_entry(OopHandle& orig_obj_handle, HeapShared::CachedOopInfo& value) {
405   oop orig_obj = orig_obj_handle.resolve();
406   _archived_objs++;
407 
408   if (java_lang_String::is_instance(orig_obj) && HeapShared::is_dumped_interned_string(orig_obj)) {
409     // It's quite often for static fields to have interned strings. These are most likely not
410     // problematic (and are hard to filter). So we will ignore them.
411     return true;
412   }
413 
414   StaticFieldInfo* info = _table.get(orig_obj);
415   if (info != nullptr) {
416     ResourceMark rm;
417     char* class_name = info->_holder->name()->as_C_string();
418     char* field_name = info->_name->as_C_string();
419     LogStream ls(Log(aot, heap)::warning());
420     ls.print_cr("Archive heap points to a static field that may hold a different value at runtime:");
421     ls.print_cr("Field: %s::%s", class_name, field_name);
422     ls.print("Value: ");
423     orig_obj->print_on(&ls);
424     ls.print_cr("--- trace begin ---");
425     trace_to_root(&ls, orig_obj, nullptr, &value);
426     ls.print_cr("--- trace end ---");
427     ls.cr();
428     _problems ++;
429   }
430 
431   return true; /* keep on iterating */
432 }
433 
434 class CDSHeapVerifier::TraceFields : public FieldClosure {
435   oop _orig_obj;
436   oop _orig_field;
437   outputStream* _st;
438 
439 public:
440   TraceFields(oop orig_obj, oop orig_field, outputStream* st)
441     : _orig_obj(orig_obj), _orig_field(orig_field), _st(st) {}
442 
443   void do_field(fieldDescriptor* fd) {
444     if (fd->field_type() == T_OBJECT || fd->field_type() == T_ARRAY) {
445       oop obj_field = _orig_obj->obj_field(fd->offset());
446       if (obj_field == _orig_field) {
447         _st->print("::%s (offset = %d)", fd->name()->as_C_string(), fd->offset());
448       }
449     }
450   }
451 };
452 
453 // Call this function (from gdb, etc) if you want to know why an object is archived.
454 void CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj) {
455   HeapShared::CachedOopInfo* info = HeapShared::get_cached_oop_info(orig_obj);
456   if (info != nullptr) {
457     trace_to_root(st, orig_obj, nullptr, info);
458   } else {
459     st->print_cr("Not an archived object??");
460   }
461 }
462 
463 const char* static_field_name(oop mirror, oop field) {
464   Klass* k = java_lang_Class::as_Klass(mirror);
465   if (k->is_instance_klass()) {
466     for (JavaFieldStream fs(InstanceKlass::cast(k)); !fs.done(); fs.next()) {
467       if (fs.access_flags().is_static()) {
468         fieldDescriptor& fd = fs.field_descriptor();
469         switch (fd.field_type()) {
470         case T_OBJECT:
471         case T_ARRAY:
472           if (mirror->obj_field(fd.offset()) == field) {
473             return fs.name()->as_C_string();
474           }
475           break;
476         default:
477           break;
478         }
479       }
480     }
481   }
482 
483   return "<unknown>";
484 }
485 
486 int CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj, oop orig_field, HeapShared::CachedOopInfo* info) {
487   int level = 0;
488   if (info->orig_referrer() != nullptr) {
489     HeapShared::CachedOopInfo* ref = HeapShared::get_cached_oop_info(info->orig_referrer());
490     assert(ref != nullptr, "sanity");
491     level = trace_to_root(st, info->orig_referrer(), orig_obj, ref) + 1;
492   } else if (java_lang_String::is_instance(orig_obj)) {
493     st->print_cr("[%2d] (shared string table)", level++);
494   }
495   Klass* k = orig_obj->klass();
496   ResourceMark rm;
497   st->print("[%2d] ", level);
498   orig_obj->print_address_on(st);
499   st->print(" %s", k->internal_name());
500   if (java_lang_Class::is_instance(orig_obj)) {
501     st->print(" (%s::%s)", java_lang_Class::as_Klass(orig_obj)->external_name(), static_field_name(orig_obj, orig_field));
502   }
503   if (orig_field != nullptr) {
504     if (k->is_instance_klass()) {
505       TraceFields clo(orig_obj, orig_field, st);
506       InstanceKlass::cast(k)->do_nonstatic_fields(&clo);
507     } else {
508       assert(orig_obj->is_refArray(), "must be");
509       refArrayOop array = oop_cast<refArrayOop>(orig_obj);
510       for (int i = 0; i < array->length(); i++) {
511         if (array->obj_at(i) == orig_field) {
512           st->print(" @[%d]", i);
513           break;
514         }
515       }
516     }
517   }
518   st->cr();
519 
520   return level;
521 }
522 
523 void CDSHeapVerifier::verify() {
524   CDSHeapVerifier verf;
525   HeapShared::archived_object_cache()->iterate(&verf);
526 }
527 
528 #endif // INCLUDE_CDS_JAVA_HEAP