Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/cds/metaspaceShared.cpp
41144 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
// At this point, many classes have been loaded.
488
// Gather systemDictionary classes in a global array and do everything to
489
// that so we don't have to walk the SystemDictionary again.
490
SystemDictionaryShared::check_excluded_classes();
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
public:
555
CollectCLDClosure() {}
556
~CollectCLDClosure() {
557
for (int i = 0; i < _loaded_cld.length(); i++) {
558
ClassLoaderData* cld = _loaded_cld.at(i);
559
cld->dec_keep_alive();
560
}
561
}
562
void do_cld(ClassLoaderData* cld) {
563
if (!cld->is_unloading()) {
564
cld->inc_keep_alive();
565
_loaded_cld.append(cld);
566
}
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
// Collect all loaded ClassLoaderData.
596
ResourceMark rm;
597
598
LambdaFormInvokers::regenerate_holder_classes(CHECK);
599
CollectCLDClosure collect_cld;
600
{
601
// ClassLoaderDataGraph::loaded_cld_do requires ClassLoaderDataGraph_lock.
602
// We cannot link the classes while holding this lock (or else we may run into deadlock).
603
// Therefore, we need to first collect all the CLDs, and then link their classes after
604
// releasing the lock.
605
MutexLocker lock(ClassLoaderDataGraph_lock);
606
ClassLoaderDataGraph::loaded_cld_do(&collect_cld);
607
}
608
609
while (true) {
610
bool has_linked = false;
611
for (int i = 0; i < collect_cld.nof_cld(); i++) {
612
ClassLoaderData* cld = collect_cld.cld_at(i);
613
for (Klass* klass = cld->klasses(); klass != NULL; klass = klass->next_link()) {
614
if (klass->is_instance_klass()) {
615
InstanceKlass* ik = InstanceKlass::cast(klass);
616
if (linking_required(ik)) {
617
has_linked |= link_class_for_cds(ik, CHECK);
618
}
619
}
620
}
621
}
622
623
if (!has_linked) {
624
break;
625
}
626
// Class linking includes verification which may load more classes.
627
// Keep scanning until we have linked no more classes.
628
}
629
}
630
631
void MetaspaceShared::prepare_for_dumping() {
632
Arguments::assert_is_dumping_archive();
633
Arguments::check_unsupported_dumping_properties();
634
635
ClassLoader::initialize_shared_path(JavaThread::current());
636
}
637
638
// Preload classes from a list, populate the shared spaces and dump to a
639
// file.
640
void MetaspaceShared::preload_and_dump() {
641
EXCEPTION_MARK;
642
ResourceMark rm(THREAD);
643
preload_and_dump_impl(THREAD);
644
if (HAS_PENDING_EXCEPTION) {
645
if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
646
vm_direct_exit(-1, err_msg("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
647
SIZE_FORMAT "M", MaxHeapSize/M));
648
} else {
649
log_error(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
650
java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
651
vm_direct_exit(-1, "VM exits due to exception, use -Xlog:cds,exceptions=trace for detail");
652
}
653
} else {
654
// On success, the VM_PopulateDumpSharedSpace op should have
655
// exited the VM.
656
ShouldNotReachHere();
657
}
658
}
659
660
void MetaspaceShared::preload_classes(TRAPS) {
661
char default_classlist[JVM_MAXPATHLEN];
662
const char* classlist_path;
663
664
if (SharedClassListFile == NULL) {
665
// Construct the path to the class list (in jre/lib)
666
// Walk up two directories from the location of the VM and
667
// optionally tack on "lib" (depending on platform)
668
os::jvm_path(default_classlist, sizeof(default_classlist));
669
for (int i = 0; i < 3; i++) {
670
char *end = strrchr(default_classlist, *os::file_separator());
671
if (end != NULL) *end = '\0';
672
}
673
int classlist_path_len = (int)strlen(default_classlist);
674
if (classlist_path_len >= 3) {
675
if (strcmp(default_classlist + classlist_path_len - 3, "lib") != 0) {
676
if (classlist_path_len < JVM_MAXPATHLEN - 4) {
677
jio_snprintf(default_classlist + classlist_path_len,
678
sizeof(default_classlist) - classlist_path_len,
679
"%slib", os::file_separator());
680
classlist_path_len += 4;
681
}
682
}
683
}
684
if (classlist_path_len < JVM_MAXPATHLEN - 10) {
685
jio_snprintf(default_classlist + classlist_path_len,
686
sizeof(default_classlist) - classlist_path_len,
687
"%sclasslist", os::file_separator());
688
}
689
classlist_path = default_classlist;
690
} else {
691
classlist_path = SharedClassListFile;
692
}
693
694
log_info(cds)("Loading classes to share ...");
695
_has_error_classes = false;
696
int class_count = parse_classlist(classlist_path, CHECK);
697
if (ExtraSharedClassListFile) {
698
class_count += parse_classlist(ExtraSharedClassListFile, CHECK);
699
}
700
701
// Exercise the manifest processing code to ensure classes used by CDS at runtime
702
// are always archived
703
const char* dummy = "Manifest-Version: 1.0\n";
704
SystemDictionaryShared::create_jar_manifest(dummy, strlen(dummy), CHECK);
705
706
log_info(cds)("Loading classes to share: done.");
707
log_info(cds)("Shared spaces: preloaded %d classes", class_count);
708
}
709
710
void MetaspaceShared::preload_and_dump_impl(TRAPS) {
711
preload_classes(CHECK);
712
713
if (SharedArchiveConfigFile) {
714
log_info(cds)("Reading extra data from %s ...", SharedArchiveConfigFile);
715
read_extra_data(THREAD, SharedArchiveConfigFile);
716
log_info(cds)("Reading extra data: done.");
717
}
718
719
HeapShared::init_for_dumping(CHECK);
720
721
// Rewrite and link classes
722
log_info(cds)("Rewriting and linking classes ...");
723
724
// Link any classes which got missed. This would happen if we have loaded classes that
725
// were not explicitly specified in the classlist. E.g., if an interface implemented by class K
726
// fails verification, all other interfaces that were not specified in the classlist but
727
// are implemented by K are not verified.
728
link_and_cleanup_shared_classes(CHECK);
729
log_info(cds)("Rewriting and linking classes: done");
730
731
#if INCLUDE_CDS_JAVA_HEAP
732
if (use_full_module_graph()) {
733
HeapShared::reset_archived_object_states(CHECK);
734
}
735
#endif
736
737
VM_PopulateDumpSharedSpace op;
738
VMThread::execute(&op);
739
}
740
741
742
int MetaspaceShared::parse_classlist(const char* classlist_path, TRAPS) {
743
ClassListParser parser(classlist_path);
744
return parser.parse(THREAD); // returns the number of classes loaded.
745
}
746
747
// Returns true if the class's status has changed.
748
bool MetaspaceShared::try_link_class(JavaThread* current, InstanceKlass* ik) {
749
ExceptionMark em(current);
750
JavaThread* THREAD = current; // For exception macros.
751
Arguments::assert_is_dumping_archive();
752
if (ik->is_loaded() && !ik->is_linked() && !ik->can_be_verified_at_dumptime() &&
753
!SystemDictionaryShared::has_class_failed_verification(ik)) {
754
bool saved = BytecodeVerificationLocal;
755
if (ik->is_shared_unregistered_class() && ik->class_loader() == NULL) {
756
// The verification decision is based on BytecodeVerificationRemote
757
// for non-system classes. Since we are using the NULL classloader
758
// to load non-system classes for customized class loaders during dumping,
759
// we need to temporarily change BytecodeVerificationLocal to be the same as
760
// BytecodeVerificationRemote. Note this can cause the parent system
761
// classes also being verified. The extra overhead is acceptable during
762
// dumping.
763
BytecodeVerificationLocal = BytecodeVerificationRemote;
764
}
765
ik->link_class(THREAD);
766
if (HAS_PENDING_EXCEPTION) {
767
ResourceMark rm(THREAD);
768
log_warning(cds)("Preload Warning: Verification failed for %s",
769
ik->external_name());
770
CLEAR_PENDING_EXCEPTION;
771
SystemDictionaryShared::set_class_has_failed_verification(ik);
772
_has_error_classes = true;
773
}
774
BytecodeVerificationLocal = saved;
775
return true;
776
} else {
777
return false;
778
}
779
}
780
781
#if INCLUDE_CDS_JAVA_HEAP
782
void VM_PopulateDumpSharedSpace::dump_java_heap_objects(GrowableArray<Klass*>* klasses) {
783
if(!HeapShared::is_heap_object_archiving_allowed()) {
784
log_info(cds)(
785
"Archived java heap is not supported as UseG1GC, "
786
"UseCompressedOops and UseCompressedClassPointers are required."
787
"Current settings: UseG1GC=%s, UseCompressedOops=%s, UseCompressedClassPointers=%s.",
788
BOOL_TO_STR(UseG1GC), BOOL_TO_STR(UseCompressedOops),
789
BOOL_TO_STR(UseCompressedClassPointers));
790
return;
791
}
792
// Find all the interned strings that should be dumped.
793
int i;
794
for (i = 0; i < klasses->length(); i++) {
795
Klass* k = klasses->at(i);
796
if (k->is_instance_klass()) {
797
InstanceKlass* ik = InstanceKlass::cast(k);
798
if (ik->is_linked()) {
799
ik->constants()->add_dumped_interned_strings();
800
}
801
}
802
}
803
if (_extra_interned_strings != NULL) {
804
for (i = 0; i < _extra_interned_strings->length(); i ++) {
805
OopHandle string = _extra_interned_strings->at(i);
806
HeapShared::add_to_dumped_interned_strings(string.resolve());
807
}
808
}
809
810
// The closed and open archive heap space has maximum two regions.
811
// See FileMapInfo::write_archive_heap_regions() for details.
812
_closed_archive_heap_regions = new GrowableArray<MemRegion>(2);
813
_open_archive_heap_regions = new GrowableArray<MemRegion>(2);
814
HeapShared::archive_java_heap_objects(_closed_archive_heap_regions,
815
_open_archive_heap_regions);
816
ArchiveBuilder::OtherROAllocMark mark;
817
HeapShared::write_subgraph_info_table();
818
}
819
820
void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps() {
821
if (HeapShared::is_heap_object_archiving_allowed()) {
822
_closed_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
823
dump_archive_heap_oopmaps(_closed_archive_heap_regions, _closed_archive_heap_oopmaps);
824
825
_open_archive_heap_oopmaps = new GrowableArray<ArchiveHeapOopmapInfo>(2);
826
dump_archive_heap_oopmaps(_open_archive_heap_regions, _open_archive_heap_oopmaps);
827
}
828
}
829
830
void VM_PopulateDumpSharedSpace::dump_archive_heap_oopmaps(GrowableArray<MemRegion>* regions,
831
GrowableArray<ArchiveHeapOopmapInfo>* oopmaps) {
832
for (int i=0; i<regions->length(); i++) {
833
ResourceBitMap oopmap = HeapShared::calculate_oopmap(regions->at(i));
834
size_t size_in_bits = oopmap.size();
835
size_t size_in_bytes = oopmap.size_in_bytes();
836
uintptr_t* buffer = (uintptr_t*)NEW_C_HEAP_ARRAY(char, size_in_bytes, mtInternal);
837
oopmap.write_to(buffer, size_in_bytes);
838
log_info(cds, heap)("Oopmap = " INTPTR_FORMAT " (" SIZE_FORMAT_W(6) " bytes) for heap region "
839
INTPTR_FORMAT " (" SIZE_FORMAT_W(8) " bytes)",
840
p2i(buffer), size_in_bytes,
841
p2i(regions->at(i).start()), regions->at(i).byte_size());
842
843
ArchiveHeapOopmapInfo info;
844
info._oopmap = (address)buffer;
845
info._oopmap_size_in_bits = size_in_bits;
846
info._oopmap_size_in_bytes = size_in_bytes;
847
oopmaps->append(info);
848
}
849
}
850
#endif // INCLUDE_CDS_JAVA_HEAP
851
852
void MetaspaceShared::set_shared_metaspace_range(void* base, void *static_top, void* top) {
853
assert(base <= static_top && static_top <= top, "must be");
854
_shared_metaspace_static_top = static_top;
855
MetaspaceObj::set_shared_metaspace_range(base, top);
856
}
857
858
// Return true if given address is in the misc data region
859
bool MetaspaceShared::is_in_shared_region(const void* p, int idx) {
860
return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_region(p, idx);
861
}
862
863
bool MetaspaceShared::is_shared_dynamic(void* p) {
864
if ((p < MetaspaceObj::shared_metaspace_top()) &&
865
(p >= _shared_metaspace_static_top)) {
866
return true;
867
} else {
868
return false;
869
}
870
}
871
872
void MetaspaceShared::initialize_runtime_shared_and_meta_spaces() {
873
assert(UseSharedSpaces, "Must be called when UseSharedSpaces is enabled");
874
MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
875
876
FileMapInfo* static_mapinfo = open_static_archive();
877
FileMapInfo* dynamic_mapinfo = NULL;
878
879
if (static_mapinfo != NULL) {
880
log_info(cds)("Core region alignment: " SIZE_FORMAT, static_mapinfo->core_region_alignment());
881
dynamic_mapinfo = open_dynamic_archive();
882
883
// First try to map at the requested address
884
result = map_archives(static_mapinfo, dynamic_mapinfo, true);
885
if (result == MAP_ARCHIVE_MMAP_FAILURE) {
886
// Mapping has failed (probably due to ASLR). Let's map at an address chosen
887
// by the OS.
888
log_info(cds)("Try to map archive(s) at an alternative address");
889
result = map_archives(static_mapinfo, dynamic_mapinfo, false);
890
}
891
}
892
893
if (result == MAP_ARCHIVE_SUCCESS) {
894
bool dynamic_mapped = (dynamic_mapinfo != NULL && dynamic_mapinfo->is_mapped());
895
char* cds_base = static_mapinfo->mapped_base();
896
char* cds_end = dynamic_mapped ? dynamic_mapinfo->mapped_end() : static_mapinfo->mapped_end();
897
set_shared_metaspace_range(cds_base, static_mapinfo->mapped_end(), cds_end);
898
_relocation_delta = static_mapinfo->relocation_delta();
899
_requested_base_address = static_mapinfo->requested_base_address();
900
if (dynamic_mapped) {
901
FileMapInfo::set_shared_path_table(dynamic_mapinfo);
902
} else {
903
FileMapInfo::set_shared_path_table(static_mapinfo);
904
}
905
} else {
906
set_shared_metaspace_range(NULL, NULL, NULL);
907
UseSharedSpaces = false;
908
FileMapInfo::fail_continue("Unable to map shared spaces");
909
if (PrintSharedArchiveAndExit) {
910
vm_exit_during_initialization("Unable to use shared archive.");
911
}
912
}
913
914
if (static_mapinfo != NULL && !static_mapinfo->is_mapped()) {
915
delete static_mapinfo;
916
}
917
if (dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped()) {
918
delete dynamic_mapinfo;
919
}
920
}
921
922
FileMapInfo* MetaspaceShared::open_static_archive() {
923
FileMapInfo* mapinfo = new FileMapInfo(true);
924
if (!mapinfo->initialize()) {
925
delete(mapinfo);
926
return NULL;
927
}
928
return mapinfo;
929
}
930
931
FileMapInfo* MetaspaceShared::open_dynamic_archive() {
932
if (DynamicDumpSharedSpaces) {
933
return NULL;
934
}
935
if (Arguments::GetSharedDynamicArchivePath() == NULL) {
936
return NULL;
937
}
938
939
FileMapInfo* mapinfo = new FileMapInfo(false);
940
if (!mapinfo->initialize()) {
941
delete(mapinfo);
942
return NULL;
943
}
944
return mapinfo;
945
}
946
947
// use_requested_addr:
948
// true = map at FileMapHeader::_requested_base_address
949
// false = map at an alternative address picked by OS.
950
MapArchiveResult MetaspaceShared::map_archives(FileMapInfo* static_mapinfo, FileMapInfo* dynamic_mapinfo,
951
bool use_requested_addr) {
952
if (use_requested_addr && static_mapinfo->requested_base_address() == NULL) {
953
log_info(cds)("Archive(s) were created with -XX:SharedBaseAddress=0. Always map at os-selected address.");
954
return MAP_ARCHIVE_MMAP_FAILURE;
955
}
956
957
PRODUCT_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
958
// For product build only -- this is for benchmarking the cost of doing relocation.
959
// For debug builds, the check is done below, after reserving the space, for better test coverage
960
// (see comment below).
961
log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
962
return MAP_ARCHIVE_MMAP_FAILURE;
963
});
964
965
if (ArchiveRelocationMode == 2 && !use_requested_addr) {
966
log_info(cds)("ArchiveRelocationMode == 2: never map archive(s) at an alternative address");
967
return MAP_ARCHIVE_MMAP_FAILURE;
968
};
969
970
if (dynamic_mapinfo != NULL) {
971
// Ensure that the OS won't be able to allocate new memory spaces between the two
972
// archives, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
973
assert(static_mapinfo->mapping_end_offset() == dynamic_mapinfo->mapping_base_offset(), "no gap");
974
}
975
976
ReservedSpace total_space_rs, archive_space_rs, class_space_rs;
977
MapArchiveResult result = MAP_ARCHIVE_OTHER_FAILURE;
978
char* mapped_base_address = reserve_address_space_for_archives(static_mapinfo,
979
dynamic_mapinfo,
980
use_requested_addr,
981
total_space_rs,
982
archive_space_rs,
983
class_space_rs);
984
if (mapped_base_address == NULL) {
985
result = MAP_ARCHIVE_MMAP_FAILURE;
986
log_debug(cds)("Failed to reserve spaces (use_requested_addr=%u)", (unsigned)use_requested_addr);
987
} else {
988
989
#ifdef ASSERT
990
// Some sanity checks after reserving address spaces for archives
991
// and class space.
992
assert(archive_space_rs.is_reserved(), "Sanity");
993
if (Metaspace::using_class_space()) {
994
// Class space must closely follow the archive space. Both spaces
995
// must be aligned correctly.
996
assert(class_space_rs.is_reserved(),
997
"A class space should have been reserved");
998
assert(class_space_rs.base() >= archive_space_rs.end(),
999
"class space should follow the cds archive space");
1000
assert(is_aligned(archive_space_rs.base(),
1001
core_region_alignment()),
1002
"Archive space misaligned");
1003
assert(is_aligned(class_space_rs.base(),
1004
Metaspace::reserve_alignment()),
1005
"class space misaligned");
1006
}
1007
#endif // ASSERT
1008
1009
log_info(cds)("Reserved archive_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1010
p2i(archive_space_rs.base()), p2i(archive_space_rs.end()), archive_space_rs.size());
1011
log_info(cds)("Reserved class_space_rs [" INTPTR_FORMAT " - " INTPTR_FORMAT "] (" SIZE_FORMAT ") bytes",
1012
p2i(class_space_rs.base()), p2i(class_space_rs.end()), class_space_rs.size());
1013
1014
if (MetaspaceShared::use_windows_memory_mapping()) {
1015
// We have now reserved address space for the archives, and will map in
1016
// the archive files into this space.
1017
//
1018
// Special handling for Windows: on Windows we cannot map a file view
1019
// into an existing memory mapping. So, we unmap the address range we
1020
// just reserved again, which will make it available for mapping the
1021
// archives.
1022
// Reserving this range has not been for naught however since it makes
1023
// us reasonably sure the address range is available.
1024
//
1025
// But still it may fail, since between unmapping the range and mapping
1026
// in the archive someone else may grab the address space. Therefore
1027
// there is a fallback in FileMap::map_region() where we just read in
1028
// the archive files sequentially instead of mapping it in. We couple
1029
// this with use_requested_addr, since we're going to patch all the
1030
// pointers anyway so there's no benefit to mmap.
1031
if (use_requested_addr) {
1032
assert(!total_space_rs.is_reserved(), "Should not be reserved for Windows");
1033
log_info(cds)("Windows mmap workaround: releasing archive space.");
1034
archive_space_rs.release();
1035
}
1036
}
1037
MapArchiveResult static_result = map_archive(static_mapinfo, mapped_base_address, archive_space_rs);
1038
MapArchiveResult dynamic_result = (static_result == MAP_ARCHIVE_SUCCESS) ?
1039
map_archive(dynamic_mapinfo, mapped_base_address, archive_space_rs) : MAP_ARCHIVE_OTHER_FAILURE;
1040
1041
DEBUG_ONLY(if (ArchiveRelocationMode == 1 && use_requested_addr) {
1042
// This is for simulating mmap failures at the requested address. In
1043
// debug builds, we do it here (after all archives have possibly been
1044
// mapped), so we can thoroughly test the code for failure handling
1045
// (releasing all allocated resource, etc).
1046
log_info(cds)("ArchiveRelocationMode == 1: always map archive(s) at an alternative address");
1047
if (static_result == MAP_ARCHIVE_SUCCESS) {
1048
static_result = MAP_ARCHIVE_MMAP_FAILURE;
1049
}
1050
if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1051
dynamic_result = MAP_ARCHIVE_MMAP_FAILURE;
1052
}
1053
});
1054
1055
if (static_result == MAP_ARCHIVE_SUCCESS) {
1056
if (dynamic_result == MAP_ARCHIVE_SUCCESS) {
1057
result = MAP_ARCHIVE_SUCCESS;
1058
} else if (dynamic_result == MAP_ARCHIVE_OTHER_FAILURE) {
1059
assert(dynamic_mapinfo != NULL && !dynamic_mapinfo->is_mapped(), "must have failed");
1060
// No need to retry mapping the dynamic archive again, as it will never succeed
1061
// (bad file, etc) -- just keep the base archive.
1062
log_warning(cds, dynamic)("Unable to use shared archive. The top archive failed to load: %s",
1063
dynamic_mapinfo->full_path());
1064
result = MAP_ARCHIVE_SUCCESS;
1065
// TODO, we can give the unused space for the dynamic archive to class_space_rs, but there's no
1066
// easy API to do that right now.
1067
} else {
1068
result = MAP_ARCHIVE_MMAP_FAILURE;
1069
}
1070
} else if (static_result == MAP_ARCHIVE_OTHER_FAILURE) {
1071
result = MAP_ARCHIVE_OTHER_FAILURE;
1072
} else {
1073
result = MAP_ARCHIVE_MMAP_FAILURE;
1074
}
1075
}
1076
1077
if (result == MAP_ARCHIVE_SUCCESS) {
1078
SharedBaseAddress = (size_t)mapped_base_address;
1079
LP64_ONLY({
1080
if (Metaspace::using_class_space()) {
1081
// Set up ccs in metaspace.
1082
Metaspace::initialize_class_space(class_space_rs);
1083
1084
// Set up compressed Klass pointer encoding: the encoding range must
1085
// cover both archive and class space.
1086
address cds_base = (address)static_mapinfo->mapped_base();
1087
address ccs_end = (address)class_space_rs.end();
1088
assert(ccs_end > cds_base, "Sanity check");
1089
CompressedKlassPointers::initialize(cds_base, ccs_end - cds_base);
1090
1091
// map_heap_regions() compares the current narrow oop and klass encodings
1092
// with the archived ones, so it must be done after all encodings are determined.
1093
static_mapinfo->map_heap_regions();
1094
}
1095
});
1096
log_info(cds)("optimized module handling: %s", MetaspaceShared::use_optimized_module_handling() ? "enabled" : "disabled");
1097
log_info(cds)("full module graph: %s", MetaspaceShared::use_full_module_graph() ? "enabled" : "disabled");
1098
} else {
1099
unmap_archive(static_mapinfo);
1100
unmap_archive(dynamic_mapinfo);
1101
release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1102
}
1103
1104
return result;
1105
}
1106
1107
1108
// This will reserve two address spaces suitable to house Klass structures, one
1109
// for the cds archives (static archive and optionally dynamic archive) and
1110
// optionally one move for ccs.
1111
//
1112
// Since both spaces must fall within the compressed class pointer encoding
1113
// range, they are allocated close to each other.
1114
//
1115
// Space for archives will be reserved first, followed by a potential gap,
1116
// followed by the space for ccs:
1117
//
1118
// +-- Base address A B End
1119
// | | | |
1120
// v v v v
1121
// +-------------+--------------+ +----------------------+
1122
// | static arc | [dyn. arch] | [gap] | compr. class space |
1123
// +-------------+--------------+ +----------------------+
1124
//
1125
// (The gap may result from different alignment requirements between metaspace
1126
// and CDS)
1127
//
1128
// If UseCompressedClassPointers is disabled, only one address space will be
1129
// reserved:
1130
//
1131
// +-- Base address End
1132
// | |
1133
// v v
1134
// +-------------+--------------+
1135
// | static arc | [dyn. arch] |
1136
// +-------------+--------------+
1137
//
1138
// Base address: If use_archive_base_addr address is true, the Base address is
1139
// determined by the address stored in the static archive. If
1140
// use_archive_base_addr address is false, this base address is determined
1141
// by the platform.
1142
//
1143
// If UseCompressedClassPointers=1, the range encompassing both spaces will be
1144
// suitable to en/decode narrow Klass pointers: the base will be valid for
1145
// encoding, the range [Base, End) not surpass KlassEncodingMetaspaceMax.
1146
//
1147
// Return:
1148
//
1149
// - On success:
1150
// - total_space_rs will be reserved as whole for archive_space_rs and
1151
// class_space_rs if UseCompressedClassPointers is true.
1152
// On Windows, try reserve archive_space_rs and class_space_rs
1153
// separately first if use_archive_base_addr is true.
1154
// - archive_space_rs will be reserved and large enough to host static and
1155
// if needed dynamic archive: [Base, A).
1156
// archive_space_rs.base and size will be aligned to CDS reserve
1157
// granularity.
1158
// - class_space_rs: If UseCompressedClassPointers=1, class_space_rs will
1159
// be reserved. Its start address will be aligned to metaspace reserve
1160
// alignment, which may differ from CDS alignment. It will follow the cds
1161
// archive space, close enough such that narrow class pointer encoding
1162
// covers both spaces.
1163
// If UseCompressedClassPointers=0, class_space_rs remains unreserved.
1164
// - On error: NULL is returned and the spaces remain unreserved.
1165
char* MetaspaceShared::reserve_address_space_for_archives(FileMapInfo* static_mapinfo,
1166
FileMapInfo* dynamic_mapinfo,
1167
bool use_archive_base_addr,
1168
ReservedSpace& total_space_rs,
1169
ReservedSpace& archive_space_rs,
1170
ReservedSpace& class_space_rs) {
1171
1172
address const base_address = (address) (use_archive_base_addr ? static_mapinfo->requested_base_address() : NULL);
1173
const size_t archive_space_alignment = core_region_alignment();
1174
1175
// Size and requested location of the archive_space_rs (for both static and dynamic archives)
1176
assert(static_mapinfo->mapping_base_offset() == 0, "Must be");
1177
size_t archive_end_offset = (dynamic_mapinfo == NULL) ? static_mapinfo->mapping_end_offset() : dynamic_mapinfo->mapping_end_offset();
1178
size_t archive_space_size = align_up(archive_end_offset, archive_space_alignment);
1179
1180
// If a base address is given, it must have valid alignment and be suitable as encoding base.
1181
if (base_address != NULL) {
1182
assert(is_aligned(base_address, archive_space_alignment),
1183
"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1184
if (Metaspace::using_class_space()) {
1185
assert(CompressedKlassPointers::is_valid_base(base_address),
1186
"Archive base address invalid: " PTR_FORMAT ".", p2i(base_address));
1187
}
1188
}
1189
1190
if (!Metaspace::using_class_space()) {
1191
// Get the simple case out of the way first:
1192
// no compressed class space, simple allocation.
1193
archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1194
os::vm_page_size(), (char*)base_address);
1195
if (archive_space_rs.is_reserved()) {
1196
assert(base_address == NULL ||
1197
(address)archive_space_rs.base() == base_address, "Sanity");
1198
// Register archive space with NMT.
1199
MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1200
return archive_space_rs.base();
1201
}
1202
return NULL;
1203
}
1204
1205
#ifdef _LP64
1206
1207
// Complex case: two spaces adjacent to each other, both to be addressable
1208
// with narrow class pointers.
1209
// We reserve the whole range spanning both spaces, then split that range up.
1210
1211
const size_t class_space_alignment = Metaspace::reserve_alignment();
1212
1213
// To simplify matters, lets assume that metaspace alignment will always be
1214
// equal or a multiple of archive alignment.
1215
assert(is_power_of_2(class_space_alignment) &&
1216
is_power_of_2(archive_space_alignment) &&
1217
class_space_alignment >= archive_space_alignment,
1218
"Sanity");
1219
1220
const size_t class_space_size = CompressedClassSpaceSize;
1221
assert(CompressedClassSpaceSize > 0 &&
1222
is_aligned(CompressedClassSpaceSize, class_space_alignment),
1223
"CompressedClassSpaceSize malformed: "
1224
SIZE_FORMAT, CompressedClassSpaceSize);
1225
1226
const size_t ccs_begin_offset = align_up(base_address + archive_space_size,
1227
class_space_alignment) - base_address;
1228
const size_t gap_size = ccs_begin_offset - archive_space_size;
1229
1230
const size_t total_range_size =
1231
align_up(archive_space_size + gap_size + class_space_size, core_region_alignment());
1232
1233
assert(total_range_size > ccs_begin_offset, "must be");
1234
if (use_windows_memory_mapping() && use_archive_base_addr) {
1235
if (base_address != nullptr) {
1236
// On Windows, we cannot safely split a reserved memory space into two (see JDK-8255917).
1237
// Hence, we optimistically reserve archive space and class space side-by-side. We only
1238
// do this for use_archive_base_addr=true since for use_archive_base_addr=false case
1239
// caller will not split the combined space for mapping, instead read the archive data
1240
// via sequential file IO.
1241
address ccs_base = base_address + archive_space_size + gap_size;
1242
archive_space_rs = ReservedSpace(archive_space_size, archive_space_alignment,
1243
os::vm_page_size(), (char*)base_address);
1244
class_space_rs = ReservedSpace(class_space_size, class_space_alignment,
1245
os::vm_page_size(), (char*)ccs_base);
1246
}
1247
if (!archive_space_rs.is_reserved() || !class_space_rs.is_reserved()) {
1248
release_reserved_spaces(total_space_rs, archive_space_rs, class_space_rs);
1249
return NULL;
1250
}
1251
} else {
1252
if (use_archive_base_addr && base_address != nullptr) {
1253
total_space_rs = ReservedSpace(total_range_size, archive_space_alignment,
1254
os::vm_page_size(), (char*) base_address);
1255
} else {
1256
// Reserve at any address, but leave it up to the platform to choose a good one.
1257
total_space_rs = Metaspace::reserve_address_space_for_compressed_classes(total_range_size);
1258
}
1259
1260
if (!total_space_rs.is_reserved()) {
1261
return NULL;
1262
}
1263
1264
// Paranoid checks:
1265
assert(base_address == NULL || (address)total_space_rs.base() == base_address,
1266
"Sanity (" PTR_FORMAT " vs " PTR_FORMAT ")", p2i(base_address), p2i(total_space_rs.base()));
1267
assert(is_aligned(total_space_rs.base(), archive_space_alignment), "Sanity");
1268
assert(total_space_rs.size() == total_range_size, "Sanity");
1269
assert(CompressedKlassPointers::is_valid_base((address)total_space_rs.base()), "Sanity");
1270
1271
// Now split up the space into ccs and cds archive. For simplicity, just leave
1272
// the gap reserved at the end of the archive space. Do not do real splitting.
1273
archive_space_rs = total_space_rs.first_part(ccs_begin_offset,
1274
(size_t)archive_space_alignment);
1275
class_space_rs = total_space_rs.last_part(ccs_begin_offset);
1276
MemTracker::record_virtual_memory_split_reserved(total_space_rs.base(), total_space_rs.size(),
1277
ccs_begin_offset);
1278
}
1279
assert(is_aligned(archive_space_rs.base(), archive_space_alignment), "Sanity");
1280
assert(is_aligned(archive_space_rs.size(), archive_space_alignment), "Sanity");
1281
assert(is_aligned(class_space_rs.base(), class_space_alignment), "Sanity");
1282
assert(is_aligned(class_space_rs.size(), class_space_alignment), "Sanity");
1283
1284
// NMT: fix up the space tags
1285
MemTracker::record_virtual_memory_type(archive_space_rs.base(), mtClassShared);
1286
MemTracker::record_virtual_memory_type(class_space_rs.base(), mtClass);
1287
1288
return archive_space_rs.base();
1289
1290
#else
1291
ShouldNotReachHere();
1292
return NULL;
1293
#endif
1294
1295
}
1296
1297
void MetaspaceShared::release_reserved_spaces(ReservedSpace& total_space_rs,
1298
ReservedSpace& archive_space_rs,
1299
ReservedSpace& class_space_rs) {
1300
if (total_space_rs.is_reserved()) {
1301
log_debug(cds)("Released shared space (archive + class) " INTPTR_FORMAT, p2i(total_space_rs.base()));
1302
total_space_rs.release();
1303
} else {
1304
if (archive_space_rs.is_reserved()) {
1305
log_debug(cds)("Released shared space (archive) " INTPTR_FORMAT, p2i(archive_space_rs.base()));
1306
archive_space_rs.release();
1307
}
1308
if (class_space_rs.is_reserved()) {
1309
log_debug(cds)("Released shared space (classes) " INTPTR_FORMAT, p2i(class_space_rs.base()));
1310
class_space_rs.release();
1311
}
1312
}
1313
}
1314
1315
static int archive_regions[] = { MetaspaceShared::rw, MetaspaceShared::ro };
1316
static int archive_regions_count = 2;
1317
1318
MapArchiveResult MetaspaceShared::map_archive(FileMapInfo* mapinfo, char* mapped_base_address, ReservedSpace rs) {
1319
assert(UseSharedSpaces, "must be runtime");
1320
if (mapinfo == NULL) {
1321
return MAP_ARCHIVE_SUCCESS; // The dynamic archive has not been specified. No error has happened -- trivially succeeded.
1322
}
1323
1324
mapinfo->set_is_mapped(false);
1325
if (mapinfo->core_region_alignment() != (size_t)core_region_alignment()) {
1326
log_info(cds)("Unable to map CDS archive -- core_region_alignment() expected: " SIZE_FORMAT
1327
" actual: " SIZE_FORMAT, mapinfo->core_region_alignment(), core_region_alignment());
1328
return MAP_ARCHIVE_OTHER_FAILURE;
1329
}
1330
1331
MapArchiveResult result =
1332
mapinfo->map_regions(archive_regions, archive_regions_count, mapped_base_address, rs);
1333
1334
if (result != MAP_ARCHIVE_SUCCESS) {
1335
unmap_archive(mapinfo);
1336
return result;
1337
}
1338
1339
if (!mapinfo->validate_shared_path_table()) {
1340
unmap_archive(mapinfo);
1341
return MAP_ARCHIVE_OTHER_FAILURE;
1342
}
1343
1344
mapinfo->set_is_mapped(true);
1345
return MAP_ARCHIVE_SUCCESS;
1346
}
1347
1348
void MetaspaceShared::unmap_archive(FileMapInfo* mapinfo) {
1349
assert(UseSharedSpaces, "must be runtime");
1350
if (mapinfo != NULL) {
1351
mapinfo->unmap_regions(archive_regions, archive_regions_count);
1352
mapinfo->unmap_region(MetaspaceShared::bm);
1353
mapinfo->set_is_mapped(false);
1354
}
1355
}
1356
1357
// For -XX:PrintSharedArchiveAndExit
1358
class CountSharedSymbols : public SymbolClosure {
1359
private:
1360
int _count;
1361
public:
1362
CountSharedSymbols() : _count(0) {}
1363
void do_symbol(Symbol** sym) {
1364
_count++;
1365
}
1366
int total() { return _count; }
1367
1368
};
1369
1370
// Read the miscellaneous data from the shared file, and
1371
// serialize it out to its various destinations.
1372
1373
void MetaspaceShared::initialize_shared_spaces() {
1374
FileMapInfo *static_mapinfo = FileMapInfo::current_info();
1375
1376
// Verify various attributes of the archive, plus initialize the
1377
// shared string/symbol tables
1378
char* buffer = static_mapinfo->serialized_data();
1379
intptr_t* array = (intptr_t*)buffer;
1380
ReadClosure rc(&array);
1381
serialize(&rc);
1382
1383
// Initialize the run-time symbol table.
1384
SymbolTable::create_table();
1385
1386
static_mapinfo->patch_archived_heap_embedded_pointers();
1387
1388
// Close the mapinfo file
1389
static_mapinfo->close();
1390
1391
static_mapinfo->unmap_region(MetaspaceShared::bm);
1392
1393
FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
1394
if (dynamic_mapinfo != NULL) {
1395
intptr_t* buffer = (intptr_t*)dynamic_mapinfo->serialized_data();
1396
ReadClosure rc(&buffer);
1397
SymbolTable::serialize_shared_table_header(&rc, false);
1398
SystemDictionaryShared::serialize_dictionary_headers(&rc, false);
1399
dynamic_mapinfo->close();
1400
dynamic_mapinfo->unmap_region(MetaspaceShared::bm);
1401
}
1402
1403
// Set up LambdaFormInvokers::_lambdaform_lines for dynamic dump
1404
if (DynamicDumpSharedSpaces) {
1405
// Read stored LF format lines stored in static archive
1406
LambdaFormInvokers::read_static_archive_invokers();
1407
}
1408
1409
if (PrintSharedArchiveAndExit) {
1410
// Print archive names
1411
if (dynamic_mapinfo != nullptr) {
1412
tty->print_cr("\n\nBase archive name: %s", Arguments::GetSharedArchivePath());
1413
tty->print_cr("Base archive version %d", static_mapinfo->version());
1414
} else {
1415
tty->print_cr("Static archive name: %s", static_mapinfo->full_path());
1416
tty->print_cr("Static archive version %d", static_mapinfo->version());
1417
}
1418
1419
SystemDictionaryShared::print_shared_archive(tty);
1420
if (dynamic_mapinfo != nullptr) {
1421
tty->print_cr("\n\nDynamic archive name: %s", dynamic_mapinfo->full_path());
1422
tty->print_cr("Dynamic archive version %d", dynamic_mapinfo->version());
1423
SystemDictionaryShared::print_shared_archive(tty, false/*dynamic*/);
1424
}
1425
1426
// collect shared symbols and strings
1427
CountSharedSymbols cl;
1428
SymbolTable::shared_symbols_do(&cl);
1429
tty->print_cr("Number of shared symbols: %d", cl.total());
1430
tty->print_cr("Number of shared strings: %zu", StringTable::shared_entry_count());
1431
tty->print_cr("VM version: %s\r\n", static_mapinfo->vm_version());
1432
if (FileMapInfo::current_info() == NULL || _archive_loading_failed) {
1433
tty->print_cr("archive is invalid");
1434
vm_exit(1);
1435
} else {
1436
tty->print_cr("archive is valid");
1437
vm_exit(0);
1438
}
1439
}
1440
}
1441
1442
// JVM/TI RedefineClasses() support:
1443
bool MetaspaceShared::remap_shared_readonly_as_readwrite() {
1444
assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1445
1446
if (UseSharedSpaces) {
1447
// remap the shared readonly space to shared readwrite, private
1448
FileMapInfo* mapinfo = FileMapInfo::current_info();
1449
if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1450
return false;
1451
}
1452
if (FileMapInfo::dynamic_info() != NULL) {
1453
mapinfo = FileMapInfo::dynamic_info();
1454
if (!mapinfo->remap_shared_readonly_as_readwrite()) {
1455
return false;
1456
}
1457
}
1458
_remapped_readwrite = true;
1459
}
1460
return true;
1461
}
1462
1463
bool MetaspaceShared::use_full_module_graph() {
1464
#if INCLUDE_CDS_JAVA_HEAP
1465
if (ClassLoaderDataShared::is_full_module_graph_loaded()) {
1466
return true;
1467
}
1468
#endif
1469
bool result = _use_optimized_module_handling && _use_full_module_graph &&
1470
(UseSharedSpaces || DumpSharedSpaces) && HeapShared::is_heap_object_archiving_allowed();
1471
if (result && UseSharedSpaces) {
1472
// Classes used by the archived full module graph are loaded in JVMTI early phase.
1473
assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
1474
"CDS should be disabled if early class hooks are enabled");
1475
}
1476
return result;
1477
}
1478
1479
void MetaspaceShared::print_on(outputStream* st) {
1480
if (UseSharedSpaces) {
1481
st->print("CDS archive(s) mapped at: ");
1482
address base = (address)MetaspaceObj::shared_metaspace_base();
1483
address static_top = (address)_shared_metaspace_static_top;
1484
address top = (address)MetaspaceObj::shared_metaspace_top();
1485
st->print("[" PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "), ", p2i(base), p2i(static_top), p2i(top));
1486
st->print("size " SIZE_FORMAT ", ", top - base);
1487
st->print("SharedBaseAddress: " PTR_FORMAT ", ArchiveRelocationMode: %d.", SharedBaseAddress, (int)ArchiveRelocationMode);
1488
} else {
1489
st->print("CDS archive(s) not mapped");
1490
}
1491
st->cr();
1492
}
1493
1494