< prev index next >

src/hotspot/share/cds/heapShared.cpp

Print this page
@@ -21,10 +21,11 @@
   * questions.
   *
   */
  
  #include "precompiled.hpp"
+ #include "cds/aotClassInitializer.hpp"
  #include "cds/archiveBuilder.hpp"
  #include "cds/archiveHeapLoader.hpp"
  #include "cds/archiveHeapWriter.hpp"
  #include "cds/archiveUtils.hpp"
  #include "cds/cdsConfig.hpp"

@@ -83,10 +84,31 @@
    bool valid() {
      return klass_name != nullptr;
    }
  };
  
+ class HeapShared::ArchivingObjectMark : public StackObj {
+ public:
+   ArchivingObjectMark(oop obj) {
+     _trace->push(obj);
+   }
+   ~ArchivingObjectMark() {
+     _trace->pop();
+   }
+ };
+ 
+ class HeapShared::ContextMark : public StackObj {
+   ResourceMark rm;
+ public:
+   ContextMark(const char* c) : rm{} {
+     _context->push(c);
+   }
+   ~ContextMark() {
+     _context->pop();
+   }
+ };
+ 
  bool HeapShared::_disable_writing = false;
  DumpedInternedStrings *HeapShared::_dumped_interned_strings = nullptr;
  
  size_t HeapShared::_alloc_count[HeapShared::ALLOC_STAT_SLOTS];
  size_t HeapShared::_alloc_size[HeapShared::ALLOC_STAT_SLOTS];

@@ -95,11 +117,11 @@
  
  #ifndef PRODUCT
  #define ARCHIVE_TEST_FIELD_NAME "archivedObjects"
  static Array<char>* _archived_ArchiveHeapTestClass = nullptr;
  static const char* _test_class_name = nullptr;
- static const Klass* _test_class = nullptr;
+ static Klass* _test_class = nullptr;
  static const ArchivedKlassSubGraphInfoRecord* _test_class_record = nullptr;
  #endif
  
  
  //

@@ -117,10 +139,12 @@
    {"jdk/internal/module/ArchivedModuleGraph",     "archivedModuleGraph"},
    {"java/util/ImmutableCollections",              "archivedObjects"},
    {"java/lang/ModuleLayer",                       "EMPTY_LAYER"},
    {"java/lang/module/Configuration",              "EMPTY_CONFIGURATION"},
    {"jdk/internal/math/FDBigInteger",              "archivedCaches"},
+   {"java/lang/reflect/Proxy$ProxyBuilder",        "archivedData"},    // FIXME -- requires AOTClassLinking
+ 
  #ifndef PRODUCT
    {nullptr, nullptr}, // Extra slot for -XX:ArchiveHeapTestClass
  #endif
    {nullptr, nullptr},
  };

@@ -132,11 +156,14 @@
    {"java/lang/Module$ArchivedData",               "archivedData"},
    {nullptr, nullptr},
  };
  
  KlassSubGraphInfo* HeapShared::_default_subgraph_info;
- GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = nullptr;
+ ArchivedKlassSubGraphInfoRecord* HeapShared::_runtime_default_subgraph_info;
+ GrowableArrayCHeap<OopHandle, mtClassShared>* HeapShared::_pending_roots = nullptr;
+ GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_trace = nullptr;
+ GrowableArrayCHeap<const char*, mtClassShared>* HeapShared::_context = nullptr;
  GrowableArrayCHeap<OopHandle, mtClassShared>* HeapShared::_root_segments;
  int HeapShared::_root_segment_max_size_elems;
  OopHandle HeapShared::_scratch_basic_type_mirrors[T_VOID+1];
  MetaspaceObjToOopHandleTable* HeapShared::_scratch_java_mirror_table = nullptr;
  MetaspaceObjToOopHandleTable* HeapShared::_scratch_references_table = nullptr;

@@ -219,19 +246,26 @@
    assert(CDSConfig::is_dumping_heap(), "dump-time only");
  
    // No GC should happen since we aren't scanning _pending_roots.
    assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
  
+   if (UsePermanentHeapObjects && obj != nullptr) {
+     int n = get_archived_object_permanent_index_locked(obj);
+     assert(n >= 0, "must have been added");
+     return n;
+   }
+ 
    if (_pending_roots == nullptr) {
-     _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
+     _pending_roots = new GrowableArrayCHeap<OopHandle, mtClassShared>(500);
    }
  
-   return _pending_roots->append(obj);
+   OopHandle oh(Universe::vm_global(), obj);
+   return _pending_roots->append(oh);
  }
  
  objArrayOop HeapShared::root_segment(int segment_idx) {
-   if (CDSConfig::is_dumping_heap()) {
+   if (CDSConfig::is_dumping_heap() && !CDSConfig::is_dumping_final_static_archive()) {
      assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
      if (!HeapShared::can_write()) {
        return nullptr;
      }
    } else {

@@ -241,10 +275,157 @@
    objArrayOop segment = (objArrayOop)_root_segments->at(segment_idx).resolve();
    assert(segment != nullptr, "should have been initialized");
    return segment;
  }
  
+ inline unsigned int oop_handle_hash(const OopHandle& oh) {
+   oop o = oh.resolve();
+   if (o == nullptr) {
+     return 0;
+   } else {
+     return o->identity_hash();
+   }
+ }
+ 
+ inline bool oop_handle_equals(const OopHandle& a, const OopHandle& b) {
+   return a.resolve() == b.resolve();
+ }
+ 
+ class OrigToScratchObjectTable: public ResourceHashtable<OopHandle, OopHandle,
+     36137, // prime number
+     AnyObj::C_HEAP,
+     mtClassShared,
+     oop_handle_hash,
+     oop_handle_equals> {};
+ 
+ static OrigToScratchObjectTable* _orig_to_scratch_object_table = nullptr;
+ 
+ void HeapShared::track_scratch_object(oop orig_obj, oop scratch_obj) {
+   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
+   if (_orig_to_scratch_object_table == nullptr) {
+     _orig_to_scratch_object_table = new (mtClass)OrigToScratchObjectTable();
+   }
+ 
+   OopHandle orig_h(Universe::vm_global(), orig_obj);
+   OopHandle scratch_h(Universe::vm_global(), scratch_obj);
+   _orig_to_scratch_object_table->put_when_absent(orig_h, scratch_h);
+ }
+ 
+ oop HeapShared::orig_to_scratch_object(oop orig_obj) {
+   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
+   if (_orig_to_scratch_object_table != nullptr) {
+     OopHandle orig(&orig_obj);
+     OopHandle* v = _orig_to_scratch_object_table->get(orig);
+     if (v != nullptr) {
+       return v->resolve();
+     }
+   }
+   return nullptr;
+ }
+ 
+ class ArchivedObjectPermanentIndexTable: public ResourceHashtable<OopHandle, int,
+     36137, // prime number
+     AnyObj::C_HEAP,
+     mtClassShared,
+     oop_handle_hash,
+     oop_handle_equals> {};
+ 
+ static ArchivedObjectPermanentIndexTable* _permanent_index_table = nullptr;
+ 
+ void HeapShared::add_to_permanent_index_table(oop obj) {
+   assert_locked_or_safepoint(ArchivedObjectTables_lock);
+ 
+   assert(CDSConfig::is_dumping_heap(), "must be");
+   if (UsePermanentHeapObjects) {
+     if (_permanent_index_table == nullptr) {
+       _permanent_index_table = new (mtClass)ArchivedObjectPermanentIndexTable();
+     }
+     if (_pending_roots == nullptr) {
+       _pending_roots = new GrowableArrayCHeap<OopHandle, mtClassShared>(500);
+     }
+ 
+     if (_orig_to_scratch_object_table != nullptr) {
+       OopHandle orig(&obj);
+       OopHandle* v = _orig_to_scratch_object_table->get(orig);
+       if (v != nullptr) {
+         obj = v->resolve();
+       }
+     }
+ 
+     OopHandle oh(Universe::vm_global(), obj);
+     int index = _pending_roots->append(oh);
+     _permanent_index_table->put_when_absent(oh, index);
+   }
+ }
+ 
+ int HeapShared::get_archived_object_permanent_index(oop obj) {
+   MutexLocker ml(ArchivedObjectTables_lock, Mutex::_no_safepoint_check_flag);
+   return get_archived_object_permanent_index_locked(obj);
+ }
+ 
+ // Can be called in the "old" workflow.
+ int HeapShared::get_archived_object_permanent_index_locked(oop obj) {
+   assert_locked_or_safepoint(ArchivedObjectTables_lock);
+   if (!UsePermanentHeapObjects) {
+     return -1;
+   }
+   if (!CDSConfig::is_dumping_heap() && !ArchiveHeapLoader::is_in_use()) {
+     return -1;
+   }
+ 
+   if (_permanent_index_table == nullptr) {
+     if (!ArchiveHeapLoader::is_in_use()) {
+       // Called in the old workflow
+       return -1;
+     } else {
+       _permanent_index_table = new (mtClass)ArchivedObjectPermanentIndexTable();
+       int count = 0;
+       for (int segment_idx = 0; segment_idx < _root_segments->length(); segment_idx++) {
+         objArrayOop segment = (objArrayOop)_root_segments->at(segment_idx).resolve();
+         for (int i = 0; i < segment->length(); i++, count++) {
+           oop root = segment->obj_at(i);
+           if (root != nullptr) {
+             OopHandle tmp(Universe::vm_global(), root);
+             int index = count;
+             _permanent_index_table->put_when_absent(tmp, index);
+           }
+         }
+       }
+     }
+   }
+ 
+   if (_orig_to_scratch_object_table != nullptr) {
+     OopHandle orig(&obj);
+     OopHandle* v = _orig_to_scratch_object_table->get(orig);
+     if (v != nullptr) {
+       obj = v->resolve();
+     }
+   }
+ 
+   OopHandle tmp(&obj);
+   int* v = _permanent_index_table->get(tmp);
+   if (v != nullptr) {
+     int n = *v;
+     return n;
+   }
+ 
+   return -1;
+ }
+ 
+ oop HeapShared::get_archived_object(int permanent_index) {
+   if (ArchiveHeapLoader::is_in_use()) {
+     return get_root(permanent_index);
+   } else {
+     assert(CDSConfig::is_dumping_heap(), "must be");
+     if (_pending_roots != nullptr) {
+       return _pending_roots->at(permanent_index).resolve();
+     } else {
+       return nullptr;
+     }
+   }
+ }
+ 
  void HeapShared::get_segment_indexes(int idx, int& seg_idx, int& int_idx) {
    assert(_root_segment_max_size_elems > 0, "sanity");
  
    // Try to avoid divisions for the common case.
    if (idx < _root_segment_max_size_elems) {

@@ -296,23 +477,36 @@
    }
  
    if (ArchiveHeapWriter::is_too_large_to_archive(obj->size())) {
      log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
                           p2i(obj), obj->size());
+     debug_trace();
      return false;
    } else {
+     add_to_permanent_index_table(obj);
      count_allocation(obj->size());
      ArchiveHeapWriter::add_source_obj(obj);
      CachedOopInfo info = make_cached_oop_info(obj);
      archived_object_cache()->put_when_absent(obj, info);
      archived_object_cache()->maybe_grow();
      mark_native_pointers(obj);
  
      if (log_is_enabled(Debug, cds, heap)) {
        ResourceMark rm;
-       log_debug(cds, heap)("Archived heap object " PTR_FORMAT " : %s",
-                            p2i(obj), obj->klass()->external_name());
+       LogTarget(Debug, cds, heap) log;
+       LogStream out(log);
+       out.print("Archived heap object " PTR_FORMAT " : %s ",
+                 p2i(obj), obj->klass()->external_name());
+       if (java_lang_Class::is_instance(obj)) {
+         Klass* k = java_lang_Class::as_Klass(obj);
+         if (k != nullptr) {
+           out.print("%s", k->external_name());
+         } else {
+           out.print("primitive");
+         }
+       }
+       out.cr();
      }
  
      if (java_lang_Module::is_instance(obj) && Modules::check_archived_module_oop(obj)) {
        Modules::update_oops_in_archived_module(obj, append_root(obj));
      }

@@ -350,10 +544,13 @@
      }
    }
  };
  
  void HeapShared::add_scratch_resolved_references(ConstantPool* src, objArrayOop dest) {
+   if (_scratch_references_table == nullptr) {
+     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
+   }
    _scratch_references_table->set_oop(src, dest);
  }
  
  objArrayOop HeapShared::scratch_resolved_references(ConstantPool* src) {
    return (objArrayOop)_scratch_references_table->get_oop(src);

@@ -363,14 +560,42 @@
    for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
      BasicType bt = (BasicType)i;
      if (!is_reference_type(bt)) {
        oop m = java_lang_Class::create_basic_type_mirror(type2name(bt), bt, CHECK);
        _scratch_basic_type_mirrors[i] = OopHandle(Universe::vm_global(), m);
+       track_scratch_object(Universe::java_mirror(bt), m);
      }
    }
    _scratch_java_mirror_table = new (mtClass)MetaspaceObjToOopHandleTable();
-   _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
+   if (_scratch_references_table == nullptr) {
+     _scratch_references_table = new (mtClass)MetaspaceObjToOopHandleTable();
+   }
+ }
+ 
+ // Given java_mirror that represents a (primitive or reference) type T,
+ // return the "scratch" version that represents the same type T.
+ // Note that if java_mirror will be returned if it's already a
+ // scratch mirror.
+ //
+ // See java_lang_Class::create_scratch_mirror() for more info.
+ oop HeapShared::scratch_java_mirror(oop java_mirror) {
+   assert(java_lang_Class::is_instance(java_mirror), "must be");
+ 
+   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
+     BasicType bt = (BasicType)i;
+     if (!is_reference_type(bt)) {
+       if (_scratch_basic_type_mirrors[i].resolve() == java_mirror) {
+         return java_mirror;
+       }
+     }
+   }
+ 
+   if (java_lang_Class::is_primitive(java_mirror)) {
+     return scratch_java_mirror(java_lang_Class::as_BasicType(java_mirror));
+   } else {
+     return scratch_java_mirror(java_lang_Class::as_Klass(java_mirror));
+   }
  }
  
  oop HeapShared::scratch_java_mirror(BasicType t) {
    assert((uint)t < T_VOID+1, "range check");
    assert(!is_reference_type(t), "sanity");

@@ -380,24 +605,140 @@
  oop HeapShared::scratch_java_mirror(Klass* k) {
    return _scratch_java_mirror_table->get_oop(k);
  }
  
  void HeapShared::set_scratch_java_mirror(Klass* k, oop mirror) {
+   track_scratch_object(k->java_mirror(), mirror);
    _scratch_java_mirror_table->set_oop(k, mirror);
  }
  
  void HeapShared::remove_scratch_objects(Klass* k) {
    _scratch_java_mirror_table->remove_oop(k);
    if (k->is_instance_klass()) {
      _scratch_references_table->remove(InstanceKlass::cast(k)->constants());
    }
+   oop mirror = k->java_mirror();
+   if (mirror != nullptr) {
+     OopHandle tmp(&mirror);
+     OopHandle* v = _orig_to_scratch_object_table->get(tmp);
+     if (v != nullptr) {
+       oop scratch_mirror = v->resolve();
+       java_lang_Class::set_klass(scratch_mirror, nullptr);
+       _orig_to_scratch_object_table->remove(tmp);
+     }
+   }
+ }
+ 
+ bool HeapShared::is_lambda_form_klass(InstanceKlass* ik) {
+   return ik->is_hidden() &&
+     (ik->name()->starts_with("java/lang/invoke/LambdaForm$MH+") ||
+      ik->name()->starts_with("java/lang/invoke/LambdaForm$DMH+") ||
+      ik->name()->starts_with("java/lang/invoke/LambdaForm$BMH+"));
+ }
+ 
+ bool HeapShared::is_lambda_proxy_klass(InstanceKlass* ik) {
+   return ik->is_hidden() && (ik->name()->index_of_at(0, "$$Lambda+", 9) > 0);
+ }
+ 
+ bool HeapShared::is_archivable_hidden_klass(InstanceKlass* ik) {
+   return CDSConfig::is_dumping_invokedynamic() && (is_lambda_form_klass(ik) || is_lambda_proxy_klass(ik));
+ }
+ 
+ void HeapShared::copy_aot_initialized_mirror(Klass* orig_k, oop orig_mirror, oop m) {
+   if (!orig_k->is_instance_klass()) {
+     return;
+   }
+   InstanceKlass* ik = InstanceKlass::cast(orig_k);
+ 
+   if (HeapShared::is_archivable_hidden_klass(ik)) {
+     // We can't rerun the <clinit> method of hidden classes as we don't save
+     // the classData, so we must archive its mirror in initialized state.
+     assert(ik->is_initialized(), "must be");
+   }
+ 
+   if (!ik->is_initialized() || !AOTClassInitializer::can_archive_initialized_mirror(ik)) {
+     return;
+   }
+ 
+   int nfields = 0;
+   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
+     if (fs.access_flags().is_static()) {
+       fieldDescriptor& fd = fs.field_descriptor();
+       int offset = fd.offset();
+       switch (fd.field_type()) {
+       case T_OBJECT:
+       case T_ARRAY:
+         m->obj_field_put(offset, orig_mirror->obj_field(offset));
+         break;
+       case T_BOOLEAN:
+         m->bool_field_put(offset, orig_mirror->bool_field(offset));
+         break;
+       case T_BYTE:
+         m->byte_field_put(offset, orig_mirror->byte_field(offset));
+         break;
+       case T_SHORT:
+         m->short_field_put(offset, orig_mirror->short_field(offset));
+         break;
+       case T_CHAR:
+         m->char_field_put(offset, orig_mirror->char_field(offset));
+         break;
+       case T_INT:
+         m->int_field_put(offset, orig_mirror->int_field(offset));
+         break;
+       case T_LONG:
+         m->long_field_put(offset, orig_mirror->long_field(offset));
+         break;
+       case T_FLOAT:
+         m->float_field_put(offset, orig_mirror->float_field(offset));
+         break;
+       case T_DOUBLE:
+         m->double_field_put(offset, orig_mirror->double_field(offset));
+         break;
+       default:
+         ShouldNotReachHere();
+       }
+       nfields ++;
+     }
+   }
+ 
+   java_lang_Class::set_class_data(m, java_lang_Class::class_data(orig_mirror));
+ 
+   // Class::reflectData use SoftReference, which cannot be archived. Set it
+   // to null and it will be recreated at runtime.
+   java_lang_Class::set_reflection_data(m, nullptr);
+ 
+   if (log_is_enabled(Info, cds, init)) {
+     ResourceMark rm;
+     log_debug(cds, init)("copied %3d field(s) in preinitialized mirror %s%s", nfields, ik->external_name(),
+                          ik->is_hidden() ? " (hidden)" : "");
+   }
+ 
+   InstanceKlass* buffered_ik = ArchiveBuilder::current()->get_buffered_addr(ik);
+   buffered_ik->set_has_preinitialized_mirror();
+ }
+ 
+ static void copy_java_mirror_hashcode(oop orig_mirror, oop scratch_m) {
+   int src_hash = orig_mirror->identity_hash();
+   scratch_m->set_mark(markWord::prototype().copy_set_hash(src_hash));
+   assert(scratch_m->mark().is_unlocked(), "sanity");
+ 
+   DEBUG_ONLY(int archived_hash = scratch_m->identity_hash());
+   assert(src_hash == archived_hash, "Java mirror wrong hash: original %x, scratch %x", src_hash, archived_hash);
  }
  
  void HeapShared::archive_java_mirrors() {
+   AOTClassInitializer::reset_preinit_check();
+ 
+   _orig_to_scratch_object_table->iterate([&](OopHandle o, OopHandle s) {
+     copy_java_mirror_hashcode(o.resolve(), s.resolve());
+     return true;
+   });
+ 
    for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
      BasicType bt = (BasicType)i;
      if (!is_reference_type(bt)) {
+       oop orig_mirror = Universe::java_mirror(bt);
        oop m = _scratch_basic_type_mirrors[i].resolve();
        assert(m != nullptr, "sanity");
        bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);
        assert(success, "sanity");
  

@@ -409,12 +750,29 @@
      }
    }
  
    GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
    assert(klasses != nullptr, "sanity");
+ 
+   for (int i = 0; i < klasses->length(); i++) {
+     Klass* orig_k = klasses->at(i);
+     oop orig_mirror = orig_k->java_mirror();
+     oop m = scratch_java_mirror(orig_k);
+     if (m != nullptr) {
+       copy_aot_initialized_mirror(orig_k, orig_mirror, m);
+       if (CDSConfig::is_dumping_reflection_data() && java_lang_Class::has_reflection_data(orig_mirror)) {
+         oop reflection_data = java_lang_Class::reflection_data(orig_mirror);
+         bool success = archive_reachable_objects_from(1, _default_subgraph_info, reflection_data);
+         guarantee(success, "");
+         java_lang_Class::set_reflection_data(m, reflection_data);
+       }
+     }
+   }
+ 
    for (int i = 0; i < klasses->length(); i++) {
      Klass* orig_k = klasses->at(i);
+     oop orig_mirror = orig_k->java_mirror();
      oop m = scratch_java_mirror(orig_k);
      if (m != nullptr) {
        Klass* buffered_k = ArchiveBuilder::get_buffered_klass(orig_k);
        bool success = archive_reachable_objects_from(1, _default_subgraph_info, m);
        guarantee(success, "scratch mirrors must point to only archivable objects");

@@ -457,10 +815,12 @@
  
  void HeapShared::mark_native_pointers(oop orig_obj) {
    if (java_lang_Class::is_instance(orig_obj)) {
      ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::klass_offset());
      ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_Class::array_klass_offset());
+   } else if (java_lang_invoke_ResolvedMethodName::is_instance(orig_obj)) {
+     ArchiveHeapWriter::mark_native_pointer(orig_obj, java_lang_invoke_ResolvedMethodName::vmtarget_offset());
    }
  }
  
  void HeapShared::get_pointer_info(oop src_obj, bool& has_oop_pointers, bool& has_native_pointers) {
    CachedOopInfo* info = archived_object_cache()->get(src_obj);

@@ -473,15 +833,109 @@
    CachedOopInfo* info = archived_object_cache()->get(src_obj);
    assert(info != nullptr, "must be");
    info->set_has_native_pointers();
  }
  
+ void HeapShared::start_finding_archivable_hidden_classes() {
+   NoSafepointVerifier nsv;
+ 
+   init_seen_objects_table();
+ 
+   find_archivable_hidden_classes_helper(archive_subgraph_entry_fields);
+   if (CDSConfig::is_dumping_full_module_graph()) {
+     find_archivable_hidden_classes_helper(fmg_archive_subgraph_entry_fields);
+   }
+ }
+ 
+ void HeapShared::end_finding_archivable_hidden_classes() {
+   NoSafepointVerifier nsv;
+ 
+   delete_seen_objects_table();
+ }
+ 
+ void HeapShared::find_archivable_hidden_classes_helper(ArchivableStaticFieldInfo fields[]) {
+   if (!CDSConfig::is_dumping_heap()) {
+     return;
+   }
+   for (int i = 0; fields[i].valid(); ) {
+     ArchivableStaticFieldInfo* info = &fields[i];
+     const char* klass_name = info->klass_name;
+     for (; fields[i].valid(); i++) {
+       ArchivableStaticFieldInfo* f = &fields[i];
+       if (f->klass_name != klass_name) {
+         break;
+       }
+ 
+       InstanceKlass* k = f->klass;
+       oop m = k->java_mirror();
+       oop o = m->obj_field(f->offset);
+       if (o != nullptr) {
+         find_archivable_hidden_classes_in_object(o);
+       }
+     }
+   }
+ }
+ 
+ class HeapShared::FindHiddenClassesOopClosure: public BasicOopIterateClosure {
+   GrowableArray<oop> _stack;
+   template <class T> void do_oop_work(T *p) {
+     // Recurse on a GrowableArray to avoid overflowing the C stack.
+     oop o = RawAccess<>::oop_load(p);
+     if (o != nullptr) {
+       _stack.append(o);
+     }
+   }
+ 
+  public:
+ 
+   void do_oop(narrowOop *p) { FindHiddenClassesOopClosure::do_oop_work(p); }
+   void do_oop(      oop *p) { FindHiddenClassesOopClosure::do_oop_work(p); }
+ 
+   FindHiddenClassesOopClosure(oop o) {
+     _stack.append(o);
+   }
+   oop pop() {
+     if (_stack.length() == 0) {
+       return nullptr;
+     } else {
+       return _stack.pop();
+     }
+   }
+ };
+ 
+ void HeapShared::find_archivable_hidden_classes_in_object(oop root) {
+   ResourceMark rm;
+   FindHiddenClassesOopClosure c(root);
+   oop o;
+   while ((o = c.pop()) != nullptr) {
+     if (!has_been_seen_during_subgraph_recording(o)) {
+       set_has_been_seen_during_subgraph_recording(o);
+ 
+       if (java_lang_Class::is_instance(o)) {
+         Klass* k = java_lang_Class::as_Klass(o);
+         if (k != nullptr && k->is_instance_klass()) {
+           SystemDictionaryShared::mark_required_class(InstanceKlass::cast(k));
+         }
+       } else if (java_lang_invoke_ResolvedMethodName::is_instance(o)) {
+         Method* m = java_lang_invoke_ResolvedMethodName::vmtarget(o);
+         if (m != nullptr && m->method_holder() != nullptr) {
+           SystemDictionaryShared::mark_required_class(m->method_holder());
+         }
+       }
+ 
+       o->oop_iterate(&c);
+     }
+   }
+ }
+ 
  void HeapShared::archive_objects(ArchiveHeapInfo *heap_info) {
    {
      NoSafepointVerifier nsv;
  
      _default_subgraph_info = init_subgraph_info(vmClasses::Object_klass(), false);
+     _trace = new GrowableArrayCHeap<oop, mtClassShared>(250);
+     _context = new GrowableArrayCHeap<const char*, mtClassShared>(250);
  
      // Cache for recording where the archived objects are copied to
      create_archived_object_cache();
  
      if (UseCompressedOops || UseG1GC) {

@@ -491,15 +945,21 @@
                      UseCompressedOops ? p2i(CompressedOops::end()) :
                                          p2i((address)G1CollectedHeap::heap()->reserved().end()));
      }
      copy_objects();
  
-     CDSHeapVerifier::verify();
+     if (!SkipArchiveHeapVerification) {
+       CDSHeapVerifier::verify();
+     }
      check_default_subgraph_classes();
    }
  
-   ArchiveHeapWriter::write(_pending_roots, heap_info);
+   GrowableArrayCHeap<oop, mtClassShared>* roots = new GrowableArrayCHeap<oop, mtClassShared>(_pending_roots->length());
+   for (int i = 0; i < _pending_roots->length(); i++) {
+     roots->append(_pending_roots->at(i).resolve());
+   }
+   ArchiveHeapWriter::write(roots, heap_info);
  }
  
  void HeapShared::copy_interned_strings() {
    init_seen_objects_table();
  

@@ -598,12 +1058,18 @@
      // initialization list.
      return;
    }
  
    if (buffered_k->is_instance_klass()) {
-     assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
-           "must be boot class");
+     if (CDSConfig::is_dumping_invokedynamic()) {
+       assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class() ||
+              HeapShared::is_lambda_proxy_klass(InstanceKlass::cast(buffered_k)),
+             "we can archive only instances of boot classes or lambda proxy classes");
+     } else {
+       assert(InstanceKlass::cast(buffered_k)->is_shared_boot_class(),
+              "must be boot class");
+     }
      // vmClasses::xxx_klass() are not updated, need to check
      // the original Klass*
      if (orig_k == vmClasses::String_klass() ||
          orig_k == vmClasses::Object_klass()) {
        // Initialized early during VM initialization. No need to be added

@@ -639,10 +1105,14 @@
    _subgraph_object_klasses->append_if_missing(buffered_k);
    _has_non_early_klasses |= is_non_early_klass(orig_k);
  }
  
  void KlassSubGraphInfo::check_allowed_klass(InstanceKlass* ik) {
+   if (CDSConfig::is_dumping_invokedynamic()) {
+     // FIXME -- this allows LambdaProxy classes
+     return;
+   }
    if (ik->module()->name() == vmSymbols::java_base()) {
      assert(ik->package() != nullptr, "classes in java.base cannot be in unnamed package");
      return;
    }
  

@@ -736,29 +1206,37 @@
    ArchivePtrMarker::mark_pointer(&_k);
    ArchivePtrMarker::mark_pointer(&_entry_field_records);
    ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
  }
  
- struct CopyKlassSubGraphInfoToArchive : StackObj {
+ class HeapShared::CopyKlassSubGraphInfoToArchive : StackObj {
    CompactHashtableWriter* _writer;
+ public:
    CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
  
    bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
      if (info.subgraph_object_klasses() != nullptr || info.subgraph_entry_fields() != nullptr) {
-       ArchivedKlassSubGraphInfoRecord* record =
-         (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
-       record->init(&info);
- 
+       ArchivedKlassSubGraphInfoRecord* record = HeapShared::archive_subgraph_info(&info);
        Klass* buffered_k = ArchiveBuilder::get_buffered_klass(klass);
        unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary((address)buffered_k);
        u4 delta = ArchiveBuilder::current()->any_to_offset_u4(record);
        _writer->add(hash, delta);
      }
      return true; // keep on iterating
    }
  };
  
+ ArchivedKlassSubGraphInfoRecord* HeapShared::archive_subgraph_info(KlassSubGraphInfo* info) {
+   ArchivedKlassSubGraphInfoRecord* record =
+       (ArchivedKlassSubGraphInfoRecord*)ArchiveBuilder::ro_region_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
+   record->init(info);
+   if (info ==  _default_subgraph_info) {
+     _runtime_default_subgraph_info = record;
+   }
+   return record;
+ }
+ 
  // Build the records of archived subgraph infos, which include:
  // - Entry points to all subgraphs from the containing class mirror. The entry
  //   points are static fields in the mirror. For each entry point, the field
  //   offset, and value are recorded in the sub-graph
  //   info. The value is stored back to the corresponding field at runtime.

@@ -811,10 +1289,11 @@
      setup_test_class(_test_class_name);
    }
  #endif
  
    _run_time_subgraph_info_table.serialize_header(soc);
+   soc->do_ptr(&_runtime_default_subgraph_info);
  }
  
  static void verify_the_heap(Klass* k, const char* which) {
    if (VerifyArchivedFields > 0) {
      ResourceMark rm;

@@ -851,10 +1330,23 @@
  void HeapShared::resolve_classes(JavaThread* current) {
    assert(CDSConfig::is_using_archive(), "runtime only!");
    if (!ArchiveHeapLoader::is_in_use()) {
      return; // nothing to do
    }
+ 
+   if (!CDSConfig::is_using_aot_linked_classes()) {
+     assert( _runtime_default_subgraph_info != nullptr, "must be");
+     Array<Klass*>* klasses = _runtime_default_subgraph_info->subgraph_object_klasses();
+     if (klasses != nullptr) {
+       for (int i = 0; i < klasses->length(); i++) {
+         Klass* k = klasses->at(i);
+         ExceptionMark em(current); // no exception can happen here
+         resolve_or_init(k, /*do_init*/false, current);
+       }
+     }
+   }
+ 
    resolve_classes_for_subgraphs(current, archive_subgraph_entry_fields);
    resolve_classes_for_subgraphs(current, fmg_archive_subgraph_entry_fields);
  }
  
  void HeapShared::resolve_classes_for_subgraphs(JavaThread* current, ArchivableStaticFieldInfo fields[]) {

@@ -878,10 +1370,51 @@
    if (record == nullptr) {
     clear_archived_roots_of(k);
    }
  }
  
+ void HeapShared::initialize_java_lang_invoke(TRAPS) {
+   if (CDSConfig::is_loading_invokedynamic() || CDSConfig::is_dumping_invokedynamic()) {
+     resolve_or_init("java/lang/invoke/Invokers$Holder", true, CHECK);
+     resolve_or_init("java/lang/invoke/MethodHandle", true, CHECK);
+     resolve_or_init("java/lang/invoke/MethodHandleNatives", true, CHECK);
+     resolve_or_init("java/lang/invoke/DirectMethodHandle$Holder", true, CHECK);
+     resolve_or_init("java/lang/invoke/DelegatingMethodHandle$Holder", true, CHECK);
+     resolve_or_init("java/lang/invoke/LambdaForm$Holder", true, CHECK);
+     resolve_or_init("java/lang/invoke/BoundMethodHandle$Species_L", true, CHECK);
+   }
+ }
+ 
+ void HeapShared::initialize_default_subgraph_classes(Handle class_loader, TRAPS) {
+   if (!ArchiveHeapLoader::is_in_use()) {
+     return;
+   }
+ 
+   assert( _runtime_default_subgraph_info != nullptr, "must be");
+   Array<Klass*>* klasses = _runtime_default_subgraph_info->subgraph_object_klasses();
+   if (klasses != nullptr) {
+     for (int pass = 0; pass < 2; pass ++) {
+       for (int i = 0; i < klasses->length(); i++) {
+         Klass* k = klasses->at(i);
+         if (k->class_loader_data() == nullptr) {
+           // This class is not yet loaded. We will initialize it in a later phase.
+           continue;
+         }
+         if (k->class_loader() == class_loader()) {
+           if (pass == 0) {
+             if (k->is_instance_klass()) {
+               InstanceKlass::cast(k)->link_class(CHECK);
+             }
+           } else {
+             resolve_or_init(k, /*do_init*/true, CHECK);
+           }
+         }
+       }
+     }
+   }
+ }
+ 
  void HeapShared::initialize_from_archived_subgraph(JavaThread* current, Klass* k) {
    JavaThread* THREAD = current;
    if (!ArchiveHeapLoader::is_in_use()) {
      return; // nothing to do
    }

@@ -981,10 +1514,23 @@
    }
  
    return record;
  }
  
+ void HeapShared::resolve_or_init(const char* klass_name, bool do_init, TRAPS) {
+   TempNewSymbol klass_name_sym =  SymbolTable::new_symbol(klass_name);
+   InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name_sym);
+   if (k == nullptr) {
+     return;
+   }
+   assert(k->is_shared_boot_class(), "sanity");
+   resolve_or_init(k, false, CHECK);
+   if (do_init) {
+     resolve_or_init(k, true, CHECK);
+   }
+ }
+ 
  void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
    if (!do_init) {
      if (k->class_loader_data() == nullptr) {
        Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
        assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");

@@ -1128,43 +1674,110 @@
    PointsToOopsChecker points_to_oops_checker;
    obj->oop_iterate(&points_to_oops_checker);
    return CachedOopInfo(referrer, points_to_oops_checker.result());
  }
  
+ // We currently allow only the box classes, as well as j.l.Object, which are
+ // initialized very early by HeapShared::init_box_classes().
+ bool HeapShared::can_mirror_be_used_in_subgraph(oop orig_java_mirror) {
+   return java_lang_Class::is_primitive(orig_java_mirror)
+     || orig_java_mirror == vmClasses::Boolean_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Character_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Float_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Double_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Byte_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Short_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Integer_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Long_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Void_klass()->java_mirror()
+     || orig_java_mirror == vmClasses::Object_klass()->java_mirror();
+ }
+ 
+ void HeapShared::init_box_classes(TRAPS) {
+   if (ArchiveHeapLoader::is_in_use()) {
+     vmClasses::Boolean_klass()->initialize(CHECK);
+     vmClasses::Character_klass()->initialize(CHECK);
+     vmClasses::Float_klass()->initialize(CHECK);
+     vmClasses::Double_klass()->initialize(CHECK);
+     vmClasses::Byte_klass()->initialize(CHECK);
+     vmClasses::Short_klass()->initialize(CHECK);
+     vmClasses::Integer_klass()->initialize(CHECK);
+     vmClasses::Long_klass()->initialize(CHECK);
+     vmClasses::Void_klass()->initialize(CHECK);
+   }
+ }
+ 
+ void HeapShared::exit_on_error() {
+   if (_context != nullptr) {
+     ResourceMark rm;
+     LogStream ls(Log(cds, heap)::error());
+     ls.print_cr("Context");
+     for (int i = 0; i < _context->length(); i++) {
+       const char* s = _context->at(i);
+       ls.print_cr("- %s", s);
+     }
+   }
+   if (_trace != nullptr) {
+     ResourceMark rm;
+     LogStream ls(Log(cds, heap)::error());
+     ls.print_cr("Reference trace");
+     for (int i = 0; i < _trace->length(); i++) {
+       oop orig_obj = _trace->at(i);
+       ls.print_cr("[%d] ========================================", i);
+       orig_obj->print_on(&ls);
+       ls.cr();
+     }
+   }
+   MetaspaceShared::unrecoverable_writing_error();
+ }
+ 
+ void HeapShared::debug_trace() {
+   WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
+   if (walker != nullptr) {
+     LogStream ls(Log(cds, heap)::error());
+     CDSHeapVerifier::trace_to_root(&ls, walker->referencing_obj());
+   }
+ }
+ 
  // (1) If orig_obj has not been archived yet, archive it.
  // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
  //     trace all  objects that are reachable from it, and make sure these objects are archived.
  // (3) Record the klasses of all orig_obj and all reachable objects.
  bool HeapShared::archive_reachable_objects_from(int level,
                                                  KlassSubGraphInfo* subgraph_info,
                                                  oop orig_obj) {
+   ArchivingObjectMark mark(orig_obj);
    assert(orig_obj != nullptr, "must be");
  
    if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
      // This object has injected fields that cannot be supported easily, so we disallow them for now.
      // If you get an error here, you probably made a change in the JDK library that has added
      // these objects that are referenced (directly or indirectly) by static fields.
      ResourceMark rm;
-     log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
-     if (log_is_enabled(Trace, cds, heap)) {
-       WalkOopAndArchiveClosure* walker = WalkOopAndArchiveClosure::current();
-       if (walker != nullptr) {
-         LogStream ls(Log(cds, heap)::trace());
-         CDSHeapVerifier::trace_to_root(&ls, walker->referencing_obj());
-       }
+     log_error(cds, heap)("Cannot archive object " PTR_FORMAT " of class %s", p2i(orig_obj), orig_obj->klass()->external_name());
+     debug_trace();
+     exit_on_error();
+   }
+ 
+   if (log_is_enabled(Debug, cds, heap) && java_lang_Class::is_instance(orig_obj)) {
+     ResourceMark rm;
+     LogTarget(Debug, cds, heap) log;
+     LogStream out(log);
+     out.print("Found java mirror " PTR_FORMAT " ", p2i(orig_obj));
+     Klass* k = java_lang_Class::as_Klass(orig_obj);
+     if (k != nullptr) {
+       out.print("%s", k->external_name());
+     } else {
+       out.print("primitive");
      }
-     MetaspaceShared::unrecoverable_writing_error();
+     out.print_cr("; scratch mirror = "  PTR_FORMAT,
+                  p2i(scratch_java_mirror(orig_obj)));
    }
  
-   // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
-   // them as Klass::_archived_mirror because they need to be specially restored at run time.
-   //
-   // If you get an error here, you probably made a change in the JDK library that has added a Class
-   // object that is referenced (directly or indirectly) by static fields.
-   if (java_lang_Class::is_instance(orig_obj) && subgraph_info != _default_subgraph_info) {
-     log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
-     MetaspaceShared::unrecoverable_writing_error();
+   if (java_lang_Class::is_instance(orig_obj)) {
+     orig_obj = scratch_java_mirror(orig_obj);
+     assert(orig_obj != nullptr, "must be archived");
    }
  
    if (has_been_seen_during_subgraph_recording(orig_obj)) {
      // orig_obj has already been archived and traced. Nothing more to do.
      return true;

@@ -1189,24 +1802,30 @@
          return false;
        } else {
          // We don't know how to handle an object that has been archived, but some of its reachable
          // objects cannot be archived. Bail out for now. We might need to fix this in the future if
          // we have a real use case.
-         MetaspaceShared::unrecoverable_writing_error();
+         exit_on_error();
        }
      }
    }
  
    Klass *orig_k = orig_obj->klass();
    subgraph_info->add_subgraph_object_klass(orig_k);
  
    WalkOopAndArchiveClosure walker(level, record_klasses_only, subgraph_info, orig_obj);
    orig_obj->oop_iterate(&walker);
  
-   if (CDSEnumKlass::is_enum_obj(orig_obj)) {
-     CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj);
+   if (CDSConfig::is_initing_classes_at_dump_time()) {
+     // The enum klasses are archived with preinitialized mirror.
+     // See AOTClassInitializer::can_archive_initialized_mirror.
+   } else {
+     if (CDSEnumKlass::is_enum_obj(orig_obj)) {
+       CDSEnumKlass::handle_enum_obj(level + 1, subgraph_info, orig_obj);
+     }
    }
+ 
    return true;
  }
  
  //
  // Start from the given static field in a java mirror and archive the

@@ -1320,10 +1939,14 @@
    delete_seen_objects_table();
  }
  
  void HeapShared::verify_reachable_objects_from(oop obj) {
    _num_total_verifications ++;
+   if (java_lang_Class::is_instance(obj)) {
+     obj = scratch_java_mirror(obj);
+     assert(obj != nullptr, "must be");
+   }
    if (!has_been_seen_during_subgraph_recording(obj)) {
      set_has_been_seen_during_subgraph_recording(obj);
      assert(has_been_archived(obj), "must be");
      VerifySharedOopClosure walker;
      obj->oop_iterate(&walker);

@@ -1334,34 +1957,31 @@
  // The "default subgraph" contains special objects (see heapShared.hpp) that
  // can be accessed before we load any Java classes (including java/lang/Class).
  // Make sure that these are only instances of the very few specific types
  // that we can handle.
  void HeapShared::check_default_subgraph_classes() {
+   if (CDSConfig::is_initing_classes_at_dump_time()) {
+     return;
+   }
+ 
    GrowableArray<Klass*>* klasses = _default_subgraph_info->subgraph_object_klasses();
    int num = klasses->length();
    for (int i = 0; i < num; i++) {
      Klass* subgraph_k = klasses->at(i);
-     if (log_is_enabled(Info, cds, heap)) {
+     Symbol* name = ArchiveBuilder::current()->get_source_addr(subgraph_k->name());
+     if (subgraph_k->is_instance_klass() &&
+         name != vmSymbols::java_lang_Class() &&
+         name != vmSymbols::java_lang_String() &&
+         name != vmSymbols::java_lang_ArithmeticException() &&
+         name != vmSymbols::java_lang_ArrayIndexOutOfBoundsException() &&
+         name != vmSymbols::java_lang_ArrayStoreException() &&
+         name != vmSymbols::java_lang_ClassCastException() &&
+         name != vmSymbols::java_lang_InternalError() &&
+         name != vmSymbols::java_lang_NullPointerException()) {
        ResourceMark rm;
-       log_info(cds, heap)(
-           "Archived object klass (default subgraph %d) => %s",
-           i, subgraph_k->external_name());
+       fatal("default subgraph cannot have objects of type %s", subgraph_k->external_name());
      }
- 
-     Symbol* name = ArchiveBuilder::current()->get_source_addr(subgraph_k->name());
-     guarantee(name == vmSymbols::java_lang_Class() ||
-               name == vmSymbols::java_lang_String() ||
-               name == vmSymbols::java_lang_ArithmeticException() ||
-               name == vmSymbols::java_lang_NullPointerException() ||
-               name == vmSymbols::java_lang_InternalError() ||
-               name == vmSymbols::java_lang_ArrayIndexOutOfBoundsException() ||
-               name == vmSymbols::java_lang_ArrayStoreException() ||
-               name == vmSymbols::java_lang_ClassCastException() ||
-               name == vmSymbols::object_array_signature() ||
-               name == vmSymbols::byte_array_signature() ||
-               name == vmSymbols::char_array_signature(),
-               "default subgraph can have only these objects");
    }
  }
  
  HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = nullptr;
  int HeapShared::_num_new_walked_objs;

@@ -1580,10 +2200,29 @@
      }
    }
  
    return false;
  }
+ 
+ void HeapShared::initialize_test_class_from_archive(JavaThread* current) {
+   Klass* k = _test_class;
+   if (k != nullptr && ArchiveHeapLoader::is_in_use()) {
+     JavaThread* THREAD = current;
+     ExceptionMark em(THREAD);
+     const ArchivedKlassSubGraphInfoRecord* record =
+       resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
+ 
+     // The _test_class is in the unnamed module, so it can't call CDS.initializeFromArchive()
+     // from its <clinit> method. So we set up its "archivedObjects" field first, before
+     // calling its <clinit>. This is not strictly clean, but it's a convenient way to write unit
+     // test cases (see test/hotspot/jtreg/runtime/cds/appcds/cacheObject/ArchiveHeapTestClass.java).
+     if (record != nullptr) {
+       init_archived_fields_for(k, record);
+     }
+     resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
+   }
+ }
  #endif
  
  void HeapShared::init_for_dumping(TRAPS) {
    if (HeapShared::can_write()) {
      setup_test_class(ArchiveHeapTestClass);

@@ -1609,20 +2248,22 @@
    for (int i = 0; fields[i].valid(); ) {
      ArchivableStaticFieldInfo* info = &fields[i];
      const char* klass_name = info->klass_name;
      start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
  
+     ContextMark cm(klass_name);
      // If you have specified consecutive fields of the same klass in
      // fields[], these will be archived in the same
      // {start_recording_subgraph ... done_recording_subgraph} pass to
      // save time.
      for (; fields[i].valid(); i++) {
        ArchivableStaticFieldInfo* f = &fields[i];
        if (f->klass_name != klass_name) {
          break;
        }
  
+       ContextMark cm(f->field_name);
        archive_reachable_objects_from_static_field(f->klass, f->klass_name,
                                                    f->offset, f->field_name);
      }
      done_recording_subgraph(info->klass, klass_name);
    }
< prev index next >