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