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