8202035: Archive the set of ModuleDescriptor and ModuleReference objects for observable system modules with unnamed initial module.
authorjiangli
Sun, 08 Jul 2018 12:43:05 -0400
changeset 50951 b96466cdfc45
parent 50950 fa2f93f99dbc
child 50952 529e8aec67bd
8202035: Archive the set of ModuleDescriptor and ModuleReference objects for observable system modules with unnamed initial module. Summary: Support system module archiving with unnamed initial module at dump time. Reviewed-by: erikj, coleenp, mchung, iklam, ccheung Contributed-by: alan.bateman@oracle.com, jiangli.zhou@oracle.com
make/hotspot/lib/JvmFeatures.gmk
make/hotspot/symbols/symbols-unix
src/hotspot/share/classfile/javaClasses.cpp
src/hotspot/share/classfile/javaClasses.hpp
src/hotspot/share/classfile/stringTable.cpp
src/hotspot/share/classfile/systemDictionary.hpp
src/hotspot/share/classfile/vmSymbols.hpp
src/hotspot/share/include/jvm.h
src/hotspot/share/memory/heapShared.cpp
src/hotspot/share/memory/heapShared.hpp
src/hotspot/share/memory/metaspaceShared.cpp
src/hotspot/share/memory/metaspaceShared.hpp
src/hotspot/share/prims/jvm.cpp
src/java.base/share/classes/jdk/internal/misc/VM.java
src/java.base/share/classes/jdk/internal/module/ArchivedModuleGraph.java
src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java
src/java.base/share/native/libjava/VM.c
test/hotspot/jtreg/runtime/appcds/TestCommon.java
test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleComboTest.java
test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleCompareTest.java
test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleWithCustomImageTest.java
test/hotspot/jtreg/runtime/appcds/cacheObject/CheckArchivedModuleApp.java
test/hotspot/jtreg/runtime/appcds/cacheObject/PrintSystemModulesApp.java
test/hotspot/jtreg/runtime/appcds/cacheObject/src/test/jdk/test/Test.java
test/hotspot/jtreg/runtime/appcds/cacheObject/src/test/module-info.java
--- a/make/hotspot/lib/JvmFeatures.gmk	Fri Jul 06 15:22:07 2018 -0400
+++ b/make/hotspot/lib/JvmFeatures.gmk	Sun Jul 08 12:43:05 2018 -0400
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -109,6 +109,7 @@
       classListParser.cpp \
       classLoaderExt.cpp \
       filemap.cpp \
+      heapShared.cpp \
       metaspaceShared.cpp \
       metaspaceShared_$(HOTSPOT_TARGET_CPU).cpp \
       metaspaceShared_$(HOTSPOT_TARGET_CPU_ARCH).cpp \
--- a/make/hotspot/symbols/symbols-unix	Fri Jul 06 15:22:07 2018 -0400
+++ b/make/hotspot/symbols/symbols-unix	Sun Jul 08 12:43:05 2018 -0400
@@ -136,6 +136,7 @@
 JVM_InitProperties
 JVM_InitStackTraceElement
 JVM_InitStackTraceElementArray
+JVM_InitializeFromArchive
 JVM_InternString
 JVM_Interrupt
 JVM_InvokeMethod
--- a/src/hotspot/share/classfile/javaClasses.cpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/classfile/javaClasses.cpp	Sun Jul 08 12:43:05 2018 -0400
@@ -1051,8 +1051,9 @@
       ResetMirrorField reset(archived_mirror_h);
       InstanceKlass::cast(k)->do_nonstatic_fields(&reset);
 
-      log_trace(cds, mirror)("Archived %s mirror object from " PTR_FORMAT " ==> " PTR_FORMAT,
-                             type2name((BasicType)t), p2i(Universe::_mirrors[t]), p2i(archived_m));
+      log_trace(cds, heap, mirror)(
+        "Archived %s mirror object from " PTR_FORMAT " ==> " PTR_FORMAT,
+        type2name((BasicType)t), p2i(Universe::_mirrors[t]), p2i(archived_m));
 
       Universe::_mirrors[t] = archived_m;
     }
@@ -1133,8 +1134,9 @@
   k->set_has_raw_archived_mirror();
 
   ResourceMark rm;
-  log_trace(cds, mirror)("Archived %s mirror object from " PTR_FORMAT " ==> " PTR_FORMAT,
-                         k->external_name(), p2i(mirror), p2i(archived_mirror));
+  log_trace(cds, heap, mirror)(
+    "Archived %s mirror object from " PTR_FORMAT " ==> " PTR_FORMAT,
+    k->external_name(), p2i(mirror), p2i(archived_mirror));
 
   return archived_mirror;
 }
@@ -1186,8 +1188,9 @@
   // klass. Updated the field in the archived mirror to point to the relocated
   // klass in the archive.
   Klass *reloc_k = MetaspaceShared::get_relocated_klass(as_Klass(mirror));
-  log_debug(cds, mirror)("Relocate mirror metadata field at _klass_offset from " PTR_FORMAT " ==> " PTR_FORMAT,
-                         p2i(as_Klass(mirror)), p2i(reloc_k));
+  log_debug(cds, heap, mirror)(
+    "Relocate mirror metadata field at _klass_offset from " PTR_FORMAT " ==> " PTR_FORMAT,
+    p2i(as_Klass(mirror)), p2i(reloc_k));
   archived_mirror->metadata_field_put(_klass_offset, reloc_k);
 
   // The field at _array_klass_offset is pointing to the original one dimension
@@ -1195,8 +1198,9 @@
   Klass *arr = array_klass_acquire(mirror);
   if (arr != NULL) {
     Klass *reloc_arr = MetaspaceShared::get_relocated_klass(arr);
-    log_debug(cds, mirror)("Relocate mirror metadata field at _array_klass_offset from " PTR_FORMAT " ==> " PTR_FORMAT,
-                           p2i(arr), p2i(reloc_arr));
+    log_debug(cds, heap, mirror)(
+      "Relocate mirror metadata field at _array_klass_offset from " PTR_FORMAT " ==> " PTR_FORMAT,
+      p2i(arr), p2i(reloc_arr));
     archived_mirror->metadata_field_put(_array_klass_offset, reloc_arr);
   }
   return archived_mirror;
@@ -1247,7 +1251,8 @@
   set_mirror_module_field(k, mirror, module, THREAD);
 
   ResourceMark rm;
-  log_trace(cds, mirror)("Restored %s archived mirror " PTR_FORMAT, k->external_name(), p2i(mirror()));
+  log_trace(cds, heap, mirror)(
+    "Restored %s archived mirror " PTR_FORMAT, k->external_name(), p2i(mirror()));
 
   return true;
 }
@@ -4273,6 +4278,9 @@
 int java_util_concurrent_locks_AbstractOwnableSynchronizer::_owner_offset;
 int reflect_ConstantPool::_oop_offset;
 int reflect_UnsafeStaticFieldAccessorImpl::_base_offset;
+int jdk_internal_module_ArchivedModuleGraph::_archivedSystemModules_offset;
+int jdk_internal_module_ArchivedModuleGraph::_archivedModuleFinder_offset;
+int jdk_internal_module_ArchivedModuleGraph::_archivedMainModule_offset;
 
 #define STACKTRACEELEMENT_FIELDS_DO(macro) \
   macro(declaringClassObject_offset,  k, "declaringClassObject", class_signature, false); \
@@ -4435,6 +4443,23 @@
   return (hardcoded_offset * heapOopSize) + instanceOopDesc::base_offset_in_bytes();
 }
 
+#define MODULEBOOTSTRAP_FIELDS_DO(macro) \
+  macro(_archivedSystemModules_offset,      k, "archivedSystemModules", systemModules_signature, true); \
+  macro(_archivedModuleFinder_offset,       k, "archivedModuleFinder",  moduleFinder_signature,  true); \
+  macro(_archivedMainModule_offset,         k, "archivedMainModule",    string_signature,        true)
+
+void jdk_internal_module_ArchivedModuleGraph::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::ArchivedModuleGraph_klass();
+  assert(k != NULL, "must be loaded");
+  MODULEBOOTSTRAP_FIELDS_DO(FIELD_COMPUTE_OFFSET);
+}
+
+#if INCLUDE_CDS
+void jdk_internal_module_ArchivedModuleGraph::serialize(SerializeClosure* f) {
+  MODULEBOOTSTRAP_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
+}
+#endif
+
 // Compute hard-coded offsets
 // Invoked before SystemDictionary::initialize, so pre-loaded classes
 // are not available to determine the offset_of_static_fields.
@@ -4493,6 +4518,8 @@
   java_lang_LiveStackFrameInfo::compute_offsets();
   java_util_concurrent_locks_AbstractOwnableSynchronizer::compute_offsets();
 
+  jdk_internal_module_ArchivedModuleGraph::compute_offsets();
+
   // generated interpreter code wants to know about the offsets we just computed:
   AbstractAssembler::update_delayed_values();
 }
--- a/src/hotspot/share/classfile/javaClasses.hpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/classfile/javaClasses.hpp	Sun Jul 08 12:43:05 2018 -0400
@@ -1491,6 +1491,19 @@
   static void serialize(SerializeClosure* f) NOT_CDS_RETURN;
 };
 
+class jdk_internal_module_ArchivedModuleGraph: AllStatic {
+ private:
+  static int _archivedSystemModules_offset;
+  static int _archivedModuleFinder_offset;
+  static int _archivedMainModule_offset;
+ public:
+  static int  archivedSystemModules_offset()      { return _archivedSystemModules_offset; }
+  static int  archivedModuleFinder_offset()       { return _archivedModuleFinder_offset; }
+  static int  archivedMainModule_offset()         { return _archivedMainModule_offset; }
+  static void compute_offsets();
+  static void serialize(SerializeClosure* f) NOT_CDS_RETURN;
+};
+
 // Use to declare fields that need to be injected into Java classes
 // for the JVM to use.  The name_index and signature_index are
 // declared in vmSymbols.  The may_be_java flag is used to declare
--- a/src/hotspot/share/classfile/stringTable.cpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/classfile/stringTable.cpp	Sun Jul 08 12:43:05 2018 -0400
@@ -785,6 +785,10 @@
 oop StringTable::create_archived_string(oop s, Thread* THREAD) {
   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 
+  if (MetaspaceShared::is_archive_object(s)) {
+    return s;
+  }
+
   oop new_s = NULL;
   typeArrayOop v = java_lang_String::value_no_keepalive(s);
   typeArrayOop new_v =
--- a/src/hotspot/share/classfile/systemDictionary.hpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/classfile/systemDictionary.hpp	Sun Jul 08 12:43:05 2018 -0400
@@ -187,6 +187,7 @@
   do_klass(jdk_internal_loader_ClassLoaders_AppClassLoader_klass,      jdk_internal_loader_ClassLoaders_AppClassLoader,       Pre ) \
   do_klass(jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass, jdk_internal_loader_ClassLoaders_PlatformClassLoader,  Pre ) \
   do_klass(CodeSource_klass,                            java_security_CodeSource,                  Pre                 ) \
+  do_klass(ArchivedModuleGraph_klass,                   jdk_internal_module_ArchivedModuleGraph,   Pre                 ) \
                                                                                                                          \
   do_klass(StackTraceElement_klass,                     java_lang_StackTraceElement,               Opt                 ) \
                                                                                                                          \
--- a/src/hotspot/share/classfile/vmSymbols.hpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/classfile/vmSymbols.hpp	Sun Jul 08 12:43:05 2018 -0400
@@ -124,6 +124,7 @@
   template(getBootClassPathEntryForClass_name,        "getBootClassPathEntryForClass")            \
   template(jdk_internal_vm_PostVMInitHook,            "jdk/internal/vm/PostVMInitHook")           \
   template(sun_net_www_ParseUtil,                     "sun/net/www/ParseUtil")                    \
+  template(jdk_internal_module_ArchivedModuleGraph,   "jdk/internal/module/ArchivedModuleGraph")  \
                                                                                                   \
   template(jdk_internal_loader_ClassLoaders_AppClassLoader,      "jdk/internal/loader/ClassLoaders$AppClassLoader")      \
   template(jdk_internal_loader_ClassLoaders_PlatformClassLoader, "jdk/internal/loader/ClassLoaders$PlatformClassLoader") \
@@ -652,6 +653,8 @@
   template(url_void_signature,                     "(Ljava/net/URL;)V")                                           \
   template(toFileURL_name,                         "toFileURL")                                                   \
   template(toFileURL_signature,                    "(Ljava/lang/String;)Ljava/net/URL;")                          \
+  template(moduleFinder_signature,                 "Ljava/lang/module/ModuleFinder;")                             \
+  template(systemModules_signature,                "Ljdk/internal/module/SystemModules;")                         \
                                                                                                                   \
   /*end*/
 
--- a/src/hotspot/share/include/jvm.h	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/include/jvm.h	Sun Jul 08 12:43:05 2018 -0400
@@ -171,6 +171,8 @@
 JNIEXPORT jobjectArray JNICALL
 JVM_GetVmArguments(JNIEnv *env);
 
+JNIEXPORT void JNICALL
+JVM_InitializeFromArchive(JNIEnv* env, jclass cls);
 
 /*
  * java.lang.Throwable
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/memory/heapShared.cpp	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,506 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "classfile/javaClasses.inline.hpp"
+#include "classfile/vmSymbols.hpp"
+#include "logging/log.hpp"
+#include "logging/logMessage.hpp"
+#include "logging/logStream.hpp"
+#include "memory/heapShared.hpp"
+#include "memory/iterator.inline.hpp"
+#include "memory/metadataFactory.hpp"
+#include "memory/metaspaceClosure.hpp"
+#include "memory/metaspaceShared.hpp"
+#include "memory/resourceArea.hpp"
+#include "oops/compressedOops.inline.hpp"
+#include "oops/oop.inline.hpp"
+
+#if INCLUDE_CDS_JAVA_HEAP
+KlassSubGraphInfo* HeapShared::_subgraph_info_list = NULL;
+int HeapShared::_num_archived_subgraph_info_records = 0;
+Array<ArchivedKlassSubGraphInfoRecord>* HeapShared::_archived_subgraph_info_records = NULL;
+
+// Currently there is only one class mirror (ArchivedModuleGraph) with archived
+// sub-graphs.
+KlassSubGraphInfo* HeapShared::find_subgraph_info(Klass* k) {
+  KlassSubGraphInfo* info = _subgraph_info_list;
+  while (info != NULL) {
+    if (info->klass() == k) {
+      return info;
+    }
+    info = info->next();
+  }
+  return NULL;
+}
+
+// Get the subgraph_info for Klass k. A new subgraph_info is created if
+// there is no existing one for k. The subgraph_info records the relocated
+// Klass* of the original k.
+KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
+  Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
+  KlassSubGraphInfo* info = find_subgraph_info(relocated_k);
+  if (info != NULL) {
+    return info;
+  }
+
+  info = new KlassSubGraphInfo(relocated_k, _subgraph_info_list);
+  _subgraph_info_list = info;
+  return info;
+}
+
+int HeapShared::num_of_subgraph_infos() {
+  int num = 0;
+  KlassSubGraphInfo* info = _subgraph_info_list;
+  while (info != NULL) {
+    num ++;
+    info = info->next();
+  }
+  return num;
+}
+
+// Add an entry field to the current KlassSubGraphInfo.
+void KlassSubGraphInfo::add_subgraph_entry_field(int static_field_offset, oop v) {
+  assert(DumpSharedSpaces, "dump time only");
+  if (_subgraph_entry_fields == NULL) {
+    _subgraph_entry_fields =
+      new(ResourceObj::C_HEAP, mtClass) GrowableArray<juint>(10, true);
+  }
+  _subgraph_entry_fields->append((juint)static_field_offset);
+  _subgraph_entry_fields->append(CompressedOops::encode(v));
+}
+
+// Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
+// Only objects of boot classes can be included in sub-graph.
+void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k, Klass *relocated_k) {
+  assert(DumpSharedSpaces, "dump time only");
+  assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
+         "must be the relocated Klass in the shared space");
+
+  if (_subgraph_object_klasses == NULL) {
+    _subgraph_object_klasses =
+      new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, true);
+  }
+
+  assert(relocated_k->is_shared(), "must be a shared class");
+  if (relocated_k->is_instance_klass()) {
+    assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
+          "must be boot class");
+    // SystemDictionary::xxx_klass() are not updated, need to check
+    // the original Klass*
+    if (orig_k == SystemDictionary::String_klass() ||
+        orig_k == SystemDictionary::Object_klass()) {
+      // Initialized early during VM initialization. No need to be added
+      // to the sub-graph object class list.
+      return;
+    }
+  } else if (relocated_k->is_objArray_klass()) {
+    Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
+    if (abk->is_instance_klass()) {
+      assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
+            "must be boot class");
+    }
+    if (relocated_k == Universe::objectArrayKlassObj()) {
+      // Initialized early during Universe::genesis. No need to be added
+      // to the list.
+      return;
+    }
+  } else {
+    assert(relocated_k->is_typeArray_klass(), "must be");
+    // Primitive type arrays are created early during Universe::genesis.
+    return;
+  }
+
+  _subgraph_object_klasses->append_if_missing(relocated_k);
+}
+
+// Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
+void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
+  _k = info->klass();
+  _next = NULL;
+  _entry_field_records = NULL;
+  _subgraph_klasses = NULL;
+
+  // populate the entry fields
+  GrowableArray<juint>* entry_fields = info->subgraph_entry_fields();
+  if (entry_fields != NULL) {
+    int num_entry_fields = entry_fields->length();
+    assert(num_entry_fields % 2 == 0, "sanity");
+    _entry_field_records =
+      MetaspaceShared::new_ro_array<juint>(num_entry_fields);
+    for (int i = 0 ; i < num_entry_fields; i++) {
+      _entry_field_records->at_put(i, entry_fields->at(i));
+    }
+  }
+
+  // the Klasses of the objects in the sub-graphs
+  GrowableArray<Klass*>* subgraph_klasses = info->subgraph_object_klasses();
+  if (subgraph_klasses != NULL) {
+    int num_subgraphs_klasses = subgraph_klasses->length();
+    _subgraph_klasses =
+      MetaspaceShared::new_ro_array<Klass*>(num_subgraphs_klasses);
+    for (int i = 0; i < num_subgraphs_klasses; i++) {
+      Klass* subgraph_k = subgraph_klasses->at(i);
+      if (log_is_enabled(Info, cds, heap)) {
+        ResourceMark rm;
+        log_info(cds, heap)(
+          "Archived object klass (%d): %s in %s sub-graphs",
+          i, subgraph_k->external_name(), _k->external_name());
+      }
+      _subgraph_klasses->at_put(i, subgraph_k);
+    }
+  }
+}
+
+// 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 are stored
+//   back to the corresponding field at runtime.
+// - A list of klasses that need to be loaded/initialized before archived
+//   java object sub-graph can be accessed at runtime.
+//
+// The records are saved in the archive file and reloaded at runtime. Currently
+// there is only one class mirror (ArchivedModuleGraph) with archived sub-graphs.
+//
+// Layout of the archived subgraph info records:
+//
+// records_size | num_records | records*
+// ArchivedKlassSubGraphInfoRecord | entry_fields | subgraph_object_klasses
+size_t HeapShared::build_archived_subgraph_info_records(int num_records) {
+  // remember the start address
+  char* start_p = MetaspaceShared::read_only_space_top();
+
+  // now populate the archived subgraph infos, which will be saved in the
+  // archive file
+  _archived_subgraph_info_records =
+    MetaspaceShared::new_ro_array<ArchivedKlassSubGraphInfoRecord>(num_records);
+  KlassSubGraphInfo* info = _subgraph_info_list;
+  int i = 0;
+  while (info != NULL) {
+    assert(i < _archived_subgraph_info_records->length(), "sanity");
+    ArchivedKlassSubGraphInfoRecord* record =
+      _archived_subgraph_info_records->adr_at(i);
+    record->init(info);
+    info = info->next();
+    i ++;
+  }
+
+  // _subgraph_info_list is no longer needed
+  delete _subgraph_info_list;
+  _subgraph_info_list = NULL;
+
+  char* end_p = MetaspaceShared::read_only_space_top();
+  size_t records_size = end_p - start_p;
+  return records_size;
+}
+
+// Write the subgraph info records in the shared _ro region
+void HeapShared::write_archived_subgraph_infos() {
+  assert(DumpSharedSpaces, "dump time only");
+
+  Array<intptr_t>* records_header = MetaspaceShared::new_ro_array<intptr_t>(3);
+
+  _num_archived_subgraph_info_records = num_of_subgraph_infos();
+  size_t records_size = build_archived_subgraph_info_records(
+                             _num_archived_subgraph_info_records);
+
+  // Now write the header information:
+  // records_size, num_records, _archived_subgraph_info_records
+  assert(records_header != NULL, "sanity");
+  intptr_t* p = (intptr_t*)(records_header->data());
+  *p = (intptr_t)records_size;
+  p ++;
+  *p = (intptr_t)_num_archived_subgraph_info_records;
+  p ++;
+  *p = (intptr_t)_archived_subgraph_info_records;
+}
+
+char* HeapShared::read_archived_subgraph_infos(char* buffer) {
+  Array<intptr_t>* records_header = (Array<intptr_t>*)buffer;
+  intptr_t* p = (intptr_t*)(records_header->data());
+  size_t records_size = (size_t)(*p);
+  p ++;
+  _num_archived_subgraph_info_records = *p;
+  p ++;
+  _archived_subgraph_info_records =
+    (Array<ArchivedKlassSubGraphInfoRecord>*)(*p);
+
+  buffer = (char*)_archived_subgraph_info_records + records_size;
+  return buffer;
+}
+
+void HeapShared::initialize_from_archived_subgraph(Klass* k) {
+  if (!MetaspaceShared::open_archive_heap_region_mapped()) {
+    return; // nothing to do
+  }
+
+  if (_num_archived_subgraph_info_records == 0) {
+    return; // no subgraph info records
+  }
+
+  // Initialize from archived data. Currently only ArchivedModuleGraph
+  // has archived object subgraphs, which is used during VM initialization
+  // time when bootstraping the system modules. No lock is needed.
+  Thread* THREAD = Thread::current();
+  for (int i = 0; i < _archived_subgraph_info_records->length(); i++) {
+    ArchivedKlassSubGraphInfoRecord* record = _archived_subgraph_info_records->adr_at(i);
+    if (record->klass() == k) {
+      int i;
+      // Found the archived subgraph info record for the requesting klass.
+      // Load/link/initialize the klasses of the objects in the subgraph.
+      // NULL class loader is used.
+      Array<Klass*>* klasses = record->subgraph_klasses();
+      if (klasses != NULL) {
+        for (i = 0; i < klasses->length(); i++) {
+          Klass* obj_k = klasses->at(i);
+          Klass* resolved_k = SystemDictionary::resolve_or_null(
+                                                (obj_k)->name(), THREAD);
+          if (resolved_k != obj_k) {
+            return;
+          }
+          if ((obj_k)->is_instance_klass()) {
+            InstanceKlass* ik = InstanceKlass::cast(obj_k);
+            ik->initialize(THREAD);
+          } else if ((obj_k)->is_objArray_klass()) {
+            ObjArrayKlass* oak = ObjArrayKlass::cast(obj_k);
+            oak->initialize(THREAD);
+          }
+        }
+      }
+
+      if (HAS_PENDING_EXCEPTION) {
+        CLEAR_PENDING_EXCEPTION;
+        // None of the field value will be set if there was an exception.
+        // The java code will not see any of the archived objects in the
+        // subgraphs referenced from k in this case.
+        return;
+      }
+
+      // Load the subgraph entry fields from the record and store them back to
+      // the corresponding fields within the mirror.
+      oop m = k->java_mirror();
+      Array<juint>* entry_field_records = record->entry_field_records();
+      if (entry_field_records != NULL) {
+        int efr_len = entry_field_records->length();
+        assert(efr_len % 2 == 0, "sanity");
+        for (i = 0; i < efr_len;) {
+          int field_offset = entry_field_records->at(i);
+          // The object refereced by the field becomes 'known' by GC from this
+          // point. All objects in the subgraph reachable from the object are
+          // also 'known' by GC.
+          oop v = MetaspaceShared::materialize_archived_object(
+            CompressedOops::decode(entry_field_records->at(i+1)));
+          m->obj_field_put(field_offset, v);
+          i += 2;
+        }
+      }
+
+      // Done. Java code can see the archived sub-graphs referenced from k's
+      // mirror after this point.
+      return;
+    }
+  }
+}
+
+class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
+  int _level;
+  KlassSubGraphInfo* _subgraph_info;
+  oop _orig_referencing_obj;
+  oop _archived_referencing_obj;
+ public:
+  WalkOopAndArchiveClosure(int level, KlassSubGraphInfo* subgraph_info,
+           oop orig, oop archived) : _level(level),
+                                     _subgraph_info(subgraph_info),
+                                     _orig_referencing_obj(orig),
+                                     _archived_referencing_obj(archived) {}
+  void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
+  void do_oop(      oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
+
+ protected:
+  template <class T> void do_oop_work(T *p) {
+    oop obj = RawAccess<>::oop_load(p);
+    if (!CompressedOops::is_null(obj)) {
+      // A java.lang.Class instance can not be included in an archived
+      // object sub-graph.
+      if (java_lang_Class::is_instance(obj)) {
+        tty->print("Unknown java.lang.Class object is in the archived sub-graph\n");
+        vm_exit(1);
+      }
+
+      LogTarget(Debug, cds, heap) log;
+      LogStream ls(log);
+      outputStream* out = &ls;
+      {
+        ResourceMark rm;
+        log.print("(%d) %s <--- referenced from:  %s",
+                  _level, obj->klass()->external_name(),
+                  CompressedOops::is_null(_orig_referencing_obj) ?
+                         "" : _orig_referencing_obj->klass()->external_name());
+        obj->print_on(out);
+      }
+
+      if (MetaspaceShared::is_archive_object(obj)) {
+        // The current oop is an archived oop, nothing needs to be done
+        log.print("--- object is already archived ---");
+        return;
+      }
+
+      size_t field_delta = pointer_delta(
+        p, _orig_referencing_obj, sizeof(char));
+      T* new_p = (T*)(address(_archived_referencing_obj) + field_delta);
+      oop archived = MetaspaceShared::find_archived_heap_object(obj);
+      if (archived != NULL) {
+        // There is an archived copy existing, update reference to point
+        // to the archived copy
+        RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
+        log.print(
+          "--- found existing archived copy, store archived " PTR_FORMAT " in " PTR_FORMAT,
+          p2i(archived), p2i(new_p));
+        return;
+      }
+
+      int l = _level + 1;
+      Thread* THREAD = Thread::current();
+      // Archive the current oop before iterating through its references
+      archived = MetaspaceShared::archive_heap_object(obj, THREAD);
+      assert(MetaspaceShared::is_archive_object(archived), "must be archived");
+      log.print("=== archiving oop " PTR_FORMAT " ==> " PTR_FORMAT,
+                 p2i(obj), p2i(archived));
+
+      // Following the references in the current oop and archive any
+      // encountered objects during the process
+      WalkOopAndArchiveClosure walker(l, _subgraph_info, obj, archived);
+      obj->oop_iterate(&walker);
+
+      // Update the reference in the archived copy of the referencing object
+      RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
+      log.print("=== store archived " PTR_FORMAT " in " PTR_FORMAT,
+                p2i(archived), p2i(new_p));
+
+      // Add the klass to the list of classes that need to be loaded before
+      // module system initialization
+      Klass *orig_k = obj->klass();
+      Klass *relocated_k = archived->klass();
+      _subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
+    }
+  }
+};
+
+//
+// Start from the given static field in a java mirror and archive the
+// complete sub-graph of java heap objects that are reached directly
+// or indirectly from the starting object by following references.
+// Currently, only ArchivedModuleGraph class instance (mirror) has archived
+// object subgraphs. Sub-graph archiving restrictions (current):
+//
+// - All classes of objects in the archived sub-graph (including the
+//   entry class) must be boot class only.
+// - No java.lang.Class instance (java mirror) can be included inside
+//   an archived sub-graph. Mirror can only be the sub-graph entry object.
+//
+// The Java heap object sub-graph archiving process (see
+// WalkOopAndArchiveClosure):
+//
+// 1) Java object sub-graph archiving starts from a given static field
+// within a Class instance (java mirror). If the static field is a
+// refererence field and points to a non-null java object, proceed to
+// the next step.
+//
+// 2) Archives the referenced java object. If an archived copy of the
+// current object already exists, updates the pointer in the archived
+// copy of the referencing object to point to the current archived object.
+// Otherwise, proceed to the next step.
+//
+// 3) Follows all references within the current java object and recursively
+// archive the sub-graph of objects starting from each reference.
+//
+// 4) Updates the pointer in the archived copy of referencing object to
+//    point to the current archived object.
+//
+// 5) The Klass of the current java object is added to the list of Klasses
+// for loading and initialzing before any object in the archived graph can
+// be accessed at runtime.
+//
+void HeapShared::archive_reachable_objects_from_static_field(Klass *k,
+                                                             int field_offset,
+                                                             BasicType field_type,
+                                                             TRAPS) {
+  assert(DumpSharedSpaces, "dump time only");
+  assert(k->is_instance_klass(), "sanity");
+  assert(InstanceKlass::cast(k)->is_shared_boot_class(),
+         "must be boot class");
+
+  oop m = k->java_mirror();
+  oop archived_m = MetaspaceShared::find_archived_heap_object(m);
+  if (CompressedOops::is_null(archived_m)) {
+    return;
+  }
+
+  if (field_type == T_OBJECT) {
+    // obtain k's subGraph Info
+    KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
+
+    // get the object referenced by the field
+    oop f = m->obj_field(field_offset);
+    if (!CompressedOops::is_null(f)) {
+      LogTarget(Debug, cds, heap) log;
+      LogStream ls(log);
+      outputStream* out = &ls;
+      log.print("Start from: ");
+      f->print_on(out);
+
+      // get the archived copy of the field referenced object
+      oop af = MetaspaceShared::archive_heap_object(f, THREAD);
+      if (!MetaspaceShared::is_archive_object(f)) {
+        WalkOopAndArchiveClosure walker(1, subgraph_info, f, af);
+        f->oop_iterate(&walker);
+      }
+
+      // The field value is not preserved in the archived mirror.
+      // Record the field as a new subGraph entry point. The recorded
+      // information is restored from the archive at runtime.
+      subgraph_info->add_subgraph_entry_field(field_offset, af);
+      Klass *relocated_k = af->klass();
+      Klass *orig_k = f->klass();
+      subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
+    } else {
+      // The field contains null, we still need to record the entry point,
+      // so it can be restored at runtime.
+      subgraph_info->add_subgraph_entry_field(field_offset, NULL);
+    }
+  } else {
+    ShouldNotReachHere();
+  }
+}
+
+#define do_module_object_graph(archive_object_graph_do) \
+  archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedSystemModules_offset(), T_OBJECT, CHECK); \
+  archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedModuleFinder_offset(), T_OBJECT, CHECK); \
+  archive_object_graph_do(SystemDictionary::ArchivedModuleGraph_klass(), jdk_internal_module_ArchivedModuleGraph::archivedMainModule_offset(), T_OBJECT, CHECK)
+
+void HeapShared::archive_module_graph_objects(Thread* THREAD) {
+  do_module_object_graph(archive_reachable_objects_from_static_field);
+}
+#endif // INCLUDE_CDS_JAVA_HEAP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/memory/heapShared.hpp	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_MEMORY_HEAPSHARED_HPP
+#define SHARE_VM_MEMORY_HEAPSHARED_HPP
+
+#include "classfile/systemDictionary.hpp"
+#include "memory/universe.hpp"
+#include "oops/objArrayKlass.hpp"
+#include "oops/oop.hpp"
+#include "oops/typeArrayKlass.hpp"
+#include "utilities/growableArray.hpp"
+
+#if INCLUDE_CDS_JAVA_HEAP
+// A dump time sub-graph info for Klass _k. It includes the entry points
+// (static fields in _k's mirror) of the archived sub-graphs reachable
+// from _k's mirror. It also contains a list of Klasses of the objects
+// within the sub-graphs.
+class KlassSubGraphInfo: public CHeapObj<mtClass> {
+ private:
+  KlassSubGraphInfo* _next;
+  // The class that contains the static field(s) as the entry point(s)
+  // of archived object sub-graph(s).
+  Klass* _k;
+  // A list of classes need to be loaded and initialized before the archived
+  // object sub-graphs can be accessed at runtime.
+  GrowableArray<Klass*>* _subgraph_object_klasses;
+  // A list of _k's static fields as the entry points of archived sub-graphs.
+  // For each entry field, it is a pair of field_offset and field_value.
+  GrowableArray<juint>*  _subgraph_entry_fields;
+
+ public:
+  KlassSubGraphInfo(Klass* k, KlassSubGraphInfo* next) :
+    _next(next), _k(k),  _subgraph_object_klasses(NULL),
+    _subgraph_entry_fields(NULL) {}
+  ~KlassSubGraphInfo() {
+    if (_subgraph_object_klasses != NULL) {
+      delete _subgraph_object_klasses;
+    }
+    if (_subgraph_entry_fields != NULL) {
+      delete _subgraph_entry_fields;
+    }
+  };
+
+  KlassSubGraphInfo* next() { return _next; }
+  Klass* klass()            { return _k; }
+  GrowableArray<Klass*>* subgraph_object_klasses() {
+    return _subgraph_object_klasses;
+  }
+  GrowableArray<juint>*  subgraph_entry_fields() {
+    return _subgraph_entry_fields;
+  }
+  void add_subgraph_entry_field(int static_field_offset, oop v);
+  void add_subgraph_object_klass(Klass *orig_k, Klass *relocated_k);
+};
+
+// An archived record of object sub-graphs reachable from static
+// fields within _k's mirror. The record is reloaded from the archive
+// at runtime.
+class ArchivedKlassSubGraphInfoRecord {
+ private:
+  ArchivedKlassSubGraphInfoRecord* _next;
+  Klass* _k;
+
+  // contains pairs of field offset and value for each subgraph entry field
+  Array<juint>* _entry_field_records;
+
+  // klasses of objects in archived sub-graphs referenced from the entry points
+  // (static fields) in the containing class
+  Array<Klass*>* _subgraph_klasses;
+ public:
+  ArchivedKlassSubGraphInfoRecord() :
+    _next(NULL), _k(NULL), _entry_field_records(NULL), _subgraph_klasses(NULL) {}
+  void init(KlassSubGraphInfo* info);
+  Klass* klass() { return _k; }
+  ArchivedKlassSubGraphInfoRecord* next() { return _next; }
+  void set_next(ArchivedKlassSubGraphInfoRecord* next) { _next = next; }
+  Array<juint>*  entry_field_records() { return _entry_field_records; }
+  Array<Klass*>* subgraph_klasses() { return _subgraph_klasses; }
+};
+#endif // INCLUDE_CDS_JAVA_HEAP
+
+class HeapShared: AllStatic {
+ private:
+#if INCLUDE_CDS_JAVA_HEAP
+  // This is a list of subgraph infos built at dump time while
+  // archiving object subgraphs.
+  static KlassSubGraphInfo* _subgraph_info_list;
+
+  // Contains a list of ArchivedKlassSubGraphInfoRecords that is stored
+  // in the archive file and reloaded at runtime.
+  static int _num_archived_subgraph_info_records;
+  static Array<ArchivedKlassSubGraphInfoRecord>* _archived_subgraph_info_records;
+
+  // Archive object sub-graph starting from the given static field
+  // in Klass k's mirror.
+  static void archive_reachable_objects_from_static_field(
+    Klass* k, int field_ofset, BasicType field_type, TRAPS);
+
+  static KlassSubGraphInfo* find_subgraph_info(Klass *k);
+  static KlassSubGraphInfo* get_subgraph_info(Klass *k);
+  static int num_of_subgraph_infos();
+
+  static size_t build_archived_subgraph_info_records(int num_records);
+#endif // INCLUDE_CDS_JAVA_HEAP
+ public:
+  static char* read_archived_subgraph_infos(char* buffer) NOT_CDS_JAVA_HEAP_RETURN_(buffer);
+  static void write_archived_subgraph_infos() NOT_CDS_JAVA_HEAP_RETURN;
+  static void initialize_from_archived_subgraph(Klass* k) NOT_CDS_JAVA_HEAP_RETURN;
+
+  static void archive_module_graph_objects(Thread* THREAD) NOT_CDS_JAVA_HEAP_RETURN;
+};
+#endif // SHARE_VM_MEMORY_HEAPSHARED_HPP
--- a/src/hotspot/share/memory/metaspaceShared.cpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/memory/metaspaceShared.cpp	Sun Jul 08 12:43:05 2018 -0400
@@ -39,6 +39,7 @@
 #include "logging/log.hpp"
 #include "logging/logMessage.hpp"
 #include "memory/filemap.hpp"
+#include "memory/heapShared.hpp"
 #include "memory/metaspace.hpp"
 #include "memory/metaspaceClosure.hpp"
 #include "memory/metaspaceShared.hpp"
@@ -207,6 +208,10 @@
   return _ro_region.allocate(num_bytes);
 }
 
+char* MetaspaceShared::read_only_space_top() {
+  return _ro_region.top();
+}
+
 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 
@@ -456,6 +461,7 @@
   java_lang_StackFrameInfo::serialize(soc);
   java_lang_LiveStackFrameInfo::serialize(soc);
   java_util_concurrent_locks_AbstractOwnableSynchronizer::serialize(soc);
+  jdk_internal_module_ArchivedModuleGraph::serialize(soc);
 }
 
 address MetaspaceShared::cds_i2i_entry_code_buffers(size_t total_size) {
@@ -1350,6 +1356,11 @@
   char* table_top = _ro_region.allocate(table_bytes, sizeof(intptr_t));
   SystemDictionary::copy_table(table_top, _ro_region.top());
 
+  // Write the archived object sub-graph infos. For each klass with sub-graphs,
+  // the info includes the static fields (sub-graph entry points) and Klasses
+  // of objects included in the sub-graph.
+  HeapShared::write_archived_subgraph_infos();
+
   // Write the other data to the output array.
   WriteClosure wc(&_ro_region);
   MetaspaceShared::serialize(&wc);
@@ -1861,6 +1872,8 @@
 
   MetaspaceShared::archive_klass_objects(THREAD);
 
+  HeapShared::archive_module_graph_objects(THREAD);
+
   G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,
                                                    os::vm_allocation_granularity());
 }
@@ -1906,14 +1919,16 @@
     ArchivedObjectCache* cache = MetaspaceShared::archive_object_cache();
     cache->put(obj, archived_oop);
   }
-  log_debug(cds)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT,
-                 p2i(obj), p2i(archived_oop));
+  log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT,
+                       p2i(obj), p2i(archived_oop));
   return archived_oop;
 }
 
 oop MetaspaceShared::materialize_archived_object(oop obj) {
-  assert(obj != NULL, "sanity");
-  return G1CollectedHeap::heap()->materialize_archived_object(obj);
+  if (obj != NULL) {
+    return G1CollectedHeap::heap()->materialize_archived_object(obj);
+  }
+  return NULL;
 }
 
 void MetaspaceShared::archive_klass_objects(Thread* THREAD) {
@@ -2121,6 +2136,9 @@
   buffer += sizeof(intptr_t);
   buffer += len;
 
+  // The table of archived java heap object sub-graph infos
+  buffer = HeapShared::read_archived_subgraph_infos(buffer);
+
   // Verify various attributes of the archive, plus initialize the
   // shared string/symbol tables
   intptr_t* array = (intptr_t*)buffer;
--- a/src/hotspot/share/memory/metaspaceShared.hpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/memory/metaspaceShared.hpp	Sun Jul 08 12:43:05 2018 -0400
@@ -232,6 +232,8 @@
   static char* misc_code_space_alloc(size_t num_bytes);
   static char* read_only_space_alloc(size_t num_bytes);
 
+  static char* read_only_space_top();
+
   template <typename T>
   static Array<T>* new_ro_array(int length) {
 #if INCLUDE_CDS
--- a/src/hotspot/share/prims/jvm.cpp	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/hotspot/share/prims/jvm.cpp	Sun Jul 08 12:43:05 2018 -0400
@@ -39,6 +39,7 @@
 #include "interpreter/bytecode.hpp"
 #include "jfr/jfrEvents.hpp"
 #include "logging/log.hpp"
+#include "memory/heapShared.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/referenceType.hpp"
 #include "memory/resourceArea.hpp"
@@ -3598,6 +3599,13 @@
   return VM_Version::supports_cx8();
 JVM_END
 
+JVM_ENTRY(void, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
+  JVMWrapper("JVM_InitializeFromArchive");
+  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
+  assert(k->is_klass(), "just checking");
+  HeapShared::initialize_from_archived_subgraph(k);
+JVM_END
+
 // Returns an array of all live Thread objects (VM internal JavaThreads,
 // jvmti agent threads, and JNI attaching threads  are skipped)
 // See CR 6404306 regarding JNI attaching threads
--- a/src/java.base/share/classes/jdk/internal/misc/VM.java	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/java.base/share/classes/jdk/internal/misc/VM.java	Sun Jul 08 12:43:05 2018 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -413,4 +413,15 @@
         initialize();
     }
     private static native void initialize();
+
+    /**
+     * Initialize archived static fields in the given Class using archived
+     * values from CDS dump time. Also initialize the classes of objects in
+     * the archived graph referenced by those fields.
+     *
+     * Those static fields remain as uninitialized if there is no mapped CDS
+     * java heap data or there is any error during initialization of the
+     * object class in the archived graph.
+     */
+    public static native void initializeFromArchive(Class<?> c);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/jdk/internal/module/ArchivedModuleGraph.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.module;
+
+import java.lang.module.ModuleFinder;
+import java.util.Objects;
+import jdk.internal.misc.VM;
+
+/**
+ * Used by ModuleBootstrap to obtain the archived system modules and finder.
+ */
+final class ArchivedModuleGraph {
+    private static String archivedMainModule;
+    private static SystemModules archivedSystemModules;
+    private static ModuleFinder archivedModuleFinder;
+
+    private final SystemModules systemModules;
+    private final ModuleFinder finder;
+
+    private ArchivedModuleGraph(SystemModules modules, ModuleFinder finder) {
+        this.systemModules = modules;
+        this.finder = finder;
+    }
+
+    SystemModules systemModules() {
+        return systemModules;
+    }
+
+    ModuleFinder finder() {
+        return finder;
+    }
+
+    // A factory method that ModuleBootstrap can use to obtain the
+    // ArchivedModuleGraph.
+    static ArchivedModuleGraph get(String mainModule) {
+        if (Objects.equals(mainModule, archivedMainModule)
+                && archivedSystemModules != null
+                && archivedModuleFinder != null) {
+            return new ArchivedModuleGraph(archivedSystemModules,
+                                           archivedModuleFinder);
+        } else {
+            return null;
+        }
+    }
+
+    // Used at CDS dump time
+    static void archive(String mainModule, SystemModules systemModules,
+                        ModuleFinder finder) {
+        if (archivedMainModule != null)
+            throw new UnsupportedOperationException();
+        archivedMainModule = mainModule;
+        archivedSystemModules = systemModules;
+        archivedModuleFinder = finder;
+    }
+
+    static {
+        VM.initializeFromArchive(ArchivedModuleGraph.class);
+    }
+}
--- a/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Sun Jul 08 12:43:05 2018 -0400
@@ -54,6 +54,7 @@
 import jdk.internal.misc.JavaLangAccess;
 import jdk.internal.misc.JavaLangModuleAccess;
 import jdk.internal.misc.SharedSecrets;
+import jdk.internal.misc.VM;
 import jdk.internal.perf.PerfCounter;
 
 /**
@@ -172,23 +173,45 @@
         boolean haveModulePath = (appModulePath != null || upgradeModulePath != null);
         boolean needResolution = true;
 
-        if (!haveModulePath && addModules.isEmpty() && limitModules.isEmpty()) {
-            systemModules = SystemModuleFinders.systemModules(mainModule);
-            if (systemModules != null && !isPatched && (traceOutput == null)) {
-                needResolution = false;
+        // If the java heap was archived at CDS dump time and the environment
+        // at dump time matches the current environment then use the archived
+        // system modules and finder.
+        ArchivedModuleGraph archivedModuleGraph = ArchivedModuleGraph.get(mainModule);
+        if (archivedModuleGraph != null
+                && !haveModulePath
+                && addModules.isEmpty()
+                && limitModules.isEmpty()
+                && !isPatched) {
+            systemModules = archivedModuleGraph.systemModules();
+            systemModuleFinder = archivedModuleGraph.finder();
+            needResolution = (traceOutput != null);
+        } else {
+            boolean canArchive = false;
+            if (!haveModulePath && addModules.isEmpty() && limitModules.isEmpty()) {
+                systemModules = SystemModuleFinders.systemModules(mainModule);
+                if (systemModules != null && !isPatched) {
+                    needResolution = (traceOutput != null);
+                    canArchive = true;
+                }
             }
-        }
-        if (systemModules == null) {
-            // all system modules are observable
-            systemModules = SystemModuleFinders.allSystemModules();
-        }
-        if (systemModules != null) {
-            // images build
-            systemModuleFinder = SystemModuleFinders.of(systemModules);
-        } else {
-            // exploded build or testing
-            systemModules = new ExplodedSystemModules();
-            systemModuleFinder = SystemModuleFinders.ofSystem();
+            if (systemModules == null) {
+                // all system modules are observable
+                systemModules = SystemModuleFinders.allSystemModules();
+            }
+            if (systemModules != null) {
+                // images build
+                systemModuleFinder = SystemModuleFinders.of(systemModules);
+            } else {
+                // exploded build or testing
+                systemModules = new ExplodedSystemModules();
+                systemModuleFinder = SystemModuleFinders.ofSystem();
+            }
+
+            // Module graph can be archived at CDS dump time. Only allow the
+            // unnamed module case for now.
+            if (canArchive && (mainModule == null)) {
+                ArchivedModuleGraph.archive(mainModule, systemModules, systemModuleFinder);
+            }
         }
 
         Counters.add("jdk.module.boot.1.systemModulesTime", t1);
--- a/src/java.base/share/native/libjava/VM.c	Fri Jul 06 15:22:07 2018 -0400
+++ b/src/java.base/share/native/libjava/VM.c	Sun Jul 08 12:43:05 2018 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,3 +60,9 @@
 Java_jdk_internal_misc_VM_getRuntimeArguments(JNIEnv *env, jclass cls) {
     return JVM_GetVmArguments(env);
 }
+
+JNIEXPORT void JNICALL
+Java_jdk_internal_misc_VM_initializeFromArchive(JNIEnv *env, jclass ignore,
+                                                jclass c) {
+    JVM_InitializeFromArchive(env, c);
+}
--- a/test/hotspot/jtreg/runtime/appcds/TestCommon.java	Fri Jul 06 15:22:07 2018 -0400
+++ b/test/hotspot/jtreg/runtime/appcds/TestCommon.java	Sun Jul 08 12:43:05 2018 -0400
@@ -33,6 +33,7 @@
 import jdk.test.lib.process.OutputAnalyzer;
 import java.io.File;
 import java.text.SimpleDateFormat;
+import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.Date;
 
@@ -343,4 +344,22 @@
         }
         return dirFile.getPath();
     }
+
+    public static boolean checkOutputStrings(String outputString1,
+                                             String outputString2,
+                                             String split_regex) {
+        String[] sa1 = outputString1.split(split_regex);
+        String[] sa2 = outputString2.split(split_regex);
+        Arrays.sort(sa1);
+        Arrays.sort(sa2);
+
+        int i = 0;
+        for (String s : sa1) {
+            if (!s.equals(sa2[i])) {
+                throw new RuntimeException(s + " is different from " + sa2[i]);
+            }
+            i ++;
+        }
+        return true;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleComboTest.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/*
+ * @test
+ * @summary Test archived system module sub-graph and verify objects are archived.
+ * @requires vm.cds.archived.java.heap
+ * @library /test/jdk/lib/testlibrary /test/lib /test/hotspot/jtreg/runtime/appcds
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ *          jdk.jartool/sun.tools.jar
+ * @build sun.hotspot.WhiteBox
+ * @compile CheckArchivedModuleApp.java
+ * @run driver ClassFileInstaller -jar app.jar CheckArchivedModuleApp
+ * @run driver ClassFileInstaller -jar WhiteBox.jar sun.hotspot.WhiteBox
+ * @run main ArchivedModuleComboTest
+ */
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+import sun.hotspot.WhiteBox;
+
+public class ArchivedModuleComboTest {
+    public static void main(String[] args) throws Exception {
+        String wbJar = ClassFileInstaller.getJarPath("WhiteBox.jar");
+        String use_whitebox_jar = "-Xbootclasspath/a:" + wbJar;
+        String appJar = ClassFileInstaller.getJarPath("app.jar");
+
+        Path userDir = Paths.get(System.getProperty("user.dir"));
+        Path moduleDir = Files.createTempDirectory(userDir, "mods");
+
+        // Dump without --module-path
+        OutputAnalyzer output = TestCommon.dump(appJar,
+                                    TestCommon.list("CheckArchivedModuleApp"),
+                                    use_whitebox_jar);
+        TestCommon.checkDump(output);
+
+        // Test case 1)
+        // - Dump without --module-path
+        // - Run from -cp only, archived boot layer module ModuleDescriptors
+        //   should be used.
+        System.out.println("----------------------- Test case 1 ----------------------");
+        output = TestCommon.exec(appJar, use_whitebox_jar,
+                                 "-XX:+UnlockDiagnosticVMOptions",
+                                 "-XX:+WhiteBoxAPI",
+                                 "CheckArchivedModuleApp",
+                                 "yes");
+        TestCommon.checkExec(output);
+
+        // Test case 2)
+        // - Dump without --module-path
+        // - Run from -cp only, archived boot layer module ModuleDescriptors
+        //   should be used with --show-module-resolution (requires resolution).
+        System.out.println("----------------------- Test case 2 ----------------------");
+        output = TestCommon.exec(appJar, use_whitebox_jar,
+                                 "--show-module-resolution",
+                                 "-XX:+UnlockDiagnosticVMOptions",
+                                 "-XX:+WhiteBoxAPI",
+                                 "CheckArchivedModuleApp",
+                                 "yes");
+        TestCommon.checkExec(output);
+
+        // Test case 3)
+        // - Dump without --module-path
+        // - Run with --module-path, archived boot layer module ModuleDescriptors
+        //   should be disabled.
+        System.out.println("----------------------- Test case 3 ----------------------");
+        output = TestCommon.exec(appJar, use_whitebox_jar,
+                                 "--module-path",
+                                 moduleDir.toString(),
+                                 "-XX:+UnlockDiagnosticVMOptions",
+                                 "-XX:+WhiteBoxAPI",
+                                 "CheckArchivedModuleApp",
+                                 "no");
+        TestCommon.checkExec(output);
+
+        // Dump with --module-path specified (test case 4, 5). Use an
+        // empty directory as it's simple and still triggers the case
+        // where system module objects are not archived.
+        output = TestCommon.dump(appJar,
+                                 TestCommon.list("CheckArchivedModuleApp"),
+                                 "--module-path",
+                                 moduleDir.toString(),
+                                 use_whitebox_jar);
+        TestCommon.checkDump(output);
+
+        // Test case 4)
+        // - Dump with --module-path
+        // - Run from -cp only, no archived boot layer module ModuleDescriptors
+        //   should be found.
+        System.out.println("----------------------- Test case 4 ----------------------");
+        output = TestCommon.exec(appJar, use_whitebox_jar,
+                                 "-XX:+UnlockDiagnosticVMOptions",
+                                 "-XX:+WhiteBoxAPI",
+                                 "CheckArchivedModuleApp",
+                                 "no");
+        TestCommon.checkExec(output);
+
+        // Test case 5)
+        // - Dump with --module-path
+        // - Run with --module-path, no archived boot layer module ModuleDescriptors
+        //   should be found.
+        System.out.println("----------------------- Test case 5 ----------------------");
+        output = TestCommon.exec(appJar, use_whitebox_jar,
+                                 "--module-path",
+                                 moduleDir.toString(),
+                                 "-XX:+UnlockDiagnosticVMOptions",
+                                 "-XX:+WhiteBoxAPI",
+                                 "CheckArchivedModuleApp",
+                                 "no");
+        TestCommon.checkExec(output);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleCompareTest.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/*
+ * @test
+ * @summary Compare archived system modules with non-archived.
+ * @requires vm.cds.archived.java.heap
+ * @library /test/jdk/lib/testlibrary /test/lib /test/hotspot/jtreg/runtime/appcds
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ *          jdk.jartool/sun.tools.jar
+ * @compile PrintSystemModulesApp.java
+ * @run driver ClassFileInstaller -jar app.jar PrintSystemModulesApp
+ * @run main ArchivedModuleCompareTest
+ */
+
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class ArchivedModuleCompareTest {
+    public static void main(String[] args) throws Exception {
+        String appJar = ClassFileInstaller.getJarPath("app.jar");
+
+        // Test case 1)
+        // Compare the list of archived system module names with non-archived
+        // list. They must be the same.
+        System.out.println("---------------- Test case 1 -----------------");
+        OutputAnalyzer output = TestCommon.dump(appJar,
+                        TestCommon.list("PrintSystemModulesApp"));
+        TestCommon.checkDump(output);
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+                                 "-cp", appJar,
+                                 "-Xshare:off",
+                                 "PrintSystemModulesApp");
+        output = TestCommon.executeAndLog(pb, "print.system.module.share.off");
+        output.shouldHaveExitValue(0);
+        String bootModules1 = output.getStdout();
+
+        output = TestCommon.exec(appJar,
+                                 "PrintSystemModulesApp");
+        TestCommon.checkExec(output);
+        if (output.getStderr().contains("sharing")) {
+            String bootModules2 = output.getStdout();
+            TestCommon.checkOutputStrings(bootModules1, bootModules2, ", ");
+        }
+
+        // Test case 2)
+        // Verify --show-module-resolution output with the output from
+        // -Xshare:off run
+        System.out.println("---------------- Test case 2 -----------------");
+        pb = ProcessTools.createJavaProcessBuilder(
+                                 "-Xshare:off",
+                                 "--show-module-resolution",
+                                 "-version");
+        output = TestCommon.executeAndLog(pb, "show.module.resolution.share.off");
+        output.shouldHaveExitValue(0);
+        String moduleResolutionOut1 = output.getStdout();
+
+        output = TestCommon.exec(appJar,
+                                 "--show-module-resolution",
+                                 "-version");
+        TestCommon.checkExec(output);
+        if (output.getStderr().contains("sharing")) {
+            String moduleResolutionOut2 = output.getStdout();
+            TestCommon.checkOutputStrings(
+                moduleResolutionOut1, moduleResolutionOut2, "\n");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/ArchivedModuleWithCustomImageTest.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,184 @@
+/**
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Test archived module graph with custom runtime image
+ * @requires vm.cds.archived.java.heap
+ * @library /test/jdk/lib/testlibrary /test/lib /test/hotspot/jtreg/runtime/appcds
+ * @modules java.base/jdk.internal.module
+ *          java.management
+ *          jdk.jlink
+ *          jdk.compiler
+ * @build sun.hotspot.WhiteBox
+ * @compile CheckArchivedModuleApp.java
+ * @run driver ClassFileInstaller -jar app.jar CheckArchivedModuleApp
+ * @run driver ClassFileInstaller -jar WhiteBox.jar sun.hotspot.WhiteBox
+ * @run main ArchivedModuleWithCustomImageTest
+ */
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import jdk.test.lib.compiler.CompilerUtils;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class ArchivedModuleWithCustomImageTest {
+    private static final String JAVA_HOME = System.getProperty("java.home");
+    private static final String TEST_MODULE = "test";
+    private static final Path jdkHome = Paths.get(System.getProperty("test.jdk"));
+    private static final Path jdkMods = jdkHome.resolve("jmods");
+    private static final Path testSrc = Paths.get(System.getProperty("test.src"));
+    private static final Path src = testSrc.resolve("src").resolve(TEST_MODULE);
+    private static final Path classes = Paths.get("classes");
+    private static final Path jmods = Paths.get("jmods");
+
+    public static void main(String[] args) throws Throwable {
+        if (Files.notExists(jdkMods)) {
+            System.out.println("No jmods/ in test JDK, not supported.");
+            return;
+        }
+
+        // compile test module class
+        if (!CompilerUtils.compile(src, classes)) {
+            throw new RuntimeException("Compilation failure.");
+        }
+
+        // create custom runtime image named 'myimage'
+        Files.createDirectories(jmods);
+        Path image = Paths.get("myimage");
+        runJmod(classes.toString(), TEST_MODULE);
+        runJlink(image, TEST_MODULE);
+
+        // test using 'myimage'
+        testArchivedModuleUsingImage(image);
+
+        Files.delete(jmods.resolve(TEST_MODULE + ".jmod"));
+    }
+
+    private static void runJlink(Path image, String modName) throws Throwable {
+        Path jlink = Paths.get(JAVA_HOME, "bin", "jlink");
+        OutputAnalyzer output = ProcessTools.executeProcess(jlink.toString(),
+                        "--output", image.toString(),
+                        "--add-modules", modName,
+                        "--module-path", jdkMods + File.pathSeparator + jmods);
+        output.shouldHaveExitValue(0);
+    }
+
+    private static void runJmod(String cp, String modName) throws Throwable {
+        Path jmod = Paths.get(JAVA_HOME, "bin", "jmod");
+        OutputAnalyzer output = ProcessTools.executeProcess(jmod.toString(),
+                       "create",
+                       "--class-path", cp,
+                       "--module-version", "1.0",
+                       "--main-class", "jdk.test.Test",
+                       jmods.resolve(modName + ".jmod").toString());
+        output.shouldHaveExitValue(0);
+    }
+
+    private static void testArchivedModuleUsingImage(Path image)
+                            throws Throwable {
+        String wbJar = ClassFileInstaller.getJarPath("WhiteBox.jar");
+        String use_whitebox_jar = "-Xbootclasspath/a:" + wbJar;
+        String appJar = ClassFileInstaller.getJarPath("app.jar");
+        Path customJava = Paths.get(image.toString(), "bin", "java");
+
+        // -Xshare:dump with custom runtime image
+        String[] dumpCmd = {
+            customJava.toString(),
+            "-XX:SharedArchiveFile=./ArchivedModuleWithCustomImageTest.jsa",
+            "-Xshare:dump"};
+        printCommand(dumpCmd);
+        ProcessBuilder pbDump = new ProcessBuilder();
+        pbDump.command(dumpCmd);
+        OutputAnalyzer output = TestCommon.executeAndLog(
+            pbDump, "custom.runtime.image.dump");
+        TestCommon.checkDump(output);
+
+        // Test case 1):
+        // test archived module graph objects are used with custome runtime image
+        System.out.println("------------------- Test case 1 -------------------");
+        String[] runCmd = {customJava.toString(),
+                           use_whitebox_jar,
+                           "-XX:SharedArchiveFile=./ArchivedModuleWithCustomImageTest.jsa",
+                           "-cp",
+                           appJar,
+                           "-Xshare:on",
+                           "-XX:+UnlockDiagnosticVMOptions",
+                           "-XX:+WhiteBoxAPI",
+                           "CheckArchivedModuleApp",
+                           "yes"};
+        printCommand(runCmd);
+        ProcessBuilder pbRun = new ProcessBuilder();
+        pbRun.command(runCmd);
+        output = TestCommon.executeAndLog(pbRun, "custom.runtime.image.run");
+        output.shouldHaveExitValue(0);
+
+
+        // Test case 2):
+        // verify --show-module-resolution output
+        System.out.println("------------------- Test case 2 -------------------");
+
+        // myimage/bin/java -Xshare:off --show-module-resolution -version
+        String[] showModuleCmd1 = {customJava.toString(),
+                                   "-Xshare:off",
+                                   "--show-module-resolution",
+                                   "-version"};
+        printCommand(showModuleCmd1);
+        pbRun = new ProcessBuilder();
+        pbRun.command(showModuleCmd1);
+        output = TestCommon.executeAndLog(
+            pbRun, "custom.runtime.image.showModuleResolution.nocds");
+        output.shouldHaveExitValue(0);
+        String moduleResolutionOut1 = output.getStdout();
+
+        // myimage/bin/java -Xshare:on --show-module-resolution -version
+        //    -XX:SharedArchiveFile=./ArchivedModuleWithCustomImageTest.jsa
+        String[] showModuleCmd2 = {
+            customJava.toString(),
+            "-XX:SharedArchiveFile=./ArchivedModuleWithCustomImageTest.jsa",
+            "-Xshare:on",
+            "--show-module-resolution",
+            "-version"};
+        printCommand(showModuleCmd2);
+        pbRun = new ProcessBuilder();
+        pbRun.command(showModuleCmd2);
+        output = TestCommon.executeAndLog(
+            pbRun, "custom.runtime.image.showModuleResolution.cds");
+        if (output.getStderr().contains("sharing")) {
+            String moduleResolutionOut2 = output.getStdout();
+            TestCommon.checkOutputStrings(
+                moduleResolutionOut1, moduleResolutionOut2, "\n");
+        }
+    }
+
+    private static void printCommand(String opts[]) {
+        StringBuilder cmdLine = new StringBuilder();
+        for (String cmd : opts)
+            cmdLine.append(cmd).append(' ');
+        System.out.println("Command line: [" + cmdLine.toString() + "]");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/CheckArchivedModuleApp.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+import java.io.File;
+import java.lang.module.ModuleDescriptor;
+import java.util.Set;
+import sun.hotspot.WhiteBox;
+
+//
+// Test archived system module graph when open archive heap objects are mapped:
+//
+public class CheckArchivedModuleApp {
+    static WhiteBox wb;
+    public static void main(String args[]) throws Exception {
+        wb = WhiteBox.getWhiteBox();
+
+        if (!wb.areOpenArchiveHeapObjectsMapped()) {
+            System.out.println("Archived open_archive_heap objects are not mapped.");
+            System.out.println("This may happen during normal operation. Test Skipped.");
+            return;
+        }
+
+        boolean expectArchived = "yes".equals(args[0]);
+        checkModuleDescriptors(expectArchived);
+    }
+
+    private static void checkModuleDescriptors(boolean expectArchived) {
+        Set<Module> modules = ModuleLayer.boot().modules();
+        for (Module m : modules) {
+            ModuleDescriptor md = m.getDescriptor();
+            String name = md.name();
+            if (expectArchived) {
+                if (wb.isShared(md)) {
+                    System.out.println(name + " is archived. Expected.");
+                } else {
+                    throw new RuntimeException(
+                        "FAILED. " + name + " is not archived. Expect archived.");
+                }
+            } else {
+                if (!wb.isShared(md)) {
+                    System.out.println(name + " is not archived. Expected.");
+                } else {
+                    throw new RuntimeException(
+                        "FAILED. " + name + " is archived. Expect not archived.");
+                }
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/PrintSystemModulesApp.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+//
+// Print the system module names
+//
+public class PrintSystemModulesApp {
+    public static void main(String args[]) throws Exception {
+        String modules = ModuleLayer.boot().toString();
+        System.out.println(modules + ", ");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/src/test/jdk/test/Test.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.test;
+
+public class Test {
+    public static void main(String[] args) {
+        ClassLoader scl = ClassLoader.getSystemClassLoader();
+        ClassLoader cl1 = Test.class.getClassLoader();
+        Module testModule = Test.class.getModule();
+        ClassLoader cl2 = ModuleLayer.boot().findLoader(testModule.getName());
+
+        if (cl1 != scl)
+            throw new RuntimeException("Not loaded by system class loader");
+        if (cl2 != scl)
+            throw new RuntimeException("Not associated with system class loader");
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/appcds/cacheObject/src/test/module-info.java	Sun Jul 08 12:43:05 2018 -0400
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+module test {
+}