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 "jvm.h"
27 #include "classfile/classLoaderData.inline.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "classfile/systemDictionaryShared.hpp"
31 #include "logging/log.hpp"
32 #include "memory/metadataFactory.hpp"
33 #include "memory/metaspace.hpp"
34 #include "memory/metaspaceClosure.hpp"
35 #include "memory/metaspaceShared.hpp"
36 #include "memory/resourceArea.hpp"
37 #include "memory/dynamicArchive.hpp"
38 #include "oops/compressedOops.hpp"
39 #include "oops/objArrayKlass.hpp"
40 #include "prims/jvmtiRedefineClasses.hpp"
41 #include "runtime/handles.inline.hpp"
42 #include "runtime/os.inline.hpp"
43 #include "runtime/sharedRuntime.hpp"
44 #include "runtime/vmThread.hpp"
45 #include "runtime/vmOperations.hpp"
46 #include "utilities/bitMap.inline.hpp"
47
48 #ifndef O_BINARY // if defined (Win32) use binary files.
49 #define O_BINARY 0 // otherwise do nothing.
50 #endif
51
52 class DynamicArchiveBuilder : ResourceObj {
53 CHeapBitMap _ptrmap;
54 static unsigned my_hash(const address& a) {
55 return primitive_hash<address>(a);
56 }
57 static bool my_equals(const address& a0, const address& a1) {
58 return primitive_equals<address>(a0, a1);
59 }
60 typedef ResourceHashtable<
61 address, address,
62 DynamicArchiveBuilder::my_hash, // solaris compiler doesn't like: primitive_hash<address>
63 DynamicArchiveBuilder::my_equals, // solaris compiler doesn't like: primitive_equals<address>
64 16384, ResourceObj::C_HEAP> RelocationTable;
65 RelocationTable _new_loc_table;
66
67 intx _buffer_to_target_delta;
68
69 DumpRegion* _current_dump_space;
70
71 static size_t reserve_alignment() {
72 return Metaspace::reserve_alignment();
73 }
74
75 static const int _total_dump_regions = 3;
76 int _num_dump_regions_used;
77
78 public:
79 void mark_pointer(address* ptr_loc) {
80 if (is_in_buffer_space(ptr_loc)) {
81 size_t idx = pointer_delta(ptr_loc, _alloc_bottom, sizeof(address));
82 _ptrmap.set_bit(idx);
83 }
84 }
85
86 DumpRegion* current_dump_space() const {
87 return _current_dump_space;
88 }
89
90 bool is_in_buffer_space(address p) const {
91 return (_alloc_bottom <= p && p < (address)current_dump_space()->top());
92 }
93
94 template <typename T> bool is_in_target_space(T target_obj) const {
95 address buff_obj = address(target_obj) - _buffer_to_target_delta;
96 return is_in_buffer_space(buff_obj);
97 }
98
99 template <typename T> bool is_in_buffer_space(T obj) const {
100 return is_in_buffer_space(address(obj));
101 }
102
103 template <typename T> T to_target_no_check(T obj) const {
111
112 template <typename T> T get_new_loc(T obj) {
113 address* pp = _new_loc_table.get((address)obj);
114 if (pp == NULL) {
115 // Excluded klasses are not copied
116 return NULL;
117 } else {
118 return (T)*pp;
119 }
120 }
121
122 address get_new_loc(MetaspaceClosure::Ref* ref) {
123 return get_new_loc(ref->obj());
124 }
125
126 template <typename T> bool has_new_loc(T obj) {
127 address* pp = _new_loc_table.get((address)obj);
128 return pp != NULL;
129 }
130
131 protected:
132 enum FollowMode {
133 make_a_copy, point_to_it, set_to_null
134 };
135
136 public:
137 void copy(MetaspaceClosure::Ref* ref, bool read_only) {
138 int bytes = ref->size() * BytesPerWord;
139 address old_obj = ref->obj();
140 address new_obj = copy_impl(ref, read_only, bytes);
141
142 assert(new_obj != NULL, "must be");
143 assert(new_obj != old_obj, "must be");
144 bool isnew = _new_loc_table.put(old_obj, new_obj);
145 assert(isnew, "must be");
146 }
147
148 // Make a shallow copy of each eligible MetaspaceObj into the buffer.
149 class ShallowCopier: public UniqueMetaspaceClosure {
150 DynamicArchiveBuilder* _builder;
223 #ifdef ASSERT
224 if (new_obj == NULL) {
225 if (orig_ref->msotype() == MetaspaceObj::ClassType) {
226 Klass* k = (Klass*)orig_obj;
227 assert(k->is_instance_klass() &&
228 SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k)),
229 "orig_obj must be excluded Class");
230 }
231 }
232 #endif
233
234 log_debug(cds, dynamic)("Relocating " PTR_FORMAT " %s", p2i(new_obj),
235 MetaspaceObj::type_name(orig_ref->msotype()));
236 if (new_obj != NULL) {
237 EmbeddedRefUpdater updater(_builder, orig_obj, new_obj);
238 orig_ref->metaspace_pointers_do(&updater);
239 }
240
241 return true; // keep recursing until every object is visited exactly once.
242 }
243 };
244
245 class EmbeddedRefUpdater: public MetaspaceClosure {
246 DynamicArchiveBuilder* _builder;
247 address _orig_obj;
248 address _new_obj;
249 public:
250 EmbeddedRefUpdater(DynamicArchiveBuilder* shuffler, address orig_obj, address new_obj) :
251 _builder(shuffler), _orig_obj(orig_obj), _new_obj(new_obj) {}
252
253 // This method gets called once for each pointer field F of orig_obj.
254 // We update new_obj->F to point to the new location of orig_obj->F.
255 //
256 // Example: Klass* 0x100 is copied to 0x400
257 // Symbol* 0x200 is copied to 0x500
258 //
259 // Let orig_obj == 0x100; and
260 // new_obj == 0x400; and
261 // ((Klass*)orig_obj)->_name == 0x200;
262 // Then this function effectively assigns
314 public:
315 PointerMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
316
317 virtual bool do_unique_ref(Ref* ref, bool read_only) {
318 if (_builder->is_in_buffer_space(ref->obj())) {
319 EmbeddedRefMarker ref_marker(_builder);
320 ref->metaspace_pointers_do(&ref_marker);
321 return true; // keep recursing until every buffered object is visited exactly once.
322 } else {
323 return false;
324 }
325 }
326 };
327
328 class EmbeddedRefMarker: public MetaspaceClosure {
329 DynamicArchiveBuilder* _builder;
330
331 public:
332 EmbeddedRefMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
333 virtual bool do_ref(Ref* ref, bool read_only) {
334 if (ref->not_null() && _builder->is_in_buffer_space(ref->obj())) {
335 _builder->mark_pointer(ref->addr());
336 }
337 return false; // Do not recurse.
338 }
339 };
340
341 void update_pointer(address* addr, address value, const char* kind, uintx offset, bool is_mso_pointer=true) {
342 // Propagate the the mask bits to the new value -- see comments above MetaspaceClosure::obj()
343 if (is_mso_pointer) {
344 const uintx FLAG_MASK = 0x03;
345 uintx mask_bits = uintx(*addr) & FLAG_MASK;
346 value = (address)(uintx(value) | mask_bits);
347 }
348
349 if (*addr != value) {
350 log_debug(cds, dynamic)("Update (%18s*) %3d [" PTR_FORMAT "] " PTR_FORMAT " -> " PTR_FORMAT,
351 kind, int(offset), p2i(addr), p2i(*addr), p2i(value));
352 *addr = value;
353 }
354 }
424
425 address copy_impl(MetaspaceClosure::Ref* ref, bool read_only, int bytes) {
426 if (ref->msotype() == MetaspaceObj::ClassType) {
427 // Save a pointer immediate in front of an InstanceKlass, so
428 // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
429 // without building another hashtable. See RunTimeSharedClassInfo::get_for()
430 // in systemDictionaryShared.cpp.
431 address obj = ref->obj();
432 Klass* klass = (Klass*)obj;
433 if (klass->is_instance_klass()) {
434 SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
435 current_dump_space()->allocate(sizeof(address), BytesPerWord);
436 }
437 }
438 address p = (address)current_dump_space()->allocate(bytes);
439 address obj = ref->obj();
440 log_debug(cds, dynamic)("COPY: " PTR_FORMAT " ==> " PTR_FORMAT " %5d %s",
441 p2i(obj), p2i(p), bytes,
442 MetaspaceObj::type_name(ref->msotype()));
443 memcpy(p, obj, bytes);
444
445 intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), p);
446 if (cloned_vtable != NULL) {
447 update_pointer((address*)p, (address)cloned_vtable, "vtb", 0, /*is_mso_pointer*/false);
448 }
449
450 return (address)p;
451 }
452
453 DynamicArchiveHeader *_header;
454 address _alloc_bottom;
455 address _last_verified_top;
456 size_t _other_region_used_bytes;
457
458 // Conservative estimate for number of bytes needed for:
459 size_t _estimated_metsapceobj_bytes; // all archived MetsapceObj's.
460 size_t _estimated_hashtable_bytes; // symbol table and dictionaries
461 size_t _estimated_trampoline_bytes; // method entry trampolines
462
463 size_t estimate_archive_size();
464 size_t estimate_trampoline_size();
465 size_t estimate_class_file_size();
466 address reserve_space_and_init_buffer_to_target_delta();
467 void init_header(address addr);
534 void doit() {
535 verify_universe("Before CDS dynamic dump");
536 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
537 SystemDictionaryShared::check_excluded_classes();
538
539 {
540 ResourceMark rm;
541 GatherKlassesAndSymbols gatherer(this);
542
543 SystemDictionaryShared::dumptime_classes_do(&gatherer);
544 SymbolTable::metaspace_pointers_do(&gatherer);
545 FileMapInfo::metaspace_pointers_do(&gatherer);
546
547 gatherer.finish();
548 }
549
550 // rw space starts ...
551 address reserved_bottom = reserve_space_and_init_buffer_to_target_delta();
552 init_header(reserved_bottom);
553
554 verify_estimate_size(sizeof(DynamicArchiveHeader), "header");
555
556 log_info(cds, dynamic)("Copying %d klasses and %d symbols",
557 _klasses->length(), _symbols->length());
558
559 {
560 assert(current_dump_space() == MetaspaceShared::read_write_dump_space(),
561 "Current dump space is not rw space");
562 // shallow-copy RW objects, if necessary
563 ResourceMark rm;
564 ShallowCopier rw_copier(this, false);
565 iterate_roots(&rw_copier);
566 }
567
568 // ro space starts ...
569 DumpRegion* ro_space = MetaspaceShared::read_only_dump_space();
570 {
571 start_dump_space(ro_space);
572
573 // shallow-copy RO objects, if necessary
574 ResourceMark rm;
575 ShallowCopier ro_copier(this, true);
576 iterate_roots(&ro_copier);
577 }
578
579 size_t bitmap_size = pointer_delta(current_dump_space()->top(),
580 _alloc_bottom, sizeof(address));
581 _ptrmap.initialize(bitmap_size);
582
583 {
584 log_info(cds)("Relocating embedded pointers ... ");
585 ResourceMark rm;
586 ShallowCopyEmbeddedRefRelocator emb_reloc(this);
587 iterate_roots(&emb_reloc);
588 }
589
590 {
591 log_info(cds)("Relocating external roots ... ");
592 ResourceMark rm;
593 ExternalRefUpdater ext_reloc(this);
594 iterate_roots(&ext_reloc);
595 }
596
597 verify_estimate_size(_estimated_metsapceobj_bytes, "MetaspaceObjs");
598
599 char* serialized_data_start;
600 {
601 set_symbols_permanent();
602
636 }
637
638 write_archive(serialized_data_start);
639
640 assert(_num_dump_regions_used == _total_dump_regions, "must be");
641 verify_universe("After CDS dynamic dump");
642 }
643
644 void iterate_roots(MetaspaceClosure* it) {
645 int i;
646 int num_klasses = _klasses->length();
647 for (i = 0; i < num_klasses; i++) {
648 it->push(&_klasses->at(i));
649 }
650
651 int num_symbols = _symbols->length();
652 for (i = 0; i < num_symbols; i++) {
653 it->push(&_symbols->at(i));
654 }
655
656 _header->shared_path_table_metaspace_pointers_do(it);
657
658 // Do not call these again, as we have already collected all the classes and symbols
659 // that we want to archive. Also, these calls would corrupt the tables when
660 // ExternalRefUpdater is used.
661 //
662 // SystemDictionaryShared::dumptime_classes_do(it);
663 // SymbolTable::metaspace_pointers_do(it);
664
665 it->finish();
666 }
667 };
668
669 size_t DynamicArchiveBuilder::estimate_archive_size() {
670 // size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's
671 _estimated_hashtable_bytes = 0;
672 _estimated_hashtable_bytes += SymbolTable::estimate_size_for_archive();
673 _estimated_hashtable_bytes += SystemDictionaryShared::estimate_size_for_archive();
674
675 _estimated_trampoline_bytes = estimate_trampoline_size();
676
677 size_t total = 0;
678
679 total += _estimated_metsapceobj_bytes;
680 total += _estimated_hashtable_bytes;
681 total += _estimated_trampoline_bytes;
682
683 // allow fragmentation at the end of each dump region
684 total += _total_dump_regions * reserve_alignment();
685
686 return align_up(total, reserve_alignment());
687 }
688
689 address DynamicArchiveBuilder::reserve_space_and_init_buffer_to_target_delta() {
690 size_t total = estimate_archive_size();
691 bool large_pages = false; // No large pages when dumping the CDS archive.
692 size_t increment = align_up(1*G, reserve_alignment());
693 char* addr = (char*)align_up(CompressedKlassPointers::base() + MetaspaceSize + increment,
694 reserve_alignment());
695
696 ReservedSpace* rs = MetaspaceShared::reserve_shared_rs(
697 total, reserve_alignment(), large_pages, addr);
698 while (!rs->is_reserved() && (addr + increment > addr)) {
699 addr += increment;
700 rs = MetaspaceShared::reserve_shared_rs(
701 total, reserve_alignment(), large_pages, addr);
702 }
703 if (!rs->is_reserved()) {
704 log_error(cds, dynamic)("Failed to reserve %d bytes of output buffer.", (int)total);
705 vm_direct_exit(0);
706 }
707
708 address buffer_base = (address)rs->base();
709 log_info(cds, dynamic)("Reserved output buffer space at : " PTR_FORMAT " [%d bytes]",
710 p2i(buffer_base), (int)total);
711
712 // At run time, we will mmap the dynamic archive at target_space_bottom.
713 // However, at dump time, we may not be able to write into the target_space,
714 // as it's occupied by dynamically loaded Klasses. So we allocate a buffer
715 // at an arbitrary location chosen by the OS. We will write all the dynamically
716 // archived classes into this buffer. At the final stage of dumping, we relocate
717 // all pointers that are inside the buffer_space to point to their (runtime)
718 // target location inside thetarget_space.
719 address target_space_bottom =
720 (address)align_up(MetaspaceShared::shared_metaspace_top(), reserve_alignment());
721 _buffer_to_target_delta = intx(target_space_bottom) - intx(buffer_base);
722
723 log_info(cds, dynamic)("Target archive space at : " PTR_FORMAT, p2i(target_space_bottom));
724 log_info(cds, dynamic)("Buffer-space to target-space delta : " PTR_FORMAT, p2i((address)_buffer_to_target_delta));
725
726 return buffer_base;
727 }
728
729 void DynamicArchiveBuilder::init_header(address reserved_bottom) {
730 _alloc_bottom = reserved_bottom;
771 Method* m = methods->at(j);
772 address c2i_entry_trampoline =
773 (address)MetaspaceShared::misc_code_space_alloc(SharedRuntime::trampoline_size());
774 m->set_from_compiled_entry(to_target(c2i_entry_trampoline));
775 AdapterHandlerEntry** adapter_trampoline =
776 (AdapterHandlerEntry**)MetaspaceShared::misc_code_space_alloc(sizeof(AdapterHandlerEntry*));
777 *adapter_trampoline = NULL;
778 m->set_adapter_trampoline(to_target(adapter_trampoline));
779 }
780 }
781
782 if (MetaspaceShared::misc_code_dump_space()->used() == 0) {
783 // We have nothing to archive, but let's avoid having an empty region.
784 MetaspaceShared::misc_code_space_alloc(SharedRuntime::trampoline_size());
785 }
786 }
787
788 void DynamicArchiveBuilder::make_klasses_shareable() {
789 int i, count = _klasses->length();
790
791 for (i = 0; i < count; i++) {
792 InstanceKlass* ik = _klasses->at(i);
793 sort_methods(ik);
794 }
795
796 for (i = 0; i < count; i++) {
797 InstanceKlass* ik = _klasses->at(i);
798 ClassLoaderData *cld = ik->class_loader_data();
799 if (cld->is_boot_class_loader_data()) {
800 ik->set_class_loader_type(ClassLoader::BOOT_LOADER);
801 }
802 else if (cld->is_platform_class_loader_data()) {
803 ik->set_class_loader_type(ClassLoader::PLATFORM_LOADER);
804 }
805 else if (cld->is_system_class_loader_data()) {
806 ik->set_class_loader_type(ClassLoader::APP_LOADER);
807 }
808
809 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(ik);
810 ik->remove_unshareable_info();
830 if (ik->java_mirror() == NULL) {
831 // NULL mirror means this class has already been visited and methods are already sorted
832 return;
833 }
834 ik->remove_java_mirror();
835
836 if (log_is_enabled(Debug, cds, dynamic)) {
837 ResourceMark rm;
838 log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " %s", p2i(to_target(ik)), ik->external_name());
839 }
840
841 // Make sure all supertypes have been sorted
842 sort_methods(ik->java_super());
843 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
844 int len = interfaces->length();
845 for (int i = 0; i < len; i++) {
846 sort_methods(interfaces->at(i));
847 }
848
849 #ifdef ASSERT
850 {
851 for (int m = 0; m < ik->methods()->length(); m++) {
852 Symbol* name = ik->methods()->at(m)->name();
853 assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
854 }
855 }
856 #endif
857
858 Thread* THREAD = Thread::current();
859 Method::sort_methods(ik->methods());
860 if (ik->default_methods() != NULL) {
861 Method::sort_methods(ik->default_methods(), /*set_idnums=*/false);
862 }
863 ik->vtable().initialize_vtable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
864 ik->itable().initialize_itable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
865 }
866
867 void DynamicArchiveBuilder::set_symbols_permanent() {
868 int count = _symbols->length();
869 for (int i=0; i<count; i++) {
870 Symbol* s = _symbols->at(i);
871 s->set_permanent();
872
873 if (log_is_enabled(Trace, cds, dynamic)) {
874 ResourceMark rm;
875 log_trace(cds, dynamic)("symbols[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(s)), s->as_quoted_ascii());
876 }
877 }
878 }
879
880 class RelocateBufferToTarget: public BitMapClosure {
881 DynamicArchiveBuilder *_builder;
885 RelocateBufferToTarget(DynamicArchiveBuilder* builder, address* bottom, intx delta) :
886 _builder(builder), _buffer_bottom(bottom), _buffer_to_target_delta(delta) {}
887
888 bool do_bit(size_t offset) {
889 address* p = _buffer_bottom + offset;
890 assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
891
892 address old_ptr = *p;
893 if (_builder->is_in_buffer_space(old_ptr)) {
894 address new_ptr = old_ptr + _buffer_to_target_delta;
895 log_trace(cds, dynamic)("Final patch: @%6d [" PTR_FORMAT " -> " PTR_FORMAT "] " PTR_FORMAT " => " PTR_FORMAT,
896 (int)offset, p2i(p), p2i(_builder->to_target(p)),
897 p2i(old_ptr), p2i(new_ptr));
898 *p = new_ptr;
899 }
900
901 return true; // keep iterating
902 }
903 };
904
905
906 void DynamicArchiveBuilder::relocate_buffer_to_target() {
907 RelocateBufferToTarget patcher(this, (address*)_alloc_bottom, _buffer_to_target_delta);
908 _ptrmap.iterate(&patcher);
909
910 Array<u8>* table = _header->shared_path_table().table();
911 table = to_target(table);
912 _header->relocate_shared_path_table(table);
913 }
914
915 void DynamicArchiveBuilder::write_regions(FileMapInfo* dynamic_info) {
916 dynamic_info->write_region(MetaspaceShared::rw,
917 MetaspaceShared::read_write_dump_space()->base(),
918 MetaspaceShared::read_write_dump_space()->used(),
919 /*read_only=*/false,/*allow_exec=*/false);
920 dynamic_info->write_region(MetaspaceShared::ro,
921 MetaspaceShared::read_only_dump_space()->base(),
922 MetaspaceShared::read_only_dump_space()->used(),
923 /*read_only=*/true, /*allow_exec=*/false);
924 dynamic_info->write_region(MetaspaceShared::mc,
925 MetaspaceShared::misc_code_dump_space()->base(),
926 MetaspaceShared::misc_code_dump_space()->used(),
927 /*read_only=*/false,/*allow_exec=*/true);
928 }
929
930 void DynamicArchiveBuilder::write_archive(char* serialized_data_start) {
931 int num_klasses = _klasses->length();
932 int num_symbols = _symbols->length();
933
934 _header->set_serialized_data_start(to_target(serialized_data_start));
935
936 FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
937 assert(dynamic_info != NULL, "Sanity");
938
939 // Now write the archived data including the file offsets.
940 const char* archive_name = Arguments::GetSharedDynamicArchivePath();
941 dynamic_info->open_for_write(archive_name);
942 write_regions(dynamic_info);
943 dynamic_info->set_header_crc(dynamic_info->compute_header_crc());
944 dynamic_info->write_header();
945 dynamic_info->close();
946
947 address base = to_target(_alloc_bottom);
948 address top = address(current_dump_space()->top()) + _buffer_to_target_delta;
949 size_t file_size = pointer_delta(top, base, sizeof(char));
950
951 log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
952 " [" SIZE_FORMAT " bytes header, " SIZE_FORMAT " bytes total]",
953 p2i(base), p2i(top), _header->header_size(), file_size);
954 log_info(cds, dynamic)("%d klasses; %d symbols", num_klasses, num_symbols);
955 }
956
957
958 class VM_PopulateDynamicDumpSharedSpace: public VM_Operation {
959 DynamicArchiveBuilder* _builder;
960 public:
961 VM_PopulateDynamicDumpSharedSpace(DynamicArchiveBuilder* builder) : _builder(builder) {}
962 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
963 void doit() {
964 ResourceMark rm;
965 if (SystemDictionaryShared::empty_dumptime_table()) {
966 log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
967 return;
968 }
969 if (AllowArchivingWithJavaAgent) {
970 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1019 assert(MetaspaceShared::is_in_shared_metaspace(orig_obj), "must be");
1020 return orig_obj;
1021 } else {
1022 return _builder->to_target(buff_obj);
1023 }
1024 }
1025
1026 uintx DynamicArchive::object_delta_uintx(void* buff_obj) {
1027 assert(DynamicDumpSharedSpaces, "must be");
1028 address target_obj = _builder->to_target_no_check(address(buff_obj));
1029 assert(uintx(target_obj) >= SharedBaseAddress, "must be");
1030 return uintx(target_obj) - SharedBaseAddress;
1031 }
1032
1033 bool DynamicArchive::is_in_target_space(void *obj) {
1034 assert(DynamicDumpSharedSpaces, "must be");
1035 return _builder->is_in_target_space(obj);
1036 }
1037
1038
1039 static DynamicArchiveHeader *_dynamic_header = NULL;
1040 DynamicArchiveBuilder* DynamicArchive::_builder = NULL;
1041
1042 void DynamicArchive::map_failed(FileMapInfo* mapinfo) {
1043 if (mapinfo->dynamic_header() != NULL) {
1044 os::free((void*)mapinfo->dynamic_header());
1045 }
1046 delete mapinfo;
1047 }
1048
1049 // Returns the top of the mapped address space
1050 address DynamicArchive::map() {
1051 assert(UseSharedSpaces, "Sanity");
1052
1053 // Create the dynamic archive map info
1054 FileMapInfo* mapinfo;
1055 const char* filename = Arguments::GetSharedDynamicArchivePath();
1056 struct stat st;
1057 address result;
1058 if ((filename != NULL) && (os::stat(filename, &st) == 0)) {
1059 mapinfo = new FileMapInfo(false);
1060 if (!mapinfo->open_for_read(filename)) {
1061 result = NULL;
1062 }
1063 result = map_impl(mapinfo);
1064 if (result == NULL) {
1065 map_failed(mapinfo);
1066 mapinfo->restore_shared_path_table();
1067 }
1068 } else {
1069 if (filename != NULL) {
1070 log_warning(cds, dynamic)("specified dynamic archive doesn't exist: %s", filename);
1071 }
1072 result = NULL;
1073 }
1074 return result;
1075 }
1076
1077 address DynamicArchive::map_impl(FileMapInfo* mapinfo) {
1078 // Read header
1079 if (!mapinfo->initialize(false)) {
1080 return NULL;
1081 }
1082
1083 _dynamic_header = mapinfo->dynamic_header();
1084 int regions[] = {MetaspaceShared::rw,
1085 MetaspaceShared::ro,
1086 MetaspaceShared::mc};
1087
1088 size_t len = sizeof(regions)/sizeof(int);
1089 char* saved_base[] = {NULL, NULL, NULL};
1090 char* top = mapinfo->map_regions(regions, saved_base, len);
1091 if (top == NULL) {
1092 mapinfo->unmap_regions(regions, saved_base, len);
1093 FileMapInfo::fail_continue("Unable to use dynamic archive. Failed map_region for using -Xshare:on.");
1094 return NULL;
1095 }
1096
1097 if (!validate(mapinfo)) {
1098 return NULL;
1099 }
1100
1101 if (_dynamic_header == NULL) {
1102 return NULL;
1103 }
1104
1105 intptr_t* buffer = (intptr_t*)_dynamic_header->serialized_data_start();
1106 ReadClosure rc(&buffer);
1107 SymbolTable::serialize_shared_table_header(&rc, false);
1108 SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1109
1110 return (address)top;
1111 }
1112
1113 bool DynamicArchive::validate(FileMapInfo* dynamic_info) {
1114 // Check if the recorded base archive matches with the current one
1115 FileMapInfo* base_info = FileMapInfo::current_info();
1116 DynamicArchiveHeader* dynamic_header = dynamic_info->dynamic_header();
1117
1118 // Check the header crc
1119 if (dynamic_header->base_header_crc() != base_info->crc()) {
1120 FileMapInfo::fail_continue("Archive header checksum verification failed.");
1121 return false;
1122 }
1123
1124 // Check each space's crc
1125 for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1126 if (dynamic_header->base_region_crc(i) != base_info->space_crc(i)) {
1127 FileMapInfo::fail_continue("Archive region #%d checksum verification failed.", i);
1128 return false;
1129 }
1130 }
1131
1132 // Validate the dynamic archived shared path table, and set the global
1133 // _shared_path_table to that.
1134 if (!dynamic_info->validate_shared_path_table()) {
1135 return false;
1136 }
1137 return true;
1138 }
1139
1140 bool DynamicArchive::is_mapped() {
1141 return (_dynamic_header != NULL);
1142 }
1143
1144 void DynamicArchive::disable() {
1145 _dynamic_header = NULL;
1146 }
|
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 "jvm.h"
27 #include "classfile/classLoaderData.inline.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "classfile/systemDictionaryShared.hpp"
31 #include "logging/log.hpp"
32 #include "memory/archiveUtils.hpp"
33 #include "memory/dynamicArchive.hpp"
34 #include "memory/metadataFactory.hpp"
35 #include "memory/metaspace.hpp"
36 #include "memory/metaspaceClosure.hpp"
37 #include "memory/metaspaceShared.hpp"
38 #include "memory/resourceArea.hpp"
39 #include "oops/compressedOops.hpp"
40 #include "oops/objArrayKlass.hpp"
41 #include "prims/jvmtiRedefineClasses.hpp"
42 #include "runtime/handles.inline.hpp"
43 #include "runtime/os.inline.hpp"
44 #include "runtime/sharedRuntime.hpp"
45 #include "runtime/vmThread.hpp"
46 #include "runtime/vmOperations.hpp"
47 #include "utilities/bitMap.inline.hpp"
48
49 #ifndef O_BINARY // if defined (Win32) use binary files.
50 #define O_BINARY 0 // otherwise do nothing.
51 #endif
52
53 class DynamicArchiveBuilder : ResourceObj {
54 static unsigned my_hash(const address& a) {
55 return primitive_hash<address>(a);
56 }
57 static bool my_equals(const address& a0, const address& a1) {
58 return primitive_equals<address>(a0, a1);
59 }
60 typedef ResourceHashtable<
61 address, address,
62 DynamicArchiveBuilder::my_hash, // solaris compiler doesn't like: primitive_hash<address>
63 DynamicArchiveBuilder::my_equals, // solaris compiler doesn't like: primitive_equals<address>
64 16384, ResourceObj::C_HEAP> RelocationTable;
65 RelocationTable _new_loc_table;
66
67 intx _buffer_to_target_delta;
68
69 DumpRegion* _current_dump_space;
70
71 static size_t reserve_alignment() {
72 return Metaspace::reserve_alignment();
73 }
74
75 static const int _total_dump_regions = 3;
76 int _num_dump_regions_used;
77
78 public:
79 void mark_pointer(address* ptr_loc) {
80 ArchivePtrMarker::mark_pointer(ptr_loc);
81 }
82
83 DumpRegion* current_dump_space() const {
84 return _current_dump_space;
85 }
86
87 bool is_in_buffer_space(address p) const {
88 return (_alloc_bottom <= p && p < (address)current_dump_space()->top());
89 }
90
91 template <typename T> bool is_in_target_space(T target_obj) const {
92 address buff_obj = address(target_obj) - _buffer_to_target_delta;
93 return is_in_buffer_space(buff_obj);
94 }
95
96 template <typename T> bool is_in_buffer_space(T obj) const {
97 return is_in_buffer_space(address(obj));
98 }
99
100 template <typename T> T to_target_no_check(T obj) const {
108
109 template <typename T> T get_new_loc(T obj) {
110 address* pp = _new_loc_table.get((address)obj);
111 if (pp == NULL) {
112 // Excluded klasses are not copied
113 return NULL;
114 } else {
115 return (T)*pp;
116 }
117 }
118
119 address get_new_loc(MetaspaceClosure::Ref* ref) {
120 return get_new_loc(ref->obj());
121 }
122
123 template <typename T> bool has_new_loc(T obj) {
124 address* pp = _new_loc_table.get((address)obj);
125 return pp != NULL;
126 }
127
128 static intx _method_comparator_name_delta;
129
130 static int dynamic_dump_method_comparator(Method* a, Method* b) {
131 Symbol* a_name = a->name();
132 Symbol* b_name = b->name();
133
134 if (!MetaspaceShared::is_in_shared_metaspace(a_name)) {
135 // a_name points to a Symbol in the top archive.
136 // When this method is called, a_name is still pointing to the output space.
137 // Translate it to point to the output space, so that it can be compared with
138 // Symbols in the base archive.
139 a_name = (Symbol*)(address(a_name) + _method_comparator_name_delta);
140 //tty->print_cr("%p", a_name);
141 }
142 if (!MetaspaceShared::is_in_shared_metaspace(b_name)) {
143 b_name = (Symbol*)(address(b_name) + _method_comparator_name_delta);
144 //tty->print_cr("%p", b_name);
145 }
146
147 return a_name->fast_compare(b_name);
148 }
149
150 protected:
151 enum FollowMode {
152 make_a_copy, point_to_it, set_to_null
153 };
154
155 public:
156 void copy(MetaspaceClosure::Ref* ref, bool read_only) {
157 int bytes = ref->size() * BytesPerWord;
158 address old_obj = ref->obj();
159 address new_obj = copy_impl(ref, read_only, bytes);
160
161 assert(new_obj != NULL, "must be");
162 assert(new_obj != old_obj, "must be");
163 bool isnew = _new_loc_table.put(old_obj, new_obj);
164 assert(isnew, "must be");
165 }
166
167 // Make a shallow copy of each eligible MetaspaceObj into the buffer.
168 class ShallowCopier: public UniqueMetaspaceClosure {
169 DynamicArchiveBuilder* _builder;
242 #ifdef ASSERT
243 if (new_obj == NULL) {
244 if (orig_ref->msotype() == MetaspaceObj::ClassType) {
245 Klass* k = (Klass*)orig_obj;
246 assert(k->is_instance_klass() &&
247 SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k)),
248 "orig_obj must be excluded Class");
249 }
250 }
251 #endif
252
253 log_debug(cds, dynamic)("Relocating " PTR_FORMAT " %s", p2i(new_obj),
254 MetaspaceObj::type_name(orig_ref->msotype()));
255 if (new_obj != NULL) {
256 EmbeddedRefUpdater updater(_builder, orig_obj, new_obj);
257 orig_ref->metaspace_pointers_do(&updater);
258 }
259
260 return true; // keep recursing until every object is visited exactly once.
261 }
262
263 virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
264 assert(type == _method_entry_ref, "only special type allowed for now");
265 address obj = ref->obj();
266 address new_obj = _builder->get_new_loc(ref);
267 size_t offset = pointer_delta(p, obj, sizeof(u1));
268 intptr_t* new_p = (intptr_t*)(new_obj + offset);
269 assert(*p == *new_p, "must be a copy");
270 ArchivePtrMarker::mark_pointer((address*)new_p);
271 }
272 };
273
274 class EmbeddedRefUpdater: public MetaspaceClosure {
275 DynamicArchiveBuilder* _builder;
276 address _orig_obj;
277 address _new_obj;
278 public:
279 EmbeddedRefUpdater(DynamicArchiveBuilder* shuffler, address orig_obj, address new_obj) :
280 _builder(shuffler), _orig_obj(orig_obj), _new_obj(new_obj) {}
281
282 // This method gets called once for each pointer field F of orig_obj.
283 // We update new_obj->F to point to the new location of orig_obj->F.
284 //
285 // Example: Klass* 0x100 is copied to 0x400
286 // Symbol* 0x200 is copied to 0x500
287 //
288 // Let orig_obj == 0x100; and
289 // new_obj == 0x400; and
290 // ((Klass*)orig_obj)->_name == 0x200;
291 // Then this function effectively assigns
343 public:
344 PointerMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
345
346 virtual bool do_unique_ref(Ref* ref, bool read_only) {
347 if (_builder->is_in_buffer_space(ref->obj())) {
348 EmbeddedRefMarker ref_marker(_builder);
349 ref->metaspace_pointers_do(&ref_marker);
350 return true; // keep recursing until every buffered object is visited exactly once.
351 } else {
352 return false;
353 }
354 }
355 };
356
357 class EmbeddedRefMarker: public MetaspaceClosure {
358 DynamicArchiveBuilder* _builder;
359
360 public:
361 EmbeddedRefMarker(DynamicArchiveBuilder* shuffler) : _builder(shuffler) {}
362 virtual bool do_ref(Ref* ref, bool read_only) {
363 if (ref->not_null()) {
364 _builder->mark_pointer(ref->addr());
365 }
366 return false; // Do not recurse.
367 }
368 };
369
370 void update_pointer(address* addr, address value, const char* kind, uintx offset, bool is_mso_pointer=true) {
371 // Propagate the the mask bits to the new value -- see comments above MetaspaceClosure::obj()
372 if (is_mso_pointer) {
373 const uintx FLAG_MASK = 0x03;
374 uintx mask_bits = uintx(*addr) & FLAG_MASK;
375 value = (address)(uintx(value) | mask_bits);
376 }
377
378 if (*addr != value) {
379 log_debug(cds, dynamic)("Update (%18s*) %3d [" PTR_FORMAT "] " PTR_FORMAT " -> " PTR_FORMAT,
380 kind, int(offset), p2i(addr), p2i(*addr), p2i(value));
381 *addr = value;
382 }
383 }
453
454 address copy_impl(MetaspaceClosure::Ref* ref, bool read_only, int bytes) {
455 if (ref->msotype() == MetaspaceObj::ClassType) {
456 // Save a pointer immediate in front of an InstanceKlass, so
457 // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
458 // without building another hashtable. See RunTimeSharedClassInfo::get_for()
459 // in systemDictionaryShared.cpp.
460 address obj = ref->obj();
461 Klass* klass = (Klass*)obj;
462 if (klass->is_instance_klass()) {
463 SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
464 current_dump_space()->allocate(sizeof(address), BytesPerWord);
465 }
466 }
467 address p = (address)current_dump_space()->allocate(bytes);
468 address obj = ref->obj();
469 log_debug(cds, dynamic)("COPY: " PTR_FORMAT " ==> " PTR_FORMAT " %5d %s",
470 p2i(obj), p2i(p), bytes,
471 MetaspaceObj::type_name(ref->msotype()));
472 memcpy(p, obj, bytes);
473 intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), p);
474 if (cloned_vtable != NULL) {
475 update_pointer((address*)p, (address)cloned_vtable, "vtb", 0, /*is_mso_pointer*/false);
476 mark_pointer((address*)p);
477 }
478
479 return (address)p;
480 }
481
482 DynamicArchiveHeader *_header;
483 address _alloc_bottom;
484 address _last_verified_top;
485 size_t _other_region_used_bytes;
486
487 // Conservative estimate for number of bytes needed for:
488 size_t _estimated_metsapceobj_bytes; // all archived MetsapceObj's.
489 size_t _estimated_hashtable_bytes; // symbol table and dictionaries
490 size_t _estimated_trampoline_bytes; // method entry trampolines
491
492 size_t estimate_archive_size();
493 size_t estimate_trampoline_size();
494 size_t estimate_class_file_size();
495 address reserve_space_and_init_buffer_to_target_delta();
496 void init_header(address addr);
563 void doit() {
564 verify_universe("Before CDS dynamic dump");
565 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
566 SystemDictionaryShared::check_excluded_classes();
567
568 {
569 ResourceMark rm;
570 GatherKlassesAndSymbols gatherer(this);
571
572 SystemDictionaryShared::dumptime_classes_do(&gatherer);
573 SymbolTable::metaspace_pointers_do(&gatherer);
574 FileMapInfo::metaspace_pointers_do(&gatherer);
575
576 gatherer.finish();
577 }
578
579 // rw space starts ...
580 address reserved_bottom = reserve_space_and_init_buffer_to_target_delta();
581 init_header(reserved_bottom);
582
583 CHeapBitMap ptrmap;
584 ArchivePtrMarker::initialize(&ptrmap, (address*)reserved_bottom, (address*)current_dump_space()->top());
585
586 verify_estimate_size(sizeof(DynamicArchiveHeader), "header");
587
588 log_info(cds, dynamic)("Copying %d klasses and %d symbols",
589 _klasses->length(), _symbols->length());
590
591 {
592 assert(current_dump_space() == MetaspaceShared::read_write_dump_space(),
593 "Current dump space is not rw space");
594 // shallow-copy RW objects, if necessary
595 ResourceMark rm;
596 ShallowCopier rw_copier(this, false);
597 iterate_roots(&rw_copier);
598 }
599
600 // ro space starts ...
601 DumpRegion* ro_space = MetaspaceShared::read_only_dump_space();
602 {
603 start_dump_space(ro_space);
604
605 // shallow-copy RO objects, if necessary
606 ResourceMark rm;
607 ShallowCopier ro_copier(this, true);
608 iterate_roots(&ro_copier);
609 }
610
611 {
612 log_info(cds)("Relocating embedded pointers ... ");
613 ResourceMark rm;
614 ShallowCopyEmbeddedRefRelocator emb_reloc(this);
615 iterate_roots(&emb_reloc);
616 }
617
618 {
619 log_info(cds)("Relocating external roots ... ");
620 ResourceMark rm;
621 ExternalRefUpdater ext_reloc(this);
622 iterate_roots(&ext_reloc);
623 }
624
625 verify_estimate_size(_estimated_metsapceobj_bytes, "MetaspaceObjs");
626
627 char* serialized_data_start;
628 {
629 set_symbols_permanent();
630
664 }
665
666 write_archive(serialized_data_start);
667
668 assert(_num_dump_regions_used == _total_dump_regions, "must be");
669 verify_universe("After CDS dynamic dump");
670 }
671
672 void iterate_roots(MetaspaceClosure* it) {
673 int i;
674 int num_klasses = _klasses->length();
675 for (i = 0; i < num_klasses; i++) {
676 it->push(&_klasses->at(i));
677 }
678
679 int num_symbols = _symbols->length();
680 for (i = 0; i < num_symbols; i++) {
681 it->push(&_symbols->at(i));
682 }
683
684 FileMapInfo::metaspace_pointers_do(it);
685
686 // Do not call these again, as we have already collected all the classes and symbols
687 // that we want to archive. Also, these calls would corrupt the tables when
688 // ExternalRefUpdater is used.
689 //
690 // SystemDictionaryShared::dumptime_classes_do(it);
691 // SymbolTable::metaspace_pointers_do(it);
692
693 it->finish();
694 }
695 };
696
697 intx DynamicArchiveBuilder::_method_comparator_name_delta;
698
699
700 size_t DynamicArchiveBuilder::estimate_archive_size() {
701 // size of the symbol table and two dictionaries, plus the RunTimeSharedClassInfo's
702 _estimated_hashtable_bytes = 0;
703 _estimated_hashtable_bytes += SymbolTable::estimate_size_for_archive();
704 _estimated_hashtable_bytes += SystemDictionaryShared::estimate_size_for_archive();
705
706 _estimated_trampoline_bytes = estimate_trampoline_size();
707
708 size_t total = 0;
709
710 total += _estimated_metsapceobj_bytes;
711 total += _estimated_hashtable_bytes;
712 total += _estimated_trampoline_bytes;
713
714 // allow fragmentation at the end of each dump region
715 total += _total_dump_regions * reserve_alignment();
716
717 return align_up(total, reserve_alignment());
718 }
719
720 address DynamicArchiveBuilder::reserve_space_and_init_buffer_to_target_delta() {
721 size_t total = estimate_archive_size();
722 ReservedSpace rs = MetaspaceShared::reserve_shared_space(total);
723 if (!rs.is_reserved()) {
724 log_error(cds, dynamic)("Failed to reserve %d bytes of output buffer.", (int)total);
725 vm_direct_exit(0);
726 }
727
728 address buffer_base = (address)rs.base();
729 log_info(cds, dynamic)("Reserved output buffer space at : " PTR_FORMAT " [%d bytes]",
730 p2i(buffer_base), (int)total);
731 MetaspaceShared::set_shared_rs(rs);
732
733 // At run time, we will mmap the dynamic archive at target_space_bottom.
734 // However, at dump time, we may not be able to write into the target_space,
735 // as it's occupied by dynamically loaded Klasses. So we allocate a buffer
736 // at an arbitrary location chosen by the OS. We will write all the dynamically
737 // archived classes into this buffer. At the final stage of dumping, we relocate
738 // all pointers that are inside the buffer_space to point to their (runtime)
739 // target location inside thetarget_space.
740 address target_space_bottom =
741 (address)align_up(MetaspaceShared::shared_metaspace_top(), reserve_alignment());
742 _buffer_to_target_delta = intx(target_space_bottom) - intx(buffer_base);
743
744 log_info(cds, dynamic)("Target archive space at : " PTR_FORMAT, p2i(target_space_bottom));
745 log_info(cds, dynamic)("Buffer-space to target-space delta : " PTR_FORMAT, p2i((address)_buffer_to_target_delta));
746
747 return buffer_base;
748 }
749
750 void DynamicArchiveBuilder::init_header(address reserved_bottom) {
751 _alloc_bottom = reserved_bottom;
792 Method* m = methods->at(j);
793 address c2i_entry_trampoline =
794 (address)MetaspaceShared::misc_code_space_alloc(SharedRuntime::trampoline_size());
795 m->set_from_compiled_entry(to_target(c2i_entry_trampoline));
796 AdapterHandlerEntry** adapter_trampoline =
797 (AdapterHandlerEntry**)MetaspaceShared::misc_code_space_alloc(sizeof(AdapterHandlerEntry*));
798 *adapter_trampoline = NULL;
799 m->set_adapter_trampoline(to_target(adapter_trampoline));
800 }
801 }
802
803 if (MetaspaceShared::misc_code_dump_space()->used() == 0) {
804 // We have nothing to archive, but let's avoid having an empty region.
805 MetaspaceShared::misc_code_space_alloc(SharedRuntime::trampoline_size());
806 }
807 }
808
809 void DynamicArchiveBuilder::make_klasses_shareable() {
810 int i, count = _klasses->length();
811
812 InstanceKlass::disable_method_binary_search();
813 _method_comparator_name_delta = _buffer_to_target_delta;
814 for (i = 0; i < count; i++) {
815 InstanceKlass* ik = _klasses->at(i);
816 sort_methods(ik);
817 }
818
819 for (i = 0; i < count; i++) {
820 InstanceKlass* ik = _klasses->at(i);
821 ClassLoaderData *cld = ik->class_loader_data();
822 if (cld->is_boot_class_loader_data()) {
823 ik->set_class_loader_type(ClassLoader::BOOT_LOADER);
824 }
825 else if (cld->is_platform_class_loader_data()) {
826 ik->set_class_loader_type(ClassLoader::PLATFORM_LOADER);
827 }
828 else if (cld->is_system_class_loader_data()) {
829 ik->set_class_loader_type(ClassLoader::APP_LOADER);
830 }
831
832 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(ik);
833 ik->remove_unshareable_info();
853 if (ik->java_mirror() == NULL) {
854 // NULL mirror means this class has already been visited and methods are already sorted
855 return;
856 }
857 ik->remove_java_mirror();
858
859 if (log_is_enabled(Debug, cds, dynamic)) {
860 ResourceMark rm;
861 log_debug(cds, dynamic)("sorting methods for " PTR_FORMAT " %s", p2i(to_target(ik)), ik->external_name());
862 }
863
864 // Make sure all supertypes have been sorted
865 sort_methods(ik->java_super());
866 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
867 int len = interfaces->length();
868 for (int i = 0; i < len; i++) {
869 sort_methods(interfaces->at(i));
870 }
871
872 #ifdef ASSERT
873 if (ik->methods() != NULL) {
874 for (int m = 0; m < ik->methods()->length(); m++) {
875 Symbol* name = ik->methods()->at(m)->name();
876 assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
877 }
878 }
879 if (ik->default_methods() != NULL) {
880 for (int m = 0; m < ik->default_methods()->length(); m++) {
881 Symbol* name = ik->default_methods()->at(m)->name();
882 assert(MetaspaceShared::is_in_shared_metaspace(name) || is_in_buffer_space(name), "must be");
883 }
884 }
885 #endif
886
887 Thread* THREAD = Thread::current();
888 Method::sort_methods(ik->methods(), /*set_idnums=*/true, dynamic_dump_method_comparator);
889 if (ik->default_methods() != NULL) {
890 Method::sort_methods(ik->default_methods(), /*set_idnums=*/false, dynamic_dump_method_comparator);
891 }
892 ik->vtable().initialize_vtable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
893 ik->itable().initialize_itable(true, THREAD); assert(!HAS_PENDING_EXCEPTION, "cannot fail");
894 }
895
896 void DynamicArchiveBuilder::set_symbols_permanent() {
897 int count = _symbols->length();
898 for (int i=0; i<count; i++) {
899 Symbol* s = _symbols->at(i);
900 s->set_permanent();
901
902 if (log_is_enabled(Trace, cds, dynamic)) {
903 ResourceMark rm;
904 log_trace(cds, dynamic)("symbols[%4i] = " PTR_FORMAT " %s", i, p2i(to_target(s)), s->as_quoted_ascii());
905 }
906 }
907 }
908
909 class RelocateBufferToTarget: public BitMapClosure {
910 DynamicArchiveBuilder *_builder;
914 RelocateBufferToTarget(DynamicArchiveBuilder* builder, address* bottom, intx delta) :
915 _builder(builder), _buffer_bottom(bottom), _buffer_to_target_delta(delta) {}
916
917 bool do_bit(size_t offset) {
918 address* p = _buffer_bottom + offset;
919 assert(_builder->is_in_buffer_space(p), "pointer must live in buffer space");
920
921 address old_ptr = *p;
922 if (_builder->is_in_buffer_space(old_ptr)) {
923 address new_ptr = old_ptr + _buffer_to_target_delta;
924 log_trace(cds, dynamic)("Final patch: @%6d [" PTR_FORMAT " -> " PTR_FORMAT "] " PTR_FORMAT " => " PTR_FORMAT,
925 (int)offset, p2i(p), p2i(_builder->to_target(p)),
926 p2i(old_ptr), p2i(new_ptr));
927 *p = new_ptr;
928 }
929
930 return true; // keep iterating
931 }
932 };
933
934 void DynamicArchiveBuilder::relocate_buffer_to_target() {
935 RelocateBufferToTarget patcher(this, (address*)_alloc_bottom, _buffer_to_target_delta);
936 ArchivePtrMarker::ptrmap()->iterate(&patcher);
937
938 Array<u8>* table = FileMapInfo::shared_path_table().table();
939 SharedPathTable runtime_table(to_target(table), FileMapInfo::shared_path_table().size());
940 _header->set_shared_path_table(runtime_table);
941
942 address relocatable_base = (address)SharedBaseAddress;
943 address relocatable_end = (address)(current_dump_space()->top()) + _buffer_to_target_delta;
944
945 ArchivePtrMarker::compact(relocatable_base, relocatable_end);
946
947 intx addr_delta = MetaspaceShared::final_delta();
948 if (addr_delta != 0) {
949 // Patch all pointers that are marked by ptrmap within this region,
950 // where we have just dumped all the metaspace data.
951 address patch_base = (address)_alloc_bottom;
952 address patch_end = (address)current_dump_space()->top();
953
954 // debug only -- the current value of the pointers to be patched must be within this
955 // range (i.e., must point to either the top archive (as currently mapped), or to the
956 // (targeted address of) the top archive)
957 address valid_old_base = relocatable_base;
958 address valid_old_end = relocatable_end;
959 size_t base_plus_top_size = valid_old_end - valid_old_base;
960 size_t top_size = patch_end - patch_base;
961 size_t base_size = base_plus_top_size - top_size;
962 assert(base_plus_top_size > base_size, "no overflow");
963 assert(base_plus_top_size > top_size, "no overflow");
964
965 // debug only -- after patching, the pointers must point inside this range
966 // (the requested location of the archive, as mapped at runtime).
967 address valid_new_base = (address)Arguments::default_SharedBaseAddress();
968 address valid_new_end = valid_new_base + base_plus_top_size;
969
970 log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT "] to "
971 "[" INTPTR_FORMAT " - " INTPTR_FORMAT "], delta = " INTX_FORMAT " bytes", p2i(patch_base + base_size), p2i(patch_end),
972 p2i(valid_new_base + base_size), p2i(valid_new_end), addr_delta);
973
974 SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
975 valid_new_base, valid_new_end, addr_delta);
976 ArchivePtrMarker::ptrmap()->iterate(&patcher);
977 }
978 }
979
980 void DynamicArchiveBuilder::write_regions(FileMapInfo* dynamic_info) {
981 dynamic_info->write_region(MetaspaceShared::rw,
982 MetaspaceShared::read_write_dump_space()->base(),
983 MetaspaceShared::read_write_dump_space()->used(),
984 /*read_only=*/false,/*allow_exec=*/false);
985 dynamic_info->write_region(MetaspaceShared::ro,
986 MetaspaceShared::read_only_dump_space()->base(),
987 MetaspaceShared::read_only_dump_space()->used(),
988 /*read_only=*/true, /*allow_exec=*/false);
989 dynamic_info->write_region(MetaspaceShared::mc,
990 MetaspaceShared::misc_code_dump_space()->base(),
991 MetaspaceShared::misc_code_dump_space()->used(),
992 /*read_only=*/false,/*allow_exec=*/true);
993 dynamic_info->write_bitmap_region(ArchivePtrMarker::ptrmap());
994 }
995
996 void DynamicArchiveBuilder::write_archive(char* serialized_data_start) {
997 int num_klasses = _klasses->length();
998 int num_symbols = _symbols->length();
999
1000 _header->set_serialized_data_start(to_target(serialized_data_start));
1001
1002 FileMapInfo* dynamic_info = FileMapInfo::dynamic_info();
1003 assert(dynamic_info != NULL, "Sanity");
1004
1005 // Now write the archived data including the file offsets.
1006 const char* archive_name = Arguments::GetSharedDynamicArchivePath();
1007 dynamic_info->open_for_write(archive_name);
1008 write_regions(dynamic_info);
1009 dynamic_info->set_final_requested_base((char*)Arguments::default_SharedBaseAddress());
1010 dynamic_info->set_header_crc(dynamic_info->compute_header_crc());
1011 dynamic_info->write_header();
1012 dynamic_info->close();
1013
1014 address base = to_target(_alloc_bottom);
1015 address top = address(current_dump_space()->top()) + _buffer_to_target_delta;
1016 size_t file_size = pointer_delta(top, base, sizeof(char));
1017
1018 base += MetaspaceShared::final_delta();
1019 top += MetaspaceShared::final_delta();
1020 log_info(cds, dynamic)("Written dynamic archive " PTR_FORMAT " - " PTR_FORMAT
1021 " [" SIZE_FORMAT " bytes header, " SIZE_FORMAT " bytes total]",
1022 p2i(base), p2i(top), _header->header_size(), file_size);
1023 log_info(cds, dynamic)("%d klasses; %d symbols", num_klasses, num_symbols);
1024 }
1025
1026
1027 class VM_PopulateDynamicDumpSharedSpace: public VM_Operation {
1028 DynamicArchiveBuilder* _builder;
1029 public:
1030 VM_PopulateDynamicDumpSharedSpace(DynamicArchiveBuilder* builder) : _builder(builder) {}
1031 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1032 void doit() {
1033 ResourceMark rm;
1034 if (SystemDictionaryShared::empty_dumptime_table()) {
1035 log_warning(cds, dynamic)("There is no class to be included in the dynamic archive.");
1036 return;
1037 }
1038 if (AllowArchivingWithJavaAgent) {
1039 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1088 assert(MetaspaceShared::is_in_shared_metaspace(orig_obj), "must be");
1089 return orig_obj;
1090 } else {
1091 return _builder->to_target(buff_obj);
1092 }
1093 }
1094
1095 uintx DynamicArchive::object_delta_uintx(void* buff_obj) {
1096 assert(DynamicDumpSharedSpaces, "must be");
1097 address target_obj = _builder->to_target_no_check(address(buff_obj));
1098 assert(uintx(target_obj) >= SharedBaseAddress, "must be");
1099 return uintx(target_obj) - SharedBaseAddress;
1100 }
1101
1102 bool DynamicArchive::is_in_target_space(void *obj) {
1103 assert(DynamicDumpSharedSpaces, "must be");
1104 return _builder->is_in_target_space(obj);
1105 }
1106
1107
1108 DynamicArchiveBuilder* DynamicArchive::_builder = NULL;
1109
1110
1111 bool DynamicArchive::validate(FileMapInfo* dynamic_info) {
1112 // Check if the recorded base archive matches with the current one
1113 FileMapInfo* base_info = FileMapInfo::current_info();
1114 DynamicArchiveHeader* dynamic_header = dynamic_info->dynamic_header();
1115
1116 // Check the header crc
1117 if (dynamic_header->base_header_crc() != base_info->crc()) {
1118 FileMapInfo::fail_continue("Archive header checksum verification failed.");
1119 return false;
1120 }
1121
1122 // Check each space's crc
1123 for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1124 if (dynamic_header->base_region_crc(i) != base_info->space_crc(i)) {
1125 FileMapInfo::fail_continue("Archive region #%d checksum verification failed.", i);
1126 return false;
1127 }
1128 }
1129
1130 // Validate the dynamic archived shared path table, and set the global
1131 // _shared_path_table to that.
1132 if (!dynamic_info->validate_shared_path_table()) {
1133 return false;
1134 }
1135 return true;
1136 }
|