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/aotClassInitializer.hpp"
27 #include "cds/aotClassLinker.hpp"
28 #include "cds/aotClassLocation.hpp"
29 #include "cds/aotConstantPoolResolver.hpp"
30 #include "cds/aotLinkedClassBulkLoader.hpp"
31 #include "cds/archiveBuilder.hpp"
32 #include "cds/archiveHeapLoader.hpp"
33 #include "cds/archiveHeapWriter.hpp"
34 #include "cds/cds_globals.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/lambdaProxyClassDictionary.hpp"
47 #include "cds/metaspaceShared.hpp"
48 #include "classfile/classLoaderDataGraph.hpp"
49 #include "classfile/classLoaderDataShared.hpp"
50 #include "classfile/classLoaderExt.hpp"
51 #include "classfile/javaClasses.inline.hpp"
52 #include "classfile/loaderConstraints.hpp"
53 #include "classfile/modules.hpp"
54 #include "classfile/placeholders.hpp"
55 #include "classfile/stringTable.hpp"
56 #include "classfile/symbolTable.hpp"
57 #include "classfile/systemDictionary.hpp"
58 #include "classfile/systemDictionaryShared.hpp"
59 #include "classfile/vmClasses.hpp"
60 #include "classfile/vmSymbols.hpp"
61 #include "code/codeCache.hpp"
62 #include "gc/shared/gcVMOperations.hpp"
63 #include "interpreter/bytecodeStream.hpp"
64 #include "interpreter/bytecodes.hpp"
65 #include "jvm_io.h"
66 #include "logging/log.hpp"
67 #include "logging/logMessage.hpp"
68 #include "logging/logStream.hpp"
69 #include "memory/memoryReserver.hpp"
70 #include "memory/metaspace.hpp"
71 #include "memory/metaspaceClosure.hpp"
72 #include "memory/resourceArea.hpp"
73 #include "memory/universe.hpp"
74 #include "nmt/memTracker.hpp"
75 #include "oops/compressedKlass.hpp"
76 #include "oops/instanceMirrorKlass.hpp"
77 #include "oops/klass.inline.hpp"
78 #include "oops/objArrayOop.hpp"
79 #include "oops/oop.inline.hpp"
80 #include "oops/oopHandle.hpp"
81 #include "prims/jvmtiExport.hpp"
82 #include "runtime/arguments.hpp"
83 #include "runtime/globals.hpp"
84 #include "runtime/globals_extension.hpp"
85 #include "runtime/handles.inline.hpp"
86 #include "runtime/javaCalls.hpp"
87 #include "runtime/os.inline.hpp"
88 #include "runtime/safepointVerifiers.hpp"
89 #include "runtime/sharedRuntime.hpp"
90 #include "runtime/vmOperations.hpp"
91 #include "runtime/vmThread.hpp"
92 #include "sanitizers/leak.hpp"
93 #include "utilities/align.hpp"
94 #include "utilities/bitMap.inline.hpp"
95 #include "utilities/defaultStream.hpp"
96 #include "utilities/macros.hpp"
97 #include "utilities/ostream.hpp"
98 #include "utilities/resourceHash.hpp"
99
100 #include <sys/stat.h>
101
102 ReservedSpace MetaspaceShared::_symbol_rs;
103 VirtualSpace MetaspaceShared::_symbol_vs;
104 bool MetaspaceShared::_archive_loading_failed = false;
105 bool MetaspaceShared::_remapped_readwrite = false;
106 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
107 intx MetaspaceShared::_relocation_delta;
108 char* MetaspaceShared::_requested_base_address;
109 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
110 bool MetaspaceShared::_use_optimized_module_handling = true;
111
112 // The CDS archive is divided into the following regions:
113 // rw - read-write metadata
114 // ro - read-only metadata and read-only tables
115 // hp - heap region
116 // bm - bitmap for relocating the above 7 regions.
117 //
118 // The rw and ro regions are linearly allocated, in the order of rw->ro.
119 // These regions are aligned with MetaspaceShared::core_region_alignment().
120 //
121 // These 2 regions are populated in the following steps:
122 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
123 // temporarily allocated outside of the shared regions.
124 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
125 // [2] C++ vtables are copied into the rw region.
126 // [3] ArchiveBuilder copies RW metadata into the rw region.
127 // [4] ArchiveBuilder copies RO metadata into the ro region.
128 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
129 // are copied into the ro region as read-only tables.
130 //
271 }
272
273 // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
274 // picked that (a) the align_up() below will always return a valid value; (b) none of
275 // the following asserts will fail.
276 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
277 p2i((void*)SharedBaseAddress), err,
278 p2i((void*)Arguments::default_SharedBaseAddress()));
279
280 specified_base = (char*)Arguments::default_SharedBaseAddress();
281 aligned_base = align_up(specified_base, alignment);
282
283 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
284 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
285 assert(shared_base_valid(aligned_base), "Sanity");
286 return aligned_base;
287 }
288
289 void MetaspaceShared::initialize_for_static_dump() {
290 assert(CDSConfig::is_dumping_static_archive(), "sanity");
291 log_info(cds)("Core region alignment: %zu", core_region_alignment());
292 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
293 // to avoid address space wrap around.
294 size_t cds_max;
295 const size_t reserve_alignment = core_region_alignment();
296
297 #ifdef _LP64
298 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
299 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
300 #else
301 // We don't support archives larger than 256MB on 32-bit due to limited
302 // virtual address space.
303 cds_max = align_down(256*M, reserve_alignment);
304 #endif
305
306 _requested_base_address = compute_shared_base(cds_max);
307 SharedBaseAddress = (size_t)_requested_base_address;
308
309 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
310 _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
463 // in archived Metadata objects.
464 CppVtables::serialize(soc);
465 soc->do_tag(--tag);
466
467 // Dump/restore miscellaneous metadata.
468 JavaClasses::serialize_offsets(soc);
469 Universe::serialize(soc);
470 soc->do_tag(--tag);
471
472 // Dump/restore references to commonly used names and signatures.
473 vmSymbols::serialize(soc);
474 soc->do_tag(--tag);
475
476 // Dump/restore the symbol/string/subgraph_info tables
477 SymbolTable::serialize_shared_table_header(soc);
478 StringTable::serialize_shared_table_header(soc);
479 HeapShared::serialize_tables(soc);
480 SystemDictionaryShared::serialize_dictionary_headers(soc);
481 AOTLinkedClassBulkLoader::serialize(soc, true);
482 FinalImageRecipes::serialize(soc);
483 InstanceMirrorKlass::serialize_offsets(soc);
484
485 // Dump/restore well known classes (pointers)
486 SystemDictionaryShared::serialize_vm_classes(soc);
487 soc->do_tag(--tag);
488
489 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
490 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
491
492 LambdaFormInvokers::serialize(soc);
493 soc->do_tag(666);
494 }
495
496 static void rewrite_nofast_bytecode(const methodHandle& method) {
497 BytecodeStream bcs(method);
498 while (!bcs.is_last_bytecode()) {
499 Bytecodes::Code opcode = bcs.next();
500 switch (opcode) {
501 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
502 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
503 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
504 case Bytecodes::_iload: {
505 if (!bcs.is_wide()) {
506 *bcs.bcp() = Bytecodes::_nofast_iload;
507 }
508 break;
509 }
510 default: break;
511 }
512 }
547 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
548
549 bool skip_operation() const { return false; }
550
551 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
552 ArchiveHeapInfo* heap_info() { return &_heap_info; }
553 FileMapInfo* map_info() const { return _map_info; }
554 void doit(); // outline because gdb sucks
555 bool allow_nested_vm_operations() const { return true; }
556 }; // class VM_PopulateDumpSharedSpace
557
558 class StaticArchiveBuilder : public ArchiveBuilder {
559 public:
560 StaticArchiveBuilder() : ArchiveBuilder() {}
561
562 virtual void iterate_roots(MetaspaceClosure* it) {
563 AOTArtifactFinder::all_cached_classes_do(it);
564 SystemDictionaryShared::dumptime_classes_do(it);
565 Universe::metaspace_pointers_do(it);
566 vmSymbols::metaspace_pointers_do(it);
567
568 // The above code should find all the symbols that are referenced by the
569 // archived classes. We just need to add the extra symbols which
570 // may not be used by any of the archived classes -- these are usually
571 // symbols that we anticipate to be used at run time, so we can store
572 // them in the RO region, to be shared across multiple processes.
573 if (_extra_symbols != nullptr) {
574 for (int i = 0; i < _extra_symbols->length(); i++) {
575 it->push(_extra_symbols->adr_at(i));
576 }
577 }
578
579 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
580 it->push(_pending_method_handle_intrinsics->adr_at(i));
581 }
582 }
583 };
584
585 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
586 ArchiveBuilder::OtherROAllocMark mark;
587
588 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
589
590 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
591 char* start = ro_region->top();
592 WriteClosure wc(ro_region);
593 MetaspaceShared::early_serialize(&wc);
594 return start;
595 }
596
597 char* VM_PopulateDumpSharedSpace::dump_read_only_tables(AOTClassLocationConfig*& cl_config) {
598 ArchiveBuilder::OtherROAllocMark mark;
599
600 SystemDictionaryShared::write_to_archive();
601 cl_config = AOTClassLocationConfig::dumptime()->write_to_archive();
602 AOTClassLinker::write_to_archive();
603 if (CDSConfig::is_dumping_preimage_static_archive()) {
604 FinalImageRecipes::record_recipes();
605 }
606 MetaspaceShared::write_method_handle_intrinsics();
607
608 // Write lambform lines into archive
609 LambdaFormInvokers::dump_static_archive_invokers();
610
611 // Write the other data to the output array.
612 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
613 char* start = ro_region->top();
614 WriteClosure wc(ro_region);
615 MetaspaceShared::serialize(&wc);
616
617 return start;
618 }
619
620 void VM_PopulateDumpSharedSpace::doit() {
621 if (!CDSConfig::is_dumping_final_static_archive()) {
622 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
623 }
624
625 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
626
627 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
628 if (CDSConfig::is_dumping_method_handles()) {
629 // When dumping AOT-linked classes, some classes may have direct references to a method handle
630 // intrinsic. The easiest thing is to save all of them into the AOT cache.
656 _builder.dump_rw_metadata();
657 _builder.dump_ro_metadata();
658 _builder.relocate_metaspaceobj_embedded_pointers();
659
660 log_info(cds)("Make classes shareable");
661 _builder.make_klasses_shareable();
662 MetaspaceShared::make_method_handle_intrinsics_shareable();
663
664 dump_java_heap_objects();
665 dump_shared_symbol_table(_builder.symbols());
666
667 char* early_serialized_data = dump_early_read_only_tables();
668 AOTClassLocationConfig* cl_config;
669 char* serialized_data = dump_read_only_tables(cl_config);
670
671 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
672 log_info(cds)("Adjust lambda proxy class dictionary");
673 LambdaProxyClassDictionary::adjust_dumptime_table();
674 }
675
676 // The vtable clones contain addresses of the current process.
677 // We don't want to write these addresses into the archive.
678 CppVtables::zero_archived_vtables();
679
680 // Write the archive file
681 if (CDSConfig::is_dumping_final_static_archive()) {
682 FileMapInfo::free_current_info(); // FIXME: should not free current info
683 }
684 const char* static_archive = CDSConfig::output_archive_path();
685 assert(static_archive != nullptr, "sanity");
686 _map_info = new FileMapInfo(static_archive, true);
687 _map_info->populate_header(MetaspaceShared::core_region_alignment());
688 _map_info->set_early_serialized_data(early_serialized_data);
689 _map_info->set_serialized_data(serialized_data);
690 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
691 _map_info->header()->set_class_location_config(cl_config);
692 }
693
694 class CollectClassesForLinking : public KlassClosure {
695 GrowableArray<OopHandle> _mirrors;
710 _mirrors.at(i).release(Universe::vm_global());
711 }
712 }
713
714 void do_cld(ClassLoaderData* cld) {
715 assert(cld->is_alive(), "must be");
716 }
717
718 void do_klass(Klass* k) {
719 if (k->is_instance_klass()) {
720 _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
721 }
722 }
723
724 const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
725 };
726
727 // Check if we can eagerly link this class at dump time, so we can avoid the
728 // runtime linking overhead (especially verification)
729 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
730 if (!ik->can_be_verified_at_dumptime()) {
731 // For old classes, try to leave them in the unlinked state, so
732 // we can still store them in the archive. They must be
733 // linked/verified at runtime.
734 return false;
735 }
736 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
737 // Linking of unregistered classes at this stage may cause more
738 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
739 // that may not be expected by custom class loaders.
740 //
741 // It's OK to do this for the built-in loaders as we know they can
742 // tolerate this.
743 return false;
744 }
745 return true;
746 }
747
748 void MetaspaceShared::link_shared_classes(TRAPS) {
749 AOTClassLinker::initialize();
750 AOTClassInitializer::init_test_class(CHECK);
751
752 while (true) {
753 ResourceMark rm(THREAD);
754 CollectClassesForLinking collect_classes;
755 bool has_linked = false;
756 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
757 for (int i = 0; i < mirrors->length(); i++) {
758 OopHandle mirror = mirrors->at(i);
759 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
760 if (may_be_eagerly_linked(ik)) {
761 has_linked |= try_link_class(THREAD, ik);
762 }
763 }
764
765 if (!has_linked) {
766 break;
767 }
768 // Class linking includes verification which may load more classes.
769 // Keep scanning until we have linked no more classes.
770 }
771
772 // Resolve constant pool entries -- we don't load any new classes during this stage
773 {
774 ResourceMark rm(THREAD);
775 CollectClassesForLinking collect_classes;
776 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
777 for (int i = 0; i < mirrors->length(); i++) {
778 OopHandle mirror = mirrors->at(i);
779 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
780 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
781 }
782 }
783
784 if (CDSConfig::is_dumping_final_static_archive()) {
785 FinalImageRecipes::apply_recipes(CHECK);
786 }
787 }
788
789 // Preload classes from a list, populate the shared spaces and dump to a
790 // file.
791 void MetaspaceShared::preload_and_dump(TRAPS) {
792 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
793 ResourceMark rm(THREAD);
794 StaticArchiveBuilder builder;
795 preload_and_dump_impl(builder, THREAD);
796 if (HAS_PENDING_EXCEPTION) {
797 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
798 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
799 "%zuM", MaxHeapSize/M);
800 MetaspaceShared::writing_error();
801 } else {
802 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
803 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
804 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
805 }
806 }
807
808 if (CDSConfig::new_aot_flags_used()) {
809 if (CDSConfig::is_dumping_preimage_static_archive()) {
810 // We are in the JVM that runs the training run. Continue execution,
811 // so that it can finish all clean-up and return the correct exit
812 // code to the OS.
813 tty->print_cr("AOTConfiguration recorded: %s", AOTConfiguration);
814 } else {
815 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
816 // When the new -XX:AOTMode=create flag is used, we can't return
817 // to the JLI launcher, as the launcher will fail when trying to
818 // run the main class, which is not what we want.
819 struct stat st;
820 if (os::stat(AOTCache, &st) != 0) {
821 tty->print_cr("AOTCache creation failed: %s", AOTCache);
822 vm_exit(0);
823 } else {
824 tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
825 vm_exit(0);
826 }
827 }
828 }
829 }
830
831 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
832 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
833 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
885 }
886 }
887
888 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
889 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
890 // are archived.
891 exercise_runtime_cds_code(CHECK);
892
893 log_info(cds)("Loading classes to share: done.");
894 }
895
896 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
897 // Exercise the manifest processing code
898 const char* dummy = "Manifest-Version: 1.0\n";
899 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
900
901 // Exercise FileSystem and URL code
902 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
903 }
904
905 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
906 if (CDSConfig::is_dumping_classic_static_archive()) {
907 // We are running with -Xshare:dump
908 preload_classes(CHECK);
909
910 if (SharedArchiveConfigFile) {
911 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
912 read_extra_data(THREAD, SharedArchiveConfigFile);
913 log_info(cds)("Reading extra data: done.");
914 }
915 }
916
917 if (CDSConfig::is_dumping_preimage_static_archive()) {
918 log_info(cds)("Reading lambda form invokers from JDK default classlist ...");
919 char default_classlist[JVM_MAXPATHLEN];
920 get_default_classlist(default_classlist, JVM_MAXPATHLEN);
921 struct stat statbuf;
922 if (os::stat(default_classlist, &statbuf) == 0) {
923 ClassListParser::parse_classlist(default_classlist,
924 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
925 }
938 #endif
939
940 if (CDSConfig::is_dumping_final_static_archive()) {
941 if (ExtraSharedClassListFile) {
942 log_info(cds)("Loading extra classes from %s ...", ExtraSharedClassListFile);
943 ClassListParser::parse_classlist(ExtraSharedClassListFile,
944 ClassListParser::_parse_all, CHECK);
945 }
946 }
947
948 // Rewrite and link classes
949 log_info(cds)("Rewriting and linking classes ...");
950
951 // Link any classes which got missed. This would happen if we have loaded classes that
952 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
953 // fails verification, all other interfaces that were not specified in the classlist but
954 // are implemented by K are not verified.
955 link_shared_classes(CHECK);
956 log_info(cds)("Rewriting and linking classes: done");
957
958 if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
959 LambdaFormInvokers::regenerate_holder_classes(CHECK);
960 }
961
962 #if INCLUDE_CDS_JAVA_HEAP
963 if (CDSConfig::is_dumping_heap()) {
964 ArchiveHeapWriter::init();
965 if (CDSConfig::is_dumping_full_module_graph()) {
966 ClassLoaderDataShared::ensure_module_entry_tables_exist();
967 HeapShared::reset_archived_object_states(CHECK);
968 }
969
970 if (CDSConfig::is_dumping_method_handles()) {
971 // This assert means that the MethodType and MethodTypeForm tables won't be
972 // updated concurrently when we are saving their contents into a side table.
973 assert(CDSConfig::allow_only_single_java_thread(), "Required");
974
975 JavaValue result(T_VOID);
976 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
977 vmSymbols::createArchivedObjects(),
978 vmSymbols::void_method_signature(),
979 CHECK);
980 }
981
982 if (CDSConfig::is_initing_classes_at_dump_time()) {
983 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
984 // to null, and it will be initialized again at runtime.
985 log_debug(cds)("Resetting Class::reflectionFactory");
986 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
987 Symbol* method_sig = vmSymbols::void_method_signature();
988 JavaValue result(T_VOID);
989 JavaCalls::call_static(&result, vmClasses::Class_klass(),
990 method_name, method_sig, CHECK);
991
992 // Perhaps there is a way to avoid hard-coding these names here.
993 // See discussion in JDK-8342481.
994 }
995
996 // Do this at the very end, when no Java code will be executed. Otherwise
997 // some new strings may be added to the intern table.
998 StringTable::allocate_shared_strings_array(CHECK);
999 } else {
1000 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1001 CDSConfig::stop_using_optimized_module_handling();
1002 }
1003 #endif
1004
1005 VM_PopulateDumpSharedSpace op(builder);
1006 VMThread::execute(&op);
1007
1008 if (!write_static_archive(&builder, op.map_info(), op.heap_info())) {
1009 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1010 }
1011 }
1012
1013 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1014 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1015 // without runtime relocation.
1016 builder->relocate_to_requested();
1017
1018 map_info->open_as_output();
1019 if (!map_info->is_open()) {
1020 return false;
1021 }
1022 builder->write_archive(map_info, heap_info);
1023
1024 if (AllowArchivingWithJavaAgent) {
1025 log_warning(cds)("This %s was created with AllowArchivingWithJavaAgent. It should be used "
1026 "for testing purposes only and should not be used in a production environment", CDSConfig::type_of_archive_being_loaded());
1027 }
1028 return true;
1029 }
1030
1031 // Returns true if the class's status has changed.
1032 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1033 ExceptionMark em(current);
1034 JavaThread* THREAD = current; // For exception macros.
1035 assert(CDSConfig::is_dumping_archive(), "sanity");
1036
1037 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1038 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1039 return false;
1040 }
1041
1042 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1043 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1044 bool saved = BytecodeVerificationLocal;
1045 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1046 // The verification decision is based on BytecodeVerificationRemote
1047 // for non-system classes. Since we are using the null classloader
1048 // to load non-system classes for customized class loaders during dumping,
1049 // we need to temporarily change BytecodeVerificationLocal to be the same as
1050 // BytecodeVerificationRemote. Note this can cause the parent system
1056 if (HAS_PENDING_EXCEPTION) {
1057 ResourceMark rm(THREAD);
1058 log_warning(cds)("Preload Warning: Verification failed for %s",
1059 ik->external_name());
1060 CLEAR_PENDING_EXCEPTION;
1061 SystemDictionaryShared::set_class_has_failed_verification(ik);
1062 } else {
1063 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1064 ik->compute_has_loops_flag_for_methods();
1065 }
1066 BytecodeVerificationLocal = saved;
1067 return true;
1068 } else {
1069 return false;
1070 }
1071 }
1072
1073 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1074 if (CDSConfig::is_dumping_heap()) {
1075 HeapShared::write_heap(&_heap_info);
1076 } else {
1077 CDSConfig::log_reasons_for_not_dumping_heap();
1078 }
1079 }
1080
1081 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1082 assert(base <= static_top && static_top <= top, "must be");
1083 _shared_metaspace_static_top = static_top;
1084 MetaspaceObj::set_shared_metaspace_range(base, top);
1085 }
1086
1087 bool MetaspaceShared::is_shared_dynamic(void* p) {
1088 if ((p < MetaspaceObj::shared_metaspace_top()) &&
1089 (p >= _shared_metaspace_static_top)) {
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
1096 bool MetaspaceShared::is_shared_static(void* p) {
1124 // This function is called when the JVM is unable to write the specified CDS archive due to an
1125 // unrecoverable error.
1126 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1127 writing_error(message);
1128 vm_direct_exit(1);
1129 }
1130
1131 // This function is called when the JVM is unable to write the specified CDS archive due to a
1132 // an error. The error will be propagated
1133 void MetaspaceShared::writing_error(const char* message) {
1134 log_error(cds)("An error has occurred while writing the shared archive file.");
1135 if (message != nullptr) {
1136 log_error(cds)("%s", message);
1137 }
1138 }
1139
1140 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1141 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1142 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1143
1144 FileMapInfo* static_mapinfo = open_static_archive();
1145 FileMapInfo* dynamic_mapinfo = nullptr;
1146
1147 if (static_mapinfo != nullptr) {
1148 log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1149 dynamic_mapinfo = open_dynamic_archive();
1150
1151 log_info(cds)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1152
1153 // First try to map at the requested address
1154 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1155 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1156 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1157 // by the OS.
1158 log_info(cds)("Try to map archive(s) at an alternative address");
1159 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1160 }
1161 }
1162
1163 if (result == MAP_ARCHIVE_SUCCESS) {
1164 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1170 _relocation_delta = static_mapinfo->relocation_delta();
1171 _requested_base_address = static_mapinfo->requested_base_address();
1172 if (dynamic_mapped) {
1173 // turn AutoCreateSharedArchive off if successfully mapped
1174 AutoCreateSharedArchive = false;
1175 }
1176 } else {
1177 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1178 if (CDSConfig::is_dumping_dynamic_archive()) {
1179 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1180 }
1181 UseSharedSpaces = false;
1182 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1183 AutoCreateSharedArchive = false;
1184 CDSConfig::disable_dumping_dynamic_archive();
1185 log_info(cds)("Unable to map shared spaces");
1186 if (PrintSharedArchiveAndExit) {
1187 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1188 } else if (RequireSharedSpaces) {
1189 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1190 }
1191 }
1192
1193 // If mapping failed and -XShare:on, the vm should exit
1194 bool has_failed = false;
1195 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1196 has_failed = true;
1197 delete static_mapinfo;
1198 }
1199 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1200 has_failed = true;
1201 delete dynamic_mapinfo;
1202 }
1203 if (RequireSharedSpaces && has_failed) {
1204 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1205 }
1206 }
1207
1208 FileMapInfo* MetaspaceShared::open_static_archive() {
1209 const char* static_archive = CDSConfig::input_static_archive_path();
1210 assert(static_archive != nullptr, "sanity");
1211 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1212 if (!mapinfo->open_as_input()) {
1213 delete(mapinfo);
1214 return nullptr;
1215 }
1216 return mapinfo;
1217 }
1218
1219 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1220 if (CDSConfig::is_dumping_dynamic_archive()) {
1221 return nullptr;
1222 }
1223 const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1224 if (dynamic_archive == nullptr) {
1225 return nullptr;
1226 }
1227
1228 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1229 if (!mapinfo->open_as_input()) {
1230 delete(mapinfo);
1231 if (RequireSharedSpaces) {
1232 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1233 }
1234 return nullptr;
1235 }
1236 return mapinfo;
1678 MemoryReserver::release(archive_space_rs);
1679 archive_space_rs = {};
1680 }
1681 if (class_space_rs.is_reserved()) {
1682 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1683 MemoryReserver::release(class_space_rs);
1684 class_space_rs = {};
1685 }
1686 }
1687 }
1688
1689 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1690 static int archive_regions_count = 2;
1691
1692 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1693 assert(CDSConfig::is_using_archive(), "must be runtime");
1694 if (mapinfo == nullptr) {
1695 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1696 }
1697
1698 mapinfo->set_is_mapped(false);
1699 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1700 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu"
1701 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
1702 return MAP_ARCHIVE_OTHER_FAILURE;
1703 }
1704
1705 MapArchiveResult result =
1706 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1707
1708 if (result != MAP_ARCHIVE_SUCCESS) {
1709 unmap_archive(mapinfo);
1710 return result;
1711 }
1712
1713 if (!mapinfo->validate_class_location()) {
1714 unmap_archive(mapinfo);
1715 return MAP_ARCHIVE_OTHER_FAILURE;
1716 }
1717
1755 };
1756
1757 // Read the miscellaneous data from the shared file, and
1758 // serialize it out to its various destinations.
1759
1760 void MetaspaceShared::initialize_shared_spaces() {
1761 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1762
1763 // Verify various attributes of the archive, plus initialize the
1764 // shared string/symbol tables.
1765 char* buffer = static_mapinfo->serialized_data();
1766 intptr_t* array = (intptr_t*)buffer;
1767 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
1768 serialize(&rc);
1769
1770 // Finish up archived heap initialization. These must be
1771 // done after ReadClosure.
1772 static_mapinfo->patch_heap_embedded_pointers();
1773 ArchiveHeapLoader::finish_initialization();
1774 Universe::load_archived_object_instances();
1775
1776 // Close the mapinfo file
1777 static_mapinfo->close();
1778
1779 static_mapinfo->unmap_region(MetaspaceShared::bm);
1780
1781 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1782 if (dynamic_mapinfo != nullptr) {
1783 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1784 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
1785 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1786 DynamicArchive::setup_array_klasses();
1787 dynamic_mapinfo->close();
1788 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1789 }
1790
1791 LogStreamHandle(Info, cds) lsh;
1792 if (lsh.is_enabled()) {
1793 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
1794 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
1805 // Read stored LF format lines stored in static archive
1806 LambdaFormInvokers::read_static_archive_invokers();
1807 }
1808
1809 if (PrintSharedArchiveAndExit) {
1810 // Print archive names
1811 if (dynamic_mapinfo != nullptr) {
1812 tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path());
1813 tty->print_cr("Base archive version %d", static_mapinfo->version());
1814 } else {
1815 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1816 tty->print_cr("Static archive version %d", static_mapinfo->version());
1817 }
1818
1819 SystemDictionaryShared::print_shared_archive(tty);
1820 if (dynamic_mapinfo != nullptr) {
1821 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1822 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1823 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1824 }
1825
1826 // collect shared symbols and strings
1827 CountSharedSymbols cl;
1828 SymbolTable::shared_symbols_do(&cl);
1829 tty->print_cr("Number of shared symbols: %d", cl.total());
1830 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1831 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1832 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1833 tty->print_cr("archive is invalid");
1834 vm_exit(1);
1835 } else {
1836 tty->print_cr("archive is valid");
1837 vm_exit(0);
1838 }
1839 }
1840 }
1841
1842 // JVM/TI RedefineClasses() support:
1843 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1844 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/aotClassInitializer.hpp"
28 #include "cds/aotClassLinker.hpp"
29 #include "cds/aotClassLocation.hpp"
30 #include "cds/aotConstantPoolResolver.hpp"
31 #include "cds/aotLinkedClassBulkLoader.hpp"
32 #include "cds/archiveBuilder.hpp"
33 #include "cds/archiveHeapLoader.hpp"
34 #include "cds/archiveHeapWriter.hpp"
35 #include "cds/cds_globals.hpp"
36 #include "cds/cdsAccess.hpp"
37 #include "cds/cdsConfig.hpp"
38 #include "cds/cdsProtectionDomain.hpp"
39 #include "cds/classListParser.hpp"
40 #include "cds/classListWriter.hpp"
41 #include "cds/cppVtables.hpp"
42 #include "cds/dumpAllocStats.hpp"
43 #include "cds/dynamicArchive.hpp"
44 #include "cds/filemap.hpp"
45 #include "cds/finalImageRecipes.hpp"
46 #include "cds/heapShared.hpp"
47 #include "cds/lambdaFormInvokers.hpp"
48 #include "cds/lambdaProxyClassDictionary.hpp"
49 #include "cds/metaspaceShared.hpp"
50 #include "classfile/classLoaderDataGraph.hpp"
51 #include "classfile/classLoaderDataShared.hpp"
52 #include "classfile/classLoaderExt.hpp"
53 #include "classfile/javaClasses.inline.hpp"
54 #include "classfile/loaderConstraints.hpp"
55 #include "classfile/modules.hpp"
56 #include "classfile/placeholders.hpp"
57 #include "classfile/stringTable.hpp"
58 #include "classfile/symbolTable.hpp"
59 #include "classfile/systemDictionary.hpp"
60 #include "classfile/systemDictionaryShared.hpp"
61 #include "classfile/vmClasses.hpp"
62 #include "classfile/vmSymbols.hpp"
63 #include "code/codeCache.hpp"
64 #include "code/SCCache.hpp"
65 #include "compiler/compileBroker.hpp"
66 #include "compiler/precompiler.hpp"
67 #include "gc/shared/gcVMOperations.hpp"
68 #include "interpreter/bytecodeStream.hpp"
69 #include "interpreter/bytecodes.hpp"
70 #include "jvm_io.h"
71 #include "logging/log.hpp"
72 #include "logging/logMessage.hpp"
73 #include "logging/logStream.hpp"
74 #include "memory/memoryReserver.hpp"
75 #include "memory/metaspace.hpp"
76 #include "memory/metaspaceClosure.hpp"
77 #include "memory/oopFactory.hpp"
78 #include "memory/resourceArea.hpp"
79 #include "memory/universe.hpp"
80 #include "nmt/memTracker.hpp"
81 #include "oops/compressedKlass.hpp"
82 #include "oops/instanceMirrorKlass.hpp"
83 #include "oops/klass.inline.hpp"
84 #include "oops/method.inline.hpp"
85 #include "oops/objArrayOop.hpp"
86 #include "oops/oop.inline.hpp"
87 #include "oops/oopHandle.hpp"
88 #include "oops/trainingData.hpp"
89 #include "prims/jvmtiExport.hpp"
90 #include "prims/whitebox.hpp"
91 #include "runtime/arguments.hpp"
92 #include "runtime/globals.hpp"
93 #include "runtime/globals_extension.hpp"
94 #include "runtime/handles.inline.hpp"
95 #include "runtime/javaCalls.hpp"
96 #include "runtime/os.inline.hpp"
97 #include "runtime/safepointVerifiers.hpp"
98 #include "runtime/sharedRuntime.hpp"
99 #include "runtime/vmOperations.hpp"
100 #include "runtime/vmThread.hpp"
101 #include "sanitizers/leak.hpp"
102 #include "utilities/align.hpp"
103 #include "utilities/bitMap.inline.hpp"
104 #include "utilities/defaultStream.hpp"
105 #include "utilities/macros.hpp"
106 #include "utilities/ostream.hpp"
107 #include "utilities/resourceHash.hpp"
108
109 #include <sys/stat.h>
110
111 ReservedSpace MetaspaceShared::_symbol_rs;
112 VirtualSpace MetaspaceShared::_symbol_vs;
113 bool MetaspaceShared::_archive_loading_failed = false;
114 bool MetaspaceShared::_remapped_readwrite = false;
115 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
116 intx MetaspaceShared::_relocation_delta;
117 char* MetaspaceShared::_requested_base_address;
118 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
119 bool MetaspaceShared::_use_optimized_module_handling = true;
120 int volatile MetaspaceShared::_preimage_static_archive_dumped = 0;
121
122 // The CDS archive is divided into the following regions:
123 // rw - read-write metadata
124 // ro - read-only metadata and read-only tables
125 // hp - heap region
126 // bm - bitmap for relocating the above 7 regions.
127 //
128 // The rw and ro regions are linearly allocated, in the order of rw->ro.
129 // These regions are aligned with MetaspaceShared::core_region_alignment().
130 //
131 // These 2 regions are populated in the following steps:
132 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
133 // temporarily allocated outside of the shared regions.
134 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
135 // [2] C++ vtables are copied into the rw region.
136 // [3] ArchiveBuilder copies RW metadata into the rw region.
137 // [4] ArchiveBuilder copies RO metadata into the ro region.
138 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
139 // are copied into the ro region as read-only tables.
140 //
281 }
282
283 // Arguments::default_SharedBaseAddress() is hard-coded in cds_globals.hpp. It must be carefully
284 // picked that (a) the align_up() below will always return a valid value; (b) none of
285 // the following asserts will fail.
286 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
287 p2i((void*)SharedBaseAddress), err,
288 p2i((void*)Arguments::default_SharedBaseAddress()));
289
290 specified_base = (char*)Arguments::default_SharedBaseAddress();
291 aligned_base = align_up(specified_base, alignment);
292
293 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
294 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
295 assert(shared_base_valid(aligned_base), "Sanity");
296 return aligned_base;
297 }
298
299 void MetaspaceShared::initialize_for_static_dump() {
300 assert(CDSConfig::is_dumping_static_archive(), "sanity");
301
302 if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
303 if (!((UseG1GC || UseParallelGC || UseSerialGC || UseEpsilonGC || UseShenandoahGC) && UseCompressedClassPointers)) {
304 const char* error;
305 if (CDSConfig::is_experimental_leyden_workflow()) {
306 error = "Cannot create the CacheDataStore";
307 } else if (CDSConfig::is_dumping_preimage_static_archive()) {
308 error = "Cannot create the AOT configuration file";
309 } else {
310 error = "Cannot create the AOT cache";
311 }
312
313 vm_exit_during_initialization(error,
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 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
320 // to avoid address space wrap around.
321 size_t cds_max;
322 const size_t reserve_alignment = core_region_alignment();
323
324 #ifdef _LP64
325 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
326 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
327 #else
328 // We don't support archives larger than 256MB on 32-bit due to limited
329 // virtual address space.
330 cds_max = align_down(256*M, reserve_alignment);
331 #endif
332
333 _requested_base_address = compute_shared_base(cds_max);
334 SharedBaseAddress = (size_t)_requested_base_address;
335
336 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
337 _symbol_rs = MemoryReserver::reserve(symbol_rs_size,
490 // in archived Metadata objects.
491 CppVtables::serialize(soc);
492 soc->do_tag(--tag);
493
494 // Dump/restore miscellaneous metadata.
495 JavaClasses::serialize_offsets(soc);
496 Universe::serialize(soc);
497 soc->do_tag(--tag);
498
499 // Dump/restore references to commonly used names and signatures.
500 vmSymbols::serialize(soc);
501 soc->do_tag(--tag);
502
503 // Dump/restore the symbol/string/subgraph_info tables
504 SymbolTable::serialize_shared_table_header(soc);
505 StringTable::serialize_shared_table_header(soc);
506 HeapShared::serialize_tables(soc);
507 SystemDictionaryShared::serialize_dictionary_headers(soc);
508 AOTLinkedClassBulkLoader::serialize(soc, true);
509 FinalImageRecipes::serialize(soc);
510 TrainingData::serialize(soc);
511 InstanceMirrorKlass::serialize_offsets(soc);
512
513 // Dump/restore well known classes (pointers)
514 SystemDictionaryShared::serialize_vm_classes(soc);
515 soc->do_tag(--tag);
516
517 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
518 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
519
520 LambdaFormInvokers::serialize(soc);
521 AdapterHandlerLibrary::serialize_shared_table_header(soc);
522
523 soc->do_tag(666);
524 }
525
526 static void rewrite_nofast_bytecode(const methodHandle& method) {
527 BytecodeStream bcs(method);
528 while (!bcs.is_last_bytecode()) {
529 Bytecodes::Code opcode = bcs.next();
530 switch (opcode) {
531 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
532 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
533 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
534 case Bytecodes::_iload: {
535 if (!bcs.is_wide()) {
536 *bcs.bcp() = Bytecodes::_nofast_iload;
537 }
538 break;
539 }
540 default: break;
541 }
542 }
577 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
578
579 bool skip_operation() const { return false; }
580
581 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
582 ArchiveHeapInfo* heap_info() { return &_heap_info; }
583 FileMapInfo* map_info() const { return _map_info; }
584 void doit(); // outline because gdb sucks
585 bool allow_nested_vm_operations() const { return true; }
586 }; // class VM_PopulateDumpSharedSpace
587
588 class StaticArchiveBuilder : public ArchiveBuilder {
589 public:
590 StaticArchiveBuilder() : ArchiveBuilder() {}
591
592 virtual void iterate_roots(MetaspaceClosure* it) {
593 AOTArtifactFinder::all_cached_classes_do(it);
594 SystemDictionaryShared::dumptime_classes_do(it);
595 Universe::metaspace_pointers_do(it);
596 vmSymbols::metaspace_pointers_do(it);
597 TrainingData::iterate_roots(it);
598
599 // The above code should find all the symbols that are referenced by the
600 // archived classes. We just need to add the extra symbols which
601 // may not be used by any of the archived classes -- these are usually
602 // symbols that we anticipate to be used at run time, so we can store
603 // them in the RO region, to be shared across multiple processes.
604 if (_extra_symbols != nullptr) {
605 for (int i = 0; i < _extra_symbols->length(); i++) {
606 it->push(_extra_symbols->adr_at(i));
607 }
608 }
609
610 for (int i = 0; i < _pending_method_handle_intrinsics->length(); i++) {
611 it->push(_pending_method_handle_intrinsics->adr_at(i));
612 }
613 }
614 };
615
616 char* VM_PopulateDumpSharedSpace::dump_early_read_only_tables() {
617 ArchiveBuilder::OtherROAllocMark mark;
618
619 CDS_JAVA_HEAP_ONLY(Modules::dump_archived_module_info());
620
621 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
622 char* start = ro_region->top();
623 WriteClosure wc(ro_region);
624 MetaspaceShared::early_serialize(&wc);
625 return start;
626 }
627
628 char* VM_PopulateDumpSharedSpace::dump_read_only_tables(AOTClassLocationConfig*& cl_config) {
629 ArchiveBuilder::OtherROAllocMark mark;
630
631 SystemDictionaryShared::write_to_archive();
632 cl_config = AOTClassLocationConfig::dumptime()->write_to_archive();
633 AOTClassLinker::write_to_archive();
634 if (CDSConfig::is_dumping_preimage_static_archive()) {
635 FinalImageRecipes::record_recipes();
636 }
637
638 TrainingData::dump_training_data();
639
640 MetaspaceShared::write_method_handle_intrinsics();
641
642 // Write lambform lines into archive
643 LambdaFormInvokers::dump_static_archive_invokers();
644
645 if (CDSConfig::is_dumping_adapters()) {
646 AdapterHandlerLibrary::archive_adapter_table();
647 }
648
649 // Write the other data to the output array.
650 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
651 char* start = ro_region->top();
652 WriteClosure wc(ro_region);
653 MetaspaceShared::serialize(&wc);
654
655 return start;
656 }
657
658 void VM_PopulateDumpSharedSpace::doit() {
659 if (!CDSConfig::is_dumping_final_static_archive()) {
660 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
661 }
662
663 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
664
665 _pending_method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
666 if (CDSConfig::is_dumping_method_handles()) {
667 // When dumping AOT-linked classes, some classes may have direct references to a method handle
668 // intrinsic. The easiest thing is to save all of them into the AOT cache.
694 _builder.dump_rw_metadata();
695 _builder.dump_ro_metadata();
696 _builder.relocate_metaspaceobj_embedded_pointers();
697
698 log_info(cds)("Make classes shareable");
699 _builder.make_klasses_shareable();
700 MetaspaceShared::make_method_handle_intrinsics_shareable();
701
702 dump_java_heap_objects();
703 dump_shared_symbol_table(_builder.symbols());
704
705 char* early_serialized_data = dump_early_read_only_tables();
706 AOTClassLocationConfig* cl_config;
707 char* serialized_data = dump_read_only_tables(cl_config);
708
709 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
710 log_info(cds)("Adjust lambda proxy class dictionary");
711 LambdaProxyClassDictionary::adjust_dumptime_table();
712 }
713
714 log_info(cds)("Make training data shareable");
715 _builder.make_training_data_shareable();
716
717 // The vtable clones contain addresses of the current process.
718 // We don't want to write these addresses into the archive.
719 CppVtables::zero_archived_vtables();
720
721 // Write the archive file
722 if (CDSConfig::is_dumping_final_static_archive()) {
723 FileMapInfo::free_current_info(); // FIXME: should not free current info
724 }
725 const char* static_archive = CDSConfig::output_archive_path();
726 assert(static_archive != nullptr, "sanity");
727 _map_info = new FileMapInfo(static_archive, true);
728 _map_info->populate_header(MetaspaceShared::core_region_alignment());
729 _map_info->set_early_serialized_data(early_serialized_data);
730 _map_info->set_serialized_data(serialized_data);
731 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
732 _map_info->header()->set_class_location_config(cl_config);
733 }
734
735 class CollectClassesForLinking : public KlassClosure {
736 GrowableArray<OopHandle> _mirrors;
751 _mirrors.at(i).release(Universe::vm_global());
752 }
753 }
754
755 void do_cld(ClassLoaderData* cld) {
756 assert(cld->is_alive(), "must be");
757 }
758
759 void do_klass(Klass* k) {
760 if (k->is_instance_klass()) {
761 _mirrors.append(OopHandle(Universe::vm_global(), k->java_mirror()));
762 }
763 }
764
765 const GrowableArray<OopHandle>* mirrors() const { return &_mirrors; }
766 };
767
768 // Check if we can eagerly link this class at dump time, so we can avoid the
769 // runtime linking overhead (especially verification)
770 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
771 if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
772 assert(ik->can_be_verified_at_dumptime(), "sanity");
773 }
774 if (!ik->can_be_verified_at_dumptime()) {
775 // For old classes, try to leave them in the unlinked state, so
776 // we can still store them in the archive. They must be
777 // linked/verified at runtime.
778 return false;
779 }
780
781 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
782 // Linking of unregistered classes at this stage may cause more
783 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
784 // that may not be expected by custom class loaders.
785 //
786 // It's OK to do this for the built-in loaders as we know they can
787 // tolerate this.
788 return false;
789 }
790 return true;
791 }
792
793 void MetaspaceShared::link_shared_classes(TRAPS) {
794 AOTClassLinker::initialize();
795 AOTClassInitializer::init_test_class(CHECK);
796
797 while (true) {
798 ResourceMark rm(THREAD);
799 CollectClassesForLinking collect_classes;
800 bool has_linked = false;
801 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
802 for (int i = 0; i < mirrors->length(); i++) {
803 OopHandle mirror = mirrors->at(i);
804 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
805 if (may_be_eagerly_linked(ik)) {
806 has_linked |= try_link_class(THREAD, ik);
807 }
808 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
809 AOTClassInitializer::maybe_preinit_class(ik, CHECK);
810 }
811 }
812
813 if (!has_linked) {
814 break;
815 }
816 // Class linking includes verification which may load more classes.
817 // Keep scanning until we have linked no more classes.
818 }
819
820 // Resolve constant pool entries -- we don't load any new classes during this stage
821 {
822 ResourceMark rm(THREAD);
823 CollectClassesForLinking collect_classes;
824 const GrowableArray<OopHandle>* mirrors = collect_classes.mirrors();
825 for (int i = 0; i < mirrors->length(); i++) {
826 OopHandle mirror = mirrors->at(i);
827 InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror.resolve()));
828 AOTConstantPoolResolver::dumptime_resolve_constants(ik, CHECK);
829 if (CDSConfig::is_dumping_preimage_static_archive()) {
830 FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
831 }
832 }
833 }
834
835 if (CDSConfig::is_dumping_final_static_archive()) {
836 FinalImageRecipes::apply_recipes(CHECK);
837 }
838 }
839
840 // Preload classes from a list, populate the shared spaces and dump to a
841 // file.
842 void MetaspaceShared::preload_and_dump(TRAPS) {
843 CDSConfig::DumperThreadMark dumper_thread_mark(THREAD);
844 ResourceMark rm(THREAD);
845 HandleMark hm(THREAD);
846
847 if (CDSConfig::is_dumping_final_static_archive() && AOTPrintTrainingInfo) {
848 tty->print_cr("==================== archived_training_data ** before dumping ====================");
849 TrainingData::print_archived_training_data_on(tty);
850 }
851
852 StaticArchiveBuilder builder;
853 preload_and_dump_impl(builder, THREAD);
854 if (HAS_PENDING_EXCEPTION) {
855 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
856 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
857 "%zuM", MaxHeapSize/M);
858 MetaspaceShared::writing_error();
859 } else {
860 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
861 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
862 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
863 }
864 if (CDSConfig::is_experimental_leyden_workflow()) {
865 vm_exit(1);
866 }
867 }
868
869 if (CDSConfig::new_aot_flags_used()) {
870 if (CDSConfig::is_dumping_preimage_static_archive()) {
871 // We are in the JVM that runs the training run. Continue execution,
872 // so that it can finish all clean-up and return the correct exit
873 // code to the OS.
874 } else {
875 // The JLI launcher only recognizes the "old" -Xshare:dump flag.
876 // When the new -XX:AOTMode=create flag is used, we can't return
877 // to the JLI launcher, as the launcher will fail when trying to
878 // run the main class, which is not what we want.
879 struct stat st;
880 if (os::stat(AOTCache, &st) != 0) {
881 tty->print_cr("AOTCache creation failed: %s", AOTCache);
882 vm_exit(0);
883 } else {
884 tty->print_cr("AOTCache creation is complete: %s " INT64_FORMAT " bytes", AOTCache, (int64_t)(st.st_size));
885 vm_exit(0);
886 }
887 }
888 }
889 }
890
891 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
892 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
893 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
945 }
946 }
947
948 // Some classes are used at CDS runtime but are not loaded, and therefore archived, at
949 // dumptime. We can perform dummmy calls to these classes at dumptime to ensure they
950 // are archived.
951 exercise_runtime_cds_code(CHECK);
952
953 log_info(cds)("Loading classes to share: done.");
954 }
955
956 void MetaspaceShared::exercise_runtime_cds_code(TRAPS) {
957 // Exercise the manifest processing code
958 const char* dummy = "Manifest-Version: 1.0\n";
959 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
960
961 // Exercise FileSystem and URL code
962 CDSProtectionDomain::to_file_URL("dummy.jar", Handle(), CHECK);
963 }
964
965 bool MetaspaceShared::is_recording_preimage_static_archive() {
966 if (CDSConfig::is_dumping_preimage_static_archive()) {
967 return _preimage_static_archive_dumped == 0;
968 }
969 return false;
970 }
971
972 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
973 if (CDSConfig::is_dumping_preimage_static_archive()) {
974 if (Atomic::cmpxchg(&_preimage_static_archive_dumped, 0, 1) != 0) {
975 return;
976 }
977 }
978
979 if (CDSConfig::is_dumping_classic_static_archive()) {
980 // We are running with -Xshare:dump
981 preload_classes(CHECK);
982
983 if (SharedArchiveConfigFile) {
984 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
985 read_extra_data(THREAD, SharedArchiveConfigFile);
986 log_info(cds)("Reading extra data: done.");
987 }
988 }
989
990 if (CDSConfig::is_dumping_preimage_static_archive()) {
991 log_info(cds)("Reading lambda form invokers from JDK default classlist ...");
992 char default_classlist[JVM_MAXPATHLEN];
993 get_default_classlist(default_classlist, JVM_MAXPATHLEN);
994 struct stat statbuf;
995 if (os::stat(default_classlist, &statbuf) == 0) {
996 ClassListParser::parse_classlist(default_classlist,
997 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
998 }
1011 #endif
1012
1013 if (CDSConfig::is_dumping_final_static_archive()) {
1014 if (ExtraSharedClassListFile) {
1015 log_info(cds)("Loading extra classes from %s ...", ExtraSharedClassListFile);
1016 ClassListParser::parse_classlist(ExtraSharedClassListFile,
1017 ClassListParser::_parse_all, CHECK);
1018 }
1019 }
1020
1021 // Rewrite and link classes
1022 log_info(cds)("Rewriting and linking classes ...");
1023
1024 // Link any classes which got missed. This would happen if we have loaded classes that
1025 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1026 // fails verification, all other interfaces that were not specified in the classlist but
1027 // are implemented by K are not verified.
1028 link_shared_classes(CHECK);
1029 log_info(cds)("Rewriting and linking classes: done");
1030
1031 if (CDSConfig::is_dumping_final_static_archive()) {
1032 assert(!AOTRecordTraining, "must be");
1033 if (CDSConfig::is_dumping_aot_linked_classes()) {
1034 AOTRecordTraining = true;
1035 }
1036 }
1037
1038 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
1039
1040 if (CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
1041 LambdaFormInvokers::regenerate_holder_classes(CHECK);
1042 }
1043
1044 #if INCLUDE_CDS_JAVA_HEAP
1045 if (CDSConfig::is_dumping_heap()) {
1046 ArchiveHeapWriter::init();
1047 if (CDSConfig::is_dumping_full_module_graph()) {
1048 ClassLoaderDataShared::ensure_module_entry_tables_exist();
1049 HeapShared::reset_archived_object_states(CHECK);
1050 }
1051
1052 if (ArchiveLoaderLookupCache) {
1053 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
1054 }
1055
1056 if (CDSConfig::is_initing_classes_at_dump_time()) {
1057 // java.lang.Class::reflectionFactory cannot be archived yet. We set this field
1058 // to null, and it will be initialized again at runtime.
1059 log_debug(cds)("Resetting Class::reflectionFactory");
1060 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
1061 Symbol* method_sig = vmSymbols::void_method_signature();
1062 JavaValue result(T_VOID);
1063 JavaCalls::call_static(&result, vmClasses::Class_klass(),
1064 method_name, method_sig, CHECK);
1065
1066 // Perhaps there is a way to avoid hard-coding these names here.
1067 // See discussion in JDK-8342481.
1068 }
1069
1070 // Do this at the very end, when no Java code will be executed. Otherwise
1071 // some new strings may be added to the intern table.
1072 StringTable::allocate_shared_strings_array(CHECK);
1073 } else {
1074 log_info(cds)("Not dumping heap, reset CDSConfig::_is_using_optimized_module_handling");
1075 CDSConfig::stop_using_optimized_module_handling();
1076 }
1077 #endif
1078
1079 VM_PopulateDumpSharedSpace op(builder);
1080 VMThread::execute(&op);
1081 FileMapInfo* mapinfo = op.map_info();
1082 ArchiveHeapInfo* heap_info = op.heap_info();
1083
1084 if (CDSConfig::is_dumping_final_static_archive()) {
1085 AOTRecordTraining = false;
1086 if (StoreCachedCode) {
1087 if (log_is_enabled(Info, cds, jit)) {
1088 CDSAccess::test_heap_access_api();
1089 }
1090
1091 // We have just created the final image. Let's run the AOT compiler
1092 if (AOTPrintTrainingInfo) {
1093 tty->print_cr("==================== archived_training_data ** after dumping ====================");
1094 TrainingData::print_archived_training_data_on(tty);
1095 }
1096
1097 CDSConfig::enable_dumping_cached_code();
1098 {
1099 builder.start_cc_region();
1100 Precompiler::compile_cached_code(&builder, CHECK);
1101 // Write the contents to cached code region and close SCCache before packing the region
1102 SCCache::close();
1103 builder.end_cc_region();
1104 }
1105 CDSConfig::disable_dumping_cached_code();
1106 }
1107 }
1108
1109 bool status = write_static_archive(&builder, mapinfo, heap_info);
1110 if (status && CDSConfig::is_dumping_preimage_static_archive()) {
1111 if (CDSConfig::is_experimental_leyden_workflow()) {
1112 fork_and_dump_final_static_archive_experimental_leyden_workflow(CHECK);
1113 } else {
1114 tty->print_cr("%s AOTConfiguration recorded: %s",
1115 CDSConfig::has_temp_aot_config_file() ? "Temporary" : "", AOTConfiguration);
1116 if (CDSConfig::is_one_step_training()) {
1117 fork_and_dump_final_static_archive(CHECK);
1118 }
1119 }
1120 }
1121
1122 if (!status) {
1123 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
1124 }
1125 }
1126
1127 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
1128 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1129 // without runtime relocation.
1130 builder->relocate_to_requested();
1131
1132 map_info->open_as_output();
1133 if (!map_info->is_open()) {
1134 return false;
1135 }
1136 builder->write_archive(map_info, heap_info);
1137
1138 if (AllowArchivingWithJavaAgent) {
1139 log_warning(cds)("This %s was created with AllowArchivingWithJavaAgent. It should be used "
1140 "for testing purposes only and should not be used in a production environment", CDSConfig::type_of_archive_being_loaded());
1141 }
1142 return true;
1143 }
1144
1145 static void print_java_launcher(outputStream* st) {
1146 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1147 }
1148
1149 static void append_args(GrowableArray<Handle>* args, const char* arg, TRAPS) {
1150 Handle string = java_lang_String::create_from_str(arg, CHECK);
1151 args->append(string);
1152 }
1153
1154 // Pass all options in Arguments::jvm_args_array() to a child JVM process
1155 // using the JAVA_TOOL_OPTIONS environment variable.
1156 static int exec_jvm_with_java_tool_options(const char* java_launcher_path, TRAPS) {
1157 ResourceMark rm(THREAD);
1158 HandleMark hm(THREAD);
1159 GrowableArray<Handle> args;
1160
1161 const char* cp = Arguments::get_appclasspath();
1162 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1163 // We cannot use "-cp", because "-cp" is only interpreted by the java launcher,
1164 // and is not interpreter by arguments.cpp when it loads args from JAVA_TOOL_OPTIONS
1165 stringStream ss;
1166 ss.print("-Djava.class.path=");
1167 ss.print_raw(cp);
1168 append_args(&args, ss.freeze(), CHECK_0);
1169 // CDS$ProcessLauncher::execWithJavaToolOptions() must unset CLASSPATH, which has
1170 // a higher priority than -Djava.class.path=
1171 }
1172
1173 // Pass all arguments. These include those from JAVA_TOOL_OPTIONS and _JAVA_OPTIONS.
1174 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1175 const char* arg = Arguments::jvm_args_array()[i];
1176 if (strncmp("-XX:AOTMode", arg, 11) == 0) {
1177 // Filter it out. We will set AOTMode=create below.
1178 } else {
1179 append_args(&args, arg, CHECK_0);
1180 }
1181 }
1182
1183 // We don't pass Arguments::jvm_flags_array(), as those will be added by
1184 // the child process when it loads .hotspotrc
1185
1186 if (CDSConfig::is_experimental_leyden_workflow()) {
1187 stringStream ss;
1188 ss.print("-XX:CDSPreimage=");
1189 ss.print_raw(CDSPreimage);
1190 append_args(&args, ss.freeze(), CHECK_0);
1191 } else {
1192 if (CDSConfig::has_temp_aot_config_file()) {
1193 stringStream ss;
1194 ss.print("-XX:AOTConfiguration=");
1195 ss.print_raw(AOTConfiguration);
1196 append_args(&args, ss.freeze(), CHECK_0);
1197 }
1198 append_args(&args, "-XX:AOTMode=create", CHECK_0);
1199 }
1200
1201 GrowableArray<const char*> aot_tool_options;
1202 jint code;
1203 if ((code = Arguments::parse_aot_tool_options_environment_variable(&aot_tool_options)) != JNI_OK) {
1204 THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("failed to parse AOT_TOOL_OPTIONS: %d", code));
1205 }
1206 for (int i = 0; i < aot_tool_options.length(); i++) {
1207 append_args(&args, aot_tool_options.at(i), CHECK_0);
1208 }
1209
1210 Symbol* klass_name = SymbolTable::new_symbol("jdk/internal/misc/CDS$ProcessLauncher");
1211 Klass* k = SystemDictionary::resolve_or_fail(klass_name, true, CHECK_0);
1212 Symbol* methodName = SymbolTable::new_symbol("execWithJavaToolOptions");
1213 Symbol* methodSignature = SymbolTable::new_symbol("(Ljava/lang/String;[Ljava/lang/String;)I");
1214
1215 Handle launcher = java_lang_String::create_from_str(java_launcher_path, CHECK_0);
1216 objArrayOop array = oopFactory::new_objArray(vmClasses::String_klass(), args.length(), CHECK_0);
1217 for (int i = 0; i < args.length(); i++) {
1218 array->obj_at_put(i, args.at(i)());
1219 }
1220 objArrayHandle launcher_args(THREAD, array);
1221
1222 // The following call will pass all options inside the JAVA_TOOL_OPTIONS env variable to
1223 // the child process. It will also clear the _JAVA_OPTIONS and CLASSPATH env variables for
1224 // the child process.
1225 //
1226 // Note: the env variables are set only for the child process. They are not changed
1227 // for the current process. See java.lang.ProcessBuilder::environment().
1228 JavaValue result(T_OBJECT);
1229 JavaCallArguments javacall_args(2);
1230 javacall_args.push_oop(launcher);
1231 javacall_args.push_oop(launcher_args);
1232 JavaCalls::call_static(&result,
1233 InstanceKlass::cast(k),
1234 methodName,
1235 methodSignature,
1236 &javacall_args,
1237 CHECK_0);
1238 return result.get_jint();
1239 }
1240
1241 // This is for debugging purposes only (-XX:+CDSManualFinalImage) so we don't bother
1242 // quoating any special characters. The user should avoid using special chars.
1243 static void print_vm_arguments(outputStream* st) {
1244 const char* cp = Arguments::get_appclasspath();
1245 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1246 st->print(" -cp "); st->print_raw(cp);
1247 }
1248 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1249 st->print(" %s", Arguments::jvm_args_array()[i]);
1250 }
1251 }
1252
1253 void MetaspaceShared::fork_and_dump_final_static_archive_experimental_leyden_workflow(TRAPS) {
1254 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1255
1256 ResourceMark rm;
1257 stringStream ss;
1258 print_java_launcher(&ss);
1259
1260 if (CDSManualFinalImage) {
1261 print_vm_arguments(&ss);
1262 ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1263 const char* cmd = ss.freeze();
1264
1265 tty->print_cr("-XX:+CDSManualFinalImage is specified");
1266 tty->print_cr("Please manually execute the following command to create the final CDS image:");
1267 tty->print(" "); tty->print_raw_cr(cmd);
1268
1269 // The following is useful if the dumping was trigger by a script that builds
1270 // a complex command-line.
1271 tty->print_cr("Note: to recreate the preimage only:");
1272 tty->print_cr(" rm -f %s", CacheDataStore);
1273 tty->print(" ");
1274 print_java_launcher(tty);
1275 print_vm_arguments(tty);
1276 if (Arguments::java_command() != nullptr) {
1277 tty->print(" %s", Arguments::java_command());
1278 }
1279 tty->cr();
1280 } else {
1281 const char* cmd = ss.freeze();
1282 log_info(cds)("Launching child process to create final CDS image:");
1283 log_info(cds)(" %s", cmd);
1284 int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1285 if (status != 0) {
1286 log_error(cds)("Child process finished; status = %d", status);
1287 log_error(cds)("To reproduce the error");
1288 ResourceMark rm;
1289 LogStream ls(Log(cds)::error());
1290 ls.print(" "); ls.print_raw_cr(cmd);
1291
1292 // The following is useful if the dumping was trigger by a script that builds
1293 // a complex command-line.
1294 ls.print_cr("Note: to recreate the preimage only:");
1295 ls.print_cr(" rm -f %s", CacheDataStore);
1296 ls.print(" ");
1297 print_java_launcher(&ls);
1298 print_vm_arguments(&ls);
1299 ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1300 if (Arguments::java_command() != nullptr) {
1301 ls.print(" %s", Arguments::java_command());
1302 }
1303 ls.cr();
1304
1305 vm_direct_exit(status);
1306 } else {
1307 log_info(cds)("Child process finished; status = %d", status);
1308 // On Windows, need WRITE permission to remove the file.
1309 WINDOWS_ONLY(chmod(CDSPreimage, _S_IREAD | _S_IWRITE));
1310 status = remove(CDSPreimage);
1311 if (status != 0) {
1312 log_error(cds)("Failed to remove CDSPreimage file %s", CDSPreimage);
1313 } else {
1314 log_info(cds)("Removed CDSPreimage file %s", CDSPreimage);
1315 }
1316 }
1317 }
1318 }
1319
1320 void MetaspaceShared::fork_and_dump_final_static_archive(TRAPS) {
1321 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1322
1323 ResourceMark rm;
1324 stringStream ss;
1325 print_java_launcher(&ss);
1326 const char* cmd = ss.freeze();
1327 tty->print_cr("Launching child process %s to assemble AOT cache %s using configuration %s", cmd, AOTCacheOutput, AOTConfiguration);
1328 int status = exec_jvm_with_java_tool_options(cmd, CHECK);
1329 if (status != 0) {
1330 log_error(cds)("Child process failed; status = %d", status);
1331 // We leave the temp config file for debugging
1332 } else if (CDSConfig::has_temp_aot_config_file()) {
1333 const char* tmp_config = AOTConfiguration;
1334 // On Windows, need WRITE permission to remove the file.
1335 WINDOWS_ONLY(chmod(tmp_config, _S_IREAD | _S_IWRITE));
1336 status = remove(tmp_config);
1337 if (status != 0) {
1338 log_error(cds)("Failed to remove temporary AOT configuration file %s", tmp_config);
1339 } else {
1340 tty->print_cr("Removed temporary AOT configuration file %s", tmp_config);
1341 }
1342 }
1343 }
1344
1345 // Returns true if the class's status has changed.
1346 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1347 ExceptionMark em(current);
1348 JavaThread* THREAD = current; // For exception macros.
1349 assert(CDSConfig::is_dumping_archive(), "sanity");
1350
1351 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1352 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1353 return false;
1354 }
1355
1356 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1357 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1358 bool saved = BytecodeVerificationLocal;
1359 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1360 // The verification decision is based on BytecodeVerificationRemote
1361 // for non-system classes. Since we are using the null classloader
1362 // to load non-system classes for customized class loaders during dumping,
1363 // we need to temporarily change BytecodeVerificationLocal to be the same as
1364 // BytecodeVerificationRemote. Note this can cause the parent system
1370 if (HAS_PENDING_EXCEPTION) {
1371 ResourceMark rm(THREAD);
1372 log_warning(cds)("Preload Warning: Verification failed for %s",
1373 ik->external_name());
1374 CLEAR_PENDING_EXCEPTION;
1375 SystemDictionaryShared::set_class_has_failed_verification(ik);
1376 } else {
1377 assert(!SystemDictionaryShared::has_class_failed_verification(ik), "sanity");
1378 ik->compute_has_loops_flag_for_methods();
1379 }
1380 BytecodeVerificationLocal = saved;
1381 return true;
1382 } else {
1383 return false;
1384 }
1385 }
1386
1387 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
1388 if (CDSConfig::is_dumping_heap()) {
1389 HeapShared::write_heap(&_heap_info);
1390 } else if (!CDSConfig::is_dumping_preimage_static_archive()) {
1391 CDSConfig::log_reasons_for_not_dumping_heap();
1392 }
1393 }
1394
1395 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
1396 assert(base <= static_top && static_top <= top, "must be");
1397 _shared_metaspace_static_top = static_top;
1398 MetaspaceObj::set_shared_metaspace_range(base, top);
1399 }
1400
1401 bool MetaspaceShared::is_shared_dynamic(void* p) {
1402 if ((p < MetaspaceObj::shared_metaspace_top()) &&
1403 (p >= _shared_metaspace_static_top)) {
1404 return true;
1405 } else {
1406 return false;
1407 }
1408 }
1409
1410 bool MetaspaceShared::is_shared_static(void* p) {
1438 // This function is called when the JVM is unable to write the specified CDS archive due to an
1439 // unrecoverable error.
1440 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1441 writing_error(message);
1442 vm_direct_exit(1);
1443 }
1444
1445 // This function is called when the JVM is unable to write the specified CDS archive due to a
1446 // an error. The error will be propagated
1447 void MetaspaceShared::writing_error(const char* message) {
1448 log_error(cds)("An error has occurred while writing the shared archive file.");
1449 if (message != nullptr) {
1450 log_error(cds)("%s", message);
1451 }
1452 }
1453
1454 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1455 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1456 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1457
1458 FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1459 FileMapInfo* dynamic_mapinfo = nullptr;
1460
1461 if (static_mapinfo != nullptr) {
1462 log_info(cds)("Core region alignment: %zu", static_mapinfo->core_region_alignment());
1463 dynamic_mapinfo = open_dynamic_archive();
1464
1465 log_info(cds)("ArchiveRelocationMode: %d", ArchiveRelocationMode);
1466
1467 // First try to map at the requested address
1468 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1469 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1470 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1471 // by the OS.
1472 log_info(cds)("Try to map archive(s) at an alternative address");
1473 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1474 }
1475 }
1476
1477 if (result == MAP_ARCHIVE_SUCCESS) {
1478 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1484 _relocation_delta = static_mapinfo->relocation_delta();
1485 _requested_base_address = static_mapinfo->requested_base_address();
1486 if (dynamic_mapped) {
1487 // turn AutoCreateSharedArchive off if successfully mapped
1488 AutoCreateSharedArchive = false;
1489 }
1490 } else {
1491 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1492 if (CDSConfig::is_dumping_dynamic_archive()) {
1493 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1494 }
1495 UseSharedSpaces = false;
1496 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1497 AutoCreateSharedArchive = false;
1498 CDSConfig::disable_dumping_dynamic_archive();
1499 log_info(cds)("Unable to map shared spaces");
1500 if (PrintSharedArchiveAndExit) {
1501 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1502 } else if (RequireSharedSpaces) {
1503 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1504 } else if (CDSConfig::is_dumping_final_static_archive()) {
1505 assert(CDSPreimage != nullptr, "must be");
1506 log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1507 MetaspaceShared::unrecoverable_loading_error();
1508 }
1509 }
1510
1511 // If mapping failed and -XShare:on, the vm should exit
1512 bool has_failed = false;
1513 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1514 has_failed = true;
1515 delete static_mapinfo;
1516 }
1517 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1518 has_failed = true;
1519 delete dynamic_mapinfo;
1520 }
1521 if (RequireSharedSpaces && has_failed) {
1522 // static archive mapped but dynamic archive failed
1523 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1524 }
1525 }
1526
1527 // This is called very early at VM start up to get the size of the cached_code region
1528 void MetaspaceShared::open_static_archive() {
1529 if (!UseSharedSpaces) { // FIXME -- is this still needed??
1530 return;
1531 }
1532 const char* static_archive = CDSConfig::input_static_archive_path();
1533 assert(static_archive != nullptr, "sanity");
1534 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1535 if (!mapinfo->open_as_input()) {
1536 delete(mapinfo);
1537 } else {
1538 FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1539 CDSAccess::set_cached_code_size(r->used_aligned());
1540 }
1541 }
1542
1543 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1544 if (CDSConfig::is_dumping_dynamic_archive()) {
1545 return nullptr;
1546 }
1547 const char* dynamic_archive = CDSConfig::input_dynamic_archive_path();
1548 if (dynamic_archive == nullptr) {
1549 return nullptr;
1550 }
1551
1552 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1553 if (!mapinfo->open_as_input()) {
1554 delete(mapinfo);
1555 if (RequireSharedSpaces) {
1556 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1557 }
1558 return nullptr;
1559 }
1560 return mapinfo;
2002 MemoryReserver::release(archive_space_rs);
2003 archive_space_rs = {};
2004 }
2005 if (class_space_rs.is_reserved()) {
2006 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2007 MemoryReserver::release(class_space_rs);
2008 class_space_rs = {};
2009 }
2010 }
2011 }
2012
2013 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
2014 static int archive_regions_count = 2;
2015
2016 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2017 assert(CDSConfig::is_using_archive(), "must be runtime");
2018 if (mapinfo == nullptr) {
2019 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2020 }
2021
2022 if (!mapinfo->validate_aot_class_linking()) {
2023 return MAP_ARCHIVE_OTHER_FAILURE;
2024 }
2025
2026 mapinfo->set_is_mapped(false);
2027 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
2028 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: %zu"
2029 " actual: %zu", mapinfo->core_region_alignment(), core_region_alignment());
2030 return MAP_ARCHIVE_OTHER_FAILURE;
2031 }
2032
2033 MapArchiveResult result =
2034 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2035
2036 if (result != MAP_ARCHIVE_SUCCESS) {
2037 unmap_archive(mapinfo);
2038 return result;
2039 }
2040
2041 if (!mapinfo->validate_class_location()) {
2042 unmap_archive(mapinfo);
2043 return MAP_ARCHIVE_OTHER_FAILURE;
2044 }
2045
2083 };
2084
2085 // Read the miscellaneous data from the shared file, and
2086 // serialize it out to its various destinations.
2087
2088 void MetaspaceShared::initialize_shared_spaces() {
2089 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2090
2091 // Verify various attributes of the archive, plus initialize the
2092 // shared string/symbol tables.
2093 char* buffer = static_mapinfo->serialized_data();
2094 intptr_t* array = (intptr_t*)buffer;
2095 ReadClosure rc(&array, (intptr_t)SharedBaseAddress);
2096 serialize(&rc);
2097
2098 // Finish up archived heap initialization. These must be
2099 // done after ReadClosure.
2100 static_mapinfo->patch_heap_embedded_pointers();
2101 ArchiveHeapLoader::finish_initialization();
2102 Universe::load_archived_object_instances();
2103 SCCache::initialize();
2104
2105 // Close the mapinfo file
2106 static_mapinfo->close();
2107
2108 static_mapinfo->unmap_region(MetaspaceShared::bm);
2109
2110 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2111 if (dynamic_mapinfo != nullptr) {
2112 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2113 ReadClosure rc(&buffer, (intptr_t)SharedBaseAddress);
2114 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
2115 DynamicArchive::setup_array_klasses();
2116 dynamic_mapinfo->close();
2117 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
2118 }
2119
2120 LogStreamHandle(Info, cds) lsh;
2121 if (lsh.is_enabled()) {
2122 lsh.print("Using AOT-linked classes: %s (static archive: %s aot-linked classes",
2123 BOOL_TO_STR(CDSConfig::is_using_aot_linked_classes()),
2134 // Read stored LF format lines stored in static archive
2135 LambdaFormInvokers::read_static_archive_invokers();
2136 }
2137
2138 if (PrintSharedArchiveAndExit) {
2139 // Print archive names
2140 if (dynamic_mapinfo != nullptr) {
2141 tty->print_cr("\n\nBase archive name: %s", CDSConfig::input_static_archive_path());
2142 tty->print_cr("Base archive version %d", static_mapinfo->version());
2143 } else {
2144 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
2145 tty->print_cr("Static archive version %d", static_mapinfo->version());
2146 }
2147
2148 SystemDictionaryShared::print_shared_archive(tty);
2149 if (dynamic_mapinfo != nullptr) {
2150 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
2151 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
2152 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
2153 }
2154 TrainingData::print_archived_training_data_on(tty);
2155
2156 if (LoadCachedCode) {
2157 tty->print_cr("\n\nCached Code");
2158 SCCache::print_on(tty);
2159 }
2160
2161 // collect shared symbols and strings
2162 CountSharedSymbols cl;
2163 SymbolTable::shared_symbols_do(&cl);
2164 tty->print_cr("Number of shared symbols: %d", cl.total());
2165 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
2166 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
2167 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
2168 tty->print_cr("archive is invalid");
2169 vm_exit(1);
2170 } else {
2171 tty->print_cr("archive is valid");
2172 vm_exit(0);
2173 }
2174 }
2175 }
2176
2177 // JVM/TI RedefineClasses() support:
2178 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2179 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|