< prev index next >

src/hotspot/share/cds/metaspaceShared.cpp

Print this page

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"

  26 #include "cds/aotClassLinker.hpp"
  27 #include "cds/aotConstantPoolResolver.hpp"
  28 #include "cds/aotLinkedClassBulkLoader.hpp"
  29 #include "cds/archiveBuilder.hpp"
  30 #include "cds/archiveHeapLoader.hpp"
  31 #include "cds/archiveHeapWriter.hpp"
  32 #include "cds/cds_globals.hpp"

  33 #include "cds/cdsConfig.hpp"
  34 #include "cds/cdsProtectionDomain.hpp"
  35 #include "cds/classListParser.hpp"
  36 #include "cds/classListWriter.hpp"
  37 #include "cds/cppVtables.hpp"
  38 #include "cds/dumpAllocStats.hpp"
  39 #include "cds/dynamicArchive.hpp"
  40 #include "cds/filemap.hpp"

  41 #include "cds/heapShared.hpp"
  42 #include "cds/lambdaFormInvokers.hpp"
  43 #include "cds/metaspaceShared.hpp"
  44 #include "classfile/classLoaderDataGraph.hpp"
  45 #include "classfile/classLoaderDataShared.hpp"
  46 #include "classfile/classLoaderExt.hpp"
  47 #include "classfile/javaClasses.inline.hpp"
  48 #include "classfile/loaderConstraints.hpp"
  49 #include "classfile/modules.hpp"
  50 #include "classfile/placeholders.hpp"
  51 #include "classfile/stringTable.hpp"
  52 #include "classfile/symbolTable.hpp"
  53 #include "classfile/systemDictionary.hpp"
  54 #include "classfile/systemDictionaryShared.hpp"
  55 #include "classfile/vmClasses.hpp"
  56 #include "classfile/vmSymbols.hpp"
  57 #include "code/codeCache.hpp"



  58 #include "gc/shared/gcVMOperations.hpp"
  59 #include "interpreter/bytecodeStream.hpp"
  60 #include "interpreter/bytecodes.hpp"
  61 #include "jvm_io.h"
  62 #include "logging/log.hpp"
  63 #include "logging/logMessage.hpp"
  64 #include "logging/logStream.hpp"
  65 #include "memory/metaspace.hpp"
  66 #include "memory/metaspaceClosure.hpp"
  67 #include "memory/resourceArea.hpp"
  68 #include "memory/universe.hpp"
  69 #include "nmt/memTracker.hpp"
  70 #include "oops/compressedKlass.hpp"
  71 #include "oops/instanceMirrorKlass.hpp"
  72 #include "oops/klass.inline.hpp"

  73 #include "oops/objArrayOop.hpp"
  74 #include "oops/oop.inline.hpp"
  75 #include "oops/oopHandle.hpp"

  76 #include "prims/jvmtiExport.hpp"

  77 #include "runtime/arguments.hpp"
  78 #include "runtime/globals.hpp"
  79 #include "runtime/globals_extension.hpp"
  80 #include "runtime/handles.inline.hpp"
  81 #include "runtime/javaCalls.hpp"
  82 #include "runtime/os.inline.hpp"
  83 #include "runtime/safepointVerifiers.hpp"
  84 #include "runtime/sharedRuntime.hpp"
  85 #include "runtime/vmOperations.hpp"
  86 #include "runtime/vmThread.hpp"
  87 #include "sanitizers/leak.hpp"
  88 #include "utilities/align.hpp"
  89 #include "utilities/bitMap.inline.hpp"
  90 #include "utilities/defaultStream.hpp"
  91 #include "utilities/macros.hpp"
  92 #include "utilities/ostream.hpp"
  93 #include "utilities/resourceHash.hpp"
  94 
  95 ReservedSpace MetaspaceShared::_symbol_rs;
  96 VirtualSpace MetaspaceShared::_symbol_vs;
  97 bool MetaspaceShared::_archive_loading_failed = false;
  98 bool MetaspaceShared::_remapped_readwrite = false;
  99 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 100 intx MetaspaceShared::_relocation_delta;
 101 char* MetaspaceShared::_requested_base_address;
 102 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 103 bool MetaspaceShared::_use_optimized_module_handling = true;

 104 
 105 // The CDS archive is divided into the following regions:
 106 //     rw  - read-write metadata
 107 //     ro  - read-only metadata and read-only tables
 108 //     hp  - heap region
 109 //     bm  - bitmap for relocating the above 7 regions.
 110 //
 111 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 112 // These regions are aligned with MetaspaceShared::core_region_alignment().
 113 //
 114 // These 2 regions are populated in the following steps:
 115 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 116 //     temporarily allocated outside of the shared regions.
 117 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 118 // [2] C++ vtables are copied into the rw region.
 119 // [3] ArchiveBuilder copies RW metadata into the rw region.
 120 // [4] ArchiveBuilder copies RO metadata into the ro region.
 121 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 122 //     are copied into the ro region as read-only tables.
 123 //

 245     err = "invalid for this platform";
 246   } else {
 247     return aligned_base;
 248   }
 249 
 250   log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 251                    p2i((void*)SharedBaseAddress), err,
 252                    p2i((void*)Arguments::default_SharedBaseAddress()));
 253 
 254   specified_base = (char*)Arguments::default_SharedBaseAddress();
 255   aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 256 
 257   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 258   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 259   assert(shared_base_valid(aligned_base), "Sanity");
 260   return aligned_base;
 261 }
 262 
 263 void MetaspaceShared::initialize_for_static_dump() {
 264   assert(CDSConfig::is_dumping_static_archive(), "sanity");








 265   log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
 266   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 267   // to avoid address space wrap around.
 268   size_t cds_max;
 269   const size_t reserve_alignment = core_region_alignment();
 270 
 271 #ifdef _LP64
 272   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 273   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 274 #else
 275   // We don't support archives larger than 256MB on 32-bit due to limited
 276   //  virtual address space.
 277   cds_max = align_down(256*M, reserve_alignment);
 278 #endif
 279 
 280   _requested_base_address = compute_shared_base(cds_max);
 281   SharedBaseAddress = (size_t)_requested_base_address;
 282 
 283   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 284   _symbol_rs = ReservedSpace(symbol_rs_size);

 445   // Need to do this first, as subsequent steps may call virtual functions
 446   // in archived Metadata objects.
 447   CppVtables::serialize(soc);
 448   soc->do_tag(--tag);
 449 
 450   // Dump/restore miscellaneous metadata.
 451   JavaClasses::serialize_offsets(soc);
 452   Universe::serialize(soc);
 453   soc->do_tag(--tag);
 454 
 455   // Dump/restore references to commonly used names and signatures.
 456   vmSymbols::serialize(soc);
 457   soc->do_tag(--tag);
 458 
 459   // Dump/restore the symbol/string/subgraph_info tables
 460   SymbolTable::serialize_shared_table_header(soc);
 461   StringTable::serialize_shared_table_header(soc);
 462   HeapShared::serialize_tables(soc);
 463   SystemDictionaryShared::serialize_dictionary_headers(soc);
 464   AOTLinkedClassBulkLoader::serialize(soc, true);


 465   InstanceMirrorKlass::serialize_offsets(soc);
 466 
 467   // Dump/restore well known classes (pointers)
 468   SystemDictionaryShared::serialize_vm_classes(soc);
 469   soc->do_tag(--tag);
 470 
 471   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 472   soc->do_ptr((void**)&_archived_method_handle_intrinsics);
 473 
 474   LambdaFormInvokers::serialize(soc);
 475   soc->do_tag(666);
 476 }
 477 
 478 static void rewrite_nofast_bytecode(const methodHandle& method) {
 479   BytecodeStream bcs(method);
 480   while (!bcs.is_last_bytecode()) {
 481     Bytecodes::Code opcode = bcs.next();
 482     switch (opcode) {
 483     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 484     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;

 529     VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
 530 
 531   bool skip_operation() const { return false; }
 532 
 533   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 534   ArchiveHeapInfo* heap_info()  { return &_heap_info; }
 535   FileMapInfo* map_info() const { return _map_info; }
 536   void doit();   // outline because gdb sucks
 537   bool allow_nested_vm_operations() const { return true; }
 538 }; // class VM_PopulateDumpSharedSpace
 539 
 540 class StaticArchiveBuilder : public ArchiveBuilder {
 541 public:
 542   StaticArchiveBuilder() : ArchiveBuilder() {}
 543 
 544   virtual void iterate_roots(MetaspaceClosure* it) {
 545     FileMapInfo::metaspace_pointers_do(it);
 546     SystemDictionaryShared::dumptime_classes_do(it);
 547     Universe::metaspace_pointers_do(it);
 548     vmSymbols::metaspace_pointers_do(it);

 549 
 550     // The above code should find all the symbols that are referenced by the
 551     // archived classes. We just need to add the extra symbols which
 552     // may not be used by any of the archived classes -- these are usually
 553     // symbols that we anticipate to be used at run time, so we can store
 554     // them in the RO region, to be shared across multiple processes.
 555     if (_extra_symbols != nullptr) {
 556       for (int i = 0; i < _extra_symbols->length(); i++) {
 557         it->push(_extra_symbols->adr_at(i));
 558       }
 559     }
 560 
 561     for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
 562       it->push(_pending_method_handle_intrinsics->adr_at(i));
 563     }
 564   }
 565 };
 566 
 567 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
 568   ArchiveBuilder::OtherROAllocMark mark;
 569 
 570   // Write module name into archive
 571   CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
 572   // Write module names from --add-modules into archive
 573   CDS_JAVA_HEAP_ONLY(Modules::dump_addmods_names();)
 574 
 575   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 576   char* start = ro_region->top();
 577   WriteClosure wc(ro_region);
 578   MetaspaceShared::early_serialize(&wc);
 579   return start;
 580 }
 581 
 582 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 583   ArchiveBuilder::OtherROAllocMark mark;
 584 
 585   SystemDictionaryShared::write_to_archive();
 586   AOTClassLinker::write_to_archive();





 587   MetaspaceShared::write_method_handle_intrinsics();
 588 
 589   // Write lambform lines into archive
 590   LambdaFormInvokers::dump_static_archive_invokers();
 591 
 592   // Write the other data to the output array.
 593   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 594   char* start = ro_region->top();
 595   WriteClosure wc(ro_region);
 596   MetaspaceShared::serialize(&wc);
 597 
 598   return start;
 599 }
 600 
 601 void VM_PopulateDumpSharedSpace::doit() {
 602   guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
 603 
 604   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 605 
 606   _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 607   if (CDSConfig::is_dumping_aot_linked_classes()) {
 608     // When dumping AOT-linked classes, some classes may have direct references to a method handle
 609     // intrinsic. The easiest thing is to save all of them into the AOT cache.
 610     SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
 611   }
 612 
 613   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 614 
 615   NOT_PRODUCT(SystemDictionary::verify();)
 616 
 617   // Block concurrent class unloading from changing the _dumptime_table
 618   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 619   SystemDictionaryShared::find_all_archivable_classes();
 620 
 621   _builder.gather_source_objs();
 622   _builder.reserve_buffer();
 623 
 624   CppVtables::dumptime_init(&_builder);
 625 
 626   _builder.sort_metadata_objs();
 627   _builder.dump_rw_metadata();
 628   _builder.dump_ro_metadata();
 629   _builder.relocate_metaspaceobj_embedded_pointers();
 630 
 631   dump_java_heap_objects(_builder.klasses());
 632   dump_shared_symbol_table(_builder.symbols());
 633 
 634   log_info(cds)("Make classes shareable");
 635   _builder.make_klasses_shareable();
 636   MetaspaceShared::make_method_handle_intrinsics_shareable();
 637 
 638   char* early_serialized_data = dump_early_read_only_tables();
 639   char* serialized_data = dump_read_only_tables();
 640 
 641   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 642 



 643   // The vtable clones contain addresses of the current process.
 644   // We don't want to write these addresses into the archive.
 645   CppVtables::zero_archived_vtables();
 646 
 647   // Write the archive file
 648   const char* static_archive = CDSConfig::static_archive_path();







 649   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 650   _map_info = new FileMapInfo(static_archive, true);
 651   _map_info->populate_header(MetaspaceShared::core_region_alignment());
 652   _map_info->set_early_serialized_data(early_serialized_data);
 653   _map_info->set_serialized_data(serialized_data);
 654   _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
 655 }
 656 
 657 class CollectCLDClosure : public CLDClosure {
 658   GrowableArray<ClassLoaderData*> _loaded_cld;
 659   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 660   Thread* _current_thread;
 661 public:
 662   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 663   ~CollectCLDClosure() {
 664     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 665       _loaded_cld_handles.at(i).release(Universe::vm_global());
 666     }
 667   }
 668   void do_cld(ClassLoaderData* cld) {
 669     assert(cld->is_alive(), "must be");
 670     _loaded_cld.append(cld);
 671     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 672   }
 673 
 674   int nof_cld() const                { return _loaded_cld.length(); }
 675   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 676 };
 677 
 678 // Check if we can eagerly link this class at dump time, so we can avoid the
 679 // runtime linking overhead (especially verification)
 680 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {



 681   if (!ik->can_be_verified_at_dumptime()) {
 682     // For old classes, try to leave them in the unlinked state, so
 683     // we can still store them in the archive. They must be
 684     // linked/verified at runtime.
 685     return false;
 686   }

 687   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 688     // Linking of unregistered classes at this stage may cause more
 689     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 690     // that may not be expected by custom class loaders.
 691     //
 692     // It's OK to do this for the built-in loaders as we know they can
 693     // tolerate this.
 694     return false;
 695   }
 696   return true;
 697 }
 698 
 699 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
 700   // Link the class to cause the bytecodes to be rewritten and the
 701   // cpcache to be created. Class verification is done according
 702   // to -Xverify setting.
 703   bool res = MetaspaceShared::try_link_class(THREAD, ik);
 704   AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK_(false));
 705   return res;
 706 }
 707 
 708 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
 709   AOTClassLinker::initialize();
 710 
 711   if (!jcmd_request) {






 712     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 713   }
 714 
 715   // Collect all loaded ClassLoaderData.
 716   CollectCLDClosure collect_cld(THREAD);
 717   {
 718     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 719     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 720     // Therefore, we need to first collect all the CLDs, and then link their classes after
 721     // releasing the lock.
 722     MutexLocker lock(ClassLoaderDataGraph_lock);
 723     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 724   }
 725 
 726   while (true) {
 727     bool has_linked = false;
 728     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 729       ClassLoaderData* cld = collect_cld.cld_at(i);
 730       for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 731         if (klass->is_instance_klass()) {
 732           InstanceKlass* ik = InstanceKlass::cast(klass);
 733           if (may_be_eagerly_linked(ik)) {
 734             has_linked |= link_class_for_cds(ik, CHECK);



 735           }
 736         }
 737       }
 738     }
 739 
 740     if (!has_linked) {
 741       break;
 742     }
 743     // Class linking includes verification which may load more classes.
 744     // Keep scanning until we have linked no more classes.
 745   }




























 746 }
 747 
 748 void MetaspaceShared::prepare_for_dumping() {
 749   assert(CDSConfig::is_dumping_archive(), "sanity");
 750   CDSConfig::check_unsupported_dumping_module_options();
 751   ClassLoader::initialize_shared_path(JavaThread::current());
 752 }
 753 
 754 // Preload classes from a list, populate the shared spaces and dump to a
 755 // file.
 756 void MetaspaceShared::preload_and_dump(TRAPS) {
 757   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 758   ResourceMark rm(THREAD);







 759   StaticArchiveBuilder builder;
 760   preload_and_dump_impl(builder, THREAD);
 761   if (HAS_PENDING_EXCEPTION) {
 762     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 763       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 764                      SIZE_FORMAT "M", MaxHeapSize/M);
 765       MetaspaceShared::writing_error();
 766     } else {
 767       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 768                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 769       MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
 770     }
 771   }
 772 
 773   if (!CDSConfig::old_cds_flags_used()) {
 774     // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 775     // When the new -XX:AOTMode=create flag is used, we can't return
 776     // to the JLI launcher, as the launcher will fail when trying to
 777     // run the main class, which is not what we want.
 778     tty->print_cr("AOTCache creation is complete: %s", AOTCache);
 779     vm_exit(0);
 780   }
 781 }
 782 
 783 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 784 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 785   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 786     return;
 787   }
 788   // CDS heap dumping requires all string oops to have an offset
 789   // from the heap bottom that can be encoded in 32-bit.
 790   julong max_heap_size = (julong)(4 * G);
 791 
 792   if (MinHeapSize > max_heap_size) {
 793     log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);

 858     }
 859   }
 860 
 861   // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
 862   // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
 863   // are archived.
 864   exercise_runtime_cds_code(CHECK);
 865 
 866   log_info(cds)("Loading classes to share: done.");
 867 }
 868 
 869 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
 870   // Exercise the manifest processing code
 871   const char* dummy = "Manifest-Version: 1.0\n";
 872   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 873 
 874   // Exercise FileSystem and URL code
 875   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 876 }
 877 







 878 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 879   preload_classes(CHECK);








 880 
 881   if (SharedArchiveConfigFile) {
 882     log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 883     read_extra_data(THREAD, SharedArchiveConfigFile);
 884     log_info(cds)("Reading extra data: done.");












 885   }
 886 
 887   // Rewrite and link classes
 888   log_info(cds)("Rewriting and linking classes ...");
 889 
 890   // Link any classes which got missed. This would happen if we have loaded classes that
 891   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 892   // fails verification, all other interfaces that were not specified in the classlist but
 893   // are implemented by K are not verified.
 894   link_shared_classes(false/*not from jcmd*/, CHECK);
 895   log_info(cds)("Rewriting and linking classes: done");
 896 







 897 #if INCLUDE_CDS_JAVA_HEAP
 898   if (CDSConfig::is_dumping_heap()) {
 899     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
 900       log_info(cds)("archivedBootLayer not available, disabling full module graph");
 901       CDSConfig::stop_dumping_full_module_graph();
 902     }
 903     HeapShared::init_for_dumping(CHECK);
 904     ArchiveHeapWriter::init();
 905     if (CDSConfig::is_dumping_full_module_graph()) {
 906       HeapShared::reset_archived_object_states(CHECK);
 907     }
 908 




 909     if (CDSConfig::is_dumping_invokedynamic()) {
 910       // This assert means that the MethodType and MethodTypeForm tables won't be
 911       // updated concurrently when we are saving their contents into a side table.
 912       assert(CDSConfig::allow_only_single_java_thread(), "Required");
 913 
 914       JavaValue result(T_VOID);
 915       JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
 916                              vmSymbols::createArchivedObjects(),
 917                              vmSymbols::void_method_signature(),
 918                              CHECK);
 919 
 920       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
 921       // to null, and it will be initialized again at runtime.
 922       log_debug(cds)("Resetting Class::reflectionFactory");
 923       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
 924       Symbol* method_sig = vmSymbols::void_method_signature();
 925       JavaCalls::call_static(&result, vmClasses::Class_klass(),
 926                              method_name, method_sig, CHECK);
 927 
 928       // Perhaps there is a way to avoid hard-coding these names here.
 929       // See discussion in JDK-8342481.
 930     }
 931 
 932     // Do this at the very end, when no Java code will be executed. Otherwise
 933     // some new strings may be added to the intern table.
 934     StringTable::allocate_shared_strings_array(CHECK);
 935   } else {
 936     log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
 937     CDSConfig::stop_using_optimized_module_handling();
 938   }
 939 #endif
 940 
 941   VM_PopulateDumpSharedSpace op(builder);
 942   VMThread::execute(&op);


































 943 
 944   if (!write_static_archive(&builder, op.map_info(), op.heap_info())) {
 945     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
 946   }
 947 }
 948 
 949 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
 950   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 951   // without runtime relocation.
 952   builder->relocate_to_requested();
 953 
 954   map_info->open_for_write();
 955   if (!map_info->is_open()) {
 956     return false;
 957   }
 958   builder->write_archive(map_info, heap_info);
 959 
 960   if (AllowArchivingWithJavaAgent) {
 961     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 962             "for testing purposes only and should not be used in a production environment");
 963   }
 964   return true;
 965 }
 966 




















































































 967 // Returns true if the class's status has changed.
 968 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
 969   ExceptionMark em(current);
 970   JavaThread* THREAD = current; // For exception macros.
 971   assert(CDSConfig::is_dumping_archive(), "sanity");
 972   if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&






 973       !SystemDictionaryShared::has_class_failed_verification(ik)) {
 974     bool saved = BytecodeVerificationLocal;
 975     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
 976       // The verification decision is based on BytecodeVerificationRemote
 977       // for non-system classes. Since we are using the null classloader
 978       // to load non-system classes for customized class loaders during dumping,
 979       // we need to temporarily change BytecodeVerificationLocal to be the same as
 980       // BytecodeVerificationRemote. Note this can cause the parent system
 981       // classes also being verified. The extra overhead is acceptable during
 982       // dumping.
 983       BytecodeVerificationLocal = BytecodeVerificationRemote;
 984     }
 985     ik->link_class(THREAD);
 986     if (HAS_PENDING_EXCEPTION) {
 987       ResourceMark rm(THREAD);
 988       log_warning(cds)("Preload Warning: Verification failed for %s",
 989                     ik->external_name());
 990       CLEAR_PENDING_EXCEPTION;
 991       SystemDictionaryShared::set_class_has_failed_verification(ik);
 992     }
 993     ik->compute_has_loops_flag_for_methods();
 994     BytecodeVerificationLocal = saved;
 995     return true;
 996   } else {
 997     return false;
 998   }
 999 }
1000 
1001 #if INCLUDE_CDS_JAVA_HEAP
1002 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1003   if(!HeapShared::can_write()) {
1004     log_info(cds)(

1005       "Archived java heap is not supported as UseG1GC "
1006       "and UseCompressedClassPointers are required."
1007       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1008       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));

1009     return;
1010   }
1011   // Find all the interned strings that should be dumped.
1012   int i;
1013   for (i = 0; i < klasses->length(); i++) {
1014     Klass* k = klasses->at(i);
1015     if (k->is_instance_klass()) {
1016       InstanceKlass* ik = InstanceKlass::cast(k);
1017       if (ik->is_linked()) {
1018         ik->constants()->add_dumped_interned_strings();
1019       }
1020     }
1021   }
1022   if (_extra_interned_strings != nullptr) {
1023     for (i = 0; i < _extra_interned_strings->length(); i ++) {
1024       OopHandle string = _extra_interned_strings->at(i);
1025       HeapShared::add_to_dumped_interned_strings(string.resolve());
1026     }
1027   }
1028 

1071 // This function is called when the JVM is unable to write the specified CDS archive due to an
1072 // unrecoverable error.
1073 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1074   writing_error(message);
1075   vm_direct_exit(1);
1076 }
1077 
1078 // This function is called when the JVM is unable to write the specified CDS archive due to a
1079 // an error. The error will be propagated
1080 void MetaspaceShared::writing_error(const char* message) {
1081   log_error(cds)("An error has occurred while writing the shared archive file.");
1082   if (message != nullptr) {
1083     log_error(cds)("%s", message);
1084   }
1085 }
1086 
1087 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1088   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1089   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1090 
1091   FileMapInfo* static_mapinfo = open_static_archive();
1092   FileMapInfo* dynamic_mapinfo = nullptr;
1093 
1094   if (static_mapinfo != nullptr) {
1095     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1096     dynamic_mapinfo = open_dynamic_archive();
1097 
1098     // First try to map at the requested address
1099     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1100     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1101       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1102       // by the OS.
1103       log_info(cds)("Try to map archive(s) at an alternative address");
1104       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1105     }
1106   }
1107 
1108   if (result == MAP_ARCHIVE_SUCCESS) {
1109     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1110     char* cds_base = static_mapinfo->mapped_base();
1111     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();

1118       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1119       // turn AutoCreateSharedArchive off if successfully mapped
1120       AutoCreateSharedArchive = false;
1121     } else {
1122       FileMapInfo::set_shared_path_table(static_mapinfo);
1123     }
1124   } else {
1125     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1126     if (CDSConfig::is_dumping_dynamic_archive()) {
1127       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1128     }
1129     UseSharedSpaces = false;
1130     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1131     AutoCreateSharedArchive = false;
1132     CDSConfig::disable_dumping_dynamic_archive();
1133     log_info(cds)("Unable to map shared spaces");
1134     if (PrintSharedArchiveAndExit) {
1135       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1136     } else if (RequireSharedSpaces) {
1137       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");




1138     }
1139   }
1140 
1141   // If mapping failed and -XShare:on, the vm should exit
1142   bool has_failed = false;
1143   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1144     has_failed = true;
1145     delete static_mapinfo;
1146   }
1147   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1148     has_failed = true;
1149     delete dynamic_mapinfo;
1150   }
1151   if (RequireSharedSpaces && has_failed) {

1152       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1153   }
1154 }
1155 
1156 FileMapInfo* MetaspaceShared::open_static_archive() {





1157   const char* static_archive = CDSConfig::static_archive_path();
1158   assert(static_archive != nullptr, "sanity");
1159   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1160   if (!mapinfo->initialize()) {
1161     delete(mapinfo);
1162     return nullptr;


1163   }
1164   return mapinfo;
1165 }
1166 
1167 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1168   if (CDSConfig::is_dumping_dynamic_archive()) {
1169     return nullptr;
1170   }
1171   const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1172   if (dynamic_archive == nullptr) {
1173     return nullptr;
1174   }
1175 
1176   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1177   if (!mapinfo->initialize()) {
1178     delete(mapinfo);
1179     if (RequireSharedSpaces) {
1180       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1181     }
1182     return nullptr;
1183   }
1184   return mapinfo;

1569     if (archive_space_rs.is_reserved()) {
1570       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1571       archive_space_rs.release();
1572     }
1573     if (class_space_rs.is_reserved()) {
1574       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1575       class_space_rs.release();
1576     }
1577   }
1578 }
1579 
1580 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1581 static int archive_regions_count = 2;
1582 
1583 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1584   assert(CDSConfig::is_using_archive(), "must be runtime");
1585   if (mapinfo == nullptr) {
1586     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1587   }
1588 




1589   mapinfo->set_is_mapped(false);
1590   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1591     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1592                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1593     return MAP_ARCHIVE_OTHER_FAILURE;
1594   }
1595 
1596   MapArchiveResult result =
1597     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1598 
1599   if (result != MAP_ARCHIVE_SUCCESS) {
1600     unmap_archive(mapinfo);
1601     return result;
1602   }
1603 
1604   if (!mapinfo->validate_shared_path_table()) {
1605     unmap_archive(mapinfo);
1606     return MAP_ARCHIVE_OTHER_FAILURE;
1607   }
1608 

1646 };
1647 
1648 // Read the miscellaneous data from the shared file, and
1649 // serialize it out to its various destinations.
1650 
1651 void MetaspaceShared::initialize_shared_spaces() {
1652   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1653 
1654   // Verify various attributes of the archive, plus initialize the
1655   // shared string/symbol tables.
1656   char* buffer = static_mapinfo->serialized_data();
1657   intptr_t* array = (intptr_t*)buffer;
1658   ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1659   serialize(&rc);
1660 
1661   // Finish up archived heap initialization. These must be
1662   // done after ReadClosure.
1663   static_mapinfo->patch_heap_embedded_pointers();
1664   ArchiveHeapLoader::finish_initialization();
1665   Universe::load_archived_object_instances();

1666 
1667   // Close the mapinfo file
1668   static_mapinfo->close();
1669 
1670   static_mapinfo->unmap_region(MetaspaceShared::bm);
1671 
1672   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1673   if (dynamic_mapinfo != nullptr) {
1674     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1675     ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1676     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1677     DynamicArchive::setup_array_klasses();
1678     dynamic_mapinfo->close();
1679     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1680   }
1681 
1682   LogStreamHandle(Info, cds) lsh;
1683   if (lsh.is_enabled()) {
1684     lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1685               BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),

1696     // Read stored LF format lines stored in static archive
1697     LambdaFormInvokers::read_static_archive_invokers();
1698   }
1699 
1700   if (PrintSharedArchiveAndExit) {
1701     // Print archive names
1702     if (dynamic_mapinfo != nullptr) {
1703       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1704       tty->print_cr("Base archive version %d", static_mapinfo->version());
1705     } else {
1706       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1707       tty->print_cr("Static archive version %d", static_mapinfo->version());
1708     }
1709 
1710     SystemDictionaryShared::print_shared_archive(tty);
1711     if (dynamic_mapinfo != nullptr) {
1712       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1713       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1714       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1715     }






1716 
1717     // collect shared symbols and strings
1718     CountSharedSymbols cl;
1719     SymbolTable::shared_symbols_do(&cl);
1720     tty->print_cr("Number of shared symbols: %d", cl.total());
1721     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1722     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1723     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1724       tty->print_cr("archive is invalid");
1725       vm_exit(1);
1726     } else {
1727       tty->print_cr("archive is valid");
1728       vm_exit(0);
1729     }
1730   }
1731 }
1732 
1733 // JVM/TI RedefineClasses() support:
1734 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1735   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");

   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/aotClassInitializer.hpp"
  27 #include "cds/aotClassLinker.hpp"
  28 #include "cds/aotConstantPoolResolver.hpp"
  29 #include "cds/aotLinkedClassBulkLoader.hpp"
  30 #include "cds/archiveBuilder.hpp"
  31 #include "cds/archiveHeapLoader.hpp"
  32 #include "cds/archiveHeapWriter.hpp"
  33 #include "cds/cds_globals.hpp"
  34 #include "cds/cdsAccess.hpp"
  35 #include "cds/cdsConfig.hpp"
  36 #include "cds/cdsProtectionDomain.hpp"
  37 #include "cds/classListParser.hpp"
  38 #include "cds/classListWriter.hpp"
  39 #include "cds/cppVtables.hpp"
  40 #include "cds/dumpAllocStats.hpp"
  41 #include "cds/dynamicArchive.hpp"
  42 #include "cds/filemap.hpp"
  43 #include "cds/finalImageRecipes.hpp"
  44 #include "cds/heapShared.hpp"
  45 #include "cds/lambdaFormInvokers.hpp"
  46 #include "cds/metaspaceShared.hpp"
  47 #include "classfile/classLoaderDataGraph.hpp"
  48 #include "classfile/classLoaderDataShared.hpp"
  49 #include "classfile/classLoaderExt.hpp"
  50 #include "classfile/javaClasses.inline.hpp"
  51 #include "classfile/loaderConstraints.hpp"
  52 #include "classfile/modules.hpp"
  53 #include "classfile/placeholders.hpp"
  54 #include "classfile/stringTable.hpp"
  55 #include "classfile/symbolTable.hpp"
  56 #include "classfile/systemDictionary.hpp"
  57 #include "classfile/systemDictionaryShared.hpp"
  58 #include "classfile/vmClasses.hpp"
  59 #include "classfile/vmSymbols.hpp"
  60 #include "code/codeCache.hpp"
  61 #include "code/SCCache.hpp"
  62 #include "compiler/compileBroker.hpp"
  63 #include "compiler/precompiler.hpp"
  64 #include "gc/shared/gcVMOperations.hpp"
  65 #include "interpreter/bytecodeStream.hpp"
  66 #include "interpreter/bytecodes.hpp"
  67 #include "jvm_io.h"
  68 #include "logging/log.hpp"
  69 #include "logging/logMessage.hpp"
  70 #include "logging/logStream.hpp"
  71 #include "memory/metaspace.hpp"
  72 #include "memory/metaspaceClosure.hpp"
  73 #include "memory/resourceArea.hpp"
  74 #include "memory/universe.hpp"
  75 #include "nmt/memTracker.hpp"
  76 #include "oops/compressedKlass.hpp"
  77 #include "oops/instanceMirrorKlass.hpp"
  78 #include "oops/klass.inline.hpp"
  79 #include "oops/method.inline.hpp"
  80 #include "oops/objArrayOop.hpp"
  81 #include "oops/oop.inline.hpp"
  82 #include "oops/oopHandle.hpp"
  83 #include "oops/trainingData.hpp"
  84 #include "prims/jvmtiExport.hpp"
  85 #include "prims/whitebox.hpp"
  86 #include "runtime/arguments.hpp"
  87 #include "runtime/globals.hpp"
  88 #include "runtime/globals_extension.hpp"
  89 #include "runtime/handles.inline.hpp"
  90 #include "runtime/javaCalls.hpp"
  91 #include "runtime/os.inline.hpp"
  92 #include "runtime/safepointVerifiers.hpp"
  93 #include "runtime/sharedRuntime.hpp"
  94 #include "runtime/vmOperations.hpp"
  95 #include "runtime/vmThread.hpp"
  96 #include "sanitizers/leak.hpp"
  97 #include "utilities/align.hpp"
  98 #include "utilities/bitMap.inline.hpp"
  99 #include "utilities/defaultStream.hpp"
 100 #include "utilities/macros.hpp"
 101 #include "utilities/ostream.hpp"
 102 #include "utilities/resourceHash.hpp"
 103 
 104 ReservedSpace MetaspaceShared::_symbol_rs;
 105 VirtualSpace MetaspaceShared::_symbol_vs;
 106 bool MetaspaceShared::_archive_loading_failed = false;
 107 bool MetaspaceShared::_remapped_readwrite = false;
 108 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 109 intx MetaspaceShared::_relocation_delta;
 110 char* MetaspaceShared::_requested_base_address;
 111 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 112 bool MetaspaceShared::_use_optimized_module_handling = true;
 113 int volatile MetaspaceShared::_preimage_static_archive_dumped = 0;
 114 
 115 // The CDS archive is divided into the following regions:
 116 //     rw  - read-write metadata
 117 //     ro  - read-only metadata and read-only tables
 118 //     hp  - heap region
 119 //     bm  - bitmap for relocating the above 7 regions.
 120 //
 121 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 122 // These regions are aligned with MetaspaceShared::core_region_alignment().
 123 //
 124 // These 2 regions are populated in the following steps:
 125 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 126 //     temporarily allocated outside of the shared regions.
 127 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 128 // [2] C++ vtables are copied into the rw region.
 129 // [3] ArchiveBuilder copies RW metadata into the rw region.
 130 // [4] ArchiveBuilder copies RO metadata into the ro region.
 131 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 132 //     are copied into the ro region as read-only tables.
 133 //

 255     err = "invalid for this platform";
 256   } else {
 257     return aligned_base;
 258   }
 259 
 260   log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
 261                    p2i((void*)SharedBaseAddress), err,
 262                    p2i((void*)Arguments::default_SharedBaseAddress()));
 263 
 264   specified_base = (char*)Arguments::default_SharedBaseAddress();
 265   aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
 266 
 267   // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
 268   assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
 269   assert(shared_base_valid(aligned_base), "Sanity");
 270   return aligned_base;
 271 }
 272 
 273 void MetaspaceShared::initialize_for_static_dump() {
 274   assert(CDSConfig::is_dumping_static_archive(), "sanity");
 275 
 276   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
 277     if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
 278       vm_exit_during_initialization("Cannot create the CacheDataStore",
 279                                     "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah");
 280     }
 281   }
 282 
 283   log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
 284   // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
 285   // to avoid address space wrap around.
 286   size_t cds_max;
 287   const size_t reserve_alignment = core_region_alignment();
 288 
 289 #ifdef _LP64
 290   const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 291   cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
 292 #else
 293   // We don't support archives larger than 256MB on 32-bit due to limited
 294   //  virtual address space.
 295   cds_max = align_down(256*M, reserve_alignment);
 296 #endif
 297 
 298   _requested_base_address = compute_shared_base(cds_max);
 299   SharedBaseAddress = (size_t)_requested_base_address;
 300 
 301   size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
 302   _symbol_rs = ReservedSpace(symbol_rs_size);

 463   // Need to do this first, as subsequent steps may call virtual functions
 464   // in archived Metadata objects.
 465   CppVtables::serialize(soc);
 466   soc->do_tag(--tag);
 467 
 468   // Dump/restore miscellaneous metadata.
 469   JavaClasses::serialize_offsets(soc);
 470   Universe::serialize(soc);
 471   soc->do_tag(--tag);
 472 
 473   // Dump/restore references to commonly used names and signatures.
 474   vmSymbols::serialize(soc);
 475   soc->do_tag(--tag);
 476 
 477   // Dump/restore the symbol/string/subgraph_info tables
 478   SymbolTable::serialize_shared_table_header(soc);
 479   StringTable::serialize_shared_table_header(soc);
 480   HeapShared::serialize_tables(soc);
 481   SystemDictionaryShared::serialize_dictionary_headers(soc);
 482   AOTLinkedClassBulkLoader::serialize(soc, true);
 483   FinalImageRecipes::serialize(soc, true);
 484   TrainingData::serialize_training_data(soc);
 485   InstanceMirrorKlass::serialize_offsets(soc);
 486 
 487   // Dump/restore well known classes (pointers)
 488   SystemDictionaryShared::serialize_vm_classes(soc);
 489   soc->do_tag(--tag);
 490 
 491   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 492   soc->do_ptr((void**)&_archived_method_handle_intrinsics);
 493 
 494   LambdaFormInvokers::serialize(soc);
 495   soc->do_tag(666);
 496 }
 497 
 498 static void rewrite_nofast_bytecode(const methodHandle& method) {
 499   BytecodeStream bcs(method);
 500   while (!bcs.is_last_bytecode()) {
 501     Bytecodes::Code opcode = bcs.next();
 502     switch (opcode) {
 503     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 504     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;

 549     VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
 550 
 551   bool skip_operation() const { return false; }
 552 
 553   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 554   ArchiveHeapInfo* heap_info()  { return &_heap_info; }
 555   FileMapInfo* map_info() const { return _map_info; }
 556   void doit();   // outline because gdb sucks
 557   bool allow_nested_vm_operations() const { return true; }
 558 }; // class VM_PopulateDumpSharedSpace
 559 
 560 class StaticArchiveBuilder : public ArchiveBuilder {
 561 public:
 562   StaticArchiveBuilder() : ArchiveBuilder() {}
 563 
 564   virtual void iterate_roots(MetaspaceClosure* it) {
 565     FileMapInfo::metaspace_pointers_do(it);
 566     SystemDictionaryShared::dumptime_classes_do(it);
 567     Universe::metaspace_pointers_do(it);
 568     vmSymbols::metaspace_pointers_do(it);
 569     TrainingData::iterate_roots(it);
 570 
 571     // The above code should find all the symbols that are referenced by the
 572     // archived classes. We just need to add the extra symbols which
 573     // may not be used by any of the archived classes -- these are usually
 574     // symbols that we anticipate to be used at run time, so we can store
 575     // them in the RO region, to be shared across multiple processes.
 576     if (_extra_symbols != nullptr) {
 577       for (int i = 0; i < _extra_symbols->length(); i++) {
 578         it->push(_extra_symbols->adr_at(i));
 579       }
 580     }
 581 
 582     for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
 583       it->push(_pending_method_handle_intrinsics->adr_at(i));
 584     }
 585   }
 586 };
 587 
 588 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
 589   ArchiveBuilder::OtherROAllocMark mark;
 590 
 591   // Write module name into archive
 592   CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
 593   // Write module names from --add-modules into archive
 594   CDS_JAVA_HEAP_ONLY(Modules::dump_addmods_names();)
 595 
 596   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 597   char* start = ro_region->top();
 598   WriteClosure wc(ro_region);
 599   MetaspaceShared::early_serialize(&wc);
 600   return start;
 601 }
 602 
 603 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 604   ArchiveBuilder::OtherROAllocMark mark;
 605 
 606   SystemDictionaryShared::write_to_archive();
 607   AOTClassLinker::write_to_archive();
 608   if (CDSConfig::is_dumping_preimage_static_archive()) {
 609     FinalImageRecipes::record_recipes();
 610   }
 611   AOTLinkedClassBulkLoader::record_unregistered_classes();
 612   TrainingData::dump_training_data();
 613   MetaspaceShared::write_method_handle_intrinsics();
 614 
 615   // Write lambform lines into archive
 616   LambdaFormInvokers::dump_static_archive_invokers();
 617 
 618   // Write the other data to the output array.
 619   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 620   char* start = ro_region->top();
 621   WriteClosure wc(ro_region);
 622   MetaspaceShared::serialize(&wc);
 623 
 624   return start;
 625 }
 626 
 627 void VM_PopulateDumpSharedSpace::doit() {
 628   //guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
 629 
 630   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 631 
 632   _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 633   if (CDSConfig::is_dumping_aot_linked_classes()) {
 634     // When dumping AOT-linked classes, some classes may have direct references to a method handle
 635     // intrinsic. The easiest thing is to save all of them into the AOT cache.
 636     SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
 637   }
 638 
 639   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 640 
 641   NOT_PRODUCT(SystemDictionary::verify();)
 642 
 643   // Block concurrent class unloading from changing the _dumptime_table
 644   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 645   SystemDictionaryShared::find_all_archivable_classes();
 646 
 647   _builder.gather_source_objs();
 648   _builder.reserve_buffer();
 649 
 650   CppVtables::dumptime_init(&_builder);
 651 
 652   _builder.sort_metadata_objs();
 653   _builder.dump_rw_metadata();
 654   _builder.dump_ro_metadata();
 655   _builder.relocate_metaspaceobj_embedded_pointers();
 656 
 657   dump_java_heap_objects(_builder.klasses());
 658   dump_shared_symbol_table(_builder.symbols());
 659 
 660   log_info(cds)("Make classes shareable");
 661   _builder.make_klasses_shareable();
 662   MetaspaceShared::make_method_handle_intrinsics_shareable();
 663 
 664   char* early_serialized_data = dump_early_read_only_tables();
 665   char* serialized_data = dump_read_only_tables();
 666 
 667   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 668 
 669   log_info(cds)("Make training data shareable");
 670   _builder.make_training_data_shareable();
 671 
 672   // The vtable clones contain addresses of the current process.
 673   // We don't want to write these addresses into the archive.
 674   CppVtables::zero_archived_vtables();
 675 
 676   // Write the archive file
 677   const char* static_archive;
 678   if (CDSConfig::is_dumping_final_static_archive()) {
 679     static_archive = CacheDataStore;
 680     assert(FileMapInfo::current_info() != nullptr, "sanity");
 681     delete FileMapInfo::current_info();
 682   } else {
 683     static_archive = CDSConfig::static_archive_path();
 684   }
 685   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 686   _map_info = new FileMapInfo(static_archive, true);
 687   _map_info->populate_header(MetaspaceShared::core_region_alignment());
 688   _map_info->set_early_serialized_data(early_serialized_data);
 689   _map_info->set_serialized_data(serialized_data);
 690   _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
 691 }
 692 
 693 class CollectCLDClosure : public CLDClosure {
 694   GrowableArray<ClassLoaderData*> _loaded_cld;
 695   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 696   Thread* _current_thread;
 697 public:
 698   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 699   ~CollectCLDClosure() {
 700     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 701       _loaded_cld_handles.at(i).release(Universe::vm_global());
 702     }
 703   }
 704   void do_cld(ClassLoaderData* cld) {
 705     assert(cld->is_alive(), "must be");
 706     _loaded_cld.append(cld);
 707     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 708   }
 709 
 710   int nof_cld() const                { return _loaded_cld.length(); }
 711   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 712 };
 713 
 714 // Check if we can eagerly link this class at dump time, so we can avoid the
 715 // runtime linking overhead (especially verification)
 716 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 717   if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
 718     assert(ik->can_be_verified_at_dumptime(), "sanity");
 719   }
 720   if (!ik->can_be_verified_at_dumptime()) {
 721     // For old classes, try to leave them in the unlinked state, so
 722     // we can still store them in the archive. They must be
 723     // linked/verified at runtime.
 724     return false;
 725   }
 726 
 727   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 728     // Linking of unregistered classes at this stage may cause more
 729     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 730     // that may not be expected by custom class loaders.
 731     //
 732     // It's OK to do this for the built-in loaders as we know they can
 733     // tolerate this.
 734     return false;
 735   }
 736   return true;
 737 }
 738 








 739 
 740 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
 741   AOTClassLinker::initialize();
 742 
 743   if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
 744       && !CDSConfig::is_dumping_preimage_static_archive()
 745       && !CDSConfig::is_dumping_final_static_archive()) {
 746     // If we have regenerated invoker classes in the dynamic archive,
 747     // they will conflict with the resolved CONSTANT_Klass references that are stored
 748     // in the static archive. This is not easy to handle. Let's disable
 749     // it for dynamic archive for now.
 750     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 751   }
 752 
 753   // Collect all loaded ClassLoaderData.
 754   CollectCLDClosure collect_cld(THREAD);
 755   {
 756     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 757     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 758     // Therefore, we need to first collect all the CLDs, and then link their classes after
 759     // releasing the lock.
 760     MutexLocker lock(ClassLoaderDataGraph_lock);
 761     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 762   }
 763 
 764   while (true) {
 765     bool has_linked = false;
 766     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 767       ClassLoaderData* cld = collect_cld.cld_at(i);
 768       for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 769         if (klass->is_instance_klass()) {
 770           InstanceKlass* ik = InstanceKlass::cast(klass);
 771           if (may_be_eagerly_linked(ik)) {
 772             has_linked |= try_link_class(THREAD, ik);
 773           }
 774           if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 775             AOTClassInitializer::maybe_preinit_class(ik, CHECK);
 776           }
 777         }
 778       }
 779     }
 780 
 781     if (!has_linked) {
 782       break;
 783     }
 784     // Class linking includes verification which may load more classes.
 785     // Keep scanning until we have linked no more classes.
 786   }
 787 
 788   // Resolve constant pool entries -- we don't load any new classes during this stage
 789   for (int i = 0; i < collect_cld.nof_cld(); i++) {
 790     ClassLoaderData* cld = collect_cld.cld_at(i);
 791     for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 792       if (klass->is_instance_klass()) {
 793         InstanceKlass* ik = InstanceKlass::cast(klass);
 794         AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
 795         if (CDSConfig::is_dumping_preimage_static_archive()) {
 796           FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 797         }
 798       }
 799     }
 800   }
 801 
 802   if (CDSConfig::is_dumping_preimage_static_archive()) {
 803     // Do this after all classes are verified by the above loop.
 804     // Any classes loaded from here on will be automatically excluded, so
 805     // there's no need to force verification or resolve CP entries.
 806     RecordTraining = false;
 807     SystemDictionaryShared::ignore_new_classes();
 808     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 809     RecordTraining = true;
 810   }
 811 
 812   if (CDSConfig::is_dumping_final_static_archive()) {
 813     FinalImageRecipes::apply_recipes(CHECK);
 814   }
 815 }
 816 
 817 void MetaspaceShared::prepare_for_dumping() {
 818   assert(CDSConfig::is_dumping_archive(), "sanity");
 819   CDSConfig::check_unsupported_dumping_module_options();
 820   ClassLoader::initialize_shared_path(JavaThread::current());
 821 }
 822 
 823 // Preload classes from a list, populate the shared spaces and dump to a
 824 // file.
 825 void MetaspaceShared::preload_and_dump(TRAPS) {
 826   CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
 827   ResourceMark rm(THREAD);
 828   HandleMark hm(THREAD);
 829 
 830   if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
 831     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 832     TrainingData::print_archived_training_data_on(tty);
 833   }
 834 
 835   StaticArchiveBuilder builder;
 836   preload_and_dump_impl(builder, THREAD);
 837   if (HAS_PENDING_EXCEPTION) {
 838     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 839       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 840                      SIZE_FORMAT "M", MaxHeapSize/M);
 841       MetaspaceShared::writing_error();
 842     } else {
 843       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 844                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 845       MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
 846     }
 847   }
 848 
 849   if (!CDSConfig::old_cds_flags_used() && !CDSConfig::is_dumping_preimage_static_archive() && !CDSConfig::is_dumping_final_static_archive()) {
 850     // The JLI launcher only recognizes the "old" -Xshare:dump flag.
 851     // When the new -XX:AOTMode=create flag is used, we can't return
 852     // to the JLI launcher, as the launcher will fail when trying to
 853     // run the main class, which is not what we want.
 854     tty->print_cr("AOTCache creation is complete: %s", AOTCache);
 855     vm_exit(0);
 856   }
 857 }
 858 
 859 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 860 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 861   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 862     return;
 863   }
 864   // CDS heap dumping requires all string oops to have an offset
 865   // from the heap bottom that can be encoded in 32-bit.
 866   julong max_heap_size = (julong)(4 * G);
 867 
 868   if (MinHeapSize > max_heap_size) {
 869     log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);

 934     }
 935   }
 936 
 937   // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
 938   // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
 939   // are archived.
 940   exercise_runtime_cds_code(CHECK);
 941 
 942   log_info(cds)("Loading classes to share: done.");
 943 }
 944 
 945 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
 946   // Exercise the manifest processing code
 947   const char* dummy = "Manifest-Version: 1.0\n";
 948   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 949 
 950   // Exercise FileSystem and URL code
 951   CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
 952 }
 953 
 954 bool MetaspaceShared::is_recording_preimage_static_archive() {
 955   if (CDSConfig::is_dumping_preimage_static_archive()) {
 956       return _preimage_static_archive_dumped == 0;
 957   }
 958   return false;
 959 }
 960 
 961 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 962   if (CDSConfig::is_dumping_preimage_static_archive()) {
 963     if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
 964       return;
 965     }
 966   }
 967 
 968   if (CDSConfig::is_dumping_classic_static_archive()) {
 969     // We are running with -Xshare:dump
 970     preload_classes(CHECK);
 971 
 972     if (SharedArchiveConfigFile) {
 973       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 974       read_extra_data(THREAD, SharedArchiveConfigFile);
 975       log_info(cds)("Reading extra data: done.");
 976     }
 977   }
 978 
 979   if (CDSConfig::is_dumping_preimage_static_archive()) {
 980     log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
 981     char default_classlist[JVM_MAXPATHLEN];
 982     get_default_classlist(default_classlist, sizeof(default_classlist));
 983     struct stat statbuf;
 984     if (os::stat(default_classlist, &statbuf) == 0) {
 985       ClassListParser::parse_classlist(default_classlist,
 986                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 987     }
 988   }
 989 
 990   // Rewrite and link classes
 991   log_info(cds)("Rewriting and linking classes ...");
 992 
 993   // Link any classes which got missed. This would happen if we have loaded classes that
 994   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 995   // fails verification, all other interfaces that were not specified in the classlist but
 996   // are implemented by K are not verified.
 997   link_shared_classes(false/*not from jcmd*/, CHECK);
 998   log_info(cds)("Rewriting and linking classes: done");
 999 
1000   if (CDSConfig::is_dumping_final_static_archive()) {
1001     assert(RecordTraining == false, "must be");
1002     RecordTraining = true;
1003   }
1004 
1005   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1006 
1007 #if INCLUDE_CDS_JAVA_HEAP
1008   if (CDSConfig::is_dumping_heap()) {
1009     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1010       log_info(cds)("archivedBootLayer not available, disabling full module graph");
1011       CDSConfig::stop_dumping_full_module_graph();
1012     }
1013     HeapShared::init_for_dumping(CHECK);
1014     ArchiveHeapWriter::init();
1015     if (CDSConfig::is_dumping_full_module_graph()) {
1016       HeapShared::reset_archived_object_states(CHECK);
1017     }
1018 
1019     if (ArchiveLoaderLookupCache) {
1020       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1021     }
1022 
1023     if (CDSConfig::is_dumping_invokedynamic()) {
1024       // This assert means that the MethodType and MethodTypeForm tables won't be
1025       // updated concurrently when we are saving their contents into a side table.
1026       assert(CDSConfig::allow_only_single_java_thread(), "Required");
1027 
1028       JavaValue result(T_VOID);
1029       JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
1030                              vmSymbols::createArchivedObjects(),
1031                              vmSymbols::void_method_signature(),
1032                              CHECK);
1033 
1034       // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1035       // to null, and it will be initialized again at runtime.
1036       log_debug(cds)("Resetting Class::reflectionFactory");
1037       TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1038       Symbol* method_sig = vmSymbols::void_method_signature();
1039       JavaCalls::call_static(&result, vmClasses::Class_klass(),
1040                              method_name, method_sig, CHECK);
1041 
1042       // Perhaps there is a way to avoid hard-coding these names here.
1043       // See discussion in JDK-8342481.
1044     }
1045 
1046     // Do this at the very end, when no Java code will be executed. Otherwise
1047     // some new strings may be added to the intern table.
1048     StringTable::allocate_shared_strings_array(CHECK);
1049   } else {
1050     log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1051     CDSConfig::stop_using_optimized_module_handling();
1052   }
1053 #endif
1054 
1055   VM_PopulateDumpSharedSpace op(builder);
1056   VMThread::execute(&op);
1057   FileMapInfo* mapinfo = op.map_info();
1058   ArchiveHeapInfo* heap_info = op.heap_info();
1059   bool status;
1060   if (CDSConfig::is_dumping_preimage_static_archive()) {
1061     if ((status = write_static_archive(&builder, mapinfo, heap_info))) {
1062       fork_and_dump_final_static_archive();
1063     }
1064   } else if (CDSConfig::is_dumping_final_static_archive()) {
1065     RecordTraining = false;
1066     if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
1067       if (log_is_enabled(Info, cds, jit)) {
1068         CDSAccess::test_heap_access_api();
1069       }
1070 
1071       // We have just created the final image. Let's run the AOT compiler
1072       if (PrintTrainingInfo) {
1073         tty->print_cr("==================== archived_training_data ** after dumping ====================");
1074         TrainingData::print_archived_training_data_on(tty);
1075       }
1076 
1077       CDSConfig::enable_dumping_cached_code();
1078       {
1079         builder.start_cc_region();
1080         Precompiler::compile_cached_code(&builder, CHECK);
1081         builder.end_cc_region();
1082       }
1083       CDSConfig::disable_dumping_cached_code();
1084 
1085       SCCache::close(); // Write final data and close archive
1086     }
1087     status = write_static_archive(&builder, mapinfo, heap_info);
1088   } else {
1089     status = write_static_archive(&builder, mapinfo, heap_info);
1090   }
1091 
1092   if (!status) {
1093     THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1094   }
1095 }
1096 
1097 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1098   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1099   // without runtime relocation.
1100   builder->relocate_to_requested();
1101 
1102   map_info->open_for_write();
1103   if (!map_info->is_open()) {
1104     return false;
1105   }
1106   builder->write_archive(map_info, heap_info);
1107 
1108   if (AllowArchivingWithJavaAgent) {
1109     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1110             "for testing purposes only and should not be used in a production environment");
1111   }
1112   return true;
1113 }
1114 
1115 static void print_java_launcher(outputStream* st) {
1116   st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1117 }
1118 
1119 static void print_vm_arguments(outputStream* st) {
1120   const char* cp = Arguments::get_appclasspath();
1121   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1122     st->print(" -cp ");  st->print_raw(cp);
1123   }
1124   for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1125     st->print(" %s", Arguments::jvm_flags_array()[i]);
1126   }
1127   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1128     st->print(" %s", Arguments::jvm_args_array()[i]);
1129   }
1130 }
1131 
1132 void MetaspaceShared::fork_and_dump_final_static_archive() {
1133   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1134 
1135   ResourceMark rm;
1136   stringStream ss;
1137   print_java_launcher(&ss);
1138   print_vm_arguments(&ss);
1139   ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1140 
1141   const char* cmd = ss.freeze();
1142   if (CDSManualFinalImage) {
1143     tty->print_cr("-XX:+CDSManualFinalImage is specified");
1144     tty->print_cr("Please manually execute the following command to create the final CDS image:");
1145     tty->print("    "); tty->print_raw_cr(cmd);
1146 
1147     // The following is useful if the dumping was trigger by a script that builds
1148     // a complex command-line.
1149     tty->print_cr("Note: to recreate the preimage only:");
1150     tty->print_cr("    rm -f %s", CacheDataStore);
1151     tty->print("    ");
1152     print_java_launcher(tty);
1153     print_vm_arguments(tty);
1154     if (Arguments::java_command() != nullptr) {
1155       tty->print(" %s", Arguments::java_command());
1156     }
1157     tty->cr();
1158   } else {
1159     // FIXME: space characters are not properly quoated. E.g.,
1160     //      java -Dfoo='a b c' HelloWorld
1161     log_info(cds)("Launching child process to create final CDS image:");
1162     log_info(cds)("    %s", cmd);
1163     int status = os::fork_and_exec(cmd);
1164     if (status != 0) {
1165       log_error(cds)("Child process finished; status = %d", status);
1166       log_error(cds)("To reproduce the error");
1167       ResourceMark rm;
1168       LogStream ls(Log(cds)::error());
1169       ls.print("    "); ls.print_raw_cr(cmd);
1170 
1171       // The following is useful if the dumping was trigger by a script that builds
1172       // a complex command-line.
1173       ls.print_cr("Note: to recreate the preimage only:");
1174       ls.print_cr("    rm -f %s", CacheDataStore);
1175       ls.print("    ");
1176       print_java_launcher(&ls);
1177       print_vm_arguments(&ls);
1178       ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1179       if (Arguments::java_command() != nullptr) {
1180         ls.print(" %s", Arguments::java_command());
1181       }
1182       ls.cr();
1183 
1184       vm_direct_exit(status);
1185     } else {
1186       log_info(cds)("Child process finished; status = %d", status);
1187       // On Windows, need WRITE permission to remove the file.
1188       WINDOWS_ONLY(chmod(SharedArchiveFile, _S_IREAD | _S_IWRITE));
1189       status = remove(SharedArchiveFile);
1190       if (status != 0) {
1191         log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1192       } else {
1193         log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1194       }
1195     }
1196   }
1197 }
1198 
1199 // Returns true if the class's status has changed.
1200 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1201   ExceptionMark em(current);
1202   JavaThread* THREAD = current; // For exception macros.
1203   assert(CDSConfig::is_dumping_archive(), "sanity");
1204 
1205   if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1206     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1207     return false;
1208   }
1209 
1210   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1211       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1212     bool saved = BytecodeVerificationLocal;
1213     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1214       // The verification decision is based on BytecodeVerificationRemote
1215       // for non-system classes. Since we are using the null classloader
1216       // to load non-system classes for customized class loaders during dumping,
1217       // we need to temporarily change BytecodeVerificationLocal to be the same as
1218       // BytecodeVerificationRemote. Note this can cause the parent system
1219       // classes also being verified. The extra overhead is acceptable during
1220       // dumping.
1221       BytecodeVerificationLocal = BytecodeVerificationRemote;
1222     }
1223     ik->link_class(THREAD);
1224     if (HAS_PENDING_EXCEPTION) {
1225       ResourceMark rm(THREAD);
1226       log_warning(cds)("Preload Warning: Verification failed for %s",
1227                     ik->external_name());
1228       CLEAR_PENDING_EXCEPTION;
1229       SystemDictionaryShared::set_class_has_failed_verification(ik);
1230     }
1231     ik->compute_has_loops_flag_for_methods();
1232     BytecodeVerificationLocal = saved;
1233     return true;
1234   } else {
1235     return false;
1236   }
1237 }
1238 
1239 #if INCLUDE_CDS_JAVA_HEAP
1240 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1241   if(!HeapShared::can_write()) {
1242     if (!CDSConfig::is_dumping_preimage_static_archive()) {
1243      log_info(cds)(
1244       "Archived java heap is not supported as UseG1GC "
1245       "and UseCompressedClassPointers are required."
1246       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1247       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1248     }
1249     return;
1250   }
1251   // Find all the interned strings that should be dumped.
1252   int i;
1253   for (i = 0; i < klasses->length(); i++) {
1254     Klass* k = klasses->at(i);
1255     if (k->is_instance_klass()) {
1256       InstanceKlass* ik = InstanceKlass::cast(k);
1257       if (ik->is_linked()) {
1258         ik->constants()->add_dumped_interned_strings();
1259       }
1260     }
1261   }
1262   if (_extra_interned_strings != nullptr) {
1263     for (i = 0; i < _extra_interned_strings->length(); i ++) {
1264       OopHandle string = _extra_interned_strings->at(i);
1265       HeapShared::add_to_dumped_interned_strings(string.resolve());
1266     }
1267   }
1268 

1311 // This function is called when the JVM is unable to write the specified CDS archive due to an
1312 // unrecoverable error.
1313 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1314   writing_error(message);
1315   vm_direct_exit(1);
1316 }
1317 
1318 // This function is called when the JVM is unable to write the specified CDS archive due to a
1319 // an error. The error will be propagated
1320 void MetaspaceShared::writing_error(const char* message) {
1321   log_error(cds)("An error has occurred while writing the shared archive file.");
1322   if (message != nullptr) {
1323     log_error(cds)("%s", message);
1324   }
1325 }
1326 
1327 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1328   assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1329   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1330 
1331   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1332   FileMapInfo* dynamic_mapinfo = nullptr;
1333 
1334   if (static_mapinfo != nullptr) {
1335     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1336     dynamic_mapinfo = open_dynamic_archive();
1337 
1338     // First try to map at the requested address
1339     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1340     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1341       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1342       // by the OS.
1343       log_info(cds)("Try to map archive(s) at an alternative address");
1344       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1345     }
1346   }
1347 
1348   if (result == MAP_ARCHIVE_SUCCESS) {
1349     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1350     char* cds_base = static_mapinfo->mapped_base();
1351     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();

1358       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1359       // turn AutoCreateSharedArchive off if successfully mapped
1360       AutoCreateSharedArchive = false;
1361     } else {
1362       FileMapInfo::set_shared_path_table(static_mapinfo);
1363     }
1364   } else {
1365     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1366     if (CDSConfig::is_dumping_dynamic_archive()) {
1367       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1368     }
1369     UseSharedSpaces = false;
1370     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1371     AutoCreateSharedArchive = false;
1372     CDSConfig::disable_dumping_dynamic_archive();
1373     log_info(cds)("Unable to map shared spaces");
1374     if (PrintSharedArchiveAndExit) {
1375       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1376     } else if (RequireSharedSpaces) {
1377       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1378     } else if (CDSConfig::is_dumping_final_static_archive()) {
1379       assert(CDSPreimage != nullptr, "must be");
1380       log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1381       MetaspaceShared::unrecoverable_loading_error();
1382     }
1383   }
1384 
1385   // If mapping failed and -XShare:on, the vm should exit
1386   bool has_failed = false;
1387   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1388     has_failed = true;
1389     delete static_mapinfo;
1390   }
1391   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1392     has_failed = true;
1393     delete dynamic_mapinfo;
1394   }
1395   if (RequireSharedSpaces && has_failed) {
1396     // static archive mapped but dynamic archive failed
1397       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1398   }
1399 }
1400 
1401 // This is called very early at VM start up to get the size of the cached_code region, which
1402 // is used in CodeCache::initialize_heaps()
1403 void MetaspaceShared::open_static_archive() {
1404   if (!UseSharedSpaces) {
1405     return;
1406   }
1407   const char* static_archive = CDSConfig::static_archive_path();
1408   assert(static_archive != nullptr, "sanity");
1409   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1410   if (!mapinfo->initialize()) {
1411     delete(mapinfo);
1412   } else {
1413     FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1414     CDSAccess::set_cached_code_size(r->used_aligned());
1415   }

1416 }
1417 
1418 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1419   if (CDSConfig::is_dumping_dynamic_archive()) {
1420     return nullptr;
1421   }
1422   const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1423   if (dynamic_archive == nullptr) {
1424     return nullptr;
1425   }
1426 
1427   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1428   if (!mapinfo->initialize()) {
1429     delete(mapinfo);
1430     if (RequireSharedSpaces) {
1431       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1432     }
1433     return nullptr;
1434   }
1435   return mapinfo;

1820     if (archive_space_rs.is_reserved()) {
1821       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1822       archive_space_rs.release();
1823     }
1824     if (class_space_rs.is_reserved()) {
1825       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1826       class_space_rs.release();
1827     }
1828   }
1829 }
1830 
1831 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1832 static int archive_regions_count = 2;
1833 
1834 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1835   assert(CDSConfig::is_using_archive(), "must be runtime");
1836   if (mapinfo == nullptr) {
1837     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1838   }
1839 
1840   if (!mapinfo->validate_aot_class_linking()) {
1841     return MAP_ARCHIVE_OTHER_FAILURE;
1842   }
1843 
1844   mapinfo->set_is_mapped(false);
1845   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1846     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1847                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1848     return MAP_ARCHIVE_OTHER_FAILURE;
1849   }
1850 
1851   MapArchiveResult result =
1852     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1853 
1854   if (result != MAP_ARCHIVE_SUCCESS) {
1855     unmap_archive(mapinfo);
1856     return result;
1857   }
1858 
1859   if (!mapinfo->validate_shared_path_table()) {
1860     unmap_archive(mapinfo);
1861     return MAP_ARCHIVE_OTHER_FAILURE;
1862   }
1863 

1901 };
1902 
1903 // Read the miscellaneous data from the shared file, and
1904 // serialize it out to its various destinations.
1905 
1906 void MetaspaceShared::initialize_shared_spaces() {
1907   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1908 
1909   // Verify various attributes of the archive, plus initialize the
1910   // shared string/symbol tables.
1911   char* buffer = static_mapinfo->serialized_data();
1912   intptr_t* array = (intptr_t*)buffer;
1913   ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1914   serialize(&rc);
1915 
1916   // Finish up archived heap initialization. These must be
1917   // done after ReadClosure.
1918   static_mapinfo->patch_heap_embedded_pointers();
1919   ArchiveHeapLoader::finish_initialization();
1920   Universe::load_archived_object_instances();
1921   SCCache::new_workflow_load_cache();
1922 
1923   // Close the mapinfo file
1924   static_mapinfo->close();
1925 
1926   static_mapinfo->unmap_region(MetaspaceShared::bm);
1927 
1928   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1929   if (dynamic_mapinfo != nullptr) {
1930     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1931     ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1932     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1933     DynamicArchive::setup_array_klasses();
1934     dynamic_mapinfo->close();
1935     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1936   }
1937 
1938   LogStreamHandle(Info, cds) lsh;
1939   if (lsh.is_enabled()) {
1940     lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1941               BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),

1952     // Read stored LF format lines stored in static archive
1953     LambdaFormInvokers::read_static_archive_invokers();
1954   }
1955 
1956   if (PrintSharedArchiveAndExit) {
1957     // Print archive names
1958     if (dynamic_mapinfo != nullptr) {
1959       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1960       tty->print_cr("Base archive version %d", static_mapinfo->version());
1961     } else {
1962       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1963       tty->print_cr("Static archive version %d", static_mapinfo->version());
1964     }
1965 
1966     SystemDictionaryShared::print_shared_archive(tty);
1967     if (dynamic_mapinfo != nullptr) {
1968       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1969       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1970       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1971     }
1972     TrainingData::print_archived_training_data_on(tty);
1973 
1974     if (LoadCachedCode) {
1975       tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
1976       SCCache::print_on(tty);
1977     }
1978 
1979     // collect shared symbols and strings
1980     CountSharedSymbols cl;
1981     SymbolTable::shared_symbols_do(&cl);
1982     tty->print_cr("Number of shared symbols: %d", cl.total());
1983     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1984     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1985     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1986       tty->print_cr("archive is invalid");
1987       vm_exit(1);
1988     } else {
1989       tty->print_cr("archive is valid");
1990       vm_exit(0);
1991     }
1992   }
1993 }
1994 
1995 // JVM/TI RedefineClasses() support:
1996 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1997   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
< prev index next >