6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/aotClassLinker.hpp"
27 #include "cds/aotConstantPoolResolver.hpp"
28 #include "cds/aotLinkedClassBulkLoader.hpp"
29 #include "cds/archiveBuilder.hpp"
30 #include "cds/archiveHeapLoader.hpp"
31 #include "cds/archiveHeapWriter.hpp"
32 #include "cds/cds_globals.hpp"
33 #include "cds/cdsConfig.hpp"
34 #include "cds/cdsProtectionDomain.hpp"
35 #include "cds/classListParser.hpp"
36 #include "cds/classListWriter.hpp"
37 #include "cds/cppVtables.hpp"
38 #include "cds/dumpAllocStats.hpp"
39 #include "cds/dynamicArchive.hpp"
40 #include "cds/filemap.hpp"
41 #include "cds/heapShared.hpp"
42 #include "cds/lambdaFormInvokers.hpp"
43 #include "cds/metaspaceShared.hpp"
44 #include "classfile/classLoaderDataGraph.hpp"
45 #include "classfile/classLoaderDataShared.hpp"
46 #include "classfile/classLoaderExt.hpp"
47 #include "classfile/javaClasses.inline.hpp"
48 #include "classfile/loaderConstraints.hpp"
49 #include "classfile/modules.hpp"
50 #include "classfile/placeholders.hpp"
51 #include "classfile/stringTable.hpp"
52 #include "classfile/symbolTable.hpp"
53 #include "classfile/systemDictionary.hpp"
54 #include "classfile/systemDictionaryShared.hpp"
55 #include "classfile/vmClasses.hpp"
56 #include "classfile/vmSymbols.hpp"
57 #include "code/codeCache.hpp"
58 #include "gc/shared/gcVMOperations.hpp"
59 #include "interpreter/bytecodeStream.hpp"
60 #include "interpreter/bytecodes.hpp"
61 #include "jvm_io.h"
62 #include "logging/log.hpp"
63 #include "logging/logMessage.hpp"
64 #include "logging/logStream.hpp"
65 #include "memory/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 //
247 err = "invalid for this platform";
248 } else {
249 return aligned_base;
250 }
251
252 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
253 p2i((void*)SharedBaseAddress), err,
254 p2i((void*)Arguments::default_SharedBaseAddress()));
255
256 specified_base = (char*)Arguments::default_SharedBaseAddress();
257 aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
258
259 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
260 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
261 assert(shared_base_valid(aligned_base), "Sanity");
262 return aligned_base;
263 }
264
265 void MetaspaceShared::initialize_for_static_dump() {
266 assert(CDSConfig::is_dumping_static_archive(), "sanity");
267 log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
268 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
269 // to avoid address space wrap around.
270 size_t cds_max;
271 const size_t reserve_alignment = core_region_alignment();
272
273 #ifdef _LP64
274 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
275 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
276 #else
277 // We don't support archives larger than 256MB on 32-bit due to limited
278 // virtual address space.
279 cds_max = align_down(256*M, reserve_alignment);
280 #endif
281
282 _requested_base_address = compute_shared_base(cds_max);
283 SharedBaseAddress = (size_t)_requested_base_address;
284
285 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
286 _symbol_rs = MemoryReserver::reserve(symbol_rs_size, mtClassShared);
446 // Need to do this first, as subsequent steps may call virtual functions
447 // in archived Metadata objects.
448 CppVtables::serialize(soc);
449 soc->do_tag(--tag);
450
451 // Dump/restore miscellaneous metadata.
452 JavaClasses::serialize_offsets(soc);
453 Universe::serialize(soc);
454 soc->do_tag(--tag);
455
456 // Dump/restore references to commonly used names and signatures.
457 vmSymbols::serialize(soc);
458 soc->do_tag(--tag);
459
460 // Dump/restore the symbol/string/subgraph_info tables
461 SymbolTable::serialize_shared_table_header(soc);
462 StringTable::serialize_shared_table_header(soc);
463 HeapShared::serialize_tables(soc);
464 SystemDictionaryShared::serialize_dictionary_headers(soc);
465 AOTLinkedClassBulkLoader::serialize(soc, true);
466 InstanceMirrorKlass::serialize_offsets(soc);
467
468 // Dump/restore well known classes (pointers)
469 SystemDictionaryShared::serialize_vm_classes(soc);
470 soc->do_tag(--tag);
471
472 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
473 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
474
475 LambdaFormInvokers::serialize(soc);
476 soc->do_tag(666);
477 }
478
479 static void rewrite_nofast_bytecode(const methodHandle& method) {
480 BytecodeStream bcs(method);
481 while (!bcs.is_last_bytecode()) {
482 Bytecodes::Code opcode = bcs.next();
483 switch (opcode) {
484 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
485 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
530 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
531
532 bool skip_operation() const { return false; }
533
534 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
535 ArchiveHeapInfo* heap_info() { return &_heap_info; }
536 FileMapInfo* map_info() const { return _map_info; }
537 void doit(); // outline because gdb sucks
538 bool allow_nested_vm_operations() const { return true; }
539 }; // class VM_PopulateDumpSharedSpace
540
541 class StaticArchiveBuilder : public ArchiveBuilder {
542 public:
543 StaticArchiveBuilder() : ArchiveBuilder() {}
544
545 virtual void iterate_roots(MetaspaceClosure* it) {
546 FileMapInfo::metaspace_pointers_do(it);
547 SystemDictionaryShared::dumptime_classes_do(it);
548 Universe::metaspace_pointers_do(it);
549 vmSymbols::metaspace_pointers_do(it);
550
551 // The above code should find all the symbols that are referenced by the
552 // archived classes. We just need to add the extra symbols which
553 // may not be used by any of the archived classes -- these are usually
554 // symbols that we anticipate to be used at run time, so we can store
555 // them in the RO region, to be shared across multiple processes.
556 if (_extra_symbols != nullptr) {
557 for (int i = 0; i < _extra_symbols->length(); i++) {
558 it->push(_extra_symbols->adr_at(i));
559 }
560 }
561
562 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
563 it->push(_pending_method_handle_intrinsics->adr_at(i));
564 }
565 }
566 };
567
568 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
569 ArchiveBuilder::OtherROAllocMark mark;
570
571 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
572
573 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
574 char* start = ro_region->top();
575 WriteClosure wc(ro_region);
576 MetaspaceShared::early_serialize(&wc);
577 return start;
578 }
579
580 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
581 ArchiveBuilder::OtherROAllocMark mark;
582
583 SystemDictionaryShared::write_to_archive();
584 AOTClassLinker::write_to_archive();
585 MetaspaceShared::write_method_handle_intrinsics();
586
587 // Write lambform lines into archive
588 LambdaFormInvokers::dump_static_archive_invokers();
589
590 // Write the other data to the output array.
591 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
592 char* start = ro_region->top();
593 WriteClosure wc(ro_region);
594 MetaspaceShared::serialize(&wc);
595
596 return start;
597 }
598
599 void VM_PopulateDumpSharedSpace::doit() {
600 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
601
602 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
603
604 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
605 if (CDSConfig::is_dumping_aot_linked_classes()) {
606 // When dumping AOT-linked classes, some classes may have direct references to a method handle
607 // intrinsic. The easiest thing is to save all of them into the AOT cache.
608 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
609 }
610
611 FileMapInfo::check_nonempty_dir_in_shared_path_table();
612
613 NOT_PRODUCT(SystemDictionary::verify();)
614
615 // Block concurrent class unloading from changing the _dumptime_table
616 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
617 SystemDictionaryShared::find_all_archivable_classes();
618
619 _builder.gather_source_objs();
620 _builder.reserve_buffer();
621
622 CppVtables::dumptime_init(&_builder);
623
624 _builder.sort_metadata_objs();
625 _builder.dump_rw_metadata();
626 _builder.dump_ro_metadata();
627 _builder.relocate_metaspaceobj_embedded_pointers();
628
629 dump_java_heap_objects(_builder.klasses());
630 dump_shared_symbol_table(_builder.symbols());
631
632 log_info(cds)("Make classes shareable");
633 _builder.make_klasses_shareable();
634 MetaspaceShared::make_method_handle_intrinsics_shareable();
635
636 char* early_serialized_data = dump_early_read_only_tables();
637 char* serialized_data = dump_read_only_tables();
638
639 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
640
641 // The vtable clones contain addresses of the current process.
642 // We don't want to write these addresses into the archive.
643 CppVtables::zero_archived_vtables();
644
645 // Write the archive file
646 const char* static_archive = CDSConfig::static_archive_path();
647 assert(static_archive != nullptr, "SharedArchiveFile not set?");
648 _map_info = new FileMapInfo(static_archive, true);
649 _map_info->populate_header(MetaspaceShared::core_region_alignment());
650 _map_info->set_early_serialized_data(early_serialized_data);
651 _map_info->set_serialized_data(serialized_data);
652 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
653 }
654
655 class CollectCLDClosure : public CLDClosure {
656 GrowableArray<ClassLoaderData*> _loaded_cld;
657 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
658 Thread* _current_thread;
659 public:
660 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
661 ~CollectCLDClosure() {
662 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
663 _loaded_cld_handles.at(i).release(Universe::vm_global());
664 }
665 }
666 void do_cld(ClassLoaderData* cld) {
667 assert(cld->is_alive(), "must be");
668 _loaded_cld.append(cld);
669 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
670 }
671
672 int nof_cld() const { return _loaded_cld.length(); }
673 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
674 };
675
676 // Check if we can eagerly link this class at dump time, so we can avoid the
677 // runtime linking overhead (especially verification)
678 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
679 if (!ik->can_be_verified_at_dumptime()) {
680 // For old classes, try to leave them in the unlinked state, so
681 // we can still store them in the archive. They must be
682 // linked/verified at runtime.
683 return false;
684 }
685 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
686 // Linking of unregistered classes at this stage may cause more
687 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
688 // that may not be expected by custom class loaders.
689 //
690 // It's OK to do this for the built-in loaders as we know they can
691 // tolerate this.
692 return false;
693 }
694 return true;
695 }
696
697 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
698 // Link the class to cause the bytecodes to be rewritten and the
699 // cpcache to be created. Class verification is done according
700 // to -Xverify setting.
701 bool res = MetaspaceShared::try_link_class(THREAD, ik);
702 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK_(false));
703 return res;
704 }
705
706 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
707 AOTClassLinker::initialize();
708
709 if (!jcmd_request) {
710 LambdaFormInvokers::regenerate_holder_classes(CHECK);
711 }
712
713 // Collect all loaded ClassLoaderData.
714 CollectCLDClosure collect_cld(THREAD);
715 {
716 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
717 // We cannot link the classes while holding this lock (or else we may run into deadlock).
718 // Therefore, we need to first collect all the CLDs, and then link their classes after
719 // releasing the lock.
720 MutexLocker lock(ClassLoaderDataGraph_lock);
721 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
722 }
723
724 while (true) {
725 bool has_linked = false;
726 for (int i = 0; i < collect_cld.nof_cld(); i++) {
727 ClassLoaderData* cld = collect_cld.cld_at(i);
728 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
729 if (klass->is_instance_klass()) {
730 InstanceKlass* ik = InstanceKlass::cast(klass);
731 if (may_be_eagerly_linked(ik)) {
732 has_linked |= link_class_for_cds(ik, CHECK);
733 }
734 }
735 }
736 }
737
738 if (!has_linked) {
739 break;
740 }
741 // Class linking includes verification which may load more classes.
742 // Keep scanning until we have linked no more classes.
743 }
744 }
745
746 void MetaspaceShared::prepare_for_dumping() {
747 assert(CDSConfig::is_dumping_archive(), "sanity");
748 CDSConfig::check_unsupported_dumping_module_options();
749 ClassLoader::initialize_shared_path(JavaThread::current());
750 }
751
752 // Preload classes from a list, populate the shared spaces and dump to a
753 // file.
754 void MetaspaceShared::preload_and_dump(TRAPS) {
755 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
756 ResourceMark rm(THREAD);
757 StaticArchiveBuilder builder;
758 preload_and_dump_impl(builder, THREAD);
759 if (HAS_PENDING_EXCEPTION) {
760 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
761 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
762 SIZE_FORMAT "M", MaxHeapSize/M);
763 MetaspaceShared::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 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
768 }
769 }
770
771 if (!CDSConfig::old_cds_flags_used()) {
772 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
773 // When the new -XX:AOTMode=create flag is used, we can't return
774 // to the JLI launcher, as the launcher will fail when trying to
775 // run the main class, which is not what we want.
776 tty->print_cr("AOTCache creation is complete: %s", AOTCache);
777 vm_exit(0);
778 }
779 }
780
781 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
782 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
783 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
784 return;
785 }
786 // CDS heap dumping requires all string oops to have an offset
787 // from the heap bottom that can be encoded in 32-bit.
788 julong max_heap_size = (julong)(4 * G);
789
790 if (MinHeapSize > max_heap_size) {
791 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);
856 }
857 }
858
859 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
860 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
861 // are archived.
862 exercise_runtime_cds_code(CHECK);
863
864 log_info(cds)("Loading classes to share: done.");
865 }
866
867 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
868 // Exercise the manifest processing code
869 const char* dummy = "Manifest-Version: 1.0\n";
870 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
871
872 // Exercise FileSystem and URL code
873 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
874 }
875
876 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
877 preload_classes(CHECK);
878
879 if (SharedArchiveConfigFile) {
880 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
881 read_extra_data(THREAD, SharedArchiveConfigFile);
882 log_info(cds)("Reading extra data: done.");
883 }
884
885 // Rewrite and link classes
886 log_info(cds)("Rewriting and linking classes ...");
887
888 // Link any classes which got missed. This would happen if we have loaded classes that
889 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
890 // fails verification, all other interfaces that were not specified in the classlist but
891 // are implemented by K are not verified.
892 link_shared_classes(false/*not from jcmd*/, CHECK);
893 log_info(cds)("Rewriting and linking classes: done");
894
895 #if INCLUDE_CDS_JAVA_HEAP
896 if (CDSConfig::is_dumping_heap()) {
897 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
898 log_info(cds)("archivedBootLayer not available, disabling full module graph");
899 CDSConfig::stop_dumping_full_module_graph();
900 }
901 HeapShared::init_for_dumping(CHECK);
902 ArchiveHeapWriter::init();
903 if (CDSConfig::is_dumping_full_module_graph()) {
904 HeapShared::reset_archived_object_states(CHECK);
905 }
906
907 if (CDSConfig::is_dumping_invokedynamic()) {
908 // This assert means that the MethodType and MethodTypeForm tables won't be
909 // updated concurrently when we are saving their contents into a side table.
910 assert(CDSConfig::allow_only_single_java_thread(), "Required");
911
912 JavaValue result(T_VOID);
913 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
914 vmSymbols::createArchivedObjects(),
915 vmSymbols::void_method_signature(),
916 CHECK);
917
918 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
919 // to null, and it will be initialized again at runtime.
920 log_debug(cds)("Resetting Class::reflectionFactory");
921 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
922 Symbol* method_sig = vmSymbols::void_method_signature();
923 JavaCalls::call_static(&result, vmClasses::Class_klass(),
924 method_name, method_sig, CHECK);
925
926 // Perhaps there is a way to avoid hard-coding these names here.
927 // See discussion in JDK-8342481.
928 }
929
930 // Do this at the very end, when no Java code will be executed. Otherwise
931 // some new strings may be added to the intern table.
932 StringTable::allocate_shared_strings_array(CHECK);
933 } else {
934 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
935 CDSConfig::stop_using_optimized_module_handling();
936 }
937 #endif
938
939 VM_PopulateDumpSharedSpace op(builder);
940 VMThread::execute(&op);
941
942 if (!write_static_archive(&builder, op.map_info(), op.heap_info())) {
943 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
944 }
945 }
946
947 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
948 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
949 // without runtime relocation.
950 builder->relocate_to_requested();
951
952 map_info->open_for_write();
953 if (!map_info->is_open()) {
954 return false;
955 }
956 builder->write_archive(map_info, heap_info);
957
958 if (AllowArchivingWithJavaAgent) {
959 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
960 "for testing purposes only and should not be used in a production environment");
961 }
962 return true;
963 }
964
965 // Returns true if the class's status has changed.
966 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
967 ExceptionMark em(current);
968 JavaThread* THREAD = current; // For exception macros.
969 assert(CDSConfig::is_dumping_archive(), "sanity");
970 if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
971 !SystemDictionaryShared::has_class_failed_verification(ik)) {
972 bool saved = BytecodeVerificationLocal;
973 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
974 // The verification decision is based on BytecodeVerificationRemote
975 // for non-system classes. Since we are using the null classloader
976 // to load non-system classes for customized class loaders during dumping,
977 // we need to temporarily change BytecodeVerificationLocal to be the same as
978 // BytecodeVerificationRemote. Note this can cause the parent system
979 // classes also being verified. The extra overhead is acceptable during
980 // dumping.
981 BytecodeVerificationLocal = BytecodeVerificationRemote;
982 }
983 ik->link_class(THREAD);
984 if (HAS_PENDING_EXCEPTION) {
985 ResourceMark rm(THREAD);
986 log_warning(cds)("Preload Warning: Verification failed for %s",
987 ik->external_name());
988 CLEAR_PENDING_EXCEPTION;
989 SystemDictionaryShared::set_class_has_failed_verification(ik);
990 } else {
991 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
992 ik->compute_has_loops_flag_for_methods();
993 }
994 BytecodeVerificationLocal = saved;
995 return true;
996 } else {
997 return false;
998 }
999 }
1000
1001 #if INCLUDE_CDS_JAVA_HEAP
1002 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1003 if(!HeapShared::can_write()) {
1004 log_info(cds)(
1005 "Archived java heap is not supported as UseG1GC "
1006 "and UseCompressedClassPointers are required."
1007 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1008 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1009 return;
1010 }
1011 // Find all the interned strings that should be dumped.
1012 int i;
1013 for (i = 0; i < klasses->length(); i++) {
1014 Klass* k = klasses->at(i);
1015 if (k->is_instance_klass()) {
1016 InstanceKlass* ik = InstanceKlass::cast(k);
1017 ik->constants()->add_dumped_interned_strings();
1018 }
1019 }
1020 if (_extra_interned_strings != nullptr) {
1021 for (i = 0; i < _extra_interned_strings->length(); i ++) {
1022 OopHandle string = _extra_interned_strings->at(i);
1023 HeapShared::add_to_dumped_interned_strings(string.resolve());
1024 }
1025 }
1026
1027 HeapShared::archive_objects(&_heap_info);
1028 ArchiveBuilder::OtherROAllocMark mark;
1069 // This function is called when the JVM is unable to write the specified CDS archive due to an
1070 // unrecoverable error.
1071 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1072 writing_error(message);
1073 vm_direct_exit(1);
1074 }
1075
1076 // This function is called when the JVM is unable to write the specified CDS archive due to a
1077 // an error. The error will be propagated
1078 void MetaspaceShared::writing_error(const char* message) {
1079 log_error(cds)("An error has occurred while writing the shared archive file.");
1080 if (message != nullptr) {
1081 log_error(cds)("%s", message);
1082 }
1083 }
1084
1085 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1086 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1087 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1088
1089 FileMapInfo* static_mapinfo = open_static_archive();
1090 FileMapInfo* dynamic_mapinfo = nullptr;
1091
1092 if (static_mapinfo != nullptr) {
1093 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1094 dynamic_mapinfo = open_dynamic_archive();
1095
1096 // First try to map at the requested address
1097 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1098 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1099 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1100 // by the OS.
1101 log_info(cds)("Try to map archive(s) at an alternative address");
1102 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1103 }
1104 }
1105
1106 if (result == MAP_ARCHIVE_SUCCESS) {
1107 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1108 char* cds_base = static_mapinfo->mapped_base();
1109 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1116 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1117 // turn AutoCreateSharedArchive off if successfully mapped
1118 AutoCreateSharedArchive = false;
1119 } else {
1120 FileMapInfo::set_shared_path_table(static_mapinfo);
1121 }
1122 } else {
1123 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1124 if (CDSConfig::is_dumping_dynamic_archive()) {
1125 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1126 }
1127 UseSharedSpaces = false;
1128 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1129 AutoCreateSharedArchive = false;
1130 CDSConfig::disable_dumping_dynamic_archive();
1131 log_info(cds)("Unable to map shared spaces");
1132 if (PrintSharedArchiveAndExit) {
1133 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1134 } else if (RequireSharedSpaces) {
1135 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1136 }
1137 }
1138
1139 // If mapping failed and -XShare:on, the vm should exit
1140 bool has_failed = false;
1141 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1142 has_failed = true;
1143 delete static_mapinfo;
1144 }
1145 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1146 has_failed = true;
1147 delete dynamic_mapinfo;
1148 }
1149 if (RequireSharedSpaces && has_failed) {
1150 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1151 }
1152 }
1153
1154 FileMapInfo* MetaspaceShared::open_static_archive() {
1155 const char* static_archive = CDSConfig::static_archive_path();
1156 assert(static_archive != nullptr, "sanity");
1157 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1158 if (!mapinfo->initialize()) {
1159 delete(mapinfo);
1160 return nullptr;
1161 }
1162 return mapinfo;
1163 }
1164
1165 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1166 if (CDSConfig::is_dumping_dynamic_archive()) {
1167 return nullptr;
1168 }
1169 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1170 if (dynamic_archive == nullptr) {
1171 return nullptr;
1172 }
1173
1174 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1175 if (!mapinfo->initialize()) {
1176 delete(mapinfo);
1177 if (RequireSharedSpaces) {
1178 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1179 }
1180 return nullptr;
1181 }
1182 return mapinfo;
1589 MemoryReserver::release(archive_space_rs);
1590 archive_space_rs = {};
1591 }
1592 if (class_space_rs.is_reserved()) {
1593 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1594 MemoryReserver::release(class_space_rs);
1595 class_space_rs = {};
1596 }
1597 }
1598 }
1599
1600 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1601 static int archive_regions_count = 2;
1602
1603 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1604 assert(CDSConfig::is_using_archive(), "must be runtime");
1605 if (mapinfo == nullptr) {
1606 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1607 }
1608
1609 mapinfo->set_is_mapped(false);
1610 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1611 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1612 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1613 return MAP_ARCHIVE_OTHER_FAILURE;
1614 }
1615
1616 MapArchiveResult result =
1617 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1618
1619 if (result != MAP_ARCHIVE_SUCCESS) {
1620 unmap_archive(mapinfo);
1621 return result;
1622 }
1623
1624 if (!mapinfo->validate_shared_path_table()) {
1625 unmap_archive(mapinfo);
1626 return MAP_ARCHIVE_OTHER_FAILURE;
1627 }
1628
1666 };
1667
1668 // Read the miscellaneous data from the shared file, and
1669 // serialize it out to its various destinations.
1670
1671 void MetaspaceShared::initialize_shared_spaces() {
1672 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1673
1674 // Verify various attributes of the archive, plus initialize the
1675 // shared string/symbol tables.
1676 char* buffer = static_mapinfo->serialized_data();
1677 intptr_t* array = (intptr_t*)buffer;
1678 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1679 serialize(&rc);
1680
1681 // Finish up archived heap initialization. These must be
1682 // done after ReadClosure.
1683 static_mapinfo->patch_heap_embedded_pointers();
1684 ArchiveHeapLoader::finish_initialization();
1685 Universe::load_archived_object_instances();
1686
1687 // Close the mapinfo file
1688 static_mapinfo->close();
1689
1690 static_mapinfo->unmap_region(MetaspaceShared::bm);
1691
1692 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1693 if (dynamic_mapinfo != nullptr) {
1694 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1695 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1696 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1697 DynamicArchive::setup_array_klasses();
1698 dynamic_mapinfo->close();
1699 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1700 }
1701
1702 LogStreamHandle(Info, cds) lsh;
1703 if (lsh.is_enabled()) {
1704 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1705 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
1716 // Read stored LF format lines stored in static archive
1717 LambdaFormInvokers::read_static_archive_invokers();
1718 }
1719
1720 if (PrintSharedArchiveAndExit) {
1721 // Print archive names
1722 if (dynamic_mapinfo != nullptr) {
1723 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1724 tty->print_cr("Base archive version %d", static_mapinfo->version());
1725 } else {
1726 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1727 tty->print_cr("Static archive version %d", static_mapinfo->version());
1728 }
1729
1730 SystemDictionaryShared::print_shared_archive(tty);
1731 if (dynamic_mapinfo != nullptr) {
1732 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1733 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1734 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1735 }
1736
1737 // collect shared symbols and strings
1738 CountSharedSymbols cl;
1739 SymbolTable::shared_symbols_do(&cl);
1740 tty->print_cr("Number of shared symbols: %d", cl.total());
1741 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1742 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1743 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1744 tty->print_cr("archive is invalid");
1745 vm_exit(1);
1746 } else {
1747 tty->print_cr("archive is valid");
1748 vm_exit(0);
1749 }
1750 }
1751 }
1752
1753 // JVM/TI RedefineClasses() support:
1754 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1755 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/aotClassInitializer.hpp"
27 #include "cds/aotClassLinker.hpp"
28 #include "cds/aotConstantPoolResolver.hpp"
29 #include "cds/aotLinkedClassBulkLoader.hpp"
30 #include "cds/archiveBuilder.hpp"
31 #include "cds/archiveHeapLoader.hpp"
32 #include "cds/archiveHeapWriter.hpp"
33 #include "cds/cds_globals.hpp"
34 #include "cds/cdsAccess.hpp"
35 #include "cds/cdsConfig.hpp"
36 #include "cds/cdsProtectionDomain.hpp"
37 #include "cds/classListParser.hpp"
38 #include "cds/classListWriter.hpp"
39 #include "cds/cppVtables.hpp"
40 #include "cds/dumpAllocStats.hpp"
41 #include "cds/dynamicArchive.hpp"
42 #include "cds/filemap.hpp"
43 #include "cds/finalImageRecipes.hpp"
44 #include "cds/heapShared.hpp"
45 #include "cds/lambdaFormInvokers.hpp"
46 #include "cds/metaspaceShared.hpp"
47 #include "classfile/classLoaderDataGraph.hpp"
48 #include "classfile/classLoaderDataShared.hpp"
49 #include "classfile/classLoaderExt.hpp"
50 #include "classfile/javaClasses.inline.hpp"
51 #include "classfile/loaderConstraints.hpp"
52 #include "classfile/modules.hpp"
53 #include "classfile/placeholders.hpp"
54 #include "classfile/stringTable.hpp"
55 #include "classfile/symbolTable.hpp"
56 #include "classfile/systemDictionary.hpp"
57 #include "classfile/systemDictionaryShared.hpp"
58 #include "classfile/vmClasses.hpp"
59 #include "classfile/vmSymbols.hpp"
60 #include "code/codeCache.hpp"
61 #include "code/SCCache.hpp"
62 #include "compiler/compileBroker.hpp"
63 #include "compiler/precompiler.hpp"
64 #include "gc/shared/gcVMOperations.hpp"
65 #include "interpreter/bytecodeStream.hpp"
66 #include "interpreter/bytecodes.hpp"
67 #include "jvm_io.h"
68 #include "logging/log.hpp"
69 #include "logging/logMessage.hpp"
70 #include "logging/logStream.hpp"
71 #include "memory/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 //
257 err = "invalid for this platform";
258 } else {
259 return aligned_base;
260 }
261
262 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
263 p2i((void*)SharedBaseAddress), err,
264 p2i((void*)Arguments::default_SharedBaseAddress()));
265
266 specified_base = (char*)Arguments::default_SharedBaseAddress();
267 aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
268
269 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
270 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
271 assert(shared_base_valid(aligned_base), "Sanity");
272 return aligned_base;
273 }
274
275 void MetaspaceShared::initialize_for_static_dump() {
276 assert(CDSConfig::is_dumping_static_archive(), "sanity");
277
278 if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
279 if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
280 vm_exit_during_initialization("Cannot create the CacheDataStore",
281 "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, Serial, Epsilon, or Shenandoah");
282 }
283 }
284
285 log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
286 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
287 // to avoid address space wrap around.
288 size_t cds_max;
289 const size_t reserve_alignment = core_region_alignment();
290
291 #ifdef _LP64
292 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
293 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
294 #else
295 // We don't support archives larger than 256MB on 32-bit due to limited
296 // virtual address space.
297 cds_max = align_down(256*M, reserve_alignment);
298 #endif
299
300 _requested_base_address = compute_shared_base(cds_max);
301 SharedBaseAddress = (size_t)_requested_base_address;
302
303 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
304 _symbol_rs = MemoryReserver::reserve(symbol_rs_size, mtClassShared);
464 // Need to do this first, as subsequent steps may call virtual functions
465 // in archived Metadata objects.
466 CppVtables::serialize(soc);
467 soc->do_tag(--tag);
468
469 // Dump/restore miscellaneous metadata.
470 JavaClasses::serialize_offsets(soc);
471 Universe::serialize(soc);
472 soc->do_tag(--tag);
473
474 // Dump/restore references to commonly used names and signatures.
475 vmSymbols::serialize(soc);
476 soc->do_tag(--tag);
477
478 // Dump/restore the symbol/string/subgraph_info tables
479 SymbolTable::serialize_shared_table_header(soc);
480 StringTable::serialize_shared_table_header(soc);
481 HeapShared::serialize_tables(soc);
482 SystemDictionaryShared::serialize_dictionary_headers(soc);
483 AOTLinkedClassBulkLoader::serialize(soc, true);
484 FinalImageRecipes::serialize(soc, true);
485 TrainingData::serialize_training_data(soc);
486 InstanceMirrorKlass::serialize_offsets(soc);
487
488 // Dump/restore well known classes (pointers)
489 SystemDictionaryShared::serialize_vm_classes(soc);
490 soc->do_tag(--tag);
491
492 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
493 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
494
495 LambdaFormInvokers::serialize(soc);
496 soc->do_tag(666);
497 }
498
499 static void rewrite_nofast_bytecode(const methodHandle& method) {
500 BytecodeStream bcs(method);
501 while (!bcs.is_last_bytecode()) {
502 Bytecodes::Code opcode = bcs.next();
503 switch (opcode) {
504 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
505 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
550 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
551
552 bool skip_operation() const { return false; }
553
554 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
555 ArchiveHeapInfo* heap_info() { return &_heap_info; }
556 FileMapInfo* map_info() const { return _map_info; }
557 void doit(); // outline because gdb sucks
558 bool allow_nested_vm_operations() const { return true; }
559 }; // class VM_PopulateDumpSharedSpace
560
561 class StaticArchiveBuilder : public ArchiveBuilder {
562 public:
563 StaticArchiveBuilder() : ArchiveBuilder() {}
564
565 virtual void iterate_roots(MetaspaceClosure* it) {
566 FileMapInfo::metaspace_pointers_do(it);
567 SystemDictionaryShared::dumptime_classes_do(it);
568 Universe::metaspace_pointers_do(it);
569 vmSymbols::metaspace_pointers_do(it);
570 TrainingData::iterate_roots(it);
571
572 // The above code should find all the symbols that are referenced by the
573 // archived classes. We just need to add the extra symbols which
574 // may not be used by any of the archived classes -- these are usually
575 // symbols that we anticipate to be used at run time, so we can store
576 // them in the RO region, to be shared across multiple processes.
577 if (_extra_symbols != nullptr) {
578 for (int i = 0; i < _extra_symbols->length(); i++) {
579 it->push(_extra_symbols->adr_at(i));
580 }
581 }
582
583 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
584 it->push(_pending_method_handle_intrinsics->adr_at(i));
585 }
586 }
587 };
588
589 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
590 ArchiveBuilder::OtherROAllocMark mark;
591
592 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
593
594 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
595 char* start = ro_region->top();
596 WriteClosure wc(ro_region);
597 MetaspaceShared::early_serialize(&wc);
598 return start;
599 }
600
601 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
602 ArchiveBuilder::OtherROAllocMark mark;
603
604 SystemDictionaryShared::write_to_archive();
605 AOTClassLinker::write_to_archive();
606 if (CDSConfig::is_dumping_preimage_static_archive()) {
607 FinalImageRecipes::record_recipes();
608 }
609 AOTLinkedClassBulkLoader::record_unregistered_classes();
610 TrainingData::dump_training_data();
611 MetaspaceShared::write_method_handle_intrinsics();
612
613 // Write lambform lines into archive
614 LambdaFormInvokers::dump_static_archive_invokers();
615
616 // Write the other data to the output array.
617 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
618 char* start = ro_region->top();
619 WriteClosure wc(ro_region);
620 MetaspaceShared::serialize(&wc);
621
622 return start;
623 }
624
625 void VM_PopulateDumpSharedSpace::doit() {
626 //guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
627
628 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
629
630 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
631 if (CDSConfig::is_dumping_aot_linked_classes()) {
632 // When dumping AOT-linked classes, some classes may have direct references to a method handle
633 // intrinsic. The easiest thing is to save all of them into the AOT cache.
634 SystemDictionary::get_all_method_handle_intrinsics(_pending_method_handle_intrinsics);
635 }
636
637 FileMapInfo::check_nonempty_dir_in_shared_path_table();
638
639 NOT_PRODUCT(SystemDictionary::verify();)
640
641 // Block concurrent class unloading from changing the _dumptime_table
642 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
643 SystemDictionaryShared::find_all_archivable_classes();
644
645 _builder.gather_source_objs();
646 _builder.reserve_buffer();
647
648 CppVtables::dumptime_init(&_builder);
649
650 _builder.sort_metadata_objs();
651 _builder.dump_rw_metadata();
652 _builder.dump_ro_metadata();
653 _builder.relocate_metaspaceobj_embedded_pointers();
654
655 dump_java_heap_objects(_builder.klasses());
656 dump_shared_symbol_table(_builder.symbols());
657
658 log_info(cds)("Make classes shareable");
659 _builder.make_klasses_shareable();
660 MetaspaceShared::make_method_handle_intrinsics_shareable();
661
662 char* early_serialized_data = dump_early_read_only_tables();
663 char* serialized_data = dump_read_only_tables();
664
665 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
666
667 log_info(cds)("Make training data shareable");
668 _builder.make_training_data_shareable();
669
670 // The vtable clones contain addresses of the current process.
671 // We don't want to write these addresses into the archive.
672 CppVtables::zero_archived_vtables();
673
674 // Write the archive file
675 const char* static_archive;
676 if (CDSConfig::is_dumping_final_static_archive()) {
677 static_archive = CacheDataStore;
678 assert(FileMapInfo::current_info() != nullptr, "sanity");
679 delete FileMapInfo::current_info();
680 } else {
681 static_archive = CDSConfig::static_archive_path();
682 }
683 assert(static_archive != nullptr, "SharedArchiveFile not set?");
684 _map_info = new FileMapInfo(static_archive, true);
685 _map_info->populate_header(MetaspaceShared::core_region_alignment());
686 _map_info->set_early_serialized_data(early_serialized_data);
687 _map_info->set_serialized_data(serialized_data);
688 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
689 }
690
691 class CollectCLDClosure : public CLDClosure {
692 GrowableArray<ClassLoaderData*> _loaded_cld;
693 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
694 Thread* _current_thread;
695 public:
696 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
697 ~CollectCLDClosure() {
698 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
699 _loaded_cld_handles.at(i).release(Universe::vm_global());
700 }
701 }
702 void do_cld(ClassLoaderData* cld) {
703 assert(cld->is_alive(), "must be");
704 _loaded_cld.append(cld);
705 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
706 }
707
708 int nof_cld() const { return _loaded_cld.length(); }
709 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
710 };
711
712 // Check if we can eagerly link this class at dump time, so we can avoid the
713 // runtime linking overhead (especially verification)
714 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
715 if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
716 assert(ik->can_be_verified_at_dumptime(), "sanity");
717 }
718 if (!ik->can_be_verified_at_dumptime()) {
719 // For old classes, try to leave them in the unlinked state, so
720 // we can still store them in the archive. They must be
721 // linked/verified at runtime.
722 return false;
723 }
724
725 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
726 // Linking of unregistered classes at this stage may cause more
727 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
728 // that may not be expected by custom class loaders.
729 //
730 // It's OK to do this for the built-in loaders as we know they can
731 // tolerate this.
732 return false;
733 }
734 return true;
735 }
736
737
738 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
739 AOTClassLinker::initialize();
740
741 if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
742 && !CDSConfig::is_dumping_preimage_static_archive()
743 && !CDSConfig::is_dumping_final_static_archive()) {
744 // If we have regenerated invoker classes in the dynamic archive,
745 // they will conflict with the resolved CONSTANT_Klass references that are stored
746 // in the static archive. This is not easy to handle. Let's disable
747 // it for dynamic archive for now.
748 LambdaFormInvokers::regenerate_holder_classes(CHECK);
749 }
750
751 // Collect all loaded ClassLoaderData.
752 CollectCLDClosure collect_cld(THREAD);
753 {
754 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
755 // We cannot link the classes while holding this lock (or else we may run into deadlock).
756 // Therefore, we need to first collect all the CLDs, and then link their classes after
757 // releasing the lock.
758 MutexLocker lock(ClassLoaderDataGraph_lock);
759 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
760 }
761
762 while (true) {
763 bool has_linked = false;
764 for (int i = 0; i < collect_cld.nof_cld(); i++) {
765 ClassLoaderData* cld = collect_cld.cld_at(i);
766 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
767 if (klass->is_instance_klass()) {
768 InstanceKlass* ik = InstanceKlass::cast(klass);
769 if (may_be_eagerly_linked(ik)) {
770 has_linked |= try_link_class(THREAD, ik);
771 }
772 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
773 AOTClassInitializer::maybe_preinit_class(ik, CHECK);
774 }
775 }
776 }
777 }
778
779 if (!has_linked) {
780 break;
781 }
782 // Class linking includes verification which may load more classes.
783 // Keep scanning until we have linked no more classes.
784 }
785
786 // Resolve constant pool entries -- we don't load any new classes during this stage
787 for (int i = 0; i < collect_cld.nof_cld(); i++) {
788 ClassLoaderData* cld = collect_cld.cld_at(i);
789 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
790 if (klass->is_instance_klass()) {
791 InstanceKlass* ik = InstanceKlass::cast(klass);
792 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
793 if (CDSConfig::is_dumping_preimage_static_archive()) {
794 FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
795 }
796 }
797 }
798 }
799
800 if (CDSConfig::is_dumping_preimage_static_archive()) {
801 // Do this after all classes are verified by the above loop.
802 // Any classes loaded from here on will be automatically excluded, so
803 // there's no need to force verification or resolve CP entries.
804 RecordTraining = false;
805 SystemDictionaryShared::ignore_new_classes();
806 LambdaFormInvokers::regenerate_holder_classes(CHECK);
807 RecordTraining = true;
808 }
809
810 if (CDSConfig::is_dumping_final_static_archive()) {
811 FinalImageRecipes::apply_recipes(CHECK);
812 }
813 }
814
815 void MetaspaceShared::prepare_for_dumping() {
816 assert(CDSConfig::is_dumping_archive(), "sanity");
817 CDSConfig::check_unsupported_dumping_module_options();
818 ClassLoader::initialize_shared_path(JavaThread::current());
819 }
820
821 // Preload classes from a list, populate the shared spaces and dump to a
822 // file.
823 void MetaspaceShared::preload_and_dump(TRAPS) {
824 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
825 ResourceMark rm(THREAD);
826 HandleMark hm(THREAD);
827
828 if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
829 tty->print_cr("==================== archived_training_data ** before dumping ====================");
830 TrainingData::print_archived_training_data_on(tty);
831 }
832
833 StaticArchiveBuilder builder;
834 preload_and_dump_impl(builder, THREAD);
835 if (HAS_PENDING_EXCEPTION) {
836 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
837 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
838 SIZE_FORMAT "M", MaxHeapSize/M);
839 MetaspaceShared::writing_error();
840 } else {
841 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
842 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
843 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
844 }
845 }
846
847 if (!CDSConfig::old_cds_flags_used() && !CDSConfig::is_dumping_preimage_static_archive() && !CDSConfig::is_dumping_final_static_archive()) {
848 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
849 // When the new -XX:AOTMode=create flag is used, we can't return
850 // to the JLI launcher, as the launcher will fail when trying to
851 // run the main class, which is not what we want.
852 tty->print_cr("AOTCache creation is complete: %s", AOTCache);
853 vm_exit(0);
854 }
855 }
856
857 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
858 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
859 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
860 return;
861 }
862 // CDS heap dumping requires all string oops to have an offset
863 // from the heap bottom that can be encoded in 32-bit.
864 julong max_heap_size = (julong)(4 * G);
865
866 if (MinHeapSize > max_heap_size) {
867 log_debug(cds)("Setting MinHeapSize to 4G for CDS dumping, original size = " SIZE_FORMAT "M", MinHeapSize/M);
932 }
933 }
934
935 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
936 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
937 // are archived.
938 exercise_runtime_cds_code(CHECK);
939
940 log_info(cds)("Loading classes to share: done.");
941 }
942
943 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
944 // Exercise the manifest processing code
945 const char* dummy = "Manifest-Version: 1.0\n";
946 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
947
948 // Exercise FileSystem and URL code
949 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
950 }
951
952 bool MetaspaceShared::is_recording_preimage_static_archive() {
953 if (CDSConfig::is_dumping_preimage_static_archive()) {
954 return _preimage_static_archive_dumped == 0;
955 }
956 return false;
957 }
958
959 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
960 if (CDSConfig::is_dumping_preimage_static_archive()) {
961 if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
962 return;
963 }
964 }
965
966 if (CDSConfig::is_dumping_classic_static_archive()) {
967 // We are running with -Xshare:dump
968 preload_classes(CHECK);
969
970 if (SharedArchiveConfigFile) {
971 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
972 read_extra_data(THREAD, SharedArchiveConfigFile);
973 log_info(cds)("Reading extra data: done.");
974 }
975 }
976
977 if (CDSConfig::is_dumping_preimage_static_archive()) {
978 log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
979 char default_classlist[JVM_MAXPATHLEN];
980 get_default_classlist(default_classlist, sizeof(default_classlist));
981 struct stat statbuf;
982 if (os::stat(default_classlist, &statbuf) == 0) {
983 ClassListParser::parse_classlist(default_classlist,
984 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
985 }
986 }
987
988 // Rewrite and link classes
989 log_info(cds)("Rewriting and linking classes ...");
990
991 // Link any classes which got missed. This would happen if we have loaded classes that
992 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
993 // fails verification, all other interfaces that were not specified in the classlist but
994 // are implemented by K are not verified.
995 link_shared_classes(false/*not from jcmd*/, CHECK);
996 log_info(cds)("Rewriting and linking classes: done");
997
998 if (CDSConfig::is_dumping_final_static_archive()) {
999 assert(RecordTraining == false, "must be");
1000 RecordTraining = true;
1001 }
1002
1003 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1004
1005 #if INCLUDE_CDS_JAVA_HEAP
1006 if (CDSConfig::is_dumping_heap()) {
1007 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
1008 log_info(cds)("archivedBootLayer not available, disabling full module graph");
1009 CDSConfig::stop_dumping_full_module_graph();
1010 }
1011 HeapShared::init_for_dumping(CHECK);
1012 ArchiveHeapWriter::init();
1013 if (CDSConfig::is_dumping_full_module_graph()) {
1014 HeapShared::reset_archived_object_states(CHECK);
1015 }
1016
1017 if (ArchiveLoaderLookupCache) {
1018 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1019 }
1020
1021 if (CDSConfig::is_dumping_invokedynamic()) {
1022 // This assert means that the MethodType and MethodTypeForm tables won't be
1023 // updated concurrently when we are saving their contents into a side table.
1024 assert(CDSConfig::allow_only_single_java_thread(), "Required");
1025
1026 JavaValue result(T_VOID);
1027 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
1028 vmSymbols::createArchivedObjects(),
1029 vmSymbols::void_method_signature(),
1030 CHECK);
1031
1032 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1033 // to null, and it will be initialized again at runtime.
1034 log_debug(cds)("Resetting Class::reflectionFactory");
1035 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1036 Symbol* method_sig = vmSymbols::void_method_signature();
1037 JavaCalls::call_static(&result, vmClasses::Class_klass(),
1038 method_name, method_sig, CHECK);
1039
1040 // Perhaps there is a way to avoid hard-coding these names here.
1041 // See discussion in JDK-8342481.
1042 }
1043
1044 // Do this at the very end, when no Java code will be executed. Otherwise
1045 // some new strings may be added to the intern table.
1046 StringTable::allocate_shared_strings_array(CHECK);
1047 } else {
1048 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1049 CDSConfig::stop_using_optimized_module_handling();
1050 }
1051 #endif
1052
1053 VM_PopulateDumpSharedSpace op(builder);
1054 VMThread::execute(&op);
1055 FileMapInfo* mapinfo = op.map_info();
1056 ArchiveHeapInfo* heap_info = op.heap_info();
1057 bool status;
1058 if (CDSConfig::is_dumping_preimage_static_archive()) {
1059 if ((status = write_static_archive(&builder, mapinfo, heap_info))) {
1060 fork_and_dump_final_static_archive();
1061 }
1062 } else if (CDSConfig::is_dumping_final_static_archive()) {
1063 RecordTraining = false;
1064 if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
1065 if (log_is_enabled(Info, cds, jit)) {
1066 CDSAccess::test_heap_access_api();
1067 }
1068
1069 // We have just created the final image. Let's run the AOT compiler
1070 if (PrintTrainingInfo) {
1071 tty->print_cr("==================== archived_training_data ** after dumping ====================");
1072 TrainingData::print_archived_training_data_on(tty);
1073 }
1074
1075 CDSConfig::enable_dumping_cached_code();
1076 {
1077 builder.start_cc_region();
1078 Precompiler::compile_cached_code(&builder, CHECK);
1079 builder.end_cc_region();
1080 }
1081 CDSConfig::disable_dumping_cached_code();
1082
1083 SCCache::close(); // Write final data and close archive
1084 }
1085 status = write_static_archive(&builder, mapinfo, heap_info);
1086 } else {
1087 status = write_static_archive(&builder, mapinfo, heap_info);
1088 }
1089
1090 if (!status) {
1091 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1092 }
1093 }
1094
1095 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1096 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1097 // without runtime relocation.
1098 builder->relocate_to_requested();
1099
1100 map_info->open_for_write();
1101 if (!map_info->is_open()) {
1102 return false;
1103 }
1104 builder->write_archive(map_info, heap_info);
1105
1106 if (AllowArchivingWithJavaAgent) {
1107 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1108 "for testing purposes only and should not be used in a production environment");
1109 }
1110 return true;
1111 }
1112
1113 static void print_java_launcher(outputStream* st) {
1114 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1115 }
1116
1117 static void print_vm_arguments(outputStream* st) {
1118 const char* cp = Arguments::get_appclasspath();
1119 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1120 st->print(" -cp "); st->print_raw(cp);
1121 }
1122 for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1123 st->print(" %s", Arguments::jvm_flags_array()[i]);
1124 }
1125 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1126 st->print(" %s", Arguments::jvm_args_array()[i]);
1127 }
1128 }
1129
1130 void MetaspaceShared::fork_and_dump_final_static_archive() {
1131 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1132
1133 ResourceMark rm;
1134 stringStream ss;
1135 print_java_launcher(&ss);
1136 print_vm_arguments(&ss);
1137 ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1138
1139 const char* cmd = ss.freeze();
1140 if (CDSManualFinalImage) {
1141 tty->print_cr("-XX:+CDSManualFinalImage is specified");
1142 tty->print_cr("Please manually execute the following command to create the final CDS image:");
1143 tty->print(" "); tty->print_raw_cr(cmd);
1144
1145 // The following is useful if the dumping was trigger by a script that builds
1146 // a complex command-line.
1147 tty->print_cr("Note: to recreate the preimage only:");
1148 tty->print_cr(" rm -f %s", CacheDataStore);
1149 tty->print(" ");
1150 print_java_launcher(tty);
1151 print_vm_arguments(tty);
1152 if (Arguments::java_command() != nullptr) {
1153 tty->print(" %s", Arguments::java_command());
1154 }
1155 tty->cr();
1156 } else {
1157 // FIXME: space characters are not properly quoated. E.g.,
1158 // java -Dfoo='a b c' HelloWorld
1159 log_info(cds)("Launching child process to create final CDS image:");
1160 log_info(cds)(" %s", cmd);
1161 int status = os::fork_and_exec(cmd);
1162 if (status != 0) {
1163 log_error(cds)("Child process finished; status = %d", status);
1164 log_error(cds)("To reproduce the error");
1165 ResourceMark rm;
1166 LogStream ls(Log(cds)::error());
1167 ls.print(" "); ls.print_raw_cr(cmd);
1168
1169 // The following is useful if the dumping was trigger by a script that builds
1170 // a complex command-line.
1171 ls.print_cr("Note: to recreate the preimage only:");
1172 ls.print_cr(" rm -f %s", CacheDataStore);
1173 ls.print(" ");
1174 print_java_launcher(&ls);
1175 print_vm_arguments(&ls);
1176 ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1177 if (Arguments::java_command() != nullptr) {
1178 ls.print(" %s", Arguments::java_command());
1179 }
1180 ls.cr();
1181
1182 vm_direct_exit(status);
1183 } else {
1184 log_info(cds)("Child process finished; status = %d", status);
1185 // On Windows, need WRITE permission to remove the file.
1186 WINDOWS_ONLY(chmod(SharedArchiveFile, _S_IREAD | _S_IWRITE));
1187 status = remove(SharedArchiveFile);
1188 if (status != 0) {
1189 log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1190 } else {
1191 log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1192 }
1193 }
1194 }
1195 }
1196
1197 // Returns true if the class's status has changed.
1198 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1199 ExceptionMark em(current);
1200 JavaThread* THREAD = current; // For exception macros.
1201 assert(CDSConfig::is_dumping_archive(), "sanity");
1202
1203 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1204 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1205 return false;
1206 }
1207
1208 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1209 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1210 bool saved = BytecodeVerificationLocal;
1211 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1212 // The verification decision is based on BytecodeVerificationRemote
1213 // for non-system classes. Since we are using the null classloader
1214 // to load non-system classes for customized class loaders during dumping,
1215 // we need to temporarily change BytecodeVerificationLocal to be the same as
1216 // BytecodeVerificationRemote. Note this can cause the parent system
1217 // classes also being verified. The extra overhead is acceptable during
1218 // dumping.
1219 BytecodeVerificationLocal = BytecodeVerificationRemote;
1220 }
1221 ik->link_class(THREAD);
1222 if (HAS_PENDING_EXCEPTION) {
1223 ResourceMark rm(THREAD);
1224 log_warning(cds)("Preload Warning: Verification failed for %s",
1225 ik->external_name());
1226 CLEAR_PENDING_EXCEPTION;
1227 SystemDictionaryShared::set_class_has_failed_verification(ik);
1228 } else {
1229 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1230 ik->compute_has_loops_flag_for_methods();
1231 }
1232 BytecodeVerificationLocal = saved;
1233 return true;
1234 } else {
1235 return false;
1236 }
1237 }
1238
1239 #if INCLUDE_CDS_JAVA_HEAP
1240 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1241 if(!HeapShared::can_write()) {
1242 if (!CDSConfig::is_dumping_preimage_static_archive()) {
1243 log_info(cds)(
1244 "Archived java heap is not supported as UseG1GC "
1245 "and UseCompressedClassPointers are required."
1246 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1247 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1248 }
1249 return;
1250 }
1251 // Find all the interned strings that should be dumped.
1252 int i;
1253 for (i = 0; i < klasses->length(); i++) {
1254 Klass* k = klasses->at(i);
1255 if (k->is_instance_klass()) {
1256 InstanceKlass* ik = InstanceKlass::cast(k);
1257 ik->constants()->add_dumped_interned_strings();
1258 }
1259 }
1260 if (_extra_interned_strings != nullptr) {
1261 for (i = 0; i < _extra_interned_strings->length(); i ++) {
1262 OopHandle string = _extra_interned_strings->at(i);
1263 HeapShared::add_to_dumped_interned_strings(string.resolve());
1264 }
1265 }
1266
1267 HeapShared::archive_objects(&_heap_info);
1268 ArchiveBuilder::OtherROAllocMark mark;
1309 // This function is called when the JVM is unable to write the specified CDS archive due to an
1310 // unrecoverable error.
1311 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1312 writing_error(message);
1313 vm_direct_exit(1);
1314 }
1315
1316 // This function is called when the JVM is unable to write the specified CDS archive due to a
1317 // an error. The error will be propagated
1318 void MetaspaceShared::writing_error(const char* message) {
1319 log_error(cds)("An error has occurred while writing the shared archive file.");
1320 if (message != nullptr) {
1321 log_error(cds)("%s", message);
1322 }
1323 }
1324
1325 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1326 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1327 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1328
1329 FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1330 FileMapInfo* dynamic_mapinfo = nullptr;
1331
1332 if (static_mapinfo != nullptr) {
1333 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1334 dynamic_mapinfo = open_dynamic_archive();
1335
1336 // First try to map at the requested address
1337 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1338 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1339 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1340 // by the OS.
1341 log_info(cds)("Try to map archive(s) at an alternative address");
1342 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1343 }
1344 }
1345
1346 if (result == MAP_ARCHIVE_SUCCESS) {
1347 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1348 char* cds_base = static_mapinfo->mapped_base();
1349 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1356 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1357 // turn AutoCreateSharedArchive off if successfully mapped
1358 AutoCreateSharedArchive = false;
1359 } else {
1360 FileMapInfo::set_shared_path_table(static_mapinfo);
1361 }
1362 } else {
1363 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1364 if (CDSConfig::is_dumping_dynamic_archive()) {
1365 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1366 }
1367 UseSharedSpaces = false;
1368 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1369 AutoCreateSharedArchive = false;
1370 CDSConfig::disable_dumping_dynamic_archive();
1371 log_info(cds)("Unable to map shared spaces");
1372 if (PrintSharedArchiveAndExit) {
1373 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1374 } else if (RequireSharedSpaces) {
1375 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1376 } else if (CDSConfig::is_dumping_final_static_archive()) {
1377 assert(CDSPreimage != nullptr, "must be");
1378 log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1379 MetaspaceShared::unrecoverable_loading_error();
1380 }
1381 }
1382
1383 // If mapping failed and -XShare:on, the vm should exit
1384 bool has_failed = false;
1385 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1386 has_failed = true;
1387 delete static_mapinfo;
1388 }
1389 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1390 has_failed = true;
1391 delete dynamic_mapinfo;
1392 }
1393 if (RequireSharedSpaces && has_failed) {
1394 // static archive mapped but dynamic archive failed
1395 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1396 }
1397 }
1398
1399 // This is called very early at VM start up to get the size of the cached_code region, which
1400 // is used in CodeCache::initialize_heaps()
1401 void MetaspaceShared::open_static_archive() {
1402 if (!UseSharedSpaces) {
1403 return;
1404 }
1405 const char* static_archive = CDSConfig::static_archive_path();
1406 assert(static_archive != nullptr, "sanity");
1407 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1408 if (!mapinfo->initialize()) {
1409 delete(mapinfo);
1410 } else {
1411 FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1412 CDSAccess::set_cached_code_size(r->used_aligned());
1413 }
1414 }
1415
1416 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1417 if (CDSConfig::is_dumping_dynamic_archive()) {
1418 return nullptr;
1419 }
1420 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1421 if (dynamic_archive == nullptr) {
1422 return nullptr;
1423 }
1424
1425 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1426 if (!mapinfo->initialize()) {
1427 delete(mapinfo);
1428 if (RequireSharedSpaces) {
1429 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1430 }
1431 return nullptr;
1432 }
1433 return mapinfo;
1840 MemoryReserver::release(archive_space_rs);
1841 archive_space_rs = {};
1842 }
1843 if (class_space_rs.is_reserved()) {
1844 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1845 MemoryReserver::release(class_space_rs);
1846 class_space_rs = {};
1847 }
1848 }
1849 }
1850
1851 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1852 static int archive_regions_count = 2;
1853
1854 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1855 assert(CDSConfig::is_using_archive(), "must be runtime");
1856 if (mapinfo == nullptr) {
1857 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1858 }
1859
1860 if (!mapinfo->validate_aot_class_linking()) {
1861 return MAP_ARCHIVE_OTHER_FAILURE;
1862 }
1863
1864 mapinfo->set_is_mapped(false);
1865 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1866 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1867 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1868 return MAP_ARCHIVE_OTHER_FAILURE;
1869 }
1870
1871 MapArchiveResult result =
1872 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1873
1874 if (result != MAP_ARCHIVE_SUCCESS) {
1875 unmap_archive(mapinfo);
1876 return result;
1877 }
1878
1879 if (!mapinfo->validate_shared_path_table()) {
1880 unmap_archive(mapinfo);
1881 return MAP_ARCHIVE_OTHER_FAILURE;
1882 }
1883
1921 };
1922
1923 // Read the miscellaneous data from the shared file, and
1924 // serialize it out to its various destinations.
1925
1926 void MetaspaceShared::initialize_shared_spaces() {
1927 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1928
1929 // Verify various attributes of the archive, plus initialize the
1930 // shared string/symbol tables.
1931 char* buffer = static_mapinfo->serialized_data();
1932 intptr_t* array = (intptr_t*)buffer;
1933 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1934 serialize(&rc);
1935
1936 // Finish up archived heap initialization. These must be
1937 // done after ReadClosure.
1938 static_mapinfo->patch_heap_embedded_pointers();
1939 ArchiveHeapLoader::finish_initialization();
1940 Universe::load_archived_object_instances();
1941 SCCache::new_workflow_load_cache();
1942
1943 // Close the mapinfo file
1944 static_mapinfo->close();
1945
1946 static_mapinfo->unmap_region(MetaspaceShared::bm);
1947
1948 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1949 if (dynamic_mapinfo != nullptr) {
1950 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1951 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1952 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1953 DynamicArchive::setup_array_klasses();
1954 dynamic_mapinfo->close();
1955 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1956 }
1957
1958 LogStreamHandle(Info, cds) lsh;
1959 if (lsh.is_enabled()) {
1960 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1961 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
1972 // Read stored LF format lines stored in static archive
1973 LambdaFormInvokers::read_static_archive_invokers();
1974 }
1975
1976 if (PrintSharedArchiveAndExit) {
1977 // Print archive names
1978 if (dynamic_mapinfo != nullptr) {
1979 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1980 tty->print_cr("Base archive version %d", static_mapinfo->version());
1981 } else {
1982 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1983 tty->print_cr("Static archive version %d", static_mapinfo->version());
1984 }
1985
1986 SystemDictionaryShared::print_shared_archive(tty);
1987 if (dynamic_mapinfo != nullptr) {
1988 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1989 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1990 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1991 }
1992 TrainingData::print_archived_training_data_on(tty);
1993
1994 if (LoadCachedCode) {
1995 tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
1996 SCCache::print_on(tty);
1997 }
1998
1999 // collect shared symbols and strings
2000 CountSharedSymbols cl;
2001 SymbolTable::shared_symbols_do(&cl);
2002 tty->print_cr("Number of shared symbols: %d", cl.total());
2003 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2004 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2005 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2006 tty->print_cr("archive is invalid");
2007 vm_exit(1);
2008 } else {
2009 tty->print_cr("archive is valid");
2010 vm_exit(0);
2011 }
2012 }
2013 }
2014
2015 // JVM/TI RedefineClasses() support:
2016 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2017 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|