10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveHeapLoader.hpp"
28 #include "cds/archiveHeapWriter.hpp"
29 #include "cds/cds_globals.hpp"
30 #include "cds/cdsConfig.hpp"
31 #include "cds/cdsProtectionDomain.hpp"
32 #include "cds/cds_globals.hpp"
33 #include "cds/classListParser.hpp"
34 #include "cds/classListWriter.hpp"
35 #include "cds/classPrelinker.hpp"
36 #include "cds/cppVtables.hpp"
37 #include "cds/dumpAllocStats.hpp"
38 #include "cds/dynamicArchive.hpp"
39 #include "cds/filemap.hpp"
40 #include "cds/heapShared.hpp"
41 #include "cds/lambdaFormInvokers.hpp"
42 #include "cds/metaspaceShared.hpp"
43 #include "classfile/classLoaderDataGraph.hpp"
44 #include "classfile/classLoaderDataShared.hpp"
45 #include "classfile/classLoaderExt.hpp"
46 #include "classfile/javaClasses.inline.hpp"
47 #include "classfile/loaderConstraints.hpp"
48 #include "classfile/modules.hpp"
49 #include "classfile/placeholders.hpp"
50 #include "classfile/stringTable.hpp"
51 #include "classfile/symbolTable.hpp"
52 #include "classfile/systemDictionary.hpp"
53 #include "classfile/systemDictionaryShared.hpp"
54 #include "classfile/vmClasses.hpp"
55 #include "classfile/vmSymbols.hpp"
56 #include "code/codeCache.hpp"
57 #include "gc/shared/gcVMOperations.hpp"
58 #include "interpreter/bytecodeStream.hpp"
59 #include "interpreter/bytecodes.hpp"
60 #include "jvm_io.h"
61 #include "logging/log.hpp"
62 #include "logging/logMessage.hpp"
63 #include "logging/logStream.hpp"
64 #include "memory/metaspace.hpp"
65 #include "memory/metaspaceClosure.hpp"
66 #include "memory/resourceArea.hpp"
67 #include "memory/universe.hpp"
68 #include "nmt/memTracker.hpp"
69 #include "oops/compressedKlass.hpp"
70 #include "oops/instanceMirrorKlass.hpp"
71 #include "oops/klass.inline.hpp"
72 #include "oops/objArrayOop.hpp"
73 #include "oops/oop.inline.hpp"
74 #include "oops/oopHandle.hpp"
75 #include "prims/jvmtiExport.hpp"
76 #include "runtime/arguments.hpp"
77 #include "runtime/globals.hpp"
78 #include "runtime/globals_extension.hpp"
79 #include "runtime/handles.inline.hpp"
80 #include "runtime/os.inline.hpp"
81 #include "runtime/safepointVerifiers.hpp"
82 #include "runtime/sharedRuntime.hpp"
83 #include "runtime/vmOperations.hpp"
84 #include "runtime/vmThread.hpp"
85 #include "sanitizers/leak.hpp"
86 #include "utilities/align.hpp"
87 #include "utilities/bitMap.inline.hpp"
88 #include "utilities/defaultStream.hpp"
89 #include "utilities/ostream.hpp"
90 #include "utilities/resourceHash.hpp"
91
92 ReservedSpace MetaspaceShared::_symbol_rs;
93 VirtualSpace MetaspaceShared::_symbol_vs;
94 bool MetaspaceShared::_archive_loading_failed = false;
95 bool MetaspaceShared::_remapped_readwrite = false;
96 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
97 intx MetaspaceShared::_relocation_delta;
98 char* MetaspaceShared::_requested_base_address;
99 bool MetaspaceShared::_use_optimized_module_handling = true;
100
101 // The CDS archive is divided into the following regions:
102 // rw - read-write metadata
103 // ro - read-only metadata and read-only tables
104 // hp - heap region
105 // bm - bitmap for relocating the above 7 regions.
106 //
107 // The rw and ro regions are linearly allocated, in the order of rw->ro.
108 // These regions are aligned with MetaspaceShared::core_region_alignment().
109 //
110 // These 2 regions are populated in the following steps:
111 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
112 // temporarily allocated outside of the shared regions.
113 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
114 // [2] C++ vtables are copied into the rw region.
115 // [3] ArchiveBuilder copies RW metadata into the rw region.
116 // [4] ArchiveBuilder copies RO metadata into the ro region.
117 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
118 // are copied into the ro region as read-only tables.
241 err = "invalid for this platform";
242 } else {
243 return aligned_base;
244 }
245
246 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
247 p2i((void*)SharedBaseAddress), err,
248 p2i((void*)Arguments::default_SharedBaseAddress()));
249
250 specified_base = (char*)Arguments::default_SharedBaseAddress();
251 aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
252
253 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
254 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
255 assert(shared_base_valid(aligned_base), "Sanity");
256 return aligned_base;
257 }
258
259 void MetaspaceShared::initialize_for_static_dump() {
260 assert(CDSConfig::is_dumping_static_archive(), "sanity");
261 log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
262 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
263 // to avoid address space wrap around.
264 size_t cds_max;
265 const size_t reserve_alignment = core_region_alignment();
266
267 #ifdef _LP64
268 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
269 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
270 #else
271 // We don't support archives larger than 256MB on 32-bit due to limited
272 // virtual address space.
273 cds_max = align_down(256*M, reserve_alignment);
274 #endif
275
276 _requested_base_address = compute_shared_base(cds_max);
277 SharedBaseAddress = (size_t)_requested_base_address;
278
279 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
280 _symbol_rs = ReservedSpace(symbol_rs_size);
290 if (CDSConfig::is_using_archive()) {
291 int size = FileMapInfo::get_number_of_shared_paths();
292 if (size > 0) {
293 CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
294 if (!CDSConfig::is_dumping_dynamic_archive()) {
295 FileMapInfo* info;
296 if (FileMapInfo::dynamic_info() == nullptr) {
297 info = FileMapInfo::current_info();
298 } else {
299 info = FileMapInfo::dynamic_info();
300 }
301 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
302 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
303 }
304 }
305 }
306 }
307
308 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
309 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;
310
311 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
312 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
313 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
314
315 HashtableTextDump reader(filename);
316 reader.check_version("VERSION: 1.0");
317
318 while (reader.remain() > 0) {
319 int utf8_length;
320 int prefix_type = reader.scan_prefix(&utf8_length);
321 ResourceMark rm(current);
322 if (utf8_length == 0x7fffffff) {
323 // buf_len will overflown 32-bit value.
324 log_error(cds)("string length too large: %d", utf8_length);
325 MetaspaceShared::unrecoverable_loading_error();
326 }
327 int buf_len = utf8_length+1;
328 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
329 reader.get_utf8(utf8_buffer, utf8_length);
340 if (HAS_PENDING_EXCEPTION) {
341 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
342 reader.last_line_no(), utf8_length);
343 CLEAR_PENDING_EXCEPTION;
344 } else {
345 #if INCLUDE_CDS_JAVA_HEAP
346 if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) {
347 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
348 reader.last_line_no(), utf8_length);
349 continue;
350 }
351 // Make sure this string is included in the dumped interned string table.
352 assert(str != nullptr, "must succeed");
353 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
354 #endif
355 }
356 }
357 }
358 }
359
360 // Read/write a data stream for restoring/preserving metadata pointers and
361 // miscellaneous data from/to the shared archive file.
362
363 void MetaspaceShared::serialize(SerializeClosure* soc) {
364 int tag = 0;
365 soc->do_tag(--tag);
366
367 // Verify the sizes of various metadata in the system.
368 soc->do_tag(sizeof(Method));
369 soc->do_tag(sizeof(ConstMethod));
370 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
371 soc->do_tag(sizeof(ConstantPool));
372 soc->do_tag(sizeof(ConstantPoolCache));
373 soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
374 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
375 soc->do_tag(sizeof(Symbol));
376
377 // Need to do this first, as subsequent steps may call virtual functions
378 // in archived Metadata objects.
379 CppVtables::serialize(soc);
380 soc->do_tag(--tag);
381
382 // Dump/restore miscellaneous metadata.
383 JavaClasses::serialize_offsets(soc);
384 Universe::serialize(soc);
385 soc->do_tag(--tag);
386
387 // Dump/restore references to commonly used names and signatures.
388 vmSymbols::serialize(soc);
389 soc->do_tag(--tag);
390
391 // Dump/restore the symbol/string/subgraph_info tables
392 SymbolTable::serialize_shared_table_header(soc);
393 StringTable::serialize_shared_table_header(soc);
394 HeapShared::serialize_tables(soc);
395 SystemDictionaryShared::serialize_dictionary_headers(soc);
396
397 InstanceMirrorKlass::serialize_offsets(soc);
398
399 // Dump/restore well known classes (pointers)
400 SystemDictionaryShared::serialize_vm_classes(soc);
401 soc->do_tag(--tag);
402
403 CDS_JAVA_HEAP_ONLY(Modules::serialize(soc);)
404 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
405
406 LambdaFormInvokers::serialize(soc);
407 soc->do_tag(666);
408 }
409
410 static void rewrite_nofast_bytecode(const methodHandle& method) {
411 BytecodeStream bcs(method);
412 while (!bcs.is_last_bytecode()) {
413 Bytecodes::Code opcode = bcs.next();
414 switch (opcode) {
415 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
416 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
417 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
418 case Bytecodes::_iload: {
419 if (!bcs.is_wide()) {
420 *bcs.bcp() = Bytecodes::_nofast_iload;
421 }
422 break;
423 }
424 default: break;
460 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
461
462 bool skip_operation() const { return false; }
463
464 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
465 ArchiveHeapInfo* heap_info() { return &_heap_info; }
466 FileMapInfo* map_info() const { return _map_info; }
467 void doit(); // outline because gdb sucks
468 bool allow_nested_vm_operations() const { return true; }
469 }; // class VM_PopulateDumpSharedSpace
470
471 class StaticArchiveBuilder : public ArchiveBuilder {
472 public:
473 StaticArchiveBuilder() : ArchiveBuilder() {}
474
475 virtual void iterate_roots(MetaspaceClosure* it) {
476 FileMapInfo::metaspace_pointers_do(it);
477 SystemDictionaryShared::dumptime_classes_do(it);
478 Universe::metaspace_pointers_do(it);
479 vmSymbols::metaspace_pointers_do(it);
480
481 // The above code should find all the symbols that are referenced by the
482 // archived classes. We just need to add the extra symbols which
483 // may not be used by any of the archived classes -- these are usually
484 // symbols that we anticipate to be used at run time, so we can store
485 // them in the RO region, to be shared across multiple processes.
486 if (_extra_symbols != nullptr) {
487 for (int i = 0; i < _extra_symbols->length(); i++) {
488 it->push(_extra_symbols->adr_at(i));
489 }
490 }
491 }
492 };
493
494 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
495 ArchiveBuilder::OtherROAllocMark mark;
496
497 SystemDictionaryShared::write_to_archive();
498
499 // Write lambform lines into archive
500 LambdaFormInvokers::dump_static_archive_invokers();
501 // Write module name into archive
502 CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
503 // Write the other data to the output array.
504 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
505 char* start = ro_region->top();
506 WriteClosure wc(ro_region);
507 MetaspaceShared::serialize(&wc);
508
509 return start;
510 }
511
512 void VM_PopulateDumpSharedSpace::doit() {
513 guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
514
515 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
516
517 FileMapInfo::check_nonempty_dir_in_shared_path_table();
518
519 NOT_PRODUCT(SystemDictionary::verify();)
520
521 // Block concurrent class unloading from changing the _dumptime_table
522 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
523 SystemDictionaryShared::check_excluded_classes();
524
525 _builder.gather_source_objs();
526 _builder.reserve_buffer();
527
528 CppVtables::dumptime_init(&_builder);
529
530 _builder.sort_metadata_objs();
531 _builder.dump_rw_metadata();
532 _builder.dump_ro_metadata();
533 _builder.relocate_metaspaceobj_embedded_pointers();
534
535 dump_java_heap_objects(_builder.klasses());
536 dump_shared_symbol_table(_builder.symbols());
537
538 log_info(cds)("Make classes shareable");
539 _builder.make_klasses_shareable();
540
541 char* serialized_data = dump_read_only_tables();
542
543 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
544
545 // The vtable clones contain addresses of the current process.
546 // We don't want to write these addresses into the archive.
547 CppVtables::zero_archived_vtables();
548
549 // Write the archive file
550 const char* static_archive = CDSConfig::static_archive_path();
551 assert(static_archive != nullptr, "SharedArchiveFile not set?");
552 _map_info = new FileMapInfo(static_archive, true);
553 _map_info->populate_header(MetaspaceShared::core_region_alignment());
554 _map_info->set_serialized_data(serialized_data);
555 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
556 }
557
558 class CollectCLDClosure : public CLDClosure {
559 GrowableArray<ClassLoaderData*> _loaded_cld;
560 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
561 Thread* _current_thread;
562 public:
563 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
564 ~CollectCLDClosure() {
565 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
566 _loaded_cld_handles.at(i).release(Universe::vm_global());
567 }
568 }
569 void do_cld(ClassLoaderData* cld) {
570 assert(cld->is_alive(), "must be");
571 _loaded_cld.append(cld);
572 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
573 }
574
575 int nof_cld() const { return _loaded_cld.length(); }
576 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
577 };
578
579 // Check if we can eagerly link this class at dump time, so we can avoid the
580 // runtime linking overhead (especially verification)
581 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
582 if (!ik->can_be_verified_at_dumptime()) {
583 // For old classes, try to leave them in the unlinked state, so
584 // we can still store them in the archive. They must be
585 // linked/verified at runtime.
586 return false;
587 }
588 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
589 // Linking of unregistered classes at this stage may cause more
590 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
591 // that may not be expected by custom class loaders.
592 //
593 // It's OK to do this for the built-in loaders as we know they can
594 // tolerate this.
595 return false;
596 }
597 return true;
598 }
599
600 bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
601 // Link the class to cause the bytecodes to be rewritten and the
602 // cpcache to be created. Class verification is done according
603 // to -Xverify setting.
604 bool res = MetaspaceShared::try_link_class(THREAD, ik);
605 ClassPrelinker::dumptime_resolve_constants(ik, CHECK_(false));
606 return res;
607 }
608
609 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
610 ClassPrelinker::initialize();
611
612 if (!jcmd_request) {
613 LambdaFormInvokers::regenerate_holder_classes(CHECK);
614 }
615
616 // Collect all loaded ClassLoaderData.
617 CollectCLDClosure collect_cld(THREAD);
618 {
619 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
620 // We cannot link the classes while holding this lock (or else we may run into deadlock).
621 // Therefore, we need to first collect all the CLDs, and then link their classes after
622 // releasing the lock.
623 MutexLocker lock(ClassLoaderDataGraph_lock);
624 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
625 }
626
627 while (true) {
628 bool has_linked = false;
629 for (int i = 0; i < collect_cld.nof_cld(); i++) {
630 ClassLoaderData* cld = collect_cld.cld_at(i);
631 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
632 if (klass->is_instance_klass()) {
633 InstanceKlass* ik = InstanceKlass::cast(klass);
634 if (may_be_eagerly_linked(ik)) {
635 has_linked |= link_class_for_cds(ik, CHECK);
636 }
637 }
638 }
639 }
640
641 if (!has_linked) {
642 break;
643 }
644 // Class linking includes verification which may load more classes.
645 // Keep scanning until we have linked no more classes.
646 }
647 }
648
649 void MetaspaceShared::prepare_for_dumping() {
650 assert(CDSConfig::is_dumping_archive(), "sanity");
651 CDSConfig::check_unsupported_dumping_module_options();
652 ClassLoader::initialize_shared_path(JavaThread::current());
653 }
654
655 // Preload classes from a list, populate the shared spaces and dump to a
656 // file.
657 void MetaspaceShared::preload_and_dump(TRAPS) {
658 ResourceMark rm(THREAD);
659 StaticArchiveBuilder builder;
660 preload_and_dump_impl(builder, THREAD);
661 if (HAS_PENDING_EXCEPTION) {
662 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
663 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
664 SIZE_FORMAT "M", MaxHeapSize/M);
665 MetaspaceShared::writing_error();
666 } else {
667 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
668 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
669 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
670 }
671 }
672 }
673
674 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
675 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
676 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
677 return;
678 }
741 ClassListParser::_parse_all, CHECK);
742 }
743 if (classlist_path != default_classlist) {
744 struct stat statbuf;
745 if (os::stat(default_classlist, &statbuf) == 0) {
746 // File exists, let's use it.
747 ClassListParser::parse_classlist(default_classlist,
748 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
749 }
750 }
751
752 // Exercise the manifest processing code to ensure classes used by CDS at runtime
753 // are always archived
754 const char* dummy = "Manifest-Version: 1.0\n";
755 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
756
757 log_info(cds)("Loading classes to share: done.");
758 }
759
760 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
761 preload_classes(CHECK);
762
763 if (SharedArchiveConfigFile) {
764 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
765 read_extra_data(THREAD, SharedArchiveConfigFile);
766 log_info(cds)("Reading extra data: done.");
767 }
768
769 // Rewrite and link classes
770 log_info(cds)("Rewriting and linking classes ...");
771
772 // Link any classes which got missed. This would happen if we have loaded classes that
773 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
774 // fails verification, all other interfaces that were not specified in the classlist but
775 // are implemented by K are not verified.
776 link_shared_classes(false/*not from jcmd*/, CHECK);
777 log_info(cds)("Rewriting and linking classes: done");
778
779 #if INCLUDE_CDS_JAVA_HEAP
780 if (CDSConfig::is_dumping_heap()) {
781 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
782 log_info(cds)("archivedBootLayer not available, disabling full module graph");
783 CDSConfig::stop_dumping_full_module_graph();
784 }
785 HeapShared::init_for_dumping(CHECK);
786 ArchiveHeapWriter::init();
787 if (CDSConfig::is_dumping_full_module_graph()) {
788 HeapShared::reset_archived_object_states(CHECK);
789 }
790
791 // Do this at the very end, when no Java code will be executed. Otherwise
792 // some new strings may be added to the intern table.
793 StringTable::allocate_shared_strings_array(CHECK);
794 }
795 #endif
796
797 VM_PopulateDumpSharedSpace op(builder);
798 VMThread::execute(&op);
799
800 if (!write_static_archive(&builder, op.map_info(), op.heap_info())) {
801 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
802 }
803 }
804
805 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
806 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
807 // without runtime relocation.
808 builder->relocate_to_requested();
809
810 map_info->open_for_write();
811 if (!map_info->is_open()) {
812 return false;
813 }
814 builder->write_archive(map_info, heap_info);
815
816 if (AllowArchivingWithJavaAgent) {
817 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
818 "for testing purposes only and should not be used in a production environment");
819 }
820 return true;
821 }
822
823 // Returns true if the class's status has changed.
824 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
825 ExceptionMark em(current);
826 JavaThread* THREAD = current; // For exception macros.
827 assert(CDSConfig::is_dumping_archive(), "sanity");
828 if (!ik->is_shared() && ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
829 !SystemDictionaryShared::has_class_failed_verification(ik)) {
830 bool saved = BytecodeVerificationLocal;
831 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
832 // The verification decision is based on BytecodeVerificationRemote
833 // for non-system classes. Since we are using the null classloader
834 // to load non-system classes for customized class loaders during dumping,
835 // we need to temporarily change BytecodeVerificationLocal to be the same as
836 // BytecodeVerificationRemote. Note this can cause the parent system
837 // classes also being verified. The extra overhead is acceptable during
838 // dumping.
839 BytecodeVerificationLocal = BytecodeVerificationRemote;
840 }
841 ik->link_class(THREAD);
842 if (HAS_PENDING_EXCEPTION) {
843 ResourceMark rm(THREAD);
844 log_warning(cds)("Preload Warning: Verification failed for %s",
845 ik->external_name());
846 CLEAR_PENDING_EXCEPTION;
847 SystemDictionaryShared::set_class_has_failed_verification(ik);
848 }
849 ik->compute_has_loops_flag_for_methods();
850 BytecodeVerificationLocal = saved;
851 return true;
852 } else {
853 return false;
854 }
855 }
856
857 #if INCLUDE_CDS_JAVA_HEAP
858 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
859 if(!HeapShared::can_write()) {
860 log_info(cds)(
861 "Archived java heap is not supported as UseG1GC "
862 "and UseCompressedClassPointers are required."
863 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
864 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
865 return;
866 }
867 // Find all the interned strings that should be dumped.
868 int i;
869 for (i = 0; i < klasses->length(); i++) {
870 Klass* k = klasses->at(i);
871 if (k->is_instance_klass()) {
872 InstanceKlass* ik = InstanceKlass::cast(k);
873 if (ik->is_linked()) {
874 ik->constants()->add_dumped_interned_strings();
875 }
876 }
877 }
878 if (_extra_interned_strings != nullptr) {
879 for (i = 0; i < _extra_interned_strings->length(); i ++) {
880 OopHandle string = _extra_interned_strings->at(i);
881 HeapShared::add_to_dumped_interned_strings(string.resolve());
882 }
883 }
884
927 // This function is called when the JVM is unable to write the specified CDS archive due to an
928 // unrecoverable error.
929 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
930 writing_error(message);
931 vm_direct_exit(1);
932 }
933
934 // This function is called when the JVM is unable to write the specified CDS archive due to a
935 // an error. The error will be propagated
936 void MetaspaceShared::writing_error(const char* message) {
937 log_error(cds)("An error has occurred while writing the shared archive file.");
938 if (message != nullptr) {
939 log_error(cds)("%s", message);
940 }
941 }
942
943 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
944 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
945 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
946
947 FileMapInfo* static_mapinfo = open_static_archive();
948 FileMapInfo* dynamic_mapinfo = nullptr;
949
950 if (static_mapinfo != nullptr) {
951 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
952 dynamic_mapinfo = open_dynamic_archive();
953
954 // First try to map at the requested address
955 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
956 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
957 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
958 // by the OS.
959 log_info(cds)("Try to map archive(s) at an alternative address");
960 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
961 }
962 }
963
964 if (result == MAP_ARCHIVE_SUCCESS) {
965 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
966 char* cds_base = static_mapinfo->mapped_base();
967 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
974 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
975 // turn AutoCreateSharedArchive off if successfully mapped
976 AutoCreateSharedArchive = false;
977 } else {
978 FileMapInfo::set_shared_path_table(static_mapinfo);
979 }
980 } else {
981 set_shared_metaspace_range(nullptr, nullptr, nullptr);
982 if (CDSConfig::is_dumping_dynamic_archive()) {
983 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
984 }
985 UseSharedSpaces = false;
986 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
987 AutoCreateSharedArchive = false;
988 CDSConfig::disable_dumping_dynamic_archive();
989 log_info(cds)("Unable to map shared spaces");
990 if (PrintSharedArchiveAndExit) {
991 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
992 } else if (RequireSharedSpaces) {
993 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
994 }
995 }
996
997 // If mapping failed and -XShare:on, the vm should exit
998 bool has_failed = false;
999 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1000 has_failed = true;
1001 delete static_mapinfo;
1002 }
1003 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1004 has_failed = true;
1005 delete dynamic_mapinfo;
1006 }
1007 if (RequireSharedSpaces && has_failed) {
1008 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1009 }
1010 }
1011
1012 FileMapInfo* MetaspaceShared::open_static_archive() {
1013 const char* static_archive = CDSConfig::static_archive_path();
1014 assert(static_archive != nullptr, "sanity");
1015 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1016 if (!mapinfo->initialize()) {
1017 delete(mapinfo);
1018 return nullptr;
1019 }
1020 return mapinfo;
1021 }
1022
1023 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1024 if (CDSConfig::is_dumping_dynamic_archive()) {
1025 return nullptr;
1026 }
1027 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1028 if (dynamic_archive == nullptr) {
1029 return nullptr;
1030 }
1031
1032 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1033 if (!mapinfo->initialize()) {
1034 delete(mapinfo);
1035 if (RequireSharedSpaces) {
1036 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1037 }
1038 return nullptr;
1039 }
1040 return mapinfo;
1419 if (archive_space_rs.is_reserved()) {
1420 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1421 archive_space_rs.release();
1422 }
1423 if (class_space_rs.is_reserved()) {
1424 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1425 class_space_rs.release();
1426 }
1427 }
1428 }
1429
1430 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1431 static int archive_regions_count = 2;
1432
1433 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1434 assert(CDSConfig::is_using_archive(), "must be runtime");
1435 if (mapinfo == nullptr) {
1436 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1437 }
1438
1439 mapinfo->set_is_mapped(false);
1440 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1441 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1442 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1443 return MAP_ARCHIVE_OTHER_FAILURE;
1444 }
1445
1446 MapArchiveResult result =
1447 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1448
1449 if (result != MAP_ARCHIVE_SUCCESS) {
1450 unmap_archive(mapinfo);
1451 return result;
1452 }
1453
1454 if (!mapinfo->validate_shared_path_table()) {
1455 unmap_archive(mapinfo);
1456 return MAP_ARCHIVE_OTHER_FAILURE;
1457 }
1458
1483 };
1484
1485 // Read the miscellaneous data from the shared file, and
1486 // serialize it out to its various destinations.
1487
1488 void MetaspaceShared::initialize_shared_spaces() {
1489 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1490
1491 // Verify various attributes of the archive, plus initialize the
1492 // shared string/symbol tables.
1493 char* buffer = static_mapinfo->serialized_data();
1494 intptr_t* array = (intptr_t*)buffer;
1495 ReadClosure rc(&array);
1496 serialize(&rc);
1497
1498 // Finish up archived heap initialization. These must be
1499 // done after ReadClosure.
1500 static_mapinfo->patch_heap_embedded_pointers();
1501 ArchiveHeapLoader::finish_initialization();
1502 Universe::load_archived_object_instances();
1503
1504 // Close the mapinfo file
1505 static_mapinfo->close();
1506
1507 static_mapinfo->unmap_region(MetaspaceShared::bm);
1508
1509 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1510 if (dynamic_mapinfo != nullptr) {
1511 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1512 ReadClosure rc(&buffer);
1513 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1514 DynamicArchive::setup_array_klasses();
1515 dynamic_mapinfo->close();
1516 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1517 }
1518
1519 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1520 if (CDSConfig::is_dumping_dynamic_archive()) {
1521 // Read stored LF format lines stored in static archive
1522 LambdaFormInvokers::read_static_archive_invokers();
1523 }
1524
1525 if (PrintSharedArchiveAndExit) {
1526 // Print archive names
1527 if (dynamic_mapinfo != nullptr) {
1528 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1529 tty->print_cr("Base archive version %d", static_mapinfo->version());
1530 } else {
1531 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1532 tty->print_cr("Static archive version %d", static_mapinfo->version());
1533 }
1534
1535 SystemDictionaryShared::print_shared_archive(tty);
1536 if (dynamic_mapinfo != nullptr) {
1537 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1538 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1539 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1540 }
1541
1542 // collect shared symbols and strings
1543 CountSharedSymbols cl;
1544 SymbolTable::shared_symbols_do(&cl);
1545 tty->print_cr("Number of shared symbols: %d", cl.total());
1546 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1547 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1548 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1549 tty->print_cr("archive is invalid");
1550 vm_exit(1);
1551 } else {
1552 tty->print_cr("archive is valid");
1553 vm_exit(0);
1554 }
1555 }
1556 }
1557
1558 // JVM/TI RedefineClasses() support:
1559 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1560 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveHeapLoader.hpp"
28 #include "cds/archiveHeapWriter.hpp"
29 #include "cds/cds_globals.hpp"
30 #include "cds/cdsAccess.hpp"
31 #include "cds/cdsConfig.hpp"
32 #include "cds/cdsProtectionDomain.hpp"
33 #include "cds/cds_globals.hpp"
34 #include "cds/classListParser.hpp"
35 #include "cds/classListWriter.hpp"
36 #include "cds/classPreinitializer.hpp"
37 #include "cds/classPrelinker.hpp"
38 #include "cds/classPreloader.hpp"
39 #include "cds/cppVtables.hpp"
40 #include "cds/dumpAllocStats.hpp"
41 #include "cds/dynamicArchive.hpp"
42 #include "cds/filemap.hpp"
43 #include "cds/finalImageRecipes.hpp"
44 #include "cds/heapShared.hpp"
45 #include "cds/lambdaFormInvokers.hpp"
46 #include "cds/metaspaceShared.hpp"
47 #include "classfile/classLoaderDataGraph.hpp"
48 #include "classfile/classLoaderDataShared.hpp"
49 #include "classfile/classLoaderExt.hpp"
50 #include "classfile/javaClasses.inline.hpp"
51 #include "classfile/loaderConstraints.hpp"
52 #include "classfile/modules.hpp"
53 #include "classfile/placeholders.hpp"
54 #include "classfile/stringTable.hpp"
55 #include "classfile/symbolTable.hpp"
56 #include "classfile/systemDictionary.hpp"
57 #include "classfile/systemDictionaryShared.hpp"
58 #include "classfile/vmClasses.hpp"
59 #include "classfile/vmSymbols.hpp"
60 #include "code/codeCache.hpp"
61 #include "code/SCCache.hpp"
62 #include "compiler/compileBroker.hpp"
63 #include "compiler/precompiler.hpp"
64 #include "gc/shared/gcVMOperations.hpp"
65 #include "interpreter/bytecodeStream.hpp"
66 #include "interpreter/bytecodes.hpp"
67 #include "jvm_io.h"
68 #include "logging/log.hpp"
69 #include "logging/logMessage.hpp"
70 #include "logging/logStream.hpp"
71 #include "memory/metaspace.hpp"
72 #include "memory/metaspaceClosure.hpp"
73 #include "memory/resourceArea.hpp"
74 #include "memory/universe.hpp"
75 #include "nmt/memTracker.hpp"
76 #include "oops/compressedKlass.hpp"
77 #include "oops/instanceMirrorKlass.hpp"
78 #include "oops/klass.inline.hpp"
79 #include "oops/method.inline.hpp"
80 #include "oops/objArrayOop.hpp"
81 #include "oops/oop.inline.hpp"
82 #include "oops/oopHandle.hpp"
83 #include "oops/trainingData.hpp"
84 #include "prims/jvmtiExport.hpp"
85 #include "prims/whitebox.hpp"
86 #include "runtime/arguments.hpp"
87 #include "runtime/globals.hpp"
88 #include "runtime/globals_extension.hpp"
89 #include "runtime/handles.inline.hpp"
90 #include "runtime/javaCalls.hpp"
91 #include "runtime/os.inline.hpp"
92 #include "runtime/safepointVerifiers.hpp"
93 #include "runtime/sharedRuntime.hpp"
94 #include "runtime/vmOperations.hpp"
95 #include "runtime/vmThread.hpp"
96 #include "sanitizers/leak.hpp"
97 #include "utilities/align.hpp"
98 #include "utilities/bitMap.inline.hpp"
99 #include "utilities/defaultStream.hpp"
100 #include "utilities/ostream.hpp"
101 #include "utilities/resourceHash.hpp"
102
103 ReservedSpace MetaspaceShared::_symbol_rs;
104 VirtualSpace MetaspaceShared::_symbol_vs;
105 bool MetaspaceShared::_archive_loading_failed = false;
106 bool MetaspaceShared::_remapped_readwrite = false;
107 void* MetaspaceShared::_shared_metaspace_static_top = nullptr;
108 intx MetaspaceShared::_relocation_delta;
109 char* MetaspaceShared::_requested_base_address;
110 Array<Method*>* MetaspaceShared::_archived_method_handle_intrinsics = nullptr;
111 bool MetaspaceShared::_use_optimized_module_handling = true;
112
113 // The CDS archive is divided into the following regions:
114 // rw - read-write metadata
115 // ro - read-only metadata and read-only tables
116 // hp - heap region
117 // bm - bitmap for relocating the above 7 regions.
118 //
119 // The rw and ro regions are linearly allocated, in the order of rw->ro.
120 // These regions are aligned with MetaspaceShared::core_region_alignment().
121 //
122 // These 2 regions are populated in the following steps:
123 // [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
124 // temporarily allocated outside of the shared regions.
125 // [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
126 // [2] C++ vtables are copied into the rw region.
127 // [3] ArchiveBuilder copies RW metadata into the rw region.
128 // [4] ArchiveBuilder copies RO metadata into the ro region.
129 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
130 // are copied into the ro region as read-only tables.
253 err = "invalid for this platform";
254 } else {
255 return aligned_base;
256 }
257
258 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
259 p2i((void*)SharedBaseAddress), err,
260 p2i((void*)Arguments::default_SharedBaseAddress()));
261
262 specified_base = (char*)Arguments::default_SharedBaseAddress();
263 aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
264
265 // Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
266 assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
267 assert(shared_base_valid(aligned_base), "Sanity");
268 return aligned_base;
269 }
270
271 void MetaspaceShared::initialize_for_static_dump() {
272 assert(CDSConfig::is_dumping_static_archive(), "sanity");
273
274 if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_final_static_archive()) {
275 if (!((UseG1GC || UseParallelGC || UseSerialGC) && UseCompressedClassPointers)) {
276 vm_exit_during_initialization("Cannot create the CacheDataStore",
277 "UseCompressedClassPointers must be enabled, and collector must be G1, Parallel, or Serial");
278 }
279 }
280
281 log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
282 // The max allowed size for CDS archive. We use this to limit SharedBaseAddress
283 // to avoid address space wrap around.
284 size_t cds_max;
285 const size_t reserve_alignment = core_region_alignment();
286
287 #ifdef _LP64
288 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
289 cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
290 #else
291 // We don't support archives larger than 256MB on 32-bit due to limited
292 // virtual address space.
293 cds_max = align_down(256*M, reserve_alignment);
294 #endif
295
296 _requested_base_address = compute_shared_base(cds_max);
297 SharedBaseAddress = (size_t)_requested_base_address;
298
299 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
300 _symbol_rs = ReservedSpace(symbol_rs_size);
310 if (CDSConfig::is_using_archive()) {
311 int size = FileMapInfo::get_number_of_shared_paths();
312 if (size > 0) {
313 CDSProtectionDomain::allocate_shared_data_arrays(size, CHECK);
314 if (!CDSConfig::is_dumping_dynamic_archive()) {
315 FileMapInfo* info;
316 if (FileMapInfo::dynamic_info() == nullptr) {
317 info = FileMapInfo::current_info();
318 } else {
319 info = FileMapInfo::dynamic_info();
320 }
321 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
322 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
323 }
324 }
325 }
326 }
327
328 static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = nullptr;
329 static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = nullptr;
330 static GrowableArray<Method*>* _method_handle_intrinsics = nullptr;
331
332 void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
333 _extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
334 _extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
335
336 HashtableTextDump reader(filename);
337 reader.check_version("VERSION: 1.0");
338
339 while (reader.remain() > 0) {
340 int utf8_length;
341 int prefix_type = reader.scan_prefix(&utf8_length);
342 ResourceMark rm(current);
343 if (utf8_length == 0x7fffffff) {
344 // buf_len will overflown 32-bit value.
345 log_error(cds)("string length too large: %d", utf8_length);
346 MetaspaceShared::unrecoverable_loading_error();
347 }
348 int buf_len = utf8_length+1;
349 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
350 reader.get_utf8(utf8_buffer, utf8_length);
361 if (HAS_PENDING_EXCEPTION) {
362 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
363 reader.last_line_no(), utf8_length);
364 CLEAR_PENDING_EXCEPTION;
365 } else {
366 #if INCLUDE_CDS_JAVA_HEAP
367 if (ArchiveHeapWriter::is_string_too_large_to_archive(str)) {
368 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
369 reader.last_line_no(), utf8_length);
370 continue;
371 }
372 // Make sure this string is included in the dumped interned string table.
373 assert(str != nullptr, "must succeed");
374 _extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
375 #endif
376 }
377 }
378 }
379 }
380
381 void MetaspaceShared::make_method_handle_intrinsics_shareable() {
382 for (int i = 0; i < _method_handle_intrinsics->length(); i++) {
383 Method* m = ArchiveBuilder::current()->get_buffered_addr(_method_handle_intrinsics->at(i));
384 m->remove_unshareable_info();
385 // Each method has its own constant pool (which is distinct from m->method_holder()->constants());
386 m->constants()->remove_unshareable_info();
387 }
388 }
389
390 void MetaspaceShared::write_method_handle_intrinsics() {
391 int len = _method_handle_intrinsics->length();
392 _archived_method_handle_intrinsics = ArchiveBuilder::new_ro_array<Method*>(len);
393 for (int i = 0; i < len; i++) {
394 ArchiveBuilder::current()->write_pointer_in_buffer(_archived_method_handle_intrinsics->adr_at(i),
395 _method_handle_intrinsics->at(i));
396 }
397 log_info(cds)("Archived %d method handle intrinsics", len);
398 }
399
400 // Read/write a data stream for restoring/preserving metadata pointers and
401 // miscellaneous data from/to the shared archive file.
402
403 void MetaspaceShared::serialize(SerializeClosure* soc) {
404 int tag = 0;
405 soc->do_tag(--tag);
406
407 // Verify the sizes of various metadata in the system.
408 soc->do_tag(sizeof(Method));
409 soc->do_tag(sizeof(ConstMethod));
410 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
411 soc->do_tag(sizeof(ConstantPool));
412 soc->do_tag(sizeof(ConstantPoolCache));
413 soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
414 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
415 soc->do_tag(sizeof(Symbol));
416
417 // Need to do this first, as subsequent steps may call virtual functions
418 // in archived Metadata objects.
419 CppVtables::serialize(soc);
420 soc->do_tag(--tag);
421
422 // Dump/restore miscellaneous metadata.
423 JavaClasses::serialize_offsets(soc);
424 HeapShared::serialize_misc_info(soc);
425 Universe::serialize(soc);
426 soc->do_tag(--tag);
427
428 // Dump/restore references to commonly used names and signatures.
429 vmSymbols::serialize(soc);
430 soc->do_tag(--tag);
431
432 // Dump/restore the symbol/string/subgraph_info tables
433 SymbolTable::serialize_shared_table_header(soc);
434 StringTable::serialize_shared_table_header(soc);
435 HeapShared::serialize_tables(soc);
436 SystemDictionaryShared::serialize_dictionary_headers(soc);
437 ClassPreloader::serialize(soc, true);
438 FinalImageRecipes::serialize(soc, true);
439 TrainingData::serialize_training_data(soc);
440 InstanceMirrorKlass::serialize_offsets(soc);
441
442 // Dump/restore well known classes (pointers)
443 SystemDictionaryShared::serialize_vm_classes(soc);
444 soc->do_tag(--tag);
445
446 CDS_JAVA_HEAP_ONLY(Modules::serialize(soc);)
447 CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
448 soc->do_ptr((void**)&_archived_method_handle_intrinsics);
449
450
451 LambdaFormInvokers::serialize(soc);
452 soc->do_tag(666);
453 }
454
455 static void rewrite_nofast_bytecode(const methodHandle& method) {
456 BytecodeStream bcs(method);
457 while (!bcs.is_last_bytecode()) {
458 Bytecodes::Code opcode = bcs.next();
459 switch (opcode) {
460 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
461 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
462 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
463 case Bytecodes::_iload: {
464 if (!bcs.is_wide()) {
465 *bcs.bcp() = Bytecodes::_nofast_iload;
466 }
467 break;
468 }
469 default: break;
505 VM_Operation(), _heap_info(), _map_info(nullptr), _builder(b) {}
506
507 bool skip_operation() const { return false; }
508
509 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
510 ArchiveHeapInfo* heap_info() { return &_heap_info; }
511 FileMapInfo* map_info() const { return _map_info; }
512 void doit(); // outline because gdb sucks
513 bool allow_nested_vm_operations() const { return true; }
514 }; // class VM_PopulateDumpSharedSpace
515
516 class StaticArchiveBuilder : public ArchiveBuilder {
517 public:
518 StaticArchiveBuilder() : ArchiveBuilder() {}
519
520 virtual void iterate_roots(MetaspaceClosure* it) {
521 FileMapInfo::metaspace_pointers_do(it);
522 SystemDictionaryShared::dumptime_classes_do(it);
523 Universe::metaspace_pointers_do(it);
524 vmSymbols::metaspace_pointers_do(it);
525 TrainingData::iterate_roots(it);
526
527 // The above code should find all the symbols that are referenced by the
528 // archived classes. We just need to add the extra symbols which
529 // may not be used by any of the archived classes -- these are usually
530 // symbols that we anticipate to be used at run time, so we can store
531 // them in the RO region, to be shared across multiple processes.
532 if (_extra_symbols != nullptr) {
533 for (int i = 0; i < _extra_symbols->length(); i++) {
534 it->push(_extra_symbols->adr_at(i));
535 }
536 }
537
538 for (int i = 0; i < _method_handle_intrinsics->length(); i++) {
539 it->push(_method_handle_intrinsics->adr_at(i));
540 }
541 }
542 };
543
544 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
545 ArchiveBuilder::OtherROAllocMark mark;
546
547 SystemDictionaryShared::write_to_archive();
548 ClassPreloader::record_initiated_classes(true);
549 ClassPreloader::record_unregistered_classes();
550 TrainingData::dump_training_data();
551 MetaspaceShared::write_method_handle_intrinsics();
552
553 // Write lambform lines into archive
554 LambdaFormInvokers::dump_static_archive_invokers();
555 // Write module name into archive
556 CDS_JAVA_HEAP_ONLY(Modules::dump_main_module_name();)
557 // Write the other data to the output array.
558 DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
559 char* start = ro_region->top();
560 WriteClosure wc(ro_region);
561 MetaspaceShared::serialize(&wc);
562
563 return start;
564 }
565
566 void VM_PopulateDumpSharedSpace::doit() {
567 //guarantee(!CDSConfig::is_using_archive(), "We should not be using an archive when we dump");
568
569 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
570
571 FileMapInfo::check_nonempty_dir_in_shared_path_table();
572
573 NOT_PRODUCT(SystemDictionary::verify();)
574
575 // Block concurrent class unloading from changing the _dumptime_table
576 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
577
578 HeapShared::start_finding_archivable_hidden_classes();
579 SystemDictionaryShared::check_excluded_classes();
580 HeapShared::end_finding_archivable_hidden_classes();
581
582 _builder.gather_source_objs();
583 _builder.reserve_buffer();
584
585 CppVtables::dumptime_init(&_builder);
586
587 _builder.sort_metadata_objs();
588 _builder.dump_rw_metadata();
589 _builder.dump_ro_metadata();
590 _builder.relocate_metaspaceobj_embedded_pointers();
591
592 dump_java_heap_objects(_builder.klasses());
593 dump_shared_symbol_table(_builder.symbols());
594
595 {
596 ArchiveBuilder::OtherROAllocMark mark;
597 ClassPreloader::record_preloaded_classes(true);
598 if (CDSConfig::is_dumping_preimage_static_archive()) {
599 FinalImageRecipes::record_recipes();
600 }
601 }
602
603 log_info(cds)("Make classes shareable");
604 _builder.make_klasses_shareable();
605 MetaspaceShared::make_method_handle_intrinsics_shareable();
606
607 char* serialized_data = dump_read_only_tables();
608
609 SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
610
611 log_info(cds)("Adjust method info dictionary");
612 SystemDictionaryShared::adjust_method_info_dictionary();
613
614 log_info(cds)("Make training data shareable");
615 _builder.make_training_data_shareable();
616
617 // The vtable clones contain addresses of the current process.
618 // We don't want to write these addresses into the archive.
619 CppVtables::zero_archived_vtables();
620
621 // Write the archive file
622 const char* static_archive;
623 if (CDSConfig::is_dumping_final_static_archive()) {
624 static_archive = CacheDataStore;
625 assert(FileMapInfo::current_info() != nullptr, "sanity");
626 delete FileMapInfo::current_info();
627 } else {
628 static_archive = CDSConfig::static_archive_path();
629 }
630 assert(static_archive != nullptr, "SharedArchiveFile not set?");
631 _map_info = new FileMapInfo(static_archive, true);
632 _map_info->populate_header(MetaspaceShared::core_region_alignment());
633 _map_info->set_serialized_data(serialized_data);
634 _map_info->set_cloned_vtables(CppVtables::vtables_serialized_base());
635 }
636
637 class CollectCLDClosure : public CLDClosure {
638 GrowableArray<ClassLoaderData*> _loaded_cld;
639 GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
640 Thread* _current_thread;
641 public:
642 CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
643 ~CollectCLDClosure() {
644 for (int i = 0; i < _loaded_cld_handles.length(); i++) {
645 _loaded_cld_handles.at(i).release(Universe::vm_global());
646 }
647 }
648 void do_cld(ClassLoaderData* cld) {
649 assert(cld->is_alive(), "must be");
650 _loaded_cld.append(cld);
651 _loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder()));
652 }
653
654 int nof_cld() const { return _loaded_cld.length(); }
655 ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
656 };
657
658 // Check if we can eagerly link this class at dump time, so we can avoid the
659 // runtime linking overhead (especially verification)
660 bool MetaspaceShared::may_be_eagerly_linked(InstanceKlass* ik) {
661 if (CDSConfig::preserve_all_dumptime_verification_states(ik)) {
662 assert(ik->can_be_verified_at_dumptime(), "sanity");
663 }
664 if (!ik->can_be_verified_at_dumptime()) {
665 // For old classes, try to leave them in the unlinked state, so
666 // we can still store them in the archive. They must be
667 // linked/verified at runtime.
668 return false;
669 }
670
671 if (CDSConfig::is_dumping_dynamic_archive() && ik->is_shared_unregistered_class()) {
672 // Linking of unregistered classes at this stage may cause more
673 // classes to be resolved, resulting in calls to ClassLoader.loadClass()
674 // that may not be expected by custom class loaders.
675 //
676 // It's OK to do this for the built-in loaders as we know they can
677 // tolerate this.
678 return false;
679 }
680 return true;
681 }
682
683 void MetaspaceShared::link_shared_classes(bool jcmd_request, TRAPS) {
684 ClassPreloader::initialize();
685 ClassPrelinker::initialize();
686
687 if (!jcmd_request && !CDSConfig::is_dumping_dynamic_archive()
688 && !CDSConfig::is_dumping_preimage_static_archive()
689 && !CDSConfig::is_dumping_final_static_archive()) {
690 // If we have regenerated invoker classes in the dynamic archive,
691 // they will conflict with the resolved CONSTANT_Klass references that are stored
692 // in the static archive. This is not easy to handle. Let's disable
693 // it for dynamic archive for now.
694 LambdaFormInvokers::regenerate_holder_classes(CHECK);
695 }
696
697 // Collect all loaded ClassLoaderData.
698 CollectCLDClosure collect_cld(THREAD);
699 {
700 // ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
701 // We cannot link the classes while holding this lock (or else we may run into deadlock).
702 // Therefore, we need to first collect all the CLDs, and then link their classes after
703 // releasing the lock.
704 MutexLocker lock(ClassLoaderDataGraph_lock);
705 ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
706 }
707
708 while (true) {
709 bool has_linked = false;
710 for (int i = 0; i < collect_cld.nof_cld(); i++) {
711 ClassLoaderData* cld = collect_cld.cld_at(i);
712 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
713 if (klass->is_instance_klass()) {
714 InstanceKlass* ik = InstanceKlass::cast(klass);
715 if (may_be_eagerly_linked(ik)) {
716 has_linked |= try_link_class(THREAD, ik);
717 }
718 if (CDSConfig::is_dumping_heap() && ik->is_linked() && !ik->is_initialized()) {
719 ClassPreinitializer::maybe_preinit_class(ik, CHECK);
720 }
721 }
722 }
723 }
724
725 if (!has_linked) {
726 break;
727 }
728 // Class linking includes verification which may load more classes.
729 // Keep scanning until we have linked no more classes.
730 }
731
732 // Resolve constant pool entries -- we don't load any new classes during this stage
733 for (int i = 0; i < collect_cld.nof_cld(); i++) {
734 ClassLoaderData* cld = collect_cld.cld_at(i);
735 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
736 if (klass->is_instance_klass()) {
737 InstanceKlass* ik = InstanceKlass::cast(klass);
738 ClassPrelinker::dumptime_resolve_constants(ik, CHECK);
739 if (CDSConfig::is_dumping_preimage_static_archive()) {
740 FinalImageRecipes::add_reflection_data_flags(ik, CHECK);
741 }
742 }
743 }
744 }
745
746 if (CDSConfig::is_dumping_preimage_static_archive()) {
747 // Do this after all classes are verified by the above loop.
748 // Any classes loaded from here on will be automatically excluded, so
749 // there's no need to force verification or resolve CP entries.
750 RecordTraining = false;
751 SystemDictionaryShared::ignore_new_classes();
752 LambdaFormInvokers::regenerate_holder_classes(CHECK);
753 RecordTraining = true;
754 }
755
756 if (CDSConfig::is_dumping_final_static_archive()) {
757 FinalImageRecipes::apply_recipes(CHECK);
758 }
759 }
760
761 void MetaspaceShared::prepare_for_dumping() {
762 assert(CDSConfig::is_dumping_archive(), "sanity");
763 CDSConfig::check_unsupported_dumping_module_options();
764 ClassLoader::initialize_shared_path(JavaThread::current());
765 }
766
767 // Preload classes from a list, populate the shared spaces and dump to a
768 // file.
769 void MetaspaceShared::preload_and_dump(TRAPS) {
770 ResourceMark rm(THREAD);
771 HandleMark hm(THREAD);
772
773 if (CDSConfig::is_dumping_final_static_archive() && PrintTrainingInfo) {
774 tty->print_cr("==================== archived_training_data ** before dumping ====================");
775 TrainingData::print_archived_training_data_on(tty);
776 }
777
778 StaticArchiveBuilder builder;
779 preload_and_dump_impl(builder, THREAD);
780 if (HAS_PENDING_EXCEPTION) {
781 if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
782 log_error(cds)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
783 SIZE_FORMAT "M", MaxHeapSize/M);
784 MetaspaceShared::writing_error();
785 } else {
786 log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
787 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
788 MetaspaceShared::writing_error("Unexpected exception, use -Xlog:cds,exceptions=trace for detail");
789 }
790 }
791 }
792
793 #if INCLUDE_CDS_JAVA_HEAP && defined(_LP64)
794 void MetaspaceShared::adjust_heap_sizes_for_dumping() {
795 if (!CDSConfig::is_dumping_heap() || UseCompressedOops) {
796 return;
797 }
860 ClassListParser::_parse_all, CHECK);
861 }
862 if (classlist_path != default_classlist) {
863 struct stat statbuf;
864 if (os::stat(default_classlist, &statbuf) == 0) {
865 // File exists, let's use it.
866 ClassListParser::parse_classlist(default_classlist,
867 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
868 }
869 }
870
871 // Exercise the manifest processing code to ensure classes used by CDS at runtime
872 // are always archived
873 const char* dummy = "Manifest-Version: 1.0\n";
874 CDSProtectionDomain::create_jar_manifest(dummy, strlen(dummy), CHECK);
875
876 log_info(cds)("Loading classes to share: done.");
877 }
878
879 void MetaspaceShared::preload_and_dump_impl(StaticArchiveBuilder& builder, TRAPS) {
880 if (CDSConfig::is_dumping_classic_static_archive()) {
881 // We are running with -Xshare:dump
882 preload_classes(CHECK);
883
884 if (SharedArchiveConfigFile) {
885 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
886 read_extra_data(THREAD, SharedArchiveConfigFile);
887 log_info(cds)("Reading extra data: done.");
888 }
889 }
890
891 if (CDSConfig::is_dumping_preimage_static_archive()) {
892 log_info(cds)("Reading lambda form invokers of in JDK default classlist ...");
893 char default_classlist[JVM_MAXPATHLEN];
894 get_default_classlist(default_classlist, sizeof(default_classlist));
895 struct stat statbuf;
896 if (os::stat(default_classlist, &statbuf) == 0) {
897 ClassListParser::parse_classlist(default_classlist,
898 ClassListParser::_parse_lambda_forms_invokers_only, CHECK);
899 }
900 }
901
902 #if INCLUDE_CDS_JAVA_HEAP
903 if (CDSConfig::is_dumping_invokedynamic()) {
904 // We also assume no other Java threads are running
905 // This makes sure that the MethodType and MethodTypeForm objects are clean.
906 JavaValue result(T_VOID);
907 JavaCalls::call_static(&result, vmClasses::MethodType_klass(),
908 vmSymbols::dumpSharedArchive(),
909 vmSymbols::void_method_signature(),
910 CHECK);
911 }
912 #endif
913
914 // Rewrite and link classes
915 log_info(cds)("Rewriting and linking classes ...");
916 // Link any classes which got missed. This would happen if we have loaded classes that
917 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
918 // fails verification, all other interfaces that were not specified in the classlist but
919 // are implemented by K are not verified.
920 link_shared_classes(false/*not from jcmd*/, CHECK);
921 log_info(cds)("Rewriting and linking classes: done");
922
923 if (CDSConfig::is_dumping_final_static_archive()) {
924 assert(RecordTraining == false, "must be");
925 RecordTraining = true;
926 }
927
928 TrainingData::init_dumptime_table(CHECK); // captures TrainingDataSetLocker
929
930 _method_handle_intrinsics = new (mtClassShared) GrowableArray<Method*>(256, mtClassShared);
931 SystemDictionary::get_all_method_handle_intrinsics(_method_handle_intrinsics);
932
933 #if INCLUDE_CDS_JAVA_HEAP
934 if (CDSConfig::is_dumping_heap()) {
935 if (!HeapShared::is_archived_boot_layer_available(THREAD)) {
936 log_info(cds)("archivedBootLayer not available, disabling full module graph");
937 CDSConfig::stop_dumping_full_module_graph();
938 }
939 HeapShared::init_for_dumping(CHECK);
940 ArchiveHeapWriter::init();
941 if (CDSConfig::is_dumping_full_module_graph()) {
942 HeapShared::reset_archived_object_states(CHECK);
943 }
944
945 if (ArchiveLoaderLookupCache) {
946 SystemDictionaryShared::create_loader_positive_lookup_cache(CHECK);
947 }
948
949 // Do this at the very end, when no Java code will be executed. Otherwise
950 // some new strings may be added to the intern table.
951 StringTable::allocate_shared_strings_array(CHECK);
952 }
953 #endif
954
955 VM_PopulateDumpSharedSpace op(builder);
956 VMThread::execute(&op);
957 FileMapInfo* mapinfo = op.map_info();
958 ArchiveHeapInfo* heap_info = op.heap_info();
959 bool status;
960 if (CDSConfig::is_dumping_preimage_static_archive()) {
961 if ((status = write_static_archive(&builder, mapinfo, heap_info))) {
962 fork_and_dump_final_static_archive();
963 }
964 } else if (CDSConfig::is_dumping_final_static_archive()) {
965 RecordTraining = false;
966 if (StoreCachedCode && CachedCodeFile != nullptr) { // FIXME: new workflow -- remove the CachedCodeFile flag
967 if (log_is_enabled(Info, cds, jit)) {
968 CDSAccess::test_heap_access_api();
969 }
970
971 // We have just created the final image. Let's run the AOT compiler
972 if (PrintTrainingInfo) {
973 tty->print_cr("==================== archived_training_data ** after dumping ====================");
974 TrainingData::print_archived_training_data_on(tty);
975 }
976
977 CDSConfig::enable_dumping_cached_code();
978 {
979 builder.start_cc_region();
980 Precompiler::compile_cached_code(&builder, CHECK);
981 builder.end_cc_region();
982 }
983 CDSConfig::disable_dumping_cached_code();
984
985 SCCache::close(); // Write final data and close archive
986 }
987 status = write_static_archive(&builder, mapinfo, heap_info);
988 } else {
989 status = write_static_archive(&builder, mapinfo, heap_info);
990 }
991
992 if (!status) {
993 THROW_MSG(vmSymbols::java_io_IOException(), "Encountered error while dumping");
994 }
995 }
996
997 bool MetaspaceShared::write_static_archive(ArchiveBuilder* builder, FileMapInfo* map_info, ArchiveHeapInfo* heap_info) {
998 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
999 // without runtime relocation.
1000 builder->relocate_to_requested();
1001
1002 map_info->open_for_write();
1003 if (!map_info->is_open()) {
1004 return false;
1005 }
1006 builder->write_archive(map_info, heap_info);
1007
1008 if (AllowArchivingWithJavaAgent) {
1009 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1010 "for testing purposes only and should not be used in a production environment");
1011 }
1012 return true;
1013 }
1014
1015 static void print_java_launcher(outputStream* st) {
1016 st->print("%s%sbin%sjava", Arguments::get_java_home(), os::file_separator(), os::file_separator());
1017 }
1018
1019 static void print_vm_arguments(outputStream* st) {
1020 const char* cp = Arguments::get_appclasspath();
1021 if (cp != nullptr && strlen(cp) > 0 && strcmp(cp, ".") != 0) {
1022 st->print(" -cp "); st->print_raw(cp);
1023 }
1024 for (int i = 0; i < Arguments::num_jvm_flags(); i++) {
1025 st->print(" %s", Arguments::jvm_flags_array()[i]);
1026 }
1027 for (int i = 0; i < Arguments::num_jvm_args(); i++) {
1028 st->print(" %s", Arguments::jvm_args_array()[i]);
1029 }
1030 }
1031
1032 void MetaspaceShared::fork_and_dump_final_static_archive() {
1033 assert(CDSConfig::is_dumping_preimage_static_archive(), "sanity");
1034
1035 ResourceMark rm;
1036 stringStream ss;
1037 print_java_launcher(&ss);
1038 print_vm_arguments(&ss);
1039 ss.print(" -XX:CDSPreimage=%s", SharedArchiveFile);
1040
1041 const char* cmd = ss.freeze();
1042 if (CDSManualFinalImage) {
1043 tty->print_cr("-XX:+CDSManualFinalImage is specified");
1044 tty->print_cr("Please manually execute the following command to create the final CDS image:");
1045 tty->print(" "); tty->print_raw_cr(cmd);
1046
1047 // The following is useful if the dumping was trigger by a script that builds
1048 // a complex command-line.
1049 tty->print_cr("Note: to recreate the preimage only:");
1050 tty->print_cr(" rm -f %s", CacheDataStore);
1051 tty->print(" ");
1052 print_java_launcher(tty);
1053 print_vm_arguments(tty);
1054 if (Arguments::java_command() != nullptr) {
1055 tty->print(" %s", Arguments::java_command());
1056 }
1057 tty->cr();
1058 } else {
1059 // FIXME: space characters are not properly quoated. E.g.,
1060 // java -Dfoo='a b c' HelloWorld
1061 log_info(cds)("Launching child process to create final CDS image:");
1062 log_info(cds)(" %s", cmd);
1063 int status = os::fork_and_exec(cmd);
1064 if (status != 0) {
1065 log_error(cds)("Child process finished; status = %d", status);
1066 log_error(cds)("To reproduce the error");
1067 ResourceMark rm;
1068 LogStream ls(Log(cds)::error());
1069 ls.print(" "); ls.print_raw_cr(cmd);
1070
1071 // The following is useful if the dumping was trigger by a script that builds
1072 // a complex command-line.
1073 ls.print_cr("Note: to recreate the preimage only:");
1074 ls.print_cr(" rm -f %s", CacheDataStore);
1075 ls.print(" ");
1076 print_java_launcher(&ls);
1077 print_vm_arguments(&ls);
1078 ls.print(" -XX:+UnlockDiagnosticVMOptions -XX:+CDSManualFinalImage");
1079 if (Arguments::java_command() != nullptr) {
1080 ls.print(" %s", Arguments::java_command());
1081 }
1082 ls.cr();
1083
1084 vm_direct_exit(status);
1085 } else {
1086 log_info(cds)("Child process finished; status = %d", status);
1087 status = remove(SharedArchiveFile);
1088 if (status != 0) {
1089 log_error(cds)("Failed to remove CDSPreimage file %s", SharedArchiveFile);
1090 } else {
1091 log_info(cds)("Removed CDSPreimage file %s", SharedArchiveFile);
1092 }
1093 }
1094 }
1095 }
1096
1097 // Returns true if the class's status has changed.
1098 bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
1099 ExceptionMark em(current);
1100 JavaThread* THREAD = current; // For exception macros.
1101 assert(CDSConfig::is_dumping_archive(), "sanity");
1102
1103 if (ik->is_shared() && !CDSConfig::is_dumping_final_static_archive()) {
1104 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1105 return false;
1106 }
1107
1108 if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
1109 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1110 bool saved = BytecodeVerificationLocal;
1111 if (ik->is_shared_unregistered_class() && ik->class_loader() == nullptr) {
1112 // The verification decision is based on BytecodeVerificationRemote
1113 // for non-system classes. Since we are using the null classloader
1114 // to load non-system classes for customized class loaders during dumping,
1115 // we need to temporarily change BytecodeVerificationLocal to be the same as
1116 // BytecodeVerificationRemote. Note this can cause the parent system
1117 // classes also being verified. The extra overhead is acceptable during
1118 // dumping.
1119 BytecodeVerificationLocal = BytecodeVerificationRemote;
1120 }
1121 ik->link_class(THREAD);
1122 if (HAS_PENDING_EXCEPTION) {
1123 ResourceMark rm(THREAD);
1124 log_warning(cds)("Preload Warning: Verification failed for %s",
1125 ik->external_name());
1126 CLEAR_PENDING_EXCEPTION;
1127 SystemDictionaryShared::set_class_has_failed_verification(ik);
1128 }
1129 ik->compute_has_loops_flag_for_methods();
1130 BytecodeVerificationLocal = saved;
1131 return true;
1132 } else {
1133 return false;
1134 }
1135 }
1136
1137 #if INCLUDE_CDS_JAVA_HEAP
1138 void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
1139 if(!HeapShared::can_write()) {
1140 if (!CDSConfig::is_dumping_preimage_static_archive()) {
1141 log_info(cds)(
1142 "Archived java heap is not supported as UseG1GC "
1143 "and UseCompressedClassPointers are required."
1144 "Current settings: UseG1GC=%s, UseCompressedClassPointers=%s.",
1145 BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedClassPointers));
1146 }
1147 return;
1148 }
1149 // Find all the interned strings that should be dumped.
1150 int i;
1151 for (i = 0; i < klasses->length(); i++) {
1152 Klass* k = klasses->at(i);
1153 if (k->is_instance_klass()) {
1154 InstanceKlass* ik = InstanceKlass::cast(k);
1155 if (ik->is_linked()) {
1156 ik->constants()->add_dumped_interned_strings();
1157 }
1158 }
1159 }
1160 if (_extra_interned_strings != nullptr) {
1161 for (i = 0; i < _extra_interned_strings->length(); i ++) {
1162 OopHandle string = _extra_interned_strings->at(i);
1163 HeapShared::add_to_dumped_interned_strings(string.resolve());
1164 }
1165 }
1166
1209 // This function is called when the JVM is unable to write the specified CDS archive due to an
1210 // unrecoverable error.
1211 void MetaspaceShared::unrecoverable_writing_error(const char* message) {
1212 writing_error(message);
1213 vm_direct_exit(1);
1214 }
1215
1216 // This function is called when the JVM is unable to write the specified CDS archive due to a
1217 // an error. The error will be propagated
1218 void MetaspaceShared::writing_error(const char* message) {
1219 log_error(cds)("An error has occurred while writing the shared archive file.");
1220 if (message != nullptr) {
1221 log_error(cds)("%s", message);
1222 }
1223 }
1224
1225 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
1226 assert(CDSConfig::is_using_archive(), "Must be called when UseSharedSpaces is enabled");
1227 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
1228
1229 FileMapInfo* static_mapinfo = FileMapInfo::current_info();
1230 FileMapInfo* dynamic_mapinfo = nullptr;
1231
1232 if (static_mapinfo != nullptr) {
1233 log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
1234 dynamic_mapinfo = open_dynamic_archive();
1235
1236 // First try to map at the requested address
1237 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
1238 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
1239 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
1240 // by the OS.
1241 log_info(cds)("Try to map archive(s) at an alternative address");
1242 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
1243 }
1244 }
1245
1246 if (result == MAP_ARCHIVE_SUCCESS) {
1247 bool dynamic_mapped = (dynamic_mapinfo != nullptr && dynamic_mapinfo->is_mapped());
1248 char* cds_base = static_mapinfo->mapped_base();
1249 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
1256 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
1257 // turn AutoCreateSharedArchive off if successfully mapped
1258 AutoCreateSharedArchive = false;
1259 } else {
1260 FileMapInfo::set_shared_path_table(static_mapinfo);
1261 }
1262 } else {
1263 set_shared_metaspace_range(nullptr, nullptr, nullptr);
1264 if (CDSConfig::is_dumping_dynamic_archive()) {
1265 log_warning(cds)("-XX:ArchiveClassesAtExit is unsupported when base CDS archive is not loaded. Run with -Xlog:cds for more info.");
1266 }
1267 UseSharedSpaces = false;
1268 // The base archive cannot be mapped. We cannot dump the dynamic shared archive.
1269 AutoCreateSharedArchive = false;
1270 CDSConfig::disable_dumping_dynamic_archive();
1271 log_info(cds)("Unable to map shared spaces");
1272 if (PrintSharedArchiveAndExit) {
1273 MetaspaceShared::unrecoverable_loading_error("Unable to use shared archive.");
1274 } else if (RequireSharedSpaces) {
1275 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1276 } else if (CDSConfig::is_dumping_final_static_archive()) {
1277 assert(CDSPreimage != nullptr, "must be");
1278 log_error(cds)("Unable to map shared spaces for CDSPreimage = %s", CDSPreimage);
1279 MetaspaceShared::unrecoverable_loading_error();
1280 }
1281 }
1282
1283 // If mapping failed and -XShare:on, the vm should exit
1284 bool has_failed = false;
1285 if (static_mapinfo != nullptr && !static_mapinfo->is_mapped()) {
1286 has_failed = true;
1287 delete static_mapinfo;
1288 }
1289 if (dynamic_mapinfo != nullptr && !dynamic_mapinfo->is_mapped()) {
1290 has_failed = true;
1291 delete dynamic_mapinfo;
1292 }
1293 if (RequireSharedSpaces && has_failed) {
1294 // static archive mapped but dynamic archive failed
1295 MetaspaceShared::unrecoverable_loading_error("Unable to map shared spaces");
1296 }
1297 }
1298
1299 // This is called very early at VM start up to get the size of the cached_code region, which
1300 // is used in CodeCache::initialize_heaps()
1301 void MetaspaceShared::open_static_archive() {
1302 if (!UseSharedSpaces) {
1303 return;
1304 }
1305 const char* static_archive = CDSConfig::static_archive_path();
1306 assert(static_archive != nullptr, "sanity");
1307 FileMapInfo* mapinfo = new FileMapInfo(static_archive, true);
1308 if (!mapinfo->initialize()) {
1309 delete(mapinfo);
1310 } else {
1311 FileMapRegion* r = mapinfo->region_at(MetaspaceShared::cc);
1312 CDSAccess::set_cached_code_size(r->used());
1313 }
1314 }
1315
1316 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
1317 if (CDSConfig::is_dumping_dynamic_archive()) {
1318 return nullptr;
1319 }
1320 const char* dynamic_archive = CDSConfig::dynamic_archive_path();
1321 if (dynamic_archive == nullptr) {
1322 return nullptr;
1323 }
1324
1325 FileMapInfo* mapinfo = new FileMapInfo(dynamic_archive, false);
1326 if (!mapinfo->initialize()) {
1327 delete(mapinfo);
1328 if (RequireSharedSpaces) {
1329 MetaspaceShared::unrecoverable_loading_error("Failed to initialize dynamic archive");
1330 }
1331 return nullptr;
1332 }
1333 return mapinfo;
1712 if (archive_space_rs.is_reserved()) {
1713 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1714 archive_space_rs.release();
1715 }
1716 if (class_space_rs.is_reserved()) {
1717 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1718 class_space_rs.release();
1719 }
1720 }
1721 }
1722
1723 static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1724 static int archive_regions_count = 2;
1725
1726 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1727 assert(CDSConfig::is_using_archive(), "must be runtime");
1728 if (mapinfo == nullptr) {
1729 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1730 }
1731
1732 if (!mapinfo->validate_leyden_config()) {
1733 return MAP_ARCHIVE_OTHER_FAILURE;
1734 }
1735
1736 mapinfo->set_is_mapped(false);
1737 if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1738 log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1739 " actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1740 return MAP_ARCHIVE_OTHER_FAILURE;
1741 }
1742
1743 MapArchiveResult result =
1744 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1745
1746 if (result != MAP_ARCHIVE_SUCCESS) {
1747 unmap_archive(mapinfo);
1748 return result;
1749 }
1750
1751 if (!mapinfo->validate_shared_path_table()) {
1752 unmap_archive(mapinfo);
1753 return MAP_ARCHIVE_OTHER_FAILURE;
1754 }
1755
1780 };
1781
1782 // Read the miscellaneous data from the shared file, and
1783 // serialize it out to its various destinations.
1784
1785 void MetaspaceShared::initialize_shared_spaces() {
1786 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1787
1788 // Verify various attributes of the archive, plus initialize the
1789 // shared string/symbol tables.
1790 char* buffer = static_mapinfo->serialized_data();
1791 intptr_t* array = (intptr_t*)buffer;
1792 ReadClosure rc(&array);
1793 serialize(&rc);
1794
1795 // Finish up archived heap initialization. These must be
1796 // done after ReadClosure.
1797 static_mapinfo->patch_heap_embedded_pointers();
1798 ArchiveHeapLoader::finish_initialization();
1799 Universe::load_archived_object_instances();
1800 SCCache::new_workflow_load_cache();
1801
1802 // Close the mapinfo file
1803 static_mapinfo->close();
1804
1805 static_mapinfo->unmap_region(MetaspaceShared::bm);
1806
1807 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1808 if (dynamic_mapinfo != nullptr) {
1809 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1810 ReadClosure rc(&buffer);
1811 ArchiveBuilder::serialize_dynamic_archivable_items(&rc);
1812 DynamicArchive::setup_array_klasses();
1813 dynamic_mapinfo->close();
1814 dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1815 }
1816
1817 // Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1818 if (CDSConfig::is_dumping_dynamic_archive()) {
1819 // Read stored LF format lines stored in static archive
1820 LambdaFormInvokers::read_static_archive_invokers();
1821 }
1822
1823 if (PrintSharedArchiveAndExit) {
1824 // Print archive names
1825 if (dynamic_mapinfo != nullptr) {
1826 tty->print_cr("\n\nBase archive name: %s", CDSConfig::static_archive_path());
1827 tty->print_cr("Base archive version %d", static_mapinfo->version());
1828 } else {
1829 tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1830 tty->print_cr("Static archive version %d", static_mapinfo->version());
1831 }
1832
1833 SystemDictionaryShared::print_shared_archive(tty);
1834 if (dynamic_mapinfo != nullptr) {
1835 tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1836 tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1837 SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1838 }
1839 TrainingData::print_archived_training_data_on(tty);
1840
1841 if (LoadCachedCode) {
1842 tty->print_cr("\n\nCached Code file: %s", CachedCodeFile);
1843 SCCache::print_on(tty);
1844 }
1845
1846 // collect shared symbols and strings
1847 CountSharedSymbols cl;
1848 SymbolTable::shared_symbols_do(&cl);
1849 tty->print_cr("Number of shared symbols: %d", cl.total());
1850 tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1851 tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1852 if (FileMapInfo::current_info() == nullptr || _archive_loading_failed) {
1853 tty->print_cr("archive is invalid");
1854 vm_exit(1);
1855 } else {
1856 tty->print_cr("archive is valid");
1857 vm_exit(0);
1858 }
1859 }
1860 }
1861
1862 // JVM/TI RedefineClasses() support:
1863 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1864 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
|