< prev index next >

src/hotspot/share/cds/metaspaceShared.cpp

Print this page

  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/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/cds_globals.hpp"

  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/cdsProtectionDomain.hpp"
  32 #include "cds/cds_globals.hpp"
  33 #include "cds/classListParser.hpp"
  34 #include "cds/classListWriter.hpp"

  35 #include "cds/classPrelinker.hpp"

  36 #include "cds/cppVtables.hpp"
  37 #include "cds/dumpAllocStats.hpp"
  38 #include "cds/dynamicArchive.hpp"
  39 #include "cds/filemap.hpp"

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



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

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

  75 #include "prims/jvmtiExport.hpp"

  76 #include "runtime/arguments.hpp"
  77 #include "runtime/globals.hpp"
  78 #include "runtime/globals_extension.hpp"
  79 #include "runtime/handles.inline.hpp"

  80 #include "runtime/os.inline.hpp"
  81 #include "runtime/safepointVerifiers.hpp"
  82 #include "runtime/sharedRuntime.hpp"
  83 #include "runtime/vmOperations.hpp"
  84 #include "runtime/vmThread.hpp"
  85 #include "sanitizers/leak.hpp"
  86 #include "utilities/align.hpp"
  87 #include "utilities/bitMap.inline.hpp"
  88 #include "utilities/defaultStream.hpp"
  89 #include "utilities/ostream.hpp"
  90 #include "utilities/resourceHash.hpp"
  91 
  92 ReservedSpace MetaspaceShared::_symbol_rs;
  93 VirtualSpace MetaspaceShared::_symbol_vs;
  94 bool MetaspaceShared::_archive_loading_failed = false;
  95 bool MetaspaceShared::_remapped_readwrite = false;
  96 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
  97 intx MetaspaceShared::_relocation_delta;
  98 char* MetaspaceShared::_requested_base_address;

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

 282   if (UseSharedSpaces) {
 283     int size = FileMapInfo::get_number_of_shared_paths();
 284     if (size > 0) {
 285       CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
 286       if (!CDSConfig::is_dumping_dynamic_archive()) {
 287         FileMapInfo* info;
 288         if (FileMapInfo::dynamic_info() == nullptr) {
 289           info = FileMapInfo::current_info();
 290         } else {
 291           info = FileMapInfo::dynamic_info();
 292         }
 293         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 294         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 295       }
 296     }
 297   }
 298 }
 299 
 300 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
 301 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;

 302 
 303 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
 304   _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
 305   _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
 306 
 307   HashtableTextDump reader(filename);
 308   reader.check_version("VERSION: 1.0");
 309 
 310   while (reader.remain() > 0) {
 311     int utf8_length;
 312     int prefix_type = reader.scan_prefix(&utf8_length);
 313     ResourceMark rm(current);
 314     if (utf8_length == 0x7fffffff) {
 315       // buf_len will overflown 32-bit value.
 316       log_error(cds)("string length too large: %d", utf8_length);
 317       MetaspaceShared::unrecoverable_loading_error();
 318     }
 319     int buf_len = utf8_length+1;
 320     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 321     reader.get_utf8(utf8_buffer, utf8_length);

 332       if (HAS_PENDING_EXCEPTION) {
 333         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 334                                reader.last_line_no(), utf8_length);
 335         CLEAR_PENDING_EXCEPTION;
 336       } else {
 337 #if INCLUDE_CDS_JAVA_HEAP
 338         if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) {
 339           log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 340                                  reader.last_line_no(), utf8_length);
 341           continue;
 342         }
 343         // Make sure this string is included in the dumped interned string table.
 344         assert(str != nullptr, "must succeed");
 345         _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
 346 #endif
 347       }
 348     }
 349   }
 350 }
 351 



















 352 // Read/write a data stream for restoring/preserving metadata pointers and
 353 // miscellaneous data from/to the shared archive file.
 354 
 355 void MetaspaceShared::serialize(SerializeClosure* soc) {
 356   int tag = 0;
 357   soc->do_tag(--tag);
 358 
 359   // Verify the sizes of various metadata in the system.
 360   soc->do_tag(sizeof(Method));
 361   soc->do_tag(sizeof(ConstMethod));
 362   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 363   soc->do_tag(sizeof(ConstantPool));
 364   soc->do_tag(sizeof(ConstantPoolCache));
 365   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 366   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 367   soc->do_tag(sizeof(Symbol));
 368 
 369   // Need to do this first, as subsequent steps may call virtual functions
 370   // in archived Metadata objects.
 371   CppVtables::serialize(soc);
 372   soc->do_tag(--tag);
 373 
 374   // Dump/restore miscellaneous metadata.
 375   JavaClasses::serialize_offsets(soc);

 376   Universe::serialize(soc);
 377   soc->do_tag(--tag);
 378 
 379   // Dump/restore references to commonly used names and signatures.
 380   vmSymbols::serialize(soc);
 381   soc->do_tag(--tag);
 382 
 383   // Dump/restore the symbol/string/subgraph_info tables
 384   SymbolTable::serialize_shared_table_header(soc);
 385   StringTable::serialize_shared_table_header(soc);
 386   HeapShared::serialize_tables(soc);
 387   SystemDictionaryShared::serialize_dictionary_headers(soc);
 388 


 389   InstanceMirrorKlass::serialize_offsets(soc);
 390 
 391   // Dump/restore well known classes (pointers)
 392   SystemDictionaryShared::serialize_vm_classes(soc);
 393   soc->do_tag(--tag);
 394 
 395   CDS_JAVA_HEAP_ONLY(Modules::serialize(soc);)
 396   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)


 397 
 398   LambdaFormInvokers::serialize(soc);
 399   soc->do_tag(666);
 400 }
 401 
 402 static void rewrite_nofast_bytecode(const methodHandle& method) {
 403   BytecodeStream bcs(method);
 404   while (!bcs.is_last_bytecode()) {
 405     Bytecodes::Code opcode = bcs.next();
 406     switch (opcode) {
 407     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 408     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 409     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 410     case Bytecodes::_iload: {
 411       if (!bcs.is_wide()) {
 412         *bcs.bcp() = Bytecodes::_nofast_iload;
 413       }
 414       break;
 415     }
 416     default: break;

 419 }
 420 
 421 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 422 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 423 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 424 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 425   for (int i = 0; i < ik->methods()->length(); i++) {
 426     methodHandle m(thread, ik->methods()->at(i));
 427     if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
 428       rewrite_nofast_bytecode(m);
 429     }
 430     Fingerprinter fp(m);
 431     // The side effect of this call sets method's fingerprint field.
 432     fp.fingerprint();
 433   }
 434 }
 435 
 436 class VM_PopulateDumpSharedSpace : public VM_Operation {
 437 private:
 438   ArchiveHeapInfo _heap_info;
 439 
 440   void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
 441   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 442     log_info(cds)("Dumping symbol table ...");
 443     SymbolTable::write_to_archive(symbols);
 444   }
 445   char* dump_read_only_tables();
 446 

 447 public:
 448 
 449   VM_PopulateDumpSharedSpace() : VM_Operation(), _heap_info() {}

 450 
 451   bool skip_operation() const { return false; }
 452 
 453   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 454   void doit();   // outline because gdb sucks
 455   bool allow_nested_vm_operations() const { return true; }


 456 }; // class VM_PopulateDumpSharedSpace
 457 
 458 class StaticArchiveBuilder : public ArchiveBuilder {
 459 public:
 460   StaticArchiveBuilder() : ArchiveBuilder() {}
 461 
 462   virtual void iterate_roots(MetaspaceClosure* it) {
 463     FileMapInfo::metaspace_pointers_do(it);
 464     SystemDictionaryShared::dumptime_classes_do(it);
 465     Universe::metaspace_pointers_do(it);
 466     vmSymbols::metaspace_pointers_do(it);

 467 
 468     // The above code should find all the symbols that are referenced by the
 469     // archived classes. We just need to add the extra symbols which
 470     // may not be used by any of the archived classes -- these are usually
 471     // symbols that we anticipate to be used at run time, so we can store
 472     // them in the RO region, to be shared across multiple processes.
 473     if (_extra_symbols != nullptr) {
 474       for (int i = 0; i < _extra_symbols->length(); i++) {
 475         it->push(_extra_symbols->adr_at(i));
 476       }
 477     }




 478   }
 479 };
 480 
 481 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 482   ArchiveBuilder::OtherROAllocMark mark;
 483 
 484   SystemDictionaryShared::write_to_archive();




 485 
 486   // Write lambform lines into archive
 487   LambdaFormInvokers::dump_static_archive_invokers();
 488   // Write module name into archive
 489   CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
 490   // Write the other data to the output array.
 491   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 492   char* start = ro_region->top();
 493   WriteClosure wc(ro_region);
 494   MetaspaceShared::serialize(&wc);
 495 
 496   return start;
 497 }
 498 
 499 void VM_PopulateDumpSharedSpace::doit() {
 500   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 501 
 502   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 503 
 504   NOT_PRODUCT(SystemDictionary::verify();)
 505 
 506   // Block concurrent class unloading from changing the _dumptime_table
 507   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 508   SystemDictionaryShared::check_excluded_classes();
 509 
 510   StaticArchiveBuilder builder;
 511   builder.gather_source_objs();
 512   builder.reserve_buffer();
 513 
 514   CppVtables::dumptime_init(&builder);
 515 
 516   builder.sort_metadata_objs();
 517   builder.dump_rw_metadata();
 518   builder.dump_ro_metadata();
 519   builder.relocate_metaspaceobj_embedded_pointers();
 520 
 521   dump_java_heap_objects(builder.klasses());
 522   dump_shared_symbol_table(builder.symbols());








 523 
 524   log_info(cds)("Make classes shareable");
 525   builder.make_klasses_shareable();

 526 
 527   char* serialized_data = dump_read_only_tables();
 528 
 529   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 530 






 531   // The vtable clones contain addresses of the current process.
 532   // We don't want to write these addresses into the archive.
 533   CppVtables::zero_archived_vtables();
 534 
 535   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 536   // without runtime relocation.
 537   builder.relocate_to_requested();
 538 
 539   // Write the archive file
 540   const char* static_archive = CDSConfig::static_archive_path();
 541   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 542   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
 543   mapinfo->populate_header(MetaspaceShared::core_region_alignment());
 544   mapinfo->set_serialized_data(serialized_data);
 545   mapinfo->set_cloned_vtables(CppVtables::vtables_serialized_base());
 546   mapinfo->open_for_write();
 547   builder.write_archive(mapinfo, &_heap_info);
 548 
 549   if (PrintSystemDictionaryAtExit) {
 550     SystemDictionary::print();
 551   }
 552 
 553   if (AllowArchivingWithJavaAgent) {
 554     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 555             "for testing purposes only and should not be used in a production environment");
 556   }





 557 }
 558 
 559 class CollectCLDClosure : public CLDClosure {
 560   GrowableArray<ClassLoaderData*> _loaded_cld;
 561   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 562   Thread* _current_thread;
 563 public:
 564   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 565   ~CollectCLDClosure() {
 566     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 567       _loaded_cld_handles.at(i).release(Universe::vm_global());
 568     }
 569   }
 570   void do_cld(ClassLoaderData* cld) {
 571     assert(cld->is_alive(), "must be");
 572     _loaded_cld.append(cld);
 573     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 574   }
 575 
 576   int nof_cld() const                { return _loaded_cld.length(); }
 577   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 578 };
 579 
 580 // Check if we can eagerly link this class at dump time, so we can avoid the
 581 // runtime linking overhead (especially verification)
 582 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {



 583   if (!ik->can_be_verified_at_dumptime()) {
 584     // For old classes, try to leave them in the unlinked state, so
 585     // we can still store them in the archive. They must be
 586     // linked/verified at runtime.
 587     return false;
 588   }

 589   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 590     // Linking of unregistered classes at this stage may cause more
 591     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 592     // that may not be expected by custom class loaders.
 593     //
 594     // It's OK to do this for the built-in loaders as we know they can
 595     // tolerate this.
 596     return false;
 597   }
 598   return true;
 599 }
 600 
 601 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
 602   // Link the class to cause the bytecodes to be rewritten and the
 603   // cpcache to be created. Class verification is done according
 604   // to -Xverify setting.
 605   bool res = MetaspaceShared::try_link_class(THREAD, ik);
 606   ClassPrelinker::dumptime_resolve_constants(ik, CHECK_(false));
 607   return res;
 608 }
 609 
 610 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {

 611   ClassPrelinker::initialize();
 612 
 613   if (!jcmd_request) {






 614     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 615   }
 616 
 617   // Collect all loaded ClassLoaderData.
 618   CollectCLDClosure collect_cld(THREAD);
 619   {
 620     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 621     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 622     // Therefore, we need to first collect all the CLDs, and then link their classes after
 623     // releasing the lock.
 624     MutexLocker lock(ClassLoaderDataGraph_lock);
 625     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 626   }
 627 
 628   while (true) {
 629     bool has_linked = false;
 630     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 631       ClassLoaderData* cld = collect_cld.cld_at(i);
 632       for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 633         if (klass->is_instance_klass()) {
 634           InstanceKlass* ik = InstanceKlass::cast(klass);
 635           if (may_be_eagerly_linked(ik)) {
 636             has_linked |= link_class_for_cds(ik, CHECK);



 637           }
 638         }
 639       }
 640     }
 641 
 642     if (!has_linked) {
 643       break;
 644     }
 645     // Class linking includes verification which may load more classes.
 646     // Keep scanning until we have linked no more classes.
 647   }




























 648 }
 649 
 650 void MetaspaceShared::prepare_for_dumping() {
 651   assert(CDSConfig::is_dumping_archive(), "sanity");
 652   CDSConfig::check_unsupported_dumping_module_options();
 653   ClassLoader::initialize_shared_path(JavaThread::current());
 654 }
 655 
 656 // Preload classes from a list, populate the shared spaces and dump to a
 657 // file.
 658 void MetaspaceShared::preload_and_dump() {
 659   EXCEPTION_MARK;
 660   ResourceMark rm(THREAD);
 661   preload_and_dump_impl(THREAD);








 662   if (HAS_PENDING_EXCEPTION) {
 663     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 664       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 665                      SIZE_FORMAT "M", MaxHeapSize/M);
 666       CLEAR_PENDING_EXCEPTION;
 667       MetaspaceShared::unrecoverable_writing_error();
 668     } else {
 669       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 670                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 671       CLEAR_PENDING_EXCEPTION;
 672       MetaspaceShared::unrecoverable_writing_error("VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
 673     }
 674   }
 675 }
 676 
 677 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 678 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 679   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 680     return;
 681   }

 743     ClassListParser::parse_classlist(ExtraSharedClassListFile,
 744                                      ClassListParser::_parse_all, CHECK);
 745   }
 746   if (classlist_path != default_classlist) {
 747     struct stat statbuf;
 748     if (os::stat(default_classlist, &statbuf) == 0) {
 749       // File exists, let's use it.
 750       ClassListParser::parse_classlist(default_classlist,
 751                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 752     }
 753   }
 754 
 755   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 756   // are always archived
 757   const char* dummy = "Manifest-Version: 1.0\n";
 758   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 759 
 760   log_info(cds)("Loading classes to share: done.");
 761 }
 762 
 763 void MetaspaceShared::preload_and_dump_impl(TRAPS) {
 764   preload_classes(CHECK);


 765 
 766   if (SharedArchiveConfigFile) {
 767     log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 768     read_extra_data(THREAD, SharedArchiveConfigFile);
 769     log_info(cds)("Reading extra data: done.");












 770   }
 771 












 772   // Rewrite and link classes
 773   log_info(cds)("Rewriting and linking classes ...");
 774 
 775   // Link any classes which got missed. This would happen if we have loaded classes that
 776   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 777   // fails verification, all other interfaces that were not specified in the classlist but
 778   // are implemented by K are not verified.
 779   link_shared_classes(false/*not from jcmd*/, CHECK);
 780   log_info(cds)("Rewriting and linking classes: done");
 781 










 782 #if INCLUDE_CDS_JAVA_HEAP
 783   if (CDSConfig::is_dumping_heap()) {
 784     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
 785       log_info(cds)("archivedBootLayer not available, disabling full module graph");
 786       CDSConfig::stop_dumping_full_module_graph();
 787     }
 788     HeapShared::init_for_dumping(CHECK);
 789     ArchiveHeapWriter::init();
 790     if (CDSConfig::is_dumping_full_module_graph()) {
 791       HeapShared::reset_archived_object_states(CHECK);
 792     }
 793 




 794     // Do this at the very end, when no Java code will be executed. Otherwise
 795     // some new strings may be added to the intern table.
 796     StringTable::allocate_shared_strings_array(CHECK);
 797   }
 798 #endif
 799 
 800   VM_PopulateDumpSharedSpace op;
 801   VMThread::execute(&op);

































































































 802 }
 803 
 804 // Returns true if the class's status has changed.
 805 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
 806   ExceptionMark em(current);
 807   JavaThread* THREAD = current; // For exception macros.
 808   assert(CDSConfig::is_dumping_archive(), "sanity");
 809   if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&






 810       !SystemDictionaryShared::has_class_failed_verification(ik)) {
 811     bool saved = BytecodeVerificationLocal;
 812     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
 813       // The verification decision is based on BytecodeVerificationRemote
 814       // for non-system classes. Since we are using the null classloader
 815       // to load non-system classes for customized class loaders during dumping,
 816       // we need to temporarily change BytecodeVerificationLocal to be the same as
 817       // BytecodeVerificationRemote. Note this can cause the parent system
 818       // classes also being verified. The extra overhead is acceptable during
 819       // dumping.
 820       BytecodeVerificationLocal = BytecodeVerificationRemote;
 821     }
 822     ik->link_class(THREAD);
 823     if (HAS_PENDING_EXCEPTION) {
 824       ResourceMark rm(THREAD);
 825       log_warning(cds)("Preload Warning: Verification failed for %s",
 826                     ik->external_name());
 827       CLEAR_PENDING_EXCEPTION;
 828       SystemDictionaryShared::set_class_has_failed_verification(ik);
 829     }
 830     ik->compute_has_loops_flag_for_methods();
 831     BytecodeVerificationLocal = saved;
 832     return true;
 833   } else {
 834     return false;
 835   }
 836 }
 837 
 838 #if INCLUDE_CDS_JAVA_HEAP
 839 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
 840   if(!HeapShared::can_write()) {
 841     log_info(cds)(

 842       "Archived java heap is not supported as UseG1GC "
 843       "and UseCompressedClassPointers are required."
 844       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
 845       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));

 846     return;
 847   }
 848   // Find all the interned strings that should be dumped.
 849   int i;
 850   for (i = 0; i < klasses->length(); i++) {
 851     Klass* k = klasses->at(i);
 852     if (k->is_instance_klass()) {
 853       InstanceKlass* ik = InstanceKlass::cast(k);
 854       if (ik->is_linked()) {
 855         ik->constants()->add_dumped_interned_strings();
 856       }
 857     }
 858   }
 859   if (_extra_interned_strings != nullptr) {
 860     for (i = 0; i < _extra_interned_strings->length(); i ++) {
 861       OopHandle string = _extra_interned_strings->at(i);
 862       HeapShared::add_to_dumped_interned_strings(string.resolve());
 863     }
 864   }
 865 

 902   if (message != nullptr) {
 903     log_error(cds)("%s", message);
 904   }
 905   vm_exit_during_initialization("Unable to use shared archive.", nullptr);
 906 }
 907 
 908 // This function is called when the JVM is unable to write the specified CDS archive due to an
 909 // unrecoverable error.
 910 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
 911   log_error(cds)("An error has occurred while writing the shared archive file.");
 912   if (message != nullptr) {
 913     log_error(cds)("%s", message);
 914   }
 915   vm_direct_exit(1);
 916 }
 917 
 918 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
 919   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
 920   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
 921 
 922   FileMapInfo* static_mapinfo = open_static_archive();
 923   FileMapInfo* dynamic_mapinfo = nullptr;
 924 
 925   if (static_mapinfo != nullptr) {
 926     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
 927     dynamic_mapinfo = open_dynamic_archive();
 928 
 929     // First try to map at the requested address
 930     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
 931     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
 932       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
 933       // by the OS.
 934       log_info(cds)("Try to map archive(s) at an alternative address");
 935       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
 936     }
 937   }
 938 
 939   if (result == MAP_ARCHIVE_SUCCESS) {
 940     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
 941     char* cds_base = static_mapinfo->mapped_base();
 942     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();

 949       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
 950       // turn AutoCreateSharedArchive off if successfully mapped
 951       AutoCreateSharedArchive = false;
 952     } else {
 953       FileMapInfo::set_shared_path_table(static_mapinfo);
 954     }
 955   } else {
 956     set_shared_metaspace_range(nullptr, nullptr, nullptr);
 957     if (CDSConfig::is_dumping_dynamic_archive()) {
 958       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
 959     }
 960     UseSharedSpaces = false;
 961     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
 962     AutoCreateSharedArchive = false;
 963     CDSConfig::disable_dumping_dynamic_archive();
 964     log_info(cds)("Unable to map shared spaces");
 965     if (PrintSharedArchiveAndExit) {
 966       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
 967     } else if (RequireSharedSpaces) {
 968       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");




 969     }
 970   }
 971 
 972   // If mapping failed and -XShare:on, the vm should exit
 973   bool has_failed = false;
 974   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
 975     has_failed = true;
 976     delete static_mapinfo;
 977   }
 978   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
 979     has_failed = true;
 980     delete dynamic_mapinfo;
 981   }
 982   if (RequireSharedSpaces && has_failed) {

 983       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
 984   }
 985 }
 986 
 987 FileMapInfo* MetaspaceShared::open_static_archive() {





 988   const char* static_archive = CDSConfig::static_archive_path();
 989   assert(static_archive != nullptr, "sanity");
 990   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
 991   if (!mapinfo->initialize()) {
 992     delete(mapinfo);
 993     return nullptr;


 994   }
 995   return mapinfo;
 996 }
 997 
 998 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
 999   if (CDSConfig::is_dumping_dynamic_archive()) {
1000     return nullptr;
1001   }
1002   const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1003   if (dynamic_archive == nullptr) {
1004     return nullptr;
1005   }
1006 
1007   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1008   if (!mapinfo->initialize()) {
1009     delete(mapinfo);
1010     if (RequireSharedSpaces) {
1011       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1012     }
1013     return nullptr;
1014   }
1015   return mapinfo;

1385     if (archive_space_rs.is_reserved()) {
1386       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1387       archive_space_rs.release();
1388     }
1389     if (class_space_rs.is_reserved()) {
1390       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1391       class_space_rs.release();
1392     }
1393   }
1394 }
1395 
1396 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1397 static int archive_regions_count = 2;
1398 
1399 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1400   assert(UseSharedSpaces, "must be runtime");
1401   if (mapinfo == nullptr) {
1402     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1403   }
1404 




1405   mapinfo->set_is_mapped(false);
1406   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1407     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1408                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1409     return MAP_ARCHIVE_OTHER_FAILURE;
1410   }
1411 
1412   MapArchiveResult result =
1413     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1414 
1415   if (result != MAP_ARCHIVE_SUCCESS) {
1416     unmap_archive(mapinfo);
1417     return result;
1418   }
1419 
1420   if (!mapinfo->validate_shared_path_table()) {
1421     unmap_archive(mapinfo);
1422     return MAP_ARCHIVE_OTHER_FAILURE;
1423   }
1424 

1449 };
1450 
1451 // Read the miscellaneous data from the shared file, and
1452 // serialize it out to its various destinations.
1453 
1454 void MetaspaceShared::initialize_shared_spaces() {
1455   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1456 
1457   // Verify various attributes of the archive, plus initialize the
1458   // shared string/symbol tables.
1459   char* buffer = static_mapinfo->serialized_data();
1460   intptr_t* array = (intptr_t*)buffer;
1461   ReadClosure rc(&array);
1462   serialize(&rc);
1463 
1464   // Finish up archived heap initialization. These must be
1465   // done after ReadClosure.
1466   static_mapinfo->patch_heap_embedded_pointers();
1467   ArchiveHeapLoader::finish_initialization();
1468   Universe::load_archived_object_instances();

1469 
1470   // Close the mapinfo file
1471   static_mapinfo->close();
1472 
1473   static_mapinfo->unmap_region(MetaspaceShared::bm);
1474 
1475   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1476   if (dynamic_mapinfo != nullptr) {
1477     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1478     ReadClosure rc(&buffer);
1479     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1480     DynamicArchive::setup_array_klasses();
1481     dynamic_mapinfo->close();
1482     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1483   }
1484 
1485   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1486   if (CDSConfig::is_dumping_dynamic_archive()) {
1487     // Read stored LF format lines stored in static archive
1488     LambdaFormInvokers::read_static_archive_invokers();
1489   }
1490 
1491   if (PrintSharedArchiveAndExit) {
1492     // Print archive names
1493     if (dynamic_mapinfo != nullptr) {
1494       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1495       tty->print_cr("Base archive version %d", static_mapinfo->version());
1496     } else {
1497       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1498       tty->print_cr("Static archive version %d", static_mapinfo->version());
1499     }
1500 
1501     SystemDictionaryShared::print_shared_archive(tty);
1502     if (dynamic_mapinfo != nullptr) {
1503       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1504       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1505       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1506     }






1507 
1508     // collect shared symbols and strings
1509     CountSharedSymbols cl;
1510     SymbolTable::shared_symbols_do(&cl);
1511     tty->print_cr("Number of shared symbols: %d", cl.total());
1512     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1513     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1514     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1515       tty->print_cr("archive is invalid");
1516       vm_exit(1);
1517     } else {
1518       tty->print_cr("archive is valid");
1519       vm_exit(0);
1520     }
1521   }
1522 }
1523 
1524 // JVM/TI RedefineClasses() support:
1525 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1526   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");

  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/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/archiveHeapWriter.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsAccess.hpp"
  31 #include "cds/cdsConfig.hpp"
  32 #include "cds/cdsProtectionDomain.hpp"
  33 #include "cds/cds_globals.hpp"
  34 #include "cds/classListParser.hpp"
  35 #include "cds/classListWriter.hpp"
  36 #include "cds/classPreinitializer.hpp"
  37 #include "cds/classPrelinker.hpp"
  38 #include "cds/classPreloader.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/ostream.hpp"
 101 #include "utilities/resourceHash.hpp"
 102 
 103 ReservedSpace MetaspaceShared::_symbol_rs;
 104 VirtualSpace MetaspaceShared::_symbol_vs;
 105 bool MetaspaceShared::_archive_loading_failed = false;
 106 bool MetaspaceShared::_remapped_readwrite = false;
 107 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
 108 intx MetaspaceShared::_relocation_delta;
 109 char* MetaspaceShared::_requested_base_address;
 110 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
 111 bool MetaspaceShared::_use_optimized_module_handling = true;
 112 
 113 // The CDS archive is divided into the following regions:
 114 //     rw  - read-write metadata
 115 //     ro  - read-only metadata and read-only tables
 116 //     hp  - heap region
 117 //     bm  - bitmap for relocating the above 7 regions.
 118 //
 119 // The rw and ro regions are linearly allocated, in the order of rw->ro.
 120 // These regions are aligned with MetaspaceShared::core_region_alignment().
 121 //
 122 // These 2 regions are populated in the following steps:
 123 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
 124 //     temporarily allocated outside of the shared regions.
 125 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
 126 // [2] C++ vtables are copied into the rw region.
 127 // [3] ArchiveBuilder copies RW metadata into the rw region.
 128 // [4] ArchiveBuilder copies RO metadata into the ro region.
 129 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
 130 //     are copied into the ro region as read-only tables.

 294   if (UseSharedSpaces) {
 295     int size = FileMapInfo::get_number_of_shared_paths();
 296     if (size > 0) {
 297       CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
 298       if (!CDSConfig::is_dumping_dynamic_archive()) {
 299         FileMapInfo* info;
 300         if (FileMapInfo::dynamic_info() == nullptr) {
 301           info = FileMapInfo::current_info();
 302         } else {
 303           info = FileMapInfo::dynamic_info();
 304         }
 305         ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
 306         ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
 307       }
 308     }
 309   }
 310 }
 311 
 312 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
 313 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;
 314 static GrowableArray<Method*>* _method_handle_intrinsics = nullptr;
 315 
 316 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
 317   _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
 318   _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
 319 
 320   HashtableTextDump reader(filename);
 321   reader.check_version("VERSION: 1.0");
 322 
 323   while (reader.remain() > 0) {
 324     int utf8_length;
 325     int prefix_type = reader.scan_prefix(&utf8_length);
 326     ResourceMark rm(current);
 327     if (utf8_length == 0x7fffffff) {
 328       // buf_len will overflown 32-bit value.
 329       log_error(cds)("string length too large: %d", utf8_length);
 330       MetaspaceShared::unrecoverable_loading_error();
 331     }
 332     int buf_len = utf8_length+1;
 333     char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
 334     reader.get_utf8(utf8_buffer, utf8_length);

 345       if (HAS_PENDING_EXCEPTION) {
 346         log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
 347                                reader.last_line_no(), utf8_length);
 348         CLEAR_PENDING_EXCEPTION;
 349       } else {
 350 #if INCLUDE_CDS_JAVA_HEAP
 351         if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) {
 352           log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
 353                                  reader.last_line_no(), utf8_length);
 354           continue;
 355         }
 356         // Make sure this string is included in the dumped interned string table.
 357         assert(str != nullptr, "must succeed");
 358         _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
 359 #endif
 360       }
 361     }
 362   }
 363 }
 364 
 365 void MetaspaceShared::make_method_handle_intrinsics_shareable() {
 366   for (int i = 0; i < _method_handle_intrinsics->length(); i++) {
 367     Method* m = ArchiveBuilder::current()->get_buffered_addr(_method_handle_intrinsics->at(i));
 368     m->remove_unshareable_info();
 369     // Each method has its own constant pool (which is distinct from m->method_holder()->constants());
 370     m->constants()->remove_unshareable_info();
 371   }
 372 }
 373 
 374 void MetaspaceShared::write_method_handle_intrinsics() {
 375   int len = _method_handle_intrinsics->length();
 376   _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len);
 377   for (int i = 0; i < len; i++) {
 378     ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i),
 379                                                        _method_handle_intrinsics->at(i));
 380   }
 381   log_info(cds)("Archived %d method handle intrinsics", len);
 382 }
 383 
 384 // Read/write a data stream for restoring/preserving metadata pointers and
 385 // miscellaneous data from/to the shared archive file.
 386 
 387 void MetaspaceShared::serialize(SerializeClosure* soc) {
 388   int tag = 0;
 389   soc->do_tag(--tag);
 390 
 391   // Verify the sizes of various metadata in the system.
 392   soc->do_tag(sizeof(Method));
 393   soc->do_tag(sizeof(ConstMethod));
 394   soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
 395   soc->do_tag(sizeof(ConstantPool));
 396   soc->do_tag(sizeof(ConstantPoolCache));
 397   soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
 398   soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
 399   soc->do_tag(sizeof(Symbol));
 400 
 401   // Need to do this first, as subsequent steps may call virtual functions
 402   // in archived Metadata objects.
 403   CppVtables::serialize(soc);
 404   soc->do_tag(--tag);
 405 
 406   // Dump/restore miscellaneous metadata.
 407   JavaClasses::serialize_offsets(soc);
 408   HeapShared::serialize_misc_info(soc);
 409   Universe::serialize(soc);
 410   soc->do_tag(--tag);
 411 
 412   // Dump/restore references to commonly used names and signatures.
 413   vmSymbols::serialize(soc);
 414   soc->do_tag(--tag);
 415 
 416   // Dump/restore the symbol/string/subgraph_info tables
 417   SymbolTable::serialize_shared_table_header(soc);
 418   StringTable::serialize_shared_table_header(soc);
 419   HeapShared::serialize_tables(soc);
 420   SystemDictionaryShared::serialize_dictionary_headers(soc);
 421   ClassPreloader::serialize(soc, true);
 422   FinalImageRecipes::serialize(soc, true);
 423   TrainingData::serialize_training_data(soc);
 424   InstanceMirrorKlass::serialize_offsets(soc);
 425 
 426   // Dump/restore well known classes (pointers)
 427   SystemDictionaryShared::serialize_vm_classes(soc);
 428   soc->do_tag(--tag);
 429 
 430   CDS_JAVA_HEAP_ONLY(Modules::serialize(soc);)
 431   CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
 432   soc->do_ptr((void**)&_archived_method_handle_intrinsics);
 433 
 434 
 435   LambdaFormInvokers::serialize(soc);
 436   soc->do_tag(666);
 437 }
 438 
 439 static void rewrite_nofast_bytecode(const methodHandle& method) {
 440   BytecodeStream bcs(method);
 441   while (!bcs.is_last_bytecode()) {
 442     Bytecodes::Code opcode = bcs.next();
 443     switch (opcode) {
 444     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
 445     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
 446     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
 447     case Bytecodes::_iload: {
 448       if (!bcs.is_wide()) {
 449         *bcs.bcp() = Bytecodes::_nofast_iload;
 450       }
 451       break;
 452     }
 453     default: break;

 456 }
 457 
 458 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
 459 //     at run time by RewriteBytecodes/RewriteFrequentPairs
 460 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
 461 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
 462   for (int i = 0; i < ik->methods()->length(); i++) {
 463     methodHandle m(thread, ik->methods()->at(i));
 464     if (ik->can_be_verified_at_dumptime() && ik->is_linked()) {
 465       rewrite_nofast_bytecode(m);
 466     }
 467     Fingerprinter fp(m);
 468     // The side effect of this call sets method's fingerprint field.
 469     fp.fingerprint();
 470   }
 471 }
 472 
 473 class VM_PopulateDumpSharedSpace : public VM_Operation {
 474 private:
 475   ArchiveHeapInfo _heap_info;

 476   void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
 477   void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
 478     log_info(cds)("Dumping symbol table ...");
 479     SymbolTable::write_to_archive(symbols);
 480   }
 481   char* dump_read_only_tables();
 482   StaticArchiveBuilder& _builder;
 483   FileMapInfo* _mapinfo;
 484 public:
 485 
 486   VM_PopulateDumpSharedSpace(StaticArchiveBuilder& b) :
 487     VM_Operation(), _heap_info(), _builder(b), _mapinfo(nullptr) {}
 488 
 489   bool skip_operation() const { return false; }
 490 
 491   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
 492   void doit();   // outline because gdb sucks
 493   bool allow_nested_vm_operations() const { return true; }
 494   FileMapInfo* mapinfo() const { return _mapinfo; }
 495   ArchiveHeapInfo* heap_info() { return &_heap_info; }
 496 }; // class VM_PopulateDumpSharedSpace
 497 
 498 class StaticArchiveBuilder : public ArchiveBuilder {
 499 public:
 500   StaticArchiveBuilder() : ArchiveBuilder() {}
 501 
 502   virtual void iterate_roots(MetaspaceClosure* it) {
 503     FileMapInfo::metaspace_pointers_do(it);
 504     SystemDictionaryShared::dumptime_classes_do(it);
 505     Universe::metaspace_pointers_do(it);
 506     vmSymbols::metaspace_pointers_do(it);
 507     TrainingData::iterate_roots(it);
 508 
 509     // The above code should find all the symbols that are referenced by the
 510     // archived classes. We just need to add the extra symbols which
 511     // may not be used by any of the archived classes -- these are usually
 512     // symbols that we anticipate to be used at run time, so we can store
 513     // them in the RO region, to be shared across multiple processes.
 514     if (_extra_symbols != nullptr) {
 515       for (int i = 0; i < _extra_symbols->length(); i++) {
 516         it->push(_extra_symbols->adr_at(i));
 517       }
 518     }
 519 
 520     for (int i = 0; i < _method_handle_intrinsics->length(); i++) {
 521       it->push(_method_handle_intrinsics->adr_at(i));
 522     }
 523   }
 524 };
 525 
 526 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
 527   ArchiveBuilder::OtherROAllocMark mark;
 528 
 529   SystemDictionaryShared::write_to_archive();
 530   ClassPreloader::record_initiated_classes(true);
 531   ClassPreloader::record_unregistered_classes();
 532   TrainingData::dump_training_data();
 533   MetaspaceShared::write_method_handle_intrinsics();
 534 
 535   // Write lambform lines into archive
 536   LambdaFormInvokers::dump_static_archive_invokers();
 537   // Write module name into archive
 538   CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
 539   // Write the other data to the output array.
 540   DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
 541   char* start = ro_region->top();
 542   WriteClosure wc(ro_region);
 543   MetaspaceShared::serialize(&wc);
 544 
 545   return start;
 546 }
 547 
 548 void VM_PopulateDumpSharedSpace::doit() {
 549   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
 550 
 551   FileMapInfo::check_nonempty_dir_in_shared_path_table();
 552 
 553   NOT_PRODUCT(SystemDictionary::verify();)
 554 
 555   // Block concurrent class unloading from changing the _dumptime_table
 556   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
 557   SystemDictionaryShared::check_excluded_classes();
 558 
 559   _builder.gather_source_objs();
 560   _builder.reserve_buffer();

 561 
 562   CppVtables::dumptime_init(&_builder);
 563 
 564   _builder.sort_metadata_objs();
 565   _builder.dump_rw_metadata();
 566   _builder.dump_ro_metadata();
 567   _builder.relocate_metaspaceobj_embedded_pointers();
 568 
 569   dump_java_heap_objects(_builder.klasses());
 570   dump_shared_symbol_table(_builder.symbols());
 571 
 572   {
 573     ArchiveBuilder::OtherROAllocMark mark;
 574     ClassPreloader::record_preloaded_classes(true);
 575     if (CDSConfig::is_dumping_preimage_static_archive()) {
 576       FinalImageRecipes::record_recipes();
 577     }
 578   }
 579 
 580   log_info(cds)("Make classes shareable");
 581   _builder.make_klasses_shareable();
 582   MetaspaceShared::make_method_handle_intrinsics_shareable();
 583 
 584   char* serialized_data = dump_read_only_tables();
 585 
 586   SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
 587 
 588   log_info(cds)("Adjust method info dictionary");
 589   SystemDictionaryShared::adjust_method_info_dictionary();
 590 
 591   log_info(cds)("Make training data shareable");
 592   _builder.make_training_data_shareable();
 593 
 594   // The vtable clones contain addresses of the current process.
 595   // We don't want to write these addresses into the archive.
 596   CppVtables::zero_archived_vtables();
 597 




 598   // Write the archive file
 599   const char* static_archive;
 600   if (CDSConfig::is_dumping_final_static_archive()) {
 601     static_archive = CacheDataStore;
 602     assert(FileMapInfo::current_info() != nullptr, "sanity");
 603     delete FileMapInfo::current_info();
 604   } else {
 605     static_archive = CDSConfig::static_archive_path();









 606   }
 607   assert(static_archive != nullptr, "SharedArchiveFile not set?");
 608   _mapinfo = new FileMapInfo(static_archive, true);
 609   _mapinfo->populate_header(MetaspaceShared::core_region_alignment());
 610   _mapinfo->set_serialized_data(serialized_data);
 611   _mapinfo->set_cloned_vtables(CppVtables::vtables_serialized_base());
 612 }
 613 
 614 class CollectCLDClosure : public CLDClosure {
 615   GrowableArray<ClassLoaderData*> _loaded_cld;
 616   GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
 617   Thread* _current_thread;
 618 public:
 619   CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
 620   ~CollectCLDClosure() {
 621     for (int i = 0; i < _loaded_cld_handles.length(); i++) {
 622       _loaded_cld_handles.at(i).release(Universe::vm_global());
 623     }
 624   }
 625   void do_cld(ClassLoaderData* cld) {
 626     assert(cld->is_alive(), "must be");
 627     _loaded_cld.append(cld);
 628     _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
 629   }
 630 
 631   int nof_cld() const                { return _loaded_cld.length(); }
 632   ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
 633 };
 634 
 635 // Check if we can eagerly link this class at dump time, so we can avoid the
 636 // runtime linking overhead (especially verification)
 637 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
 638   if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
 639     assert(ik->can_be_verified_at_dumptime(), "sanity");
 640   }
 641   if (!ik->can_be_verified_at_dumptime()) {
 642     // For old classes, try to leave them in the unlinked state, so
 643     // we can still store them in the archive. They must be
 644     // linked/verified at runtime.
 645     return false;
 646   }
 647 
 648   if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
 649     // Linking of unregistered classes at this stage may cause more
 650     // classes to be resolved, resulting in calls to ClassLoader.loadClass()
 651     // that may not be expected by custom class loaders.
 652     //
 653     // It's OK to do this for the built-in loaders as we know they can
 654     // tolerate this.
 655     return false;
 656   }
 657   return true;
 658 }
 659 









 660 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
 661   ClassPreloader::initialize();
 662   ClassPrelinker::initialize();
 663 
 664   if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
 665       && !CDSConfig::is_dumping_preimage_static_archive()
 666       && !CDSConfig::is_dumping_final_static_archive()) {
 667     // If we have regenerated invoker classes in the dynamic archive,
 668     // they will conflict with the resolved CONSTANT_Klass references that are stored
 669     // in the static archive. This is not easy to handle. Let's disable
 670     // it for dynamic archive for now.
 671     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 672   }
 673 
 674   // Collect all loaded ClassLoaderData.
 675   CollectCLDClosure collect_cld(THREAD);
 676   {
 677     // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
 678     // We cannot link the classes while holding this lock (or else we may run into deadlock).
 679     // Therefore, we need to first collect all the CLDs, and then link their classes after
 680     // releasing the lock.
 681     MutexLocker lock(ClassLoaderDataGraph_lock);
 682     ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
 683   }
 684 
 685   while (true) {
 686     bool has_linked = false;
 687     for (int i = 0; i < collect_cld.nof_cld(); i++) {
 688       ClassLoaderData* cld = collect_cld.cld_at(i);
 689       for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 690         if (klass->is_instance_klass()) {
 691           InstanceKlass* ik = InstanceKlass::cast(klass);
 692           if (may_be_eagerly_linked(ik)) {
 693             has_linked |= try_link_class(THREAD, ik);
 694           }
 695           if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
 696             ClassPreinitializer::maybe_preinit_class(ik, CHECK);
 697           }
 698         }
 699       }
 700     }
 701 
 702     if (!has_linked) {
 703       break;
 704     }
 705     // Class linking includes verification which may load more classes.
 706     // Keep scanning until we have linked no more classes.
 707   }
 708 
 709   // Resolve constant pool entries -- we don't load any new classes during this stage
 710   for (int i = 0; i < collect_cld.nof_cld(); i++) {
 711     ClassLoaderData* cld = collect_cld.cld_at(i);
 712     for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
 713       if (klass->is_instance_klass()) {
 714         InstanceKlass* ik = InstanceKlass::cast(klass);
 715         ClassPrelinker::dumptime_resolve_constants(ik, CHECK);
 716         if (CDSConfig::is_dumping_preimage_static_archive()) {
 717           FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
 718         }
 719       }
 720     }
 721   }
 722 
 723   if (CDSConfig::is_dumping_preimage_static_archive()) {
 724     // Do this after all classes are verified by the above loop.
 725     // Any classes loaded from here on will be automatically excluded, so
 726     // there's no need to force verification or resolve CP entries. 
 727     RecordTraining = false;
 728     SystemDictionaryShared::ignore_new_classes();
 729     LambdaFormInvokers::regenerate_holder_classes(CHECK);
 730     RecordTraining = true;
 731   }
 732 
 733   if (CDSConfig::is_dumping_final_static_archive()) {
 734     FinalImageRecipes::apply_recipes(CHECK);
 735   }
 736 }
 737 
 738 void MetaspaceShared::prepare_for_dumping() {
 739   assert(CDSConfig::is_dumping_archive(), "sanity");
 740   CDSConfig::check_unsupported_dumping_module_options();
 741   ClassLoader::initialize_shared_path(JavaThread::current());
 742 }
 743 
 744 // Preload classes from a list, populate the shared spaces and dump to a
 745 // file.
 746 void MetaspaceShared::preload_and_dump() {
 747   EXCEPTION_MARK;
 748   ResourceMark rm(THREAD);
 749   HandleMark hm(THREAD);
 750 
 751   if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
 752     tty->print_cr("==================== archived_training_data ** before dumping ====================");
 753     TrainingData::print_archived_training_data_on(tty);
 754   }
 755 
 756   StaticArchiveBuilder builder;
 757   preload_and_dump_impl(builder, THREAD);
 758   if (HAS_PENDING_EXCEPTION) {
 759     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
 760       log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
 761                      SIZE_FORMAT "M", MaxHeapSize/M);
 762       CLEAR_PENDING_EXCEPTION;
 763       MetaspaceShared::unrecoverable_writing_error();
 764     } else {
 765       log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
 766                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
 767       CLEAR_PENDING_EXCEPTION;
 768       MetaspaceShared::unrecoverable_writing_error("VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
 769     }
 770   }
 771 }
 772 
 773 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
 774 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
 775   if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
 776     return;
 777   }

 839     ClassListParser::parse_classlist(ExtraSharedClassListFile,
 840                                      ClassListParser::_parse_all, CHECK);
 841   }
 842   if (classlist_path != default_classlist) {
 843     struct stat statbuf;
 844     if (os::stat(default_classlist, &statbuf) == 0) {
 845       // File exists, let's use it.
 846       ClassListParser::parse_classlist(default_classlist,
 847                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 848     }
 849   }
 850 
 851   // Exercise the manifest processing code to ensure classes used by CDS at runtime
 852   // are always archived
 853   const char* dummy = "Manifest-Version: 1.0\n";
 854   CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
 855 
 856   log_info(cds)("Loading classes to share: done.");
 857 }
 858 
 859 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
 860   if (CDSConfig::is_dumping_classic_static_archive()) {
 861     // We are running with -Xshare:dump
 862     preload_classes(CHECK);
 863 
 864     if (SharedArchiveConfigFile) {
 865       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
 866       read_extra_data(THREAD, SharedArchiveConfigFile);
 867       log_info(cds)("Reading extra data: done.");
 868     }
 869   }
 870 
 871   if (CDSConfig::is_dumping_preimage_static_archive()) {
 872     log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
 873     char default_classlist[JVM_MAXPATHLEN];
 874     get_default_classlist(default_classlist, sizeof(default_classlist));
 875     struct stat statbuf;
 876     if (os::stat(default_classlist, &statbuf) == 0) {
 877       ClassListParser::parse_classlist(default_classlist,
 878                                        ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
 879     }
 880   }
 881 
 882 #if INCLUDE_CDS_JAVA_HEAP
 883   if (CDSConfig::is_dumping_heap() && ArchiveInvokeDynamic) {
 884     // We also assume no other Java threads are running
 885     // This makes sure that the MethodType and MethodTypeForm objects are clean.
 886     JavaValue result(T_VOID);
 887     JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
 888                            vmSymbols::dumpSharedArchive(),
 889                            vmSymbols::void_method_signature(),
 890                            CHECK);
 891   }
 892 #endif
 893 
 894   // Rewrite and link classes
 895   log_info(cds)("Rewriting and linking classes ...");

 896   // Link any classes which got missed. This would happen if we have loaded classes that
 897   // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
 898   // fails verification, all other interfaces that were not specified in the classlist but
 899   // are implemented by K are not verified.
 900   link_shared_classes(false/*not from jcmd*/, CHECK);
 901   log_info(cds)("Rewriting and linking classes: done");
 902 
 903   if (CDSConfig::is_dumping_final_static_archive()) {
 904     assert(RecordTraining == false, "must be");
 905     RecordTraining = true;
 906   }
 907 
 908   TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
 909 
 910   _method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
 911   SystemDictionary::get_all_method_handle_intrinsics(_method_handle_intrinsics);
 912 
 913 #if INCLUDE_CDS_JAVA_HEAP
 914   if (CDSConfig::is_dumping_heap()) {
 915     if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
 916       log_info(cds)("archivedBootLayer not available, disabling full module graph");
 917       CDSConfig::stop_dumping_full_module_graph();
 918     }
 919     HeapShared::init_for_dumping(CHECK);
 920     ArchiveHeapWriter::init();
 921     if (CDSConfig::is_dumping_full_module_graph()) {
 922       HeapShared::reset_archived_object_states(CHECK);
 923     }
 924 
 925     if (ArchiveLoaderLookupCache) {
 926       SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
 927     }
 928 
 929     // Do this at the very end, when no Java code will be executed. Otherwise
 930     // some new strings may be added to the intern table.
 931     StringTable::allocate_shared_strings_array(CHECK);
 932   }
 933 #endif
 934 
 935   VM_PopulateDumpSharedSpace op(builder);
 936   VMThread::execute(&op);
 937   FileMapInfo* mapinfo = op.mapinfo();
 938   ArchiveHeapInfo* heap_info = op.heap_info();
 939 
 940   if (CDSConfig::is_dumping_preimage_static_archive()) {
 941     write_static_archive(&builder, mapinfo, heap_info);
 942     fork_and_dump_final_static_archive();
 943   } else if (CDSConfig::is_dumping_final_static_archive()) {
 944     RecordTraining = false;
 945     if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
 946       if (log_is_enabled(Info, cds, jit)) {
 947         CDSAccess::test_heap_access_api();
 948       }
 949 
 950       // We have just created the final image. Let's run the AOT compiler
 951       if (PrintTrainingInfo) {
 952         tty->print_cr("==================== archived_training_data ** after dumping ====================");
 953         TrainingData::print_archived_training_data_on(tty);
 954       }
 955 
 956       CDSConfig::enable_dumping_cached_code();
 957       {
 958         builder.start_cc_region();
 959         Precompiler::compile_cached_code(&builder, CHECK);
 960         builder.end_cc_region();
 961       }
 962       CDSConfig::disable_dumping_cached_code();
 963 
 964       SCCache::close(); // Write final data and close archive
 965     }
 966     write_static_archive(&builder, mapinfo, heap_info);
 967   } else {
 968     write_static_archive(&builder, mapinfo, heap_info);
 969   }
 970 }
 971 
 972 void MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
 973   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
 974   // without runtime relocation.
 975   builder->relocate_to_requested();
 976 
 977   mapinfo->open_for_write();
 978   builder->write_archive(mapinfo, heap_info);
 979 
 980   if (PrintSystemDictionaryAtExit) {
 981     SystemDictionary::print();
 982   }
 983 
 984   if (AllowArchivingWithJavaAgent) {
 985     log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
 986             "for testing purposes only and should not be used in a production environment");
 987   }
 988 }
 989 
 990 void MetaspaceShared::fork_and_dump_final_static_archive() {
 991   assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
 992 
 993   ResourceMark rm;
 994   stringStream st;
 995   st.print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
 996   const char* cp = Arguments::get_appclasspath();
 997   if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
 998     st.print(" -cp ");  st.print_raw(cp);
 999   }
1000   for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1001     st.print(" %s", Arguments::jvm_flags_array()[i]);
1002   }
1003   for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1004     st.print(" %s", Arguments::jvm_args_array()[i]);
1005   }
1006   st.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1007 
1008   const char* cmd = st.freeze();
1009   if (CDSManualFinalImage) {
1010     tty->print_cr("-XX:+CDSManualFinalImage is specified");
1011     tty->print_cr("Please manually execute the following command to create the final CDS image:");
1012     tty->print("    "); tty->print_raw_cr(cmd);
1013   } else {
1014     log_info(cds)("Launching child process to create final CDS image:");
1015     log_info(cds)("    %s", cmd);
1016     int status = os::fork_and_exec(cmd);
1017     if (status != 0) {
1018       log_error(cds)("Child process finished; status = %d", status);
1019       log_error(cds)("To reproduce the error");
1020       ResourceMark rm;
1021       LogStream ls(Log(cds)::error());
1022       ls.print("    "); ls.print_raw_cr(cmd);
1023       vm_direct_exit(status);
1024     } else {
1025       log_info(cds)("Child process finished; status = %d", status);
1026       status = remove(SharedArchiveFile);
1027       if (status != 0) {
1028         log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1029       } else {
1030         log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1031       }
1032     }
1033   }
1034 }
1035 
1036 // Returns true if the class's status has changed.
1037 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1038   ExceptionMark em(current);
1039   JavaThread* THREAD = current; // For exception macros.
1040   assert(CDSConfig::is_dumping_archive(), "sanity");
1041 
1042   if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1043     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1044     return false;
1045   }
1046 
1047   if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1048       !SystemDictionaryShared::has_class_failed_verification(ik)) {
1049     bool saved = BytecodeVerificationLocal;
1050     if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1051       // The verification decision is based on BytecodeVerificationRemote
1052       // for non-system classes. Since we are using the null classloader
1053       // to load non-system classes for customized class loaders during dumping,
1054       // we need to temporarily change BytecodeVerificationLocal to be the same as
1055       // BytecodeVerificationRemote. Note this can cause the parent system
1056       // classes also being verified. The extra overhead is acceptable during
1057       // dumping.
1058       BytecodeVerificationLocal = BytecodeVerificationRemote;
1059     }
1060     ik->link_class(THREAD);
1061     if (HAS_PENDING_EXCEPTION) {
1062       ResourceMark rm(THREAD);
1063       log_warning(cds)("Preload Warning: Verification failed for %s",
1064                     ik->external_name());
1065       CLEAR_PENDING_EXCEPTION;
1066       SystemDictionaryShared::set_class_has_failed_verification(ik);
1067     }
1068     ik->compute_has_loops_flag_for_methods();
1069     BytecodeVerificationLocal = saved;
1070     return true;
1071   } else {
1072     return false;
1073   }
1074 }
1075 
1076 #if INCLUDE_CDS_JAVA_HEAP
1077 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1078   if(!HeapShared::can_write()) {
1079     if (!CDSConfig::is_dumping_preimage_static_archive()) {
1080      log_info(cds)(
1081       "Archived java heap is not supported as UseG1GC "
1082       "and UseCompressedClassPointers are required."
1083       "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1084       BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1085     }
1086     return;
1087   }
1088   // Find all the interned strings that should be dumped.
1089   int i;
1090   for (i = 0; i < klasses->length(); i++) {
1091     Klass* k = klasses->at(i);
1092     if (k->is_instance_klass()) {
1093       InstanceKlass* ik = InstanceKlass::cast(k);
1094       if (ik->is_linked()) {
1095         ik->constants()->add_dumped_interned_strings();
1096       }
1097     }
1098   }
1099   if (_extra_interned_strings != nullptr) {
1100     for (i = 0; i < _extra_interned_strings->length(); i ++) {
1101       OopHandle string = _extra_interned_strings->at(i);
1102       HeapShared::add_to_dumped_interned_strings(string.resolve());
1103     }
1104   }
1105 

1142   if (message != nullptr) {
1143     log_error(cds)("%s", message);
1144   }
1145   vm_exit_during_initialization("Unable to use shared archive.", nullptr);
1146 }
1147 
1148 // This function is called when the JVM is unable to write the specified CDS archive due to an
1149 // unrecoverable error.
1150 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1151   log_error(cds)("An error has occurred while writing the shared archive file.");
1152   if (message != nullptr) {
1153     log_error(cds)("%s", message);
1154   }
1155   vm_direct_exit(1);
1156 }
1157 
1158 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1159   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
1160   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1161 
1162   FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1163   FileMapInfo* dynamic_mapinfo = nullptr;
1164 
1165   if (static_mapinfo != nullptr) {
1166     log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1167     dynamic_mapinfo = open_dynamic_archive();
1168 
1169     // First try to map at the requested address
1170     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1171     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1172       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1173       // by the OS.
1174       log_info(cds)("Try to map archive(s) at an alternative address");
1175       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1176     }
1177   }
1178 
1179   if (result == MAP_ARCHIVE_SUCCESS) {
1180     bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1181     char* cds_base = static_mapinfo->mapped_base();
1182     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();

1189       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1190       // turn AutoCreateSharedArchive off if successfully mapped
1191       AutoCreateSharedArchive = false;
1192     } else {
1193       FileMapInfo::set_shared_path_table(static_mapinfo);
1194     }
1195   } else {
1196     set_shared_metaspace_range(nullptr, nullptr, nullptr);
1197     if (CDSConfig::is_dumping_dynamic_archive()) {
1198       log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1199     }
1200     UseSharedSpaces = false;
1201     // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1202     AutoCreateSharedArchive = false;
1203     CDSConfig::disable_dumping_dynamic_archive();
1204     log_info(cds)("Unable to map shared spaces");
1205     if (PrintSharedArchiveAndExit) {
1206       MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1207     } else if (RequireSharedSpaces) {
1208       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1209     } else if (CDSConfig::is_dumping_final_static_archive()) {
1210       assert(CDSPreimage != nullptr, "must be");
1211       log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1212       MetaspaceShared::unrecoverable_loading_error();
1213     }
1214   }
1215 
1216   // If mapping failed and -XShare:on, the vm should exit
1217   bool has_failed = false;
1218   if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1219     has_failed = true;
1220     delete static_mapinfo;
1221   }
1222   if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1223     has_failed = true;
1224     delete dynamic_mapinfo;
1225   }
1226   if (RequireSharedSpaces && has_failed) {
1227     // static archive mapped but dynamic archive failed
1228       MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1229   }
1230 }
1231 
1232 // This is called very early at VM start up to get the size of the cached_code region, which
1233 // is used in CodeCache::initialize_heaps()
1234 void MetaspaceShared::open_static_archive() {
1235   if (!UseSharedSpaces) {
1236     return;
1237   }
1238   const char* static_archive = CDSConfig::static_archive_path();
1239   assert(static_archive != nullptr, "sanity");
1240   FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1241   if (!mapinfo->initialize()) {
1242     delete(mapinfo);
1243   } else {
1244     FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1245     CDSAccess::set_cached_code_size(r->used());
1246   }

1247 }
1248 
1249 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1250   if (CDSConfig::is_dumping_dynamic_archive()) {
1251     return nullptr;
1252   }
1253   const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1254   if (dynamic_archive == nullptr) {
1255     return nullptr;
1256   }
1257 
1258   FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1259   if (!mapinfo->initialize()) {
1260     delete(mapinfo);
1261     if (RequireSharedSpaces) {
1262       MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1263     }
1264     return nullptr;
1265   }
1266   return mapinfo;

1636     if (archive_space_rs.is_reserved()) {
1637       log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1638       archive_space_rs.release();
1639     }
1640     if (class_space_rs.is_reserved()) {
1641       log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1642       class_space_rs.release();
1643     }
1644   }
1645 }
1646 
1647 static int archive_regions[]     = { MetaspaceShared::rw, MetaspaceShared::ro };
1648 static int archive_regions_count = 2;
1649 
1650 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1651   assert(UseSharedSpaces, "must be runtime");
1652   if (mapinfo == nullptr) {
1653     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1654   }
1655 
1656   if (!mapinfo->validate_leyden_config()) {
1657     return MAP_ARCHIVE_OTHER_FAILURE;
1658   }
1659 
1660   mapinfo->set_is_mapped(false);
1661   if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1662     log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1663                   " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1664     return MAP_ARCHIVE_OTHER_FAILURE;
1665   }
1666 
1667   MapArchiveResult result =
1668     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1669 
1670   if (result != MAP_ARCHIVE_SUCCESS) {
1671     unmap_archive(mapinfo);
1672     return result;
1673   }
1674 
1675   if (!mapinfo->validate_shared_path_table()) {
1676     unmap_archive(mapinfo);
1677     return MAP_ARCHIVE_OTHER_FAILURE;
1678   }
1679 

1704 };
1705 
1706 // Read the miscellaneous data from the shared file, and
1707 // serialize it out to its various destinations.
1708 
1709 void MetaspaceShared::initialize_shared_spaces() {
1710   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1711 
1712   // Verify various attributes of the archive, plus initialize the
1713   // shared string/symbol tables.
1714   char* buffer = static_mapinfo->serialized_data();
1715   intptr_t* array = (intptr_t*)buffer;
1716   ReadClosure rc(&array);
1717   serialize(&rc);
1718 
1719   // Finish up archived heap initialization. These must be
1720   // done after ReadClosure.
1721   static_mapinfo->patch_heap_embedded_pointers();
1722   ArchiveHeapLoader::finish_initialization();
1723   Universe::load_archived_object_instances();
1724   SCCache::new_workflow_load_cache();
1725 
1726   // Close the mapinfo file
1727   static_mapinfo->close();
1728 
1729   static_mapinfo->unmap_region(MetaspaceShared::bm);
1730 
1731   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1732   if (dynamic_mapinfo != nullptr) {
1733     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1734     ReadClosure rc(&buffer);
1735     ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1736     DynamicArchive::setup_array_klasses();
1737     dynamic_mapinfo->close();
1738     dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1739   }
1740 
1741   // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1742   if (CDSConfig::is_dumping_dynamic_archive()) {
1743     // Read stored LF format lines stored in static archive
1744     LambdaFormInvokers::read_static_archive_invokers();
1745   }
1746 
1747   if (PrintSharedArchiveAndExit) {
1748     // Print archive names
1749     if (dynamic_mapinfo != nullptr) {
1750       tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1751       tty->print_cr("Base archive version %d", static_mapinfo->version());
1752     } else {
1753       tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1754       tty->print_cr("Static archive version %d", static_mapinfo->version());
1755     }
1756 
1757     SystemDictionaryShared::print_shared_archive(tty);
1758     if (dynamic_mapinfo != nullptr) {
1759       tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1760       tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1761       SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1762     }
1763     TrainingData::print_archived_training_data_on(tty);
1764 
1765     if (LoadCachedCode) {
1766       tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
1767       SCCache::print_on(tty);
1768     }
1769 
1770     // collect shared symbols and strings
1771     CountSharedSymbols cl;
1772     SymbolTable::shared_symbols_do(&cl);
1773     tty->print_cr("Number of shared symbols: %d", cl.total());
1774     tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1775     tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1776     if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1777       tty->print_cr("archive is invalid");
1778       vm_exit(1);
1779     } else {
1780       tty->print_cr("archive is valid");
1781       vm_exit(0);
1782     }
1783   }
1784 }
1785 
1786 // JVM/TI RedefineClasses() support:
1787 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1788   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
< prev index next >