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