5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotArtifactFinder.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/memoryReserver.hpp"
66 #include "memory/metaspace.hpp"
67 #include "memory/metaspaceClosure.hpp"
68 #include "memory/resourceArea.hpp"
69 #include "memory/universe.hpp"
70 #include "nmt/memTracker.hpp"
71 #include "oops/compressedKlass.hpp"
72 #include "oops/instanceMirrorKlass.hpp"
73 #include "oops/klass.inline.hpp"
74 #include "oops/objArrayOop.hpp"
75 #include "oops/oop.inline.hpp"
76 #include "oops/oopHandle.hpp"
77 #include "prims/jvmtiExport.hpp"
78 #include "runtime/arguments.hpp"
79 #include "runtime/globals.hpp"
80 #include "runtime/globals_extension.hpp"
81 #include "runtime/handles.inline.hpp"
82 #include "runtime/javaCalls.hpp"
83 #include "runtime/os.inline.hpp"
84 #include "runtime/safepointVerifiers.hpp"
85 #include "runtime/sharedRuntime.hpp"
86 #include "runtime/vmOperations.hpp"
87 #include "runtime/vmThread.hpp"
88 #include "sanitizers/leak.hpp"
89 #include "utilities/align.hpp"
90 #include "utilities/bitMap.inline.hpp"
91 #include "utilities/defaultStream.hpp"
92 #include "utilities/macros.hpp"
93 #include "utilities/ostream.hpp"
94 #include "utilities/resourceHash.hpp"
95
96 ReservedSpace MetaspaceShared::_symbol_rs;
97 VirtualSpace MetaspaceShared::_symbol_vs;
98 bool MetaspaceShared::_archive_loading_failed = false;
99 bool MetaspaceShared::_remapped_readwrite = false;
100 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
101 intx MetaspaceShared::_relocation_delta;
102 char* MetaspaceShared::_requested_base_address;
103 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
104 bool MetaspaceShared::_use_optimized_module_handling = true;
105
106 // The CDS archive is divided into the following regions:
107 // rw - read-write metadata
108 // ro - read-only metadata and read-only tables
109 // hp - heap region
110 // bm - bitmap for relocating the above 7 regions.
111 //
112 // The rw and ro regions are linearly allocated, in the order of rw->ro.
113 // These regions are aligned with MetaspaceShared::core_region_alignment().
114 //
115 // These 2 regions are populated in the following steps:
116 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
117 // temporarily allocated outside of the shared regions.
118 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
119 // [2] C++ vtables are copied into the rw region.
120 // [3] ArchiveBuilder copies RW metadata into the rw region.
121 // [4] ArchiveBuilder copies RO metadata into the ro region.
122 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
123 // are copied into the ro region as read-only tables.
124 //
280 }
281
282 // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
283 // picked that (a) the align_up() below will always return a valid value; (b) none of
284 // the following asserts will fail.
285 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
286 p2i((void*)SharedBaseAddress), err,
287 p2i((void*)Arguments::default_SharedBaseAddress()));
288
289 specified_base = (char*)Arguments::default_SharedBaseAddress();
290 aligned_base = align_up(specified_base, alignment);
291
292 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
293 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
294 assert(shared_base_valid(aligned_base), "Sanity");
295 return aligned_base;
296 }
297
298 void MetaspaceShared::initialize_for_static_dump() {
299 assert(CDSConfig::is_dumping_static_archive(), "sanity");
300 log_info(cds)("Core region alignment: %zu", core_region_alignment());
301 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
302 // to avoid address space wrap around.
303 size_t cds_max;
304 const size_t reserve_alignment = core_region_alignment();
305
306 #ifdef _LP64
307 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
308 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
309 #else
310 // We don't support archives larger than 256MB on 32-bit due to limited
311 // virtual address space.
312 cds_max = align_down(256*M, reserve_alignment);
313 #endif
314
315 _requested_base_address = compute_shared_base(cds_max);
316 SharedBaseAddress = (size_t)_requested_base_address;
317
318 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
319 _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
320 os::vm_allocation_granularity(),
482 // Need to do this first, as subsequent steps may call virtual functions
483 // in archived Metadata objects.
484 CppVtables::serialize(soc);
485 soc->do_tag(--tag);
486
487 // Dump/restore miscellaneous metadata.
488 JavaClasses::serialize_offsets(soc);
489 Universe::serialize(soc);
490 soc->do_tag(--tag);
491
492 // Dump/restore references to commonly used names and signatures.
493 vmSymbols::serialize(soc);
494 soc->do_tag(--tag);
495
496 // Dump/restore the symbol/string/subgraph_info tables
497 SymbolTable::serialize_shared_table_header(soc);
498 StringTable::serialize_shared_table_header(soc);
499 HeapShared::serialize_tables(soc);
500 SystemDictionaryShared::serialize_dictionary_headers(soc);
501 AOTLinkedClassBulkLoader::serialize(soc, true);
502 InstanceMirrorKlass::serialize_offsets(soc);
503
504 // Dump/restore well known classes (pointers)
505 SystemDictionaryShared::serialize_vm_classes(soc);
506 soc->do_tag(--tag);
507
508 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
509 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
510
511 LambdaFormInvokers::serialize(soc);
512 soc->do_tag(666);
513 }
514
515 static void rewrite_nofast_bytecode(const methodHandle& method) {
516 BytecodeStream bcs(method);
517 while (!bcs.is_last_bytecode()) {
518 Bytecodes::Code opcode = bcs.next();
519 switch (opcode) {
520 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
521 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
522 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
523 case Bytecodes::_iload: {
524 if (!bcs.is_wide()) {
525 *bcs.bcp() = Bytecodes::_nofast_iload;
526 }
527 break;
528 }
529 default: break;
530 }
531 }
567
568 bool skip_operation() const { return false; }
569
570 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
571 ArchiveHeapInfo* heap_info() { return &_heap_info; }
572 FileMapInfo* map_info() const { return _map_info; }
573 void doit(); // outline because gdb sucks
574 bool allow_nested_vm_operations() const { return true; }
575 }; // class VM_PopulateDumpSharedSpace
576
577 class StaticArchiveBuilder : public ArchiveBuilder {
578 public:
579 StaticArchiveBuilder() : ArchiveBuilder() {}
580
581 virtual void iterate_roots(MetaspaceClosure* it) {
582 FileMapInfo::metaspace_pointers_do(it);
583 AOTArtifactFinder::all_cached_classes_do(it);
584 SystemDictionaryShared::dumptime_classes_do(it);
585 Universe::metaspace_pointers_do(it);
586 vmSymbols::metaspace_pointers_do(it);
587
588 // The above code should find all the symbols that are referenced by the
589 // archived classes. We just need to add the extra symbols which
590 // may not be used by any of the archived classes -- these are usually
591 // symbols that we anticipate to be used at run time, so we can store
592 // them in the RO region, to be shared across multiple processes.
593 if (_extra_symbols != nullptr) {
594 for (int i = 0; i < _extra_symbols->length(); i++) {
595 it->push(_extra_symbols->adr_at(i));
596 }
597 }
598
599 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
600 it->push(_pending_method_handle_intrinsics->adr_at(i));
601 }
602 }
603 };
604
605 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
606 ArchiveBuilder::OtherROAllocMark mark;
607
608 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
609
610 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
611 char* start = ro_region->top();
612 WriteClosure wc(ro_region);
613 MetaspaceShared::early_serialize(&wc);
614 return start;
615 }
616
617 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
618 ArchiveBuilder::OtherROAllocMark mark;
619
620 SystemDictionaryShared::write_to_archive();
621 AOTClassLinker::write_to_archive();
622 MetaspaceShared::write_method_handle_intrinsics();
623
624 // Write lambform lines into archive
625 LambdaFormInvokers::dump_static_archive_invokers();
626
627 // Write the other data to the output array.
628 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
629 char* start = ro_region->top();
630 WriteClosure wc(ro_region);
631 MetaspaceShared::serialize(&wc);
632
633 return start;
634 }
635
636 void VM_PopulateDumpSharedSpace::doit() {
637 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
638
639 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
640
641 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
642 if (CDSConfig::is_dumping_aot_linked_classes()) {
643 // When dumping AOT-linked classes, some classes may have direct references to a method handle
644 // intrinsic. The easiest thing is to save all of them into the AOT cache.
645 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
646 }
647
648 FileMapInfo::check_nonempty_dir_in_shared_path_table();
649
650 NOT_PRODUCT(SystemDictionary::verify();)
651
652 // Block concurrent class unloading from changing the _dumptime_table
653 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
654
655 #if INCLUDE_CDS_JAVA_HEAP
656 if (CDSConfig::is_dumping_heap() && _extra_interned_strings != nullptr) {
657 for (int i = 0; i < _extra_interned_strings->length(); i ++) {
666
667 CppVtables::dumptime_init(&_builder);
668
669 _builder.sort_metadata_objs();
670 _builder.dump_rw_metadata();
671 _builder.dump_ro_metadata();
672 _builder.relocate_metaspaceobj_embedded_pointers();
673
674 log_info(cds)("Make classes shareable");
675 _builder.make_klasses_shareable();
676 MetaspaceShared::make_method_handle_intrinsics_shareable();
677
678 dump_java_heap_objects();
679 dump_shared_symbol_table(_builder.symbols());
680
681 char* early_serialized_data = dump_early_read_only_tables();
682 char* serialized_data = dump_read_only_tables();
683
684 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
685
686 // The vtable clones contain addresses of the current process.
687 // We don't want to write these addresses into the archive.
688 CppVtables::zero_archived_vtables();
689
690 // Write the archive file
691 const char* static_archive = CDSConfig::static_archive_path();
692 assert(static_archive != nullptr, "SharedArchiveFile not set?");
693 _map_info = new FileMapInfo(static_archive, true);
694 _map_info->populate_header(MetaspaceShared::core_region_alignment());
695 _map_info->set_early_serialized_data(early_serialized_data);
696 _map_info->set_serialized_data(serialized_data);
697 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
698 }
699
700 class CollectCLDClosure : public CLDClosure {
701 GrowableArray<ClassLoaderData*> _loaded_cld;
702 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
703 Thread* _current_thread;
704 public:
705 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
706 ~CollectCLDClosure() {
707 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
708 _loaded_cld_handles.at(i).release(Universe::vm_global());
709 }
710 }
711 void do_cld(ClassLoaderData* cld) {
712 assert(cld->is_alive(), "must be");
713 _loaded_cld.append(cld);
714 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
715 }
716
717 int nof_cld() const { return _loaded_cld.length(); }
718 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
719 };
720
721 // Check if we can eagerly link this class at dump time, so we can avoid the
722 // runtime linking overhead (especially verification)
723 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
724 if (!ik->can_be_verified_at_dumptime()) {
725 // For old classes, try to leave them in the unlinked state, so
726 // we can still store them in the archive. They must be
727 // linked/verified at runtime.
728 return false;
729 }
730 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
731 // Linking of unregistered classes at this stage may cause more
732 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
733 // that may not be expected by custom class loaders.
734 //
735 // It's OK to do this for the built-in loaders as we know they can
736 // tolerate this.
737 return false;
738 }
739 return true;
740 }
741
742 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
743 // Link the class to cause the bytecodes to be rewritten and the
744 // cpcache to be created. Class verification is done according
745 // to -Xverify setting.
746 bool res = MetaspaceShared::try_link_class(THREAD, ik);
747 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK_(false));
748 return res;
749 }
750
751 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
752 AOTClassLinker::initialize();
753
754 if (!jcmd_request) {
755 LambdaFormInvokers::regenerate_holder_classes(CHECK);
756 }
757
758 // Collect all loaded ClassLoaderData.
759 CollectCLDClosure collect_cld(THREAD);
760 {
761 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
762 // We cannot link the classes while holding this lock (or else we may run into deadlock).
763 // Therefore, we need to first collect all the CLDs, and then link their classes after
764 // releasing the lock.
765 MutexLocker lock(ClassLoaderDataGraph_lock);
766 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
767 }
768
769 while (true) {
770 bool has_linked = false;
771 for (int i = 0; i < collect_cld.nof_cld(); i++) {
772 ClassLoaderData* cld = collect_cld.cld_at(i);
773 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
774 if (klass->is_instance_klass()) {
775 InstanceKlass* ik = InstanceKlass::cast(klass);
776 if (may_be_eagerly_linked(ik)) {
777 has_linked |= link_class_for_cds(ik, CHECK);
778 }
779 }
780 }
781 }
782
783 if (!has_linked) {
784 break;
785 }
786 // Class linking includes verification which may load more classes.
787 // Keep scanning until we have linked no more classes.
788 }
789 }
790
791 void MetaspaceShared::prepare_for_dumping() {
792 assert(CDSConfig::is_dumping_archive(), "sanity");
793 CDSConfig::check_unsupported_dumping_module_options();
794 ClassLoader::initialize_shared_path(JavaThread::current());
795 }
796
797 // Preload classes from a list, populate the shared spaces and dump to a
798 // file.
799 void MetaspaceShared::preload_and_dump(TRAPS) {
800 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
801 ResourceMark rm(THREAD);
802 StaticArchiveBuilder builder;
803 preload_and_dump_impl(builder, THREAD);
804 if (HAS_PENDING_EXCEPTION) {
805 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
806 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
807 "%zuM", MaxHeapSize/M);
808 MetaspaceShared::writing_error();
809 } else {
810 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
811 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
812 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
813 }
814 }
815
816 if (!CDSConfig::old_cds_flags_used()) {
817 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
818 // When the new -XX:AOTMode=create flag is used, we can't return
819 // to the JLI launcher, as the launcher will fail when trying to
820 // run the main class, which is not what we want.
821 tty->print_cr("AOTCache creation is complete: %s", AOTCache);
822 vm_exit(0);
823 }
824 }
825
826 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
827 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
828 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
829 return;
830 }
831 // CDS heap dumping requires all string oops to have an offset
832 // from the heap bottom that can be encoded in 32-bit.
833 julong max_heap_size = (julong)(4 * G);
834
835 if (MinHeapSize > max_heap_size) {
836 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M);
901 }
902 }
903
904 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
905 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
906 // are archived.
907 exercise_runtime_cds_code(CHECK);
908
909 log_info(cds)("Loading classes to share: done.");
910 }
911
912 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
913 // Exercise the manifest processing code
914 const char* dummy = "Manifest-Version: 1.0\n";
915 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
916
917 // Exercise FileSystem and URL code
918 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
919 }
920
921 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
922 preload_classes(CHECK);
923
924 if (SharedArchiveConfigFile) {
925 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
926 read_extra_data(THREAD, SharedArchiveConfigFile);
927 log_info(cds)("Reading extra data: done.");
928 }
929
930 // Rewrite and link classes
931 log_info(cds)("Rewriting and linking classes ...");
932
933 // Link any classes which got missed. This would happen if we have loaded classes that
934 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
935 // fails verification, all other interfaces that were not specified in the classlist but
936 // are implemented by K are not verified.
937 link_shared_classes(false/*not from jcmd*/, CHECK);
938 log_info(cds)("Rewriting and linking classes: done");
939
940 #if INCLUDE_CDS_JAVA_HEAP
941 if (CDSConfig::is_dumping_heap()) {
942 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
943 log_info(cds)("archivedBootLayer not available, disabling full module graph");
944 CDSConfig::stop_dumping_full_module_graph();
945 }
946 HeapShared::init_for_dumping(CHECK);
947 ArchiveHeapWriter::init();
948 if (CDSConfig::is_dumping_full_module_graph()) {
949 HeapShared::reset_archived_object_states(CHECK);
950 }
951
952 if (CDSConfig::is_dumping_invokedynamic()) {
953 // This assert means that the MethodType and MethodTypeForm tables won't be
954 // updated concurrently when we are saving their contents into a side table.
955 assert(CDSConfig::allow_only_single_java_thread(), "Required");
956
957 JavaValue result(T_VOID);
958 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
959 vmSymbols::createArchivedObjects(),
960 vmSymbols::void_method_signature(),
961 CHECK);
962
963 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
964 // to null, and it will be initialized again at runtime.
965 log_debug(cds)("Resetting Class::reflectionFactory");
966 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
967 Symbol* method_sig = vmSymbols::void_method_signature();
968 JavaCalls::call_static(&result, vmClasses::Class_klass(),
969 method_name, method_sig, CHECK);
970
971 // Perhaps there is a way to avoid hard-coding these names here.
972 // See discussion in JDK-8342481.
973 }
974
975 // Do this at the very end, when no Java code will be executed. Otherwise
976 // some new strings may be added to the intern table.
977 StringTable::allocate_shared_strings_array(CHECK);
978 } else {
979 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
980 CDSConfig::stop_using_optimized_module_handling();
981 }
982 #endif
983
984 VM_PopulateDumpSharedSpace op(builder);
985 VMThread::execute(&op);
986
987 if (!write_static_archive(&builder, op.map_info(), op.heap_info())) {
988 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
989 }
990 }
991
992 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
993 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
994 // without runtime relocation.
995 builder->relocate_to_requested();
996
997 map_info->open_for_write();
998 if (!map_info->is_open()) {
999 return false;
1000 }
1001 builder->write_archive(map_info, heap_info);
1002
1003 if (AllowArchivingWithJavaAgent) {
1004 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1005 "for testing purposes only and should not be used in a production environment");
1006 }
1007 return true;
1008 }
1009
1010 // Returns true if the class's status has changed.
1011 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1012 ExceptionMark em(current);
1013 JavaThread* THREAD = current; // For exception macros.
1014 assert(CDSConfig::is_dumping_archive(), "sanity");
1015 if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1016 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1017 bool saved = BytecodeVerificationLocal;
1018 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1019 // The verification decision is based on BytecodeVerificationRemote
1020 // for non-system classes. Since we are using the null classloader
1021 // to load non-system classes for customized class loaders during dumping,
1022 // we need to temporarily change BytecodeVerificationLocal to be the same as
1023 // BytecodeVerificationRemote. Note this can cause the parent system
1024 // classes also being verified. The extra overhead is acceptable during
1025 // dumping.
1026 BytecodeVerificationLocal = BytecodeVerificationRemote;
1027 }
1028 ik->link_class(THREAD);
1029 if (HAS_PENDING_EXCEPTION) {
1030 ResourceMark rm(THREAD);
1031 log_warning(cds)("Preload Warning: Verification failed for %s",
1032 ik->external_name());
1033 CLEAR_PENDING_EXCEPTION;
1034 SystemDictionaryShared::set_class_has_failed_verification(ik);
1035 } else {
1036 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1037 ik->compute_has_loops_flag_for_methods();
1038 }
1039 BytecodeVerificationLocal = saved;
1040 return true;
1041 } else {
1042 return false;
1043 }
1044 }
1045
1046 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1047 if (CDSConfig::is_dumping_heap()) {
1048 HeapShared::write_heap(&_heap_info);
1049 } else {
1050 CDSConfig::log_reasons_for_not_dumping_heap();
1051 }
1052 }
1053
1054 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1055 assert(base <= static_top && static_top <= top, "must be");
1056 _shared_metaspace_static_top = static_top;
1057 MetaspaceObj::set_shared_metaspace_range(base, top);
1058 }
1059
1060 bool MetaspaceShared::is_shared_dynamic(void* p) {
1061 if ((p < MetaspaceObj::shared_metaspace_top()) &&
1062 (p >= _shared_metaspace_static_top)) {
1063 return true;
1064 } else {
1065 return false;
1066 }
1067 }
1068
1069 bool MetaspaceShared::is_shared_static(void* p) {
1090 // This function is called when the JVM is unable to write the specified CDS archive due to an
1091 // unrecoverable error.
1092 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1093 writing_error(message);
1094 vm_direct_exit(1);
1095 }
1096
1097 // This function is called when the JVM is unable to write the specified CDS archive due to a
1098 // an error. The error will be propagated
1099 void MetaspaceShared::writing_error(const char* message) {
1100 log_error(cds)("An error has occurred while writing the shared archive file.");
1101 if (message != nullptr) {
1102 log_error(cds)("%s", message);
1103 }
1104 }
1105
1106 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1107 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1108 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1109
1110 FileMapInfo* static_mapinfo = open_static_archive();
1111 FileMapInfo* dynamic_mapinfo = nullptr;
1112
1113 if (static_mapinfo != nullptr) {
1114 log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1115 dynamic_mapinfo = open_dynamic_archive();
1116
1117 // First try to map at the requested address
1118 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1119 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1120 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1121 // by the OS.
1122 log_info(cds)("Try to map archive(s) at an alternative address");
1123 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1124 }
1125 }
1126
1127 if (result == MAP_ARCHIVE_SUCCESS) {
1128 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1129 char* cds_base = static_mapinfo->mapped_base();
1130 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1137 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1138 // turn AutoCreateSharedArchive off if successfully mapped
1139 AutoCreateSharedArchive = false;
1140 } else {
1141 FileMapInfo::set_shared_path_table(static_mapinfo);
1142 }
1143 } else {
1144 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1145 if (CDSConfig::is_dumping_dynamic_archive()) {
1146 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1147 }
1148 UseSharedSpaces = false;
1149 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1150 AutoCreateSharedArchive = false;
1151 CDSConfig::disable_dumping_dynamic_archive();
1152 log_info(cds)("Unable to map shared spaces");
1153 if (PrintSharedArchiveAndExit) {
1154 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1155 } else if (RequireSharedSpaces) {
1156 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1157 }
1158 }
1159
1160 // If mapping failed and -XShare:on, the vm should exit
1161 bool has_failed = false;
1162 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1163 has_failed = true;
1164 delete static_mapinfo;
1165 }
1166 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1167 has_failed = true;
1168 delete dynamic_mapinfo;
1169 }
1170 if (RequireSharedSpaces && has_failed) {
1171 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1172 }
1173 }
1174
1175 FileMapInfo* MetaspaceShared::open_static_archive() {
1176 const char* static_archive = CDSConfig::static_archive_path();
1177 assert(static_archive != nullptr, "sanity");
1178 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1179 if (!mapinfo->initialize()) {
1180 delete(mapinfo);
1181 return nullptr;
1182 }
1183 return mapinfo;
1184 }
1185
1186 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1187 if (CDSConfig::is_dumping_dynamic_archive()) {
1188 return nullptr;
1189 }
1190 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1191 if (dynamic_archive == nullptr) {
1192 return nullptr;
1193 }
1194
1195 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1196 if (!mapinfo->initialize()) {
1197 delete(mapinfo);
1198 if (RequireSharedSpaces) {
1199 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1200 }
1201 return nullptr;
1202 }
1203 return mapinfo;
1609 MemoryReserver::release(archive_space_rs);
1610 archive_space_rs = {};
1611 }
1612 if (class_space_rs.is_reserved()) {
1613 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1614 MemoryReserver::release(class_space_rs);
1615 class_space_rs = {};
1616 }
1617 }
1618 }
1619
1620 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1621 static int archive_regions_count = 2;
1622
1623 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1624 assert(CDSConfig::is_using_archive(), "must be runtime");
1625 if (mapinfo == nullptr) {
1626 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1627 }
1628
1629 mapinfo->set_is_mapped(false);
1630 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1631 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu"
1632 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
1633 return MAP_ARCHIVE_OTHER_FAILURE;
1634 }
1635
1636 MapArchiveResult result =
1637 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1638
1639 if (result != MAP_ARCHIVE_SUCCESS) {
1640 unmap_archive(mapinfo);
1641 return result;
1642 }
1643
1644 if (!mapinfo->validate_shared_path_table()) {
1645 unmap_archive(mapinfo);
1646 return MAP_ARCHIVE_OTHER_FAILURE;
1647 }
1648
1686 };
1687
1688 // Read the miscellaneous data from the shared file, and
1689 // serialize it out to its various destinations.
1690
1691 void MetaspaceShared::initialize_shared_spaces() {
1692 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1693
1694 // Verify various attributes of the archive, plus initialize the
1695 // shared string/symbol tables.
1696 char* buffer = static_mapinfo->serialized_data();
1697 intptr_t* array = (intptr_t*)buffer;
1698 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1699 serialize(&rc);
1700
1701 // Finish up archived heap initialization. These must be
1702 // done after ReadClosure.
1703 static_mapinfo->patch_heap_embedded_pointers();
1704 ArchiveHeapLoader::finish_initialization();
1705 Universe::load_archived_object_instances();
1706
1707 // Close the mapinfo file
1708 static_mapinfo->close();
1709
1710 static_mapinfo->unmap_region(MetaspaceShared::bm);
1711
1712 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1713 if (dynamic_mapinfo != nullptr) {
1714 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1715 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1716 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1717 DynamicArchive::setup_array_klasses();
1718 dynamic_mapinfo->close();
1719 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1720 }
1721
1722 LogStreamHandle(Info, cds) lsh;
1723 if (lsh.is_enabled()) {
1724 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1725 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
1736 // Read stored LF format lines stored in static archive
1737 LambdaFormInvokers::read_static_archive_invokers();
1738 }
1739
1740 if (PrintSharedArchiveAndExit) {
1741 // Print archive names
1742 if (dynamic_mapinfo != nullptr) {
1743 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1744 tty->print_cr("Base archive version %d", static_mapinfo->version());
1745 } else {
1746 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1747 tty->print_cr("Static archive version %d", static_mapinfo->version());
1748 }
1749
1750 SystemDictionaryShared::print_shared_archive(tty);
1751 if (dynamic_mapinfo != nullptr) {
1752 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1753 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1754 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1755 }
1756
1757 // collect shared symbols and strings
1758 CountSharedSymbols cl;
1759 SymbolTable::shared_symbols_do(&cl);
1760 tty->print_cr("Number of shared symbols: %d", cl.total());
1761 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1762 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1763 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1764 tty->print_cr("archive is invalid");
1765 vm_exit(1);
1766 } else {
1767 tty->print_cr("archive is valid");
1768 vm_exit(0);
1769 }
1770 }
1771 }
1772
1773 // JVM/TI RedefineClasses() support:
1774 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1775 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotClassInitializer.hpp"
26 #include "cds/aotArtifactFinder.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/memoryReserver.hpp"
72 #include "memory/metaspace.hpp"
73 #include "memory/metaspaceClosure.hpp"
74 #include "memory/resourceArea.hpp"
75 #include "memory/universe.hpp"
76 #include "nmt/memTracker.hpp"
77 #include "oops/compressedKlass.hpp"
78 #include "oops/instanceMirrorKlass.hpp"
79 #include "oops/klass.inline.hpp"
80 #include "oops/method.inline.hpp"
81 #include "oops/objArrayOop.hpp"
82 #include "oops/oop.inline.hpp"
83 #include "oops/oopHandle.hpp"
84 #include "oops/trainingData.hpp"
85 #include "prims/jvmtiExport.hpp"
86 #include "prims/whitebox.hpp"
87 #include "runtime/arguments.hpp"
88 #include "runtime/globals.hpp"
89 #include "runtime/globals_extension.hpp"
90 #include "runtime/handles.inline.hpp"
91 #include "runtime/javaCalls.hpp"
92 #include "runtime/os.inline.hpp"
93 #include "runtime/safepointVerifiers.hpp"
94 #include "runtime/sharedRuntime.hpp"
95 #include "runtime/vmOperations.hpp"
96 #include "runtime/vmThread.hpp"
97 #include "sanitizers/leak.hpp"
98 #include "utilities/align.hpp"
99 #include "utilities/bitMap.inline.hpp"
100 #include "utilities/defaultStream.hpp"
101 #include "utilities/macros.hpp"
102 #include "utilities/ostream.hpp"
103 #include "utilities/resourceHash.hpp"
104
105 ReservedSpace MetaspaceShared::_symbol_rs;
106 VirtualSpace MetaspaceShared::_symbol_vs;
107 bool MetaspaceShared::_archive_loading_failed = false;
108 bool MetaspaceShared::_remapped_readwrite = false;
109 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
110 intx MetaspaceShared::_relocation_delta;
111 char* MetaspaceShared::_requested_base_address;
112 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
113 bool MetaspaceShared::_use_optimized_module_handling = true;
114 int volatile MetaspaceShared::_preimage_static_archive_dumped = 0;
115
116 // The CDS archive is divided into the following regions:
117 // rw - read-write metadata
118 // ro - read-only metadata and read-only tables
119 // hp - heap region
120 // bm - bitmap for relocating the above 7 regions.
121 //
122 // The rw and ro regions are linearly allocated, in the order of rw->ro.
123 // These regions are aligned with MetaspaceShared::core_region_alignment().
124 //
125 // These 2 regions are populated in the following steps:
126 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
127 // temporarily allocated outside of the shared regions.
128 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
129 // [2] C++ vtables are copied into the rw region.
130 // [3] ArchiveBuilder copies RW metadata into the rw region.
131 // [4] ArchiveBuilder copies RO metadata into the ro region.
132 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
133 // are copied into the ro region as read-only tables.
134 //
290 }
291
292 // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
293 // picked that (a) the align_up() below will always return a valid value; (b) none of
294 // the following asserts will fail.
295 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
296 p2i((void*)SharedBaseAddress), err,
297 p2i((void*)Arguments::default_SharedBaseAddress()));
298
299 specified_base = (char*)Arguments::default_SharedBaseAddress();
300 aligned_base = align_up(specified_base, alignment);
301
302 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
303 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
304 assert(shared_base_valid(aligned_base), "Sanity");
305 return aligned_base;
306 }
307
308 void MetaspaceShared::initialize_for_static_dump() {
309 assert(CDSConfig::is_dumping_static_archive(), "sanity");
310
311 if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
312 if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
313 vm_exit_during_initialization("Cannot create the CacheDataStore",
314 "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah");
315 }
316 }
317
318 log_info(cds)("Core region alignment: %zu", core_region_alignment());
319
320 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
321 // to avoid address space wrap around.
322 size_t cds_max;
323 const size_t reserve_alignment = core_region_alignment();
324
325 #ifdef _LP64
326 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
327 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
328 #else
329 // We don't support archives larger than 256MB on 32-bit due to limited
330 // virtual address space.
331 cds_max = align_down(256*M, reserve_alignment);
332 #endif
333
334 _requested_base_address = compute_shared_base(cds_max);
335 SharedBaseAddress = (size_t)_requested_base_address;
336
337 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
338 _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
339 os::vm_allocation_granularity(),
501 // Need to do this first, as subsequent steps may call virtual functions
502 // in archived Metadata objects.
503 CppVtables::serialize(soc);
504 soc->do_tag(--tag);
505
506 // Dump/restore miscellaneous metadata.
507 JavaClasses::serialize_offsets(soc);
508 Universe::serialize(soc);
509 soc->do_tag(--tag);
510
511 // Dump/restore references to commonly used names and signatures.
512 vmSymbols::serialize(soc);
513 soc->do_tag(--tag);
514
515 // Dump/restore the symbol/string/subgraph_info tables
516 SymbolTable::serialize_shared_table_header(soc);
517 StringTable::serialize_shared_table_header(soc);
518 HeapShared::serialize_tables(soc);
519 SystemDictionaryShared::serialize_dictionary_headers(soc);
520 AOTLinkedClassBulkLoader::serialize(soc, true);
521 FinalImageRecipes::serialize(soc, true);
522 TrainingData::serialize_training_data(soc);
523 InstanceMirrorKlass::serialize_offsets(soc);
524
525 // Dump/restore well known classes (pointers)
526 SystemDictionaryShared::serialize_vm_classes(soc);
527 soc->do_tag(--tag);
528
529 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
530 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
531
532 LambdaFormInvokers::serialize(soc);
533 AdapterHandlerLibrary::serialize_shared_table_header(soc);
534
535 soc->do_tag(666);
536 }
537
538 static void rewrite_nofast_bytecode(const methodHandle& method) {
539 BytecodeStream bcs(method);
540 while (!bcs.is_last_bytecode()) {
541 Bytecodes::Code opcode = bcs.next();
542 switch (opcode) {
543 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
544 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
545 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
546 case Bytecodes::_iload: {
547 if (!bcs.is_wide()) {
548 *bcs.bcp() = Bytecodes::_nofast_iload;
549 }
550 break;
551 }
552 default: break;
553 }
554 }
590
591 bool skip_operation() const { return false; }
592
593 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
594 ArchiveHeapInfo* heap_info() { return &_heap_info; }
595 FileMapInfo* map_info() const { return _map_info; }
596 void doit(); // outline because gdb sucks
597 bool allow_nested_vm_operations() const { return true; }
598 }; // class VM_PopulateDumpSharedSpace
599
600 class StaticArchiveBuilder : public ArchiveBuilder {
601 public:
602 StaticArchiveBuilder() : ArchiveBuilder() {}
603
604 virtual void iterate_roots(MetaspaceClosure* it) {
605 FileMapInfo::metaspace_pointers_do(it);
606 AOTArtifactFinder::all_cached_classes_do(it);
607 SystemDictionaryShared::dumptime_classes_do(it);
608 Universe::metaspace_pointers_do(it);
609 vmSymbols::metaspace_pointers_do(it);
610 TrainingData::iterate_roots(it);
611
612 // The above code should find all the symbols that are referenced by the
613 // archived classes. We just need to add the extra symbols which
614 // may not be used by any of the archived classes -- these are usually
615 // symbols that we anticipate to be used at run time, so we can store
616 // them in the RO region, to be shared across multiple processes.
617 if (_extra_symbols != nullptr) {
618 for (int i = 0; i < _extra_symbols->length(); i++) {
619 it->push(_extra_symbols->adr_at(i));
620 }
621 }
622
623 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
624 it->push(_pending_method_handle_intrinsics->adr_at(i));
625 }
626 }
627 };
628
629 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
630 ArchiveBuilder::OtherROAllocMark mark;
631
632 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
633
634 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
635 char* start = ro_region->top();
636 WriteClosure wc(ro_region);
637 MetaspaceShared::early_serialize(&wc);
638 return start;
639 }
640
641 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
642 ArchiveBuilder::OtherROAllocMark mark;
643
644 SystemDictionaryShared::write_to_archive();
645 AOTClassLinker::write_to_archive();
646 if (CDSConfig::is_dumping_preimage_static_archive()) {
647 FinalImageRecipes::record_recipes();
648 }
649 AOTLinkedClassBulkLoader::record_unregistered_classes();
650 TrainingData::dump_training_data();
651 MetaspaceShared::write_method_handle_intrinsics();
652
653 // Write lambform lines into archive
654 LambdaFormInvokers::dump_static_archive_invokers();
655
656 if (CDSConfig::is_dumping_adapters()) {
657 AdapterHandlerLibrary::archive_adapter_table();
658 }
659
660 // Write the other data to the output array.
661 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
662 char* start = ro_region->top();
663 WriteClosure wc(ro_region);
664 MetaspaceShared::serialize(&wc);
665
666 return start;
667 }
668
669 void VM_PopulateDumpSharedSpace::doit() {
670 //guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
671
672 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
673
674 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
675 if (CDSConfig::is_dumping_aot_linked_classes()) {
676 // When dumping AOT-linked classes, some classes may have direct references to a method handle
677 // intrinsic. The easiest thing is to save all of them into the AOT cache.
678 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
679 }
680
681 FileMapInfo::check_nonempty_dir_in_shared_path_table();
682
683 NOT_PRODUCT(SystemDictionary::verify();)
684
685 // Block concurrent class unloading from changing the _dumptime_table
686 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
687
688 #if INCLUDE_CDS_JAVA_HEAP
689 if (CDSConfig::is_dumping_heap() && _extra_interned_strings != nullptr) {
690 for (int i = 0; i < _extra_interned_strings->length(); i ++) {
699
700 CppVtables::dumptime_init(&_builder);
701
702 _builder.sort_metadata_objs();
703 _builder.dump_rw_metadata();
704 _builder.dump_ro_metadata();
705 _builder.relocate_metaspaceobj_embedded_pointers();
706
707 log_info(cds)("Make classes shareable");
708 _builder.make_klasses_shareable();
709 MetaspaceShared::make_method_handle_intrinsics_shareable();
710
711 dump_java_heap_objects();
712 dump_shared_symbol_table(_builder.symbols());
713
714 char* early_serialized_data = dump_early_read_only_tables();
715 char* serialized_data = dump_read_only_tables();
716
717 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
718
719 log_info(cds)("Make training data shareable");
720 _builder.make_training_data_shareable();
721
722 // The vtable clones contain addresses of the current process.
723 // We don't want to write these addresses into the archive.
724 CppVtables::zero_archived_vtables();
725
726 // Write the archive file
727 const char* static_archive;
728 if (CDSConfig::is_dumping_final_static_archive()) {
729 static_archive = CacheDataStore;
730 assert(FileMapInfo::current_info() != nullptr, "sanity");
731 delete FileMapInfo::current_info();
732 } else {
733 static_archive = CDSConfig::static_archive_path();
734 }
735 assert(static_archive != nullptr, "SharedArchiveFile not set?");
736 _map_info = new FileMapInfo(static_archive, true);
737 _map_info->populate_header(MetaspaceShared::core_region_alignment());
738 _map_info->set_early_serialized_data(early_serialized_data);
739 _map_info->set_serialized_data(serialized_data);
740 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
741 }
742
743 class CollectCLDClosure : public CLDClosure {
744 GrowableArray<ClassLoaderData*> _loaded_cld;
745 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
746 Thread* _current_thread;
747 public:
748 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
749 ~CollectCLDClosure() {
750 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
751 _loaded_cld_handles.at(i).release(Universe::vm_global());
752 }
753 }
754 void do_cld(ClassLoaderData* cld) {
755 assert(cld->is_alive(), "must be");
756 _loaded_cld.append(cld);
757 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
758 }
759
760 int nof_cld() const { return _loaded_cld.length(); }
761 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
762 };
763
764 // Check if we can eagerly link this class at dump time, so we can avoid the
765 // runtime linking overhead (especially verification)
766 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
767 if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
768 assert(ik->can_be_verified_at_dumptime(), "sanity");
769 }
770 if (!ik->can_be_verified_at_dumptime()) {
771 // For old classes, try to leave them in the unlinked state, so
772 // we can still store them in the archive. They must be
773 // linked/verified at runtime.
774 return false;
775 }
776
777 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
778 // Linking of unregistered classes at this stage may cause more
779 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
780 // that may not be expected by custom class loaders.
781 //
782 // It's OK to do this for the built-in loaders as we know they can
783 // tolerate this.
784 return false;
785 }
786 return true;
787 }
788
789
790 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
791 AOTClassLinker::initialize();
792
793 if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
794 && !CDSConfig::is_dumping_preimage_static_archive()
795 && !CDSConfig::is_dumping_final_static_archive()) {
796 // If we have regenerated invoker classes in the dynamic archive,
797 // they will conflict with the resolved CONSTANT_Klass references that are stored
798 // in the static archive. This is not easy to handle. Let's disable
799 // it for dynamic archive for now.
800 LambdaFormInvokers::regenerate_holder_classes(CHECK);
801 }
802
803 // Collect all loaded ClassLoaderData.
804 CollectCLDClosure collect_cld(THREAD);
805 {
806 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
807 // We cannot link the classes while holding this lock (or else we may run into deadlock).
808 // Therefore, we need to first collect all the CLDs, and then link their classes after
809 // releasing the lock.
810 MutexLocker lock(ClassLoaderDataGraph_lock);
811 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
812 }
813
814 while (true) {
815 bool has_linked = false;
816 for (int i = 0; i < collect_cld.nof_cld(); i++) {
817 ClassLoaderData* cld = collect_cld.cld_at(i);
818 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
819 if (klass->is_instance_klass()) {
820 InstanceKlass* ik = InstanceKlass::cast(klass);
821 if (may_be_eagerly_linked(ik)) {
822 has_linked |= try_link_class(THREAD, ik);
823 }
824 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
825 AOTClassInitializer::maybe_preinit_class(ik, CHECK);
826 }
827 }
828 }
829 }
830
831 if (!has_linked) {
832 break;
833 }
834 // Class linking includes verification which may load more classes.
835 // Keep scanning until we have linked no more classes.
836 }
837
838 // Resolve constant pool entries -- we don't load any new classes during this stage
839 for (int i = 0; i < collect_cld.nof_cld(); i++) {
840 ClassLoaderData* cld = collect_cld.cld_at(i);
841 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
842 if (klass->is_instance_klass()) {
843 InstanceKlass* ik = InstanceKlass::cast(klass);
844 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
845 if (CDSConfig::is_dumping_preimage_static_archive()) {
846 FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
847 }
848 }
849 }
850 }
851
852 if (CDSConfig::is_dumping_preimage_static_archive()) {
853 // Do this after all classes are verified by the above loop.
854 // Any classes loaded from here on will be automatically excluded, so
855 // there's no need to force verification or resolve CP entries.
856 RecordTraining = false;
857 SystemDictionaryShared::ignore_new_classes();
858 LambdaFormInvokers::regenerate_holder_classes(CHECK);
859 RecordTraining = true;
860 }
861
862 if (CDSConfig::is_dumping_final_static_archive()) {
863 FinalImageRecipes::apply_recipes(CHECK);
864 }
865 }
866
867 void MetaspaceShared::prepare_for_dumping() {
868 assert(CDSConfig::is_dumping_archive(), "sanity");
869 CDSConfig::check_unsupported_dumping_module_options();
870 ClassLoader::initialize_shared_path(JavaThread::current());
871 }
872
873 // Preload classes from a list, populate the shared spaces and dump to a
874 // file.
875 void MetaspaceShared::preload_and_dump(TRAPS) {
876 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
877 ResourceMark rm(THREAD);
878 HandleMark hm(THREAD);
879
880 if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
881 tty->print_cr("==================== archived_training_data ** before dumping ====================");
882 TrainingData::print_archived_training_data_on(tty);
883 }
884
885 StaticArchiveBuilder builder;
886 preload_and_dump_impl(builder, THREAD);
887 if (HAS_PENDING_EXCEPTION) {
888 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
889 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
890 "%zuM", MaxHeapSize/M);
891 MetaspaceShared::writing_error();
892 } else {
893 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
894 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
895 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
896 }
897 }
898
899 if (!CDSConfig::old_cds_flags_used() && !CDSConfig::is_dumping_preimage_static_archive() && !CDSConfig::is_dumping_final_static_archive()) {
900 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
901 // When the new -XX:AOTMode=create flag is used, we can't return
902 // to the JLI launcher, as the launcher will fail when trying to
903 // run the main class, which is not what we want.
904 tty->print_cr("AOTCache creation is complete: %s", AOTCache);
905 vm_exit(0);
906 }
907 }
908
909 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
910 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
911 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
912 return;
913 }
914 // CDS heap dumping requires all string oops to have an offset
915 // from the heap bottom that can be encoded in 32-bit.
916 julong max_heap_size = (julong)(4 * G);
917
918 if (MinHeapSize > max_heap_size) {
919 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = %zuM", MinHeapSize/M);
984 }
985 }
986
987 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
988 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
989 // are archived.
990 exercise_runtime_cds_code(CHECK);
991
992 log_info(cds)("Loading classes to share: done.");
993 }
994
995 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
996 // Exercise the manifest processing code
997 const char* dummy = "Manifest-Version: 1.0\n";
998 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
999
1000 // Exercise FileSystem and URL code
1001 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
1002 }
1003
1004 bool MetaspaceShared::is_recording_preimage_static_archive() {
1005 if (CDSConfig::is_dumping_preimage_static_archive()) {
1006 return _preimage_static_archive_dumped == 0;
1007 }
1008 return false;
1009 }
1010
1011 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
1012 if (CDSConfig::is_dumping_preimage_static_archive()) {
1013 if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
1014 return;
1015 }
1016 }
1017
1018 if (CDSConfig::is_dumping_classic_static_archive()) {
1019 // We are running with -Xshare:dump
1020 preload_classes(CHECK);
1021
1022 if (SharedArchiveConfigFile) {
1023 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1024 read_extra_data(THREAD, SharedArchiveConfigFile);
1025 log_info(cds)("Reading extra data: done.");
1026 }
1027 }
1028
1029 if (CDSConfig::is_dumping_preimage_static_archive()) {
1030 log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
1031 char default_classlist[JVM_MAXPATHLEN];
1032 get_default_classlist(default_classlist, sizeof(default_classlist));
1033 struct stat statbuf;
1034 if (os::stat(default_classlist, &statbuf) == 0) {
1035 ClassListParser::parse_classlist(default_classlist,
1036 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
1037 }
1038 }
1039
1040 // Rewrite and link classes
1041 log_info(cds)("Rewriting and linking classes ...");
1042
1043 // Link any classes which got missed. This would happen if we have loaded classes that
1044 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1045 // fails verification, all other interfaces that were not specified in the classlist but
1046 // are implemented by K are not verified.
1047 link_shared_classes(false/*not from jcmd*/, CHECK);
1048 log_info(cds)("Rewriting and linking classes: done");
1049
1050 if (CDSConfig::is_dumping_final_static_archive()) {
1051 assert(RecordTraining == false, "must be");
1052 RecordTraining = true;
1053 }
1054
1055 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1056
1057 #if INCLUDE_CDS_JAVA_HEAP
1058 if (CDSConfig::is_dumping_heap()) {
1059 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1060 log_info(cds)("archivedBootLayer not available, disabling full module graph");
1061 CDSConfig::stop_dumping_full_module_graph();
1062 }
1063 HeapShared::init_for_dumping(CHECK);
1064 ArchiveHeapWriter::init();
1065 if (CDSConfig::is_dumping_full_module_graph()) {
1066 HeapShared::reset_archived_object_states(CHECK);
1067 }
1068
1069 if (ArchiveLoaderLookupCache) {
1070 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1071 }
1072
1073 if (CDSConfig::is_dumping_invokedynamic()) {
1074 // This assert means that the MethodType and MethodTypeForm tables won't be
1075 // updated concurrently when we are saving their contents into a side table.
1076 assert(CDSConfig::allow_only_single_java_thread(), "Required");
1077
1078 JavaValue result(T_VOID);
1079 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
1080 vmSymbols::createArchivedObjects(),
1081 vmSymbols::void_method_signature(),
1082 CHECK);
1083
1084 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1085 // to null, and it will be initialized again at runtime.
1086 log_debug(cds)("Resetting Class::reflectionFactory");
1087 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1088 Symbol* method_sig = vmSymbols::void_method_signature();
1089 JavaCalls::call_static(&result, vmClasses::Class_klass(),
1090 method_name, method_sig, CHECK);
1091
1092 // Perhaps there is a way to avoid hard-coding these names here.
1093 // See discussion in JDK-8342481.
1094 }
1095
1096 // Do this at the very end, when no Java code will be executed. Otherwise
1097 // some new strings may be added to the intern table.
1098 StringTable::allocate_shared_strings_array(CHECK);
1099 } else {
1100 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1101 CDSConfig::stop_using_optimized_module_handling();
1102 }
1103 #endif
1104
1105 VM_PopulateDumpSharedSpace op(builder);
1106 VMThread::execute(&op);
1107 FileMapInfo* mapinfo = op.map_info();
1108 ArchiveHeapInfo* heap_info = op.heap_info();
1109 bool status;
1110 if (CDSConfig::is_dumping_preimage_static_archive()) {
1111 if ((status = write_static_archive(&builder, mapinfo, heap_info))) {
1112 fork_and_dump_final_static_archive();
1113 }
1114 } else if (CDSConfig::is_dumping_final_static_archive()) {
1115 RecordTraining = false;
1116 if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
1117 if (log_is_enabled(Info, cds, jit)) {
1118 CDSAccess::test_heap_access_api();
1119 }
1120
1121 // We have just created the final image. Let's run the AOT compiler
1122 if (PrintTrainingInfo) {
1123 tty->print_cr("==================== archived_training_data ** after dumping ====================");
1124 TrainingData::print_archived_training_data_on(tty);
1125 }
1126
1127 CDSConfig::enable_dumping_cached_code();
1128 {
1129 builder.start_cc_region();
1130 Precompiler::compile_cached_code(&builder, CHECK);
1131 builder.end_cc_region();
1132 }
1133 CDSConfig::disable_dumping_cached_code();
1134
1135 SCCache::close(); // Write final data and close archive
1136 }
1137 status = write_static_archive(&builder, mapinfo, heap_info);
1138 } else {
1139 status = write_static_archive(&builder, mapinfo, heap_info);
1140 }
1141
1142 if (!status) {
1143 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1144 }
1145 }
1146
1147 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1148 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1149 // without runtime relocation.
1150 builder->relocate_to_requested();
1151
1152 map_info->open_for_write();
1153 if (!map_info->is_open()) {
1154 return false;
1155 }
1156 builder->write_archive(map_info, heap_info);
1157
1158 if (AllowArchivingWithJavaAgent) {
1159 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1160 "for testing purposes only and should not be used in a production environment");
1161 }
1162 return true;
1163 }
1164
1165 static void print_java_launcher(outputStream* st) {
1166 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1167 }
1168
1169 static void print_vm_arguments(outputStream* st) {
1170 const char* cp = Arguments::get_appclasspath();
1171 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1172 st->print(" -cp "); st->print_raw(cp);
1173 }
1174 for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1175 st->print(" %s", Arguments::jvm_flags_array()[i]);
1176 }
1177 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1178 st->print(" %s", Arguments::jvm_args_array()[i]);
1179 }
1180 }
1181
1182 void MetaspaceShared::fork_and_dump_final_static_archive() {
1183 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1184
1185 ResourceMark rm;
1186 stringStream ss;
1187 print_java_launcher(&ss);
1188 print_vm_arguments(&ss);
1189 ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1190
1191 const char* cmd = ss.freeze();
1192 if (CDSManualFinalImage) {
1193 tty->print_cr("-XX:+CDSManualFinalImage is specified");
1194 tty->print_cr("Please manually execute the following command to create the final CDS image:");
1195 tty->print(" "); tty->print_raw_cr(cmd);
1196
1197 // The following is useful if the dumping was trigger by a script that builds
1198 // a complex command-line.
1199 tty->print_cr("Note: to recreate the preimage only:");
1200 tty->print_cr(" rm -f %s", CacheDataStore);
1201 tty->print(" ");
1202 print_java_launcher(tty);
1203 print_vm_arguments(tty);
1204 if (Arguments::java_command() != nullptr) {
1205 tty->print(" %s", Arguments::java_command());
1206 }
1207 tty->cr();
1208 } else {
1209 // FIXME: space characters are not properly quoated. E.g.,
1210 // java -Dfoo='a b c' HelloWorld
1211 log_info(cds)("Launching child process to create final CDS image:");
1212 log_info(cds)(" %s", cmd);
1213 int status = os::fork_and_exec(cmd);
1214 if (status != 0) {
1215 log_error(cds)("Child process finished; status = %d", status);
1216 log_error(cds)("To reproduce the error");
1217 ResourceMark rm;
1218 LogStream ls(Log(cds)::error());
1219 ls.print(" "); ls.print_raw_cr(cmd);
1220
1221 // The following is useful if the dumping was trigger by a script that builds
1222 // a complex command-line.
1223 ls.print_cr("Note: to recreate the preimage only:");
1224 ls.print_cr(" rm -f %s", CacheDataStore);
1225 ls.print(" ");
1226 print_java_launcher(&ls);
1227 print_vm_arguments(&ls);
1228 ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1229 if (Arguments::java_command() != nullptr) {
1230 ls.print(" %s", Arguments::java_command());
1231 }
1232 ls.cr();
1233
1234 vm_direct_exit(status);
1235 } else {
1236 log_info(cds)("Child process finished; status = %d", status);
1237 // On Windows, need WRITE permission to remove the file.
1238 WINDOWS_ONLY(chmod(SharedArchiveFile, _S_IREAD | _S_IWRITE));
1239 status = remove(SharedArchiveFile);
1240 if (status != 0) {
1241 log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1242 } else {
1243 log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1244 }
1245 }
1246 }
1247 }
1248
1249 // Returns true if the class's status has changed.
1250 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1251 ExceptionMark em(current);
1252 JavaThread* THREAD = current; // For exception macros.
1253 assert(CDSConfig::is_dumping_archive(), "sanity");
1254
1255 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1256 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1257 return false;
1258 }
1259
1260 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1261 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1262 bool saved = BytecodeVerificationLocal;
1263 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1264 // The verification decision is based on BytecodeVerificationRemote
1265 // for non-system classes. Since we are using the null classloader
1266 // to load non-system classes for customized class loaders during dumping,
1267 // we need to temporarily change BytecodeVerificationLocal to be the same as
1268 // BytecodeVerificationRemote. Note this can cause the parent system
1269 // classes also being verified. The extra overhead is acceptable during
1270 // dumping.
1271 BytecodeVerificationLocal = BytecodeVerificationRemote;
1272 }
1273 ik->link_class(THREAD);
1274 if (HAS_PENDING_EXCEPTION) {
1275 ResourceMark rm(THREAD);
1276 log_warning(cds)("Preload Warning: Verification failed for %s",
1277 ik->external_name());
1278 CLEAR_PENDING_EXCEPTION;
1279 SystemDictionaryShared::set_class_has_failed_verification(ik);
1280 } else {
1281 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1282 ik->compute_has_loops_flag_for_methods();
1283 }
1284 BytecodeVerificationLocal = saved;
1285 return true;
1286 } else {
1287 return false;
1288 }
1289 }
1290
1291 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1292 if (CDSConfig::is_dumping_heap()) {
1293 HeapShared::write_heap(&_heap_info);
1294 } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1295 CDSConfig::log_reasons_for_not_dumping_heap();
1296 }
1297 }
1298
1299 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1300 assert(base <= static_top && static_top <= top, "must be");
1301 _shared_metaspace_static_top = static_top;
1302 MetaspaceObj::set_shared_metaspace_range(base, top);
1303 }
1304
1305 bool MetaspaceShared::is_shared_dynamic(void* p) {
1306 if ((p < MetaspaceObj::shared_metaspace_top()) &&
1307 (p >= _shared_metaspace_static_top)) {
1308 return true;
1309 } else {
1310 return false;
1311 }
1312 }
1313
1314 bool MetaspaceShared::is_shared_static(void* p) {
1335 // This function is called when the JVM is unable to write the specified CDS archive due to an
1336 // unrecoverable error.
1337 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1338 writing_error(message);
1339 vm_direct_exit(1);
1340 }
1341
1342 // This function is called when the JVM is unable to write the specified CDS archive due to a
1343 // an error. The error will be propagated
1344 void MetaspaceShared::writing_error(const char* message) {
1345 log_error(cds)("An error has occurred while writing the shared archive file.");
1346 if (message != nullptr) {
1347 log_error(cds)("%s", message);
1348 }
1349 }
1350
1351 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1352 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1353 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1354
1355 FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1356 FileMapInfo* dynamic_mapinfo = nullptr;
1357
1358 if (static_mapinfo != nullptr) {
1359 log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1360 dynamic_mapinfo = open_dynamic_archive();
1361
1362 // First try to map at the requested address
1363 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1364 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1365 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1366 // by the OS.
1367 log_info(cds)("Try to map archive(s) at an alternative address");
1368 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1369 }
1370 }
1371
1372 if (result == MAP_ARCHIVE_SUCCESS) {
1373 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1374 char* cds_base = static_mapinfo->mapped_base();
1375 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1382 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1383 // turn AutoCreateSharedArchive off if successfully mapped
1384 AutoCreateSharedArchive = false;
1385 } else {
1386 FileMapInfo::set_shared_path_table(static_mapinfo);
1387 }
1388 } else {
1389 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1390 if (CDSConfig::is_dumping_dynamic_archive()) {
1391 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1392 }
1393 UseSharedSpaces = false;
1394 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1395 AutoCreateSharedArchive = false;
1396 CDSConfig::disable_dumping_dynamic_archive();
1397 log_info(cds)("Unable to map shared spaces");
1398 if (PrintSharedArchiveAndExit) {
1399 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1400 } else if (RequireSharedSpaces) {
1401 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1402 } else if (CDSConfig::is_dumping_final_static_archive()) {
1403 assert(CDSPreimage != nullptr, "must be");
1404 log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1405 MetaspaceShared::unrecoverable_loading_error();
1406 }
1407 }
1408
1409 // If mapping failed and -XShare:on, the vm should exit
1410 bool has_failed = false;
1411 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1412 has_failed = true;
1413 delete static_mapinfo;
1414 }
1415 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1416 has_failed = true;
1417 delete dynamic_mapinfo;
1418 }
1419 if (RequireSharedSpaces && has_failed) {
1420 // static archive mapped but dynamic archive failed
1421 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1422 }
1423 }
1424
1425 // This is called very early at VM start up to get the size of the cached_code region, which
1426 // is used in CodeCache::initialize_heaps()
1427 void MetaspaceShared::open_static_archive() {
1428 if (!UseSharedSpaces) {
1429 return;
1430 }
1431 const char* static_archive = CDSConfig::static_archive_path();
1432 assert(static_archive != nullptr, "sanity");
1433 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1434 if (!mapinfo->initialize()) {
1435 delete(mapinfo);
1436 } else {
1437 FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1438 CDSAccess::set_cached_code_size(r->used_aligned());
1439 }
1440 }
1441
1442 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1443 if (CDSConfig::is_dumping_dynamic_archive()) {
1444 return nullptr;
1445 }
1446 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1447 if (dynamic_archive == nullptr) {
1448 return nullptr;
1449 }
1450
1451 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1452 if (!mapinfo->initialize()) {
1453 delete(mapinfo);
1454 if (RequireSharedSpaces) {
1455 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1456 }
1457 return nullptr;
1458 }
1459 return mapinfo;
1865 MemoryReserver::release(archive_space_rs);
1866 archive_space_rs = {};
1867 }
1868 if (class_space_rs.is_reserved()) {
1869 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1870 MemoryReserver::release(class_space_rs);
1871 class_space_rs = {};
1872 }
1873 }
1874 }
1875
1876 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1877 static int archive_regions_count = 2;
1878
1879 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1880 assert(CDSConfig::is_using_archive(), "must be runtime");
1881 if (mapinfo == nullptr) {
1882 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1883 }
1884
1885 if (!mapinfo->validate_aot_class_linking()) {
1886 return MAP_ARCHIVE_OTHER_FAILURE;
1887 }
1888
1889 mapinfo->set_is_mapped(false);
1890 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1891 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu"
1892 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
1893 return MAP_ARCHIVE_OTHER_FAILURE;
1894 }
1895
1896 MapArchiveResult result =
1897 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1898
1899 if (result != MAP_ARCHIVE_SUCCESS) {
1900 unmap_archive(mapinfo);
1901 return result;
1902 }
1903
1904 if (!mapinfo->validate_shared_path_table()) {
1905 unmap_archive(mapinfo);
1906 return MAP_ARCHIVE_OTHER_FAILURE;
1907 }
1908
1946 };
1947
1948 // Read the miscellaneous data from the shared file, and
1949 // serialize it out to its various destinations.
1950
1951 void MetaspaceShared::initialize_shared_spaces() {
1952 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1953
1954 // Verify various attributes of the archive, plus initialize the
1955 // shared string/symbol tables.
1956 char* buffer = static_mapinfo->serialized_data();
1957 intptr_t* array = (intptr_t*)buffer;
1958 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1959 serialize(&rc);
1960
1961 // Finish up archived heap initialization. These must be
1962 // done after ReadClosure.
1963 static_mapinfo->patch_heap_embedded_pointers();
1964 ArchiveHeapLoader::finish_initialization();
1965 Universe::load_archived_object_instances();
1966 SCCache::new_workflow_load_cache();
1967
1968 // Close the mapinfo file
1969 static_mapinfo->close();
1970
1971 static_mapinfo->unmap_region(MetaspaceShared::bm);
1972
1973 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1974 if (dynamic_mapinfo != nullptr) {
1975 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1976 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1977 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1978 DynamicArchive::setup_array_klasses();
1979 dynamic_mapinfo->close();
1980 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1981 }
1982
1983 LogStreamHandle(Info, cds) lsh;
1984 if (lsh.is_enabled()) {
1985 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1986 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
1997 // Read stored LF format lines stored in static archive
1998 LambdaFormInvokers::read_static_archive_invokers();
1999 }
2000
2001 if (PrintSharedArchiveAndExit) {
2002 // Print archive names
2003 if (dynamic_mapinfo != nullptr) {
2004 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
2005 tty->print_cr("Base archive version %d", static_mapinfo->version());
2006 } else {
2007 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
2008 tty->print_cr("Static archive version %d", static_mapinfo->version());
2009 }
2010
2011 SystemDictionaryShared::print_shared_archive(tty);
2012 if (dynamic_mapinfo != nullptr) {
2013 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
2014 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
2015 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
2016 }
2017 TrainingData::print_archived_training_data_on(tty);
2018
2019 if (LoadCachedCode) {
2020 tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
2021 SCCache::print_on(tty);
2022 }
2023
2024 // collect shared symbols and strings
2025 CountSharedSymbols cl;
2026 SymbolTable::shared_symbols_do(&cl);
2027 tty->print_cr("Number of shared symbols: %d", cl.total());
2028 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2029 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2030 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2031 tty->print_cr("archive is invalid");
2032 vm_exit(1);
2033 } else {
2034 tty->print_cr("archive is valid");
2035 vm_exit(0);
2036 }
2037 }
2038 }
2039
2040 // JVM/TI RedefineClasses() support:
2041 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2042 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|