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