1 /*
2 * Copyright (c) 2018, 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 "classfile/classLoaderData.hpp"
27 #include "classfile/classLoaderDataShared.hpp"
28 #include "classfile/javaClasses.inline.hpp"
29 #include "classfile/moduleEntry.hpp"
30 #include "classfile/stringTable.hpp"
31 #include "classfile/symbolTable.hpp"
32 #include "classfile/systemDictionary.hpp"
33 #include "classfile/systemDictionaryShared.hpp"
34 #include "classfile/vmSymbols.hpp"
35 #include "gc/shared/gcLocker.hpp"
36 #include "gc/shared/gcVMOperations.hpp"
37 #include "logging/log.hpp"
38 #include "logging/logMessage.hpp"
39 #include "logging/logStream.hpp"
40 #include "memory/archiveBuilder.hpp"
41 #include "memory/archiveUtils.hpp"
42 #include "memory/filemap.hpp"
43 #include "memory/heapShared.inline.hpp"
44 #include "memory/iterator.inline.hpp"
45 #include "memory/metadataFactory.hpp"
46 #include "memory/metaspaceClosure.hpp"
47 #include "memory/metaspaceShared.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/compressedOops.inline.hpp"
51 #include "oops/fieldStreams.inline.hpp"
52 #include "oops/objArrayOop.hpp"
53 #include "oops/oop.inline.hpp"
54 #include "prims/jvmtiExport.hpp"
55 #include "runtime/fieldDescriptor.inline.hpp"
56 #include "runtime/globals_extension.hpp"
57 #include "runtime/init.hpp"
58 #include "runtime/javaCalls.hpp"
59 #include "runtime/safepointVerifiers.hpp"
60 #include "utilities/bitMap.inline.hpp"
61 #include "utilities/copy.hpp"
62 #if INCLUDE_G1GC
63 #include "gc/g1/g1CollectedHeap.hpp"
64 #endif
65
66 #if INCLUDE_CDS_JAVA_HEAP
67
68 bool HeapShared::_closed_archive_heap_region_mapped = false;
69 bool HeapShared::_open_archive_heap_region_mapped = false;
70 bool HeapShared::_archive_heap_region_fixed = false;
71 address HeapShared::_narrow_oop_base;
72 int HeapShared::_narrow_oop_shift;
73 DumpedInternedStrings *HeapShared::_dumped_interned_strings = NULL;
74
75 //
76 // If you add new entries to the following tables, you should know what you're doing!
77 //
78
79 // Entry fields for shareable subgraphs archived in the closed archive heap
80 // region. Warning: Objects in the subgraphs should not have reference fields
81 // assigned at runtime.
82 static ArchivableStaticFieldInfo closed_archive_subgraph_entry_fields[] = {
83 {"java/lang/Integer$IntegerCache", "archivedCache"},
84 {"java/lang/Long$LongCache", "archivedCache"},
85 {"java/lang/Byte$ByteCache", "archivedCache"},
86 {"java/lang/Short$ShortCache", "archivedCache"},
87 {"java/lang/Character$CharacterCache", "archivedCache"},
88 {"java/util/jar/Attributes$Name", "KNOWN_NAMES"},
89 {"sun/util/locale/BaseLocale", "constantBaseLocales"},
90 };
91 // Entry fields for subgraphs archived in the open archive heap region.
92 static ArchivableStaticFieldInfo open_archive_subgraph_entry_fields[] = {
93 {"jdk/internal/module/ArchivedModuleGraph", "archivedModuleGraph"},
94 {"java/util/ImmutableCollections", "archivedObjects"},
95 {"java/lang/ModuleLayer", "EMPTY_LAYER"},
96 {"java/lang/module/Configuration", "EMPTY_CONFIGURATION"},
97 {"jdk/internal/math/FDBigInteger", "archivedCaches"},
98 };
99
100 // Entry fields for subgraphs archived in the open archive heap region (full module graph).
101 static ArchivableStaticFieldInfo fmg_open_archive_subgraph_entry_fields[] = {
102 {"jdk/internal/loader/ArchivedClassLoaders", "archivedClassLoaders"},
103 {"jdk/internal/module/ArchivedBootLayer", "archivedBootLayer"},
104 {"java/lang/Module$ArchivedData", "archivedData"},
105 };
106
107 const static int num_closed_archive_subgraph_entry_fields =
108 sizeof(closed_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
109 const static int num_open_archive_subgraph_entry_fields =
110 sizeof(open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
111 const static int num_fmg_open_archive_subgraph_entry_fields =
112 sizeof(fmg_open_archive_subgraph_entry_fields) / sizeof(ArchivableStaticFieldInfo);
113
114 GrowableArrayCHeap<oop, mtClassShared>* HeapShared::_pending_roots = NULL;
115 narrowOop HeapShared::_roots_narrow;
116 OopHandle HeapShared::_roots;
117
118 ////////////////////////////////////////////////////////////////
119 //
120 // Java heap object archiving support
121 //
122 ////////////////////////////////////////////////////////////////
fixup_mapped_heap_regions()123 void HeapShared::fixup_mapped_heap_regions() {
124 FileMapInfo *mapinfo = FileMapInfo::current_info();
125 mapinfo->fixup_mapped_heap_regions();
126 set_archive_heap_region_fixed();
127 if (is_mapped()) {
128 _roots = OopHandle(Universe::vm_global(), decode_from_archive(_roots_narrow));
129 if (!MetaspaceShared::use_full_module_graph()) {
130 // Need to remove all the archived java.lang.Module objects from HeapShared::roots().
131 ClassLoaderDataShared::clear_archived_oops();
132 }
133 }
134 SystemDictionaryShared::update_archived_mirror_native_pointers();
135 }
136
oop_hash(oop const & p)137 unsigned HeapShared::oop_hash(oop const& p) {
138 assert(!p->mark().has_bias_pattern(),
139 "this object should never have been locked"); // so identity_hash won't safepoin
140 unsigned hash = (unsigned)p->identity_hash();
141 return hash;
142 }
143
reset_states(oop obj,TRAPS)144 static void reset_states(oop obj, TRAPS) {
145 Handle h_obj(THREAD, obj);
146 InstanceKlass* klass = InstanceKlass::cast(obj->klass());
147 TempNewSymbol method_name = SymbolTable::new_symbol("resetArchivedStates");
148 Symbol* method_sig = vmSymbols::void_method_signature();
149
150 while (klass != NULL) {
151 Method* method = klass->find_method(method_name, method_sig);
152 if (method != NULL) {
153 assert(method->is_private(), "must be");
154 if (log_is_enabled(Debug, cds)) {
155 ResourceMark rm(THREAD);
156 log_debug(cds)(" calling %s", method->name_and_sig_as_C_string());
157 }
158 JavaValue result(T_VOID);
159 JavaCalls::call_special(&result, h_obj, klass,
160 method_name, method_sig, CHECK);
161 }
162 klass = klass->java_super();
163 }
164 }
165
reset_archived_object_states(TRAPS)166 void HeapShared::reset_archived_object_states(TRAPS) {
167 assert(DumpSharedSpaces, "dump-time only");
168 log_debug(cds)("Resetting platform loader");
169 reset_states(SystemDictionary::java_platform_loader(), THREAD);
170 log_debug(cds)("Resetting system loader");
171 reset_states(SystemDictionary::java_system_loader(), THREAD);
172 }
173
174 HeapShared::ArchivedObjectCache* HeapShared::_archived_object_cache = NULL;
find_archived_heap_object(oop obj)175 oop HeapShared::find_archived_heap_object(oop obj) {
176 assert(DumpSharedSpaces, "dump-time only");
177 ArchivedObjectCache* cache = archived_object_cache();
178 oop* p = cache->get(obj);
179 if (p != NULL) {
180 return *p;
181 } else {
182 return NULL;
183 }
184 }
185
append_root(oop obj)186 int HeapShared::append_root(oop obj) {
187 assert(DumpSharedSpaces, "dump-time only");
188
189 // No GC should happen since we aren't scanning _pending_roots.
190 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
191
192 if (_pending_roots == NULL) {
193 _pending_roots = new GrowableArrayCHeap<oop, mtClassShared>(500);
194 }
195
196 return _pending_roots->append(obj);
197 }
198
roots()199 objArrayOop HeapShared::roots() {
200 if (DumpSharedSpaces) {
201 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
202 if (!is_heap_object_archiving_allowed()) {
203 return NULL;
204 }
205 } else {
206 assert(UseSharedSpaces, "must be");
207 }
208
209 objArrayOop roots = (objArrayOop)_roots.resolve();
210 assert(roots != NULL, "should have been initialized");
211 return roots;
212 }
213
set_roots(narrowOop roots)214 void HeapShared::set_roots(narrowOop roots) {
215 assert(UseSharedSpaces, "runtime only");
216 assert(open_archive_heap_region_mapped(), "must be");
217 _roots_narrow = roots;
218 }
219
220 // Returns an objArray that contains all the roots of the archived objects
get_root(int index,bool clear)221 oop HeapShared::get_root(int index, bool clear) {
222 assert(index >= 0, "sanity");
223 if (DumpSharedSpaces) {
224 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
225 assert(_pending_roots != NULL, "sanity");
226 return _pending_roots->at(index);
227 } else {
228 assert(UseSharedSpaces, "must be");
229 assert(!_roots.is_empty(), "must have loaded shared heap");
230 oop result = roots()->obj_at(index);
231 if (clear) {
232 clear_root(index);
233 }
234 return result;
235 }
236 }
237
clear_root(int index)238 void HeapShared::clear_root(int index) {
239 assert(index >= 0, "sanity");
240 assert(UseSharedSpaces, "must be");
241 if (open_archive_heap_region_mapped()) {
242 if (log_is_enabled(Debug, cds, heap)) {
243 oop old = roots()->obj_at(index);
244 log_debug(cds, heap)("Clearing root %d: was " PTR_FORMAT, index, p2i(old));
245 }
246 roots()->obj_at_put(index, NULL);
247 }
248 }
249
archive_heap_object(oop obj,Thread * THREAD)250 oop HeapShared::archive_heap_object(oop obj, Thread* THREAD) {
251 assert(DumpSharedSpaces, "dump-time only");
252
253 oop ao = find_archived_heap_object(obj);
254 if (ao != NULL) {
255 // already archived
256 return ao;
257 }
258
259 int len = obj->size();
260 if (G1CollectedHeap::heap()->is_archive_alloc_too_large(len)) {
261 log_debug(cds, heap)("Cannot archive, object (" PTR_FORMAT ") is too large: " SIZE_FORMAT,
262 p2i(obj), (size_t)obj->size());
263 return NULL;
264 }
265
266 oop archived_oop = (oop)G1CollectedHeap::heap()->archive_mem_allocate(len);
267 if (archived_oop != NULL) {
268 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), cast_from_oop<HeapWord*>(archived_oop), len);
269 MetaspaceShared::relocate_klass_ptr(archived_oop);
270 // Reinitialize markword to remove age/marking/locking/etc.
271 //
272 // We need to retain the identity_hash, because it may have been used by some hashtables
273 // in the shared heap. This also has the side effect of pre-initializing the
274 // identity_hash for all shared objects, so they are less likely to be written
275 // into during run time, increasing the potential of memory sharing.
276 int hash_original = obj->identity_hash();
277 archived_oop->set_mark(markWord::prototype().copy_set_hash(hash_original));
278 assert(archived_oop->mark().is_unlocked(), "sanity");
279
280 DEBUG_ONLY(int hash_archived = archived_oop->identity_hash());
281 assert(hash_original == hash_archived, "Different hash codes: original %x, archived %x", hash_original, hash_archived);
282
283 ArchivedObjectCache* cache = archived_object_cache();
284 cache->put(obj, archived_oop);
285 if (log_is_enabled(Debug, cds, heap)) {
286 ResourceMark rm;
287 log_debug(cds, heap)("Archived heap object " PTR_FORMAT " ==> " PTR_FORMAT " : %s",
288 p2i(obj), p2i(archived_oop), obj->klass()->external_name());
289 }
290 } else {
291 log_error(cds, heap)(
292 "Cannot allocate space for object " PTR_FORMAT " in archived heap region",
293 p2i(obj));
294 vm_direct_exit(-1,
295 err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
296 SIZE_FORMAT "M", MaxHeapSize/M));
297 }
298 return archived_oop;
299 }
300
archive_klass_objects(Thread * THREAD)301 void HeapShared::archive_klass_objects(Thread* THREAD) {
302 GrowableArray<Klass*>* klasses = MetaspaceShared::collected_klasses();
303 assert(klasses != NULL, "sanity");
304 for (int i = 0; i < klasses->length(); i++) {
305 Klass* k = klasses->at(i);
306
307 // archive mirror object
308 java_lang_Class::archive_mirror(k, CHECK);
309
310 // archive the resolved_referenes array
311 if (k->is_instance_klass()) {
312 InstanceKlass* ik = InstanceKlass::cast(k);
313 ik->constants()->archive_resolved_references(THREAD);
314 }
315 }
316 }
317
run_full_gc_in_vm_thread()318 void HeapShared::run_full_gc_in_vm_thread() {
319 if (is_heap_object_archiving_allowed()) {
320 // Avoid fragmentation while archiving heap objects.
321 // We do this inside a safepoint, so that no further allocation can happen after GC
322 // has finished.
323 if (GCLocker::is_active()) {
324 // Just checking for safety ...
325 // This should not happen during -Xshare:dump. If you see this, probably the Java core lib
326 // has been modified such that JNI code is executed in some clean up threads after
327 // we have finished class loading.
328 log_warning(cds)("GC locker is held, unable to start extra compacting GC. This may produce suboptimal results.");
329 } else {
330 log_info(cds)("Run GC ...");
331 Universe::heap()->collect_as_vm_thread(GCCause::_archive_time_gc);
332 log_info(cds)("Run GC done");
333 }
334 }
335 }
336
archive_java_heap_objects(GrowableArray<MemRegion> * closed,GrowableArray<MemRegion> * open)337 void HeapShared::archive_java_heap_objects(GrowableArray<MemRegion>* closed,
338 GrowableArray<MemRegion>* open) {
339
340 G1HeapVerifier::verify_ready_for_archiving();
341
342 {
343 NoSafepointVerifier nsv;
344
345 // Cache for recording where the archived objects are copied to
346 create_archived_object_cache();
347
348 log_info(cds)("Dumping objects to closed archive heap region ...");
349 copy_closed_archive_heap_objects(closed);
350
351 log_info(cds)("Dumping objects to open archive heap region ...");
352 copy_open_archive_heap_objects(open);
353
354 destroy_archived_object_cache();
355 }
356
357 G1HeapVerifier::verify_archive_regions();
358 }
359
copy_closed_archive_heap_objects(GrowableArray<MemRegion> * closed_archive)360 void HeapShared::copy_closed_archive_heap_objects(
361 GrowableArray<MemRegion> * closed_archive) {
362 assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
363
364 Thread* THREAD = Thread::current();
365 G1CollectedHeap::heap()->begin_archive_alloc_range();
366
367 // Archive interned string objects
368 StringTable::write_to_archive(_dumped_interned_strings);
369
370 archive_object_subgraphs(closed_archive_subgraph_entry_fields,
371 num_closed_archive_subgraph_entry_fields,
372 true /* is_closed_archive */,
373 false /* is_full_module_graph */,
374 THREAD);
375
376 G1CollectedHeap::heap()->end_archive_alloc_range(closed_archive,
377 os::vm_allocation_granularity());
378 }
379
copy_open_archive_heap_objects(GrowableArray<MemRegion> * open_archive)380 void HeapShared::copy_open_archive_heap_objects(
381 GrowableArray<MemRegion> * open_archive) {
382 assert(is_heap_object_archiving_allowed(), "Cannot archive java heap objects");
383
384 Thread* THREAD = Thread::current();
385 G1CollectedHeap::heap()->begin_archive_alloc_range(true /* open */);
386
387 java_lang_Class::archive_basic_type_mirrors(THREAD);
388
389 archive_klass_objects(THREAD);
390
391 archive_object_subgraphs(open_archive_subgraph_entry_fields,
392 num_open_archive_subgraph_entry_fields,
393 false /* is_closed_archive */,
394 false /* is_full_module_graph */,
395 THREAD);
396 if (MetaspaceShared::use_full_module_graph()) {
397 archive_object_subgraphs(fmg_open_archive_subgraph_entry_fields,
398 num_fmg_open_archive_subgraph_entry_fields,
399 false /* is_closed_archive */,
400 true /* is_full_module_graph */,
401 THREAD);
402 ClassLoaderDataShared::init_archived_oops();
403 }
404
405 copy_roots();
406
407 G1CollectedHeap::heap()->end_archive_alloc_range(open_archive,
408 os::vm_allocation_granularity());
409 }
410
411 // Copy _pending_archive_roots into an objArray
copy_roots()412 void HeapShared::copy_roots() {
413 int length = _pending_roots != NULL ? _pending_roots->length() : 0;
414 int size = objArrayOopDesc::object_size(length);
415 Klass* k = Universe::objectArrayKlassObj(); // already relocated to point to archived klass
416 HeapWord* mem = G1CollectedHeap::heap()->archive_mem_allocate(size);
417
418 memset(mem, 0, size * BytesPerWord);
419 {
420 // This is copied from MemAllocator::finish
421 if (UseBiasedLocking) {
422 oopDesc::set_mark(mem, k->prototype_header());
423 } else {
424 oopDesc::set_mark(mem, markWord::prototype());
425 }
426 oopDesc::release_set_klass(mem, k);
427 }
428 {
429 // This is copied from ObjArrayAllocator::initialize
430 arrayOopDesc::set_length(mem, length);
431 }
432
433 _roots = OopHandle(Universe::vm_global(), (oop)mem);
434 for (int i = 0; i < length; i++) {
435 roots()->obj_at_put(i, _pending_roots->at(i));
436 }
437 log_info(cds)("archived obj roots[%d] = %d words, klass = %p, obj = %p", length, size, k, mem);
438 }
439
init_narrow_oop_decoding(address base,int shift)440 void HeapShared::init_narrow_oop_decoding(address base, int shift) {
441 _narrow_oop_base = base;
442 _narrow_oop_shift = shift;
443 }
444
445 //
446 // Subgraph archiving support
447 //
448 HeapShared::DumpTimeKlassSubGraphInfoTable* HeapShared::_dump_time_subgraph_info_table = NULL;
449 HeapShared::RunTimeKlassSubGraphInfoTable HeapShared::_run_time_subgraph_info_table;
450
451 // Get the subgraph_info for Klass k. A new subgraph_info is created if
452 // there is no existing one for k. The subgraph_info records the relocated
453 // Klass* of the original k.
init_subgraph_info(Klass * k,bool is_full_module_graph)454 KlassSubGraphInfo* HeapShared::init_subgraph_info(Klass* k, bool is_full_module_graph) {
455 assert(DumpSharedSpaces, "dump time only");
456 bool created;
457 Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
458 KlassSubGraphInfo* info =
459 _dump_time_subgraph_info_table->put_if_absent(relocated_k, KlassSubGraphInfo(relocated_k, is_full_module_graph),
460 &created);
461 assert(created, "must not initialize twice");
462 return info;
463 }
464
get_subgraph_info(Klass * k)465 KlassSubGraphInfo* HeapShared::get_subgraph_info(Klass* k) {
466 assert(DumpSharedSpaces, "dump time only");
467 Klass* relocated_k = MetaspaceShared::get_relocated_klass(k);
468 KlassSubGraphInfo* info = _dump_time_subgraph_info_table->get(relocated_k);
469 assert(info != NULL, "must have been initialized");
470 return info;
471 }
472
473 // Add an entry field to the current KlassSubGraphInfo.
add_subgraph_entry_field(int static_field_offset,oop v,bool is_closed_archive)474 void KlassSubGraphInfo::add_subgraph_entry_field(
475 int static_field_offset, oop v, bool is_closed_archive) {
476 assert(DumpSharedSpaces, "dump time only");
477 if (_subgraph_entry_fields == NULL) {
478 _subgraph_entry_fields =
479 new(ResourceObj::C_HEAP, mtClass) GrowableArray<int>(10, mtClass);
480 }
481 _subgraph_entry_fields->append(static_field_offset);
482 _subgraph_entry_fields->append(HeapShared::append_root(v));
483 }
484
485 // Add the Klass* for an object in the current KlassSubGraphInfo's subgraphs.
486 // Only objects of boot classes can be included in sub-graph.
add_subgraph_object_klass(Klass * orig_k,Klass * relocated_k)487 void KlassSubGraphInfo::add_subgraph_object_klass(Klass* orig_k, Klass* relocated_k) {
488 assert(DumpSharedSpaces, "dump time only");
489 assert(relocated_k == MetaspaceShared::get_relocated_klass(orig_k),
490 "must be the relocated Klass in the shared space");
491
492 if (_subgraph_object_klasses == NULL) {
493 _subgraph_object_klasses =
494 new(ResourceObj::C_HEAP, mtClass) GrowableArray<Klass*>(50, mtClass);
495 }
496
497 assert(ArchiveBuilder::singleton()->is_in_buffer_space(relocated_k), "must be a shared class");
498
499 if (_k == relocated_k) {
500 // Don't add the Klass containing the sub-graph to it's own klass
501 // initialization list.
502 return;
503 }
504
505 if (relocated_k->is_instance_klass()) {
506 assert(InstanceKlass::cast(relocated_k)->is_shared_boot_class(),
507 "must be boot class");
508 // SystemDictionary::xxx_klass() are not updated, need to check
509 // the original Klass*
510 if (orig_k == SystemDictionary::String_klass() ||
511 orig_k == SystemDictionary::Object_klass()) {
512 // Initialized early during VM initialization. No need to be added
513 // to the sub-graph object class list.
514 return;
515 }
516 } else if (relocated_k->is_objArray_klass()) {
517 Klass* abk = ObjArrayKlass::cast(relocated_k)->bottom_klass();
518 if (abk->is_instance_klass()) {
519 assert(InstanceKlass::cast(abk)->is_shared_boot_class(),
520 "must be boot class");
521 }
522 if (relocated_k == Universe::objectArrayKlassObj()) {
523 // Initialized early during Universe::genesis. No need to be added
524 // to the list.
525 return;
526 }
527 } else {
528 assert(relocated_k->is_typeArray_klass(), "must be");
529 // Primitive type arrays are created early during Universe::genesis.
530 return;
531 }
532
533 if (log_is_enabled(Debug, cds, heap)) {
534 if (!_subgraph_object_klasses->contains(relocated_k)) {
535 ResourceMark rm;
536 log_debug(cds, heap)("Adding klass %s", orig_k->external_name());
537 }
538 }
539
540 _subgraph_object_klasses->append_if_missing(relocated_k);
541 _has_non_early_klasses |= is_non_early_klass(orig_k);
542 }
543
is_non_early_klass(Klass * k)544 bool KlassSubGraphInfo::is_non_early_klass(Klass* k) {
545 if (k->is_objArray_klass()) {
546 k = ObjArrayKlass::cast(k)->bottom_klass();
547 }
548 if (k->is_instance_klass()) {
549 if (!SystemDictionaryShared::is_early_klass(InstanceKlass::cast(k))) {
550 ResourceMark rm;
551 log_info(cds, heap)("non-early: %s", k->external_name());
552 return true;
553 } else {
554 return false;
555 }
556 } else {
557 return false;
558 }
559 }
560
561 // Initialize an archived subgraph_info_record from the given KlassSubGraphInfo.
init(KlassSubGraphInfo * info)562 void ArchivedKlassSubGraphInfoRecord::init(KlassSubGraphInfo* info) {
563 _k = info->klass();
564 _entry_field_records = NULL;
565 _subgraph_object_klasses = NULL;
566 _is_full_module_graph = info->is_full_module_graph();
567 _has_non_early_klasses = info->has_non_early_klasses();
568
569 if (_has_non_early_klasses) {
570 ResourceMark rm;
571 log_info(cds, heap)(
572 "Subgraph of klass %s has non-early klasses and cannot be used when JVMTI ClassFileLoadHook is enabled",
573 _k->external_name());
574 }
575
576 // populate the entry fields
577 GrowableArray<int>* entry_fields = info->subgraph_entry_fields();
578 if (entry_fields != NULL) {
579 int num_entry_fields = entry_fields->length();
580 assert(num_entry_fields % 2 == 0, "sanity");
581 _entry_field_records =
582 MetaspaceShared::new_ro_array<int>(num_entry_fields);
583 for (int i = 0 ; i < num_entry_fields; i++) {
584 _entry_field_records->at_put(i, entry_fields->at(i));
585 }
586 }
587
588 // the Klasses of the objects in the sub-graphs
589 GrowableArray<Klass*>* subgraph_object_klasses = info->subgraph_object_klasses();
590 if (subgraph_object_klasses != NULL) {
591 int num_subgraphs_klasses = subgraph_object_klasses->length();
592 _subgraph_object_klasses =
593 MetaspaceShared::new_ro_array<Klass*>(num_subgraphs_klasses);
594 for (int i = 0; i < num_subgraphs_klasses; i++) {
595 Klass* subgraph_k = subgraph_object_klasses->at(i);
596 if (log_is_enabled(Info, cds, heap)) {
597 ResourceMark rm;
598 log_info(cds, heap)(
599 "Archived object klass %s (%2d) => %s",
600 _k->external_name(), i, subgraph_k->external_name());
601 }
602 _subgraph_object_klasses->at_put(i, subgraph_k);
603 ArchivePtrMarker::mark_pointer(_subgraph_object_klasses->adr_at(i));
604 }
605 }
606
607 ArchivePtrMarker::mark_pointer(&_k);
608 ArchivePtrMarker::mark_pointer(&_entry_field_records);
609 ArchivePtrMarker::mark_pointer(&_subgraph_object_klasses);
610 }
611
612 struct CopyKlassSubGraphInfoToArchive : StackObj {
613 CompactHashtableWriter* _writer;
CopyKlassSubGraphInfoToArchiveCopyKlassSubGraphInfoToArchive614 CopyKlassSubGraphInfoToArchive(CompactHashtableWriter* writer) : _writer(writer) {}
615
do_entryCopyKlassSubGraphInfoToArchive616 bool do_entry(Klass* klass, KlassSubGraphInfo& info) {
617 if (info.subgraph_object_klasses() != NULL || info.subgraph_entry_fields() != NULL) {
618 ArchivedKlassSubGraphInfoRecord* record =
619 (ArchivedKlassSubGraphInfoRecord*)MetaspaceShared::read_only_space_alloc(sizeof(ArchivedKlassSubGraphInfoRecord));
620 record->init(&info);
621
622 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(klass);
623 u4 delta = MetaspaceShared::object_delta_u4(record);
624 _writer->add(hash, delta);
625 }
626 return true; // keep on iterating
627 }
628 };
629
630 // Build the records of archived subgraph infos, which include:
631 // - Entry points to all subgraphs from the containing class mirror. The entry
632 // points are static fields in the mirror. For each entry point, the field
633 // offset, value and is_closed_archive flag are recorded in the sub-graph
634 // info. The value is stored back to the corresponding field at runtime.
635 // - A list of klasses that need to be loaded/initialized before archived
636 // java object sub-graph can be accessed at runtime.
write_subgraph_info_table()637 void HeapShared::write_subgraph_info_table() {
638 // Allocate the contents of the hashtable(s) inside the RO region of the CDS archive.
639 DumpTimeKlassSubGraphInfoTable* d_table = _dump_time_subgraph_info_table;
640 CompactHashtableStats stats;
641
642 _run_time_subgraph_info_table.reset();
643
644 CompactHashtableWriter writer(d_table->_count, &stats);
645 CopyKlassSubGraphInfoToArchive copy(&writer);
646 d_table->iterate(©);
647
648 writer.dump(&_run_time_subgraph_info_table, "subgraphs");
649 }
650
serialize_subgraph_info_table_header(SerializeClosure * soc)651 void HeapShared::serialize_subgraph_info_table_header(SerializeClosure* soc) {
652 _run_time_subgraph_info_table.serialize_header(soc);
653 }
654
verify_the_heap(Klass * k,const char * which)655 static void verify_the_heap(Klass* k, const char* which) {
656 if (VerifyArchivedFields) {
657 ResourceMark rm;
658 log_info(cds, heap)("Verify heap %s initializing static field(s) in %s",
659 which, k->external_name());
660
661 VM_Verify verify_op;
662 VMThread::execute(&verify_op);
663
664 if (!FLAG_IS_DEFAULT(VerifyArchivedFields)) {
665 // If VerifyArchivedFields has a non-default value (e.g., specified on the command-line), do
666 // more expensive checks.
667 if (is_init_completed()) {
668 FlagSetting fs1(VerifyBeforeGC, true);
669 FlagSetting fs2(VerifyDuringGC, true);
670 FlagSetting fs3(VerifyAfterGC, true);
671 Universe::heap()->collect(GCCause::_java_lang_system_gc);
672 }
673 }
674 }
675 }
676
677 // Before GC can execute, we must ensure that all oops reachable from HeapShared::roots()
678 // have a valid klass. I.e., oopDesc::klass() must have already been resolved.
679 //
680 // Note: if a ArchivedKlassSubGraphInfoRecord contains non-early classes, and JVMTI
681 // ClassFileLoadHook is enabled, it's possible for this class to be dynamically replaced. In
682 // this case, we will not load the ArchivedKlassSubGraphInfoRecord and will clear its roots.
resolve_classes(TRAPS)683 void HeapShared::resolve_classes(TRAPS) {
684 if (!is_mapped()) {
685 return; // nothing to do
686 }
687 resolve_classes_for_subgraphs(closed_archive_subgraph_entry_fields,
688 num_closed_archive_subgraph_entry_fields,
689 CHECK);
690 resolve_classes_for_subgraphs(open_archive_subgraph_entry_fields,
691 num_open_archive_subgraph_entry_fields,
692 CHECK);
693 resolve_classes_for_subgraphs(fmg_open_archive_subgraph_entry_fields,
694 num_fmg_open_archive_subgraph_entry_fields,
695 CHECK);
696 }
697
resolve_classes_for_subgraphs(ArchivableStaticFieldInfo fields[],int num,TRAPS)698 void HeapShared::resolve_classes_for_subgraphs(ArchivableStaticFieldInfo fields[],
699 int num, TRAPS) {
700 for (int i = 0; i < num; i++) {
701 ArchivableStaticFieldInfo* info = &fields[i];
702 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
703 InstanceKlass* k = SystemDictionaryShared::find_builtin_class(klass_name);
704 assert(k != NULL && k->is_shared_boot_class(), "sanity");
705 resolve_classes_for_subgraph_of(k, CHECK);
706 }
707 }
708
resolve_classes_for_subgraph_of(Klass * k,TRAPS)709 void HeapShared::resolve_classes_for_subgraph_of(Klass* k, TRAPS) {
710 const ArchivedKlassSubGraphInfoRecord* record = resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/false, THREAD);
711 if (HAS_PENDING_EXCEPTION) {
712 CLEAR_PENDING_EXCEPTION;
713 }
714 if (record == NULL) {
715 clear_archived_roots_of(k);
716 }
717 }
718
initialize_from_archived_subgraph(Klass * k,TRAPS)719 void HeapShared::initialize_from_archived_subgraph(Klass* k, TRAPS) {
720 if (!is_mapped()) {
721 return; // nothing to do
722 }
723
724 const ArchivedKlassSubGraphInfoRecord* record =
725 resolve_or_init_classes_for_subgraph_of(k, /*do_init=*/true, THREAD);
726
727 if (HAS_PENDING_EXCEPTION) {
728 CLEAR_PENDING_EXCEPTION;
729 // None of the field value will be set if there was an exception when initializing the classes.
730 // The java code will not see any of the archived objects in the
731 // subgraphs referenced from k in this case.
732 return;
733 }
734
735 if (record != NULL) {
736 init_archived_fields_for(k, record, THREAD);
737 }
738 }
739
740 const ArchivedKlassSubGraphInfoRecord*
resolve_or_init_classes_for_subgraph_of(Klass * k,bool do_init,TRAPS)741 HeapShared::resolve_or_init_classes_for_subgraph_of(Klass* k, bool do_init, TRAPS) {
742 assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces");
743
744 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(k);
745 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
746
747 // Initialize from archived data. Currently this is done only
748 // during VM initialization time. No lock is needed.
749 if (record != NULL) {
750 if (record->is_full_module_graph() && !MetaspaceShared::use_full_module_graph()) {
751 if (log_is_enabled(Info, cds, heap)) {
752 ResourceMark rm;
753 log_info(cds, heap)("subgraph %s cannot be used because full module graph is disabled",
754 k->external_name());
755 }
756 return NULL;
757 }
758
759 if (record->has_non_early_klasses() && JvmtiExport::should_post_class_file_load_hook()) {
760 if (log_is_enabled(Info, cds, heap)) {
761 ResourceMark rm;
762 log_info(cds, heap)("subgraph %s cannot be used because JVMTI ClassFileLoadHook is enabled",
763 k->external_name());
764 }
765 return NULL;
766 }
767
768 resolve_or_init(k, do_init, CHECK_NULL);
769
770 // Load/link/initialize the klasses of the objects in the subgraph.
771 // NULL class loader is used.
772 Array<Klass*>* klasses = record->subgraph_object_klasses();
773 if (klasses != NULL) {
774 for (int i = 0; i < klasses->length(); i++) {
775 resolve_or_init(klasses->at(i), do_init, CHECK_NULL);
776 }
777 }
778 }
779
780 return record;
781 }
782
resolve_or_init(Klass * k,bool do_init,TRAPS)783 void HeapShared::resolve_or_init(Klass* k, bool do_init, TRAPS) {
784 if (!do_init) {
785 if (k->class_loader_data() == NULL) {
786 Klass* resolved_k = SystemDictionary::resolve_or_null(k->name(), CHECK);
787 assert(resolved_k == k, "classes used by archived heap must not be replaced by JVMTI ClassFileLoadHook");
788 }
789 } else {
790 assert(k->class_loader_data() != NULL, "must have been resolved by HeapShared::resolve_classes");
791 if (k->is_instance_klass()) {
792 InstanceKlass* ik = InstanceKlass::cast(k);
793 ik->initialize(CHECK);
794 } else if (k->is_objArray_klass()) {
795 ObjArrayKlass* oak = ObjArrayKlass::cast(k);
796 oak->initialize(CHECK);
797 }
798 }
799 }
800
init_archived_fields_for(Klass * k,const ArchivedKlassSubGraphInfoRecord * record,TRAPS)801 void HeapShared::init_archived_fields_for(Klass* k, const ArchivedKlassSubGraphInfoRecord* record, TRAPS) {
802 verify_the_heap(k, "before");
803
804 // Load the subgraph entry fields from the record and store them back to
805 // the corresponding fields within the mirror.
806 oop m = k->java_mirror();
807 Array<int>* entry_field_records = record->entry_field_records();
808 if (entry_field_records != NULL) {
809 int efr_len = entry_field_records->length();
810 assert(efr_len % 2 == 0, "sanity");
811 for (int i = 0; i < efr_len; i += 2) {
812 int field_offset = entry_field_records->at(i);
813 int root_index = entry_field_records->at(i+1);
814 oop v = get_root(root_index, /*clear=*/true);
815 m->obj_field_put(field_offset, v);
816 log_debug(cds, heap)(" " PTR_FORMAT " init field @ %2d = " PTR_FORMAT, p2i(k), field_offset, p2i(v));
817 }
818
819 // Done. Java code can see the archived sub-graphs referenced from k's
820 // mirror after this point.
821 if (log_is_enabled(Info, cds, heap)) {
822 ResourceMark rm;
823 log_info(cds, heap)("initialize_from_archived_subgraph %s " PTR_FORMAT "%s",
824 k->external_name(), p2i(k), JvmtiExport::is_early_phase() ? " (early)" : "");
825 }
826 }
827
828 verify_the_heap(k, "after ");
829 }
830
clear_archived_roots_of(Klass * k)831 void HeapShared::clear_archived_roots_of(Klass* k) {
832 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(k);
833 const ArchivedKlassSubGraphInfoRecord* record = _run_time_subgraph_info_table.lookup(k, hash, 0);
834 if (record != NULL) {
835 Array<int>* entry_field_records = record->entry_field_records();
836 if (entry_field_records != NULL) {
837 int efr_len = entry_field_records->length();
838 assert(efr_len % 2 == 0, "sanity");
839 for (int i = 0; i < efr_len; i += 2) {
840 int root_index = entry_field_records->at(i+1);
841 clear_root(root_index);
842 }
843 }
844 }
845 }
846
847 class WalkOopAndArchiveClosure: public BasicOopIterateClosure {
848 int _level;
849 bool _is_closed_archive;
850 bool _record_klasses_only;
851 KlassSubGraphInfo* _subgraph_info;
852 oop _orig_referencing_obj;
853 oop _archived_referencing_obj;
854 Thread* _thread;
855 public:
WalkOopAndArchiveClosure(int level,bool is_closed_archive,bool record_klasses_only,KlassSubGraphInfo * subgraph_info,oop orig,oop archived,TRAPS)856 WalkOopAndArchiveClosure(int level,
857 bool is_closed_archive,
858 bool record_klasses_only,
859 KlassSubGraphInfo* subgraph_info,
860 oop orig, oop archived, TRAPS) :
861 _level(level), _is_closed_archive(is_closed_archive),
862 _record_klasses_only(record_klasses_only),
863 _subgraph_info(subgraph_info),
864 _orig_referencing_obj(orig), _archived_referencing_obj(archived),
865 _thread(THREAD) {}
do_oop(narrowOop * p)866 void do_oop(narrowOop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
do_oop(oop * p)867 void do_oop( oop *p) { WalkOopAndArchiveClosure::do_oop_work(p); }
868
869 protected:
do_oop_work(T * p)870 template <class T> void do_oop_work(T *p) {
871 oop obj = RawAccess<>::oop_load(p);
872 if (!CompressedOops::is_null(obj)) {
873 assert(!HeapShared::is_archived_object(obj),
874 "original objects must not point to archived objects");
875
876 size_t field_delta = pointer_delta(p, _orig_referencing_obj, sizeof(char));
877 T* new_p = (T*)(cast_from_oop<address>(_archived_referencing_obj) + field_delta);
878 Thread* THREAD = _thread;
879
880 if (!_record_klasses_only && log_is_enabled(Debug, cds, heap)) {
881 ResourceMark rm;
882 log_debug(cds, heap)("(%d) %s[" SIZE_FORMAT "] ==> " PTR_FORMAT " size %d %s", _level,
883 _orig_referencing_obj->klass()->external_name(), field_delta,
884 p2i(obj), obj->size() * HeapWordSize, obj->klass()->external_name());
885 LogTarget(Trace, cds, heap) log;
886 LogStream out(log);
887 obj->print_on(&out);
888 }
889
890 oop archived = HeapShared::archive_reachable_objects_from(
891 _level + 1, _subgraph_info, obj, _is_closed_archive, THREAD);
892 assert(archived != NULL, "VM should have exited with unarchivable objects for _level > 1");
893 assert(HeapShared::is_archived_object(archived), "must be");
894
895 if (!_record_klasses_only) {
896 // Update the reference in the archived copy of the referencing object.
897 log_debug(cds, heap)("(%d) updating oop @[" PTR_FORMAT "] " PTR_FORMAT " ==> " PTR_FORMAT,
898 _level, p2i(new_p), p2i(obj), p2i(archived));
899 RawAccess<IS_NOT_NULL>::oop_store(new_p, archived);
900 }
901 }
902 }
903 };
904
check_closed_archive_heap_region_object(InstanceKlass * k,Thread * THREAD)905 void HeapShared::check_closed_archive_heap_region_object(InstanceKlass* k,
906 Thread* THREAD) {
907 // Check fields in the object
908 for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
909 if (!fs.access_flags().is_static()) {
910 BasicType ft = fs.field_descriptor().field_type();
911 if (!fs.access_flags().is_final() && is_reference_type(ft)) {
912 ResourceMark rm(THREAD);
913 log_warning(cds, heap)(
914 "Please check reference field in %s instance in closed archive heap region: %s %s",
915 k->external_name(), (fs.name())->as_C_string(),
916 (fs.signature())->as_C_string());
917 }
918 }
919 }
920 }
921
check_module_oop(oop orig_module_obj)922 void HeapShared::check_module_oop(oop orig_module_obj) {
923 assert(DumpSharedSpaces, "must be");
924 assert(java_lang_Module::is_instance(orig_module_obj), "must be");
925 ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);
926 if (orig_module_ent == NULL) {
927 // These special Module objects are created in Java code. They are not
928 // defined via Modules::define_module(), so they don't have a ModuleEntry:
929 // java.lang.Module::ALL_UNNAMED_MODULE
930 // java.lang.Module::EVERYONE_MODULE
931 // jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule
932 assert(java_lang_Module::name(orig_module_obj) == NULL, "must be unnamed");
933 log_info(cds, heap)("Module oop with No ModuleEntry* @[" PTR_FORMAT "]", p2i(orig_module_obj));
934 } else {
935 ClassLoaderData* loader_data = orig_module_ent->loader_data();
936 assert(loader_data->is_builtin_class_loader_data(), "must be");
937 }
938 }
939
940
941 // (1) If orig_obj has not been archived yet, archive it.
942 // (2) If orig_obj has not been seen yet (since start_recording_subgraph() was called),
943 // trace all objects that are reachable from it, and make sure these objects are archived.
944 // (3) Record the klasses of all orig_obj and all reachable objects.
archive_reachable_objects_from(int level,KlassSubGraphInfo * subgraph_info,oop orig_obj,bool is_closed_archive,TRAPS)945 oop HeapShared::archive_reachable_objects_from(int level,
946 KlassSubGraphInfo* subgraph_info,
947 oop orig_obj,
948 bool is_closed_archive,
949 TRAPS) {
950 assert(orig_obj != NULL, "must be");
951 assert(!is_archived_object(orig_obj), "sanity");
952
953 if (!JavaClasses::is_supported_for_archiving(orig_obj)) {
954 // This object has injected fields that cannot be supported easily, so we disallow them for now.
955 // If you get an error here, you probably made a change in the JDK library that has added
956 // these objects that are referenced (directly or indirectly) by static fields.
957 ResourceMark rm;
958 log_error(cds, heap)("Cannot archive object of class %s", orig_obj->klass()->external_name());
959 vm_direct_exit(1);
960 }
961
962 // java.lang.Class instances cannot be included in an archived object sub-graph. We only support
963 // them as Klass::_archived_mirror because they need to be specially restored at run time.
964 //
965 // If you get an error here, you probably made a change in the JDK library that has added a Class
966 // object that is referenced (directly or indirectly) by static fields.
967 if (java_lang_Class::is_instance(orig_obj)) {
968 log_error(cds, heap)("(%d) Unknown java.lang.Class object is in the archived sub-graph", level);
969 vm_direct_exit(1);
970 }
971
972 oop archived_obj = find_archived_heap_object(orig_obj);
973 if (java_lang_String::is_instance(orig_obj) && archived_obj != NULL) {
974 // To save time, don't walk strings that are already archived. They just contain
975 // pointers to a type array, whose klass doesn't need to be recorded.
976 return archived_obj;
977 }
978
979 if (has_been_seen_during_subgraph_recording(orig_obj)) {
980 // orig_obj has already been archived and traced. Nothing more to do.
981 return archived_obj;
982 } else {
983 set_has_been_seen_during_subgraph_recording(orig_obj);
984 }
985
986 bool record_klasses_only = (archived_obj != NULL);
987 if (archived_obj == NULL) {
988 ++_num_new_archived_objs;
989 archived_obj = archive_heap_object(orig_obj, THREAD);
990 if (archived_obj == NULL) {
991 // Skip archiving the sub-graph referenced from the current entry field.
992 ResourceMark rm;
993 log_error(cds, heap)(
994 "Cannot archive the sub-graph referenced from %s object ("
995 PTR_FORMAT ") size %d, skipped.",
996 orig_obj->klass()->external_name(), p2i(orig_obj), orig_obj->size() * HeapWordSize);
997 if (level == 1) {
998 // Don't archive a subgraph root that's too big. For archives static fields, that's OK
999 // as the Java code will take care of initializing this field dynamically.
1000 return NULL;
1001 } else {
1002 // We don't know how to handle an object that has been archived, but some of its reachable
1003 // objects cannot be archived. Bail out for now. We might need to fix this in the future if
1004 // we have a real use case.
1005 vm_direct_exit(1);
1006 }
1007 }
1008
1009 if (java_lang_Module::is_instance(orig_obj)) {
1010 check_module_oop(orig_obj);
1011 java_lang_Module::set_module_entry(archived_obj, NULL);
1012 java_lang_Module::set_loader(archived_obj, NULL);
1013 } else if (java_lang_ClassLoader::is_instance(orig_obj)) {
1014 // class_data will be restored explicitly at run time.
1015 guarantee(orig_obj == SystemDictionary::java_platform_loader() ||
1016 orig_obj == SystemDictionary::java_system_loader() ||
1017 java_lang_ClassLoader::loader_data_raw(orig_obj) == NULL, "must be");
1018 java_lang_ClassLoader::release_set_loader_data(archived_obj, NULL);
1019 }
1020 }
1021
1022 assert(archived_obj != NULL, "must be");
1023 Klass *orig_k = orig_obj->klass();
1024 Klass *relocated_k = archived_obj->klass();
1025 subgraph_info->add_subgraph_object_klass(orig_k, relocated_k);
1026
1027 WalkOopAndArchiveClosure walker(level, is_closed_archive, record_klasses_only,
1028 subgraph_info, orig_obj, archived_obj, THREAD);
1029 orig_obj->oop_iterate(&walker);
1030 if (is_closed_archive && orig_k->is_instance_klass()) {
1031 check_closed_archive_heap_region_object(InstanceKlass::cast(orig_k), THREAD);
1032 }
1033 return archived_obj;
1034 }
1035
1036 //
1037 // Start from the given static field in a java mirror and archive the
1038 // complete sub-graph of java heap objects that are reached directly
1039 // or indirectly from the starting object by following references.
1040 // Sub-graph archiving restrictions (current):
1041 //
1042 // - All classes of objects in the archived sub-graph (including the
1043 // entry class) must be boot class only.
1044 // - No java.lang.Class instance (java mirror) can be included inside
1045 // an archived sub-graph. Mirror can only be the sub-graph entry object.
1046 //
1047 // The Java heap object sub-graph archiving process (see
1048 // WalkOopAndArchiveClosure):
1049 //
1050 // 1) Java object sub-graph archiving starts from a given static field
1051 // within a Class instance (java mirror). If the static field is a
1052 // refererence field and points to a non-null java object, proceed to
1053 // the next step.
1054 //
1055 // 2) Archives the referenced java object. If an archived copy of the
1056 // current object already exists, updates the pointer in the archived
1057 // copy of the referencing object to point to the current archived object.
1058 // Otherwise, proceed to the next step.
1059 //
1060 // 3) Follows all references within the current java object and recursively
1061 // archive the sub-graph of objects starting from each reference.
1062 //
1063 // 4) Updates the pointer in the archived copy of referencing object to
1064 // point to the current archived object.
1065 //
1066 // 5) The Klass of the current java object is added to the list of Klasses
1067 // for loading and initialzing before any object in the archived graph can
1068 // be accessed at runtime.
1069 //
archive_reachable_objects_from_static_field(InstanceKlass * k,const char * klass_name,int field_offset,const char * field_name,bool is_closed_archive,TRAPS)1070 void HeapShared::archive_reachable_objects_from_static_field(InstanceKlass *k,
1071 const char* klass_name,
1072 int field_offset,
1073 const char* field_name,
1074 bool is_closed_archive,
1075 TRAPS) {
1076 assert(DumpSharedSpaces, "dump time only");
1077 assert(k->is_shared_boot_class(), "must be boot class");
1078
1079 oop m = k->java_mirror();
1080
1081 KlassSubGraphInfo* subgraph_info = get_subgraph_info(k);
1082 oop f = m->obj_field(field_offset);
1083
1084 log_debug(cds, heap)("Start archiving from: %s::%s (" PTR_FORMAT ")", klass_name, field_name, p2i(f));
1085
1086 if (!CompressedOops::is_null(f)) {
1087 if (log_is_enabled(Trace, cds, heap)) {
1088 LogTarget(Trace, cds, heap) log;
1089 LogStream out(log);
1090 f->print_on(&out);
1091 }
1092
1093 oop af = archive_reachable_objects_from(1, subgraph_info, f,
1094 is_closed_archive, CHECK);
1095
1096 if (af == NULL) {
1097 log_error(cds, heap)("Archiving failed %s::%s (some reachable objects cannot be archived)",
1098 klass_name, field_name);
1099 } else {
1100 // Note: the field value is not preserved in the archived mirror.
1101 // Record the field as a new subGraph entry point. The recorded
1102 // information is restored from the archive at runtime.
1103 subgraph_info->add_subgraph_entry_field(field_offset, af, is_closed_archive);
1104 log_info(cds, heap)("Archived field %s::%s => " PTR_FORMAT, klass_name, field_name, p2i(af));
1105 }
1106 } else {
1107 // The field contains null, we still need to record the entry point,
1108 // so it can be restored at runtime.
1109 subgraph_info->add_subgraph_entry_field(field_offset, NULL, false);
1110 }
1111 }
1112
1113 #ifndef PRODUCT
1114 class VerifySharedOopClosure: public BasicOopIterateClosure {
1115 private:
1116 bool _is_archived;
1117
1118 public:
VerifySharedOopClosure(bool is_archived)1119 VerifySharedOopClosure(bool is_archived) : _is_archived(is_archived) {}
1120
do_oop(narrowOop * p)1121 void do_oop(narrowOop *p) { VerifySharedOopClosure::do_oop_work(p); }
do_oop(oop * p)1122 void do_oop( oop *p) { VerifySharedOopClosure::do_oop_work(p); }
1123
1124 protected:
do_oop_work(T * p)1125 template <class T> void do_oop_work(T *p) {
1126 oop obj = RawAccess<>::oop_load(p);
1127 if (!CompressedOops::is_null(obj)) {
1128 HeapShared::verify_reachable_objects_from(obj, _is_archived);
1129 }
1130 }
1131 };
1132
verify_subgraph_from_static_field(InstanceKlass * k,int field_offset)1133 void HeapShared::verify_subgraph_from_static_field(InstanceKlass* k, int field_offset) {
1134 assert(DumpSharedSpaces, "dump time only");
1135 assert(k->is_shared_boot_class(), "must be boot class");
1136
1137 oop m = k->java_mirror();
1138 oop f = m->obj_field(field_offset);
1139 if (!CompressedOops::is_null(f)) {
1140 verify_subgraph_from(f);
1141 }
1142 }
1143
verify_subgraph_from(oop orig_obj)1144 void HeapShared::verify_subgraph_from(oop orig_obj) {
1145 oop archived_obj = find_archived_heap_object(orig_obj);
1146 if (archived_obj == NULL) {
1147 // It's OK for the root of a subgraph to be not archived. See comments in
1148 // archive_reachable_objects_from().
1149 return;
1150 }
1151
1152 // Verify that all objects reachable from orig_obj are archived.
1153 init_seen_objects_table();
1154 verify_reachable_objects_from(orig_obj, false);
1155 delete_seen_objects_table();
1156
1157 // Note: we could also verify that all objects reachable from the archived
1158 // copy of orig_obj can only point to archived objects, with:
1159 // init_seen_objects_table();
1160 // verify_reachable_objects_from(archived_obj, true);
1161 // init_seen_objects_table();
1162 // but that's already done in G1HeapVerifier::verify_archive_regions so we
1163 // won't do it here.
1164 }
1165
verify_reachable_objects_from(oop obj,bool is_archived)1166 void HeapShared::verify_reachable_objects_from(oop obj, bool is_archived) {
1167 _num_total_verifications ++;
1168 if (!has_been_seen_during_subgraph_recording(obj)) {
1169 set_has_been_seen_during_subgraph_recording(obj);
1170
1171 if (is_archived) {
1172 assert(is_archived_object(obj), "must be");
1173 assert(find_archived_heap_object(obj) == NULL, "must be");
1174 } else {
1175 assert(!is_archived_object(obj), "must be");
1176 assert(find_archived_heap_object(obj) != NULL, "must be");
1177 }
1178
1179 VerifySharedOopClosure walker(is_archived);
1180 obj->oop_iterate(&walker);
1181 }
1182 }
1183 #endif
1184
1185 HeapShared::SeenObjectsTable* HeapShared::_seen_objects_table = NULL;
1186 int HeapShared::_num_new_walked_objs;
1187 int HeapShared::_num_new_archived_objs;
1188 int HeapShared::_num_old_recorded_klasses;
1189
1190 int HeapShared::_num_total_subgraph_recordings = 0;
1191 int HeapShared::_num_total_walked_objs = 0;
1192 int HeapShared::_num_total_archived_objs = 0;
1193 int HeapShared::_num_total_recorded_klasses = 0;
1194 int HeapShared::_num_total_verifications = 0;
1195
has_been_seen_during_subgraph_recording(oop obj)1196 bool HeapShared::has_been_seen_during_subgraph_recording(oop obj) {
1197 return _seen_objects_table->get(obj) != NULL;
1198 }
1199
set_has_been_seen_during_subgraph_recording(oop obj)1200 void HeapShared::set_has_been_seen_during_subgraph_recording(oop obj) {
1201 assert(!has_been_seen_during_subgraph_recording(obj), "sanity");
1202 _seen_objects_table->put(obj, true);
1203 ++ _num_new_walked_objs;
1204 }
1205
start_recording_subgraph(InstanceKlass * k,const char * class_name,bool is_full_module_graph)1206 void HeapShared::start_recording_subgraph(InstanceKlass *k, const char* class_name, bool is_full_module_graph) {
1207 log_info(cds, heap)("Start recording subgraph(s) for archived fields in %s", class_name);
1208 init_subgraph_info(k, is_full_module_graph);
1209 init_seen_objects_table();
1210 _num_new_walked_objs = 0;
1211 _num_new_archived_objs = 0;
1212 _num_old_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses();
1213 }
1214
done_recording_subgraph(InstanceKlass * k,const char * class_name)1215 void HeapShared::done_recording_subgraph(InstanceKlass *k, const char* class_name) {
1216 int num_new_recorded_klasses = get_subgraph_info(k)->num_subgraph_object_klasses() -
1217 _num_old_recorded_klasses;
1218 log_info(cds, heap)("Done recording subgraph(s) for archived fields in %s: "
1219 "walked %d objs, archived %d new objs, recorded %d classes",
1220 class_name, _num_new_walked_objs, _num_new_archived_objs,
1221 num_new_recorded_klasses);
1222
1223 delete_seen_objects_table();
1224
1225 _num_total_subgraph_recordings ++;
1226 _num_total_walked_objs += _num_new_walked_objs;
1227 _num_total_archived_objs += _num_new_archived_objs;
1228 _num_total_recorded_klasses += num_new_recorded_klasses;
1229 }
1230
1231 class ArchivableStaticFieldFinder: public FieldClosure {
1232 InstanceKlass* _ik;
1233 Symbol* _field_name;
1234 bool _found;
1235 int _offset;
1236 public:
ArchivableStaticFieldFinder(InstanceKlass * ik,Symbol * field_name)1237 ArchivableStaticFieldFinder(InstanceKlass* ik, Symbol* field_name) :
1238 _ik(ik), _field_name(field_name), _found(false), _offset(-1) {}
1239
do_field(fieldDescriptor * fd)1240 virtual void do_field(fieldDescriptor* fd) {
1241 if (fd->name() == _field_name) {
1242 assert(!_found, "fields cannot be overloaded");
1243 assert(is_reference_type(fd->field_type()), "can archive only fields that are references");
1244 _found = true;
1245 _offset = fd->offset();
1246 }
1247 }
found()1248 bool found() { return _found; }
offset()1249 int offset() { return _offset; }
1250 };
1251
init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],int num,Thread * THREAD)1252 void HeapShared::init_subgraph_entry_fields(ArchivableStaticFieldInfo fields[],
1253 int num, Thread* THREAD) {
1254 for (int i = 0; i < num; i++) {
1255 ArchivableStaticFieldInfo* info = &fields[i];
1256 TempNewSymbol klass_name = SymbolTable::new_symbol(info->klass_name);
1257 TempNewSymbol field_name = SymbolTable::new_symbol(info->field_name);
1258
1259 Klass* k = SystemDictionary::resolve_or_null(klass_name, THREAD);
1260 if (HAS_PENDING_EXCEPTION) {
1261 ResourceMark rm(THREAD);
1262 ArchiveUtils::check_for_oom(PENDING_EXCEPTION); // exit on OOM
1263 log_info(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
1264 java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
1265 vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
1266 }
1267 InstanceKlass* ik = InstanceKlass::cast(k);
1268 assert(InstanceKlass::cast(ik)->is_shared_boot_class(),
1269 "Only support boot classes");
1270 ik->initialize(THREAD);
1271 guarantee(!HAS_PENDING_EXCEPTION, "exception in initialize");
1272
1273 ArchivableStaticFieldFinder finder(ik, field_name);
1274 ik->do_local_static_fields(&finder);
1275 assert(finder.found(), "field must exist");
1276
1277 info->klass = ik;
1278 info->offset = finder.offset();
1279 }
1280 }
1281
init_subgraph_entry_fields(Thread * THREAD)1282 void HeapShared::init_subgraph_entry_fields(Thread* THREAD) {
1283 assert(is_heap_object_archiving_allowed(), "Sanity check");
1284 _dump_time_subgraph_info_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeKlassSubGraphInfoTable();
1285 init_subgraph_entry_fields(closed_archive_subgraph_entry_fields,
1286 num_closed_archive_subgraph_entry_fields,
1287 THREAD);
1288 init_subgraph_entry_fields(open_archive_subgraph_entry_fields,
1289 num_open_archive_subgraph_entry_fields,
1290 THREAD);
1291 if (MetaspaceShared::use_full_module_graph()) {
1292 init_subgraph_entry_fields(fmg_open_archive_subgraph_entry_fields,
1293 num_fmg_open_archive_subgraph_entry_fields,
1294 THREAD);
1295 }
1296 }
1297
init_for_dumping(Thread * THREAD)1298 void HeapShared::init_for_dumping(Thread* THREAD) {
1299 if (is_heap_object_archiving_allowed()) {
1300 _dumped_interned_strings = new (ResourceObj::C_HEAP, mtClass)DumpedInternedStrings();
1301 init_subgraph_entry_fields(THREAD);
1302 }
1303 }
1304
archive_object_subgraphs(ArchivableStaticFieldInfo fields[],int num,bool is_closed_archive,bool is_full_module_graph,Thread * THREAD)1305 void HeapShared::archive_object_subgraphs(ArchivableStaticFieldInfo fields[],
1306 int num, bool is_closed_archive,
1307 bool is_full_module_graph,
1308 Thread* THREAD) {
1309 _num_total_subgraph_recordings = 0;
1310 _num_total_walked_objs = 0;
1311 _num_total_archived_objs = 0;
1312 _num_total_recorded_klasses = 0;
1313 _num_total_verifications = 0;
1314
1315 // For each class X that has one or more archived fields:
1316 // [1] Dump the subgraph of each archived field
1317 // [2] Create a list of all the class of the objects that can be reached
1318 // by any of these static fields.
1319 // At runtime, these classes are initialized before X's archived fields
1320 // are restored by HeapShared::initialize_from_archived_subgraph().
1321 int i;
1322 for (i = 0; i < num; ) {
1323 ArchivableStaticFieldInfo* info = &fields[i];
1324 const char* klass_name = info->klass_name;
1325 start_recording_subgraph(info->klass, klass_name, is_full_module_graph);
1326
1327 // If you have specified consecutive fields of the same klass in
1328 // fields[], these will be archived in the same
1329 // {start_recording_subgraph ... done_recording_subgraph} pass to
1330 // save time.
1331 for (; i < num; i++) {
1332 ArchivableStaticFieldInfo* f = &fields[i];
1333 if (f->klass_name != klass_name) {
1334 break;
1335 }
1336
1337 archive_reachable_objects_from_static_field(f->klass, f->klass_name,
1338 f->offset, f->field_name,
1339 is_closed_archive, CHECK);
1340 }
1341 done_recording_subgraph(info->klass, klass_name);
1342 }
1343
1344 log_info(cds, heap)("Archived subgraph records in %s archive heap region = %d",
1345 is_closed_archive ? "closed" : "open",
1346 _num_total_subgraph_recordings);
1347 log_info(cds, heap)(" Walked %d objects", _num_total_walked_objs);
1348 log_info(cds, heap)(" Archived %d objects", _num_total_archived_objs);
1349 log_info(cds, heap)(" Recorded %d klasses", _num_total_recorded_klasses);
1350
1351 #ifndef PRODUCT
1352 for (int i = 0; i < num; i++) {
1353 ArchivableStaticFieldInfo* f = &fields[i];
1354 verify_subgraph_from_static_field(f->klass, f->offset);
1355 }
1356 log_info(cds, heap)(" Verified %d references", _num_total_verifications);
1357 #endif
1358 }
1359
1360 // Not all the strings in the global StringTable are dumped into the archive, because
1361 // some of those strings may be only referenced by classes that are excluded from
1362 // the archive. We need to explicitly mark the strings that are:
1363 // [1] used by classes that WILL be archived;
1364 // [2] included in the SharedArchiveConfigFile.
add_to_dumped_interned_strings(oop string)1365 void HeapShared::add_to_dumped_interned_strings(oop string) {
1366 assert_at_safepoint(); // DumpedInternedStrings uses raw oops
1367 bool created;
1368 _dumped_interned_strings->put_if_absent(string, true, &created);
1369 }
1370
1371 // At dump-time, find the location of all the non-null oop pointers in an archived heap
1372 // region. This way we can quickly relocate all the pointers without using
1373 // BasicOopIterateClosure at runtime.
1374 class FindEmbeddedNonNullPointers: public BasicOopIterateClosure {
1375 narrowOop* _start;
1376 BitMap *_oopmap;
1377 int _num_total_oops;
1378 int _num_null_oops;
1379 public:
FindEmbeddedNonNullPointers(narrowOop * start,BitMap * oopmap)1380 FindEmbeddedNonNullPointers(narrowOop* start, BitMap* oopmap)
1381 : _start(start), _oopmap(oopmap), _num_total_oops(0), _num_null_oops(0) {}
1382
do_oop(narrowOop * p)1383 virtual void do_oop(narrowOop* p) {
1384 _num_total_oops ++;
1385 narrowOop v = *p;
1386 if (!CompressedOops::is_null(v)) {
1387 size_t idx = p - _start;
1388 _oopmap->set_bit(idx);
1389 } else {
1390 _num_null_oops ++;
1391 }
1392 }
do_oop(oop * p)1393 virtual void do_oop(oop *p) {
1394 ShouldNotReachHere();
1395 }
num_total_oops() const1396 int num_total_oops() const { return _num_total_oops; }
num_null_oops() const1397 int num_null_oops() const { return _num_null_oops; }
1398 };
1399
calculate_oopmap(MemRegion region)1400 ResourceBitMap HeapShared::calculate_oopmap(MemRegion region) {
1401 assert(UseCompressedOops, "must be");
1402 size_t num_bits = region.byte_size() / sizeof(narrowOop);
1403 ResourceBitMap oopmap(num_bits);
1404
1405 HeapWord* p = region.start();
1406 HeapWord* end = region.end();
1407 FindEmbeddedNonNullPointers finder((narrowOop*)p, &oopmap);
1408
1409 int num_objs = 0;
1410 while (p < end) {
1411 oop o = (oop)p;
1412 o->oop_iterate(&finder);
1413 p += o->size();
1414 ++ num_objs;
1415 }
1416
1417 log_info(cds, heap)("calculate_oopmap: objects = %6d, embedded oops = %7d, nulls = %7d",
1418 num_objs, finder.num_total_oops(), finder.num_null_oops());
1419 return oopmap;
1420 }
1421
1422 // Patch all the embedded oop pointers inside an archived heap region,
1423 // to be consistent with the runtime oop encoding.
1424 class PatchEmbeddedPointers: public BitMapClosure {
1425 narrowOop* _start;
1426
1427 public:
PatchEmbeddedPointers(narrowOop * start)1428 PatchEmbeddedPointers(narrowOop* start) : _start(start) {}
1429
do_bit(size_t offset)1430 bool do_bit(size_t offset) {
1431 narrowOop* p = _start + offset;
1432 narrowOop v = *p;
1433 assert(!CompressedOops::is_null(v), "null oops should have been filtered out at dump time");
1434 oop o = HeapShared::decode_from_archive(v);
1435 RawAccess<IS_NOT_NULL>::oop_store(p, o);
1436 return true;
1437 }
1438 };
1439
patch_archived_heap_embedded_pointers(MemRegion region,address oopmap,size_t oopmap_size_in_bits)1440 void HeapShared::patch_archived_heap_embedded_pointers(MemRegion region, address oopmap,
1441 size_t oopmap_size_in_bits) {
1442 BitMapView bm((BitMap::bm_word_t*)oopmap, oopmap_size_in_bits);
1443
1444 #ifndef PRODUCT
1445 ResourceMark rm;
1446 ResourceBitMap checkBm = calculate_oopmap(region);
1447 assert(bm.is_same(checkBm), "sanity");
1448 #endif
1449
1450 PatchEmbeddedPointers patcher((narrowOop*)region.start());
1451 bm.iterate(&patcher);
1452 }
1453
1454 #endif // INCLUDE_CDS_JAVA_HEAP
1455