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 
expand_top_to(char * newtop)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 
allocate(size_t num_bytes,size_t alignment)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 
append_intptr_t(intptr_t n,bool need_to_mark)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 
print(size_t total_bytes) const169 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 
print_out_of_space_msg(const char * failing_region,size_t needed_bytes)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 
init(ReservedSpace * rs,VirtualSpace * vs)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 
pack(DumpRegion * next)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 
init_shared_dump_space(DumpRegion * first_space)210 void MetaspaceShared::init_shared_dump_space(DumpRegion* first_space) {
211   first_space->init(&_shared_rs, &_shared_vs);
212 }
213 
misc_code_dump_space()214 DumpRegion* MetaspaceShared::misc_code_dump_space() {
215   return &_mc_region;
216 }
217 
read_write_dump_space()218 DumpRegion* MetaspaceShared::read_write_dump_space() {
219   return &_rw_region;
220 }
221 
read_only_dump_space()222 DumpRegion* MetaspaceShared::read_only_dump_space() {
223   return &_ro_region;
224 }
225 
pack_dump_space(DumpRegion * current,DumpRegion * next,ReservedSpace * rs)226 void MetaspaceShared::pack_dump_space(DumpRegion* current, DumpRegion* next,
227                                       ReservedSpace* rs) {
228   current->pack(next);
229 }
230 
symbol_space_alloc(size_t num_bytes)231 char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
232   return _symbol_region.allocate(num_bytes);
233 }
234 
misc_code_space_alloc(size_t num_bytes)235 char* MetaspaceShared::misc_code_space_alloc(size_t num_bytes) {
236   return _mc_region.allocate(num_bytes);
237 }
238 
read_only_space_alloc(size_t num_bytes)239 char* MetaspaceShared::read_only_space_alloc(size_t num_bytes) {
240   return _ro_region.allocate(num_bytes);
241 }
242 
reserved_space_alignment()243 size_t MetaspaceShared::reserved_space_alignment() { return os::vm_allocation_granularity(); }
244 
shared_base_valid(char * shared_base)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 
shared_base_too_high(char * shared_base,size_t cds_total)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 
compute_shared_base(size_t cds_total)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 
initialize_dumptime_shared_and_meta_spaces()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()
post_initialize(TRAPS)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 GrowableArray<Handle>* _extra_interned_strings = NULL;
460 
read_extra_data(const char * filename,TRAPS)461 void MetaspaceShared::read_extra_data(const char* filename, TRAPS) {
462   _extra_interned_strings = new (ResourceObj::C_HEAP, mtInternal)GrowableArray<Handle>(10000, true);
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 
commit_to(ReservedSpace * rs,VirtualSpace * vs,char * newtop)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 
initialize_ptr_marker(CHeapBitMap * ptrmap)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 
serialize(SerializeClosure * soc)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 
i2i_entry_code_buffers(size_t total_size)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 
object_delta_uintx(void * obj)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 
global_klass_compare(Klass ** a,Klass ** b)627 static int global_klass_compare(Klass** a, Klass **b) {
628   return a[0]->name()->fast_compare(b[0]->name());
629 }
630 
collected_klasses()631 GrowableArray<Klass*>* MetaspaceShared::collected_klasses() {
632   return _global_klass_objects;
633 }
634 
collect_array_classes(Klass * k)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 {
do_klass(Klass * k)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 
remove_unshareable_in_classes()666 static void remove_unshareable_in_classes() {
667   for (int i = 0; i < _global_klass_objects->length(); i++) {
668     Klass* k = _global_klass_objects->at(i);
669     if (!k->is_objArray_klass()) {
670       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
671       // on their array classes.
672       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
673       k->remove_unshareable_info();
674     }
675   }
676 }
677 
remove_java_mirror_in_classes()678 static void remove_java_mirror_in_classes() {
679   for (int i = 0; i < _global_klass_objects->length(); i++) {
680     Klass* k = _global_klass_objects->at(i);
681     if (!k->is_objArray_klass()) {
682       // InstanceKlass and TypeArrayKlass will in turn call remove_unshareable_info
683       // on their array classes.
684       assert(k->is_instance_klass() || k->is_typeArray_klass(), "must be");
685       k->remove_java_mirror();
686     }
687   }
688 }
689 
clear_basic_type_mirrors()690 static void clear_basic_type_mirrors() {
691   assert(!HeapShared::is_heap_object_archiving_allowed(), "Sanity");
692   Universe::set_int_mirror(NULL);
693   Universe::set_float_mirror(NULL);
694   Universe::set_double_mirror(NULL);
695   Universe::set_byte_mirror(NULL);
696   Universe::set_bool_mirror(NULL);
697   Universe::set_char_mirror(NULL);
698   Universe::set_long_mirror(NULL);
699   Universe::set_short_mirror(NULL);
700   Universe::set_void_mirror(NULL);
701 }
702 
rewrite_nofast_bytecode(const methodHandle & method)703 static void rewrite_nofast_bytecode(const methodHandle& method) {
704   BytecodeStream bcs(method);
705   while (!bcs.is_last_bytecode()) {
706     Bytecodes::Code opcode = bcs.next();
707     switch (opcode) {
708     case Bytecodes::_getfield:      *bcs.bcp() = Bytecodes::_nofast_getfield;      break;
709     case Bytecodes::_putfield:      *bcs.bcp() = Bytecodes::_nofast_putfield;      break;
710     case Bytecodes::_aload_0:       *bcs.bcp() = Bytecodes::_nofast_aload_0;       break;
711     case Bytecodes::_iload: {
712       if (!bcs.is_wide()) {
713         *bcs.bcp() = Bytecodes::_nofast_iload;
714       }
715       break;
716     }
717     default: break;
718     }
719   }
720 }
721 
722 // Walk all methods in the class list to ensure that they won't be modified at
723 // run time. This includes:
724 // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
725 //     at run time by RewriteBytecodes/RewriteFrequentPairs
726 // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread * thread)727 static void rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread) {
728   for (int i = 0; i < _global_klass_objects->length(); i++) {
729     Klass* k = _global_klass_objects->at(i);
730     if (k->is_instance_klass()) {
731       InstanceKlass* ik = InstanceKlass::cast(k);
732       MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(thread, ik);
733     }
734   }
735 }
736 
rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread * thread,InstanceKlass * ik)737 void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
738   for (int i = 0; i < ik->methods()->length(); i++) {
739     methodHandle m(thread, ik->methods()->at(i));
740     rewrite_nofast_bytecode(m);
741     Fingerprinter fp(m);
742     // The side effect of this call sets method's fingerprint field.
743     fp.fingerprint();
744   }
745 }
746 
747 // Objects of the Metadata types (such as Klass and ConstantPool) have C++ vtables.
748 // (In GCC this is the field <Type>::_vptr, i.e., first word in the object.)
749 //
750 // Addresses of the vtables and the methods may be different across JVM runs,
751 // if libjvm.so is dynamically loaded at a different base address.
752 //
753 // To ensure that the Metadata objects in the CDS archive always have the correct vtable:
754 //
755 // + at dump time:  we redirect the _vptr to point to our own vtables inside
756 //                  the CDS image
757 // + at run time:   we clone the actual contents of the vtables from libjvm.so
758 //                  into our own tables.
759 
760 // Currently, the archive contain ONLY the following types of objects that have C++ vtables.
761 #define CPP_VTABLE_PATCH_TYPES_DO(f) \
762   f(ConstantPool) \
763   f(InstanceKlass) \
764   f(InstanceClassLoaderKlass) \
765   f(InstanceMirrorKlass) \
766   f(InstanceRefKlass) \
767   f(Method) \
768   f(ObjArrayKlass) \
769   f(TypeArrayKlass)
770 
771 class CppVtableInfo {
772   intptr_t _vtable_size;
773   intptr_t _cloned_vtable[1];
774 public:
num_slots(int vtable_size)775   static int num_slots(int vtable_size) {
776     return 1 + vtable_size; // Need to add the space occupied by _vtable_size;
777   }
vtable_size()778   int vtable_size()           { return int(uintx(_vtable_size)); }
set_vtable_size(int n)779   void set_vtable_size(int n) { _vtable_size = intptr_t(n); }
cloned_vtable()780   intptr_t* cloned_vtable()   { return &_cloned_vtable[0]; }
zero()781   void zero()                 { memset(_cloned_vtable, 0, sizeof(intptr_t) * vtable_size()); }
782   // Returns the address of the next CppVtableInfo that can be placed immediately after this CppVtableInfo
byte_size(int vtable_size)783   static size_t byte_size(int vtable_size) {
784     CppVtableInfo i;
785     return pointer_delta(&i._cloned_vtable[vtable_size], &i, sizeof(u1));
786   }
787 };
788 
789 template <class T> class CppVtableCloner : public T {
vtable_of(Metadata & m)790   static intptr_t* vtable_of(Metadata& m) {
791     return *((intptr_t**)&m);
792   }
793   static CppVtableInfo* _info;
794 
795   static int get_vtable_length(const char* name);
796 
797 public:
798   // Allocate and initialize the C++ vtable, starting from top, but do not go past end.
799   static intptr_t* allocate(const char* name);
800 
801   // Clone the vtable to ...
802   static intptr_t* clone_vtable(const char* name, CppVtableInfo* info);
803 
zero_vtable_clone()804   static void zero_vtable_clone() {
805     assert(DumpSharedSpaces, "dump-time only");
806     _info->zero();
807   }
808 
is_valid_shared_object(const T * obj)809   static bool is_valid_shared_object(const T* obj) {
810     intptr_t* vptr = *(intptr_t**)obj;
811     return vptr == _info->cloned_vtable();
812   }
813 };
814 
815 template <class T> CppVtableInfo* CppVtableCloner<T>::_info = NULL;
816 
817 template <class T>
allocate(const char * name)818 intptr_t* CppVtableCloner<T>::allocate(const char* name) {
819   assert(is_aligned(_mc_region.top(), sizeof(intptr_t)), "bad alignment");
820   int n = get_vtable_length(name);
821   _info = (CppVtableInfo*)_mc_region.allocate(CppVtableInfo::byte_size(n), sizeof(intptr_t));
822   _info->set_vtable_size(n);
823 
824   intptr_t* p = clone_vtable(name, _info);
825   assert((char*)p == _mc_region.top(), "must be");
826 
827   return _info->cloned_vtable();
828 }
829 
830 template <class T>
clone_vtable(const char * name,CppVtableInfo * info)831 intptr_t* CppVtableCloner<T>::clone_vtable(const char* name, CppVtableInfo* info) {
832   if (!DumpSharedSpaces) {
833     assert(_info == 0, "_info is initialized only at dump time");
834     _info = info; // Remember it -- it will be used by MetaspaceShared::is_valid_shared_method()
835   }
836   T tmp; // Allocate temporary dummy metadata object to get to the original vtable.
837   int n = info->vtable_size();
838   intptr_t* srcvtable = vtable_of(tmp);
839   intptr_t* dstvtable = info->cloned_vtable();
840 
841   // We already checked (and, if necessary, adjusted n) when the vtables were allocated, so we are
842   // safe to do memcpy.
843   log_debug(cds, vtables)("Copying %3d vtable entries for %s", n, name);
844   memcpy(dstvtable, srcvtable, sizeof(intptr_t) * n);
845   return dstvtable + n;
846 }
847 
848 // To determine the size of the vtable for each type, we use the following
849 // trick by declaring 2 subclasses:
850 //
851 //   class CppVtableTesterA: public InstanceKlass {virtual int   last_virtual_method() {return 1;}    };
852 //   class CppVtableTesterB: public InstanceKlass {virtual void* last_virtual_method() {return NULL}; };
853 //
854 // CppVtableTesterA and CppVtableTesterB's vtables have the following properties:
855 // - Their size (N+1) is exactly one more than the size of InstanceKlass's vtable (N)
856 // - The first N entries have are exactly the same as in InstanceKlass's vtable.
857 // - Their last entry is different.
858 //
859 // So to determine the value of N, we just walk CppVtableTesterA and CppVtableTesterB's tables
860 // and find the first entry that's different.
861 //
862 // This works on all C++ compilers supported by Oracle, but you may need to tweak it for more
863 // esoteric compilers.
864 
865 template <class T> class CppVtableTesterB: public T {
866 public:
last_virtual_method()867   virtual int last_virtual_method() {return 1;}
868 };
869 
870 template <class T> class CppVtableTesterA : public T {
871 public:
last_virtual_method()872   virtual void* last_virtual_method() {
873     // Make this different than CppVtableTesterB::last_virtual_method so the C++
874     // compiler/linker won't alias the two functions.
875     return NULL;
876   }
877 };
878 
879 template <class T>
get_vtable_length(const char * name)880 int CppVtableCloner<T>::get_vtable_length(const char* name) {
881   CppVtableTesterA<T> a;
882   CppVtableTesterB<T> b;
883 
884   intptr_t* avtable = vtable_of(a);
885   intptr_t* bvtable = vtable_of(b);
886 
887   // Start at slot 1, because slot 0 may be RTTI (on Solaris/Sparc)
888   int vtable_len = 1;
889   for (; ; vtable_len++) {
890     if (avtable[vtable_len] != bvtable[vtable_len]) {
891       break;
892     }
893   }
894   log_debug(cds, vtables)("Found   %3d vtable entries for %s", vtable_len, name);
895 
896   return vtable_len;
897 }
898 
899 #define ALLOC_CPP_VTABLE_CLONE(c) \
900   _cloned_cpp_vtptrs[c##_Kind] = CppVtableCloner<c>::allocate(#c); \
901   ArchivePtrMarker::mark_pointer(&_cloned_cpp_vtptrs[c##_Kind]);
902 
903 #define CLONE_CPP_VTABLE(c) \
904   p = CppVtableCloner<c>::clone_vtable(#c, (CppVtableInfo*)p);
905 
906 #define ZERO_CPP_VTABLE(c) \
907  CppVtableCloner<c>::zero_vtable_clone();
908 
909 //------------------------------ for DynamicDumpSharedSpaces - start
910 #define DECLARE_CLONED_VTABLE_KIND(c) c ## _Kind,
911 
912 enum {
913   // E.g., ConstantPool_Kind == 0, InstanceKlass == 1, etc.
914   CPP_VTABLE_PATCH_TYPES_DO(DECLARE_CLONED_VTABLE_KIND)
915   _num_cloned_vtable_kinds
916 };
917 
918 // This is the index of all the cloned vtables. E.g., for
919 //     ConstantPool* cp = ....; // an archived constant pool
920 //     InstanceKlass* ik = ....;// an archived class
921 // the following holds true:
922 //     _cloned_cpp_vtptrs[ConstantPool_Kind]  == ((intptr_t**)cp)[0]
923 //     _cloned_cpp_vtptrs[InstanceKlass_Kind] == ((intptr_t**)ik)[0]
924 static intptr_t** _cloned_cpp_vtptrs = NULL;
925 
allocate_cloned_cpp_vtptrs()926 void MetaspaceShared::allocate_cloned_cpp_vtptrs() {
927   assert(DumpSharedSpaces, "must");
928   size_t vtptrs_bytes = _num_cloned_vtable_kinds * sizeof(intptr_t*);
929   _cloned_cpp_vtptrs = (intptr_t**)_mc_region.allocate(vtptrs_bytes, sizeof(intptr_t*));
930 }
931 
serialize_cloned_cpp_vtptrs(SerializeClosure * soc)932 void MetaspaceShared::serialize_cloned_cpp_vtptrs(SerializeClosure* soc) {
933   soc->do_ptr((void**)&_cloned_cpp_vtptrs);
934 }
935 
fix_cpp_vtable_for_dynamic_archive(MetaspaceObj::Type msotype,address obj)936 intptr_t* MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(MetaspaceObj::Type msotype, address obj) {
937   Arguments::assert_is_dumping_archive();
938   int kind = -1;
939   switch (msotype) {
940   case MetaspaceObj::SymbolType:
941   case MetaspaceObj::TypeArrayU1Type:
942   case MetaspaceObj::TypeArrayU2Type:
943   case MetaspaceObj::TypeArrayU4Type:
944   case MetaspaceObj::TypeArrayU8Type:
945   case MetaspaceObj::TypeArrayOtherType:
946   case MetaspaceObj::ConstMethodType:
947   case MetaspaceObj::ConstantPoolCacheType:
948   case MetaspaceObj::AnnotationsType:
949   case MetaspaceObj::MethodCountersType:
950   case MetaspaceObj::RecordComponentType:
951     // These have no vtables.
952     break;
953   case MetaspaceObj::ClassType:
954     {
955       Klass* k = (Klass*)obj;
956       assert(k->is_klass(), "must be");
957       if (k->is_instance_klass()) {
958         InstanceKlass* ik = InstanceKlass::cast(k);
959         if (ik->is_class_loader_instance_klass()) {
960           kind = InstanceClassLoaderKlass_Kind;
961         } else if (ik->is_reference_instance_klass()) {
962           kind = InstanceRefKlass_Kind;
963         } else if (ik->is_mirror_instance_klass()) {
964           kind = InstanceMirrorKlass_Kind;
965         } else {
966           kind = InstanceKlass_Kind;
967         }
968       } else if (k->is_typeArray_klass()) {
969         kind = TypeArrayKlass_Kind;
970       } else {
971         assert(k->is_objArray_klass(), "must be");
972         kind = ObjArrayKlass_Kind;
973       }
974     }
975     break;
976 
977   case MetaspaceObj::MethodType:
978     {
979       Method* m = (Method*)obj;
980       assert(m->is_method(), "must be");
981       kind = Method_Kind;
982     }
983     break;
984 
985   case MetaspaceObj::MethodDataType:
986     // We don't archive MethodData <-- should have been removed in removed_unsharable_info
987     ShouldNotReachHere();
988     break;
989 
990   case MetaspaceObj::ConstantPoolType:
991     {
992       ConstantPool *cp = (ConstantPool*)obj;
993       assert(cp->is_constantPool(), "must be");
994       kind = ConstantPool_Kind;
995     }
996     break;
997 
998   default:
999     ShouldNotReachHere();
1000   }
1001 
1002   if (kind >= 0) {
1003     assert(kind < _num_cloned_vtable_kinds, "must be");
1004     return _cloned_cpp_vtptrs[kind];
1005   } else {
1006     return NULL;
1007   }
1008 }
1009 
1010 //------------------------------ for DynamicDumpSharedSpaces - end
1011 
1012 // This can be called at both dump time and run time:
1013 // - clone the contents of the c++ vtables into the space
1014 //   allocated by allocate_cpp_vtable_clones()
clone_cpp_vtables(intptr_t * p)1015 void MetaspaceShared::clone_cpp_vtables(intptr_t* p) {
1016   assert(DumpSharedSpaces || UseSharedSpaces, "sanity");
1017   CPP_VTABLE_PATCH_TYPES_DO(CLONE_CPP_VTABLE);
1018 }
1019 
zero_cpp_vtable_clones_for_writing()1020 void MetaspaceShared::zero_cpp_vtable_clones_for_writing() {
1021   assert(DumpSharedSpaces, "dump-time only");
1022   CPP_VTABLE_PATCH_TYPES_DO(ZERO_CPP_VTABLE);
1023 }
1024 
1025 // Allocate and initialize the C++ vtables, starting from top, but do not go past end.
allocate_cpp_vtable_clones()1026 char* MetaspaceShared::allocate_cpp_vtable_clones() {
1027   char* cloned_vtables = _mc_region.top(); // This is the beginning of all the cloned vtables
1028 
1029   assert(DumpSharedSpaces, "dump-time only");
1030   // Layout (each slot is a intptr_t):
1031   //   [number of slots in the first vtable = n1]
1032   //   [ <n1> slots for the first vtable]
1033   //   [number of slots in the first second = n2]
1034   //   [ <n2> slots for the second vtable]
1035   //   ...
1036   // The order of the vtables is the same as the CPP_VTAB_PATCH_TYPES_DO macro.
1037   CPP_VTABLE_PATCH_TYPES_DO(ALLOC_CPP_VTABLE_CLONE);
1038 
1039   return cloned_vtables;
1040 }
1041 
is_valid_shared_method(const Method * m)1042 bool MetaspaceShared::is_valid_shared_method(const Method* m) {
1043   assert(is_in_shared_metaspace(m), "must be");
1044   return CppVtableCloner<Method>::is_valid_shared_object(m);
1045 }
1046 
do_oop(oop * o)1047 void WriteClosure::do_oop(oop* o) {
1048   if (*o == NULL) {
1049     _dump_region->append_intptr_t(0);
1050   } else {
1051     assert(HeapShared::is_heap_object_archiving_allowed(),
1052            "Archiving heap object is not allowed");
1053     _dump_region->append_intptr_t(
1054       (intptr_t)CompressedOops::encode_not_null(*o));
1055   }
1056 }
1057 
do_region(u_char * start,size_t size)1058 void WriteClosure::do_region(u_char* start, size_t size) {
1059   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
1060   assert(size % sizeof(intptr_t) == 0, "bad size");
1061   do_tag((int)size);
1062   while (size > 0) {
1063     _dump_region->append_intptr_t(*(intptr_t*)start, true);
1064     start += sizeof(intptr_t);
1065     size -= sizeof(intptr_t);
1066   }
1067 }
1068 
1069 // This is for dumping detailed statistics for the allocations
1070 // in the shared spaces.
1071 class DumpAllocStats : public ResourceObj {
1072 public:
1073 
1074   // Here's poor man's enum inheritance
1075 #define SHAREDSPACE_OBJ_TYPES_DO(f) \
1076   METASPACE_OBJ_TYPES_DO(f) \
1077   f(SymbolHashentry) \
1078   f(SymbolBucket) \
1079   f(StringHashentry) \
1080   f(StringBucket) \
1081   f(Other)
1082 
1083   enum Type {
1084     // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc
1085     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_DECLARE)
1086     _number_of_types
1087   };
1088 
type_name(Type type)1089   static const char * type_name(Type type) {
1090     switch(type) {
1091     SHAREDSPACE_OBJ_TYPES_DO(METASPACE_OBJ_TYPE_NAME_CASE)
1092     default:
1093       ShouldNotReachHere();
1094       return NULL;
1095     }
1096   }
1097 
1098 public:
1099   enum { RO = 0, RW = 1 };
1100 
1101   int _counts[2][_number_of_types];
1102   int _bytes [2][_number_of_types];
1103 
DumpAllocStats()1104   DumpAllocStats() {
1105     memset(_counts, 0, sizeof(_counts));
1106     memset(_bytes,  0, sizeof(_bytes));
1107   };
1108 
record(MetaspaceObj::Type type,int byte_size,bool read_only)1109   void record(MetaspaceObj::Type type, int byte_size, bool read_only) {
1110     assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity");
1111     int which = (read_only) ? RO : RW;
1112     _counts[which][type] ++;
1113     _bytes [which][type] += byte_size;
1114   }
1115 
record_other_type(int byte_size,bool read_only)1116   void record_other_type(int byte_size, bool read_only) {
1117     int which = (read_only) ? RO : RW;
1118     _bytes [which][OtherType] += byte_size;
1119   }
1120   void print_stats(int ro_all, int rw_all, int mc_all);
1121 };
1122 
print_stats(int ro_all,int rw_all,int mc_all)1123 void DumpAllocStats::print_stats(int ro_all, int rw_all, int mc_all) {
1124   // Calculate size of data that was not allocated by Metaspace::allocate()
1125   MetaspaceSharedStats *stats = MetaspaceShared::stats();
1126 
1127   // symbols
1128   _counts[RO][SymbolHashentryType] = stats->symbol.hashentry_count;
1129   _bytes [RO][SymbolHashentryType] = stats->symbol.hashentry_bytes;
1130 
1131   _counts[RO][SymbolBucketType] = stats->symbol.bucket_count;
1132   _bytes [RO][SymbolBucketType] = stats->symbol.bucket_bytes;
1133 
1134   // strings
1135   _counts[RO][StringHashentryType] = stats->string.hashentry_count;
1136   _bytes [RO][StringHashentryType] = stats->string.hashentry_bytes;
1137 
1138   _counts[RO][StringBucketType] = stats->string.bucket_count;
1139   _bytes [RO][StringBucketType] = stats->string.bucket_bytes;
1140 
1141   // TODO: count things like dictionary, vtable, etc
1142   _bytes[RW][OtherType] += mc_all;
1143   rw_all += mc_all; // mc is mapped Read/Write
1144 
1145   // prevent divide-by-zero
1146   if (ro_all < 1) {
1147     ro_all = 1;
1148   }
1149   if (rw_all < 1) {
1150     rw_all = 1;
1151   }
1152 
1153   int all_ro_count = 0;
1154   int all_ro_bytes = 0;
1155   int all_rw_count = 0;
1156   int all_rw_bytes = 0;
1157 
1158 // To make fmt_stats be a syntactic constant (for format warnings), use #define.
1159 #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f"
1160   const char *sep = "--------------------+---------------------------+---------------------------+--------------------------";
1161   const char *hdr = "                        ro_cnt   ro_bytes     % |   rw_cnt   rw_bytes     % |  all_cnt  all_bytes     %";
1162 
1163   LogMessage(cds) msg;
1164 
1165   msg.debug("Detailed metadata info (excluding st regions; rw stats include mc regions):");
1166   msg.debug("%s", hdr);
1167   msg.debug("%s", sep);
1168   for (int type = 0; type < int(_number_of_types); type ++) {
1169     const char *name = type_name((Type)type);
1170     int ro_count = _counts[RO][type];
1171     int ro_bytes = _bytes [RO][type];
1172     int rw_count = _counts[RW][type];
1173     int rw_bytes = _bytes [RW][type];
1174     int count = ro_count + rw_count;
1175     int bytes = ro_bytes + rw_bytes;
1176 
1177     double ro_perc = percent_of(ro_bytes, ro_all);
1178     double rw_perc = percent_of(rw_bytes, rw_all);
1179     double perc    = percent_of(bytes, ro_all + rw_all);
1180 
1181     msg.debug(fmt_stats, name,
1182                          ro_count, ro_bytes, ro_perc,
1183                          rw_count, rw_bytes, rw_perc,
1184                          count, bytes, perc);
1185 
1186     all_ro_count += ro_count;
1187     all_ro_bytes += ro_bytes;
1188     all_rw_count += rw_count;
1189     all_rw_bytes += rw_bytes;
1190   }
1191 
1192   int all_count = all_ro_count + all_rw_count;
1193   int all_bytes = all_ro_bytes + all_rw_bytes;
1194 
1195   double all_ro_perc = percent_of(all_ro_bytes, ro_all);
1196   double all_rw_perc = percent_of(all_rw_bytes, rw_all);
1197   double all_perc    = percent_of(all_bytes, ro_all + rw_all);
1198 
1199   msg.debug("%s", sep);
1200   msg.debug(fmt_stats, "Total",
1201                        all_ro_count, all_ro_bytes, all_ro_perc,
1202                        all_rw_count, all_rw_bytes, all_rw_perc,
1203                        all_count, all_bytes, all_perc);
1204 
1205   assert(all_ro_bytes == ro_all, "everything should have been counted");
1206   assert(all_rw_bytes == rw_all, "everything should have been counted");
1207 
1208 #undef fmt_stats
1209 }
1210 
1211 // Populate the shared space.
1212 
1213 class VM_PopulateDumpSharedSpace: public VM_Operation {
1214 private:
1215   GrowableArray<MemRegion> *_closed_archive_heap_regions;
1216   GrowableArray<MemRegion> *_open_archive_heap_regions;
1217 
1218   GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
1219   GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
1220 
1221   void dump_java_heap_objects() NOT_CDS_JAVA_HEAP_RETURN;
1222   void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
1223   void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
1224                                  GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
1225   void dump_symbols();
1226   char* dump_read_only_tables();
1227   void print_class_stats();
1228   void print_region_stats(FileMapInfo* map_info);
1229   void print_bitmap_region_stats(size_t size, size_t total_size);
1230   void print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1231                                const char *name, size_t total_size);
1232   void relocate_to_requested_base_address(CHeapBitMap* ptrmap);
1233 
1234 public:
1235 
type() const1236   VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
1237   void doit();   // outline because gdb sucks
allow_nested_vm_operations() const1238   bool allow_nested_vm_operations() const { return true; }
1239 }; // class VM_PopulateDumpSharedSpace
1240 
1241 class SortedSymbolClosure: public SymbolClosure {
1242   GrowableArray<Symbol*> _symbols;
do_symbol(Symbol ** sym)1243   virtual void do_symbol(Symbol** sym) {
1244     assert((*sym)->is_permanent(), "archived symbols must be permanent");
1245     _symbols.append(*sym);
1246   }
compare_symbols_by_address(Symbol ** a,Symbol ** b)1247   static int compare_symbols_by_address(Symbol** a, Symbol** b) {
1248     if (a[0] < b[0]) {
1249       return -1;
1250     } else if (a[0] == b[0]) {
1251       ResourceMark rm;
1252       log_warning(cds)("Duplicated symbol %s unexpected", (*a)->as_C_string());
1253       return 0;
1254     } else {
1255       return 1;
1256     }
1257   }
1258 
1259 public:
SortedSymbolClosure()1260   SortedSymbolClosure() {
1261     SymbolTable::symbols_do(this);
1262     _symbols.sort(compare_symbols_by_address);
1263   }
get_sorted_symbols()1264   GrowableArray<Symbol*>* get_sorted_symbols() {
1265     return &_symbols;
1266   }
1267 };
1268 
1269 // ArchiveCompactor --
1270 //
1271 // This class is the central piece of shared archive compaction -- all metaspace data are
1272 // initially allocated outside of the shared regions. ArchiveCompactor copies the
1273 // metaspace data into their final location in the shared regions.
1274 
1275 class ArchiveCompactor : AllStatic {
1276   static const int INITIAL_TABLE_SIZE = 8087;
1277   static const int MAX_TABLE_SIZE     = 1000000;
1278 
1279   static DumpAllocStats* _alloc_stats;
1280   static SortedSymbolClosure* _ssc;
1281 
1282   typedef KVHashtable<address, address, mtInternal> RelocationTable;
1283   static RelocationTable* _new_loc_table;
1284 
1285 public:
initialize()1286   static void initialize() {
1287     _alloc_stats = new(ResourceObj::C_HEAP, mtInternal)DumpAllocStats;
1288     _new_loc_table = new RelocationTable(INITIAL_TABLE_SIZE);
1289   }
alloc_stats()1290   static DumpAllocStats* alloc_stats() {
1291     return _alloc_stats;
1292   }
1293 
1294   // Use this when you allocate space with MetaspaceShare::read_only_space_alloc()
1295   // outside of ArchiveCompactor::allocate(). These are usually for misc tables
1296   // that are allocated in the RO space.
1297   class OtherROAllocMark {
1298     char* _oldtop;
1299   public:
OtherROAllocMark()1300     OtherROAllocMark() {
1301       _oldtop = _ro_region.top();
1302     }
~OtherROAllocMark()1303     ~OtherROAllocMark() {
1304       char* newtop = _ro_region.top();
1305       ArchiveCompactor::alloc_stats()->record_other_type(int(newtop - _oldtop), true);
1306     }
1307   };
1308 
allocate(MetaspaceClosure::Ref * ref,bool read_only)1309   static void allocate(MetaspaceClosure::Ref* ref, bool read_only) {
1310     address obj = ref->obj();
1311     int bytes = ref->size() * BytesPerWord;
1312     char* p;
1313     size_t alignment = BytesPerWord;
1314     char* oldtop;
1315     char* newtop;
1316 
1317     if (read_only) {
1318       oldtop = _ro_region.top();
1319       p = _ro_region.allocate(bytes, alignment);
1320       newtop = _ro_region.top();
1321     } else {
1322       oldtop = _rw_region.top();
1323       if (ref->msotype() == MetaspaceObj::ClassType) {
1324         // Save a pointer immediate in front of an InstanceKlass, so
1325         // we can do a quick lookup from InstanceKlass* -> RunTimeSharedClassInfo*
1326         // without building another hashtable. See RunTimeSharedClassInfo::get_for()
1327         // in systemDictionaryShared.cpp.
1328         Klass* klass = (Klass*)obj;
1329         if (klass->is_instance_klass()) {
1330           SystemDictionaryShared::validate_before_archiving(InstanceKlass::cast(klass));
1331           _rw_region.allocate(sizeof(address), BytesPerWord);
1332         }
1333       }
1334       p = _rw_region.allocate(bytes, alignment);
1335       newtop = _rw_region.top();
1336     }
1337     memcpy(p, obj, bytes);
1338 
1339     intptr_t* cloned_vtable = MetaspaceShared::fix_cpp_vtable_for_dynamic_archive(ref->msotype(), (address)p);
1340     if (cloned_vtable != NULL) {
1341       *(address*)p = (address)cloned_vtable;
1342       ArchivePtrMarker::mark_pointer((address*)p);
1343     }
1344 
1345     assert(_new_loc_table->lookup(obj) == NULL, "each object can be relocated at most once");
1346     _new_loc_table->add(obj, (address)p);
1347     log_trace(cds)("Copy: " PTR_FORMAT " ==> " PTR_FORMAT " %d", p2i(obj), p2i(p), bytes);
1348     if (_new_loc_table->maybe_grow(MAX_TABLE_SIZE)) {
1349       log_info(cds, hashtables)("Expanded _new_loc_table to %d", _new_loc_table->table_size());
1350     }
1351     _alloc_stats->record(ref->msotype(), int(newtop - oldtop), read_only);
1352   }
1353 
get_new_loc(MetaspaceClosure::Ref * ref)1354   static address get_new_loc(MetaspaceClosure::Ref* ref) {
1355     address* pp = _new_loc_table->lookup(ref->obj());
1356     assert(pp != NULL, "must be");
1357     return *pp;
1358   }
1359 
1360 private:
1361   // Makes a shallow copy of visited MetaspaceObj's
1362   class ShallowCopier: public UniqueMetaspaceClosure {
1363     bool _read_only;
1364   public:
ShallowCopier(bool read_only)1365     ShallowCopier(bool read_only) : _read_only(read_only) {}
1366 
do_unique_ref(Ref * ref,bool read_only)1367     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1368       if (read_only == _read_only) {
1369         allocate(ref, read_only);
1370       }
1371       return true; // recurse into ref.obj()
1372     }
1373   };
1374 
1375   // Relocate embedded pointers within a MetaspaceObj's shallow copy
1376   class ShallowCopyEmbeddedRefRelocator: public UniqueMetaspaceClosure {
1377   public:
do_unique_ref(Ref * ref,bool read_only)1378     virtual bool do_unique_ref(Ref* ref, bool read_only) {
1379       address new_loc = get_new_loc(ref);
1380       RefRelocator refer;
1381       ref->metaspace_pointers_do_at(&refer, new_loc);
1382       return true; // recurse into ref.obj()
1383     }
push_special(SpecialRef type,Ref * ref,intptr_t * p)1384     virtual void push_special(SpecialRef type, Ref* ref, intptr_t* p) {
1385       assert(type == _method_entry_ref, "only special type allowed for now");
1386       address obj = ref->obj();
1387       address new_obj = get_new_loc(ref);
1388       size_t offset = pointer_delta(p, obj,  sizeof(u1));
1389       intptr_t* new_p = (intptr_t*)(new_obj + offset);
1390       assert(*p == *new_p, "must be a copy");
1391       ArchivePtrMarker::mark_pointer((address*)new_p);
1392     }
1393   };
1394 
1395   // Relocate a reference to point to its shallow copy
1396   class RefRelocator: public MetaspaceClosure {
1397   public:
do_ref(Ref * ref,bool read_only)1398     virtual bool do_ref(Ref* ref, bool read_only) {
1399       if (ref->not_null()) {
1400         ref->update(get_new_loc(ref));
1401         ArchivePtrMarker::mark_pointer(ref->addr());
1402       }
1403       return false; // Do not recurse.
1404     }
1405   };
1406 
1407 #ifdef ASSERT
1408   class IsRefInArchiveChecker: public MetaspaceClosure {
1409   public:
do_ref(Ref * ref,bool read_only)1410     virtual bool do_ref(Ref* ref, bool read_only) {
1411       if (ref->not_null()) {
1412         char* obj = (char*)ref->obj();
1413         assert(_ro_region.contains(obj) || _rw_region.contains(obj),
1414                "must be relocated to point to CDS archive");
1415       }
1416       return false; // Do not recurse.
1417     }
1418   };
1419 #endif
1420 
1421 public:
copy_and_compact()1422   static void copy_and_compact() {
1423     ResourceMark rm;
1424     SortedSymbolClosure the_ssc; // StackObj
1425     _ssc = &the_ssc;
1426 
1427     log_info(cds)("Scanning all metaspace objects ... ");
1428     {
1429       // allocate and shallow-copy RW objects, immediately following the MC region
1430       log_info(cds)("Allocating RW objects ... ");
1431       _mc_region.pack(&_rw_region);
1432 
1433       ResourceMark rm;
1434       ShallowCopier rw_copier(false);
1435       iterate_roots(&rw_copier);
1436     }
1437     {
1438       // allocate and shallow-copy of RO object, immediately following the RW region
1439       log_info(cds)("Allocating RO objects ... ");
1440       _rw_region.pack(&_ro_region);
1441 
1442       ResourceMark rm;
1443       ShallowCopier ro_copier(true);
1444       iterate_roots(&ro_copier);
1445     }
1446     {
1447       log_info(cds)("Relocating embedded pointers ... ");
1448       ResourceMark rm;
1449       ShallowCopyEmbeddedRefRelocator emb_reloc;
1450       iterate_roots(&emb_reloc);
1451     }
1452     {
1453       log_info(cds)("Relocating external roots ... ");
1454       ResourceMark rm;
1455       RefRelocator ext_reloc;
1456       iterate_roots(&ext_reloc);
1457     }
1458     {
1459       log_info(cds)("Fixing symbol identity hash ... ");
1460       os::init_random(0x12345678);
1461       GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1462       for (int i=0; i<symbols->length(); i++) {
1463         symbols->at(i)->update_identity_hash();
1464       }
1465     }
1466 #ifdef ASSERT
1467     {
1468       log_info(cds)("Verifying external roots ... ");
1469       ResourceMark rm;
1470       IsRefInArchiveChecker checker;
1471       iterate_roots(&checker);
1472     }
1473 #endif
1474 
1475 
1476     // cleanup
1477     _ssc = NULL;
1478   }
1479 
1480   // We must relocate the System::_well_known_klasses only after we have copied the
1481   // java objects in during dump_java_heap_objects(): during the object copy, we operate on
1482   // old objects which assert that their klass is the original klass.
relocate_well_known_klasses()1483   static void relocate_well_known_klasses() {
1484     {
1485       log_info(cds)("Relocating SystemDictionary::_well_known_klasses[] ... ");
1486       ResourceMark rm;
1487       RefRelocator ext_reloc;
1488       SystemDictionary::well_known_klasses_do(&ext_reloc);
1489     }
1490     // NOTE: after this point, we shouldn't have any globals that can reach the old
1491     // objects.
1492 
1493     // We cannot use any of the objects in the heap anymore (except for the
1494     // shared strings) because their headers no longer point to valid Klasses.
1495   }
1496 
iterate_roots(MetaspaceClosure * it)1497   static void iterate_roots(MetaspaceClosure* it) {
1498     // To ensure deterministic contents in the archive, we just need to ensure that
1499     // we iterate the MetsapceObjs in a deterministic order. It doesn't matter where
1500     // the MetsapceObjs are located originally, as they are copied sequentially into
1501     // the archive during the iteration.
1502     //
1503     // The only issue here is that the symbol table and the system directories may be
1504     // randomly ordered, so we copy the symbols and klasses into two arrays and sort
1505     // them deterministically.
1506     //
1507     // During -Xshare:dump, the order of Symbol creation is strictly determined by
1508     // the SharedClassListFile (class loading is done in a single thread and the JIT
1509     // is disabled). Also, Symbols are allocated in monotonically increasing addresses
1510     // (see Symbol::operator new(size_t, int)). So if we iterate the Symbols by
1511     // ascending address order, we ensure that all Symbols are copied into deterministic
1512     // locations in the archive.
1513     GrowableArray<Symbol*>* symbols = _ssc->get_sorted_symbols();
1514     for (int i=0; i<symbols->length(); i++) {
1515       it->push(symbols->adr_at(i));
1516     }
1517     if (_global_klass_objects != NULL) {
1518       // Need to fix up the pointers
1519       for (int i = 0; i < _global_klass_objects->length(); i++) {
1520         // NOTE -- this requires that the vtable is NOT yet patched, or else we are hosed.
1521         it->push(_global_klass_objects->adr_at(i));
1522       }
1523     }
1524     FileMapInfo::metaspace_pointers_do(it, false);
1525     SystemDictionaryShared::dumptime_classes_do(it);
1526     Universe::metaspace_pointers_do(it);
1527     SymbolTable::metaspace_pointers_do(it);
1528     vmSymbols::metaspace_pointers_do(it);
1529 
1530     it->finish();
1531   }
1532 
get_relocated_klass(Klass * orig_klass)1533   static Klass* get_relocated_klass(Klass* orig_klass) {
1534     assert(DumpSharedSpaces, "dump time only");
1535     address* pp = _new_loc_table->lookup((address)orig_klass);
1536     assert(pp != NULL, "must be");
1537     Klass* klass = (Klass*)(*pp);
1538     assert(klass->is_klass(), "must be");
1539     return klass;
1540   }
1541 };
1542 
1543 DumpAllocStats* ArchiveCompactor::_alloc_stats;
1544 SortedSymbolClosure* ArchiveCompactor::_ssc;
1545 ArchiveCompactor::RelocationTable* ArchiveCompactor::_new_loc_table;
1546 
dump_symbols()1547 void VM_PopulateDumpSharedSpace::dump_symbols() {
1548   log_info(cds)("Dumping symbol table ...");
1549 
1550   NOT_PRODUCT(SymbolTable::verify());
1551   SymbolTable::write_to_archive();
1552 }
1553 
dump_read_only_tables()1554 char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
1555   ArchiveCompactor::OtherROAllocMark mark;
1556 
1557   log_info(cds)("Removing java_mirror ... ");
1558   if (!HeapShared::is_heap_object_archiving_allowed()) {
1559     clear_basic_type_mirrors();
1560   }
1561   remove_java_mirror_in_classes();
1562   log_info(cds)("done. ");
1563 
1564   SystemDictionaryShared::write_to_archive();
1565 
1566   // Write the other data to the output array.
1567   char* start = _ro_region.top();
1568   WriteClosure wc(&_ro_region);
1569   MetaspaceShared::serialize(&wc);
1570 
1571   // Write the bitmaps for patching the archive heap regions
1572   _closed_archive_heap_oopmaps = NULL;
1573   _open_archive_heap_oopmaps = NULL;
1574   dump_archive_heap_oopmaps();
1575 
1576   return start;
1577 }
1578 
print_class_stats()1579 void VM_PopulateDumpSharedSpace::print_class_stats() {
1580   log_info(cds)("Number of classes %d", _global_klass_objects->length());
1581   {
1582     int num_type_array = 0, num_obj_array = 0, num_inst = 0;
1583     for (int i = 0; i < _global_klass_objects->length(); i++) {
1584       Klass* k = _global_klass_objects->at(i);
1585       if (k->is_instance_klass()) {
1586         num_inst ++;
1587       } else if (k->is_objArray_klass()) {
1588         num_obj_array ++;
1589       } else {
1590         assert(k->is_typeArray_klass(), "sanity");
1591         num_type_array ++;
1592       }
1593     }
1594     log_info(cds)("    instance classes   = %5d", num_inst);
1595     log_info(cds)("    obj array classes  = %5d", num_obj_array);
1596     log_info(cds)("    type array classes = %5d", num_type_array);
1597   }
1598 }
1599 
relocate_to_requested_base_address(CHeapBitMap * ptrmap)1600 void VM_PopulateDumpSharedSpace::relocate_to_requested_base_address(CHeapBitMap* ptrmap) {
1601   intx addr_delta = MetaspaceShared::final_delta();
1602   if (addr_delta == 0) {
1603     ArchivePtrMarker::compact((address)SharedBaseAddress, (address)_ro_region.top());
1604   } else {
1605     // We are not able to reserve space at MetaspaceShared::requested_base_address() (due to ASLR).
1606     // This means that the current content of the archive is based on a random
1607     // address. Let's relocate all the pointers, so that it can be mapped to
1608     // MetaspaceShared::requested_base_address() without runtime relocation.
1609     //
1610     // Note: both the base and dynamic archive are written with
1611     // FileMapHeader::_requested_base_address == MetaspaceShared::requested_base_address()
1612 
1613     // Patch all pointers that are marked by ptrmap within this region,
1614     // where we have just dumped all the metaspace data.
1615     address patch_base = (address)SharedBaseAddress;
1616     address patch_end  = (address)_ro_region.top();
1617     size_t size = patch_end - patch_base;
1618 
1619     // the current value of the pointers to be patched must be within this
1620     // range (i.e., must point to valid metaspace objects)
1621     address valid_old_base = patch_base;
1622     address valid_old_end  = patch_end;
1623 
1624     // after patching, the pointers must point inside this range
1625     // (the requested location of the archive, as mapped at runtime).
1626     address valid_new_base = (address)MetaspaceShared::requested_base_address();
1627     address valid_new_end  = valid_new_base + size;
1628 
1629     log_debug(cds)("Relocating archive from [" INTPTR_FORMAT " - " INTPTR_FORMAT " ] to "
1630                    "[" INTPTR_FORMAT " - " INTPTR_FORMAT " ]", p2i(patch_base), p2i(patch_end),
1631                    p2i(valid_new_base), p2i(valid_new_end));
1632 
1633     SharedDataRelocator<true> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1634                                       valid_new_base, valid_new_end, addr_delta, ptrmap);
1635     ptrmap->iterate(&patcher);
1636     ArchivePtrMarker::compact(patcher.max_non_null_offset());
1637   }
1638 }
1639 
doit()1640 void VM_PopulateDumpSharedSpace::doit() {
1641   CHeapBitMap ptrmap;
1642   MetaspaceShared::initialize_ptr_marker(&ptrmap);
1643 
1644   // We should no longer allocate anything from the metaspace, so that:
1645   //
1646   // (1) Metaspace::allocate might trigger GC if we have run out of
1647   //     committed metaspace, but we can't GC because we're running
1648   //     in the VM thread.
1649   // (2) ArchiveCompactor needs to work with a stable set of MetaspaceObjs.
1650   Metaspace::freeze();
1651   DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
1652 
1653   Thread* THREAD = VMThread::vm_thread();
1654 
1655   FileMapInfo::check_nonempty_dir_in_shared_path_table();
1656 
1657   NOT_PRODUCT(SystemDictionary::verify();)
1658   // The following guarantee is meant to ensure that no loader constraints
1659   // exist yet, since the constraints table is not shared.  This becomes
1660   // more important now that we don't re-initialize vtables/itables for
1661   // shared classes at runtime, where constraints were previously created.
1662   guarantee(SystemDictionary::constraints()->number_of_entries() == 0,
1663             "loader constraints are not saved");
1664   guarantee(SystemDictionary::placeholders()->number_of_entries() == 0,
1665           "placeholders are not saved");
1666 
1667   // At this point, many classes have been loaded.
1668   // Gather systemDictionary classes in a global array and do everything to
1669   // that so we don't have to walk the SystemDictionary again.
1670   SystemDictionaryShared::check_excluded_classes();
1671   _global_klass_objects = new GrowableArray<Klass*>(1000);
1672   CollectClassesClosure collect_classes;
1673   ClassLoaderDataGraph::loaded_classes_do(&collect_classes);
1674   _global_klass_objects->sort(global_klass_compare);
1675 
1676   print_class_stats();
1677 
1678   // Ensure the ConstMethods won't be modified at run-time
1679   log_info(cds)("Updating ConstMethods ... ");
1680   rewrite_nofast_bytecodes_and_calculate_fingerprints(THREAD);
1681   log_info(cds)("done. ");
1682 
1683   // Remove all references outside the metadata
1684   log_info(cds)("Removing unshareable information ... ");
1685   remove_unshareable_in_classes();
1686   log_info(cds)("done. ");
1687 
1688   MetaspaceShared::allocate_cloned_cpp_vtptrs();
1689   char* cloned_vtables = _mc_region.top();
1690   MetaspaceShared::allocate_cpp_vtable_clones();
1691 
1692   ArchiveCompactor::initialize();
1693   ArchiveCompactor::copy_and_compact();
1694 
1695   dump_symbols();
1696 
1697   // Dump supported java heap objects
1698   _closed_archive_heap_regions = NULL;
1699   _open_archive_heap_regions = NULL;
1700   dump_java_heap_objects();
1701 
1702   ArchiveCompactor::relocate_well_known_klasses();
1703 
1704   char* serialized_data = dump_read_only_tables();
1705   _ro_region.pack();
1706 
1707   // The vtable clones contain addresses of the current process.
1708   // We don't want to write these addresses into the archive. Same for i2i buffer.
1709   MetaspaceShared::zero_cpp_vtable_clones_for_writing();
1710   memset(MetaspaceShared::i2i_entry_code_buffers(), 0,
1711          MetaspaceShared::i2i_entry_code_buffers_size());
1712 
1713   // relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
1714   // without runtime relocation.
1715   relocate_to_requested_base_address(&ptrmap);
1716 
1717   // Create and write the archive file that maps the shared spaces.
1718 
1719   FileMapInfo* mapinfo = new FileMapInfo(true);
1720   mapinfo->populate_header(os::vm_allocation_granularity());
1721   mapinfo->set_serialized_data(serialized_data);
1722   mapinfo->set_cloned_vtables(cloned_vtables);
1723   mapinfo->set_i2i_entry_code_buffers(MetaspaceShared::i2i_entry_code_buffers(),
1724                                       MetaspaceShared::i2i_entry_code_buffers_size());
1725   mapinfo->open_for_write();
1726   MetaspaceShared::write_core_archive_regions(mapinfo, _closed_archive_heap_oopmaps, _open_archive_heap_oopmaps);
1727   _total_closed_archive_region_size = mapinfo->write_archive_heap_regions(
1728                                         _closed_archive_heap_regions,
1729                                         _closed_archive_heap_oopmaps,
1730                                         MetaspaceShared::first_closed_archive_heap_region,
1731                                         MetaspaceShared::max_closed_archive_heap_region);
1732   _total_open_archive_region_size = mapinfo->write_archive_heap_regions(
1733                                         _open_archive_heap_regions,
1734                                         _open_archive_heap_oopmaps,
1735                                         MetaspaceShared::first_open_archive_heap_region,
1736                                         MetaspaceShared::max_open_archive_heap_region);
1737 
1738   mapinfo->set_final_requested_base((char*)MetaspaceShared::requested_base_address());
1739   mapinfo->set_header_crc(mapinfo->compute_header_crc());
1740   mapinfo->write_header();
1741   print_region_stats(mapinfo);
1742   mapinfo->close();
1743 
1744   if (log_is_enabled(Info, cds)) {
1745     ArchiveCompactor::alloc_stats()->print_stats(int(_ro_region.used()), int(_rw_region.used()),
1746                                                  int(_mc_region.used()));
1747   }
1748 
1749   if (PrintSystemDictionaryAtExit) {
1750     SystemDictionary::print();
1751   }
1752 
1753   if (AllowArchivingWithJavaAgent) {
1754     warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
1755             "for testing purposes only and should not be used in a production environment");
1756   }
1757 
1758   // There may be other pending VM operations that operate on the InstanceKlasses,
1759   // which will fail because InstanceKlasses::remove_unshareable_info()
1760   // has been called. Forget these operations and exit the VM directly.
1761   vm_direct_exit(0);
1762 }
1763 
print_region_stats(FileMapInfo * map_info)1764 void VM_PopulateDumpSharedSpace::print_region_stats(FileMapInfo *map_info) {
1765   // Print statistics of all the regions
1766   const size_t bitmap_used = map_info->space_at(MetaspaceShared::bm)->used();
1767   const size_t bitmap_reserved = map_info->space_at(MetaspaceShared::bm)->used_aligned();
1768   const size_t total_reserved = _ro_region.reserved()  + _rw_region.reserved() +
1769                                 _mc_region.reserved()  +
1770                                 bitmap_reserved +
1771                                 _total_closed_archive_region_size +
1772                                 _total_open_archive_region_size;
1773   const size_t total_bytes = _ro_region.used()  + _rw_region.used() +
1774                              _mc_region.used()  +
1775                              bitmap_used +
1776                              _total_closed_archive_region_size +
1777                              _total_open_archive_region_size;
1778   const double total_u_perc = percent_of(total_bytes, total_reserved);
1779 
1780   _mc_region.print(total_reserved);
1781   _rw_region.print(total_reserved);
1782   _ro_region.print(total_reserved);
1783   print_bitmap_region_stats(bitmap_used, total_reserved);
1784   print_heap_region_stats(_closed_archive_heap_regions, "ca", total_reserved);
1785   print_heap_region_stats(_open_archive_heap_regions, "oa", total_reserved);
1786 
1787   log_debug(cds)("total    : " SIZE_FORMAT_W(9) " [100.0%% of total] out of " SIZE_FORMAT_W(9) " bytes [%5.1f%% used]",
1788                  total_bytes, total_reserved, total_u_perc);
1789 }
1790 
print_bitmap_region_stats(size_t size,size_t total_size)1791 void VM_PopulateDumpSharedSpace::print_bitmap_region_stats(size_t size, size_t total_size) {
1792   log_debug(cds)("bm  space: " SIZE_FORMAT_W(9) " [ %4.1f%% of total] out of " SIZE_FORMAT_W(9) " bytes [100.0%% used]",
1793                  size, size/double(total_size)*100.0, size);
1794 }
1795 
print_heap_region_stats(GrowableArray<MemRegion> * heap_mem,const char * name,size_t total_size)1796 void VM_PopulateDumpSharedSpace::print_heap_region_stats(GrowableArray<MemRegion> *heap_mem,
1797                                                          const char *name, size_t total_size) {
1798   int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1799   for (int i = 0; i < arr_len; i++) {
1800       char* start = (char*)heap_mem->at(i).start();
1801       size_t size = heap_mem->at(i).byte_size();
1802       char* top = start + size;
1803       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,
1804                      name, i, size, size/double(total_size)*100.0, size, p2i(start));
1805 
1806   }
1807 }
1808 
write_core_archive_regions(FileMapInfo * mapinfo,GrowableArray<ArchiveHeapOopmapInfo> * closed_oopmaps,GrowableArray<ArchiveHeapOopmapInfo> * open_oopmaps)1809 void MetaspaceShared::write_core_archive_regions(FileMapInfo* mapinfo,
1810                                                  GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1811                                                  GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) {
1812   // Make sure NUM_CDS_REGIONS (exported in cds.h) agrees with
1813   // MetaspaceShared::n_regions (internal to hotspot).
1814   assert(NUM_CDS_REGIONS == MetaspaceShared::n_regions, "sanity");
1815 
1816   // mc contains the trampoline code for method entries, which are patched at run time,
1817   // so it needs to be read/write.
1818   write_region(mapinfo, mc, &_mc_region, /*read_only=*/false,/*allow_exec=*/true);
1819   write_region(mapinfo, rw, &_rw_region, /*read_only=*/false,/*allow_exec=*/false);
1820   write_region(mapinfo, ro, &_ro_region, /*read_only=*/true, /*allow_exec=*/false);
1821   mapinfo->write_bitmap_region(ArchivePtrMarker::ptrmap(), closed_oopmaps, open_oopmaps);
1822 }
1823 
write_region(FileMapInfo * mapinfo,int region_idx,DumpRegion * dump_region,bool read_only,bool allow_exec)1824 void MetaspaceShared::write_region(FileMapInfo* mapinfo, int region_idx, DumpRegion* dump_region, bool read_only,  bool allow_exec) {
1825   mapinfo->write_region(region_idx, dump_region->base(), dump_region->used(), read_only, allow_exec);
1826 }
1827 
1828 // Update a Java object to point its Klass* to the new location after
1829 // shared archive has been compacted.
relocate_klass_ptr(oop o)1830 void MetaspaceShared::relocate_klass_ptr(oop o) {
1831   assert(DumpSharedSpaces, "sanity");
1832   Klass* k = ArchiveCompactor::get_relocated_klass(o->klass());
1833   o->set_klass(k);
1834 }
1835 
get_relocated_klass(Klass * k,bool is_final)1836 Klass* MetaspaceShared::get_relocated_klass(Klass *k, bool is_final) {
1837   assert(DumpSharedSpaces, "sanity");
1838   k = ArchiveCompactor::get_relocated_klass(k);
1839   if (is_final) {
1840     k = (Klass*)(address(k) + final_delta());
1841   }
1842   return k;
1843 }
1844 
1845 class LinkSharedClassesClosure : public KlassClosure {
1846   Thread* THREAD;
1847   bool    _made_progress;
1848  public:
LinkSharedClassesClosure(Thread * thread)1849   LinkSharedClassesClosure(Thread* thread) : THREAD(thread), _made_progress(false) {}
1850 
reset()1851   void reset()               { _made_progress = false; }
made_progress() const1852   bool made_progress() const { return _made_progress; }
1853 
do_klass(Klass * k)1854   void do_klass(Klass* k) {
1855     if (k->is_instance_klass()) {
1856       InstanceKlass* ik = InstanceKlass::cast(k);
1857       // For dynamic CDS dump, only link classes loaded by the builtin class loaders.
1858       bool do_linking = DumpSharedSpaces ? true : !ik->is_shared_unregistered_class();
1859       if (do_linking) {
1860         // Link the class to cause the bytecodes to be rewritten and the
1861         // cpcache to be created. Class verification is done according
1862         // to -Xverify setting.
1863         _made_progress |= MetaspaceShared::try_link_class(ik, THREAD);
1864         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1865 
1866         if (DumpSharedSpaces) {
1867           // The following function is used to resolve all Strings in the statically
1868           // dumped classes to archive all the Strings. The archive heap is not supported
1869           // for the dynamic archive.
1870           ik->constants()->resolve_class_constants(THREAD);
1871         }
1872       }
1873     }
1874   }
1875 };
1876 
link_and_cleanup_shared_classes(TRAPS)1877 void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
1878   // We need to iterate because verification may cause additional classes
1879   // to be loaded.
1880   LinkSharedClassesClosure link_closure(THREAD);
1881   do {
1882     link_closure.reset();
1883     ClassLoaderDataGraph::unlocked_loaded_classes_do(&link_closure);
1884     guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
1885   } while (link_closure.made_progress());
1886 }
1887 
prepare_for_dumping()1888 void MetaspaceShared::prepare_for_dumping() {
1889   Arguments::check_unsupported_dumping_properties();
1890   ClassLoader::initialize_shared_path();
1891 }
1892 
1893 // Preload classes from a list, populate the shared spaces and dump to a
1894 // file.
preload_and_dump(TRAPS)1895 void MetaspaceShared::preload_and_dump(TRAPS) {
1896   { TraceTime timer("Dump Shared Spaces", TRACETIME_LOG(Info, startuptime));
1897     ResourceMark rm(THREAD);
1898     char class_list_path_str[JVM_MAXPATHLEN];
1899     // Preload classes to be shared.
1900     const char* class_list_path;
1901     if (SharedClassListFile == NULL) {
1902       // Construct the path to the class list (in jre/lib)
1903       // Walk up two directories from the location of the VM and
1904       // optionally tack on "lib" (depending on platform)
1905       os::jvm_path(class_list_path_str, sizeof(class_list_path_str));
1906       for (int i = 0; i < 3; i++) {
1907         char *end = strrchr(class_list_path_str, *os::file_separator());
1908         if (end != NULL) *end = '\0';
1909       }
1910       int class_list_path_len = (int)strlen(class_list_path_str);
1911       if (class_list_path_len >= 3) {
1912         if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) {
1913           if (class_list_path_len < JVM_MAXPATHLEN - 4) {
1914             jio_snprintf(class_list_path_str + class_list_path_len,
1915                          sizeof(class_list_path_str) - class_list_path_len,
1916                          "%slib", os::file_separator());
1917             class_list_path_len += 4;
1918           }
1919         }
1920       }
1921       if (class_list_path_len < JVM_MAXPATHLEN - 10) {
1922         jio_snprintf(class_list_path_str + class_list_path_len,
1923                      sizeof(class_list_path_str) - class_list_path_len,
1924                      "%sclasslist", os::file_separator());
1925       }
1926       class_list_path = class_list_path_str;
1927     } else {
1928       class_list_path = SharedClassListFile;
1929     }
1930 
1931     log_info(cds)("Loading classes to share ...");
1932     _has_error_classes = false;
1933     int class_count = preload_classes(class_list_path, THREAD);
1934     if (ExtraSharedClassListFile) {
1935       class_count += preload_classes(ExtraSharedClassListFile, THREAD);
1936     }
1937     log_info(cds)("Loading classes to share: done.");
1938 
1939     log_info(cds)("Shared spaces: preloaded %d classes", class_count);
1940 
1941     if (SharedArchiveConfigFile) {
1942       log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
1943       read_extra_data(SharedArchiveConfigFile, THREAD);
1944     }
1945     log_info(cds)("Reading extra data: done.");
1946 
1947     HeapShared::init_subgraph_entry_fields(THREAD);
1948 
1949     // Rewrite and link classes
1950     log_info(cds)("Rewriting and linking classes ...");
1951 
1952     // Link any classes which got missed. This would happen if we have loaded classes that
1953     // were not explicitly specified in the classlist. E.g., if an interface implemented by class K
1954     // fails verification, all other interfaces that were not specified in the classlist but
1955     // are implemented by K are not verified.
1956     link_and_cleanup_shared_classes(CATCH);
1957     log_info(cds)("Rewriting and linking classes: done");
1958 
1959     if (HeapShared::is_heap_object_archiving_allowed()) {
1960       // Avoid fragmentation while archiving heap objects.
1961       Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1962       Universe::heap()->collect(GCCause::_archive_time_gc);
1963       Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1964     }
1965 
1966     VM_PopulateDumpSharedSpace op;
1967     VMThread::execute(&op);
1968   }
1969 }
1970 
1971 
preload_classes(const char * class_list_path,TRAPS)1972 int MetaspaceShared::preload_classes(const char* class_list_path, TRAPS) {
1973   ClassListParser parser(class_list_path);
1974   int class_count = 0;
1975 
1976   while (parser.parse_one_line()) {
1977     Klass* klass = parser.load_current_class(THREAD);
1978     if (HAS_PENDING_EXCEPTION) {
1979       if (klass == NULL &&
1980           (PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_ClassNotFoundException())) {
1981         // print a warning only when the pending exception is class not found
1982         log_warning(cds)("Preload Warning: Cannot find %s", parser.current_class_name());
1983       }
1984       CLEAR_PENDING_EXCEPTION;
1985     }
1986     if (klass != NULL) {
1987       if (log_is_enabled(Trace, cds)) {
1988         ResourceMark rm(THREAD);
1989         log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
1990       }
1991 
1992       if (klass->is_instance_klass()) {
1993         InstanceKlass* ik = InstanceKlass::cast(klass);
1994 
1995         // Link the class to cause the bytecodes to be rewritten and the
1996         // cpcache to be created. The linking is done as soon as classes
1997         // are loaded in order that the related data structures (klass and
1998         // cpCache) are located together.
1999         try_link_class(ik, THREAD);
2000         guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class");
2001       }
2002 
2003       class_count++;
2004     }
2005   }
2006 
2007   return class_count;
2008 }
2009 
2010 // Returns true if the class's status has changed
try_link_class(InstanceKlass * ik,TRAPS)2011 bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) {
2012   Arguments::assert_is_dumping_archive();
2013   if (ik->init_state() < InstanceKlass::linked &&
2014       !SystemDictionaryShared::has_class_failed_verification(ik)) {
2015     bool saved = BytecodeVerificationLocal;
2016     if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
2017       // The verification decision is based on BytecodeVerificationRemote
2018       // for non-system classes. Since we are using the NULL classloader
2019       // to load non-system classes for customized class loaders during dumping,
2020       // we need to temporarily change BytecodeVerificationLocal to be the same as
2021       // BytecodeVerificationRemote. Note this can cause the parent system
2022       // classes also being verified. The extra overhead is acceptable during
2023       // dumping.
2024       BytecodeVerificationLocal = BytecodeVerificationRemote;
2025     }
2026     ik->link_class(THREAD);
2027     if (HAS_PENDING_EXCEPTION) {
2028       ResourceMark rm(THREAD);
2029       log_warning(cds)("Preload Warning: Verification failed for %s",
2030                     ik->external_name());
2031       CLEAR_PENDING_EXCEPTION;
2032       SystemDictionaryShared::set_class_has_failed_verification(ik);
2033       _has_error_classes = true;
2034     }
2035     BytecodeVerificationLocal = saved;
2036     return true;
2037   } else {
2038     return false;
2039   }
2040 }
2041 
2042 #if INCLUDE_CDS_JAVA_HEAP
dump_java_heap_objects()2043 void VM_PopulateDumpSharedSpace::dump_java_heap_objects() {
2044   // The closed and open archive heap space has maximum two regions.
2045   // See FileMapInfo::write_archive_heap_regions() for details.
2046   _closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
2047   _open_archive_heap_regions = new GrowableArray<MemRegion>(2);
2048   HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
2049                                         _open_archive_heap_regions);
2050   ArchiveCompactor::OtherROAllocMark mark;
2051   HeapShared::write_subgraph_info_table();
2052 }
2053 
dump_archive_heap_oopmaps()2054 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
2055   if (HeapShared::is_heap_object_archiving_allowed()) {
2056     _closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2057     dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
2058 
2059     _open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
2060     dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
2061   }
2062 }
2063 
dump_archive_heap_oopmaps(GrowableArray<MemRegion> * regions,GrowableArray<ArchiveHeapOopmapInfo> * oopmaps)2064 void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
2065                                                            GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
2066   for (int i=0; i<regions->length(); i++) {
2067     ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
2068     size_t size_in_bits = oopmap.size();
2069     size_t size_in_bytes = oopmap.size_in_bytes();
2070     uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
2071     oopmap.write_to(buffer, size_in_bytes);
2072     log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
2073                         INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
2074                         p2i(buffer), size_in_bytes,
2075                         p2i(regions->at(i).start()), regions->at(i).byte_size());
2076 
2077     ArchiveHeapOopmapInfo info;
2078     info._oopmap = (address)buffer;
2079     info._oopmap_size_in_bits = size_in_bits;
2080     info._oopmap_size_in_bytes = size_in_bytes;
2081     oopmaps->append(info);
2082   }
2083 }
2084 #endif // INCLUDE_CDS_JAVA_HEAP
2085 
do_ptr(void ** p)2086 void ReadClosure::do_ptr(void** p) {
2087   assert(*p == NULL, "initializing previous initialized pointer.");
2088   intptr_t obj = nextPtr();
2089   assert((intptr_t)obj >= 0 || (intptr_t)obj < -100,
2090          "hit tag while initializing ptrs.");
2091   *p = (void*)obj;
2092 }
2093 
do_u4(u4 * p)2094 void ReadClosure::do_u4(u4* p) {
2095   intptr_t obj = nextPtr();
2096   *p = (u4)(uintx(obj));
2097 }
2098 
do_bool(bool * p)2099 void ReadClosure::do_bool(bool* p) {
2100   intptr_t obj = nextPtr();
2101   *p = (bool)(uintx(obj));
2102 }
2103 
do_tag(int tag)2104 void ReadClosure::do_tag(int tag) {
2105   int old_tag;
2106   old_tag = (int)(intptr_t)nextPtr();
2107   // do_int(&old_tag);
2108   assert(tag == old_tag, "old tag doesn't match");
2109   FileMapInfo::assert_mark(tag == old_tag);
2110 }
2111 
do_oop(oop * p)2112 void ReadClosure::do_oop(oop *p) {
2113   narrowOop o = (narrowOop)nextPtr();
2114   if (o == 0 || !HeapShared::open_archive_heap_region_mapped()) {
2115     p = NULL;
2116   } else {
2117     assert(HeapShared::is_heap_object_archiving_allowed(),
2118            "Archived heap object is not allowed");
2119     assert(HeapShared::open_archive_heap_region_mapped(),
2120            "Open archive heap region is not mapped");
2121     *p = HeapShared::decode_from_archive(o);
2122   }
2123 }
2124 
do_region(u_char * start,size_t size)2125 void ReadClosure::do_region(u_char* start, size_t size) {
2126   assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment");
2127   assert(size % sizeof(intptr_t) == 0, "bad size");
2128   do_tag((int)size);
2129   while (size > 0) {
2130     *(intptr_t*)start = nextPtr();
2131     start += sizeof(intptr_t);
2132     size -= sizeof(intptr_t);
2133   }
2134 }
2135 
set_shared_metaspace_range(void * base,void * static_top,void * top)2136 void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
2137   assert(base <= static_top && static_top <= top, "must be");
2138   _shared_metaspace_static_top = static_top;
2139   MetaspaceObj::set_shared_metaspace_range(base, top);
2140 }
2141 
2142 // Return true if given address is in the misc data region
is_in_shared_region(const void * p,int idx)2143 bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
2144   return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
2145 }
2146 
is_in_trampoline_frame(address addr)2147 bool MetaspaceShared::is_in_trampoline_frame(address addr) {
2148   if (UseSharedSpaces && is_in_shared_region(addr, MetaspaceShared::mc)) {
2149     return true;
2150   }
2151   return false;
2152 }
2153 
is_shared_dynamic(void * p)2154 bool MetaspaceShared::is_shared_dynamic(void* p) {
2155   if ((p < MetaspaceObj::shared_metaspace_top()) &&
2156       (p >= _shared_metaspace_static_top)) {
2157     return true;
2158   } else {
2159     return false;
2160   }
2161 }
2162 
initialize_runtime_shared_and_meta_spaces()2163 void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
2164   assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
2165   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2166 
2167   FileMapInfo* static_mapinfo = open_static_archive();
2168   FileMapInfo* dynamic_mapinfo = NULL;
2169 
2170   if (static_mapinfo != NULL) {
2171     dynamic_mapinfo = open_dynamic_archive();
2172 
2173     // First try to map at the requested address
2174     result = map_archives(static_mapinfo, dynamic_mapinfo, true);
2175     if (result == MAP_ARCHIVE_MMAP_FAILURE) {
2176       // Mapping has failed (probably due to ASLR). Let's map at an address chosen
2177       // by the OS.
2178       log_info(cds)("Try to map archive(s) at an alternative address");
2179       result = map_archives(static_mapinfo, dynamic_mapinfo, false);
2180     }
2181   }
2182 
2183   if (result == MAP_ARCHIVE_SUCCESS) {
2184     bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
2185     char* cds_base = static_mapinfo->mapped_base();
2186     char* cds_end =  dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
2187     set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
2188     _relocation_delta = static_mapinfo->relocation_delta();
2189     if (dynamic_mapped) {
2190       FileMapInfo::set_shared_path_table(dynamic_mapinfo);
2191     } else {
2192       FileMapInfo::set_shared_path_table(static_mapinfo);
2193     }
2194     _requested_base_address = static_mapinfo->requested_base_address();
2195   } else {
2196     set_shared_metaspace_range(NULL, NULL, NULL);
2197     UseSharedSpaces = false;
2198     FileMapInfo::fail_continue("Unable to map shared spaces");
2199     if (PrintSharedArchiveAndExit) {
2200       vm_exit_during_initialization("Unable to use shared archive.");
2201     }
2202   }
2203 
2204   if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
2205     delete static_mapinfo;
2206   }
2207   if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
2208     delete dynamic_mapinfo;
2209   }
2210 }
2211 
open_static_archive()2212 FileMapInfo* MetaspaceShared::open_static_archive() {
2213   FileMapInfo* mapinfo = new FileMapInfo(true);
2214   if (!mapinfo->initialize()) {
2215     delete(mapinfo);
2216     return NULL;
2217   }
2218   return mapinfo;
2219 }
2220 
open_dynamic_archive()2221 FileMapInfo* MetaspaceShared::open_dynamic_archive() {
2222   if (DynamicDumpSharedSpaces) {
2223     return NULL;
2224   }
2225   if (Arguments::GetSharedDynamicArchivePath() == NULL) {
2226     return NULL;
2227   }
2228 
2229   FileMapInfo* mapinfo = new FileMapInfo(false);
2230   if (!mapinfo->initialize()) {
2231     delete(mapinfo);
2232     return NULL;
2233   }
2234   return mapinfo;
2235 }
2236 
2237 // use_requested_addr:
2238 //  true  = map at FileMapHeader::_requested_base_address
2239 //  false = map at an alternative address picked by OS.
map_archives(FileMapInfo * static_mapinfo,FileMapInfo * dynamic_mapinfo,bool use_requested_addr)2240 MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
2241                                                bool use_requested_addr) {
2242   if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
2243     log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
2244     return MAP_ARCHIVE_MMAP_FAILURE;
2245   }
2246 
2247   PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2248       // For product build only -- this is for benchmarking the cost of doing relocation.
2249       // For debug builds, the check is done below, after reserving the space, for better test coverage
2250       // (see comment below).
2251       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2252       return MAP_ARCHIVE_MMAP_FAILURE;
2253     });
2254 
2255   if (ArchiveRelocationMode == 2 && !use_requested_addr) {
2256     log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
2257     return MAP_ARCHIVE_MMAP_FAILURE;
2258   };
2259 
2260   if (dynamic_mapinfo != NULL) {
2261     // Ensure that the OS won't be able to allocate new memory spaces between the two
2262     // archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
2263     assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
2264   }
2265 
2266   ReservedSpace archive_space_rs, class_space_rs;
2267   MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
2268   char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo, dynamic_mapinfo,
2269                                                                  use_requested_addr, archive_space_rs,
2270                                                                  class_space_rs);
2271   if (mapped_base_address == NULL) {
2272     result = MAP_ARCHIVE_MMAP_FAILURE;
2273     log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
2274   } else {
2275 
2276 #ifdef ASSERT
2277     // Some sanity checks after reserving address spaces for archives
2278     //  and class space.
2279     assert(archive_space_rs.is_reserved(), "Sanity");
2280     if (Metaspace::using_class_space()) {
2281       // Class space must closely follow the archive space. Both spaces
2282       //  must be aligned correctly.
2283       assert(class_space_rs.is_reserved(),
2284              "A class space should have been reserved");
2285       assert(class_space_rs.base() >= archive_space_rs.end(),
2286              "class space should follow the cds archive space");
2287       assert(is_aligned(archive_space_rs.base(),
2288                         MetaspaceShared::reserved_space_alignment()),
2289              "Archive space misaligned");
2290       assert(is_aligned(class_space_rs.base(),
2291                         Metaspace::reserve_alignment()),
2292              "class space misaligned");
2293     }
2294 #endif // ASSERT
2295 
2296     log_debug(cds)("Reserved archive_space_rs     [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2297                    p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
2298     log_debug(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
2299                    p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
2300 
2301     if (MetaspaceShared::use_windows_memory_mapping()) {
2302       // We have now reserved address space for the archives, and will map in
2303       //  the archive files into this space.
2304       //
2305       // Special handling for Windows: on Windows we cannot map a file view
2306       //  into an existing memory mapping. So, we unmap the address range we
2307       //  just reserved again, which will make it available for mapping the
2308       //  archives.
2309       // Reserving this range has not been for naught however since it makes
2310       //  us reasonably sure the address range is available.
2311       //
2312       // But still it may fail, since between unmapping the range and mapping
2313       //  in the archive someone else may grab the address space. Therefore
2314       //  there is a fallback in FileMap::map_region() where we just read in
2315       //  the archive files sequentially instead of mapping it in. We couple
2316       //  this with use_requested_addr, since we're going to patch all the
2317       //  pointers anyway so there's no benefit to mmap.
2318       if (use_requested_addr) {
2319         log_info(cds)("Windows mmap workaround: releasing archive space.");
2320         archive_space_rs.release();
2321       }
2322     }
2323     MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
2324     MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
2325                                      map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
2326 
2327     DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
2328       // This is for simulating mmap failures at the requested address. In
2329       //  debug builds, we do it here (after all archives have possibly been
2330       //  mapped), so we can thoroughly test the code for failure handling
2331       //  (releasing all allocated resource, etc).
2332       log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
2333       if (static_result == MAP_ARCHIVE_SUCCESS) {
2334         static_result = MAP_ARCHIVE_MMAP_FAILURE;
2335       }
2336       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2337         dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
2338       }
2339     });
2340 
2341     if (static_result == MAP_ARCHIVE_SUCCESS) {
2342       if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
2343         result = MAP_ARCHIVE_SUCCESS;
2344       } else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
2345         assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
2346         // No need to retry mapping the dynamic archive again, as it will never succeed
2347         // (bad file, etc) -- just keep the base archive.
2348         log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
2349                                   dynamic_mapinfo->full_path());
2350         result = MAP_ARCHIVE_SUCCESS;
2351         // TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
2352         // easy API to do that right now.
2353       } else {
2354         result = MAP_ARCHIVE_MMAP_FAILURE;
2355       }
2356     } else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
2357       result = MAP_ARCHIVE_OTHER_FAILURE;
2358     } else {
2359       result = MAP_ARCHIVE_MMAP_FAILURE;
2360     }
2361   }
2362 
2363   if (result == MAP_ARCHIVE_SUCCESS) {
2364     SharedBaseAddress = (size_t)mapped_base_address;
2365     LP64_ONLY({
2366         if (Metaspace::using_class_space()) {
2367           // Set up ccs in metaspace.
2368           Metaspace::initialize_class_space(class_space_rs);
2369 
2370           // Set up compressed Klass pointer encoding: the encoding range must
2371           //  cover both archive and class space.
2372           address cds_base = (address)static_mapinfo->mapped_base();
2373           address ccs_end = (address)class_space_rs.end();
2374           CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
2375 
2376           // map_heap_regions() compares the current narrow oop and klass encodings
2377           // with the archived ones, so it must be done after all encodings are determined.
2378           static_mapinfo->map_heap_regions();
2379         }
2380       });
2381     log_info(cds)("Using optimized module handling %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
2382   } else {
2383     unmap_archive(static_mapinfo);
2384     unmap_archive(dynamic_mapinfo);
2385     release_reserved_spaces(archive_space_rs, class_space_rs);
2386   }
2387 
2388   return result;
2389 }
2390 
2391 
2392 // This will reserve two address spaces suitable to house Klass structures, one
2393 //  for the cds archives (static archive and optionally dynamic archive) and
2394 //  optionally one move for ccs.
2395 //
2396 // Since both spaces must fall within the compressed class pointer encoding
2397 //  range, they are allocated close to each other.
2398 //
2399 // Space for archives will be reserved first, followed by a potential gap,
2400 //  followed by the space for ccs:
2401 //
2402 // +-- Base address             A        B                     End
2403 // |                            |        |                      |
2404 // v                            v        v                      v
2405 // +-------------+--------------+        +----------------------+
2406 // | static arc  | [dyn. arch]  | [gap]  | compr. class space   |
2407 // +-------------+--------------+        +----------------------+
2408 //
2409 // (The gap may result from different alignment requirements between metaspace
2410 //  and CDS)
2411 //
2412 // If UseCompressedClassPointers is disabled, only one address space will be
2413 //  reserved:
2414 //
2415 // +-- Base address             End
2416 // |                            |
2417 // v                            v
2418 // +-------------+--------------+
2419 // | static arc  | [dyn. arch]  |
2420 // +-------------+--------------+
2421 //
2422 // Base address: If use_archive_base_addr address is true, the Base address is
2423 //  determined by the address stored in the static archive. If
2424 //  use_archive_base_addr address is false, this base address is determined
2425 //  by the platform.
2426 //
2427 // If UseCompressedClassPointers=1, the range encompassing both spaces will be
2428 //  suitable to en/decode narrow Klass pointers: the base will be valid for
2429 //  encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
2430 //
2431 // Return:
2432 //
2433 // - On success:
2434 //    - archive_space_rs will be reserved and large enough to host static and
2435 //      if needed dynamic archive: [Base, A).
2436 //      archive_space_rs.base and size will be aligned to CDS reserve
2437 //      granularity.
2438 //    - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
2439 //      be reserved. Its start address will be aligned to metaspace reserve
2440 //      alignment, which may differ from CDS alignment. It will follow the cds
2441 //      archive space, close enough such that narrow class pointer encoding
2442 //      covers both spaces.
2443 //      If UseCompressedClassPointers=0, class_space_rs remains unreserved.
2444 // - On error: NULL is returned and the spaces remain unreserved.
reserve_address_space_for_archives(FileMapInfo * static_mapinfo,FileMapInfo * dynamic_mapinfo,bool use_archive_base_addr,ReservedSpace & archive_space_rs,ReservedSpace & class_space_rs)2445 char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
2446                                                           FileMapInfo* dynamic_mapinfo,
2447                                                           bool use_archive_base_addr,
2448                                                           ReservedSpace& archive_space_rs,
2449                                                           ReservedSpace& class_space_rs) {
2450 
2451   address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
2452   const size_t archive_space_alignment = MetaspaceShared::reserved_space_alignment();
2453 
2454   // Size and requested location of the archive_space_rs (for both static and dynamic archives)
2455   assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
2456   size_t archive_end_offset  = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
2457   size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
2458 
2459   // If a base address is given, it must have valid alignment and be suitable as encoding base.
2460   if (base_address != NULL) {
2461     assert(is_aligned(base_address, archive_space_alignment),
2462            "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2463     if (Metaspace::using_class_space()) {
2464       assert(CompressedKlassPointers::is_valid_base(base_address),
2465              "Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
2466     }
2467   }
2468 
2469   if (!Metaspace::using_class_space()) {
2470     // Get the simple case out of the way first:
2471     // no compressed class space, simple allocation.
2472     archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
2473                                      false /* bool large */, (char*)base_address);
2474     if (archive_space_rs.is_reserved()) {
2475       assert(base_address == NULL ||
2476              (address)archive_space_rs.base() == base_address, "Sanity");
2477       // Register archive space with NMT.
2478       MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2479       return archive_space_rs.base();
2480     }
2481     return NULL;
2482   }
2483 
2484 #ifdef _LP64
2485 
2486   // Complex case: two spaces adjacent to each other, both to be addressable
2487   //  with narrow class pointers.
2488   // We reserve the whole range spanning both spaces, then split that range up.
2489 
2490   const size_t class_space_alignment = Metaspace::reserve_alignment();
2491 
2492   // To simplify matters, lets assume that metaspace alignment will always be
2493   //  equal or a multiple of archive alignment.
2494   assert(is_power_of_2(class_space_alignment) &&
2495                        is_power_of_2(archive_space_alignment) &&
2496                        class_space_alignment >= archive_space_alignment,
2497                        "Sanity");
2498 
2499   const size_t class_space_size = CompressedClassSpaceSize;
2500   assert(CompressedClassSpaceSize > 0 &&
2501          is_aligned(CompressedClassSpaceSize, class_space_alignment),
2502          "CompressedClassSpaceSize malformed: "
2503          SIZE_FORMAT, CompressedClassSpaceSize);
2504 
2505   const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
2506                                            class_space_alignment) - base_address;
2507   const size_t gap_size = ccs_begin_offset - archive_space_size;
2508 
2509   const size_t total_range_size =
2510       align_up(archive_space_size + gap_size + class_space_size,
2511                os::vm_allocation_granularity());
2512 
2513   ReservedSpace total_rs;
2514   if (base_address != NULL) {
2515     // Reserve at the given archive base address, or not at all.
2516     total_rs = ReservedSpace(total_range_size, archive_space_alignment,
2517                              false /* bool large */, (char*) base_address);
2518   } else {
2519     // Reserve at any address, but leave it up to the platform to choose a good one.
2520     total_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
2521   }
2522 
2523   if (!total_rs.is_reserved()) {
2524     return NULL;
2525   }
2526 
2527   // Paranoid checks:
2528   assert(base_address == NULL || (address)total_rs.base() == base_address,
2529          "Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_rs.base()));
2530   assert(is_aligned(total_rs.base(), archive_space_alignment), "Sanity");
2531   assert(total_rs.size() == total_range_size, "Sanity");
2532   assert(CompressedKlassPointers::is_valid_base((address)total_rs.base()), "Sanity");
2533 
2534   // Now split up the space into ccs and cds archive. For simplicity, just leave
2535   //  the gap reserved at the end of the archive space.
2536   archive_space_rs = total_rs.first_part(ccs_begin_offset,
2537                                          (size_t)os::vm_allocation_granularity(),
2538                                          /*split=*/true);
2539   class_space_rs = total_rs.last_part(ccs_begin_offset);
2540 
2541   assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
2542   assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
2543   assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
2544   assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
2545 
2546   // NMT: fix up the space tags
2547   MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
2548   MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
2549 
2550   return archive_space_rs.base();
2551 
2552 #else
2553   ShouldNotReachHere();
2554   return NULL;
2555 #endif
2556 
2557 }
2558 
release_reserved_spaces(ReservedSpace & archive_space_rs,ReservedSpace & class_space_rs)2559 void MetaspaceShared::release_reserved_spaces(ReservedSpace& archive_space_rs,
2560                                               ReservedSpace& class_space_rs) {
2561   if (archive_space_rs.is_reserved()) {
2562     log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
2563     archive_space_rs.release();
2564   }
2565   if (class_space_rs.is_reserved()) {
2566     log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
2567     class_space_rs.release();
2568   }
2569 }
2570 
2571 static int archive_regions[]  = {MetaspaceShared::mc,
2572                                  MetaspaceShared::rw,
2573                                  MetaspaceShared::ro};
2574 static int archive_regions_count  = 3;
2575 
map_archive(FileMapInfo * mapinfo,char * mapped_base_address,ReservedSpace rs)2576 MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
2577   assert(UseSharedSpaces, "must be runtime");
2578   if (mapinfo == NULL) {
2579     return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
2580   }
2581 
2582   mapinfo->set_is_mapped(false);
2583 
2584   if (mapinfo->alignment() != (size_t)os::vm_allocation_granularity()) {
2585     log_error(cds)("Unable to map CDS archive -- os::vm_allocation_granularity() expected: " SIZE_FORMAT
2586                    " actual: %d", mapinfo->alignment(), os::vm_allocation_granularity());
2587     return MAP_ARCHIVE_OTHER_FAILURE;
2588   }
2589 
2590   MapArchiveResult result =
2591     mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
2592 
2593   if (result != MAP_ARCHIVE_SUCCESS) {
2594     unmap_archive(mapinfo);
2595     return result;
2596   }
2597 
2598   if (!mapinfo->validate_shared_path_table()) {
2599     unmap_archive(mapinfo);
2600     return MAP_ARCHIVE_OTHER_FAILURE;
2601   }
2602 
2603   mapinfo->set_is_mapped(true);
2604   return MAP_ARCHIVE_SUCCESS;
2605 }
2606 
unmap_archive(FileMapInfo * mapinfo)2607 void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
2608   assert(UseSharedSpaces, "must be runtime");
2609   if (mapinfo != NULL) {
2610     mapinfo->unmap_regions(archive_regions, archive_regions_count);
2611     mapinfo->set_is_mapped(false);
2612   }
2613 }
2614 
2615 // Read the miscellaneous data from the shared file, and
2616 // serialize it out to its various destinations.
2617 
initialize_shared_spaces()2618 void MetaspaceShared::initialize_shared_spaces() {
2619   FileMapInfo *static_mapinfo = FileMapInfo::current_info();
2620   _i2i_entry_code_buffers = static_mapinfo->i2i_entry_code_buffers();
2621   _i2i_entry_code_buffers_size = static_mapinfo->i2i_entry_code_buffers_size();
2622   char* buffer = static_mapinfo->cloned_vtables();
2623   clone_cpp_vtables((intptr_t*)buffer);
2624 
2625   // Verify various attributes of the archive, plus initialize the
2626   // shared string/symbol tables
2627   buffer = static_mapinfo->serialized_data();
2628   intptr_t* array = (intptr_t*)buffer;
2629   ReadClosure rc(&array);
2630   serialize(&rc);
2631 
2632   // Initialize the run-time symbol table.
2633   SymbolTable::create_table();
2634 
2635   static_mapinfo->patch_archived_heap_embedded_pointers();
2636 
2637   // Close the mapinfo file
2638   static_mapinfo->close();
2639 
2640   static_mapinfo->unmap_region(MetaspaceShared::bm);
2641 
2642   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2643   if (dynamic_mapinfo != NULL) {
2644     intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
2645     ReadClosure rc(&buffer);
2646     SymbolTable::serialize_shared_table_header(&rc, false);
2647     SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
2648     dynamic_mapinfo->close();
2649   }
2650 
2651   if (PrintSharedArchiveAndExit) {
2652     if (PrintSharedDictionary) {
2653       tty->print_cr("\nShared classes:\n");
2654       SystemDictionaryShared::print_on(tty);
2655     }
2656     if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
2657       tty->print_cr("archive is invalid");
2658       vm_exit(1);
2659     } else {
2660       tty->print_cr("archive is valid");
2661       vm_exit(0);
2662     }
2663   }
2664 }
2665 
2666 // JVM/TI RedefineClasses() support:
remap_shared_readonly_as_readwrite()2667 bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
2668   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2669 
2670   if (UseSharedSpaces) {
2671     // remap the shared readonly space to shared readwrite, private
2672     FileMapInfo* mapinfo = FileMapInfo::current_info();
2673     if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2674       return false;
2675     }
2676     if (FileMapInfo::dynamic_info() != NULL) {
2677       mapinfo = FileMapInfo::dynamic_info();
2678       if (!mapinfo->remap_shared_readonly_as_readwrite()) {
2679         return false;
2680       }
2681     }
2682     _remapped_readwrite = true;
2683   }
2684   return true;
2685 }
2686 
report_out_of_space(const char * name,size_t needed_bytes)2687 void MetaspaceShared::report_out_of_space(const char* name, size_t needed_bytes) {
2688   // This is highly unlikely to happen on 64-bits because we have reserved a 4GB space.
2689   // On 32-bit we reserve only 256MB so you could run out of space with 100,000 classes
2690   // or so.
2691   _mc_region.print_out_of_space_msg(name, needed_bytes);
2692   _rw_region.print_out_of_space_msg(name, needed_bytes);
2693   _ro_region.print_out_of_space_msg(name, needed_bytes);
2694 
2695   vm_exit_during_initialization(err_msg("Unable to allocate from '%s' region", name),
2696                                 "Please reduce the number of shared classes.");
2697 }
2698 
2699 // This is used to relocate the pointers so that the base archive can be mapped at
2700 // MetaspaceShared::requested_base_address() without runtime relocation.
final_delta()2701 intx MetaspaceShared::final_delta() {
2702   return intx(MetaspaceShared::requested_base_address())  // We want the base archive to be mapped to here at runtime
2703        - intx(SharedBaseAddress);                         // .. but the base archive is mapped at here at dump time
2704 }
2705 
print_on(outputStream * st)2706 void MetaspaceShared::print_on(outputStream* st) {
2707   if (UseSharedSpaces || DumpSharedSpaces) {
2708     st->print("CDS archive(s) mapped at: ");
2709     address base;
2710     address top;
2711     if (UseSharedSpaces) { // Runtime
2712       base = (address)MetaspaceObj::shared_metaspace_base();
2713       address static_top = (address)_shared_metaspace_static_top;
2714       top = (address)MetaspaceObj::shared_metaspace_top();
2715       st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
2716     } else if (DumpSharedSpaces) { // Dump Time
2717       base = (address)_shared_rs.base();
2718       top = (address)_shared_rs.end();
2719       st->print("[" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(top));
2720     }
2721     st->print("size " SIZE_FORMAT ", ", top - base);
2722     st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
2723   } else {
2724     st->print("CDS disabled.");
2725   }
2726   st->cr();
2727 }
2728 
2729 
2730 
2731 
2732 
2733