1 /*
2 * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "classfile/classLoaderDataGraph.hpp"
28 #include "classfile/classListParser.hpp"
29 #include "classfile/classLoaderExt.hpp"
30 #include "classfile/dictionary.hpp"
31 #include "classfile/loaderConstraints.hpp"
32 #include "classfile/javaClasses.inline.hpp"
33 #include "classfile/placeholders.hpp"
34 #include "classfile/symbolTable.hpp"
35 #include "classfile/stringTable.hpp"
36 #include "classfile/systemDictionary.hpp"
37 #include "classfile/systemDictionaryShared.hpp"
38 #include "code/codeCache.hpp"
39 #include "gc/shared/softRefPolicy.hpp"
40 #include "interpreter/bytecodeStream.hpp"
41 #include "interpreter/bytecodes.hpp"
42 #include "logging/log.hpp"
43 #include "logging/logMessage.hpp"
44 #include "memory/archiveUtils.inline.hpp"
45 #include "memory/dynamicArchive.hpp"
46 #include "memory/filemap.hpp"
47 #include "memory/heapShared.inline.hpp"
48 #include "memory/metaspace.hpp"
49 #include "memory/metaspaceClosure.hpp"
50 #include "memory/metaspaceShared.hpp"
51 #include "memory/resourceArea.hpp"
52 #include "memory/universe.hpp"
53 #include "oops/compressedOops.inline.hpp"
54 #include "oops/instanceClassLoaderKlass.hpp"
55 #include "oops/instanceMirrorKlass.hpp"
56 #include "oops/instanceRefKlass.hpp"
57 #include "oops/methodData.hpp"
58 #include "oops/objArrayKlass.hpp"
59 #include "oops/objArrayOop.hpp"
60 #include "oops/oop.inline.hpp"
61 #include "oops/typeArrayKlass.hpp"
62 #include "prims/jvmtiRedefineClasses.hpp"
63 #include "runtime/handles.inline.hpp"
64 #include "runtime/os.hpp"
65 #include "runtime/safepointVerifiers.hpp"
66 #include "runtime/signature.hpp"
67 #include "runtime/timerTrace.hpp"
68 #include "runtime/vmThread.hpp"
69 #include "runtime/vmOperations.hpp"
70 #include "utilities/align.hpp"
71 #include "utilities/bitMap.inline.hpp"
72 #include "utilities/ostream.hpp"
73 #include "utilities/defaultStream.hpp"
74 #include "utilities/hashtable.inline.hpp"
75 #if INCLUDE_G1GC
76 #include "gc/g1/g1CollectedHeap.hpp"
77 #endif
78
79 ReservedSpace MetaspaceShared::_shared_rs;
80 VirtualSpace MetaspaceShared::_shared_vs;
81 ReservedSpace MetaspaceShared::_symbol_rs;
82 VirtualSpace MetaspaceShared::_symbol_vs;
83 MetaspaceSharedStats MetaspaceShared::_stats;
84 bool MetaspaceShared::_has_error_classes;
85 bool MetaspaceShared::_archive_loading_failed = false;
86 bool MetaspaceShared::_remapped_readwrite = false;
87 address MetaspaceShared::_i2i_entry_code_buffers = NULL;
88 size_t MetaspaceShared::_i2i_entry_code_buffers_size = 0;
89 void* MetaspaceShared::_shared_metaspace_static_top = NULL;
90 intx MetaspaceShared::_relocation_delta;
91 char* MetaspaceShared::_requested_base_address;
92 bool MetaspaceShared::_use_optimized_module_handling = true;
93
94 // The CDS archive is divided into the following regions:
95 // mc - misc code (the method entry trampolines, c++ vtables)
96 // rw - read-write metadata
97 // ro - read-only metadata and read-only tables
98 //
99 // ca0 - closed archive heap space #0
100 // ca1 - closed archive heap space #1 (may be empty)
101 // oa0 - open archive heap space #0
102 // oa1 - open archive heap space #1 (may be empty)
103 //
104 // The mc, rw, and ro regions are linearly allocated, starting from
105 // SharedBaseAddress, in the order of mc->rw->ro. The size of these 3 regions
106 // are page-aligned, and there's no gap between any consecutive regions.
107 //
108 // These 3 regions are populated in the following steps:
109 // [1] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
110 // temporarily allocated outside of the shared regions. Only the method entry
111 // trampolines are written into the mc region.
112 // [2] C++ vtables are copied into the mc region.
113 // [3] ArchiveCompactor copies RW metadata into the rw region.
114 // [4] ArchiveCompactor copies RO metadata into the ro region.
115 // [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
116 // are copied into the ro region as read-only tables.
117 //
118 // The s0/s1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
119 // Their layout is independent of the other 4 regions.
120
121 char* DumpRegion::expand_top_to(char* newtop) {
122 assert(is_allocatable(), "must be initialized and not packed");
123 assert(newtop >= _top, "must not grow backwards");
124 if (newtop > _end) {
125 MetaspaceShared::report_out_of_space(_name, newtop - _top);
126 ShouldNotReachHere();
127 }
128
129 if (_rs == MetaspaceShared::shared_rs()) {
130 uintx delta;
131 if (DynamicDumpSharedSpaces) {
132 delta = DynamicArchive::object_delta_uintx(newtop);
133 } else {
134 delta = MetaspaceShared::object_delta_uintx(newtop);
135 }
136 if (delta > MAX_SHARED_DELTA) {
137 // This is just a sanity check and should not appear in any real world usage. This
138 // happens only if you allocate more than 2GB of shared objects and would require
139 // millions of shared classes.
140 vm_exit_during_initialization("Out of memory in the CDS archive",
141 "Please reduce the number of shared classes.");
142 }
143 }
144
145 MetaspaceShared::commit_to(_rs, _vs, newtop);
146 _top = newtop;
147 return _top;
148 }
149
150 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
151 char* p = (char*)align_up(_top, alignment);
152 char* newtop = p + align_up(num_bytes, alignment);
153 expand_top_to(newtop);
154 memset(p, 0, newtop - p);
155 return p;
156 }
157
158 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
159 assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
160 intptr_t *p = (intptr_t*)_top;
161 char* newtop = _top + sizeof(intptr_t);
162 expand_top_to(newtop);
163 *p = n;
164 if (need_to_mark) {
165 ArchivePtrMarker::mark_pointer(p);
166 }
167 }
168
169 void DumpRegion::print(size_t total_bytes) const {
170 log_debug(cds)("%-3s space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used] at " INTPTR_FORMAT,
171 _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
172 p2i(_base + MetaspaceShared::final_delta()));
173 }
174
175 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
176 log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
177 _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
178 if (strcmp(_name, failing_region) == 0) {
179 log_error(cds)(" required = %d", int(needed_bytes));
180 }
181 }
182
183 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
184 _rs = rs;
185 _vs = vs;
186 // Start with 0 committed bytes. The memory will be committed as needed by
187 // MetaspaceShared::commit_to().
188 if (!_vs->initialize(*_rs, 0)) {
189 fatal("Unable to allocate memory for shared space");
190 }
191 _base = _top = _rs->base();
192 _end = _rs->end();
193 }
194
195 void DumpRegion::pack(DumpRegion* next) {
196 assert(!is_packed(), "sanity");
197 _end = (char*)align_up(_top, MetaspaceShared::reserved_space_alignment());
198 _is_packed = true;
199 if (next != NULL) {
200 next->_rs = _rs;
201 next->_vs = _vs;
202 next->_base = next->_top = this->_end;
203 next->_end = _rs->end();
204 }
205 }
206
207 static DumpRegion _mc_region("mc"), _ro_region("ro"), _rw_region("rw"), _symbol_region("symbols");
208 static size_t _total_closed_archive_region_size = 0, _total_open_archive_region_size = 0;
209
210 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space) {
211 first_space->init(&_shared_rs, &_shared_vs);
212 }
213
214 DumpRegion* MetaspaceShared::misc_code_dump_space() {
215 return &_mc_region;
216 }
217
218 DumpRegion* MetaspaceShared::read_write_dump_space() {
219 return &_rw_region;
220 }
221
222 DumpRegion* MetaspaceShared::read_only_dump_space() {
223 return &_ro_region;
224 }
225
226 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
227 ReservedSpace* rs) {
228 current->pack(next);
229 }
230
231 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
232 return _symbol_region.allocate(num_bytes);
233 }
234
235 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
236 return _mc_region.allocate(num_bytes);
237 }
238
239 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
240 return _ro_region.allocate(num_bytes);
241 }
242
243 size_t MetaspaceShared::reserved_space_alignment() { return os::vm_allocation_granularity(); }
244
245 static bool shared_base_valid(char* shared_base) {
246 #ifdef _LP64
247 return CompressedKlassPointers::is_valid_base((address)shared_base);
248 #else
249 return true;
250 #endif
251 }
252
253 static bool shared_base_too_high(char* shared_base, size_t cds_total) {
254 if (SharedBaseAddress != 0 && shared_base < (char*)SharedBaseAddress) {
255 // SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
256 // align_up(SharedBaseAddress, MetaspaceShared::reserved_space_alignment()) has wrapped around.
257 return true;
258 }
259 if (max_uintx - uintx(shared_base) < uintx(cds_total)) {
260 // The end of the archive will wrap around
261 return true;
262 }
263
264 return false;
265 }
266
267 static char* compute_shared_base(size_t cds_total) {
268 char* shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
269 const char* err = NULL;
270 if (shared_base_too_high(shared_base, cds_total)) {
271 err = "too high";
272 } else if (!shared_base_valid(shared_base)) {
273 err = "invalid for this platform";
274 }
275 if (err) {
276 log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
277 p2i((void*)SharedBaseAddress), err,
278 p2i((void*)Arguments::default_SharedBaseAddress()));
279 SharedBaseAddress = Arguments::default_SharedBaseAddress();
280 shared_base = (char*)align_up((char*)SharedBaseAddress, MetaspaceShared::reserved_space_alignment());
281 }
282 assert(!shared_base_too_high(shared_base, cds_total) && shared_base_valid(shared_base), "Sanity");
283 return shared_base;
284 }
285
286 void MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() {
287 assert(DumpSharedSpaces, "should be called for dump time only");
288
289 const size_t reserve_alignment = MetaspaceShared::reserved_space_alignment();
290
291 #ifdef _LP64
292 // On 64-bit VM we reserve a 4G range and, if UseCompressedClassPointers=1,
293 // will use that to house both the archives and the ccs. See below for
294 // details.
295 const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
296 const size_t cds_total = align_down(UnscaledClassSpaceMax, reserve_alignment);
297 #else
298 // We don't support archives larger than 256MB on 32-bit due to limited
299 // virtual address space.
300 size_t cds_total = align_down(256*M, reserve_alignment);
301 #endif
302
303 char* shared_base = compute_shared_base(cds_total);
304 _requested_base_address = shared_base;
305
306 // Whether to use SharedBaseAddress as attach address.
307 bool use_requested_base = true;
308
309 if (shared_base == NULL) {
310 use_requested_base = false;
311 }
312
313 if (ArchiveRelocationMode == 1) {
314 log_info(cds)("ArchiveRelocationMode == 1: always allocate class space at an alternative address");
315 use_requested_base = false;
316 }
317
318 // First try to reserve the space at the specified SharedBaseAddress.
319 assert(!_shared_rs.is_reserved(), "must be");
320 if (use_requested_base) {
321 _shared_rs = ReservedSpace(cds_total, reserve_alignment,
322 false /* large */, (char*)shared_base);
323 if (_shared_rs.is_reserved()) {
324 assert(_shared_rs.base() == shared_base, "should match");
325 } else {
326 log_info(cds)("dumptime space reservation: failed to map at "
327 "SharedBaseAddress " PTR_FORMAT, p2i(shared_base));
328 }
329 }
330 if (!_shared_rs.is_reserved()) {
331 // Get a reserved space anywhere if attaching at the SharedBaseAddress
332 // fails:
333 if (UseCompressedClassPointers) {
334 // If we need to reserve class space as well, let the platform handle
335 // the reservation.
336 LP64_ONLY(_shared_rs =
337 Metaspace::reserve_address_space_for_compressed_classes(cds_total);)
338 NOT_LP64(ShouldNotReachHere();)
339 } else {
340 // anywhere is fine.
341 _shared_rs = ReservedSpace(cds_total, reserve_alignment,
342 false /* large */, (char*)NULL);
343 }
344 }
345
346 if (!_shared_rs.is_reserved()) {
347 vm_exit_during_initialization("Unable to reserve memory for shared space",
348 err_msg(SIZE_FORMAT " bytes.", cds_total));
349 }
350
351 #ifdef _LP64
352
353 if (UseCompressedClassPointers) {
354
355 assert(CompressedKlassPointers::is_valid_base((address)_shared_rs.base()), "Sanity");
356
357 // On 64-bit VM, if UseCompressedClassPointers=1, the compressed class space
358 // must be allocated near the cds such as that the compressed Klass pointer
359 // encoding can be used to en/decode pointers from both cds and ccs. Since
360 // Metaspace cannot do this (it knows nothing about cds), we do it for
361 // Metaspace here and pass it the space to use for ccs.
362 //
363 // We do this by reserving space for the ccs behind the archives. Note
364 // however that ccs follows a different alignment
365 // (Metaspace::reserve_alignment), so there may be a gap between ccs and
366 // cds.
367 // We use a similar layout at runtime, see reserve_address_space_for_archives().
368 //
369 // +-- SharedBaseAddress (default = 0x800000000)
370 // v
371 // +-..---------+---------+ ... +----+----+----+--------+-----------------+
372 // | Heap | Archive | | MC | RW | RO | [gap] | class space |
373 // +-..---------+---------+ ... +----+----+----+--------+-----------------+
374 // |<-- MaxHeapSize -->| |<-- UnscaledClassSpaceMax = 4GB -->|
375 //
376 // Note: ccs must follow the archives, and the archives must start at the
377 // encoding base. However, the exact placement of ccs does not matter as
378 // long as it it resides in the encoding range of CompressedKlassPointers
379 // and comes after the archive.
380 //
381 // We do this by splitting up the allocated 4G into 3G of archive space,
382 // followed by 1G for the ccs:
383 // + The upper 1 GB is used as the "temporary compressed class space"
384 // -- preload_classes() will store Klasses into this space.
385 // + The lower 3 GB is used for the archive -- when preload_classes()
386 // is done, ArchiveCompactor will copy the class metadata into this
387 // space, first the RW parts, then the RO parts.
388
389 // Starting address of ccs must be aligned to Metaspace::reserve_alignment()...
390 size_t class_space_size = align_down(_shared_rs.size() / 4, Metaspace::reserve_alignment());
391 address class_space_start = (address)align_down(_shared_rs.end() - class_space_size, Metaspace::reserve_alignment());
392 size_t archive_size = class_space_start - (address)_shared_rs.base();
393
394 ReservedSpace tmp_class_space = _shared_rs.last_part(archive_size);
395 _shared_rs = _shared_rs.first_part(archive_size);
396
397 // ... as does the size of ccs.
398 tmp_class_space = tmp_class_space.first_part(class_space_size);
399 CompressedClassSpaceSize = class_space_size;
400
401 // Let Metaspace initialize ccs
402 Metaspace::initialize_class_space(tmp_class_space);
403
404 // and set up CompressedKlassPointers encoding.
405 CompressedKlassPointers::initialize((address)_shared_rs.base(), cds_total);
406
407 log_info(cds)("narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
408 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
409
410 log_info(cds)("Allocated temporary class space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
411 CompressedClassSpaceSize, p2i(tmp_class_space.base()));
412
413 assert(_shared_rs.end() == tmp_class_space.base() &&
414 is_aligned(_shared_rs.base(), MetaspaceShared::reserved_space_alignment()) &&
415 is_aligned(tmp_class_space.base(), Metaspace::reserve_alignment()) &&
416 is_aligned(tmp_class_space.size(), Metaspace::reserve_alignment()), "Sanity");
417 }
418
419 #endif
420
421 init_shared_dump_space(&_mc_region);
422 SharedBaseAddress = (size_t)_shared_rs.base();
423 log_info(cds)("Allocated shared space: " SIZE_FORMAT " bytes at " PTR_FORMAT,
424 _shared_rs.size(), p2i(_shared_rs.base()));
425
426 // We don't want any valid object to be at the very bottom of the archive.
427 // See ArchivePtrMarker::mark_pointer().
428 MetaspaceShared::misc_code_space_alloc(16);
429
430 size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
431 _symbol_rs = ReservedSpace(symbol_rs_size);
432 if (!_symbol_rs.is_reserved()) {
433 vm_exit_during_initialization("Unable to reserve memory for symbols",
434 err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
435 }
436 _symbol_region.init(&_symbol_rs, &_symbol_vs);
437 }
438
439 // Called by universe_post_init()
440 void MetaspaceShared::post_initialize(TRAPS) {
441 if (UseSharedSpaces) {
442 int size = FileMapInfo::get_number_of_shared_paths();
443 if (size > 0) {
444 SystemDictionaryShared::allocate_shared_data_arrays(size, THREAD);
445 if (!DynamicDumpSharedSpaces) {
446 FileMapInfo* info;
447 if (FileMapInfo::dynamic_info() == NULL) {
448 info = FileMapInfo::current_info();
449 } else {
450 info = FileMapInfo::dynamic_info();
451 }
452 ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
453 ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
454 }
455 }
456 }
457 }
458
459 static GrowableArrayCHeap<Handle, mtClassShared>* _extra_interned_strings = NULL;
460
461 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
462 _extra_interned_strings = new GrowableArrayCHeap<Handle, mtClassShared>(10000);
463
464 HashtableTextDump reader(filename);
465 reader.check_version("VERSION: 1.0");
466
467 while (reader.remain() > 0) {
468 int utf8_length;
469 int prefix_type = reader.scan_prefix(&utf8_length);
470 ResourceMark rm(THREAD);
471 if (utf8_length == 0x7fffffff) {
472 // buf_len will overflown 32-bit value.
473 vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
474 }
475 int buf_len = utf8_length+1;
476 char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
477 reader.get_utf8(utf8_buffer, utf8_length);
478 utf8_buffer[utf8_length] = '\0';
479
480 if (prefix_type == HashtableTextDump::SymbolPrefix) {
481 SymbolTable::new_permanent_symbol(utf8_buffer);
482 } else{
483 assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
484 oop s = StringTable::intern(utf8_buffer, THREAD);
485
486 if (HAS_PENDING_EXCEPTION) {
487 log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
488 reader.last_line_no(), utf8_length);
489 CLEAR_PENDING_EXCEPTION;
490 } else {
491 #if INCLUDE_G1GC
492 if (UseG1GC) {
493 typeArrayOop body = java_lang_String::value(s);
494 const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
495 if (hr->is_humongous()) {
496 // Don't keep it alive, so it will be GC'ed before we dump the strings, in order
497 // to maximize free heap space and minimize fragmentation.
498 log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
499 reader.last_line_no(), utf8_length);
500 continue;
501 }
502 }
503 #endif
504 // Interned strings are GC'ed if there are no references to it, so let's
505 // add a reference to keep this string alive.
506 assert(s != NULL, "must succeed");
507 Handle h(THREAD, s);
508 _extra_interned_strings->append(h);
509 }
510 }
511 }
512 }
513
514 void MetaspaceShared::commit_to(ReservedSpace* rs, VirtualSpace* vs, char* newtop) {
515 Arguments::assert_is_dumping_archive();
516 char* base = rs->base();
517 size_t need_committed_size = newtop - base;
518 size_t has_committed_size = vs->committed_size();
519 if (need_committed_size < has_committed_size) {
520 return;
521 }
522
523 size_t min_bytes = need_committed_size - has_committed_size;
524 size_t preferred_bytes = 1 * M;
525 size_t uncommitted = vs->reserved_size() - has_committed_size;
526
527 size_t commit =MAX2(min_bytes, preferred_bytes);
528 commit = MIN2(commit, uncommitted);
529 assert(commit <= uncommitted, "sanity");
530
531 bool result = vs->expand_by(commit, false);
532 if (rs == &_shared_rs) {
533 ArchivePtrMarker::expand_ptr_end((address*)vs->high());
534 }
535
536 if (!result) {
537 vm_exit_during_initialization(err_msg("Failed to expand shared space to " SIZE_FORMAT " bytes",
538 need_committed_size));
539 }
540
541 assert(rs == &_shared_rs || rs == &_symbol_rs, "must be");
542 const char* which = (rs == &_shared_rs) ? "shared" : "symbol";
543 log_debug(cds)("Expanding %s spaces by " SIZE_FORMAT_W(7) " bytes [total " SIZE_FORMAT_W(9) " bytes ending at %p]",
544 which, commit, vs->actual_committed_size(), vs->high());
545 }
546
547 void MetaspaceShared::initialize_ptr_marker(CHeapBitMap* ptrmap) {
548 ArchivePtrMarker::initialize(ptrmap, (address*)_shared_vs.low(), (address*)_shared_vs.high());
549 }
550
551 // Read/write a data stream for restoring/preserving metadata pointers and
552 // miscellaneous data from/to the shared archive file.
553
554 void MetaspaceShared::serialize(SerializeClosure* soc) {
555 int tag = 0;
556 soc->do_tag(--tag);
557
558 // Verify the sizes of various metadata in the system.
559 soc->do_tag(sizeof(Method));
560 soc->do_tag(sizeof(ConstMethod));
561 soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
562 soc->do_tag(sizeof(ConstantPool));
563 soc->do_tag(sizeof(ConstantPoolCache));
564 soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
565 soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
566 soc->do_tag(sizeof(Symbol));
567
568 // Dump/restore miscellaneous metadata.
569 JavaClasses::serialize_offsets(soc);
570 Universe::serialize(soc);
571 soc->do_tag(--tag);
572
573 // Dump/restore references to commonly used names and signatures.
574 vmSymbols::serialize(soc);
575 soc->do_tag(--tag);
576
577 // Dump/restore the symbol/string/subgraph_info tables
578 SymbolTable::serialize_shared_table_header(soc);
579 StringTable::serialize_shared_table_header(soc);
580 HeapShared::serialize_subgraph_info_table_header(soc);
581 SystemDictionaryShared::serialize_dictionary_headers(soc);
582
583 InstanceMirrorKlass::serialize_offsets(soc);
584
585 // Dump/restore well known classes (pointers)
586 SystemDictionaryShared::serialize_well_known_klasses(soc);
587 soc->do_tag(--tag);
588
589 serialize_cloned_cpp_vtptrs(soc);
590 soc->do_tag(--tag);
591
592 soc->do_tag(666);
593 }
594
595 address MetaspaceShared::i2i_entry_code_buffers(size_t total_size) {
596 if (DumpSharedSpaces) {
597 if (_i2i_entry_code_buffers == NULL) {
598 _i2i_entry_code_buffers = (address)misc_code_space_alloc(total_size);
599 _i2i_entry_code_buffers_size = total_size;
600 }
601 } else if (UseSharedSpaces) {
602 assert(_i2i_entry_code_buffers != NULL, "must already been initialized");
603 } else {
604 return NULL;
605 }
606
607 assert(_i2i_entry_code_buffers_size == total_size, "must not change");
608 return _i2i_entry_code_buffers;
609 }
610
611 uintx MetaspaceShared::object_delta_uintx(void* obj) {
612 Arguments::assert_is_dumping_archive();
613 if (DumpSharedSpaces) {
614 assert(shared_rs()->contains(obj), "must be");
615 } else {
616 assert(is_in_shared_metaspace(obj) || DynamicArchive::is_in_target_space(obj), "must be");
617 }
618 address base_address = address(SharedBaseAddress);
619 uintx deltax = address(obj) - base_address;
620 return deltax;
621 }
622
623 // Global object for holding classes that have been loaded. Since this
624 // is run at a safepoint just before exit, this is the entire set of classes.
625 static GrowableArray<Klass*>* _global_klass_objects;
626
627 static int global_klass_compare(Klass** a, Klass **b) {
628 return a[0]->name()->fast_compare(b[0]->name());
629 }
630
631 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() {
632 return _global_klass_objects;
633 }
634
635 static void collect_array_classes(Klass* k) {
636 _global_klass_objects->append_if_missing(k);
637 if (k->is_array_klass()) {
638 // Add in the array classes too
639 ArrayKlass* ak = ArrayKlass::cast(k);
640 Klass* h = ak->higher_dimension();
641 if (h != NULL) {
642 h->array_klasses_do(collect_array_classes);
643 }
644 }
645 }
646
647 class CollectClassesClosure : public KlassClosure {
648 void do_klass(Klass* k) {
649 if (k->is_instance_klass() &&
650 SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(k))) {
651 // Don't add to the _global_klass_objects
652 } else {
653 _global_klass_objects->append_if_missing(k);
654 }
655 if (k->is_array_klass()) {
656 // Add in the array classes too
657 ArrayKlass* ak = ArrayKlass::cast(k);
658 Klass* h = ak->higher_dimension();
659 if (h != NULL) {
660 h->array_klasses_do(collect_array_classes);
661 }
662 }
663 }
664 };
665
666 // Global object for holding symbols that created during class loading. See SymbolTable::new_symbol
667 static GrowableArray<Symbol*>* _global_symbol_objects = NULL;
668
669 static int compare_symbols_by_address(Symbol** a, Symbol** b) {
670 if (a[0] < b[0]) {
671 return -1;
672 } else if (a[0] == b[0]) {
673 ResourceMark rm;
674 log_warning(cds)("Duplicated symbol %s unexpected", (*a)->as_C_string());
675 return 0;
676 } else {
677 return 1;
678 }
679 }
680
681 void MetaspaceShared::add_symbol(Symbol* sym) {
682 MutexLocker ml(CDSAddSymbol_lock, Mutex::_no_safepoint_check_flag);
683 if (_global_symbol_objects == NULL) {
684 _global_symbol_objects = new (ResourceObj::C_HEAP, mtSymbol) GrowableArray<Symbol*>(2048, mtSymbol);
685 }
686 _global_symbol_objects->append(sym);
687 }
688
689 GrowableArray<Symbol*>* MetaspaceShared::collected_symbols() {
690 return _global_symbol_objects;
691 }
692
693 static void remove_unshareable_in_classes() {
694 for (int i = 0; i < _global_klass_objects->length(); i++) {
695 Klass* k = _global_klass_objects->at(i);
696 if (!k->is_objArray_klass()) {
697 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
698 // on their array classes.
699 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
700 k->remove_unshareable_info();
701 }
702 }
703 }
704
705 static void remove_java_mirror_in_classes() {
706 for (int i = 0; i < _global_klass_objects->length(); i++) {
707 Klass* k = _global_klass_objects->at(i);
708 if (!k->is_objArray_klass()) {
709 // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
710 // on their array classes.
711 assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
712 k->remove_java_mirror();
713 }
714 }
715 }
716
717 static void clear_basic_type_mirrors() {
718 assert(!HeapShared::is_heap_object_archiving_allowed(), "Sanity");
719 Universe::set_int_mirror(NULL);
720 Universe::set_float_mirror(NULL);
721 Universe::set_double_mirror(NULL);
722 Universe::set_byte_mirror(NULL);
723 Universe::set_bool_mirror(NULL);
724 Universe::set_char_mirror(NULL);
725 Universe::set_long_mirror(NULL);
726 Universe::set_short_mirror(NULL);
727 Universe::set_void_mirror(NULL);
728 }
729
730 static void rewrite_nofast_bytecode(const methodHandle& method) {
731 BytecodeStream bcs(method);
732 while (!bcs.is_last_bytecode()) {
733 Bytecodes::Code opcode = bcs.next();
734 switch (opcode) {
735 case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
736 case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
737 case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
738 case Bytecodes::_iload: {
739 if (!bcs.is_wide()) {
740 *bcs.bcp() = Bytecodes::_nofast_iload;
741 }
742 break;
743 }
744 default: break;
745 }
746 }
747 }
748
749 // Walk all methods in the class list to ensure that they won't be modified at
750 // run time. This includes:
751 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
752 // at run time by RewriteBytecodes/RewriteFrequentPairs
753 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
754 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
755 for (int i = 0; i < _global_klass_objects->length(); i++) {
756 Klass* k = _global_klass_objects->at(i);
757 if (k->is_instance_klass()) {
758 InstanceKlass* ik = InstanceKlass::cast(k);
759 MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
760 }
761 }
762 }
763
764 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
765 for (int i = 0; i < ik->methods()->length(); i++) {
766 methodHandle m(thread, ik->methods()->at(i));
767 rewrite_nofast_bytecode(m);
768 Fingerprinter fp(m);
769 // The side effect of this call sets method's fingerprint field.
770 fp.fingerprint();
771 }
772 }
773
774 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
775 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
776 //
777 // Addresses of the vtables and the methods may be different across JVM runs,
778 // if libjvm.so is dynamically loaded at a different base address.
779 //
780 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
781 //
782 // + at dump time: we redirect the _vptr to point to our own vtables inside
783 // the CDS image
784 // + at run time: we clone the actual contents of the vtables from libjvm.so
785 // into our own tables.
786
787 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
788 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
789 f(ConstantPool) \
790 f(InstanceKlass) \
791 f(InstanceClassLoaderKlass) \
792 f(InstanceMirrorKlass) \
793 f(InstanceRefKlass) \
794 f(Method) \
795 f(ObjArrayKlass) \
796 f(TypeArrayKlass)
797
798 class CppVtableInfo {
799 intptr_t _vtable_size;
800 intptr_t _cloned_vtable[1];
801 public:
802 static int num_slots(int vtable_size) {
803 return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
804 }
805 int vtable_size() { return int(uintx(_vtable_size)); }
806 void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
807 intptr_t* cloned_vtable() { return &_cloned_vtable[0]; }
808 void zero() { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
809 // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
810 static size_t byte_size(int vtable_size) {
811 CppVtableInfo i;
812 return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
813 }
814 };
815
816 static inline intptr_t* vtable_of(Metadata* m) {
817 return *((intptr_t**)m);
818 }
819
820 template <class T> class CppVtableCloner : public T {
821 static CppVtableInfo* _info;
822
823 static int get_vtable_length(const char* name);
824
825 public:
826 // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
827 static intptr_t* allocate(const char* name);
828
829 // Clone the vtable to ...
830 static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
831
832 static void zero_vtable_clone() {
833 assert(DumpSharedSpaces, "dump-time only");
834 _info->zero();
835 }
836
837 static bool is_valid_shared_object(const T* obj) {
838 intptr_t* vptr = *(intptr_t**)obj;
839 return vptr == _info->cloned_vtable();
840 }
841
842 static void init_orig_cpp_vtptr(int kind);
843 };
844
845 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
846
847 template <class T>
848 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
849 assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
850 int n = get_vtable_length(name);
851 _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
852 _info->set_vtable_size(n);
853
854 intptr_t* p = clone_vtable(name, _info);
855 assert((char*)p == _mc_region.top(), "must be");
856
857 return _info->cloned_vtable();
858 }
859
860 template <class T>
861 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
862 if (!DumpSharedSpaces) {
863 assert(_info == 0, "_info is initialized only at dump time");
864 _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
865 }
866 T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
867 int n = info->vtable_size();
868 intptr_t* srcvtable = vtable_of(&tmp);
869 intptr_t* dstvtable = info->cloned_vtable();
870
871 // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
872 // safe to do memcpy.
873 log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
874 memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
875 return dstvtable + n;
876 }
877
878 // To determine the size of the vtable for each type, we use the following
879 // trick by declaring 2 subclasses:
880 //
881 // class CppVtableTesterA: public InstanceKlass {virtual int last_virtual_method() {return 1;} };
882 // class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
883 //
884 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
885 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
886 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
887 // - Their last entry is different.
888 //
889 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
890 // and find the first entry that's different.
891 //
892 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
893 // esoteric compilers.
894
895 template <class T> class CppVtableTesterB: public T {
896 public:
897 virtual int last_virtual_method() {return 1;}
898 };
899
900 template <class T> class CppVtableTesterA : public T {
901 public:
902 virtual void* last_virtual_method() {
903 // Make this different than CppVtableTesterB::last_virtual_method so the C++
904 // compiler/linker won't alias the two functions.
905 return NULL;
906 }
907 };
908
909 template <class T>
910 int CppVtableCloner<T>::get_vtable_length(const char* name) {
911 CppVtableTesterA<T> a;
912 CppVtableTesterB<T> b;
913
914 intptr_t* avtable = vtable_of(&a);
915 intptr_t* bvtable = vtable_of(&b);
916
917 // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
918 int vtable_len = 1;
919 for (; ; vtable_len++) {
920 if (avtable[vtable_len] != bvtable[vtable_len]) {
921 break;
922 }
923 }
924 log_debug(cds, vtables)("Found %3d vtable entries for %s", vtable_len, name);
925
926 return vtable_len;
927 }
928
929 #define ALLOC_CPP_VTABLE_CLONE(c) \
930 _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
931 ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
932
933 #define CLONE_CPP_VTABLE(c) \
934 p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
935
936 #define ZERO_CPP_VTABLE(c) \
937 CppVtableCloner<c>::zero_vtable_clone();
938
939 #define INIT_ORIG_CPP_VTPTRS(c) \
940 CppVtableCloner<c>::init_orig_cpp_vtptr(c##_Kind);
941
942 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
943
944 enum ClonedVtableKind {
945 // E.g., ConstantPool_Kind == 0, InstanceKlass_Kind == 1, etc.
946 CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
947 _num_cloned_vtable_kinds
948 };
949
950 // This is a map of all the original vtptrs. E.g., for
951 // ConstantPool *cp = new (...) ConstantPool(...) ; // a dynamically allocated constant pool
952 // the following holds true:
953 // _orig_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0]
954 static intptr_t* _orig_cpp_vtptrs[_num_cloned_vtable_kinds];
955 static bool _orig_cpp_vtptrs_inited = false;
956
957 template <class T>
958 void CppVtableCloner<T>::init_orig_cpp_vtptr(int kind) {
959 assert(kind < _num_cloned_vtable_kinds, "sanity");
960 T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
961 intptr_t* srcvtable = vtable_of(&tmp);
962 _orig_cpp_vtptrs[kind] = srcvtable;
963 }
964
965 // This is the index of all the cloned vtables. E.g., for
966 // ConstantPool* cp = ....; // an archived constant pool
967 // InstanceKlass* ik = ....;// an archived class
968 // the following holds true:
969 // _cloned_cpp_vtptrs[ConstantPool_Kind] == ((intptr_t**)cp)[0]
970 // _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
971 static intptr_t** _cloned_cpp_vtptrs = NULL;
972
973 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
974 assert(DumpSharedSpaces, "must");
975 size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
976 _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
977 }
978
979 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
980 soc->do_ptr((void**)&_cloned_cpp_vtptrs);
981 }
982
983 intptr_t* MetaspaceShared::get_archived_cpp_vtable(MetaspaceObj::Type msotype, address obj) {
984 if (!_orig_cpp_vtptrs_inited) {
985 CPP_VTABLE_PATCH_TYPES_DO(INIT_ORIG_CPP_VTPTRS);
986 _orig_cpp_vtptrs_inited = true;
987 }
988
989 Arguments::assert_is_dumping_archive();
990 int kind = -1;
991 switch (msotype) {
992 case MetaspaceObj::SymbolType:
993 case MetaspaceObj::TypeArrayU1Type:
994 case MetaspaceObj::TypeArrayU2Type:
995 case MetaspaceObj::TypeArrayU4Type:
996 case MetaspaceObj::TypeArrayU8Type:
997 case MetaspaceObj::TypeArrayOtherType:
998 case MetaspaceObj::ConstMethodType:
999 case MetaspaceObj::ConstantPoolCacheType:
1000 case MetaspaceObj::AnnotationsType:
1001 case MetaspaceObj::MethodCountersType:
1002 case MetaspaceObj::RecordComponentType:
1003 // These have no vtables.
1004 break;
1005 case MetaspaceObj::MethodDataType:
1006 // We don't archive MethodData <-- should have been removed in removed_unsharable_info
1007 ShouldNotReachHere();
1008 break;
1009 default:
1010 for (kind = 0; kind < _num_cloned_vtable_kinds; kind ++) {
1011 if (vtable_of((Metadata*)obj) == _orig_cpp_vtptrs[kind]) {
1012 break;
1013 }
1014 }
1015 if (kind >= _num_cloned_vtable_kinds) {
1016 fatal("Cannot find C++ vtable for " INTPTR_FORMAT " -- you probably added"
1017 " a new subtype of Klass or MetaData without updating CPP_VTABLE_PATCH_TYPES_DO",
1018 p2i(obj));
1019 }
1020 }
1021
1022 if (kind >= 0) {
1023 assert(kind < _num_cloned_vtable_kinds, "must be");
1024 return _cloned_cpp_vtptrs[kind];
1025 } else {
1026 return NULL;
1027 }
1028 }
1029
1030 // This can be called at both dump time and run time:
1031 // - clone the contents of the c++ vtables into the space
1032 // allocated by allocate_cpp_vtable_clones()
1033 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
1034 assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
1035 CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
1036 }
1037
1038 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
1039 assert(DumpSharedSpaces, "dump-time only");
1040 CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
1041 }
1042
1043 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
1044 char* MetaspaceShared::allocate_cpp_vtable_clones() {
1045 char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
1046
1047 assert(DumpSharedSpaces, "dump-time only");
1048 // Layout (each slot is a intptr_t):
1049 // [number of slots in the first vtable = n1]
1050 // [ <n1> slots for the first vtable]
1051 // [number of slots in the first second = n2]
1052 // [ <n2> slots for the second vtable]
1053 // ...
1054 // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
1055 CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
1056
1057 return cloned_vtables;
1058 }
1059
1060 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
1061 assert(is_in_shared_metaspace(m), "must be");
1062 return CppVtableCloner<Method>::is_valid_shared_object(m);
1063 }
1064
1065 void WriteClosure::do_oop(oop* o) {
1066 if (*o == NULL) {
1067 _dump_region->append_intptr_t(0);
1068 } else {
1069 assert(HeapShared::is_heap_object_archiving_allowed(),
1070 "Archiving heap object is not allowed");
1071 _dump_region->append_intptr_t(
1072 (intptr_t)CompressedOops::encode_not_null(*o));
1073 }
1074 }
1075
1076 void WriteClosure::do_region(u_char* start, size_t size) {
1077 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1078 assert(size % sizeof(intptr_t) == 0, "bad size");
1079 do_tag((int)size);
1080 while (size > 0) {
1081 _dump_region->append_intptr_t(*(intptr_t*)start, true);
1082 start += sizeof(intptr_t);
1083 size -= sizeof(intptr_t);
1084 }
1085 }
1086
1087 // This is for dumping detailed statistics for the allocations
1088 // in the shared spaces.
1089 class DumpAllocStats : public ResourceObj {
1090 public:
1091
1092 // Here's poor man's enum inheritance
1093 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
1094 METASPACE_OBJ_TYPES_DO(f) \
1095 f(SymbolHashentry) \
1096 f(SymbolBucket) \
1097 f(StringHashentry) \
1098 f(StringBucket) \
1099 f(Other)
1100
1101 enum Type {
1102 // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
1103 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
1104 _number_of_types
1105 };
1106
1107 static const char * type_name(Type type) {
1108 switch(type) {
1109 SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
1110 default:
1111 ShouldNotReachHere();
1112 return NULL;
1113 }
1114 }
1115
1116 public:
1117 enum { RO = 0, RW = 1 };
1118
1119 int _counts[2][_number_of_types];
1120 int _bytes [2][_number_of_types];
1121
1122 DumpAllocStats() {
1123 memset(_counts, 0, sizeof(_counts));
1124 memset(_bytes, 0, sizeof(_bytes));
1125 };
1126
1127 void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
1128 assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
1129 int which = (read_only) ? RO : RW;
1130 _counts[which][type] ++;
1131 _bytes [which][type] += byte_size;
1132 }
1133
1134 void record_other_type(int byte_size, bool read_only) {
1135 int which = (read_only) ? RO : RW;
1136 _bytes [which][OtherType] += byte_size;
1137 }
1138 void print_stats(int ro_all, int rw_all, int mc_all);
1139 };
1140
1141 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) {
1142 // Calculate size of data that was not allocated by Metaspace::allocate()
1143 MetaspaceSharedStats *stats = MetaspaceShared::stats();
1144
1145 // symbols
1146 _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
1147 _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
1148
1149 _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
1150 _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
1151
1152 // strings
1153 _counts[RO][StringHashentryType] = stats->string.hashentry_count;
1154 _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
1155
1156 _counts[RO][StringBucketType] = stats->string.bucket_count;
1157 _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
1158
1159 // TODO: count things like dictionary, vtable, etc
1160 _bytes[RW][OtherType] += mc_all;
1161 rw_all += mc_all; // mc is mapped Read/Write
1162
1163 // prevent divide-by-zero
1164 if (ro_all < 1) {
1165 ro_all = 1;
1166 }
1167 if (rw_all < 1) {
1168 rw_all = 1;
1169 }
1170
1171 int all_ro_count = 0;
1172 int all_ro_bytes = 0;
1173 int all_rw_count = 0;
1174 int all_rw_bytes = 0;
1175
1176 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1177 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1178 const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1179 const char *hdr = " ro_cnt ro_bytes % | rw_cnt rw_bytes % | all_cnt all_bytes %";
1180
1181 LogMessage(cds) msg;
1182
1183 msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):");
1184 msg.debug("%s", hdr);
1185 msg.debug("%s", sep);
1186 for (int type = 0; type < int(_number_of_types); type ++) {
1187 const char *name = type_name((Type)type);
1188 int ro_count = _counts[RO][type];
1189 int ro_bytes = _bytes [RO][type];
1190 int rw_count = _counts[RW][type];
1191 int rw_bytes = _bytes [RW][type];
1192 int count = ro_count + rw_count;
1193 int bytes = ro_bytes + rw_bytes;
1194
1195 double ro_perc = percent_of(ro_bytes, ro_all);
1196 double rw_perc = percent_of(rw_bytes, rw_all);
1197 double perc = percent_of(bytes, ro_all + rw_all);
1198
1199 msg.debug(fmt_stats, name,
1200 ro_count, ro_bytes, ro_perc,
1201 rw_count, rw_bytes, rw_perc,
1202 count, bytes, perc);
1203
1204 all_ro_count += ro_count;
1205 all_ro_bytes += ro_bytes;
1206 all_rw_count += rw_count;
1207 all_rw_bytes += rw_bytes;
1208 }
1209
1210 int all_count = all_ro_count + all_rw_count;
1211 int all_bytes = all_ro_bytes + all_rw_bytes;
1212
1213 double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1214 double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1215 double all_perc = percent_of(all_bytes, ro_all + rw_all);
1216
1217 msg.debug("%s", sep);
1218 msg.debug(fmt_stats, "Total",
1219 all_ro_count, all_ro_bytes, all_ro_perc,
1220 all_rw_count, all_rw_bytes, all_rw_perc,
1221 all_count, all_bytes, all_perc);
1222
1223 assert(all_ro_bytes == ro_all, "everything should have been counted");
1224 assert(all_rw_bytes == rw_all, "everything should have been counted");
1225
1226 #undef fmt_stats
1227 }
1228
1229 // Populate the shared space.
1230
1231 class VM_PopulateDumpSharedSpace: public VM_Operation {
1232 private:
1233 GrowableArray<MemRegion> *_closed_archive_heap_regions;
1234 GrowableArray<MemRegion> *_open_archive_heap_regions;
1235
1236 GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1237 GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1238
1239 void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1240 void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1241 void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1242 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1243 void dump_symbols();
1244 char* dump_read_only_tables();
1245 void print_class_stats();
1246 void print_region_stats(FileMapInfo* map_info);
1247 void print_bitmap_region_stats(size_t size, size_t total_size);
1248 void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1249 const char *name, size_t total_size);
1250 void relocate_to_requested_base_address(CHeapBitMap* ptrmap);
1251
1252 public:
1253
1254 VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1255 void doit(); // outline because gdb sucks
1256 bool allow_nested_vm_operations() const { return true; }
1257 }; // class VM_PopulateDumpSharedSpace
1258
1259 // ArchiveCompactor --
1260 //
1261 // This class is the central piece of shared archive compaction -- all metaspace data are
1262 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1263 // metaspace data into their final location in the shared regions.
1264
1265 class ArchiveCompactor : AllStatic {
1266 static const int INITIAL_TABLE_SIZE = 8087;
1267 static const int MAX_TABLE_SIZE = 1000000;
1268
1269 static DumpAllocStats* _alloc_stats;
1270
1271 typedef KVHashtable<address, address, mtInternal> RelocationTable;
1272 static RelocationTable* _new_loc_table;
1273
1274 public:
1275 static void initialize() {
1276 _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1277 _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE);
1278 }
1279 static DumpAllocStats* alloc_stats() {
1280 return _alloc_stats;
1281 }
1282
1283 // Use this when you allocate space with MetaspaceShare::read_only_space_alloc()
1284 // outside of ArchiveCompactor::allocate(). These are usually for misc tables
1285 // that are allocated in the RO space.
1286 class OtherROAllocMark {
1287 char* _oldtop;
1288 public:
1289 OtherROAllocMark() {
1290 _oldtop = _ro_region.top();
1291 }
1292 ~OtherROAllocMark() {
1293 char* newtop = _ro_region.top();
1294 ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
1295 }
1296 };
1297
1298 static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1299 address obj = ref->obj();
1300 int bytes = ref->size() * BytesPerWord;
1301 char* p;
1302 size_t alignment = BytesPerWord;
1303 char* oldtop;
1304 char* newtop;
1305
1306 if (read_only) {
1307 oldtop = _ro_region.top();
1308 p = _ro_region.allocate(bytes, alignment);
1309 newtop = _ro_region.top();
1310 } else {
1311 oldtop = _rw_region.top();
1312 if (ref->msotype() == MetaspaceObj::ClassType) {
1313 // Save a pointer immediate in front of an InstanceKlass, so
1314 // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
1315 // without building another hashtable. See RunTimeSharedClassInfo::get_for()
1316 // in systemDictionaryShared.cpp.
1317 Klass* klass = (Klass*)obj;
1318 if (klass->is_instance_klass()) {
1319 SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
1320 _rw_region.allocate(sizeof(address), BytesPerWord);
1321 }
1322 }
1323 p = _rw_region.allocate(bytes, alignment);
1324 newtop = _rw_region.top();
1325 }
1326 memcpy(p, obj, bytes);
1327
1328 intptr_t* archived_vtable = MetaspaceShared::get_archived_cpp_vtable(ref->msotype(), (address)p);
1329 if (archived_vtable != NULL) {
1330 *(address*)p = (address)archived_vtable;
1331 ArchivePtrMarker::mark_pointer((address*)p);
1332 }
1333
1334 assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once");
1335 _new_loc_table->add(obj, (address)p);
1336 log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1337 if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) {
1338 log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size());
1339 }
1340 _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1341 }
1342
1343 static address get_new_loc(MetaspaceClosure::Ref* ref) {
1344 address* pp = _new_loc_table->lookup(ref->obj());
1345 assert(pp != NULL, "must be");
1346 return *pp;
1347 }
1348
1349 private:
1350 // Makes a shallow copy of visited MetaspaceObj's
1351 class ShallowCopier: public UniqueMetaspaceClosure {
1352 bool _read_only;
1353 public:
1354 ShallowCopier(bool read_only) : _read_only(read_only) {}
1355
1356 virtual bool do_unique_ref(Ref* ref, bool read_only) {
1357 if (read_only == _read_only) {
1358 allocate(ref, read_only);
1359 }
1360 return true; // recurse into ref.obj()
1361 }
1362 };
1363
1364 // Relocate embedded pointers within a MetaspaceObj's shallow copy
1365 class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1366 public:
1367 virtual bool do_unique_ref(Ref* ref, bool read_only) {
1368 address new_loc = get_new_loc(ref);
1369 RefRelocator refer;
1370 ref->metaspace_pointers_do_at(&refer, new_loc);
1371 return true; // recurse into ref.obj()
1372 }
1373 virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
1374 assert(type == _method_entry_ref, "only special type allowed for now");
1375 address obj = ref->obj();
1376 address new_obj = get_new_loc(ref);
1377 size_t offset = pointer_delta(p, obj, sizeof(u1));
1378 intptr_t* new_p = (intptr_t*)(new_obj + offset);
1379 assert(*p == *new_p, "must be a copy");
1380 ArchivePtrMarker::mark_pointer((address*)new_p);
1381 }
1382 };
1383
1384 // Relocate a reference to point to its shallow copy
1385 class RefRelocator: public MetaspaceClosure {
1386 public:
1387 virtual bool do_ref(Ref* ref, bool read_only) {
1388 if (ref->not_null()) {
1389 ref->update(get_new_loc(ref));
1390 ArchivePtrMarker::mark_pointer(ref->addr());
1391 }
1392 return false; // Do not recurse.
1393 }
1394 };
1395
1396 #ifdef ASSERT
1397 class IsRefInArchiveChecker: public MetaspaceClosure {
1398 public:
1399 virtual bool do_ref(Ref* ref, bool read_only) {
1400 if (ref->not_null()) {
1401 char* obj = (char*)ref->obj();
1402 assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1403 "must be relocated to point to CDS archive");
1404 }
1405 return false; // Do not recurse.
1406 }
1407 };
1408 #endif
1409
1410 public:
1411 static void copy_and_compact() {
1412 ResourceMark rm;
1413
1414 log_info(cds)("Scanning all metaspace objects ... ");
1415 {
1416 // allocate and shallow-copy RW objects, immediately following the MC region
1417 log_info(cds)("Allocating RW objects ... ");
1418 _mc_region.pack(&_rw_region);
1419
1420 ResourceMark rm;
1421 ShallowCopier rw_copier(false);
1422 iterate_roots(&rw_copier);
1423 }
1424 {
1425 // allocate and shallow-copy of RO object, immediately following the RW region
1426 log_info(cds)("Allocating RO objects ... ");
1427 _rw_region.pack(&_ro_region);
1428
1429 ResourceMark rm;
1430 ShallowCopier ro_copier(true);
1431 iterate_roots(&ro_copier);
1432 }
1433 {
1434 log_info(cds)("Relocating embedded pointers ... ");
1435 ResourceMark rm;
1436 ShallowCopyEmbeddedRefRelocator emb_reloc;
1437 iterate_roots(&emb_reloc);
1438 }
1439 {
1440 log_info(cds)("Relocating external roots ... ");
1441 ResourceMark rm;
1442 RefRelocator ext_reloc;
1443 iterate_roots(&ext_reloc);
1444 }
1445 {
1446 log_info(cds)("Fixing symbol identity hash ... ");
1447 os::init_random(0x12345678);
1448 GrowableArray<Symbol*>* all_symbols = MetaspaceShared::collected_symbols();
1449 all_symbols->sort(compare_symbols_by_address);
1450 for (int i = 0; i < all_symbols->length(); i++) {
1451 assert(all_symbols->at(i)->is_permanent(), "archived symbols must be permanent");
1452 all_symbols->at(i)->update_identity_hash();
1453 }
1454 }
1455 #ifdef ASSERT
1456 {
1457 log_info(cds)("Verifying external roots ... ");
1458 ResourceMark rm;
1459 IsRefInArchiveChecker checker;
1460 iterate_roots(&checker);
1461 }
1462 #endif
1463 }
1464
1465 // We must relocate the System::_well_known_klasses only after we have copied the
1466 // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1467 // old objects which assert that their klass is the original klass.
1468 static void relocate_well_known_klasses() {
1469 {
1470 log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... ");
1471 ResourceMark rm;
1472 RefRelocator ext_reloc;
1473 SystemDictionary::well_known_klasses_do(&ext_reloc);
1474 }
1475 // NOTE: after this point, we shouldn't have any globals that can reach the old
1476 // objects.
1477
1478 // We cannot use any of the objects in the heap anymore (except for the
1479 // shared strings) because their headers no longer point to valid Klasses.
1480 }
1481
1482 static void iterate_roots(MetaspaceClosure* it) {
1483 // To ensure deterministic contents in the archive, we just need to ensure that
1484 // we iterate the MetsapceObjs in a deterministic order. It doesn't matter where
1485 // the MetsapceObjs are located originally, as they are copied sequentially into
1486 // the archive during the iteration.
1487 //
1488 // The only issue here is that the symbol table and the system directories may be
1489 // randomly ordered, so we copy the symbols and klasses into two arrays and sort
1490 // them deterministically.
1491 //
1492 // During -Xshare:dump, the order of Symbol creation is strictly determined by
1493 // the SharedClassListFile (class loading is done in a single thread and the JIT
1494 // is disabled). Also, Symbols are allocated in monotonically increasing addresses
1495 // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
1496 // ascending address order, we ensure that all Symbols are copied into deterministic
1497 // locations in the archive.
1498 GrowableArray<Symbol*>* symbols = _global_symbol_objects;
1499 for (int i = 0; i < symbols->length(); i++) {
1500 it->push(symbols->adr_at(i));
1501 }
1502 if (_global_klass_objects != NULL) {
1503 // Need to fix up the pointers
1504 for (int i = 0; i < _global_klass_objects->length(); i++) {
1505 // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1506 it->push(_global_klass_objects->adr_at(i));
1507 }
1508 }
1509 FileMapInfo::metaspace_pointers_do(it, false);
1510 SystemDictionaryShared::dumptime_classes_do(it);
1511 Universe::metaspace_pointers_do(it);
1512 SymbolTable::metaspace_pointers_do(it);
1513 vmSymbols::metaspace_pointers_do(it);
1514
1515 it->finish();
1516 }
1517
1518 static Klass* get_relocated_klass(Klass* orig_klass) {
1519 assert(DumpSharedSpaces, "dump time only");
1520 address* pp = _new_loc_table->lookup((address)orig_klass);
1521 assert(pp != NULL, "must be");
1522 Klass* klass = (Klass*)(*pp);
1523 assert(klass->is_klass(), "must be");
1524 return klass;
1525 }
1526 };
1527
1528 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1529 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1530
1531 void VM_PopulateDumpSharedSpace::dump_symbols() {
1532 log_info(cds)("Dumping symbol table ...");
1533
1534 NOT_PRODUCT(SymbolTable::verify());
1535 SymbolTable::write_to_archive();
1536 }
1537
1538 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1539 ArchiveCompactor::OtherROAllocMark mark;
1540
1541 log_info(cds)("Removing java_mirror ... ");
1542 if (!HeapShared::is_heap_object_archiving_allowed()) {
1543 clear_basic_type_mirrors();
1544 }
1545 remove_java_mirror_in_classes();
1546 log_info(cds)("done. ");
1547
1548 SystemDictionaryShared::write_to_archive();
1549
1550 // Write the other data to the output array.
1551 char* start = _ro_region.top();
1552 WriteClosure wc(&_ro_region);
1553 MetaspaceShared::serialize(&wc);
1554
1555 // Write the bitmaps for patching the archive heap regions
1556 _closed_archive_heap_oopmaps = NULL;
1557 _open_archive_heap_oopmaps = NULL;
1558 dump_archive_heap_oopmaps();
1559
1560 return start;
1561 }
1562
1563 void VM_PopulateDumpSharedSpace::print_class_stats() {
1564 log_info(cds)("Number of classes %d", _global_klass_objects->length());
1565 {
1566 int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1567 for (int i = 0; i < _global_klass_objects->length(); i++) {
1568 Klass* k = _global_klass_objects->at(i);
1569 if (k->is_instance_klass()) {
1570 num_inst ++;
1571 } else if (k->is_objArray_klass()) {
1572 num_obj_array ++;
1573 } else {
1574 assert(k->is_typeArray_klass(), "sanity");
1575 num_type_array ++;
1576 }
1577 }
1578 log_info(cds)(" instance classes = %5d", num_inst);
1579 log_info(cds)(" obj array classes = %5d", num_obj_array);
1580 log_info(cds)(" type array classes = %5d", num_type_array);
1581 }
1582 }
1583
1584 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) {
1585 intx addr_delta = MetaspaceShared::final_delta();
1586 if (addr_delta == 0) {
1587 ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
1588 } else {
1589 // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR).
1590 // This means that the current content of the archive is based on a random
1591 // address. Let's relocate all the pointers, so that it can be mapped to
1592 // MetaspaceShared::requested_base_address() without runtime relocation.
1593 //
1594 // Note: both the base and dynamic archive are written with
1595 // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
1596
1597 // Patch all pointers that are marked by ptrmap within this region,
1598 // where we have just dumped all the metaspace data.
1599 address patch_base = (address)SharedBaseAddress;
1600 address patch_end = (address)_ro_region.top();
1601 size_t size = patch_end - patch_base;
1602
1603 // the current value of the pointers to be patched must be within this
1604 // range (i.e., must point to valid metaspace objects)
1605 address valid_old_base = patch_base;
1606 address valid_old_end = patch_end;
1607
1608 // after patching, the pointers must point inside this range
1609 // (the requested location of the archive, as mapped at runtime).
1610 address valid_new_base = (address)MetaspaceShared::requested_base_address();
1611 address valid_new_end = valid_new_base + size;
1612
1613 log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1614 "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1615 p2i(valid_new_base), p2i(valid_new_end));
1616
1617 SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1618 valid_new_base, valid_new_end, addr_delta, ptrmap);
1619 ptrmap->iterate(&patcher);
1620 ArchivePtrMarker::compact(patcher.max_non_null_offset());
1621 }
1622 }
1623
1624 void VM_PopulateDumpSharedSpace::doit() {
1625 HeapShared::run_full_gc_in_vm_thread();
1626 CHeapBitMap ptrmap;
1627 MetaspaceShared::initialize_ptr_marker(&ptrmap);
1628
1629 // We should no longer allocate anything from the metaspace, so that:
1630 //
1631 // (1) Metaspace::allocate might trigger GC if we have run out of
1632 // committed metaspace, but we can't GC because we're running
1633 // in the VM thread.
1634 // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs.
1635 Metaspace::freeze();
1636 DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1637
1638 Thread* THREAD = VMThread::vm_thread();
1639
1640 FileMapInfo::check_nonempty_dir_in_shared_path_table();
1641
1642 NOT_PRODUCT(SystemDictionary::verify();)
1643 // The following guarantee is meant to ensure that no loader constraints
1644 // exist yet, since the constraints table is not shared. This becomes
1645 // more important now that we don't re-initialize vtables/itables for
1646 // shared classes at runtime, where constraints were previously created.
1647 guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1648 "loader constraints are not saved");
1649 guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1650 "placeholders are not saved");
1651
1652 // At this point, many classes have been loaded.
1653 // Gather systemDictionary classes in a global array and do everything to
1654 // that so we don't have to walk the SystemDictionary again.
1655 SystemDictionaryShared::check_excluded_classes();
1656 _global_klass_objects = new GrowableArray<Klass*>(1000);
1657 CollectClassesClosure collect_classes;
1658 ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1659 _global_klass_objects->sort(global_klass_compare);
1660
1661 print_class_stats();
1662
1663 // Ensure the ConstMethods won't be modified at run-time
1664 log_info(cds)("Updating ConstMethods ... ");
1665 rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1666 log_info(cds)("done. ");
1667
1668 // Remove all references outside the metadata
1669 log_info(cds)("Removing unshareable information ... ");
1670 remove_unshareable_in_classes();
1671 log_info(cds)("done. ");
1672
1673 MetaspaceShared::allocate_cloned_cpp_vtptrs();
1674 char* cloned_vtables = _mc_region.top();
1675 MetaspaceShared::allocate_cpp_vtable_clones();
1676
1677 ArchiveCompactor::initialize();
1678 ArchiveCompactor::copy_and_compact();
1679
1680 dump_symbols();
1681
1682 // Dump supported java heap objects
1683 _closed_archive_heap_regions = NULL;
1684 _open_archive_heap_regions = NULL;
1685 dump_java_heap_objects();
1686
1687 ArchiveCompactor::relocate_well_known_klasses();
1688
1689 char* serialized_data = dump_read_only_tables();
1690 _ro_region.pack();
1691
1692 // The vtable clones contain addresses of the current process.
1693 // We don't want to write these addresses into the archive. Same for i2i buffer.
1694 MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1695 memset(MetaspaceShared::i2i_entry_code_buffers(), 0,
1696 MetaspaceShared::i2i_entry_code_buffers_size());
1697
1698 // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1699 // without runtime relocation.
1700 relocate_to_requested_base_address(&ptrmap);
1701
1702 // Create and write the archive file that maps the shared spaces.
1703
1704 FileMapInfo* mapinfo = new FileMapInfo(true);
1705 mapinfo->populate_header(os::vm_allocation_granularity());
1706 mapinfo->set_serialized_data(serialized_data);
1707 mapinfo->set_cloned_vtables(cloned_vtables);
1708 mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1709 MetaspaceShared::i2i_entry_code_buffers_size());
1710 mapinfo->open_for_write();
1711 MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps);
1712 _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1713 _closed_archive_heap_regions,
1714 _closed_archive_heap_oopmaps,
1715 MetaspaceShared::first_closed_archive_heap_region,
1716 MetaspaceShared::max_closed_archive_heap_region);
1717 _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1718 _open_archive_heap_regions,
1719 _open_archive_heap_oopmaps,
1720 MetaspaceShared::first_open_archive_heap_region,
1721 MetaspaceShared::max_open_archive_heap_region);
1722
1723 mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1724 mapinfo->set_header_crc(mapinfo->compute_header_crc());
1725 mapinfo->write_header();
1726 print_region_stats(mapinfo);
1727 mapinfo->close();
1728
1729 if (log_is_enabled(Info, cds)) {
1730 ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1731 int(_mc_region.used()));
1732 }
1733
1734 if (PrintSystemDictionaryAtExit) {
1735 SystemDictionary::print();
1736 }
1737
1738 if (AllowArchivingWithJavaAgent) {
1739 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1740 "for testing purposes only and should not be used in a production environment");
1741 }
1742
1743 // There may be other pending VM operations that operate on the InstanceKlasses,
1744 // which will fail because InstanceKlasses::remove_unshareable_info()
1745 // has been called. Forget these operations and exit the VM directly.
1746 vm_direct_exit(0);
1747 }
1748
1749 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) {
1750 // Print statistics of all the regions
1751 const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used();
1752 const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned();
1753 const size_t total_reserved = _ro_region.reserved() + _rw_region.reserved() +
1754 _mc_region.reserved() +
1755 bitmap_reserved +
1756 _total_closed_archive_region_size +
1757 _total_open_archive_region_size;
1758 const size_t total_bytes = _ro_region.used() + _rw_region.used() +
1759 _mc_region.used() +
1760 bitmap_used +
1761 _total_closed_archive_region_size +
1762 _total_open_archive_region_size;
1763 const double total_u_perc = percent_of(total_bytes, total_reserved);
1764
1765 _mc_region.print(total_reserved);
1766 _rw_region.print(total_reserved);
1767 _ro_region.print(total_reserved);
1768 print_bitmap_region_stats(bitmap_used, total_reserved);
1769 print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1770 print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1771
1772 log_debug(cds)("total : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1773 total_bytes, total_reserved, total_u_perc);
1774 }
1775
1776 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1777 log_debug(cds)("bm space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1778 size, size/double(total_size)*100.0, size);
1779 }
1780
1781 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1782 const char *name, size_t total_size) {
1783 int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1784 for (int i = 0; i < arr_len; i++) {
1785 char* start = (char*)heap_mem->at(i).start();
1786 size_t size = heap_mem->at(i).byte_size();
1787 char* top = start + size;
1788 log_debug(cds)("%s%d space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used] at " INTPTR_FORMAT,
1789 name, i, size, size/double(total_size)*100.0, size, p2i(start));
1790
1791 }
1792 }
1793
1794 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo,
1795 GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1796 GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) {
1797 // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1798 // MetaspaceShared::n_regions (internal to hotspot).
1799 assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1800
1801 // mc contains the trampoline code for method entries, which are patched at run time,
1802 // so it needs to be read/write.
1803 write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1804 write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1805 write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1806 mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps);
1807 }
1808
1809 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only, bool allow_exec) {
1810 mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1811 }
1812
1813 // Update a Java object to point its Klass* to the new location after
1814 // shared archive has been compacted.
1815 void MetaspaceShared::relocate_klass_ptr(oop o) {
1816 assert(DumpSharedSpaces, "sanity");
1817 Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1818 o->set_klass(k);
1819 }
1820
1821 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1822 assert(DumpSharedSpaces, "sanity");
1823 k = ArchiveCompactor::get_relocated_klass(k);
1824 if (is_final) {
1825 k = (Klass*)(address(k) + final_delta());
1826 }
1827 return k;
1828 }
1829
1830 class LinkSharedClassesClosure : public KlassClosure {
1831 Thread* THREAD;
1832 bool _made_progress;
1833 public:
1834 LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1835
1836 void reset() { _made_progress = false; }
1837 bool made_progress() const { return _made_progress; }
1838
1839 void do_klass(Klass* k) {
1840 if (k->is_instance_klass()) {
1841 InstanceKlass* ik = InstanceKlass::cast(k);
1842 // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1843 bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class();
1844 if (do_linking) {
1845 // Link the class to cause the bytecodes to be rewritten and the
1846 // cpcache to be created. Class verification is done according
1847 // to -Xverify setting.
1848 _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1849 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1850
1851 if (DumpSharedSpaces) {
1852 // The following function is used to resolve all Strings in the statically
1853 // dumped classes to archive all the Strings. The archive heap is not supported
1854 // for the dynamic archive.
1855 ik->constants()->resolve_class_constants(THREAD);
1856 }
1857 }
1858 }
1859 }
1860 };
1861
1862 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1863 // We need to iterate because verification may cause additional classes
1864 // to be loaded.
1865 LinkSharedClassesClosure link_closure(THREAD);
1866 do {
1867 link_closure.reset();
1868 ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1869 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1870 } while (link_closure.made_progress());
1871 }
1872
1873 void MetaspaceShared::prepare_for_dumping() {
1874 Arguments::check_unsupported_dumping_properties();
1875 ClassLoader::initialize_shared_path();
1876 }
1877
1878 // Preload classes from a list, populate the shared spaces and dump to a
1879 // file.
1880 void MetaspaceShared::preload_and_dump(TRAPS) {
1881 { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1882 ResourceMark rm(THREAD);
1883 char class_list_path_str[JVM_MAXPATHLEN];
1884 // Preload classes to be shared.
1885 const char* class_list_path;
1886 if (SharedClassListFile == NULL) {
1887 // Construct the path to the class list (in jre/lib)
1888 // Walk up two directories from the location of the VM and
1889 // optionally tack on "lib" (depending on platform)
1890 os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1891 for (int i = 0; i < 3; i++) {
1892 char *end = strrchr(class_list_path_str, *os::file_separator());
1893 if (end != NULL) *end = '\0';
1894 }
1895 int class_list_path_len = (int)strlen(class_list_path_str);
1896 if (class_list_path_len >= 3) {
1897 if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1898 if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1899 jio_snprintf(class_list_path_str + class_list_path_len,
1900 sizeof(class_list_path_str) - class_list_path_len,
1901 "%slib", os::file_separator());
1902 class_list_path_len += 4;
1903 }
1904 }
1905 }
1906 if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1907 jio_snprintf(class_list_path_str + class_list_path_len,
1908 sizeof(class_list_path_str) - class_list_path_len,
1909 "%sclasslist", os::file_separator());
1910 }
1911 class_list_path = class_list_path_str;
1912 } else {
1913 class_list_path = SharedClassListFile;
1914 }
1915
1916 log_info(cds)("Loading classes to share ...");
1917 _has_error_classes = false;
1918 int class_count = preload_classes(class_list_path, THREAD);
1919 if (ExtraSharedClassListFile) {
1920 class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1921 }
1922 log_info(cds)("Loading classes to share: done.");
1923
1924 log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1925
1926 if (SharedArchiveConfigFile) {
1927 log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1928 read_extra_data(SharedArchiveConfigFile, THREAD);
1929 }
1930 log_info(cds)("Reading extra data: done.");
1931
1932 HeapShared::init_subgraph_entry_fields(THREAD);
1933
1934 // Rewrite and link classes
1935 log_info(cds)("Rewriting and linking classes ...");
1936
1937 // Link any classes which got missed. This would happen if we have loaded classes that
1938 // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1939 // fails verification, all other interfaces that were not specified in the classlist but
1940 // are implemented by K are not verified.
1941 link_and_cleanup_shared_classes(CATCH);
1942 log_info(cds)("Rewriting and linking classes: done");
1943
1944 VM_PopulateDumpSharedSpace op;
1945 MutexLocker ml(THREAD, HeapShared::is_heap_object_archiving_allowed() ?
1946 Heap_lock : NULL); // needed by HeapShared::run_gc()
1947 VMThread::execute(&op);
1948 }
1949 }
1950
1951
1952 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1953 ClassListParser parser(class_list_path);
1954 int class_count = 0;
1955
1956 while (parser.parse_one_line()) {
1957 Klass* klass = parser.load_current_class(THREAD);
1958 if (HAS_PENDING_EXCEPTION) {
1959 if (klass == NULL &&
1960 (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1961 // print a warning only when the pending exception is class not found
1962 log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1963 }
1964 CLEAR_PENDING_EXCEPTION;
1965 }
1966 if (klass != NULL) {
1967 if (log_is_enabled(Trace, cds)) {
1968 ResourceMark rm(THREAD);
1969 log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1970 }
1971
1972 if (klass->is_instance_klass()) {
1973 InstanceKlass* ik = InstanceKlass::cast(klass);
1974
1975 // Link the class to cause the bytecodes to be rewritten and the
1976 // cpcache to be created. The linking is done as soon as classes
1977 // are loaded in order that the related data structures (klass and
1978 // cpCache) are located together.
1979 try_link_class(ik, THREAD);
1980 guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1981 }
1982
1983 class_count++;
1984 }
1985 }
1986
1987 return class_count;
1988 }
1989
1990 // Returns true if the class's status has changed
1991 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
1992 Arguments::assert_is_dumping_archive();
1993 if (ik->init_state() < InstanceKlass::linked &&
1994 !SystemDictionaryShared::has_class_failed_verification(ik)) {
1995 bool saved = BytecodeVerificationLocal;
1996 if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
1997 // The verification decision is based on BytecodeVerificationRemote
1998 // for non-system classes. Since we are using the NULL classloader
1999 // to load non-system classes for customized class loaders during dumping,
2000 // we need to temporarily change BytecodeVerificationLocal to be the same as
2001 // BytecodeVerificationRemote. Note this can cause the parent system
2002 // classes also being verified. The extra overhead is acceptable during
2003 // dumping.
2004 BytecodeVerificationLocal = BytecodeVerificationRemote;
2005 }
2006 ik->link_class(THREAD);
2007 if (HAS_PENDING_EXCEPTION) {
2008 ResourceMark rm(THREAD);
2009 log_warning(cds)("Preload Warning: Verification failed for %s",
2010 ik->external_name());
2011 CLEAR_PENDING_EXCEPTION;
2012 SystemDictionaryShared::set_class_has_failed_verification(ik);
2013 _has_error_classes = true;
2014 }
2015 BytecodeVerificationLocal = saved;
2016 return true;
2017 } else {
2018 return false;
2019 }
2020 }
2021
2022 #if INCLUDE_CDS_JAVA_HEAP
2023 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
2024 // The closed and open archive heap space has maximum two regions.
2025 // See FileMapInfo::write_archive_heap_regions() for details.
2026 _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
2027 _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
2028 HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
2029 _open_archive_heap_regions);
2030 ArchiveCompactor::OtherROAllocMark mark;
2031 HeapShared::write_subgraph_info_table();
2032 }
2033
2034 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
2035 if (HeapShared::is_heap_object_archiving_allowed()) {
2036 _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2037 dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
2038
2039 _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2040 dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
2041 }
2042 }
2043
2044 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
2045 GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
2046 for (int i=0; i<regions->length(); i++) {
2047 ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
2048 size_t size_in_bits = oopmap.size();
2049 size_t size_in_bytes = oopmap.size_in_bytes();
2050 uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
2051 oopmap.write_to(buffer, size_in_bytes);
2052 log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
2053 INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
2054 p2i(buffer), size_in_bytes,
2055 p2i(regions->at(i).start()), regions->at(i).byte_size());
2056
2057 ArchiveHeapOopmapInfo info;
2058 info._oopmap = (address)buffer;
2059 info._oopmap_size_in_bits = size_in_bits;
2060 info._oopmap_size_in_bytes = size_in_bytes;
2061 oopmaps->append(info);
2062 }
2063 }
2064 #endif // INCLUDE_CDS_JAVA_HEAP
2065
2066 void ReadClosure::do_ptr(void** p) {
2067 assert(*p == NULL, "initializing previous initialized pointer.");
2068 intptr_t obj = nextPtr();
2069 assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
2070 "hit tag while initializing ptrs.");
2071 *p = (void*)obj;
2072 }
2073
2074 void ReadClosure::do_u4(u4* p) {
2075 intptr_t obj = nextPtr();
2076 *p = (u4)(uintx(obj));
2077 }
2078
2079 void ReadClosure::do_bool(bool* p) {
2080 intptr_t obj = nextPtr();
2081 *p = (bool)(uintx(obj));
2082 }
2083
2084 void ReadClosure::do_tag(int tag) {
2085 int old_tag;
2086 old_tag = (int)(intptr_t)nextPtr();
2087 // do_int(&old_tag);
2088 assert(tag == old_tag, "old tag doesn't match");
2089 FileMapInfo::assert_mark(tag == old_tag);
2090 }
2091
2092 void ReadClosure::do_oop(oop *p) {
2093 narrowOop o = (narrowOop)nextPtr();
2094 if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) {
2095 p = NULL;
2096 } else {
2097 assert(HeapShared::is_heap_object_archiving_allowed(),
2098 "Archived heap object is not allowed");
2099 assert(HeapShared::open_archive_heap_region_mapped(),
2100 "Open archive heap region is not mapped");
2101 *p = HeapShared::decode_from_archive(o);
2102 }
2103 }
2104
2105 void ReadClosure::do_region(u_char* start, size_t size) {
2106 assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
2107 assert(size % sizeof(intptr_t) == 0, "bad size");
2108 do_tag((int)size);
2109 while (size > 0) {
2110 *(intptr_t*)start = nextPtr();
2111 start += sizeof(intptr_t);
2112 size -= sizeof(intptr_t);
2113 }
2114 }
2115
2116 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
2117 assert(base <= static_top && static_top <= top, "must be");
2118 _shared_metaspace_static_top = static_top;
2119 MetaspaceObj::set_shared_metaspace_range(base, top);
2120 }
2121
2122 // Return true if given address is in the misc data region
2123 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
2124 return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
2125 }
2126
2127 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
2128 if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
2129 return true;
2130 }
2131 return false;
2132 }
2133
2134 bool MetaspaceShared::is_shared_dynamic(void* p) {
2135 if ((p < MetaspaceObj::shared_metaspace_top()) &&
2136 (p >= _shared_metaspace_static_top)) {
2137 return true;
2138 } else {
2139 return false;
2140 }
2141 }
2142
2143 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
2144 assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
2145 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2146
2147 FileMapInfo* static_mapinfo = open_static_archive();
2148 FileMapInfo* dynamic_mapinfo = NULL;
2149
2150 if (static_mapinfo != NULL) {
2151 dynamic_mapinfo = open_dynamic_archive();
2152
2153 // First try to map at the requested address
2154 result = map_archives(static_mapinfo, dynamic_mapinfo, true);
2155 if (result == MAP_ARCHIVE_MMAP_FAILURE) {
2156 // Mapping has failed (probably due to ASLR). Let's map at an address chosen
2157 // by the OS.
2158 log_info(cds)("Try to map archive(s) at an alternative address");
2159 result = map_archives(static_mapinfo, dynamic_mapinfo, false);
2160 }
2161 }
2162
2163 if (result == MAP_ARCHIVE_SUCCESS) {
2164 bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
2165 char* cds_base = static_mapinfo->mapped_base();
2166 char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
2167 set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
2168 _relocation_delta = static_mapinfo->relocation_delta();
2169 if (dynamic_mapped) {
2170 FileMapInfo::set_shared_path_table(dynamic_mapinfo);
2171 } else {
2172 FileMapInfo::set_shared_path_table(static_mapinfo);
2173 }
2174 _requested_base_address = static_mapinfo->requested_base_address();
2175 } else {
2176 set_shared_metaspace_range(NULL, NULL, NULL);
2177 UseSharedSpaces = false;
2178 FileMapInfo::fail_continue("Unable to map shared spaces");
2179 if (PrintSharedArchiveAndExit) {
2180 vm_exit_during_initialization("Unable to use shared archive.");
2181 }
2182 }
2183
2184 if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
2185 delete static_mapinfo;
2186 }
2187 if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
2188 delete dynamic_mapinfo;
2189 }
2190 }
2191
2192 FileMapInfo* MetaspaceShared::open_static_archive() {
2193 FileMapInfo* mapinfo = new FileMapInfo(true);
2194 if (!mapinfo->initialize()) {
2195 delete(mapinfo);
2196 return NULL;
2197 }
2198 return mapinfo;
2199 }
2200
2201 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
2202 if (DynamicDumpSharedSpaces) {
2203 return NULL;
2204 }
2205 if (Arguments::GetSharedDynamicArchivePath() == NULL) {
2206 return NULL;
2207 }
2208
2209 FileMapInfo* mapinfo = new FileMapInfo(false);
2210 if (!mapinfo->initialize()) {
2211 delete(mapinfo);
2212 return NULL;
2213 }
2214 return mapinfo;
2215 }
2216
2217 // use_requested_addr:
2218 // true = map at FileMapHeader::_requested_base_address
2219 // false = map at an alternative address picked by OS.
2220 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
2221 bool use_requested_addr) {
2222 if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
2223 log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
2224 return MAP_ARCHIVE_MMAP_FAILURE;
2225 }
2226
2227 PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2228 // For product build only -- this is for benchmarking the cost of doing relocation.
2229 // For debug builds, the check is done below, after reserving the space, for better test coverage
2230 // (see comment below).
2231 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2232 return MAP_ARCHIVE_MMAP_FAILURE;
2233 });
2234
2235 if (ArchiveRelocationMode == 2 && !use_requested_addr) {
2236 log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
2237 return MAP_ARCHIVE_MMAP_FAILURE;
2238 };
2239
2240 if (dynamic_mapinfo != NULL) {
2241 // Ensure that the OS won't be able to allocate new memory spaces between the two
2242 // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
2243 assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
2244 }
2245
2246 ReservedSpace archive_space_rs, class_space_rs;
2247 MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2248 char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
2249 use_requested_addr, archive_space_rs,
2250 class_space_rs);
2251 if (mapped_base_address == NULL) {
2252 result = MAP_ARCHIVE_MMAP_FAILURE;
2253 log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
2254 } else {
2255
2256 #ifdef ASSERT
2257 // Some sanity checks after reserving address spaces for archives
2258 // and class space.
2259 assert(archive_space_rs.is_reserved(), "Sanity");
2260 if (Metaspace::using_class_space()) {
2261 // Class space must closely follow the archive space. Both spaces
2262 // must be aligned correctly.
2263 assert(class_space_rs.is_reserved(),
2264 "A class space should have been reserved");
2265 assert(class_space_rs.base() >= archive_space_rs.end(),
2266 "class space should follow the cds archive space");
2267 assert(is_aligned(archive_space_rs.base(),
2268 MetaspaceShared::reserved_space_alignment()),
2269 "Archive space misaligned");
2270 assert(is_aligned(class_space_rs.base(),
2271 Metaspace::reserve_alignment()),
2272 "class space misaligned");
2273 }
2274 #endif // ASSERT
2275
2276 log_debug(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2277 p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
2278 log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2279 p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
2280
2281 if (MetaspaceShared::use_windows_memory_mapping()) {
2282 // We have now reserved address space for the archives, and will map in
2283 // the archive files into this space.
2284 //
2285 // Special handling for Windows: on Windows we cannot map a file view
2286 // into an existing memory mapping. So, we unmap the address range we
2287 // just reserved again, which will make it available for mapping the
2288 // archives.
2289 // Reserving this range has not been for naught however since it makes
2290 // us reasonably sure the address range is available.
2291 //
2292 // But still it may fail, since between unmapping the range and mapping
2293 // in the archive someone else may grab the address space. Therefore
2294 // there is a fallback in FileMap::map_region() where we just read in
2295 // the archive files sequentially instead of mapping it in. We couple
2296 // this with use_requested_addr, since we're going to patch all the
2297 // pointers anyway so there's no benefit to mmap.
2298 if (use_requested_addr) {
2299 log_info(cds)("Windows mmap workaround: releasing archive space.");
2300 archive_space_rs.release();
2301 }
2302 }
2303 MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
2304 MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
2305 map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
2306
2307 DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2308 // This is for simulating mmap failures at the requested address. In
2309 // debug builds, we do it here (after all archives have possibly been
2310 // mapped), so we can thoroughly test the code for failure handling
2311 // (releasing all allocated resource, etc).
2312 log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2313 if (static_result == MAP_ARCHIVE_SUCCESS) {
2314 static_result = MAP_ARCHIVE_MMAP_FAILURE;
2315 }
2316 if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2317 dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
2318 }
2319 });
2320
2321 if (static_result == MAP_ARCHIVE_SUCCESS) {
2322 if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2323 result = MAP_ARCHIVE_SUCCESS;
2324 } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
2325 assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
2326 // No need to retry mapping the dynamic archive again, as it will never succeed
2327 // (bad file, etc) -- just keep the base archive.
2328 log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
2329 dynamic_mapinfo->full_path());
2330 result = MAP_ARCHIVE_SUCCESS;
2331 // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
2332 // easy API to do that right now.
2333 } else {
2334 result = MAP_ARCHIVE_MMAP_FAILURE;
2335 }
2336 } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
2337 result = MAP_ARCHIVE_OTHER_FAILURE;
2338 } else {
2339 result = MAP_ARCHIVE_MMAP_FAILURE;
2340 }
2341 }
2342
2343 if (result == MAP_ARCHIVE_SUCCESS) {
2344 SharedBaseAddress = (size_t)mapped_base_address;
2345 LP64_ONLY({
2346 if (Metaspace::using_class_space()) {
2347 // Set up ccs in metaspace.
2348 Metaspace::initialize_class_space(class_space_rs);
2349
2350 // Set up compressed Klass pointer encoding: the encoding range must
2351 // cover both archive and class space.
2352 address cds_base = (address)static_mapinfo->mapped_base();
2353 address ccs_end = (address)class_space_rs.end();
2354 CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
2355
2356 // map_heap_regions() compares the current narrow oop and klass encodings
2357 // with the archived ones, so it must be done after all encodings are determined.
2358 static_mapinfo->map_heap_regions();
2359 }
2360 });
2361 log_info(cds)("Using optimized module handling %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
2362 } else {
2363 unmap_archive(static_mapinfo);
2364 unmap_archive(dynamic_mapinfo);
2365 release_reserved_spaces(archive_space_rs, class_space_rs);
2366 }
2367
2368 return result;
2369 }
2370
2371
2372 // This will reserve two address spaces suitable to house Klass structures, one
2373 // for the cds archives (static archive and optionally dynamic archive) and
2374 // optionally one move for ccs.
2375 //
2376 // Since both spaces must fall within the compressed class pointer encoding
2377 // range, they are allocated close to each other.
2378 //
2379 // Space for archives will be reserved first, followed by a potential gap,
2380 // followed by the space for ccs:
2381 //
2382 // +-- Base address A B End
2383 // | | | |
2384 // v v v v
2385 // +-------------+--------------+ +----------------------+
2386 // | static arc | [dyn. arch] | [gap] | compr. class space |
2387 // +-------------+--------------+ +----------------------+
2388 //
2389 // (The gap may result from different alignment requirements between metaspace
2390 // and CDS)
2391 //
2392 // If UseCompressedClassPointers is disabled, only one address space will be
2393 // reserved:
2394 //
2395 // +-- Base address End
2396 // | |
2397 // v v
2398 // +-------------+--------------+
2399 // | static arc | [dyn. arch] |
2400 // +-------------+--------------+
2401 //
2402 // Base address: If use_archive_base_addr address is true, the Base address is
2403 // determined by the address stored in the static archive. If
2404 // use_archive_base_addr address is false, this base address is determined
2405 // by the platform.
2406 //
2407 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
2408 // suitable to en/decode narrow Klass pointers: the base will be valid for
2409 // encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
2410 //
2411 // Return:
2412 //
2413 // - On success:
2414 // - archive_space_rs will be reserved and large enough to host static and
2415 // if needed dynamic archive: [Base, A).
2416 // archive_space_rs.base and size will be aligned to CDS reserve
2417 // granularity.
2418 // - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
2419 // be reserved. Its start address will be aligned to metaspace reserve
2420 // alignment, which may differ from CDS alignment. It will follow the cds
2421 // archive space, close enough such that narrow class pointer encoding
2422 // covers both spaces.
2423 // If UseCompressedClassPointers=0, class_space_rs remains unreserved.
2424 // - On error: NULL is returned and the spaces remain unreserved.
2425 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
2426 FileMapInfo* dynamic_mapinfo,
2427 bool use_archive_base_addr,
2428 ReservedSpace& archive_space_rs,
2429 ReservedSpace& class_space_rs) {
2430
2431 address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
2432 const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment();
2433
2434 // Size and requested location of the archive_space_rs (for both static and dynamic archives)
2435 assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
2436 size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
2437 size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
2438
2439 // If a base address is given, it must have valid alignment and be suitable as encoding base.
2440 if (base_address != NULL) {
2441 assert(is_aligned(base_address, archive_space_alignment),
2442 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2443 if (Metaspace::using_class_space()) {
2444 assert(CompressedKlassPointers::is_valid_base(base_address),
2445 "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2446 }
2447 }
2448
2449 if (!Metaspace::using_class_space()) {
2450 // Get the simple case out of the way first:
2451 // no compressed class space, simple allocation.
2452 archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
2453 false /* bool large */, (char*)base_address);
2454 if (archive_space_rs.is_reserved()) {
2455 assert(base_address == NULL ||
2456 (address)archive_space_rs.base() == base_address, "Sanity");
2457 // Register archive space with NMT.
2458 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2459 return archive_space_rs.base();
2460 }
2461 return NULL;
2462 }
2463
2464 #ifdef _LP64
2465
2466 // Complex case: two spaces adjacent to each other, both to be addressable
2467 // with narrow class pointers.
2468 // We reserve the whole range spanning both spaces, then split that range up.
2469
2470 const size_t class_space_alignment = Metaspace::reserve_alignment();
2471
2472 // To simplify matters, lets assume that metaspace alignment will always be
2473 // equal or a multiple of archive alignment.
2474 assert(is_power_of_2(class_space_alignment) &&
2475 is_power_of_2(archive_space_alignment) &&
2476 class_space_alignment >= archive_space_alignment,
2477 "Sanity");
2478
2479 const size_t class_space_size = CompressedClassSpaceSize;
2480 assert(CompressedClassSpaceSize > 0 &&
2481 is_aligned(CompressedClassSpaceSize, class_space_alignment),
2482 "CompressedClassSpaceSize malformed: "
2483 SIZE_FORMAT, CompressedClassSpaceSize);
2484
2485 const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
2486 class_space_alignment) - base_address;
2487 const size_t gap_size = ccs_begin_offset - archive_space_size;
2488
2489 const size_t total_range_size =
2490 align_up(archive_space_size + gap_size + class_space_size,
2491 os::vm_allocation_granularity());
2492
2493 ReservedSpace total_rs;
2494 if (base_address != NULL) {
2495 // Reserve at the given archive base address, or not at all.
2496 total_rs = ReservedSpace(total_range_size, archive_space_alignment,
2497 false /* bool large */, (char*) base_address);
2498 } else {
2499 // Reserve at any address, but leave it up to the platform to choose a good one.
2500 total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
2501 }
2502
2503 if (!total_rs.is_reserved()) {
2504 return NULL;
2505 }
2506
2507 // Paranoid checks:
2508 assert(base_address == NULL || (address)total_rs.base() == base_address,
2509 "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base()));
2510 assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity");
2511 assert(total_rs.size() == total_range_size, "Sanity");
2512 assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity");
2513
2514 // Now split up the space into ccs and cds archive. For simplicity, just leave
2515 // the gap reserved at the end of the archive space.
2516 archive_space_rs = total_rs.first_part(ccs_begin_offset,
2517 (size_t)os::vm_allocation_granularity(),
2518 /*split=*/true);
2519 class_space_rs = total_rs.last_part(ccs_begin_offset);
2520
2521 assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
2522 assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
2523 assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
2524 assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
2525
2526 // NMT: fix up the space tags
2527 MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2528 MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
2529
2530 return archive_space_rs.base();
2531
2532 #else
2533 ShouldNotReachHere();
2534 return NULL;
2535 #endif
2536
2537 }
2538
2539 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs,
2540 ReservedSpace& class_space_rs) {
2541 if (archive_space_rs.is_reserved()) {
2542 log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2543 archive_space_rs.release();
2544 }
2545 if (class_space_rs.is_reserved()) {
2546 log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2547 class_space_rs.release();
2548 }
2549 }
2550
2551 static int archive_regions[] = {MetaspaceShared::mc,
2552 MetaspaceShared::rw,
2553 MetaspaceShared::ro};
2554 static int archive_regions_count = 3;
2555
2556 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2557 assert(UseSharedSpaces, "must be runtime");
2558 if (mapinfo == NULL) {
2559 return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2560 }
2561
2562 mapinfo->set_is_mapped(false);
2563
2564 if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
2565 log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
2566 " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
2567 return MAP_ARCHIVE_OTHER_FAILURE;
2568 }
2569
2570 MapArchiveResult result =
2571 mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2572
2573 if (result != MAP_ARCHIVE_SUCCESS) {
2574 unmap_archive(mapinfo);
2575 return result;
2576 }
2577
2578 if (!mapinfo->validate_shared_path_table()) {
2579 unmap_archive(mapinfo);
2580 return MAP_ARCHIVE_OTHER_FAILURE;
2581 }
2582
2583 mapinfo->set_is_mapped(true);
2584 return MAP_ARCHIVE_SUCCESS;
2585 }
2586
2587 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2588 assert(UseSharedSpaces, "must be runtime");
2589 if (mapinfo != NULL) {
2590 mapinfo->unmap_regions(archive_regions, archive_regions_count);
2591 mapinfo->set_is_mapped(false);
2592 }
2593 }
2594
2595 // Read the miscellaneous data from the shared file, and
2596 // serialize it out to its various destinations.
2597
2598 void MetaspaceShared::initialize_shared_spaces() {
2599 FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2600 _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
2601 _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
2602 char* buffer = static_mapinfo->cloned_vtables();
2603 clone_cpp_vtables((intptr_t*)buffer);
2604
2605 // Verify various attributes of the archive, plus initialize the
2606 // shared string/symbol tables
2607 buffer = static_mapinfo->serialized_data();
2608 intptr_t* array = (intptr_t*)buffer;
2609 ReadClosure rc(&array);
2610 serialize(&rc);
2611
2612 // Initialize the run-time symbol table.
2613 SymbolTable::create_table();
2614
2615 static_mapinfo->patch_archived_heap_embedded_pointers();
2616
2617 // Close the mapinfo file
2618 static_mapinfo->close();
2619
2620 static_mapinfo->unmap_region(MetaspaceShared::bm);
2621
2622 FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2623 if (dynamic_mapinfo != NULL) {
2624 intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2625 ReadClosure rc(&buffer);
2626 SymbolTable::serialize_shared_table_header(&rc, false);
2627 SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2628 dynamic_mapinfo->close();
2629 }
2630
2631 if (PrintSharedArchiveAndExit) {
2632 if (PrintSharedDictionary) {
2633 tty->print_cr("\nShared classes:\n");
2634 SystemDictionaryShared::print_on(tty);
2635 }
2636 if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2637 tty->print_cr("archive is invalid");
2638 vm_exit(1);
2639 } else {
2640 tty->print_cr("archive is valid");
2641 vm_exit(0);
2642 }
2643 }
2644 }
2645
2646 // JVM/TI RedefineClasses() support:
2647 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2648 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2649
2650 if (UseSharedSpaces) {
2651 // remap the shared readonly space to shared readwrite, private
2652 FileMapInfo* mapinfo = FileMapInfo::current_info();
2653 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2654 return false;
2655 }
2656 if (FileMapInfo::dynamic_info() != NULL) {
2657 mapinfo = FileMapInfo::dynamic_info();
2658 if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2659 return false;
2660 }
2661 }
2662 _remapped_readwrite = true;
2663 }
2664 return true;
2665 }
2666
2667 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2668 // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2669 // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2670 // or so.
2671 _mc_region.print_out_of_space_msg(name, needed_bytes);
2672 _rw_region.print_out_of_space_msg(name, needed_bytes);
2673 _ro_region.print_out_of_space_msg(name, needed_bytes);
2674
2675 vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2676 "Please reduce the number of shared classes.");
2677 }
2678
2679 // This is used to relocate the pointers so that the base archive can be mapped at
2680 // MetaspaceShared::requested_base_address() without runtime relocation.
2681 intx MetaspaceShared::final_delta() {
2682 return intx(MetaspaceShared::requested_base_address()) // We want the base archive to be mapped to here at runtime
2683 - intx(SharedBaseAddress); // .. but the base archive is mapped at here at dump time
2684 }
2685
2686 void MetaspaceShared::print_on(outputStream* st) {
2687 if (UseSharedSpaces || DumpSharedSpaces) {
2688 st->print("CDS archive(s) mapped at: ");
2689 address base;
2690 address top;
2691 if (UseSharedSpaces) { // Runtime
2692 base = (address)MetaspaceObj::shared_metaspace_base();
2693 address static_top = (address)_shared_metaspace_static_top;
2694 top = (address)MetaspaceObj::shared_metaspace_top();
2695 st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2696 } else if (DumpSharedSpaces) { // Dump Time
2697 base = (address)_shared_rs.base();
2698 top = (address)_shared_rs.end();
2699 st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top));
2700 }
2701 st->print("size " SIZE_FORMAT ", ", top - base);
2702 st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
2703 } else {
2704 st->print("CDS disabled.");
2705 }
2706 st->cr();
2707 }
2708
2709
2710
2711
2712