6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveHeapWriter.hpp"
28 #include "cds/archiveUtils.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "cds/cppVtables.hpp"
31 #include "cds/dumpAllocStats.hpp"
32 #include "cds/dynamicArchive.hpp"
33 #include "cds/heapShared.hpp"
34 #include "cds/metaspaceShared.hpp"
35 #include "cds/regeneratedClasses.hpp"
36 #include "classfile/classLoaderDataShared.hpp"
37 #include "classfile/javaClasses.hpp"
38 #include "classfile/symbolTable.hpp"
39 #include "classfile/systemDictionaryShared.hpp"
40 #include "classfile/vmClasses.hpp"
41 #include "interpreter/abstractInterpreter.hpp"
42 #include "jvm.h"
43 #include "logging/log.hpp"
44 #include "logging/logStream.hpp"
45 #include "memory/allStatic.hpp"
46 #include "memory/memRegion.hpp"
47 #include "memory/resourceArea.hpp"
48 #include "oops/compressedKlass.inline.hpp"
49 #include "oops/instanceKlass.hpp"
50 #include "oops/objArrayKlass.hpp"
51 #include "oops/objArrayOop.inline.hpp"
52 #include "oops/oopHandle.inline.hpp"
53 #include "runtime/arguments.hpp"
54 #include "runtime/fieldDescriptor.inline.hpp"
55 #include "runtime/globals_extension.hpp"
56 #include "runtime/javaThread.hpp"
57 #include "runtime/sharedRuntime.hpp"
58 #include "utilities/align.hpp"
59 #include "utilities/bitMap.inline.hpp"
60 #include "utilities/formatBuffer.hpp"
61
62 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
63
64 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
65 char* newtop = ArchiveBuilder::current()->_ro_region.top();
66 ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
67 }
68
69 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
70 _total_bytes = 0;
71 _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
72 }
143
144 RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
145 _ptrmap.iterate(&relocator, start, end);
146 }
147
148 ArchiveBuilder::ArchiveBuilder() :
149 _current_dump_region(nullptr),
150 _buffer_bottom(nullptr),
151 _last_verified_top(nullptr),
152 _num_dump_regions_used(0),
153 _other_region_used_bytes(0),
154 _requested_static_archive_bottom(nullptr),
155 _requested_static_archive_top(nullptr),
156 _requested_dynamic_archive_bottom(nullptr),
157 _requested_dynamic_archive_top(nullptr),
158 _mapped_static_archive_bottom(nullptr),
159 _mapped_static_archive_top(nullptr),
160 _buffer_to_requested_delta(0),
161 _rw_region("rw", MAX_SHARED_DELTA),
162 _ro_region("ro", MAX_SHARED_DELTA),
163 _ptrmap(mtClassShared),
164 _rw_ptrmap(mtClassShared),
165 _ro_ptrmap(mtClassShared),
166 _rw_src_objs(),
167 _ro_src_objs(),
168 _src_obj_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
169 _buffered_to_src_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
170 _total_heap_region_size(0),
171 _estimated_metaspaceobj_bytes(0),
172 _estimated_hashtable_bytes(0)
173 {
174 _klasses = new (mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);
175 _symbols = new (mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);
176 _entropy_seed = 0x12345678;
177 assert(_current == nullptr, "must be");
178 _current = this;
179 }
180
181 ArchiveBuilder::~ArchiveBuilder() {
182 assert(_current == this, "must be");
183 _current = nullptr;
184
185 for (int i = 0; i < _symbols->length(); i++) {
209 public:
210 GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
211
212 virtual bool do_unique_ref(Ref* ref, bool read_only) {
213 return _builder->gather_klass_and_symbol(ref, read_only);
214 }
215 };
216
217 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
218 if (ref->obj() == nullptr) {
219 return false;
220 }
221 if (get_follow_mode(ref) != make_a_copy) {
222 return false;
223 }
224 if (ref->msotype() == MetaspaceObj::ClassType) {
225 Klass* klass = (Klass*)ref->obj();
226 assert(klass->is_klass(), "must be");
227 if (!is_excluded(klass)) {
228 _klasses->append(klass);
229 }
230 // See RunTimeClassInfo::get_for()
231 _estimated_metaspaceobj_bytes += align_up(BytesPerWord, SharedSpaceObjectAlignment);
232 } else if (ref->msotype() == MetaspaceObj::SymbolType) {
233 // Make sure the symbol won't be GC'ed while we are dumping the archive.
234 Symbol* sym = (Symbol*)ref->obj();
235 sym->increment_refcount();
236 _symbols->append(sym);
237 }
238
239 int bytes = ref->size() * BytesPerWord;
240 _estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);
241
242 return true; // recurse
243 }
244
245 void ArchiveBuilder::gather_klasses_and_symbols() {
246 ResourceMark rm;
247 log_info(cds)("Gathering classes and symbols ... ");
248 GatherKlassesAndSymbols doit(this);
265 // them deterministically.
266 //
267 // During -Xshare:dump, the order of Symbol creation is strictly determined by
268 // the SharedClassListFile (class loading is done in a single thread and the JIT
269 // is disabled). Also, Symbols are allocated in monotonically increasing addresses
270 // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
271 // ascending address order, we ensure that all Symbols are copied into deterministic
272 // locations in the archive.
273 //
274 // TODO: in the future, if we want to produce deterministic contents in the
275 // dynamic archive, we might need to sort the symbols alphabetically (also see
276 // DynamicArchiveBuilder::sort_methods()).
277 log_info(cds)("Sorting symbols ... ");
278 _symbols->sort(compare_symbols_by_address);
279 sort_klasses();
280
281 // TODO -- we need a proper estimate for the archived modules, etc,
282 // but this should be enough for now
283 _estimated_metaspaceobj_bytes += 200 * 1024 * 1024;
284 }
285 }
286
287 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
288 if (a[0] < b[0]) {
289 return -1;
290 } else {
291 assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
292 return 1;
293 }
294 }
295
296 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
297 return a[0]->name()->fast_compare(b[0]->name());
298 }
299
300 void ArchiveBuilder::sort_klasses() {
301 log_info(cds)("Sorting classes ... ");
302 _klasses->sort(compare_klass_by_name);
303 }
304
305 size_t ArchiveBuilder::estimate_archive_size() {
306 // size of the symbol table and two dictionaries, plus the RunTimeClassInfo's
307 size_t symbol_table_est = SymbolTable::estimate_size_for_archive();
308 size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();
309 _estimated_hashtable_bytes = symbol_table_est + dictionary_est;
310
311 size_t total = 0;
312
313 total += _estimated_metaspaceobj_bytes;
314 total += _estimated_hashtable_bytes;
315
316 // allow fragmentation at the end of each dump region
317 total += _total_dump_regions * MetaspaceShared::core_region_alignment();
318
319 log_info(cds)("_estimated_hashtable_bytes = " SIZE_FORMAT " + " SIZE_FORMAT " = " SIZE_FORMAT,
320 symbol_table_est, dictionary_est, _estimated_hashtable_bytes);
321 log_info(cds)("_estimated_metaspaceobj_bytes = " SIZE_FORMAT, _estimated_metaspaceobj_bytes);
322 log_info(cds)("total estimate bytes = " SIZE_FORMAT, total);
323
324 return align_up(total, MetaspaceShared::core_region_alignment());
325 }
326
327 address ArchiveBuilder::reserve_buffer() {
328 size_t buffer_size = estimate_archive_size();
329 ReservedSpace rs(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());
330 if (!rs.is_reserved()) {
404
405 iterate_roots(it);
406 }
407
408 class GatherSortedSourceObjs : public MetaspaceClosure {
409 ArchiveBuilder* _builder;
410
411 public:
412 GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
413
414 virtual bool do_ref(Ref* ref, bool read_only) {
415 return _builder->gather_one_source_obj(ref, read_only);
416 }
417 };
418
419 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only) {
420 address src_obj = ref->obj();
421 if (src_obj == nullptr) {
422 return false;
423 }
424 if (RegeneratedClasses::has_been_regenerated(src_obj)) {
425 // No need to copy it. We will later relocate it to point to the regenerated klass/method.
426 return false;
427 }
428 remember_embedded_pointer_in_enclosing_obj(ref);
429
430 FollowMode follow_mode = get_follow_mode(ref);
431 SourceObjInfo src_info(ref, read_only, follow_mode);
432 bool created;
433 SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
434 if (created) {
435 if (_src_obj_table.maybe_grow()) {
436 log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
437 }
438 }
439
440 #ifdef ASSERT
441 if (ref->msotype() == MetaspaceObj::MethodType) {
442 Method* m = (Method*)ref->obj();
443 assert(!RegeneratedClasses::has_been_regenerated((address)m->method_holder()),
444 "Should not archive methods in a class that has been regenerated");
445 }
446 #endif
447
448 assert(p->read_only() == src_info.read_only(), "must be");
508 _rw_src_objs.remember_embedded_pointer(src_info, ref);
509 }
510 }
511 }
512
513 void ArchiveBuilder::gather_source_objs() {
514 ResourceMark rm;
515 log_info(cds)("Gathering all archivable objects ... ");
516 gather_klasses_and_symbols();
517 GatherSortedSourceObjs doit(this);
518 iterate_sorted_roots(&doit);
519 doit.finish();
520 }
521
522 bool ArchiveBuilder::is_excluded(Klass* klass) {
523 if (klass->is_instance_klass()) {
524 InstanceKlass* ik = InstanceKlass::cast(klass);
525 return SystemDictionaryShared::is_excluded_class(ik);
526 } else if (klass->is_objArray_klass()) {
527 Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
528 if (MetaspaceShared::is_shared_static(bottom)) {
529 // The bottom class is in the static archive so it's clearly not excluded.
530 assert(CDSConfig::is_dumping_dynamic_archive(), "sanity");
531 return false;
532 } else if (bottom->is_instance_klass()) {
533 return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
534 }
535 }
536
537 return false;
538 }
539
540 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
541 address obj = ref->obj();
542 if (MetaspaceShared::is_in_shared_metaspace(obj)) {
543 // Don't dump existing shared metadata again.
544 return point_to_it;
545 } else if (ref->msotype() == MetaspaceObj::MethodDataType ||
546 ref->msotype() == MetaspaceObj::MethodCountersType) {
547 return set_to_null;
548 } else {
549 if (ref->msotype() == MetaspaceObj::ClassType) {
550 Klass* klass = (Klass*)ref->obj();
551 assert(klass->is_klass(), "must be");
552 if (is_excluded(klass)) {
553 ResourceMark rm;
554 log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
555 return set_to_null;
556 }
557 }
558
559 return make_a_copy;
560 }
561 }
562
563 void ArchiveBuilder::start_dump_region(DumpRegion* next) {
564 address bottom = _last_verified_top;
565 address top = (address)(current_dump_region()->top());
566 _other_region_used_bytes += size_t(top - bottom);
567
716 ArchivePtrMarker::mark_pointer(ptr_location);
717 }
718 }
719
720 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
721 assert(*ptr_location != nullptr, "sanity");
722 if (!is_in_mapped_static_archive(*ptr_location)) {
723 *ptr_location = get_buffered_addr(*ptr_location);
724 }
725 ArchivePtrMarker::mark_pointer(ptr_location);
726 }
727
728 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
729 SourceObjInfo* p = _src_obj_table.get(src_addr);
730 assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
731 p2i(src_addr));
732
733 return p->buffered_addr();
734 }
735
736 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
737 assert(is_in_buffer_space(buffered_addr), "must be");
738 address* src_p = _buffered_to_src_table.get(buffered_addr);
739 assert(src_p != nullptr && *src_p != nullptr, "must be");
740 return *src_p;
741 }
742
743 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
744 for (int i = 0; i < src_objs->objs()->length(); i++) {
745 src_objs->relocate(i, this);
746 }
747 }
748
749 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
750 log_info(cds)("Relocating embedded pointers in core regions ... ");
751 relocate_embedded_pointers(&_rw_src_objs);
752 relocate_embedded_pointers(&_ro_src_objs);
753 }
754
755 void ArchiveBuilder::make_klasses_shareable() {
756 int num_instance_klasses = 0;
757 int num_boot_klasses = 0;
758 int num_platform_klasses = 0;
759 int num_app_klasses = 0;
760 int num_hidden_klasses = 0;
761 int num_unlinked_klasses = 0;
762 int num_unregistered_klasses = 0;
763 int num_obj_array_klasses = 0;
764 int num_type_array_klasses = 0;
765
766 for (int i = 0; i < klasses()->length(); i++) {
767 // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
768 // to be in linked state, so it must be call here before the next loop, which returns
769 // all classes to unlinked state.
770 Klass* k = get_buffered_addr(klasses()->at(i));
771 if (k->is_instance_klass()) {
772 InstanceKlass::cast(k)->constants()->remove_unshareable_info();
773 }
774 }
775
776 for (int i = 0; i < klasses()->length(); i++) {
777 const char* type;
778 const char* unlinked = "";
779 const char* hidden = "";
780 const char* generated = "";
781 Klass* k = get_buffered_addr(klasses()->at(i));
782 k->remove_java_mirror();
783 if (k->is_objArray_klass()) {
784 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
785 // on their array classes.
786 num_obj_array_klasses ++;
787 type = "array";
788 } else if (k->is_typeArray_klass()) {
789 num_type_array_klasses ++;
790 type = "array";
791 k->remove_unshareable_info();
792 } else {
793 assert(k->is_instance_klass(), " must be");
794 num_instance_klasses ++;
795 InstanceKlass* ik = InstanceKlass::cast(k);
796 if (ik->is_shared_boot_class()) {
797 type = "boot";
798 num_boot_klasses ++;
799 } else if (ik->is_shared_platform_class()) {
800 type = "plat";
801 num_platform_klasses ++;
802 } else if (ik->is_shared_app_class()) {
803 type = "app";
804 num_app_klasses ++;
805 } else {
806 assert(ik->is_shared_unregistered_class(), "must be");
807 type = "unreg";
808 num_unregistered_klasses ++;
809 }
810
811 if (!ik->is_linked()) {
812 num_unlinked_klasses ++;
813 unlinked = " ** unlinked";
814 }
815
816 if (ik->is_hidden()) {
817 num_hidden_klasses ++;
818 hidden = " ** hidden";
819 }
820
821 if (ik->is_generated_shared_class()) {
822 generated = " ** generated";
823 }
824 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
825 ik->remove_unshareable_info();
826 }
827
828 if (log_is_enabled(Debug, cds, class)) {
829 ResourceMark rm;
830 log_debug(cds, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s", i,
831 p2i(to_requested(k)), type, k->external_name(),
832 hidden, unlinked, generated);
833 }
834 }
835
836 log_info(cds)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
837 log_info(cds)(" instance classes = %5d", num_instance_klasses);
838 log_info(cds)(" boot = %5d", num_boot_klasses);
839 log_info(cds)(" app = %5d", num_app_klasses);
840 log_info(cds)(" platform = %5d", num_platform_klasses);
841 log_info(cds)(" unregistered = %5d", num_unregistered_klasses);
842 log_info(cds)(" (hidden) = %5d", num_hidden_klasses);
843 log_info(cds)(" (unlinked) = %5d", num_unlinked_klasses);
844 log_info(cds)(" obj array classes = %5d", num_obj_array_klasses);
845 log_info(cds)(" type array classes = %5d", num_type_array_klasses);
846 log_info(cds)(" symbols = %5d", _symbols->length());
847
848 DynamicArchive::make_array_klasses_shareable();
849 }
850
851 void ArchiveBuilder::serialize_dynamic_archivable_items(SerializeClosure* soc) {
852 SymbolTable::serialize_shared_table_header(soc, false);
853 SystemDictionaryShared::serialize_dictionary_headers(soc, false);
854 DynamicArchive::serialize_array_klasses(soc);
855 }
856
857 uintx ArchiveBuilder::buffer_to_offset(address p) const {
858 address requested_p = to_requested(p);
859 assert(requested_p >= _requested_static_archive_bottom, "must be");
860 return requested_p - _requested_static_archive_bottom;
861 }
862
863 uintx ArchiveBuilder::any_to_offset(address p) const {
864 if (is_in_mapped_static_archive(p)) {
865 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
866 return p - _mapped_static_archive_bottom;
867 }
868 if (!is_in_buffer_space(p)) {
869 // p must be a "source" address
870 p = get_buffered_addr(p);
871 }
872 return buffer_to_offset(p);
873 }
874
875 #if INCLUDE_CDS_JAVA_HEAP
876 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
877 assert(CDSConfig::is_dumping_heap(), "sanity");
878 k = get_buffered_klass(k);
879 Klass* requested_k = to_requested(k);
880 address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
881 const int narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift;
882 return CompressedKlassPointers::encode_not_null(requested_k, narrow_klass_base, narrow_klass_shift);
883 }
884 #endif // INCLUDE_CDS_JAVA_HEAP
885
886 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
887 // so that the archive can be mapped to the "requested" location without runtime relocation.
888 //
889 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
890 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
891 // - Every pointer must have one of the following values:
892 // [a] nullptr:
893 // No relocation is needed. Remove this pointer from ptrmap so we don't need to
894 // consider it at runtime.
944 } else {
945 assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
946 *p += _mapped_to_requested_static_archive_delta;
947 assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
948 }
949 }
950 _max_non_null_offset = offset;
951 }
952
953 return true; // keep iterating
954 }
955
956 void doit() {
957 ArchivePtrMarker::ptrmap()->iterate(this);
958 ArchivePtrMarker::compact(_max_non_null_offset);
959 }
960 };
961
962
963 void ArchiveBuilder::relocate_to_requested() {
964 ro_region()->pack();
965
966 size_t my_archive_size = buffer_top() - buffer_bottom();
967
968 if (CDSConfig::is_dumping_static_archive()) {
969 _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
970 RelocateBufferToRequested<true> patcher(this);
971 patcher.doit();
972 } else {
973 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
974 _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
975 RelocateBufferToRequested<false> patcher(this);
976 patcher.doit();
977 }
978 }
979
980 // Write detailed info to a mapfile to analyze contents of the archive.
981 // static dump:
982 // java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
983 // dynamic dump:
984 // java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
1206 ArchiveBuilder* builder = ArchiveBuilder::current();
1207 Klass* requested_klass = builder->to_requested(builder->get_buffered_addr(source_klass));
1208
1209 st.print(" - klass: ");
1210 source_klass->print_value_on(&st);
1211 st.print(" " PTR_FORMAT, p2i(requested_klass));
1212 st.cr();
1213
1214 if (source_oop->is_typeArray()) {
1215 TypeArrayKlass::cast(source_klass)->oop_print_elements_on(typeArrayOop(source_oop), &st);
1216 } else if (source_oop->is_objArray()) {
1217 objArrayOop source_obj_array = objArrayOop(source_oop);
1218 for (int i = 0; i < source_obj_array->length(); i++) {
1219 st.print(" -%4d: ", i);
1220 print_oop_with_requested_addr_cr(&st, source_obj_array->obj_at(i));
1221 }
1222 } else {
1223 st.print_cr(" - fields (" SIZE_FORMAT " words):", source_oop->size());
1224 ArchivedFieldPrinter print_field(heap_info, &st, source_oop, buffered_addr);
1225 InstanceKlass::cast(source_klass)->print_nonstatic_fields(&print_field);
1226 }
1227 }
1228 }
1229
1230 static void log_heap_roots() {
1231 LogStreamHandle(Trace, cds, map, oops) st;
1232 if (st.is_enabled()) {
1233 for (int i = 0; i < HeapShared::pending_roots()->length(); i++) {
1234 st.print("roots[%4d]: ", i);
1235 print_oop_with_requested_addr_cr(&st, HeapShared::pending_roots()->at(i));
1236 }
1237 }
1238 }
1239
1240 // The output looks like this. The first number is the requested address. The second number is
1241 // the narrowOop version of the requested address.
1242 // 0x00000007ffc7e840 (0xfff8fd08) java.lang.Class
1243 // 0x00000007ffc000f8 (0xfff8001f) [B length: 11
1244 static void print_oop_with_requested_addr_cr(outputStream* st, oop source_oop, bool print_addr = true) {
1245 if (source_oop == nullptr) {
1246 st->print_cr("null");
1247 } else {
1248 ResourceMark rm;
1249 oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(source_oop);
1250 if (print_addr) {
1251 st->print(PTR_FORMAT " ", p2i(requested_obj));
1252 }
1253 if (UseCompressedOops) {
1254 st->print("(0x%08x) ", CompressedOops::narrow_oop_value(requested_obj));
1255 }
1256 if (source_oop->is_array()) {
1257 int array_len = arrayOop(source_oop)->length();
1258 st->print_cr("%s length: %d", source_oop->klass()->external_name(), array_len);
1259 } else {
1260 st->print_cr("%s", source_oop->klass()->external_name());
1261 }
1262 }
1263 }
1264 #endif // INCLUDE_CDS_JAVA_HEAP
1265
1266 // Log all the data [base...top). Pretend that the base address
1267 // will be mapped to requested_base at run-time.
1268 static void log_as_hex(address base, address top, address requested_base, bool is_heap = false) {
1269 assert(top >= base, "must be");
1270
1271 LogStreamHandle(Trace, cds, map) lsh;
1272 if (lsh.is_enabled()) {
1273 int unitsize = sizeof(address);
1274 if (is_heap && UseCompressedOops) {
1275 // This makes the compressed oop pointers easier to read, but
1276 // longs and doubles will be split into two words.
1277 unitsize = sizeof(narrowOop);
1278 }
1279 os::print_hex_dump(&lsh, base, top, unitsize, /* print_ascii=*/true, /* bytes_per_line=*/32, requested_base);
1280 }
1313 if (heap_info->is_used()) {
1314 log_heap_region(heap_info);
1315 }
1316 #endif
1317
1318 log_info(cds, map)("[End of CDS archive map]");
1319 }
1320 }; // end ArchiveBuilder::CDSMapLogger
1321
1322 void ArchiveBuilder::print_stats() {
1323 _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1324 }
1325
1326 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info) {
1327 // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1328 // MetaspaceShared::n_regions (internal to hotspot).
1329 assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1330
1331 write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1332 write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1333
1334 // Split pointer map into read-write and read-only bitmaps
1335 ArchivePtrMarker::initialize_rw_ro_maps(&_rw_ptrmap, &_ro_ptrmap);
1336
1337 size_t bitmap_size_in_bytes;
1338 char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(), ArchivePtrMarker::ro_ptrmap(), heap_info,
1339 bitmap_size_in_bytes);
1340
1341 if (heap_info->is_used()) {
1342 _total_heap_region_size = mapinfo->write_heap_region(heap_info);
1343 }
1344
1345 print_region_stats(mapinfo, heap_info);
1346
1347 mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1348 mapinfo->set_header_crc(mapinfo->compute_header_crc());
1349 // After this point, we should not write any data into mapinfo->header() since this
1350 // would corrupt its checksum we have calculated before.
1351 mapinfo->write_header();
1352 mapinfo->close();
1353
1354 if (log_is_enabled(Info, cds)) {
1355 print_stats();
1356 }
1357
1358 if (log_is_enabled(Info, cds, map)) {
1364 }
1365
1366 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) {
1367 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1368 }
1369
1370 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
1371 // Print statistics of all the regions
1372 const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1373 const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1374 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() +
1375 bitmap_reserved +
1376 _total_heap_region_size;
1377 const size_t total_bytes = _ro_region.used() + _rw_region.used() +
1378 bitmap_used +
1379 _total_heap_region_size;
1380 const double total_u_perc = percent_of(total_bytes, total_reserved);
1381
1382 _rw_region.print(total_reserved);
1383 _ro_region.print(total_reserved);
1384
1385 print_bitmap_region_stats(bitmap_used, total_reserved);
1386
1387 if (heap_info->is_used()) {
1388 print_heap_region_stats(heap_info, total_reserved);
1389 }
1390
1391 log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1392 total_bytes, total_reserved, total_u_perc);
1393 }
1394
1395 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1396 log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1397 size, size/double(total_size)*100.0, size);
1398 }
1399
1400 void ArchiveBuilder::print_heap_region_stats(ArchiveHeapInfo *info, size_t total_size) {
1401 char* start = info->buffer_start();
1402 size_t size = info->buffer_byte_size();
1403 char* top = start + size;
|
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "cds/aotClassLinker.hpp"
27 #include "cds/aotLinkedClassBulkLoader.hpp"
28 #include "cds/archiveBuilder.hpp"
29 #include "cds/archiveHeapWriter.hpp"
30 #include "cds/archiveUtils.hpp"
31 #include "cds/cdsConfig.hpp"
32 #include "cds/cppVtables.hpp"
33 #include "cds/dumpAllocStats.hpp"
34 #include "cds/dynamicArchive.hpp"
35 #include "cds/finalImageRecipes.hpp"
36 #include "cds/heapShared.hpp"
37 #include "cds/metaspaceShared.hpp"
38 #include "cds/regeneratedClasses.hpp"
39 #include "classfile/classLoader.hpp"
40 #include "classfile/classLoaderExt.hpp"
41 #include "classfile/classLoaderDataShared.hpp"
42 #include "classfile/javaClasses.hpp"
43 #include "classfile/symbolTable.hpp"
44 #include "classfile/systemDictionaryShared.hpp"
45 #include "classfile/vmClasses.hpp"
46 #include "interpreter/abstractInterpreter.hpp"
47 #include "jvm.h"
48 #include "logging/log.hpp"
49 #include "logging/logStream.hpp"
50 #include "memory/allStatic.hpp"
51 #include "memory/memRegion.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "oops/compressedKlass.inline.hpp"
54 #include "oops/instanceKlass.hpp"
55 #include "oops/methodCounters.hpp"
56 #include "oops/methodData.hpp"
57 #include "oops/objArrayKlass.hpp"
58 #include "oops/objArrayOop.inline.hpp"
59 #include "oops/oopHandle.inline.hpp"
60 #include "oops/trainingData.hpp"
61 #include "runtime/arguments.hpp"
62 #include "runtime/fieldDescriptor.inline.hpp"
63 #include "runtime/globals_extension.hpp"
64 #include "runtime/javaThread.hpp"
65 #include "runtime/sharedRuntime.hpp"
66 #include "utilities/align.hpp"
67 #include "utilities/bitMap.inline.hpp"
68 #include "utilities/formatBuffer.hpp"
69
70 ArchiveBuilder* ArchiveBuilder::_current = nullptr;
71
72 ArchiveBuilder::OtherROAllocMark::~OtherROAllocMark() {
73 char* newtop = ArchiveBuilder::current()->_ro_region.top();
74 ArchiveBuilder::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
75 }
76
77 ArchiveBuilder::SourceObjList::SourceObjList() : _ptrmap(16 * K, mtClassShared) {
78 _total_bytes = 0;
79 _objs = new (mtClassShared) GrowableArray<SourceObjInfo*>(128 * K, mtClassShared);
80 }
151
152 RelocateEmbeddedPointers relocator(builder, src_info->buffered_addr(), start);
153 _ptrmap.iterate(&relocator, start, end);
154 }
155
156 ArchiveBuilder::ArchiveBuilder() :
157 _current_dump_region(nullptr),
158 _buffer_bottom(nullptr),
159 _last_verified_top(nullptr),
160 _num_dump_regions_used(0),
161 _other_region_used_bytes(0),
162 _requested_static_archive_bottom(nullptr),
163 _requested_static_archive_top(nullptr),
164 _requested_dynamic_archive_bottom(nullptr),
165 _requested_dynamic_archive_top(nullptr),
166 _mapped_static_archive_bottom(nullptr),
167 _mapped_static_archive_top(nullptr),
168 _buffer_to_requested_delta(0),
169 _rw_region("rw", MAX_SHARED_DELTA),
170 _ro_region("ro", MAX_SHARED_DELTA),
171 _cc_region("cc", MAX_SHARED_DELTA),
172 _ptrmap(mtClassShared),
173 _rw_ptrmap(mtClassShared),
174 _ro_ptrmap(mtClassShared),
175 _cc_ptrmap(mtClassShared),
176 _rw_src_objs(),
177 _ro_src_objs(),
178 _src_obj_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
179 _buffered_to_src_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
180 _total_heap_region_size(0),
181 _estimated_metaspaceobj_bytes(0),
182 _estimated_hashtable_bytes(0)
183 {
184 _klasses = new (mtClassShared) GrowableArray<Klass*>(4 * K, mtClassShared);
185 _symbols = new (mtClassShared) GrowableArray<Symbol*>(256 * K, mtClassShared);
186 _entropy_seed = 0x12345678;
187 assert(_current == nullptr, "must be");
188 _current = this;
189 }
190
191 ArchiveBuilder::~ArchiveBuilder() {
192 assert(_current == this, "must be");
193 _current = nullptr;
194
195 for (int i = 0; i < _symbols->length(); i++) {
219 public:
220 GatherKlassesAndSymbols(ArchiveBuilder* builder) : _builder(builder) {}
221
222 virtual bool do_unique_ref(Ref* ref, bool read_only) {
223 return _builder->gather_klass_and_symbol(ref, read_only);
224 }
225 };
226
227 bool ArchiveBuilder::gather_klass_and_symbol(MetaspaceClosure::Ref* ref, bool read_only) {
228 if (ref->obj() == nullptr) {
229 return false;
230 }
231 if (get_follow_mode(ref) != make_a_copy) {
232 return false;
233 }
234 if (ref->msotype() == MetaspaceObj::ClassType) {
235 Klass* klass = (Klass*)ref->obj();
236 assert(klass->is_klass(), "must be");
237 if (!is_excluded(klass)) {
238 _klasses->append(klass);
239 if (klass->is_hidden() && klass->is_instance_klass()) {
240 update_hidden_class_loader_type(InstanceKlass::cast(klass));
241 }
242 }
243 // See RunTimeClassInfo::get_for()
244 _estimated_metaspaceobj_bytes += align_up(BytesPerWord, SharedSpaceObjectAlignment);
245 } else if (ref->msotype() == MetaspaceObj::SymbolType) {
246 // Make sure the symbol won't be GC'ed while we are dumping the archive.
247 Symbol* sym = (Symbol*)ref->obj();
248 sym->increment_refcount();
249 _symbols->append(sym);
250 }
251
252 int bytes = ref->size() * BytesPerWord;
253 _estimated_metaspaceobj_bytes += align_up(bytes, SharedSpaceObjectAlignment);
254
255 return true; // recurse
256 }
257
258 void ArchiveBuilder::gather_klasses_and_symbols() {
259 ResourceMark rm;
260 log_info(cds)("Gathering classes and symbols ... ");
261 GatherKlassesAndSymbols doit(this);
278 // them deterministically.
279 //
280 // During -Xshare:dump, the order of Symbol creation is strictly determined by
281 // the SharedClassListFile (class loading is done in a single thread and the JIT
282 // is disabled). Also, Symbols are allocated in monotonically increasing addresses
283 // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
284 // ascending address order, we ensure that all Symbols are copied into deterministic
285 // locations in the archive.
286 //
287 // TODO: in the future, if we want to produce deterministic contents in the
288 // dynamic archive, we might need to sort the symbols alphabetically (also see
289 // DynamicArchiveBuilder::sort_methods()).
290 log_info(cds)("Sorting symbols ... ");
291 _symbols->sort(compare_symbols_by_address);
292 sort_klasses();
293
294 // TODO -- we need a proper estimate for the archived modules, etc,
295 // but this should be enough for now
296 _estimated_metaspaceobj_bytes += 200 * 1024 * 1024;
297 }
298
299 AOTClassLinker::add_candidates();
300 }
301
302 #if INCLUDE_CDS_JAVA_HEAP
303
304 void ArchiveBuilder::update_hidden_class_loader_type(InstanceKlass* ik) {
305 s2 classloader_type;
306 if (HeapShared::is_lambda_form_klass(ik)) {
307 assert(CDSConfig::is_dumping_invokedynamic(), "lambda form classes are archived only if CDSConfig::is_dumping_invokedynamic() is true");
308 classloader_type = ClassLoader::BOOT_LOADER;
309 } else if (SystemDictionaryShared::should_hidden_class_be_archived(ik)) {
310 oop loader = ik->class_loader();
311
312 if (loader == nullptr) {
313 classloader_type = ClassLoader::BOOT_LOADER;
314 } else if (SystemDictionary::is_platform_class_loader(loader)) {
315 classloader_type = ClassLoader::PLATFORM_LOADER;
316 } else if (SystemDictionary::is_system_class_loader(loader)) {
317 classloader_type = ClassLoader::APP_LOADER;
318 } else {
319 ShouldNotReachHere();
320 }
321 } else {
322 ShouldNotReachHere();
323 }
324
325 ik->set_shared_class_loader_type(classloader_type);
326 if (HeapShared::is_lambda_proxy_klass(ik)) {
327 InstanceKlass* nest_host = ik->nest_host_not_null();
328 ik->set_shared_classpath_index(nest_host->shared_classpath_index());
329 } else if (!HeapShared::is_lambda_form_klass(ik)) {
330 // Injected invoker classes: fake this for now. Probably not needed!
331 if (classloader_type == ClassLoader::APP_LOADER) {
332 ik->set_shared_classpath_index(ClassLoaderExt::app_class_paths_start_index()); // HACK
333 } else {
334 ik->set_shared_classpath_index(0);
335 }
336 }
337 }
338
339 #endif //INCLUDE_CDS_JAVA_HEAP
340
341 int ArchiveBuilder::compare_symbols_by_address(Symbol** a, Symbol** b) {
342 if (a[0] < b[0]) {
343 return -1;
344 } else {
345 assert(a[0] > b[0], "Duplicated symbol %s unexpected", (*a)->as_C_string());
346 return 1;
347 }
348 }
349
350 int ArchiveBuilder::compare_klass_by_name(Klass** a, Klass** b) {
351 return a[0]->name()->fast_compare(b[0]->name());
352 }
353
354 void ArchiveBuilder::sort_klasses() {
355 log_info(cds)("Sorting classes ... ");
356 _klasses->sort(compare_klass_by_name);
357 }
358
359 size_t ArchiveBuilder::estimate_archive_size() {
360 // size of the symbol table and two dictionaries, plus the RunTimeClassInfo's
361 size_t symbol_table_est = SymbolTable::estimate_size_for_archive();
362 size_t dictionary_est = SystemDictionaryShared::estimate_size_for_archive();
363 size_t training_data_est = TrainingData::estimate_size_for_archive();
364 _estimated_hashtable_bytes = symbol_table_est + dictionary_est + training_data_est;
365
366 if (CDSConfig::is_dumping_aot_linked_classes()) {
367 _estimated_hashtable_bytes += _klasses->length() * 16 * sizeof(Klass*);
368 }
369
370 if (CDSConfig::is_dumping_final_static_archive()) {
371 _estimated_hashtable_bytes += 200 * 1024 * 1024; // FIXME -- need to iterate archived symbols??
372 }
373
374 if (CDSConfig::is_dumping_dynamic_archive()) {
375 // Some extra space for traning data. Be generous. Unused areas will be trimmed from the archive file.
376 _estimated_hashtable_bytes += 200 * 1024 * 1024;
377 }
378 size_t total = 0;
379
380 total += _estimated_metaspaceobj_bytes;
381 total += _estimated_hashtable_bytes;
382
383 // allow fragmentation at the end of each dump region
384 total += _total_dump_regions * MetaspaceShared::core_region_alignment();
385
386 log_info(cds)("_estimated_hashtable_bytes = " SIZE_FORMAT " + " SIZE_FORMAT " = " SIZE_FORMAT,
387 symbol_table_est, dictionary_est, _estimated_hashtable_bytes);
388 log_info(cds)("_estimated_metaspaceobj_bytes = " SIZE_FORMAT, _estimated_metaspaceobj_bytes);
389 log_info(cds)("total estimate bytes = " SIZE_FORMAT, total);
390
391 return align_up(total, MetaspaceShared::core_region_alignment());
392 }
393
394 address ArchiveBuilder::reserve_buffer() {
395 size_t buffer_size = estimate_archive_size();
396 ReservedSpace rs(buffer_size, MetaspaceShared::core_region_alignment(), os::vm_page_size());
397 if (!rs.is_reserved()) {
471
472 iterate_roots(it);
473 }
474
475 class GatherSortedSourceObjs : public MetaspaceClosure {
476 ArchiveBuilder* _builder;
477
478 public:
479 GatherSortedSourceObjs(ArchiveBuilder* builder) : _builder(builder) {}
480
481 virtual bool do_ref(Ref* ref, bool read_only) {
482 return _builder->gather_one_source_obj(ref, read_only);
483 }
484 };
485
486 bool ArchiveBuilder::gather_one_source_obj(MetaspaceClosure::Ref* ref, bool read_only) {
487 address src_obj = ref->obj();
488 if (src_obj == nullptr) {
489 return false;
490 }
491
492 remember_embedded_pointer_in_enclosing_obj(ref);
493 if (RegeneratedClasses::has_been_regenerated(src_obj)) {
494 // No need to copy it. We will later relocate it to point to the regenerated klass/method.
495 return false;
496 }
497
498 FollowMode follow_mode = get_follow_mode(ref);
499 SourceObjInfo src_info(ref, read_only, follow_mode);
500 bool created;
501 SourceObjInfo* p = _src_obj_table.put_if_absent(src_obj, src_info, &created);
502 if (created) {
503 if (_src_obj_table.maybe_grow()) {
504 log_info(cds, hashtables)("Expanded _src_obj_table table to %d", _src_obj_table.table_size());
505 }
506 }
507
508 #ifdef ASSERT
509 if (ref->msotype() == MetaspaceObj::MethodType) {
510 Method* m = (Method*)ref->obj();
511 assert(!RegeneratedClasses::has_been_regenerated((address)m->method_holder()),
512 "Should not archive methods in a class that has been regenerated");
513 }
514 #endif
515
516 assert(p->read_only() == src_info.read_only(), "must be");
576 _rw_src_objs.remember_embedded_pointer(src_info, ref);
577 }
578 }
579 }
580
581 void ArchiveBuilder::gather_source_objs() {
582 ResourceMark rm;
583 log_info(cds)("Gathering all archivable objects ... ");
584 gather_klasses_and_symbols();
585 GatherSortedSourceObjs doit(this);
586 iterate_sorted_roots(&doit);
587 doit.finish();
588 }
589
590 bool ArchiveBuilder::is_excluded(Klass* klass) {
591 if (klass->is_instance_klass()) {
592 InstanceKlass* ik = InstanceKlass::cast(klass);
593 return SystemDictionaryShared::is_excluded_class(ik);
594 } else if (klass->is_objArray_klass()) {
595 Klass* bottom = ObjArrayKlass::cast(klass)->bottom_klass();
596 if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_shared_static(bottom)) {
597 // The bottom class is in the static archive so it's clearly not excluded.
598 assert(CDSConfig::is_dumping_dynamic_archive(), "sanity");
599 return false;
600 } else if (bottom->is_instance_klass()) {
601 return SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(bottom));
602 }
603 }
604
605 return false;
606 }
607
608 ArchiveBuilder::FollowMode ArchiveBuilder::get_follow_mode(MetaspaceClosure::Ref *ref) {
609 address obj = ref->obj();
610 if (CDSConfig::is_dumping_dynamic_archive() && MetaspaceShared::is_in_shared_metaspace(obj)) {
611 // Don't dump existing shared metadata again.
612 return point_to_it;
613 } else if (ref->msotype() == MetaspaceObj::MethodDataType ||
614 ref->msotype() == MetaspaceObj::MethodCountersType ||
615 ref->msotype() == MetaspaceObj::KlassTrainingDataType ||
616 ref->msotype() == MetaspaceObj::MethodTrainingDataType ||
617 ref->msotype() == MetaspaceObj::CompileTrainingDataType) {
618 return TrainingData::need_data() ? make_a_copy : set_to_null;
619 } else {
620 if (ref->msotype() == MetaspaceObj::ClassType) {
621 Klass* klass = (Klass*)ref->obj();
622 assert(klass->is_klass(), "must be");
623 if (is_excluded(klass)) {
624 ResourceMark rm;
625 log_debug(cds, dynamic)("Skipping class (excluded): %s", klass->external_name());
626 return set_to_null;
627 }
628 }
629
630 return make_a_copy;
631 }
632 }
633
634 void ArchiveBuilder::start_dump_region(DumpRegion* next) {
635 address bottom = _last_verified_top;
636 address top = (address)(current_dump_region()->top());
637 _other_region_used_bytes += size_t(top - bottom);
638
787 ArchivePtrMarker::mark_pointer(ptr_location);
788 }
789 }
790
791 void ArchiveBuilder::mark_and_relocate_to_buffered_addr(address* ptr_location) {
792 assert(*ptr_location != nullptr, "sanity");
793 if (!is_in_mapped_static_archive(*ptr_location)) {
794 *ptr_location = get_buffered_addr(*ptr_location);
795 }
796 ArchivePtrMarker::mark_pointer(ptr_location);
797 }
798
799 address ArchiveBuilder::get_buffered_addr(address src_addr) const {
800 SourceObjInfo* p = _src_obj_table.get(src_addr);
801 assert(p != nullptr, "src_addr " INTPTR_FORMAT " is used but has not been archived",
802 p2i(src_addr));
803
804 return p->buffered_addr();
805 }
806
807 bool ArchiveBuilder::has_been_archived(address src_addr) const {
808 SourceObjInfo* p = _src_obj_table.get(src_addr);
809 return (p != nullptr);
810 }
811
812 address ArchiveBuilder::get_source_addr(address buffered_addr) const {
813 assert(is_in_buffer_space(buffered_addr), "must be");
814 address* src_p = _buffered_to_src_table.get(buffered_addr);
815 assert(src_p != nullptr && *src_p != nullptr, "must be");
816 return *src_p;
817 }
818
819 void ArchiveBuilder::relocate_embedded_pointers(ArchiveBuilder::SourceObjList* src_objs) {
820 for (int i = 0; i < src_objs->objs()->length(); i++) {
821 src_objs->relocate(i, this);
822 }
823 }
824
825 void ArchiveBuilder::relocate_metaspaceobj_embedded_pointers() {
826 log_info(cds)("Relocating embedded pointers in core regions ... ");
827 relocate_embedded_pointers(&_rw_src_objs);
828 relocate_embedded_pointers(&_ro_src_objs);
829 }
830
831 #define ADD_COUNT(x) \
832 x += 1; \
833 x ## _a += aotlinked; \
834 x ## _i += inited;
835
836 #define DECLARE_INSTANCE_KLASS_COUNTER(x) \
837 int x = 0; \
838 int x ## _a = 0; \
839 int x ## _i = 0;
840
841 void ArchiveBuilder::make_klasses_shareable() {
842 DECLARE_INSTANCE_KLASS_COUNTER(num_instance_klasses);
843 DECLARE_INSTANCE_KLASS_COUNTER(num_boot_klasses);
844 DECLARE_INSTANCE_KLASS_COUNTER(num_vm_klasses);
845 DECLARE_INSTANCE_KLASS_COUNTER(num_platform_klasses);
846 DECLARE_INSTANCE_KLASS_COUNTER(num_app_klasses);
847 DECLARE_INSTANCE_KLASS_COUNTER(num_hidden_klasses);
848 DECLARE_INSTANCE_KLASS_COUNTER(num_unlinked_klasses);
849 DECLARE_INSTANCE_KLASS_COUNTER(num_unregistered_klasses);
850 int num_obj_array_klasses = 0;
851 int num_type_array_klasses = 0;
852
853 int boot_unlinked = 0;
854 int platform_unlinked = 0;
855 int app_unlinked = 0;
856 int unreg_unlinked = 0;
857
858 for (int i = 0; i < klasses()->length(); i++) {
859 // Some of the code in ConstantPool::remove_unshareable_info() requires the classes
860 // to be in linked state, so it must be call here before the next loop, which returns
861 // all classes to unlinked state.
862 Klass* k = get_buffered_addr(klasses()->at(i));
863 if (k->is_instance_klass()) {
864 InstanceKlass::cast(k)->constants()->remove_unshareable_info();
865 }
866 }
867
868 for (int i = 0; i < klasses()->length(); i++) {
869 const char* type;
870 const char* unlinked = "";
871 const char* kind = "";
872 const char* hidden = "";
873 const char* generated = "";
874 const char* aotlinked_msg = "";
875 const char* inited_msg = "";
876 Klass* k = get_buffered_addr(klasses()->at(i));
877 k->remove_java_mirror();
878 if (k->is_objArray_klass()) {
879 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
880 // on their array classes.
881 num_obj_array_klasses ++;
882 type = "array";
883 } else if (k->is_typeArray_klass()) {
884 num_type_array_klasses ++;
885 type = "array";
886 k->remove_unshareable_info();
887 } else {
888 assert(k->is_instance_klass(), " must be");
889 InstanceKlass* ik = InstanceKlass::cast(k);
890 InstanceKlass* src_ik = get_source_addr(ik);
891 int aotlinked = AOTClassLinker::is_candidate(src_ik);
892 int inited = ik->has_preinitialized_mirror();
893 ADD_COUNT(num_instance_klasses);
894 if (CDSConfig::is_dumping_dynamic_archive()) {
895 // For static dump, class loader type are already set.
896 ik->assign_class_loader_type();
897 }
898 if (ik->is_hidden()) {
899 oop loader = k->class_loader();
900 if (loader == nullptr) {
901 type = "boot";
902 ADD_COUNT(num_boot_klasses);
903 } else if (loader == SystemDictionary::java_platform_loader()) {
904 type = "plat";
905 ADD_COUNT(num_platform_klasses);
906 } else if (loader == SystemDictionary::java_system_loader()) {
907 type = "app";
908 ADD_COUNT(num_app_klasses);
909 } else {
910 type = "bad";
911 assert(0, "shouldn't happen");
912 }
913 } else if (ik->is_shared_boot_class()) {
914 type = "boot";
915 ADD_COUNT(num_boot_klasses);
916 } else if (ik->is_shared_platform_class()) {
917 type = "plat";
918 ADD_COUNT(num_platform_klasses);
919 } else if (ik->is_shared_app_class()) {
920 type = "app";
921 ADD_COUNT(num_app_klasses);
922 } else {
923 assert(ik->is_shared_unregistered_class(), "must be");
924 type = "unreg";
925 ADD_COUNT(num_unregistered_klasses);
926 }
927
928 if (AOTClassLinker::is_vm_class(src_ik)) {
929 ADD_COUNT(num_vm_klasses);
930 }
931
932 if (!ik->is_linked()) {
933 ADD_COUNT(num_unlinked_klasses);
934 unlinked = " unlinked";
935 if (ik->is_shared_boot_class()) {
936 boot_unlinked ++;
937 } else if (ik->is_shared_platform_class()) {
938 platform_unlinked ++;
939 } else if (ik->is_shared_app_class()) {
940 app_unlinked ++;
941 } else {
942 unreg_unlinked ++;
943 }
944 }
945
946 if (ik->is_interface()) {
947 kind = " interface";
948 } else if (src_ik->java_super() == vmClasses::Enum_klass()) {
949 kind = " enum";
950 }
951
952 if (ik->is_hidden()) {
953 ADD_COUNT(num_hidden_klasses);
954 hidden = " hidden";
955 }
956
957 if (ik->is_generated_shared_class()) {
958 generated = " generated";
959 }
960 if (aotlinked) {
961 aotlinked_msg = " aot-linked";
962 }
963 if (inited) {
964 inited_msg = " inited";
965 }
966
967 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread::current(), ik);
968 ik->remove_unshareable_info();
969 }
970
971 if (log_is_enabled(Debug, cds, class)) {
972 ResourceMark rm;
973 log_debug(cds, class)("klasses[%5d] = " PTR_FORMAT " %-5s %s%s%s%s%s%s%s", i,
974 p2i(to_requested(k)), type, k->external_name(),
975 kind, hidden, unlinked, generated, aotlinked_msg, inited_msg);
976 }
977 }
978
979 #define STATS_FORMAT "= %5d, aot-linked = %5d, inited = %5d"
980 #define STATS_PARAMS(x) num_ ## x, num_ ## x ## _a, num_ ## x ## _i
981
982 log_info(cds)("Number of classes %d", num_instance_klasses + num_obj_array_klasses + num_type_array_klasses);
983 log_info(cds)(" instance classes " STATS_FORMAT, STATS_PARAMS(instance_klasses));
984 log_info(cds)(" boot " STATS_FORMAT, STATS_PARAMS(boot_klasses));
985 log_info(cds)(" vm " STATS_FORMAT, STATS_PARAMS(vm_klasses));
986 log_info(cds)(" platform " STATS_FORMAT, STATS_PARAMS(platform_klasses));
987 log_info(cds)(" app " STATS_FORMAT, STATS_PARAMS(app_klasses));
988 log_info(cds)(" unregistered " STATS_FORMAT, STATS_PARAMS(unregistered_klasses));
989 log_info(cds)(" (hidden) " STATS_FORMAT, STATS_PARAMS(hidden_klasses));
990 log_info(cds)(" (unlinked) " STATS_FORMAT ", boot = %d, plat = %d, app = %d, unreg = %d",
991 STATS_PARAMS(unlinked_klasses),
992 boot_unlinked, platform_unlinked,
993 app_unlinked, unreg_unlinked);
994 log_info(cds)(" obj array classes = %5d", num_obj_array_klasses);
995 log_info(cds)(" type array classes = %5d", num_type_array_klasses);
996 log_info(cds)(" symbols = %5d", _symbols->length());
997
998 #undef STATS_FORMAT
999 #undef STATS_PARAMS
1000
1001 DynamicArchive::make_array_klasses_shareable();
1002 }
1003
1004 void ArchiveBuilder::make_training_data_shareable() {
1005 auto clean_td = [&] (address& src_obj, SourceObjInfo& info) {
1006 if (!is_in_buffer_space(info.buffered_addr())) {
1007 return;
1008 }
1009
1010 if (info.msotype() == MetaspaceObj::KlassTrainingDataType ||
1011 info.msotype() == MetaspaceObj::MethodTrainingDataType ||
1012 info.msotype() == MetaspaceObj::CompileTrainingDataType) {
1013 TrainingData* buffered_td = (TrainingData*)info.buffered_addr();
1014 buffered_td->remove_unshareable_info();
1015 } else if (info.msotype() == MetaspaceObj::MethodDataType) {
1016 MethodData* buffered_mdo = (MethodData*)info.buffered_addr();
1017 buffered_mdo->remove_unshareable_info();
1018 } else if (info.msotype() == MetaspaceObj::MethodCountersType) {
1019 MethodCounters* buffered_mc = (MethodCounters*)info.buffered_addr();
1020 buffered_mc->remove_unshareable_info();
1021 }
1022 };
1023 _src_obj_table.iterate_all(clean_td);
1024 }
1025
1026 void ArchiveBuilder::serialize_dynamic_archivable_items(SerializeClosure* soc) {
1027 SymbolTable::serialize_shared_table_header(soc, false);
1028 SystemDictionaryShared::serialize_dictionary_headers(soc, false);
1029 DynamicArchive::serialize_array_klasses(soc);
1030 AOTLinkedClassBulkLoader::serialize(soc, false);
1031 FinalImageRecipes::serialize(soc, false);
1032 TrainingData::serialize_training_data(soc);
1033 }
1034
1035 uintx ArchiveBuilder::buffer_to_offset(address p) const {
1036 address requested_p = to_requested(p);
1037 assert(requested_p >= _requested_static_archive_bottom, "must be");
1038 return requested_p - _requested_static_archive_bottom;
1039 }
1040
1041 uintx ArchiveBuilder::any_to_offset(address p) const {
1042 if (is_in_mapped_static_archive(p)) {
1043 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1044 return p - _mapped_static_archive_bottom;
1045 }
1046 if (!is_in_buffer_space(p)) {
1047 // p must be a "source" address
1048 p = get_buffered_addr(p);
1049 }
1050 return buffer_to_offset(p);
1051 }
1052
1053 void ArchiveBuilder::start_cc_region() {
1054 ro_region()->pack();
1055 start_dump_region(&_cc_region);
1056 }
1057
1058 void ArchiveBuilder::end_cc_region() {
1059 _cc_region.pack();
1060 }
1061
1062 #if INCLUDE_CDS_JAVA_HEAP
1063 narrowKlass ArchiveBuilder::get_requested_narrow_klass(Klass* k) {
1064 assert(CDSConfig::is_dumping_heap(), "sanity");
1065 k = get_buffered_klass(k);
1066 Klass* requested_k = to_requested(k);
1067 address narrow_klass_base = _requested_static_archive_bottom; // runtime encoding base == runtime mapping start
1068 const int narrow_klass_shift = ArchiveHeapWriter::precomputed_narrow_klass_shift;
1069 return CompressedKlassPointers::encode_not_null(requested_k, narrow_klass_base, narrow_klass_shift);
1070 }
1071 #endif // INCLUDE_CDS_JAVA_HEAP
1072
1073 // RelocateBufferToRequested --- Relocate all the pointers in rw/ro,
1074 // so that the archive can be mapped to the "requested" location without runtime relocation.
1075 //
1076 // - See ArchiveBuilder header for the definition of "buffer", "mapped" and "requested"
1077 // - ArchivePtrMarker::ptrmap() marks all the pointers in the rw/ro regions
1078 // - Every pointer must have one of the following values:
1079 // [a] nullptr:
1080 // No relocation is needed. Remove this pointer from ptrmap so we don't need to
1081 // consider it at runtime.
1131 } else {
1132 assert(_builder->is_in_mapped_static_archive(*p), "old pointer must point inside buffer space or mapped static archive");
1133 *p += _mapped_to_requested_static_archive_delta;
1134 assert(_builder->is_in_requested_static_archive(*p), "new pointer must point inside requested archive");
1135 }
1136 }
1137 _max_non_null_offset = offset;
1138 }
1139
1140 return true; // keep iterating
1141 }
1142
1143 void doit() {
1144 ArchivePtrMarker::ptrmap()->iterate(this);
1145 ArchivePtrMarker::compact(_max_non_null_offset);
1146 }
1147 };
1148
1149
1150 void ArchiveBuilder::relocate_to_requested() {
1151 if (!ro_region()->is_packed()) {
1152 ro_region()->pack();
1153 }
1154
1155 size_t my_archive_size = buffer_top() - buffer_bottom();
1156
1157 if (CDSConfig::is_dumping_static_archive()) {
1158 _requested_static_archive_top = _requested_static_archive_bottom + my_archive_size;
1159 RelocateBufferToRequested<true> patcher(this);
1160 patcher.doit();
1161 } else {
1162 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
1163 _requested_dynamic_archive_top = _requested_dynamic_archive_bottom + my_archive_size;
1164 RelocateBufferToRequested<false> patcher(this);
1165 patcher.doit();
1166 }
1167 }
1168
1169 // Write detailed info to a mapfile to analyze contents of the archive.
1170 // static dump:
1171 // java -Xshare:dump -Xlog:cds+map=trace:file=cds.map:none:filesize=0
1172 // dynamic dump:
1173 // java -cp MyApp.jar -XX:ArchiveClassesAtExit=MyApp.jsa \
1395 ArchiveBuilder* builder = ArchiveBuilder::current();
1396 Klass* requested_klass = builder->to_requested(builder->get_buffered_addr(source_klass));
1397
1398 st.print(" - klass: ");
1399 source_klass->print_value_on(&st);
1400 st.print(" " PTR_FORMAT, p2i(requested_klass));
1401 st.cr();
1402
1403 if (source_oop->is_typeArray()) {
1404 TypeArrayKlass::cast(source_klass)->oop_print_elements_on(typeArrayOop(source_oop), &st);
1405 } else if (source_oop->is_objArray()) {
1406 objArrayOop source_obj_array = objArrayOop(source_oop);
1407 for (int i = 0; i < source_obj_array->length(); i++) {
1408 st.print(" -%4d: ", i);
1409 print_oop_with_requested_addr_cr(&st, source_obj_array->obj_at(i));
1410 }
1411 } else {
1412 st.print_cr(" - fields (" SIZE_FORMAT " words):", source_oop->size());
1413 ArchivedFieldPrinter print_field(heap_info, &st, source_oop, buffered_addr);
1414 InstanceKlass::cast(source_klass)->print_nonstatic_fields(&print_field);
1415
1416 if (java_lang_Class::is_instance(source_oop)) {
1417 st.print(" - signature: ");
1418 if (java_lang_Class::is_primitive(source_oop)) {
1419 st.print("primitive ??");
1420 } else {
1421 java_lang_Class::print_signature(source_oop, &st);
1422 }
1423 st.cr();
1424 }
1425 }
1426 }
1427 }
1428
1429 static void log_heap_roots() {
1430 LogStreamHandle(Trace, cds, map, oops) st;
1431 if (st.is_enabled()) {
1432 for (int i = 0; i < HeapShared::pending_roots()->length(); i++) {
1433 st.print("roots[%4d]: ", i);
1434 print_oop_with_requested_addr_cr(&st, HeapShared::pending_roots()->at(i).resolve());
1435 }
1436 }
1437 }
1438
1439 // The output looks like this. The first number is the requested address. The second number is
1440 // the narrowOop version of the requested address.
1441 // 0x00000007ffc7e840 (0xfff8fd08) java.lang.Class
1442 // 0x00000007ffc000f8 (0xfff8001f) [B length: 11
1443 static void print_oop_with_requested_addr_cr(outputStream* st, oop source_oop, bool print_addr = true) {
1444 if (source_oop == nullptr) {
1445 st->print_cr("null");
1446 } else {
1447 ResourceMark rm;
1448 oop requested_obj = ArchiveHeapWriter::source_obj_to_requested_obj(source_oop);
1449 if (print_addr) {
1450 st->print(PTR_FORMAT " ", p2i(requested_obj));
1451 }
1452 if (UseCompressedOops) {
1453 st->print("(0x%08x) ", CompressedOops::narrow_oop_value(requested_obj));
1454 }
1455 if (source_oop->is_array()) {
1456 int array_len = arrayOop(source_oop)->length();
1457 st->print_cr("%s length: %d", source_oop->klass()->external_name(), array_len);
1458 } else {
1459 st->print("%s", source_oop->klass()->external_name());
1460 if (java_lang_invoke_MethodType::is_instance(source_oop)) {
1461 st->print(" ");
1462 java_lang_invoke_MethodType::print_signature(source_oop, st);
1463 }
1464 st->cr();
1465 }
1466 }
1467 }
1468 #endif // INCLUDE_CDS_JAVA_HEAP
1469
1470 // Log all the data [base...top). Pretend that the base address
1471 // will be mapped to requested_base at run-time.
1472 static void log_as_hex(address base, address top, address requested_base, bool is_heap = false) {
1473 assert(top >= base, "must be");
1474
1475 LogStreamHandle(Trace, cds, map) lsh;
1476 if (lsh.is_enabled()) {
1477 int unitsize = sizeof(address);
1478 if (is_heap && UseCompressedOops) {
1479 // This makes the compressed oop pointers easier to read, but
1480 // longs and doubles will be split into two words.
1481 unitsize = sizeof(narrowOop);
1482 }
1483 os::print_hex_dump(&lsh, base, top, unitsize, /* print_ascii=*/true, /* bytes_per_line=*/32, requested_base);
1484 }
1517 if (heap_info->is_used()) {
1518 log_heap_region(heap_info);
1519 }
1520 #endif
1521
1522 log_info(cds, map)("[End of CDS archive map]");
1523 }
1524 }; // end ArchiveBuilder::CDSMapLogger
1525
1526 void ArchiveBuilder::print_stats() {
1527 _alloc_stats.print_stats(int(_ro_region.used()), int(_rw_region.used()));
1528 }
1529
1530 void ArchiveBuilder::write_archive(FileMapInfo* mapinfo, ArchiveHeapInfo* heap_info) {
1531 // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1532 // MetaspaceShared::n_regions (internal to hotspot).
1533 assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1534
1535 write_region(mapinfo, MetaspaceShared::rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1536 write_region(mapinfo, MetaspaceShared::ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1537 write_region(mapinfo, MetaspaceShared::cc, &_cc_region, /*read_only=*/false,/*allow_exec=*/false);
1538
1539 // Split pointer map into read-write and read-only bitmaps
1540 ArchivePtrMarker::initialize_rw_ro_cc_maps(&_rw_ptrmap, &_ro_ptrmap, &_cc_ptrmap);
1541
1542 size_t bitmap_size_in_bytes;
1543 char* bitmap = mapinfo->write_bitmap_region(ArchivePtrMarker::rw_ptrmap(),
1544 ArchivePtrMarker::ro_ptrmap(),
1545 ArchivePtrMarker::cc_ptrmap(),
1546 heap_info,
1547 bitmap_size_in_bytes);
1548
1549 if (heap_info->is_used()) {
1550 _total_heap_region_size = mapinfo->write_heap_region(heap_info);
1551 }
1552
1553 print_region_stats(mapinfo, heap_info);
1554
1555 mapinfo->set_requested_base((char*)MetaspaceShared::requested_base_address());
1556 mapinfo->set_header_crc(mapinfo->compute_header_crc());
1557 // After this point, we should not write any data into mapinfo->header() since this
1558 // would corrupt its checksum we have calculated before.
1559 mapinfo->write_header();
1560 mapinfo->close();
1561
1562 if (log_is_enabled(Info, cds)) {
1563 print_stats();
1564 }
1565
1566 if (log_is_enabled(Info, cds, map)) {
1572 }
1573
1574 void ArchiveBuilder::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) {
1575 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1576 }
1577
1578 void ArchiveBuilder::print_region_stats(FileMapInfo *mapinfo, ArchiveHeapInfo* heap_info) {
1579 // Print statistics of all the regions
1580 const size_t bitmap_used = mapinfo->region_at(MetaspaceShared::bm)->used();
1581 const size_t bitmap_reserved = mapinfo->region_at(MetaspaceShared::bm)->used_aligned();
1582 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() +
1583 bitmap_reserved +
1584 _total_heap_region_size;
1585 const size_t total_bytes = _ro_region.used() + _rw_region.used() +
1586 bitmap_used +
1587 _total_heap_region_size;
1588 const double total_u_perc = percent_of(total_bytes, total_reserved);
1589
1590 _rw_region.print(total_reserved);
1591 _ro_region.print(total_reserved);
1592 _cc_region.print(total_reserved);
1593
1594 print_bitmap_region_stats(bitmap_used, total_reserved);
1595
1596 if (heap_info->is_used()) {
1597 print_heap_region_stats(heap_info, total_reserved);
1598 }
1599
1600 log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1601 total_bytes, total_reserved, total_u_perc);
1602 }
1603
1604 void ArchiveBuilder::print_bitmap_region_stats(size_t size, size_t total_size) {
1605 log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1606 size, size/double(total_size)*100.0, size);
1607 }
1608
1609 void ArchiveBuilder::print_heap_region_stats(ArchiveHeapInfo *info, size_t total_size) {
1610 char* start = info->buffer_start();
1611 size_t size = info->buffer_byte_size();
1612 char* top = start + size;
|