Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/hotspot/share/cds/metaspaceShared.cpp
64441 views
1
/*
2
* Copyright (c) 2012, 2021, 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_io.h"
27
#include "cds/archiveBuilder.hpp"
28
#include "cds/classListParser.hpp"
29
#include "cds/cppVtables.hpp"
30
#include "cds/dumpAllocStats.hpp"
31
#include "cds/filemap.hpp"
32
#include "cds/heapShared.hpp"
33
#include "cds/lambdaFormInvokers.hpp"
34
#include "cds/metaspaceShared.hpp"
35
#include "classfile/classLoaderDataGraph.hpp"
36
#include "classfile/classLoaderDataShared.hpp"
37
#include "classfile/classLoaderExt.hpp"
38
#include "classfile/javaClasses.inline.hpp"
39
#include "classfile/loaderConstraints.hpp"
40
#include "classfile/placeholders.hpp"
41
#include "classfile/symbolTable.hpp"
42
#include "classfile/stringTable.hpp"
43
#include "classfile/systemDictionary.hpp"
44
#include "classfile/systemDictionaryShared.hpp"
45
#include "classfile/vmClasses.hpp"
46
#include "classfile/vmSymbols.hpp"
47
#include "code/codeCache.hpp"
48
#include "gc/shared/gcVMOperations.hpp"
49
#include "interpreter/bytecodeStream.hpp"
50
#include "interpreter/bytecodes.hpp"
51
#include "logging/log.hpp"
52
#include "logging/logMessage.hpp"
53
#include "logging/logStream.hpp"
54
#include "memory/metaspace.hpp"
55
#include "memory/metaspaceClosure.hpp"
56
#include "memory/resourceArea.hpp"
57
#include "memory/universe.hpp"
58
#include "oops/compressedOops.inline.hpp"
59
#include "oops/instanceMirrorKlass.hpp"
60
#include "oops/klass.inline.hpp"
61
#include "oops/objArrayOop.hpp"
62
#include "oops/oop.inline.hpp"
63
#include "oops/oopHandle.hpp"
64
#include "prims/jvmtiExport.hpp"
65
#include "runtime/arguments.hpp"
66
#include "runtime/handles.inline.hpp"
67
#include "runtime/os.hpp"
68
#include "runtime/safepointVerifiers.hpp"
69
#include "runtime/sharedRuntime.hpp"
70
#include "runtime/vmThread.hpp"
71
#include "runtime/vmOperations.hpp"
72
#include "utilities/align.hpp"
73
#include "utilities/bitMap.inline.hpp"
74
#include "utilities/ostream.hpp"
75
#include "utilities/defaultStream.hpp"
76
#if INCLUDE_G1GC
77
#include "gc/g1/g1CollectedHeap.inline.hpp"
78
#endif
79
80
ReservedSpace MetaspaceShared::_symbol_rs;
81
VirtualSpace MetaspaceShared::_symbol_vs;
82
bool MetaspaceShared::_has_error_classes;
83
bool MetaspaceShared::_archive_loading_failed = false;
84
bool MetaspaceShared::_remapped_readwrite = false;
85
void* MetaspaceShared::_shared_metaspace_static_top = NULL;
86
intx MetaspaceShared::_relocation_delta;
87
char* MetaspaceShared::_requested_base_address;
88
bool MetaspaceShared::_use_optimized_module_handling = true;
89
bool MetaspaceShared::_use_full_module_graph = true;
90
91
// The CDS archive is divided into the following regions:
92
// rw - read-write metadata
93
// ro - read-only metadata and read-only tables
94
//
95
// ca0 - closed archive heap space #0
96
// ca1 - closed archive heap space #1 (may be empty)
97
// oa0 - open archive heap space #0
98
// oa1 - open archive heap space #1 (may be empty)
99
//
100
// bm - bitmap for relocating the above 7 regions.
101
//
102
// The rw and ro regions are linearly allocated, in the order of rw->ro.
103
// These regions are aligned with MetaspaceShared::core_region_alignment().
104
//
105
// These 2 regions are populated in the following steps:
106
// [0] All classes are loaded in MetaspaceShared::preload_classes(). All metadata are
107
// temporarily allocated outside of the shared regions.
108
// [1] We enter a safepoint and allocate a buffer for the rw/ro regions.
109
// [2] C++ vtables are copied into the rw region.
110
// [3] ArchiveBuilder copies RW metadata into the rw region.
111
// [4] ArchiveBuilder copies RO metadata into the ro region.
112
// [5] SymbolTable, StringTable, SystemDictionary, and a few other read-only data
113
// are copied into the ro region as read-only tables.
114
//
115
// The ca0/ca1 and oa0/oa1 regions are populated inside HeapShared::archive_java_heap_objects.
116
// Their layout is independent of the rw/ro regions.
117
118
static DumpRegion _symbol_region("symbols");
119
120
char* MetaspaceShared::symbol_space_alloc(size_t num_bytes) {
121
return _symbol_region.allocate(num_bytes);
122
}
123
124
// os::vm_allocation_granularity() is usually 4K for most OSes. However, on Linux/aarch64,
125
// it can be either 4K or 64K and on Macosx-arm it is 16K. To generate archives that are
126
// compatible for both settings, an alternative cds core region alignment can be enabled
127
// at building time:
128
// --enable-compactible-cds-alignment
129
// Upon successful configuration, the compactible alignment then can be defined as in:
130
// os_linux_aarch64.hpp
131
// which is the highest page size configured on the platform.
132
size_t MetaspaceShared::core_region_alignment() {
133
#if defined(CDS_CORE_REGION_ALIGNMENT)
134
return CDS_CORE_REGION_ALIGNMENT;
135
#else
136
return (size_t)os::vm_allocation_granularity();
137
#endif // CDS_CORE_REGION_ALIGNMENT
138
}
139
140
static bool shared_base_valid(char* shared_base) {
141
#ifdef _LP64
142
return CompressedKlassPointers::is_valid_base((address)shared_base);
143
#else
144
return true;
145
#endif
146
}
147
148
class DumpClassListCLDClosure : public CLDClosure {
149
fileStream *_stream;
150
public:
151
DumpClassListCLDClosure(fileStream* f) : CLDClosure() { _stream = f; }
152
void do_cld(ClassLoaderData* cld) {
153
for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
154
if (klass->is_instance_klass()) {
155
InstanceKlass* ik = InstanceKlass::cast(klass);
156
if (ik->is_shareable()) {
157
_stream->print_cr("%s", ik->name()->as_C_string());
158
}
159
}
160
}
161
}
162
};
163
164
void MetaspaceShared::dump_loaded_classes(const char* file_name, TRAPS) {
165
fileStream stream(file_name, "w");
166
if (stream.is_open()) {
167
MutexLocker lock(ClassLoaderDataGraph_lock);
168
DumpClassListCLDClosure collect_classes(&stream);
169
ClassLoaderDataGraph::loaded_cld_do(&collect_classes);
170
} else {
171
THROW_MSG(vmSymbols::java_io_IOException(), "Failed to open file");
172
}
173
}
174
175
static bool shared_base_too_high(char* specified_base, char* aligned_base, size_t cds_max) {
176
if (specified_base != NULL && aligned_base < specified_base) {
177
// SharedBaseAddress is very high (e.g., 0xffffffffffffff00) so
178
// align_up(SharedBaseAddress, MetaspaceShared::core_region_alignment()) has wrapped around.
179
return true;
180
}
181
if (max_uintx - uintx(aligned_base) < uintx(cds_max)) {
182
// The end of the archive will wrap around
183
return true;
184
}
185
186
return false;
187
}
188
189
static char* compute_shared_base(size_t cds_max) {
190
char* specified_base = (char*)SharedBaseAddress;
191
char* aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
192
193
const char* err = NULL;
194
if (shared_base_too_high(specified_base, aligned_base, cds_max)) {
195
err = "too high";
196
} else if (!shared_base_valid(aligned_base)) {
197
err = "invalid for this platform";
198
} else {
199
return aligned_base;
200
}
201
202
log_warning(cds)("SharedBaseAddress (" INTPTR_FORMAT ") is %s. Reverted to " INTPTR_FORMAT,
203
p2i((void*)SharedBaseAddress), err,
204
p2i((void*)Arguments::default_SharedBaseAddress()));
205
206
specified_base = (char*)Arguments::default_SharedBaseAddress();
207
aligned_base = align_up(specified_base, MetaspaceShared::core_region_alignment());
208
209
// Make sure the default value of SharedBaseAddress specified in globals.hpp is sane.
210
assert(!shared_base_too_high(specified_base, aligned_base, cds_max), "Sanity");
211
assert(shared_base_valid(aligned_base), "Sanity");
212
return aligned_base;
213
}
214
215
void MetaspaceShared::initialize_for_static_dump() {
216
assert(DumpSharedSpaces, "should be called for dump time only");
217
log_info(cds)("Core region alignment: " SIZE_FORMAT, core_region_alignment());
218
// The max allowed size for CDS archive. We use this to limit SharedBaseAddress
219
// to avoid address space wrap around.
220
size_t cds_max;
221
const size_t reserve_alignment = core_region_alignment();
222
223
#ifdef _LP64
224
const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
225
cds_max = align_down(UnscaledClassSpaceMax, reserve_alignment);
226
#else
227
// We don't support archives larger than 256MB on 32-bit due to limited
228
// virtual address space.
229
cds_max = align_down(256*M, reserve_alignment);
230
#endif
231
232
_requested_base_address = compute_shared_base(cds_max);
233
SharedBaseAddress = (size_t)_requested_base_address;
234
235
size_t symbol_rs_size = LP64_ONLY(3 * G) NOT_LP64(128 * M);
236
_symbol_rs = ReservedSpace(symbol_rs_size);
237
if (!_symbol_rs.is_reserved()) {
238
vm_exit_during_initialization("Unable to reserve memory for symbols",
239
err_msg(SIZE_FORMAT " bytes.", symbol_rs_size));
240
}
241
_symbol_region.init(&_symbol_rs, &_symbol_vs);
242
}
243
244
// Called by universe_post_init()
245
void MetaspaceShared::post_initialize(TRAPS) {
246
if (UseSharedSpaces) {
247
int size = FileMapInfo::get_number_of_shared_paths();
248
if (size > 0) {
249
SystemDictionaryShared::allocate_shared_data_arrays(size, CHECK);
250
if (!DynamicDumpSharedSpaces) {
251
FileMapInfo* info;
252
if (FileMapInfo::dynamic_info() == NULL) {
253
info = FileMapInfo::current_info();
254
} else {
255
info = FileMapInfo::dynamic_info();
256
}
257
ClassLoaderExt::init_paths_start_index(info->app_class_paths_start_index());
258
ClassLoaderExt::init_app_module_paths_start_index(info->app_module_paths_start_index());
259
}
260
}
261
}
262
}
263
264
static GrowableArrayCHeap<OopHandle, mtClassShared>* _extra_interned_strings = NULL;
265
static GrowableArrayCHeap<Symbol*, mtClassShared>* _extra_symbols = NULL;
266
267
void MetaspaceShared::read_extra_data(JavaThread* current, const char* filename) {
268
_extra_interned_strings = new GrowableArrayCHeap<OopHandle, mtClassShared>(10000);
269
_extra_symbols = new GrowableArrayCHeap<Symbol*, mtClassShared>(1000);
270
271
HashtableTextDump reader(filename);
272
reader.check_version("VERSION: 1.0");
273
274
while (reader.remain() > 0) {
275
int utf8_length;
276
int prefix_type = reader.scan_prefix(&utf8_length);
277
ResourceMark rm(current);
278
if (utf8_length == 0x7fffffff) {
279
// buf_len will overflown 32-bit value.
280
vm_exit_during_initialization(err_msg("string length too large: %d", utf8_length));
281
}
282
int buf_len = utf8_length+1;
283
char* utf8_buffer = NEW_RESOURCE_ARRAY(char, buf_len);
284
reader.get_utf8(utf8_buffer, utf8_length);
285
utf8_buffer[utf8_length] = '\0';
286
287
if (prefix_type == HashtableTextDump::SymbolPrefix) {
288
_extra_symbols->append(SymbolTable::new_permanent_symbol(utf8_buffer));
289
} else{
290
assert(prefix_type == HashtableTextDump::StringPrefix, "Sanity");
291
ExceptionMark em(current);
292
JavaThread* THREAD = current; // For exception macros.
293
oop str = StringTable::intern(utf8_buffer, THREAD);
294
295
if (HAS_PENDING_EXCEPTION) {
296
log_warning(cds, heap)("[line %d] extra interned string allocation failed; size too large: %d",
297
reader.last_line_no(), utf8_length);
298
CLEAR_PENDING_EXCEPTION;
299
} else {
300
#if INCLUDE_G1GC
301
if (UseG1GC) {
302
typeArrayOop body = java_lang_String::value(str);
303
const HeapRegion* hr = G1CollectedHeap::heap()->heap_region_containing(body);
304
if (hr->is_humongous()) {
305
// Don't keep it alive, so it will be GC'ed before we dump the strings, in order
306
// to maximize free heap space and minimize fragmentation.
307
log_warning(cds, heap)("[line %d] extra interned string ignored; size too large: %d",
308
reader.last_line_no(), utf8_length);
309
continue;
310
}
311
}
312
#endif
313
// Make sure this string is included in the dumped interned string table.
314
assert(str != NULL, "must succeed");
315
_extra_interned_strings->append(OopHandle(Universe::vm_global(), str));
316
}
317
}
318
}
319
}
320
321
// Read/write a data stream for restoring/preserving metadata pointers and
322
// miscellaneous data from/to the shared archive file.
323
324
void MetaspaceShared::serialize(SerializeClosure* soc) {
325
int tag = 0;
326
soc->do_tag(--tag);
327
328
// Verify the sizes of various metadata in the system.
329
soc->do_tag(sizeof(Method));
330
soc->do_tag(sizeof(ConstMethod));
331
soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE));
332
soc->do_tag(sizeof(ConstantPool));
333
soc->do_tag(sizeof(ConstantPoolCache));
334
soc->do_tag(objArrayOopDesc::base_offset_in_bytes());
335
soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE));
336
soc->do_tag(sizeof(Symbol));
337
338
// Dump/restore miscellaneous metadata.
339
JavaClasses::serialize_offsets(soc);
340
Universe::serialize(soc);
341
soc->do_tag(--tag);
342
343
// Dump/restore references to commonly used names and signatures.
344
vmSymbols::serialize(soc);
345
soc->do_tag(--tag);
346
347
// Dump/restore the symbol/string/subgraph_info tables
348
SymbolTable::serialize_shared_table_header(soc);
349
StringTable::serialize_shared_table_header(soc);
350
HeapShared::serialize_subgraph_info_table_header(soc);
351
SystemDictionaryShared::serialize_dictionary_headers(soc);
352
353
InstanceMirrorKlass::serialize_offsets(soc);
354
355
// Dump/restore well known classes (pointers)
356
SystemDictionaryShared::serialize_vm_classes(soc);
357
soc->do_tag(--tag);
358
359
CppVtables::serialize(soc);
360
soc->do_tag(--tag);
361
362
CDS_JAVA_HEAP_ONLY(ClassLoaderDataShared::serialize(soc);)
363
364
LambdaFormInvokers::serialize(soc);
365
soc->do_tag(666);
366
}
367
368
static void rewrite_nofast_bytecode(const methodHandle& method) {
369
BytecodeStream bcs(method);
370
while (!bcs.is_last_bytecode()) {
371
Bytecodes::Code opcode = bcs.next();
372
switch (opcode) {
373
case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break;
374
case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break;
375
case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break;
376
case Bytecodes::_iload: {
377
if (!bcs.is_wide()) {
378
*bcs.bcp() = Bytecodes::_nofast_iload;
379
}
380
break;
381
}
382
default: break;
383
}
384
}
385
}
386
387
// [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified
388
// at run time by RewriteBytecodes/RewriteFrequentPairs
389
// [2] Assign a fingerprint, so one doesn't need to be assigned at run-time.
390
void MetaspaceShared::rewrite_nofast_bytecodes_and_calculate_fingerprints(Thread* thread, InstanceKlass* ik) {
391
for (int i = 0; i < ik->methods()->length(); i++) {
392
methodHandle m(thread, ik->methods()->at(i));
393
if (ik->can_be_verified_at_dumptime()) {
394
rewrite_nofast_bytecode(m);
395
}
396
Fingerprinter fp(m);
397
// The side effect of this call sets method's fingerprint field.
398
fp.fingerprint();
399
}
400
}
401
402
class VM_PopulateDumpSharedSpace : public VM_GC_Operation {
403
private:
404
GrowableArray<MemRegion> *_closed_archive_heap_regions;
405
GrowableArray<MemRegion> *_open_archive_heap_regions;
406
407
GrowableArray<ArchiveHeapOopmapInfo> *_closed_archive_heap_oopmaps;
408
GrowableArray<ArchiveHeapOopmapInfo> *_open_archive_heap_oopmaps;
409
410
void dump_java_heap_objects(GrowableArray<Klass*>* klasses) NOT_CDS_JAVA_HEAP_RETURN;
411
void dump_archive_heap_oopmaps() NOT_CDS_JAVA_HEAP_RETURN;
412
void dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
413
GrowableArray<ArchiveHeapOopmapInfo>* oopmaps);
414
void dump_shared_symbol_table(GrowableArray<Symbol*>* symbols) {
415
log_info(cds)("Dumping symbol table ...");
416
SymbolTable::write_to_archive(symbols);
417
}
418
char* dump_read_only_tables();
419
420
public:
421
422
VM_PopulateDumpSharedSpace() :
423
VM_GC_Operation(0 /* total collections, ignored */, GCCause::_archive_time_gc),
424
_closed_archive_heap_regions(NULL),
425
_open_archive_heap_regions(NULL),
426
_closed_archive_heap_oopmaps(NULL),
427
_open_archive_heap_oopmaps(NULL) {}
428
429
bool skip_operation() const { return false; }
430
431
VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; }
432
void doit(); // outline because gdb sucks
433
bool allow_nested_vm_operations() const { return true; }
434
}; // class VM_PopulateDumpSharedSpace
435
436
class StaticArchiveBuilder : public ArchiveBuilder {
437
public:
438
StaticArchiveBuilder() : ArchiveBuilder() {}
439
440
virtual void iterate_roots(MetaspaceClosure* it, bool is_relocating_pointers) {
441
FileMapInfo::metaspace_pointers_do(it, false);
442
SystemDictionaryShared::dumptime_classes_do(it);
443
Universe::metaspace_pointers_do(it);
444
vmSymbols::metaspace_pointers_do(it);
445
446
// The above code should find all the symbols that are referenced by the
447
// archived classes. We just need to add the extra symbols which
448
// may not be used by any of the archived classes -- these are usually
449
// symbols that we anticipate to be used at run time, so we can store
450
// them in the RO region, to be shared across multiple processes.
451
if (_extra_symbols != NULL) {
452
for (int i = 0; i < _extra_symbols->length(); i++) {
453
it->push(_extra_symbols->adr_at(i));
454
}
455
}
456
}
457
};
458
459
char* VM_PopulateDumpSharedSpace::dump_read_only_tables() {
460
ArchiveBuilder::OtherROAllocMark mark;
461
462
SystemDictionaryShared::write_to_archive();
463
464
// Write lambform lines into archive
465
LambdaFormInvokers::dump_static_archive_invokers();
466
// Write the other data to the output array.
467
DumpRegion* ro_region = ArchiveBuilder::current()->ro_region();
468
char* start = ro_region->top();
469
WriteClosure wc(ro_region);
470
MetaspaceShared::serialize(&wc);
471
472
// Write the bitmaps for patching the archive heap regions
473
dump_archive_heap_oopmaps();
474
475
return start;
476
}
477
478
void VM_PopulateDumpSharedSpace::doit() {
479
HeapShared::run_full_gc_in_vm_thread();
480
481
DEBUG_ONLY(SystemDictionaryShared::NoClassLoadingMark nclm);
482
483
FileMapInfo::check_nonempty_dir_in_shared_path_table();
484
485
NOT_PRODUCT(SystemDictionary::verify();)
486
487
// Block concurrent class unloading from changing the _dumptime_table
488
MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
489
SystemDictionaryShared::check_excluded_classes();
490
SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary();
491
492
StaticArchiveBuilder builder;
493
builder.gather_source_objs();
494
builder.reserve_buffer();
495
496
char* cloned_vtables = CppVtables::dumptime_init(&builder);
497
498
builder.dump_rw_metadata();
499
builder.dump_ro_metadata();
500
builder.relocate_metaspaceobj_embedded_pointers();
501
502
// Dump supported java heap objects
503
dump_java_heap_objects(builder.klasses());
504
505
builder.relocate_roots();
506
dump_shared_symbol_table(builder.symbols());
507
508
builder.relocate_vm_classes();
509
510
log_info(cds)("Make classes shareable");
511
builder.make_klasses_shareable();
512
513
char* serialized_data = dump_read_only_tables();
514
515
SystemDictionaryShared::adjust_lambda_proxy_class_dictionary();
516
517
// The vtable clones contain addresses of the current process.
518
// We don't want to write these addresses into the archive.
519
CppVtables::zero_archived_vtables();
520
521
// relocate the data so that it can be mapped to MetaspaceShared::requested_base_address()
522
// without runtime relocation.
523
builder.relocate_to_requested();
524
525
// Write the archive file
526
FileMapInfo* mapinfo = new FileMapInfo(true);
527
mapinfo->populate_header(MetaspaceShared::core_region_alignment());
528
mapinfo->set_serialized_data(serialized_data);
529
mapinfo->set_cloned_vtables(cloned_vtables);
530
mapinfo->open_for_write();
531
builder.write_archive(mapinfo,
532
_closed_archive_heap_regions,
533
_open_archive_heap_regions,
534
_closed_archive_heap_oopmaps,
535
_open_archive_heap_oopmaps);
536
537
if (PrintSystemDictionaryAtExit) {
538
SystemDictionary::print();
539
}
540
541
if (AllowArchivingWithJavaAgent) {
542
warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
543
"for testing purposes only and should not be used in a production environment");
544
}
545
546
// There may be pending VM operations. We have changed some global states
547
// (such as vmClasses::_klasses) that may cause these VM operations
548
// to fail. For safety, forget these operations and exit the VM directly.
549
vm_direct_exit(0);
550
}
551
552
class CollectCLDClosure : public CLDClosure {
553
GrowableArray<ClassLoaderData*> _loaded_cld;
554
GrowableArray<OopHandle> _loaded_cld_handles; // keep the CLDs alive
555
Thread* _current_thread;
556
public:
557
CollectCLDClosure(Thread* thread) : _current_thread(thread) {}
558
~CollectCLDClosure() {
559
for (int i = 0; i < _loaded_cld_handles.length(); i++) {
560
_loaded_cld_handles.at(i).release(Universe::vm_global());
561
}
562
}
563
void do_cld(ClassLoaderData* cld) {
564
assert(cld->is_alive(), "must be");
565
_loaded_cld.append(cld);
566
_loaded_cld_handles.append(OopHandle(Universe::vm_global(), cld->holder_phantom()));
567
}
568
569
int nof_cld() const { return _loaded_cld.length(); }
570
ClassLoaderData* cld_at(int index) { return _loaded_cld.at(index); }
571
};
572
573
bool MetaspaceShared::linking_required(InstanceKlass* ik) {
574
// For static CDS dump, do not link old classes.
575
// For dynamic CDS dump, only link classes loaded by the builtin class loaders.
576
return DumpSharedSpaces ? ik->can_be_verified_at_dumptime() : !ik->is_shared_unregistered_class();
577
}
578
579
bool MetaspaceShared::link_class_for_cds(InstanceKlass* ik, TRAPS) {
580
// Link the class to cause the bytecodes to be rewritten and the
581
// cpcache to be created. Class verification is done according
582
// to -Xverify setting.
583
bool res = MetaspaceShared::try_link_class(THREAD, ik);
584
585
if (DumpSharedSpaces) {
586
// The following function is used to resolve all Strings in the statically
587
// dumped classes to archive all the Strings. The archive heap is not supported
588
// for the dynamic archive.
589
ik->constants()->resolve_class_constants(CHECK_(false)); // may throw OOM when interning strings.
590
}
591
return res;
592
}
593
594
void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) {
595
LambdaFormInvokers::regenerate_holder_classes(CHECK);
596
597
// Collect all loaded ClassLoaderData.
598
CollectCLDClosure collect_cld(THREAD);
599
{
600
// ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
601
// We cannot link the classes while holding this lock (or else we may run into deadlock).
602
// Therefore, we need to first collect all the CLDs, and then link their classes after
603
// releasing the lock.
604
MutexLocker lock(ClassLoaderDataGraph_lock);
605
ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
606
}
607
608
while (true) {
609
bool has_linked = false;
610
for (int i = 0; i < collect_cld.nof_cld(); i++) {
611
ClassLoaderData* cld = collect_cld.cld_at(i);
612
for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
613
if (klass->is_instance_klass()) {
614
InstanceKlass* ik = InstanceKlass::cast(klass);
615
if (linking_required(ik)) {
616
has_linked |= link_class_for_cds(ik, CHECK);
617
}
618
}
619
}
620
}
621
622
if (!has_linked) {
623
break;
624
}
625
// Class linking includes verification which may load more classes.
626
// Keep scanning until we have linked no more classes.
627
}
628
}
629
630
void MetaspaceShared::prepare_for_dumping() {
631
Arguments::assert_is_dumping_archive();
632
Arguments::check_unsupported_dumping_properties();
633
634
ClassLoader::initialize_shared_path(JavaThread::current());
635
}
636
637
// Preload classes from a list, populate the shared spaces and dump to a
638
// file.
639
void MetaspaceShared::preload_and_dump() {
640
EXCEPTION_MARK;
641
ResourceMark rm(THREAD);
642
preload_and_dump_impl(THREAD);
643
if (HAS_PENDING_EXCEPTION) {
644
if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
645
vm_direct_exit(-1, err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
646
SIZE_FORMAT "M", MaxHeapSize/M));
647
} else {
648
log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
649
java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
650
vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
651
}
652
} else {
653
// On success, the VM_PopulateDumpSharedSpace op should have
654
// exited the VM.
655
ShouldNotReachHere();
656
}
657
}
658
659
void MetaspaceShared::preload_classes(TRAPS) {
660
char default_classlist[JVM_MAXPATHLEN];
661
const char* classlist_path;
662
663
if (SharedClassListFile == NULL) {
664
// Construct the path to the class list (in jre/lib)
665
// Walk up two directories from the location of the VM and
666
// optionally tack on "lib" (depending on platform)
667
os::jvm_path(default_classlist, sizeof(default_classlist));
668
for (int i = 0; i < 3; i++) {
669
char *end = strrchr(default_classlist, *os::file_separator());
670
if (end != NULL) *end = '\0';
671
}
672
int classlist_path_len = (int)strlen(default_classlist);
673
if (classlist_path_len >= 3) {
674
if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
675
if (classlist_path_len < JVM_MAXPATHLEN - 4) {
676
jio_snprintf(default_classlist + classlist_path_len,
677
sizeof(default_classlist) - classlist_path_len,
678
"%slib", os::file_separator());
679
classlist_path_len += 4;
680
}
681
}
682
}
683
if (classlist_path_len < JVM_MAXPATHLEN - 10) {
684
jio_snprintf(default_classlist + classlist_path_len,
685
sizeof(default_classlist) - classlist_path_len,
686
"%sclasslist", os::file_separator());
687
}
688
classlist_path = default_classlist;
689
} else {
690
classlist_path = SharedClassListFile;
691
}
692
693
log_info(cds)("Loading classes to share ...");
694
_has_error_classes = false;
695
int class_count = parse_classlist(classlist_path, CHECK);
696
if (ExtraSharedClassListFile) {
697
class_count += parse_classlist(ExtraSharedClassListFile, CHECK);
698
}
699
700
// Exercise the manifest processing code to ensure classes used by CDS at runtime
701
// are always archived
702
const char* dummy = "Manifest-Version: 1.0\n";
703
SystemDictionaryShared::create_jar_manifest(dummy, strlen(dummy), CHECK);
704
705
log_info(cds)("Loading classes to share: done.");
706
log_info(cds)("Shared spaces: preloaded %d classes", class_count);
707
}
708
709
void MetaspaceShared::preload_and_dump_impl(TRAPS) {
710
preload_classes(CHECK);
711
712
if (SharedArchiveConfigFile) {
713
log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
714
read_extra_data(THREAD, SharedArchiveConfigFile);
715
log_info(cds)("Reading extra data: done.");
716
}
717
718
HeapShared::init_for_dumping(CHECK);
719
720
// Rewrite and link classes
721
log_info(cds)("Rewriting and linking classes ...");
722
723
// Link any classes which got missed. This would happen if we have loaded classes that
724
// were not explicitly specified in the classlist. E.g., if an interface implemented by class K
725
// fails verification, all other interfaces that were not specified in the classlist but
726
// are implemented by K are not verified.
727
link_and_cleanup_shared_classes(CHECK);
728
log_info(cds)("Rewriting and linking classes: done");
729
730
#if INCLUDE_CDS_JAVA_HEAP
731
if (use_full_module_graph()) {
732
HeapShared::reset_archived_object_states(CHECK);
733
}
734
#endif
735
736
VM_PopulateDumpSharedSpace op;
737
VMThread::execute(&op);
738
}
739
740
741
int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {
742
ClassListParser parser(classlist_path);
743
return parser.parse(THREAD); // returns the number of classes loaded.
744
}
745
746
// Returns true if the class's status has changed.
747
bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
748
ExceptionMark em(current);
749
JavaThread* THREAD = current; // For exception macros.
750
Arguments::assert_is_dumping_archive();
751
if (ik->is_loaded() && !ik->is_linked() && ik->can_be_verified_at_dumptime() &&
752
!SystemDictionaryShared::has_class_failed_verification(ik)) {
753
bool saved = BytecodeVerificationLocal;
754
if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
755
// The verification decision is based on BytecodeVerificationRemote
756
// for non-system classes. Since we are using the NULL classloader
757
// to load non-system classes for customized class loaders during dumping,
758
// we need to temporarily change BytecodeVerificationLocal to be the same as
759
// BytecodeVerificationRemote. Note this can cause the parent system
760
// classes also being verified. The extra overhead is acceptable during
761
// dumping.
762
BytecodeVerificationLocal = BytecodeVerificationRemote;
763
}
764
ik->link_class(THREAD);
765
if (HAS_PENDING_EXCEPTION) {
766
ResourceMark rm(THREAD);
767
log_warning(cds)("Preload Warning: Verification failed for %s",
768
ik->external_name());
769
CLEAR_PENDING_EXCEPTION;
770
SystemDictionaryShared::set_class_has_failed_verification(ik);
771
_has_error_classes = true;
772
}
773
BytecodeVerificationLocal = saved;
774
return true;
775
} else {
776
return false;
777
}
778
}
779
780
#if INCLUDE_CDS_JAVA_HEAP
781
void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
782
if(!HeapShared::is_heap_object_archiving_allowed()) {
783
log_info(cds)(
784
"Archived java heap is not supported as UseG1GC, "
785
"UseCompressedOops and UseCompressedClassPointers are required."
786
"Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
787
BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
788
BOOL_TO_STR(UseCompressedClassPointers));
789
return;
790
}
791
// Find all the interned strings that should be dumped.
792
int i;
793
for (i = 0; i < klasses->length(); i++) {
794
Klass* k = klasses->at(i);
795
if (k->is_instance_klass()) {
796
InstanceKlass* ik = InstanceKlass::cast(k);
797
if (ik->is_linked()) {
798
ik->constants()->add_dumped_interned_strings();
799
}
800
}
801
}
802
if (_extra_interned_strings != NULL) {
803
for (i = 0; i < _extra_interned_strings->length(); i ++) {
804
OopHandle string = _extra_interned_strings->at(i);
805
HeapShared::add_to_dumped_interned_strings(string.resolve());
806
}
807
}
808
809
// The closed and open archive heap space has maximum two regions.
810
// See FileMapInfo::write_archive_heap_regions() for details.
811
_closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
812
_open_archive_heap_regions = new GrowableArray<MemRegion>(2);
813
HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
814
_open_archive_heap_regions);
815
ArchiveBuilder::OtherROAllocMark mark;
816
HeapShared::write_subgraph_info_table();
817
}
818
819
void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
820
if (HeapShared::is_heap_object_archiving_allowed()) {
821
_closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
822
dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
823
824
_open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
825
dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
826
}
827
}
828
829
void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
830
GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
831
for (int i=0; i<regions->length(); i++) {
832
ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
833
size_t size_in_bits = oopmap.size();
834
size_t size_in_bytes = oopmap.size_in_bytes();
835
uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
836
oopmap.write_to(buffer, size_in_bytes);
837
log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
838
INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
839
p2i(buffer), size_in_bytes,
840
p2i(regions->at(i).start()), regions->at(i).byte_size());
841
842
ArchiveHeapOopmapInfo info;
843
info._oopmap = (address)buffer;
844
info._oopmap_size_in_bits = size_in_bits;
845
info._oopmap_size_in_bytes = size_in_bytes;
846
oopmaps->append(info);
847
}
848
}
849
#endif // INCLUDE_CDS_JAVA_HEAP
850
851
void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
852
assert(base <= static_top && static_top <= top, "must be");
853
_shared_metaspace_static_top = static_top;
854
MetaspaceObj::set_shared_metaspace_range(base, top);
855
}
856
857
// Return true if given address is in the misc data region
858
bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
859
return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
860
}
861
862
bool MetaspaceShared::is_shared_dynamic(void* p) {
863
if ((p < MetaspaceObj::shared_metaspace_top()) &&
864
(p >= _shared_metaspace_static_top)) {
865
return true;
866
} else {
867
return false;
868
}
869
}
870
871
void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
872
assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
873
MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
874
875
FileMapInfo* static_mapinfo = open_static_archive();
876
FileMapInfo* dynamic_mapinfo = NULL;
877
878
if (static_mapinfo != NULL) {
879
log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
880
dynamic_mapinfo = open_dynamic_archive();
881
882
// First try to map at the requested address
883
result = map_archives(static_mapinfo, dynamic_mapinfo, true);
884
if (result == MAP_ARCHIVE_MMAP_FAILURE) {
885
// Mapping has failed (probably due to ASLR). Let's map at an address chosen
886
// by the OS.
887
log_info(cds)("Try to map archive(s) at an alternative address");
888
result = map_archives(static_mapinfo, dynamic_mapinfo, false);
889
}
890
}
891
892
if (result == MAP_ARCHIVE_SUCCESS) {
893
bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
894
char* cds_base = static_mapinfo->mapped_base();
895
char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
896
set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
897
_relocation_delta = static_mapinfo->relocation_delta();
898
_requested_base_address = static_mapinfo->requested_base_address();
899
if (dynamic_mapped) {
900
FileMapInfo::set_shared_path_table(dynamic_mapinfo);
901
} else {
902
FileMapInfo::set_shared_path_table(static_mapinfo);
903
}
904
} else {
905
set_shared_metaspace_range(NULL, NULL, NULL);
906
UseSharedSpaces = false;
907
FileMapInfo::fail_continue("Unable to map shared spaces");
908
if (PrintSharedArchiveAndExit) {
909
vm_exit_during_initialization("Unable to use shared archive.");
910
}
911
}
912
913
if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
914
delete static_mapinfo;
915
}
916
if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
917
delete dynamic_mapinfo;
918
}
919
}
920
921
FileMapInfo* MetaspaceShared::open_static_archive() {
922
FileMapInfo* mapinfo = new FileMapInfo(true);
923
if (!mapinfo->initialize()) {
924
delete(mapinfo);
925
return NULL;
926
}
927
return mapinfo;
928
}
929
930
FileMapInfo* MetaspaceShared::open_dynamic_archive() {
931
if (DynamicDumpSharedSpaces) {
932
return NULL;
933
}
934
if (Arguments::GetSharedDynamicArchivePath() == NULL) {
935
return NULL;
936
}
937
938
FileMapInfo* mapinfo = new FileMapInfo(false);
939
if (!mapinfo->initialize()) {
940
delete(mapinfo);
941
return NULL;
942
}
943
return mapinfo;
944
}
945
946
// use_requested_addr:
947
// true = map at FileMapHeader::_requested_base_address
948
// false = map at an alternative address picked by OS.
949
MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
950
bool use_requested_addr) {
951
if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
952
log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
953
return MAP_ARCHIVE_MMAP_FAILURE;
954
}
955
956
PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
957
// For product build only -- this is for benchmarking the cost of doing relocation.
958
// For debug builds, the check is done below, after reserving the space, for better test coverage
959
// (see comment below).
960
log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
961
return MAP_ARCHIVE_MMAP_FAILURE;
962
});
963
964
if (ArchiveRelocationMode == 2 && !use_requested_addr) {
965
log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
966
return MAP_ARCHIVE_MMAP_FAILURE;
967
};
968
969
if (dynamic_mapinfo != NULL) {
970
// Ensure that the OS won't be able to allocate new memory spaces between the two
971
// archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
972
assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
973
}
974
975
ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
976
MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
977
char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
978
dynamic_mapinfo,
979
use_requested_addr,
980
total_space_rs,
981
archive_space_rs,
982
class_space_rs);
983
if (mapped_base_address == NULL) {
984
result = MAP_ARCHIVE_MMAP_FAILURE;
985
log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
986
} else {
987
988
#ifdef ASSERT
989
// Some sanity checks after reserving address spaces for archives
990
// and class space.
991
assert(archive_space_rs.is_reserved(), "Sanity");
992
if (Metaspace::using_class_space()) {
993
// Class space must closely follow the archive space. Both spaces
994
// must be aligned correctly.
995
assert(class_space_rs.is_reserved(),
996
"A class space should have been reserved");
997
assert(class_space_rs.base() >= archive_space_rs.end(),
998
"class space should follow the cds archive space");
999
assert(is_aligned(archive_space_rs.base(),
1000
core_region_alignment()),
1001
"Archive space misaligned");
1002
assert(is_aligned(class_space_rs.base(),
1003
Metaspace::reserve_alignment()),
1004
"class space misaligned");
1005
}
1006
#endif // ASSERT
1007
1008
log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1009
p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1010
log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1011
p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1012
1013
if (MetaspaceShared::use_windows_memory_mapping()) {
1014
// We have now reserved address space for the archives, and will map in
1015
// the archive files into this space.
1016
//
1017
// Special handling for Windows: on Windows we cannot map a file view
1018
// into an existing memory mapping. So, we unmap the address range we
1019
// just reserved again, which will make it available for mapping the
1020
// archives.
1021
// Reserving this range has not been for naught however since it makes
1022
// us reasonably sure the address range is available.
1023
//
1024
// But still it may fail, since between unmapping the range and mapping
1025
// in the archive someone else may grab the address space. Therefore
1026
// there is a fallback in FileMap::map_region() where we just read in
1027
// the archive files sequentially instead of mapping it in. We couple
1028
// this with use_requested_addr, since we're going to patch all the
1029
// pointers anyway so there's no benefit to mmap.
1030
if (use_requested_addr) {
1031
assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1032
log_info(cds)("Windows mmap workaround: releasing archive space.");
1033
archive_space_rs.release();
1034
}
1035
}
1036
MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1037
MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1038
map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1039
1040
DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1041
// This is for simulating mmap failures at the requested address. In
1042
// debug builds, we do it here (after all archives have possibly been
1043
// mapped), so we can thoroughly test the code for failure handling
1044
// (releasing all allocated resource, etc).
1045
log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1046
if (static_result == MAP_ARCHIVE_SUCCESS) {
1047
static_result = MAP_ARCHIVE_MMAP_FAILURE;
1048
}
1049
if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1050
dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1051
}
1052
});
1053
1054
if (static_result == MAP_ARCHIVE_SUCCESS) {
1055
if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1056
result = MAP_ARCHIVE_SUCCESS;
1057
} else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1058
assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1059
// No need to retry mapping the dynamic archive again, as it will never succeed
1060
// (bad file, etc) -- just keep the base archive.
1061
log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1062
dynamic_mapinfo->full_path());
1063
result = MAP_ARCHIVE_SUCCESS;
1064
// TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1065
// easy API to do that right now.
1066
} else {
1067
result = MAP_ARCHIVE_MMAP_FAILURE;
1068
}
1069
} else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1070
result = MAP_ARCHIVE_OTHER_FAILURE;
1071
} else {
1072
result = MAP_ARCHIVE_MMAP_FAILURE;
1073
}
1074
}
1075
1076
if (result == MAP_ARCHIVE_SUCCESS) {
1077
SharedBaseAddress = (size_t)mapped_base_address;
1078
LP64_ONLY({
1079
if (Metaspace::using_class_space()) {
1080
// Set up ccs in metaspace.
1081
Metaspace::initialize_class_space(class_space_rs);
1082
1083
// Set up compressed Klass pointer encoding: the encoding range must
1084
// cover both archive and class space.
1085
address cds_base = (address)static_mapinfo->mapped_base();
1086
address ccs_end = (address)class_space_rs.end();
1087
assert(ccs_end > cds_base, "Sanity check");
1088
CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1089
1090
// map_heap_regions() compares the current narrow oop and klass encodings
1091
// with the archived ones, so it must be done after all encodings are determined.
1092
static_mapinfo->map_heap_regions();
1093
}
1094
});
1095
log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1096
log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1097
} else {
1098
unmap_archive(static_mapinfo);
1099
unmap_archive(dynamic_mapinfo);
1100
release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1101
}
1102
1103
return result;
1104
}
1105
1106
1107
// This will reserve two address spaces suitable to house Klass structures, one
1108
// for the cds archives (static archive and optionally dynamic archive) and
1109
// optionally one move for ccs.
1110
//
1111
// Since both spaces must fall within the compressed class pointer encoding
1112
// range, they are allocated close to each other.
1113
//
1114
// Space for archives will be reserved first, followed by a potential gap,
1115
// followed by the space for ccs:
1116
//
1117
// +-- Base address A B End
1118
// | | | |
1119
// v v v v
1120
// +-------------+--------------+ +----------------------+
1121
// | static arc | [dyn. arch] | [gap] | compr. class space |
1122
// +-------------+--------------+ +----------------------+
1123
//
1124
// (The gap may result from different alignment requirements between metaspace
1125
// and CDS)
1126
//
1127
// If UseCompressedClassPointers is disabled, only one address space will be
1128
// reserved:
1129
//
1130
// +-- Base address End
1131
// | |
1132
// v v
1133
// +-------------+--------------+
1134
// | static arc | [dyn. arch] |
1135
// +-------------+--------------+
1136
//
1137
// Base address: If use_archive_base_addr address is true, the Base address is
1138
// determined by the address stored in the static archive. If
1139
// use_archive_base_addr address is false, this base address is determined
1140
// by the platform.
1141
//
1142
// If UseCompressedClassPointers=1, the range encompassing both spaces will be
1143
// suitable to en/decode narrow Klass pointers: the base will be valid for
1144
// encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1145
//
1146
// Return:
1147
//
1148
// - On success:
1149
// - total_space_rs will be reserved as whole for archive_space_rs and
1150
// class_space_rs if UseCompressedClassPointers is true.
1151
// On Windows, try reserve archive_space_rs and class_space_rs
1152
// separately first if use_archive_base_addr is true.
1153
// - archive_space_rs will be reserved and large enough to host static and
1154
// if needed dynamic archive: [Base, A).
1155
// archive_space_rs.base and size will be aligned to CDS reserve
1156
// granularity.
1157
// - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1158
// be reserved. Its start address will be aligned to metaspace reserve
1159
// alignment, which may differ from CDS alignment. It will follow the cds
1160
// archive space, close enough such that narrow class pointer encoding
1161
// covers both spaces.
1162
// If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1163
// - On error: NULL is returned and the spaces remain unreserved.
1164
char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1165
FileMapInfo* dynamic_mapinfo,
1166
bool use_archive_base_addr,
1167
ReservedSpace& total_space_rs,
1168
ReservedSpace& archive_space_rs,
1169
ReservedSpace& class_space_rs) {
1170
1171
address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1172
const size_t archive_space_alignment = core_region_alignment();
1173
1174
// Size and requested location of the archive_space_rs (for both static and dynamic archives)
1175
assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1176
size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1177
size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1178
1179
// If a base address is given, it must have valid alignment and be suitable as encoding base.
1180
if (base_address != NULL) {
1181
assert(is_aligned(base_address, archive_space_alignment),
1182
"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1183
if (Metaspace::using_class_space()) {
1184
assert(CompressedKlassPointers::is_valid_base(base_address),
1185
"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1186
}
1187
}
1188
1189
if (!Metaspace::using_class_space()) {
1190
// Get the simple case out of the way first:
1191
// no compressed class space, simple allocation.
1192
archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1193
os::vm_page_size(), (char*)base_address);
1194
if (archive_space_rs.is_reserved()) {
1195
assert(base_address == NULL ||
1196
(address)archive_space_rs.base() == base_address, "Sanity");
1197
// Register archive space with NMT.
1198
MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1199
return archive_space_rs.base();
1200
}
1201
return NULL;
1202
}
1203
1204
#ifdef _LP64
1205
1206
// Complex case: two spaces adjacent to each other, both to be addressable
1207
// with narrow class pointers.
1208
// We reserve the whole range spanning both spaces, then split that range up.
1209
1210
const size_t class_space_alignment = Metaspace::reserve_alignment();
1211
1212
// To simplify matters, lets assume that metaspace alignment will always be
1213
// equal or a multiple of archive alignment.
1214
assert(is_power_of_2(class_space_alignment) &&
1215
is_power_of_2(archive_space_alignment) &&
1216
class_space_alignment >= archive_space_alignment,
1217
"Sanity");
1218
1219
const size_t class_space_size = CompressedClassSpaceSize;
1220
assert(CompressedClassSpaceSize > 0 &&
1221
is_aligned(CompressedClassSpaceSize, class_space_alignment),
1222
"CompressedClassSpaceSize malformed: "
1223
SIZE_FORMAT, CompressedClassSpaceSize);
1224
1225
const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1226
class_space_alignment) - base_address;
1227
const size_t gap_size = ccs_begin_offset - archive_space_size;
1228
1229
const size_t total_range_size =
1230
align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());
1231
1232
assert(total_range_size > ccs_begin_offset, "must be");
1233
if (use_windows_memory_mapping() && use_archive_base_addr) {
1234
if (base_address != nullptr) {
1235
// On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1236
// Hence, we optimistically reserve archive space and class space side-by-side. We only
1237
// do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1238
// caller will not split the combined space for mapping, instead read the archive data
1239
// via sequential file IO.
1240
address ccs_base = base_address + archive_space_size + gap_size;
1241
archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1242
os::vm_page_size(), (char*)base_address);
1243
class_space_rs = ReservedSpace(class_space_size, class_space_alignment,
1244
os::vm_page_size(), (char*)ccs_base);
1245
}
1246
if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1247
release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1248
return NULL;
1249
}
1250
} else {
1251
if (use_archive_base_addr && base_address != nullptr) {
1252
total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,
1253
os::vm_page_size(), (char*) base_address);
1254
} else {
1255
// Reserve at any address, but leave it up to the platform to choose a good one.
1256
total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1257
}
1258
1259
if (!total_space_rs.is_reserved()) {
1260
return NULL;
1261
}
1262
1263
// Paranoid checks:
1264
assert(base_address == NULL || (address)total_space_rs.base() == base_address,
1265
"Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1266
assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");
1267
assert(total_space_rs.size() == total_range_size, "Sanity");
1268
assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");
1269
1270
// Now split up the space into ccs and cds archive. For simplicity, just leave
1271
// the gap reserved at the end of the archive space. Do not do real splitting.
1272
archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1273
(size_t)archive_space_alignment);
1274
class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1275
MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1276
ccs_begin_offset);
1277
}
1278
assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1279
assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1280
assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1281
assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1282
1283
// NMT: fix up the space tags
1284
MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1285
MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1286
1287
return archive_space_rs.base();
1288
1289
#else
1290
ShouldNotReachHere();
1291
return NULL;
1292
#endif
1293
1294
}
1295
1296
void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1297
ReservedSpace& archive_space_rs,
1298
ReservedSpace& class_space_rs) {
1299
if (total_space_rs.is_reserved()) {
1300
log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1301
total_space_rs.release();
1302
} else {
1303
if (archive_space_rs.is_reserved()) {
1304
log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1305
archive_space_rs.release();
1306
}
1307
if (class_space_rs.is_reserved()) {
1308
log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1309
class_space_rs.release();
1310
}
1311
}
1312
}
1313
1314
static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1315
static int archive_regions_count = 2;
1316
1317
MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1318
assert(UseSharedSpaces, "must be runtime");
1319
if (mapinfo == NULL) {
1320
return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1321
}
1322
1323
mapinfo->set_is_mapped(false);
1324
if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1325
log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1326
" actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1327
return MAP_ARCHIVE_OTHER_FAILURE;
1328
}
1329
1330
MapArchiveResult result =
1331
mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1332
1333
if (result != MAP_ARCHIVE_SUCCESS) {
1334
unmap_archive(mapinfo);
1335
return result;
1336
}
1337
1338
if (!mapinfo->validate_shared_path_table()) {
1339
unmap_archive(mapinfo);
1340
return MAP_ARCHIVE_OTHER_FAILURE;
1341
}
1342
1343
mapinfo->set_is_mapped(true);
1344
return MAP_ARCHIVE_SUCCESS;
1345
}
1346
1347
void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1348
assert(UseSharedSpaces, "must be runtime");
1349
if (mapinfo != NULL) {
1350
mapinfo->unmap_regions(archive_regions, archive_regions_count);
1351
mapinfo->unmap_region(MetaspaceShared::bm);
1352
mapinfo->set_is_mapped(false);
1353
}
1354
}
1355
1356
// For -XX:PrintSharedArchiveAndExit
1357
class CountSharedSymbols : public SymbolClosure {
1358
private:
1359
int _count;
1360
public:
1361
CountSharedSymbols() : _count(0) {}
1362
void do_symbol(Symbol** sym) {
1363
_count++;
1364
}
1365
int total() { return _count; }
1366
1367
};
1368
1369
// Read the miscellaneous data from the shared file, and
1370
// serialize it out to its various destinations.
1371
1372
void MetaspaceShared::initialize_shared_spaces() {
1373
FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1374
1375
// Verify various attributes of the archive, plus initialize the
1376
// shared string/symbol tables
1377
char* buffer = static_mapinfo->serialized_data();
1378
intptr_t* array = (intptr_t*)buffer;
1379
ReadClosure rc(&array);
1380
serialize(&rc);
1381
1382
// Initialize the run-time symbol table.
1383
SymbolTable::create_table();
1384
1385
static_mapinfo->patch_archived_heap_embedded_pointers();
1386
1387
// Close the mapinfo file
1388
static_mapinfo->close();
1389
1390
static_mapinfo->unmap_region(MetaspaceShared::bm);
1391
1392
FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1393
if (dynamic_mapinfo != NULL) {
1394
intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1395
ReadClosure rc(&buffer);
1396
SymbolTable::serialize_shared_table_header(&rc, false);
1397
SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1398
dynamic_mapinfo->close();
1399
dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1400
}
1401
1402
// Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1403
if (DynamicDumpSharedSpaces) {
1404
// Read stored LF format lines stored in static archive
1405
LambdaFormInvokers::read_static_archive_invokers();
1406
}
1407
1408
if (PrintSharedArchiveAndExit) {
1409
// Print archive names
1410
if (dynamic_mapinfo != nullptr) {
1411
tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());
1412
tty->print_cr("Base archive version %d", static_mapinfo->version());
1413
} else {
1414
tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1415
tty->print_cr("Static archive version %d", static_mapinfo->version());
1416
}
1417
1418
SystemDictionaryShared::print_shared_archive(tty);
1419
if (dynamic_mapinfo != nullptr) {
1420
tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1421
tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1422
SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1423
}
1424
1425
// collect shared symbols and strings
1426
CountSharedSymbols cl;
1427
SymbolTable::shared_symbols_do(&cl);
1428
tty->print_cr("Number of shared symbols: %d", cl.total());
1429
tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1430
tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1431
if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
1432
tty->print_cr("archive is invalid");
1433
vm_exit(1);
1434
} else {
1435
tty->print_cr("archive is valid");
1436
vm_exit(0);
1437
}
1438
}
1439
}
1440
1441
// JVM/TI RedefineClasses() support:
1442
bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1443
assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1444
1445
if (UseSharedSpaces) {
1446
// remap the shared readonly space to shared readwrite, private
1447
FileMapInfo* mapinfo = FileMapInfo::current_info();
1448
if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1449
return false;
1450
}
1451
if (FileMapInfo::dynamic_info() != NULL) {
1452
mapinfo = FileMapInfo::dynamic_info();
1453
if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1454
return false;
1455
}
1456
}
1457
_remapped_readwrite = true;
1458
}
1459
return true;
1460
}
1461
1462
bool MetaspaceShared::use_full_module_graph() {
1463
#if INCLUDE_CDS_JAVA_HEAP
1464
if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1465
return true;
1466
}
1467
#endif
1468
bool result = _use_optimized_module_handling && _use_full_module_graph &&
1469
(UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();
1470
if (result && UseSharedSpaces) {
1471
// Classes used by the archived full module graph are loaded in JVMTI early phase.
1472
assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1473
"CDS should be disabled if early class hooks are enabled");
1474
}
1475
return result;
1476
}
1477
1478
void MetaspaceShared::print_on(outputStream* st) {
1479
if (UseSharedSpaces) {
1480
st->print("CDS archive(s) mapped at: ");
1481
address base = (address)MetaspaceObj::shared_metaspace_base();
1482
address static_top = (address)_shared_metaspace_static_top;
1483
address top = (address)MetaspaceObj::shared_metaspace_top();
1484
st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1485
st->print("size " SIZE_FORMAT ", ", top - base);
1486
st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
1487
} else {
1488
st->print("CDS archive(s) not mapped");
1489
}
1490
st->cr();
1491
}
1492
1493