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   if (CDSConfig::is_dumping_dynamic_proxies()) {
158     ADD_EXCL("java/lang/reflect/ProxyGenerator",          "CD_Object_array");      // D
159   }
160 
161   // These are used by BuiltinClassLoader::negativeLookupCache, etc but seem to be
162   // OK. TODO - we should completely disable the caching unless ArchiveLoaderLookupCache
163   // is enabled
164   ADD_EXCL("java/lang/Boolean",                           "TRUE",                  // E
165                                                           "FALSE");                // E
166 
167 # undef ADD_EXCL
168 
169   if (CDSConfig::is_initing_classes_at_dump_time()) {
170     add_shared_secret_accessors();
171   }
172   ClassLoaderDataGraph::classes_do(this);
173 }
174 
175 // We allow only "stateless" accessors in the SharedSecrets class to be AOT-initialized, for example,
176 // in the following pattern:
177 //
178 // class URL {
179 //     static {
180 //         SharedSecrets.setJavaNetURLAccess(
181 //              new JavaNetURLAccess() { ... });
182 //     }
183 //
184 // This initializes the field SharedSecrets::javaNetUriAccess, whose type (the inner case in the
185 // above example) has no fields (static or otherwise) and is not a hidden class, so it cannot possibly
186 // capture any transient state from the assembly phase that might become invalid in the production run.
187 //
188 class CDSHeapVerifier::SharedSecretsAccessorFinder : public FieldClosure {
189   CDSHeapVerifier* _verifier;
190   InstanceKlass* _ik;
191 public:
192   SharedSecretsAccessorFinder(CDSHeapVerifier* verifier, InstanceKlass* ik)
193     : _verifier(verifier), _ik(ik) {}
194 
195   void do_field(fieldDescriptor* fd) {
196     if (fd->field_type() == T_OBJECT) {
197       oop static_obj_field = _ik->java_mirror()->obj_field(fd->offset());
198       if (static_obj_field != nullptr) {
199         Klass* field_type = static_obj_field->klass();
200 
201         if (!field_type->is_instance_klass()) {
202           ResourceMark rm;
203           log_error(aot, heap)("jdk.internal.access.SharedSecrets::%s must not be an array",
204                                fd->name()->as_C_string());
205           AOTMetaspace::unrecoverable_writing_error();
206         }
207 
208         InstanceKlass* field_type_ik = InstanceKlass::cast(field_type);
209         if (has_any_fields(field_type_ik) || field_type_ik->is_hidden()) {
210           // If field_type_ik is a hidden class, the accessor is probably initialized using a
211           // Lambda, which may contain transient states.
212           ResourceMark rm;
213           log_error(aot, heap)("jdk.internal.access.SharedSecrets::%s (%s) must be stateless",
214                                fd->name()->as_C_string(), field_type_ik->external_name());
215           AOTMetaspace::unrecoverable_writing_error();
216         }
217 
218         _verifier->add_shared_secret_accessor(static_obj_field);
219       }
220     }
221   }
222 
223   // Does k (or any of its supertypes) have at least one (static or non-static) field?
224   static bool has_any_fields(InstanceKlass* k) {
225     if (k->static_field_size() != 0 || k->nonstatic_field_size() != 0) {
226       return true;
227     }
228 
229     if (k->super() != nullptr && has_any_fields(k->super())) {
230       return true;
231     }
232 
233     Array<InstanceKlass*>* interfaces = k->local_interfaces();
234     int num_interfaces = interfaces->length();
235     for (int index = 0; index < num_interfaces; index++) {
236       if (has_any_fields(interfaces->at(index))) {
237         return true;
238       }
239     }
240 
241     return false;
242   }
243 };
244 
245 // This function is for allowing the following pattern in the core libraries:
246 //
247 //     public class URLClassPath {
248 //          private static final JavaNetURLAccess JNUA = SharedSecrets.getJavaNetURLAccess();
249 //
250 // SharedSecrets::javaNetUriAccess has no states so it can be safely AOT-initialized. During
251 // the production run, even if URLClassPath.<clinit> is re-executed, it will get back the same
252 // instance of javaNetUriAccess as it did during the assembly phase.
253 //
254 // Note: this will forbid complex accessors such as SharedSecrets::javaObjectInputFilterAccess
255 // to be initialized during the AOT assembly phase.
256 void CDSHeapVerifier::add_shared_secret_accessors() {
257   TempNewSymbol klass_name = SymbolTable::new_symbol("jdk/internal/access/SharedSecrets");
258   InstanceKlass* ik = SystemDictionary::find_instance_klass(Thread::current(), klass_name,
259                                                            Handle());
260   assert(ik != nullptr, "must have been loaded");
261 
262   SharedSecretsAccessorFinder finder(this, ik);
263   ik->do_local_static_fields(&finder);
264 }
265 
266 CDSHeapVerifier::~CDSHeapVerifier() {
267   if (_problems > 0) {
268     log_error(aot, heap)("Scanned %zu objects. Found %d case(s) where "
269                          "an object points to a static field that "
270                          "may hold a different value at runtime.", _archived_objs, _problems);
271     log_error(aot, heap)("Please see cdsHeapVerifier.cpp and aotClassInitializer.cpp for details");
272     AOTMetaspace::unrecoverable_writing_error();
273   }
274 }
275 
276 class CDSHeapVerifier::CheckStaticFields : public FieldClosure {
277   CDSHeapVerifier* _verifier;
278   InstanceKlass* _ik; // The class whose static fields are being checked.
279   const char** _exclusions;
280 public:
281   CheckStaticFields(CDSHeapVerifier* verifier, InstanceKlass* ik)
282     : _verifier(verifier), _ik(ik) {
283     _exclusions = _verifier->find_exclusion(_ik);
284   }
285 
286   void do_field(fieldDescriptor* fd) {
287     if (fd->field_type() != T_OBJECT) {
288       return;
289     }
290 
291     if (fd->signature()->equals("Ljdk/internal/reflect/ReflectionFactory;")) {
292       return;
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 (fd->is_final() && java_lang_String::is_instance(static_obj_field) && fd->has_initial_value()) {
310         // This field looks like like this in the Java source:
311         //    static final SOME_STRING = "a string literal";
312         // This string literal has been stored in the shared string table, so it's OK
313         // for the archived objects to refer to it.
314         return;
315       }
316       if (fd->is_final() && java_lang_Class::is_instance(static_obj_field)) {
317         // This field points to an archived mirror.
318         return;
319       }
320 
321       if (field_type->is_instance_klass()) {
322         InstanceKlass* field_ik = InstanceKlass::cast(field_type);
323         if (field_ik->is_enum_subclass()) {
324           if (field_ik->has_archived_enum_objs() || ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
325             // This field is an Enum. If any instance of this Enum has been archived, we will archive
326             // all static fields of this Enum as well.
327             return;
328           }
329         }
330 
331         if (field_ik->is_hidden() && ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
332           // We have a static field in a core-library class that points to a method reference, which
333           // are safe to archive.
334           guarantee(_ik->module()->name() == vmSymbols::java_base(), "sanity");
335           return;
336         }
337 
338         if (field_ik == vmClasses::MethodType_klass()) {
339           // The identity of MethodTypes are preserved between assembly phase and production runs
340           // (by MethodType::AOTHolder::archivedMethodTypes). No need to check.
341           return;
342         }
343 
344         if (ArchiveUtils::has_aot_initialized_mirror(field_ik)) {
345           if (field_ik == vmClasses::internal_Unsafe_klass()) {
346             // There's only a single instance of jdk/internal/misc/Unsafe, so all references will
347             // be pointing to this singleton, which has been archived.
348             return;
349           }
350           if (field_ik == vmClasses::Boolean_klass()) {
351             // TODO: check if is TRUE or FALSE
352             return;
353           }
354         }
355       }
356 
357       // This field *may* be initialized to a different value at runtime. Remember it
358       // and check later if it appears in the archived object graph.
359       _verifier->add_static_obj_field(_ik, static_obj_field, fd->name());
360     }
361   }
362 };
363 
364 // Remember all the static object fields of every class that are currently
365 // loaded. Later, we will check if any archived objects reference one of
366 // these fields.
367 void CDSHeapVerifier::do_klass(Klass* k) {
368   if (k->is_instance_klass()) {
369     InstanceKlass* ik = InstanceKlass::cast(k);
370 
371     if (HeapShared::is_subgraph_root_class(ik)) {
372       // ik is inside one of the ArchivableStaticFieldInfo tables
373       // in heapShared.cpp. We assume such classes are programmed to
374       // update their static fields correctly at runtime.
375       return;
376     }
377 
378     if (ArchiveUtils::has_aot_initialized_mirror(ik)) {
379       // ik's <clinit> won't be executed at runtime, the static fields in
380       // ik will carry their values to runtime.
381       return;
382     }
383 
384     CheckStaticFields csf(this, ik);
385     ik->do_local_static_fields(&csf);
386   }
387 }
388 
389 void CDSHeapVerifier::add_static_obj_field(InstanceKlass* ik, oop field, Symbol* name) {
390   StaticFieldInfo info = {ik, name};
391   _table.put(field, info);
392 }
393 
394 // This function is called once for every archived heap object. Warn if this object is referenced by
395 // a static field of a class that's not aot-initialized.
396 inline bool CDSHeapVerifier::do_entry(OopHandle& orig_obj_handle, HeapShared::CachedOopInfo& value) {
397   oop orig_obj = orig_obj_handle.resolve();
398   _archived_objs++;
399 
400   if (java_lang_String::is_instance(orig_obj) && HeapShared::is_dumped_interned_string(orig_obj)) {
401     // It's quite often for static fields to have interned strings. These are most likely not
402     // problematic (and are hard to filter). So we will ignore them.
403     return true;
404   }
405 
406   StaticFieldInfo* info = _table.get(orig_obj);
407   if (info != nullptr) {
408     ResourceMark rm;
409     char* class_name = info->_holder->name()->as_C_string();
410     char* field_name = info->_name->as_C_string();
411     LogStream ls(Log(aot, heap)::warning());
412     ls.print_cr("Archive heap points to a static field that may hold a different value at runtime:");
413     ls.print_cr("Field: %s::%s", class_name, field_name);
414     ls.print("Value: ");
415     orig_obj->print_on(&ls);
416     ls.print_cr("--- trace begin ---");
417     trace_to_root(&ls, orig_obj, nullptr, &value);
418     ls.print_cr("--- trace end ---");
419     ls.cr();
420     _problems ++;
421   }
422 
423   return true; /* keep on iterating */
424 }
425 
426 class CDSHeapVerifier::TraceFields : public FieldClosure {
427   oop _orig_obj;
428   oop _orig_field;
429   outputStream* _st;
430 
431 public:
432   TraceFields(oop orig_obj, oop orig_field, outputStream* st)
433     : _orig_obj(orig_obj), _orig_field(orig_field), _st(st) {}
434 
435   void do_field(fieldDescriptor* fd) {
436     if (fd->field_type() == T_OBJECT || fd->field_type() == T_ARRAY) {
437       oop obj_field = _orig_obj->obj_field(fd->offset());
438       if (obj_field == _orig_field) {
439         _st->print("::%s (offset = %d)", fd->name()->as_C_string(), fd->offset());
440       }
441     }
442   }
443 };
444 
445 // Call this function (from gdb, etc) if you want to know why an object is archived.
446 void CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj) {
447   HeapShared::CachedOopInfo* info = HeapShared::get_cached_oop_info(orig_obj);
448   if (info != nullptr) {
449     trace_to_root(st, orig_obj, nullptr, info);
450   } else {
451     st->print_cr("Not an archived object??");
452   }
453 }
454 
455 const char* static_field_name(oop mirror, oop field) {
456   Klass* k = java_lang_Class::as_Klass(mirror);
457   if (k->is_instance_klass()) {
458     for (JavaFieldStream fs(InstanceKlass::cast(k)); !fs.done(); fs.next()) {
459       if (fs.access_flags().is_static()) {
460         fieldDescriptor& fd = fs.field_descriptor();
461         switch (fd.field_type()) {
462         case T_OBJECT:
463         case T_ARRAY:
464           if (mirror->obj_field(fd.offset()) == field) {
465             return fs.name()->as_C_string();
466           }
467           break;
468         default:
469           break;
470         }
471       }
472     }
473   }
474 
475   return "<unknown>";
476 }
477 
478 int CDSHeapVerifier::trace_to_root(outputStream* st, oop orig_obj, oop orig_field, HeapShared::CachedOopInfo* info) {
479   int level = 0;
480   if (info->orig_referrer() != nullptr) {
481     HeapShared::CachedOopInfo* ref = HeapShared::get_cached_oop_info(info->orig_referrer());
482     assert(ref != nullptr, "sanity");
483     level = trace_to_root(st, info->orig_referrer(), orig_obj, ref) + 1;
484   } else if (java_lang_String::is_instance(orig_obj)) {
485     st->print_cr("[%2d] (shared string table)", level++);
486   }
487   Klass* k = orig_obj->klass();
488   ResourceMark rm;
489   st->print("[%2d] ", level);
490   orig_obj->print_address_on(st);
491   st->print(" %s", k->internal_name());
492   if (java_lang_Class::is_instance(orig_obj)) {
493     st->print(" (%s::%s)", java_lang_Class::as_Klass(orig_obj)->external_name(), static_field_name(orig_obj, orig_field));
494   }
495   if (orig_field != nullptr) {
496     if (k->is_instance_klass()) {
497       TraceFields clo(orig_obj, orig_field, st);
498       InstanceKlass::cast(k)->do_nonstatic_fields(&clo);
499     } else {
500       assert(orig_obj->is_objArray(), "must be");
501       objArrayOop array = (objArrayOop)orig_obj;
502       for (int i = 0; i < array->length(); i++) {
503         if (array->obj_at(i) == orig_field) {
504           st->print(" @[%d]", i);
505           break;
506         }
507       }
508     }
509   }
510   st->cr();
511 
512   return level;
513 }
514 
515 void CDSHeapVerifier::verify() {
516   CDSHeapVerifier verf;
517   HeapShared::archived_object_cache()->iterate(&verf);
518 }
519 
520 #endif // INCLUDE_CDS_JAVA_HEAP