Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/cds/filemap.cpp
41145 views
1
/*
2
* Copyright (c) 2003, 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.h"
27
#include "cds/archiveBuilder.hpp"
28
#include "cds/archiveUtils.inline.hpp"
29
#include "cds/dynamicArchive.hpp"
30
#include "cds/filemap.hpp"
31
#include "cds/heapShared.inline.hpp"
32
#include "cds/metaspaceShared.hpp"
33
#include "classfile/altHashing.hpp"
34
#include "classfile/classFileStream.hpp"
35
#include "classfile/classLoader.inline.hpp"
36
#include "classfile/classLoaderData.inline.hpp"
37
#include "classfile/classLoaderExt.hpp"
38
#include "classfile/symbolTable.hpp"
39
#include "classfile/systemDictionaryShared.hpp"
40
#include "classfile/vmClasses.hpp"
41
#include "classfile/vmSymbols.hpp"
42
#include "logging/log.hpp"
43
#include "logging/logStream.hpp"
44
#include "logging/logMessage.hpp"
45
#include "memory/iterator.inline.hpp"
46
#include "memory/metadataFactory.hpp"
47
#include "memory/metaspaceClosure.hpp"
48
#include "memory/oopFactory.hpp"
49
#include "memory/universe.hpp"
50
#include "oops/compressedOops.hpp"
51
#include "oops/compressedOops.inline.hpp"
52
#include "oops/objArrayOop.hpp"
53
#include "oops/oop.inline.hpp"
54
#include "prims/jvmtiExport.hpp"
55
#include "runtime/arguments.hpp"
56
#include "runtime/java.hpp"
57
#include "runtime/mutexLocker.hpp"
58
#include "runtime/os.hpp"
59
#include "runtime/vm_version.hpp"
60
#include "services/memTracker.hpp"
61
#include "utilities/align.hpp"
62
#include "utilities/bitMap.inline.hpp"
63
#include "utilities/classpathStream.hpp"
64
#include "utilities/defaultStream.hpp"
65
#include "utilities/ostream.hpp"
66
#if INCLUDE_G1GC
67
#include "gc/g1/g1CollectedHeap.hpp"
68
#include "gc/g1/heapRegion.hpp"
69
#endif
70
71
# include <sys/stat.h>
72
# include <errno.h>
73
74
#ifndef O_BINARY // if defined (Win32) use binary files.
75
#define O_BINARY 0 // otherwise do nothing.
76
#endif
77
78
// Complain and stop. All error conditions occurring during the writing of
79
// an archive file should stop the process. Unrecoverable errors during
80
// the reading of the archive file should stop the process.
81
82
static void fail_exit(const char *msg, va_list ap) {
83
// This occurs very early during initialization: tty is not initialized.
84
jio_fprintf(defaultStream::error_stream(),
85
"An error has occurred while processing the"
86
" shared archive file.\n");
87
jio_vfprintf(defaultStream::error_stream(), msg, ap);
88
jio_fprintf(defaultStream::error_stream(), "\n");
89
// Do not change the text of the below message because some tests check for it.
90
vm_exit_during_initialization("Unable to use shared archive.", NULL);
91
}
92
93
94
void FileMapInfo::fail_stop(const char *msg, ...) {
95
va_list ap;
96
va_start(ap, msg);
97
fail_exit(msg, ap); // Never returns.
98
va_end(ap); // for completeness.
99
}
100
101
102
// Complain and continue. Recoverable errors during the reading of the
103
// archive file may continue (with sharing disabled).
104
//
105
// If we continue, then disable shared spaces and close the file.
106
107
void FileMapInfo::fail_continue(const char *msg, ...) {
108
va_list ap;
109
va_start(ap, msg);
110
if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
111
// If we are doing PrintSharedArchiveAndExit and some of the classpath entries
112
// do not validate, we can still continue "limping" to validate the remaining
113
// entries. No need to quit.
114
tty->print("[");
115
tty->vprint(msg, ap);
116
tty->print_cr("]");
117
} else {
118
if (RequireSharedSpaces) {
119
fail_exit(msg, ap);
120
} else {
121
if (log_is_enabled(Info, cds)) {
122
ResourceMark rm;
123
LogStream ls(Log(cds)::info());
124
ls.print("UseSharedSpaces: ");
125
ls.vprint_cr(msg, ap);
126
}
127
}
128
}
129
va_end(ap);
130
}
131
132
// Fill in the fileMapInfo structure with data about this VM instance.
133
134
// This method copies the vm version info into header_version. If the version is too
135
// long then a truncated version, which has a hash code appended to it, is copied.
136
//
137
// Using a template enables this method to verify that header_version is an array of
138
// length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and
139
// the code that reads the CDS file will both use the same size buffer. Hence, will
140
// use identical truncation. This is necessary for matching of truncated versions.
141
template <int N> static void get_header_version(char (&header_version) [N]) {
142
assert(N == JVM_IDENT_MAX, "Bad header_version size");
143
144
const char *vm_version = VM_Version::internal_vm_info_string();
145
const int version_len = (int)strlen(vm_version);
146
147
memset(header_version, 0, JVM_IDENT_MAX);
148
149
if (version_len < (JVM_IDENT_MAX-1)) {
150
strcpy(header_version, vm_version);
151
152
} else {
153
// Get the hash value. Use a static seed because the hash needs to return the same
154
// value over multiple jvm invocations.
155
uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
156
157
// Truncate the ident, saving room for the 8 hex character hash value.
158
strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
159
160
// Append the hash code as eight hex digits.
161
sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
162
header_version[JVM_IDENT_MAX-1] = 0; // Null terminate.
163
}
164
165
assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
166
}
167
168
FileMapInfo::FileMapInfo(bool is_static) {
169
memset((void*)this, 0, sizeof(FileMapInfo));
170
_is_static = is_static;
171
size_t header_size;
172
if (is_static) {
173
assert(_current_info == NULL, "must be singleton"); // not thread safe
174
_current_info = this;
175
header_size = sizeof(FileMapHeader);
176
} else {
177
assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe
178
_dynamic_archive_info = this;
179
header_size = sizeof(DynamicArchiveHeader);
180
}
181
_header = (FileMapHeader*)os::malloc(header_size, mtInternal);
182
memset((void*)_header, 0, header_size);
183
_header->set_header_size(header_size);
184
_header->set_version(INVALID_CDS_ARCHIVE_VERSION);
185
_header->set_has_platform_or_app_classes(true);
186
_file_offset = 0;
187
_file_open = false;
188
}
189
190
FileMapInfo::~FileMapInfo() {
191
if (_is_static) {
192
assert(_current_info == this, "must be singleton"); // not thread safe
193
_current_info = NULL;
194
} else {
195
assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
196
_dynamic_archive_info = NULL;
197
}
198
}
199
200
void FileMapInfo::populate_header(size_t core_region_alignment) {
201
header()->populate(this, core_region_alignment);
202
}
203
204
void FileMapHeader::populate(FileMapInfo* mapinfo, size_t core_region_alignment) {
205
if (DynamicDumpSharedSpaces) {
206
_magic = CDS_DYNAMIC_ARCHIVE_MAGIC;
207
} else {
208
_magic = CDS_ARCHIVE_MAGIC;
209
}
210
_version = CURRENT_CDS_ARCHIVE_VERSION;
211
_core_region_alignment = core_region_alignment;
212
_obj_alignment = ObjectAlignmentInBytes;
213
_compact_strings = CompactStrings;
214
if (HeapShared::is_heap_object_archiving_allowed()) {
215
_narrow_oop_mode = CompressedOops::mode();
216
_narrow_oop_base = CompressedOops::base();
217
_narrow_oop_shift = CompressedOops::shift();
218
_heap_begin = CompressedOops::begin();
219
_heap_end = CompressedOops::end();
220
}
221
_compressed_oops = UseCompressedOops;
222
_compressed_class_ptrs = UseCompressedClassPointers;
223
_max_heap_size = MaxHeapSize;
224
_narrow_klass_shift = CompressedKlassPointers::shift();
225
_use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling();
226
_use_full_module_graph = MetaspaceShared::use_full_module_graph();
227
228
// The following fields are for sanity checks for whether this archive
229
// will function correctly with this JVM and the bootclasspath it's
230
// invoked with.
231
232
// JVM version string ... changes on each build.
233
get_header_version(_jvm_ident);
234
235
_app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
236
_app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
237
_num_module_paths = ClassLoader::num_module_path_entries();
238
_max_used_path_index = ClassLoaderExt::max_used_path_index();
239
240
_verify_local = BytecodeVerificationLocal;
241
_verify_remote = BytecodeVerificationRemote;
242
_has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
243
_requested_base_address = (char*)SharedBaseAddress;
244
_mapped_base_address = (char*)SharedBaseAddress;
245
_allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
246
// the following 2 fields will be set in write_header for dynamic archive header
247
_base_archive_name_size = 0;
248
_base_archive_is_default = false;
249
250
if (!DynamicDumpSharedSpaces) {
251
set_shared_path_table(mapinfo->_shared_path_table);
252
CDS_JAVA_HEAP_ONLY(_heap_obj_roots = CompressedOops::encode(HeapShared::roots());)
253
}
254
}
255
256
void FileMapHeader::print(outputStream* st) {
257
ResourceMark rm;
258
259
st->print_cr("- magic: 0x%08x", _magic);
260
st->print_cr("- crc: 0x%08x", _crc);
261
st->print_cr("- version: %d", _version);
262
263
for (int i = 0; i < NUM_CDS_REGIONS; i++) {
264
FileMapRegion* si = space_at(i);
265
si->print(st, i);
266
}
267
st->print_cr("============ end regions ======== ");
268
269
st->print_cr("- header_size: " SIZE_FORMAT, _header_size);
270
st->print_cr("- core_region_alignment: " SIZE_FORMAT, _core_region_alignment);
271
st->print_cr("- obj_alignment: %d", _obj_alignment);
272
st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));
273
st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));
274
st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift);
275
st->print_cr("- compact_strings: %d", _compact_strings);
276
st->print_cr("- max_heap_size: " UINTX_FORMAT, _max_heap_size);
277
st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode);
278
st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift);
279
st->print_cr("- compressed_oops: %d", _compressed_oops);
280
st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs);
281
st->print_cr("- cloned_vtables_offset: " SIZE_FORMAT_HEX, _cloned_vtables_offset);
282
st->print_cr("- serialized_data_offset: " SIZE_FORMAT_HEX, _serialized_data_offset);
283
st->print_cr("- heap_end: " INTPTR_FORMAT, p2i(_heap_end));
284
st->print_cr("- base_archive_is_default: %d", _base_archive_is_default);
285
st->print_cr("- jvm_ident: %s", _jvm_ident);
286
st->print_cr("- base_archive_name_size: " SIZE_FORMAT, _base_archive_name_size);
287
st->print_cr("- shared_path_table_offset: " SIZE_FORMAT_HEX, _shared_path_table_offset);
288
st->print_cr("- shared_path_table_size: %d", _shared_path_table_size);
289
st->print_cr("- app_class_paths_start_index: %d", _app_class_paths_start_index);
290
st->print_cr("- app_module_paths_start_index: %d", _app_module_paths_start_index);
291
st->print_cr("- num_module_paths: %d", _num_module_paths);
292
st->print_cr("- max_used_path_index: %d", _max_used_path_index);
293
st->print_cr("- verify_local: %d", _verify_local);
294
st->print_cr("- verify_remote: %d", _verify_remote);
295
st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes);
296
st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address));
297
st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address));
298
st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);
299
st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling);
300
st->print_cr("- use_full_module_graph %d", _use_full_module_graph);
301
st->print_cr("- ptrmap_size_in_bits: " SIZE_FORMAT, _ptrmap_size_in_bits);
302
}
303
304
void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
305
_type = non_existent_entry;
306
set_name(path, CHECK);
307
}
308
309
void SharedClassPathEntry::init(bool is_modules_image,
310
bool is_module_path,
311
ClassPathEntry* cpe, TRAPS) {
312
Arguments::assert_is_dumping_archive();
313
_timestamp = 0;
314
_filesize = 0;
315
_from_class_path_attr = false;
316
317
struct stat st;
318
if (os::stat(cpe->name(), &st) == 0) {
319
if ((st.st_mode & S_IFMT) == S_IFDIR) {
320
_type = dir_entry;
321
} else {
322
// The timestamp of the modules_image is not checked at runtime.
323
if (is_modules_image) {
324
_type = modules_image_entry;
325
} else {
326
_type = jar_entry;
327
_timestamp = st.st_mtime;
328
_from_class_path_attr = cpe->from_class_path_attr();
329
}
330
_filesize = st.st_size;
331
_is_module_path = is_module_path;
332
}
333
} else {
334
// The file/dir must exist, or it would not have been added
335
// into ClassLoader::classpath_entry().
336
//
337
// If we can't access a jar file in the boot path, then we can't
338
// make assumptions about where classes get loaded from.
339
FileMapInfo::fail_stop("Unable to open file %s.", cpe->name());
340
}
341
342
// No need to save the name of the module file, as it will be computed at run time
343
// to allow relocation of the JDK directory.
344
const char* name = is_modules_image ? "" : cpe->name();
345
set_name(name, CHECK);
346
}
347
348
void SharedClassPathEntry::set_name(const char* name, TRAPS) {
349
size_t len = strlen(name) + 1;
350
_name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);
351
strcpy(_name->data(), name);
352
}
353
354
void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {
355
_type = ent->_type;
356
_is_module_path = ent->_is_module_path;
357
_timestamp = ent->_timestamp;
358
_filesize = ent->_filesize;
359
_from_class_path_attr = ent->_from_class_path_attr;
360
set_name(ent->name(), CHECK);
361
362
if (ent->is_jar() && !ent->is_signed() && ent->manifest() != NULL) {
363
Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
364
ent->manifest_size(),
365
CHECK);
366
char* p = (char*)(buf->data());
367
memcpy(p, ent->manifest(), ent->manifest_size());
368
set_manifest(buf);
369
}
370
}
371
372
const char* SharedClassPathEntry::name() const {
373
if (UseSharedSpaces && is_modules_image()) {
374
// In order to validate the runtime modules image file size against the archived
375
// size information, we need to obtain the runtime modules image path. The recorded
376
// dump time modules image path in the archive may be different from the runtime path
377
// if the JDK image has beed moved after generating the archive.
378
return ClassLoader::get_jrt_entry()->name();
379
} else {
380
return _name->data();
381
}
382
}
383
384
bool SharedClassPathEntry::validate(bool is_class_path) const {
385
assert(UseSharedSpaces, "runtime only");
386
387
struct stat st;
388
const char* name = this->name();
389
390
bool ok = true;
391
log_info(class, path)("checking shared classpath entry: %s", name);
392
if (os::stat(name, &st) != 0 && is_class_path) {
393
// If the archived module path entry does not exist at runtime, it is not fatal
394
// (no need to invalid the shared archive) because the shared runtime visibility check
395
// filters out any archived module classes that do not have a matching runtime
396
// module path location.
397
FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
398
ok = false;
399
} else if (is_dir()) {
400
if (!os::dir_is_empty(name)) {
401
FileMapInfo::fail_continue("directory is not empty: %s", name);
402
ok = false;
403
}
404
} else if ((has_timestamp() && _timestamp != st.st_mtime) ||
405
_filesize != st.st_size) {
406
ok = false;
407
if (PrintSharedArchiveAndExit) {
408
FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
409
"Timestamp mismatch" :
410
"File size mismatch");
411
} else {
412
FileMapInfo::fail_continue("A jar file is not the one used while building"
413
" the shared archive file: %s", name);
414
}
415
}
416
417
if (PrintSharedArchiveAndExit && !ok) {
418
// If PrintSharedArchiveAndExit is enabled, don't report failure to the
419
// caller. Please see above comments for more details.
420
ok = true;
421
MetaspaceShared::set_archive_loading_failed();
422
}
423
return ok;
424
}
425
426
bool SharedClassPathEntry::check_non_existent() const {
427
assert(_type == non_existent_entry, "must be");
428
log_info(class, path)("should be non-existent: %s", name());
429
struct stat st;
430
if (os::stat(name(), &st) != 0) {
431
log_info(class, path)("ok");
432
return true; // file doesn't exist
433
} else {
434
return false;
435
}
436
}
437
438
439
void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
440
it->push(&_name);
441
it->push(&_manifest);
442
}
443
444
void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
445
it->push(&_table);
446
for (int i=0; i<_size; i++) {
447
path_at(i)->metaspace_pointers_do(it);
448
}
449
}
450
451
void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {
452
size_t entry_size = sizeof(SharedClassPathEntry);
453
int num_entries = 0;
454
num_entries += ClassLoader::num_boot_classpath_entries();
455
num_entries += ClassLoader::num_app_classpath_entries();
456
num_entries += ClassLoader::num_module_path_entries();
457
num_entries += FileMapInfo::num_non_existent_class_paths();
458
size_t bytes = entry_size * num_entries;
459
460
_table = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);
461
_size = num_entries;
462
}
463
464
// Make a copy of the _shared_path_table for use during dynamic CDS dump.
465
// It is needed because some Java code continues to execute after dynamic dump has finished.
466
// However, during dynamic dump, we have modified FileMapInfo::_shared_path_table so
467
// FileMapInfo::shared_path(i) returns incorrect information in ClassLoader::record_result().
468
void FileMapInfo::copy_shared_path_table(ClassLoaderData* loader_data, TRAPS) {
469
size_t entry_size = sizeof(SharedClassPathEntry);
470
size_t bytes = entry_size * _shared_path_table.size();
471
472
Array<u8>* array = MetadataFactory::new_array<u8>(loader_data, (int)bytes, CHECK);
473
_saved_shared_path_table = SharedPathTable(array, _shared_path_table.size());
474
475
for (int i = 0; i < _shared_path_table.size(); i++) {
476
_saved_shared_path_table.path_at(i)->copy_from(shared_path(i), loader_data, CHECK);
477
}
478
}
479
480
void FileMapInfo::allocate_shared_path_table(TRAPS) {
481
Arguments::assert_is_dumping_archive();
482
483
ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
484
ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
485
486
assert(jrt != NULL,
487
"No modular java runtime image present when allocating the CDS classpath entry table");
488
489
_shared_path_table.dumptime_init(loader_data, CHECK);
490
491
// 1. boot class path
492
int i = 0;
493
i = add_shared_classpaths(i, "boot", jrt, CHECK);
494
i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), CHECK);
495
i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);
496
497
for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
498
const char* path = _non_existent_class_paths->at(x);
499
shared_path(i)->init_as_non_existent(path, CHECK);
500
}
501
502
assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
503
504
copy_shared_path_table(loader_data, CHECK);
505
}
506
507
int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
508
while (cpe != NULL) {
509
bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
510
bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();
511
const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
512
log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
513
SharedClassPathEntry* ent = shared_path(i);
514
ent->init(is_jrt, is_module_path, cpe, CHECK_0);
515
if (cpe->is_jar_file()) {
516
update_jar_manifest(cpe, ent, CHECK_0);
517
}
518
if (is_jrt) {
519
cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
520
} else {
521
cpe = cpe->next();
522
}
523
i++;
524
}
525
526
return i;
527
}
528
529
void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
530
Arguments::assert_is_dumping_archive();
531
532
bool has_nonempty_dir = false;
533
534
int last = _shared_path_table.size() - 1;
535
if (last > ClassLoaderExt::max_used_path_index()) {
536
// no need to check any path beyond max_used_path_index
537
last = ClassLoaderExt::max_used_path_index();
538
}
539
540
for (int i = 0; i <= last; i++) {
541
SharedClassPathEntry *e = shared_path(i);
542
if (e->is_dir()) {
543
const char* path = e->name();
544
if (!os::dir_is_empty(path)) {
545
log_error(cds)("Error: non-empty directory '%s'", path);
546
has_nonempty_dir = true;
547
}
548
}
549
}
550
551
if (has_nonempty_dir) {
552
ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
553
}
554
}
555
556
void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
557
Arguments::assert_is_dumping_archive();
558
log_info(class, path)("non-existent Class-Path entry %s", path);
559
if (_non_existent_class_paths == NULL) {
560
_non_existent_class_paths = new (ResourceObj::C_HEAP, mtClass)GrowableArray<const char*>(10, mtClass);
561
}
562
_non_existent_class_paths->append(os::strdup(path));
563
}
564
565
int FileMapInfo::num_non_existent_class_paths() {
566
Arguments::assert_is_dumping_archive();
567
if (_non_existent_class_paths != NULL) {
568
return _non_existent_class_paths->length();
569
} else {
570
return 0;
571
}
572
}
573
574
int FileMapInfo::get_module_shared_path_index(Symbol* location) {
575
if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {
576
assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
577
return 0;
578
}
579
580
if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {
581
// The archive(s) were created without --module-path option
582
return -1;
583
}
584
585
if (!location->starts_with("file:", 5)) {
586
return -1;
587
}
588
589
// skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
590
ResourceMark rm;
591
const char* file = ClassLoader::skip_uri_protocol(location->as_C_string());
592
for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {
593
SharedClassPathEntry* ent = shared_path(i);
594
assert(ent->in_named_module(), "must be");
595
bool cond = strcmp(file, ent->name()) == 0;
596
log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
597
location->as_C_string(), ent->name(), cond ? "same" : "different");
598
if (cond) {
599
return i;
600
}
601
}
602
603
return -1;
604
}
605
606
class ManifestStream: public ResourceObj {
607
private:
608
u1* _buffer_start; // Buffer bottom
609
u1* _buffer_end; // Buffer top (one past last element)
610
u1* _current; // Current buffer position
611
612
public:
613
// Constructor
614
ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
615
_current(buffer) {
616
_buffer_end = buffer + length;
617
}
618
619
static bool is_attr(u1* attr, const char* name) {
620
return strncmp((const char*)attr, name, strlen(name)) == 0;
621
}
622
623
static char* copy_attr(u1* value, size_t len) {
624
char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
625
strncpy(buf, (char*)value, len);
626
buf[len] = 0;
627
return buf;
628
}
629
630
// The return value indicates if the JAR is signed or not
631
bool check_is_signed() {
632
u1* attr = _current;
633
bool isSigned = false;
634
while (_current < _buffer_end) {
635
if (*_current == '\n') {
636
*_current = '\0';
637
u1* value = (u1*)strchr((char*)attr, ':');
638
if (value != NULL) {
639
assert(*(value+1) == ' ', "Unrecognized format" );
640
if (strstr((char*)attr, "-Digest") != NULL) {
641
isSigned = true;
642
break;
643
}
644
}
645
*_current = '\n'; // restore
646
attr = _current + 1;
647
}
648
_current ++;
649
}
650
return isSigned;
651
}
652
};
653
654
void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
655
ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
656
ResourceMark rm(THREAD);
657
jint manifest_size;
658
659
assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
660
char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);
661
if (manifest != NULL) {
662
ManifestStream* stream = new ManifestStream((u1*)manifest,
663
manifest_size);
664
if (stream->check_is_signed()) {
665
ent->set_is_signed();
666
} else {
667
// Copy the manifest into the shared archive
668
manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);
669
Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
670
manifest_size,
671
CHECK);
672
char* p = (char*)(buf->data());
673
memcpy(p, manifest, manifest_size);
674
ent->set_manifest(buf);
675
}
676
}
677
}
678
679
char* FileMapInfo::skip_first_path_entry(const char* path) {
680
size_t path_sep_len = strlen(os::path_separator());
681
char* p = strstr((char*)path, os::path_separator());
682
if (p != NULL) {
683
debug_only( {
684
size_t image_name_len = strlen(MODULES_IMAGE_NAME);
685
assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
686
"first entry must be the modules image");
687
} );
688
p += path_sep_len;
689
} else {
690
debug_only( {
691
assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
692
"first entry must be the modules image");
693
} );
694
}
695
return p;
696
}
697
698
int FileMapInfo::num_paths(const char* path) {
699
if (path == NULL) {
700
return 0;
701
}
702
int npaths = 1;
703
char* p = (char*)path;
704
while (p != NULL) {
705
char* prev = p;
706
p = strstr((char*)p, os::path_separator());
707
if (p != NULL) {
708
p++;
709
// don't count empty path
710
if ((p - prev) > 1) {
711
npaths++;
712
}
713
}
714
}
715
return npaths;
716
}
717
718
GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
719
GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
720
721
ClasspathStream cp_stream(paths);
722
while (cp_stream.has_next()) {
723
const char* path = cp_stream.get_next();
724
struct stat st;
725
if (os::stat(path, &st) == 0) {
726
path_array->append(path);
727
}
728
}
729
return path_array;
730
}
731
732
bool FileMapInfo::classpath_failure(const char* msg, const char* name) {
733
ClassLoader::trace_class_path(msg, name);
734
if (PrintSharedArchiveAndExit) {
735
MetaspaceShared::set_archive_loading_failed();
736
}
737
return false;
738
}
739
740
bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) {
741
int i = 0;
742
int j = shared_path_start_idx;
743
bool mismatch = false;
744
while (i < num_paths && !mismatch) {
745
while (shared_path(j)->from_class_path_attr()) {
746
// shared_path(j) was expanded from the JAR file attribute "Class-Path:"
747
// during dump time. It's not included in the -classpath VM argument.
748
j++;
749
}
750
if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) {
751
mismatch = true;
752
}
753
i++;
754
j++;
755
}
756
return mismatch;
757
}
758
759
bool FileMapInfo::validate_boot_class_paths() {
760
//
761
// - Archive contains boot classes only - relaxed boot path check:
762
// Extra path elements appended to the boot path at runtime are allowed.
763
//
764
// - Archive contains application or platform classes - strict boot path check:
765
// Validate the entire runtime boot path, which must be compatible
766
// with the dump time boot path. Appending boot path at runtime is not
767
// allowed.
768
//
769
770
// The first entry in boot path is the modules_image (guaranteed by
771
// ClassLoader::setup_boot_search_path()). Skip the first entry. The
772
// path of the runtime modules_image may be different from the dump
773
// time path (e.g. the JDK image is copied to a different location
774
// after generating the shared archive), which is acceptable. For most
775
// common cases, the dump time boot path might contain modules_image only.
776
char* runtime_boot_path = Arguments::get_sysclasspath();
777
char* rp = skip_first_path_entry(runtime_boot_path);
778
assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
779
int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image
780
bool mismatch = false;
781
782
bool relaxed_check = !header()->has_platform_or_app_classes();
783
if (dp_len == 0 && rp == NULL) {
784
return true; // ok, both runtime and dump time boot paths have modules_images only
785
} else if (dp_len == 0 && rp != NULL) {
786
if (relaxed_check) {
787
return true; // ok, relaxed check, runtime has extra boot append path entries
788
} else {
789
mismatch = true;
790
}
791
} else if (dp_len > 0 && rp != NULL) {
792
int num;
793
ResourceMark rm;
794
GrowableArray<const char*>* rp_array = create_path_array(rp);
795
int rp_len = rp_array->length();
796
if (rp_len >= dp_len) {
797
if (relaxed_check) {
798
// only check the leading entries in the runtime boot path, up to
799
// the length of the dump time boot path
800
num = dp_len;
801
} else {
802
// check the full runtime boot path, must match with dump time
803
num = rp_len;
804
}
805
mismatch = check_paths(1, num, rp_array);
806
} else {
807
// create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths
808
// are the same initially, after the call to create_path_array(), the runtime boot classpath length could become
809
// shorter. We consider boot classpath mismatch in this case.
810
mismatch = true;
811
}
812
}
813
814
if (mismatch) {
815
// The paths are different
816
return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);
817
}
818
return true;
819
}
820
821
bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
822
const char *appcp = Arguments::get_appclasspath();
823
assert(appcp != NULL, "NULL app classpath");
824
int rp_len = num_paths(appcp);
825
bool mismatch = false;
826
if (rp_len < shared_app_paths_len) {
827
return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);
828
}
829
if (shared_app_paths_len != 0 && rp_len != 0) {
830
// Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
831
ResourceMark rm;
832
GrowableArray<const char*>* rp_array = create_path_array(appcp);
833
if (rp_array->length() == 0) {
834
// None of the jar file specified in the runtime -cp exists.
835
return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
836
}
837
if (rp_array->length() < shared_app_paths_len) {
838
// create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths
839
// are the same initially, after the call to create_path_array(), the runtime app classpath length could become
840
// shorter. We consider app classpath mismatch in this case.
841
return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
842
}
843
844
// Handling of non-existent entries in the classpath: we eliminate all the non-existent
845
// entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
846
// and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
847
// entries. E.g.:
848
//
849
// dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive.
850
// run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched
851
// run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched
852
853
int j = header()->app_class_paths_start_index();
854
mismatch = check_paths(j, shared_app_paths_len, rp_array);
855
if (mismatch) {
856
return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
857
}
858
}
859
return true;
860
}
861
862
void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
863
LogTarget(Info, class, path) lt;
864
if (lt.is_enabled()) {
865
LogStream ls(lt);
866
ls.print("%s", msg);
867
const char* prefix = "";
868
for (int i = start_idx; i < end_idx; i++) {
869
ls.print("%s%s", prefix, shared_path(i)->name());
870
prefix = os::path_separator();
871
}
872
ls.cr();
873
}
874
}
875
876
bool FileMapInfo::validate_shared_path_table() {
877
assert(UseSharedSpaces, "runtime only");
878
879
_validating_shared_path_table = true;
880
881
// Load the shared path table info from the archive header
882
_shared_path_table = header()->shared_path_table();
883
if (DynamicDumpSharedSpaces) {
884
// Only support dynamic dumping with the usage of the default CDS archive
885
// or a simple base archive.
886
// If the base layer archive contains additional path component besides
887
// the runtime image and the -cp, dynamic dumping is disabled.
888
//
889
// When dynamic archiving is enabled, the _shared_path_table is overwritten
890
// to include the application path and stored in the top layer archive.
891
assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
892
if (header()->app_class_paths_start_index() > 1) {
893
DynamicDumpSharedSpaces = false;
894
warning(
895
"Dynamic archiving is disabled because base layer archive has appended boot classpath");
896
}
897
if (header()->num_module_paths() > 0) {
898
DynamicDumpSharedSpaces = false;
899
warning(
900
"Dynamic archiving is disabled because base layer archive has module path");
901
}
902
}
903
904
log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());
905
log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());
906
907
int module_paths_start_index = header()->app_module_paths_start_index();
908
int shared_app_paths_len = 0;
909
910
// validate the path entries up to the _max_used_path_index
911
for (int i=0; i < header()->max_used_path_index() + 1; i++) {
912
if (i < module_paths_start_index) {
913
if (shared_path(i)->validate()) {
914
// Only count the app class paths not from the "Class-path" attribute of a jar manifest.
915
if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {
916
shared_app_paths_len++;
917
}
918
log_info(class, path)("ok");
919
} else {
920
if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
921
assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
922
}
923
return false;
924
}
925
} else if (i >= module_paths_start_index) {
926
if (shared_path(i)->validate(false /* not a class path entry */)) {
927
log_info(class, path)("ok");
928
} else {
929
if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) {
930
assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
931
}
932
return false;
933
}
934
}
935
}
936
937
if (header()->max_used_path_index() == 0) {
938
// default archive only contains the module image in the bootclasspath
939
assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
940
} else {
941
if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
942
fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
943
return false;
944
}
945
}
946
947
validate_non_existent_class_paths();
948
949
_validating_shared_path_table = false;
950
951
#if INCLUDE_JVMTI
952
if (_classpath_entries_for_jvmti != NULL) {
953
os::free(_classpath_entries_for_jvmti);
954
}
955
size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
956
_classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
957
memset((void*)_classpath_entries_for_jvmti, 0, sz);
958
#endif
959
960
return true;
961
}
962
963
void FileMapInfo::validate_non_existent_class_paths() {
964
// All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
965
// files on the app classpath. If any of these are found to exist during runtime,
966
// it will change how classes are loading for the app loader. For safety, disable
967
// loading of archived platform/app classes (currently there's no way to disable just the
968
// app classes).
969
970
assert(UseSharedSpaces, "runtime only");
971
for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();
972
i < get_number_of_shared_paths();
973
i++) {
974
SharedClassPathEntry* ent = shared_path(i);
975
if (!ent->check_non_existent()) {
976
warning("Archived non-system classes are disabled because the "
977
"file %s exists", ent->name());
978
header()->set_has_platform_or_app_classes(false);
979
}
980
}
981
}
982
983
bool FileMapInfo::check_archive(const char* archive_name, bool is_static) {
984
int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
985
if (fd < 0) {
986
// do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths()
987
// requires a shared archive name. The open_for_read() function will log a message regarding
988
// failure in opening a shared archive.
989
return false;
990
}
991
992
size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
993
void* header = os::malloc(sz, mtInternal);
994
memset(header, 0, sz);
995
size_t n = os::read(fd, header, (unsigned int)sz);
996
if (n != sz) {
997
os::free(header);
998
os::close(fd);
999
vm_exit_during_initialization("Unable to read header from shared archive", archive_name);
1000
return false;
1001
}
1002
if (is_static) {
1003
FileMapHeader* static_header = (FileMapHeader*)header;
1004
if (static_header->magic() != CDS_ARCHIVE_MAGIC) {
1005
os::free(header);
1006
os::close(fd);
1007
vm_exit_during_initialization("Not a base shared archive", archive_name);
1008
return false;
1009
}
1010
} else {
1011
DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header;
1012
if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1013
os::free(header);
1014
os::close(fd);
1015
vm_exit_during_initialization("Not a top shared archive", archive_name);
1016
return false;
1017
}
1018
}
1019
os::free(header);
1020
os::close(fd);
1021
return true;
1022
}
1023
1024
bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
1025
int* size, char** base_archive_name) {
1026
int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0);
1027
if (fd < 0) {
1028
*size = 0;
1029
return false;
1030
}
1031
1032
// read the header as a dynamic archive header
1033
size_t sz = sizeof(DynamicArchiveHeader);
1034
DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal);
1035
size_t n = os::read(fd, dynamic_header, (unsigned int)sz);
1036
if (n != sz) {
1037
fail_continue("Unable to read the file header.");
1038
os::free(dynamic_header);
1039
os::close(fd);
1040
return false;
1041
}
1042
if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1043
// Not a dynamic header, no need to proceed further.
1044
*size = 0;
1045
os::free(dynamic_header);
1046
os::close(fd);
1047
return false;
1048
}
1049
if (dynamic_header->base_archive_is_default()) {
1050
*base_archive_name = Arguments::get_default_shared_archive_path();
1051
} else {
1052
// read the base archive name
1053
size_t name_size = dynamic_header->base_archive_name_size();
1054
if (name_size == 0) {
1055
os::free(dynamic_header);
1056
os::close(fd);
1057
return false;
1058
}
1059
*base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal);
1060
n = os::read(fd, *base_archive_name, (unsigned int)name_size);
1061
if (n != name_size) {
1062
fail_continue("Unable to read the base archive name from the header.");
1063
FREE_C_HEAP_ARRAY(char, *base_archive_name);
1064
*base_archive_name = NULL;
1065
os::free(dynamic_header);
1066
os::close(fd);
1067
return false;
1068
}
1069
}
1070
1071
os::free(dynamic_header);
1072
os::close(fd);
1073
return true;
1074
}
1075
1076
// Read the FileMapInfo information from the file.
1077
1078
bool FileMapInfo::init_from_file(int fd) {
1079
size_t sz = is_static() ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader);
1080
size_t n = os::read(fd, header(), (unsigned int)sz);
1081
if (n != sz) {
1082
fail_continue("Unable to read the file header.");
1083
return false;
1084
}
1085
1086
if (!Arguments::has_jimage()) {
1087
FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
1088
return false;
1089
}
1090
1091
unsigned int expected_magic = is_static() ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;
1092
if (header()->magic() != expected_magic) {
1093
log_info(cds)("_magic expected: 0x%08x", expected_magic);
1094
log_info(cds)(" actual: 0x%08x", header()->magic());
1095
FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
1096
return false;
1097
}
1098
1099
if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
1100
log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);
1101
log_info(cds)(" actual: %d", header()->version());
1102
fail_continue("The shared archive file has the wrong version.");
1103
return false;
1104
}
1105
1106
if (header()->header_size() != sz) {
1107
log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);
1108
log_info(cds)(" actual: " SIZE_FORMAT, header()->header_size());
1109
FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");
1110
return false;
1111
}
1112
1113
const char* actual_ident = header()->jvm_ident();
1114
1115
if (actual_ident[JVM_IDENT_MAX-1] != 0) {
1116
FileMapInfo::fail_continue("JVM version identifier is corrupted.");
1117
return false;
1118
}
1119
1120
char expected_ident[JVM_IDENT_MAX];
1121
get_header_version(expected_ident);
1122
if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1123
log_info(cds)("_jvm_ident expected: %s", expected_ident);
1124
log_info(cds)(" actual: %s", actual_ident);
1125
FileMapInfo::fail_continue("The shared archive file was created by a different"
1126
" version or build of HotSpot");
1127
return false;
1128
}
1129
1130
if (VerifySharedSpaces) {
1131
int expected_crc = header()->compute_crc();
1132
if (expected_crc != header()->crc()) {
1133
log_info(cds)("_crc expected: %d", expected_crc);
1134
log_info(cds)(" actual: %d", header()->crc());
1135
FileMapInfo::fail_continue("Header checksum verification failed.");
1136
return false;
1137
}
1138
}
1139
1140
_file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name
1141
1142
if (is_static()) {
1143
// just checking the last region is sufficient since the archive is written
1144
// in sequential order
1145
size_t len = lseek(fd, 0, SEEK_END);
1146
FileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
1147
// The last space might be empty
1148
if (si->file_offset() > len || len - si->file_offset() < si->used()) {
1149
fail_continue("The shared archive file has been truncated.");
1150
return false;
1151
}
1152
}
1153
1154
return true;
1155
}
1156
1157
void FileMapInfo::seek_to_position(size_t pos) {
1158
if (lseek(_fd, (long)pos, SEEK_SET) < 0) {
1159
fail_stop("Unable to seek to position " SIZE_FORMAT, pos);
1160
}
1161
}
1162
1163
// Read the FileMapInfo information from the file.
1164
bool FileMapInfo::open_for_read() {
1165
if (_file_open) {
1166
return true;
1167
}
1168
if (is_static()) {
1169
_full_path = Arguments::GetSharedArchivePath();
1170
} else {
1171
_full_path = Arguments::GetSharedDynamicArchivePath();
1172
}
1173
log_info(cds)("trying to map %s", _full_path);
1174
int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1175
if (fd < 0) {
1176
if (errno == ENOENT) {
1177
fail_continue("Specified shared archive not found (%s).", _full_path);
1178
} else {
1179
fail_continue("Failed to open shared archive file (%s).",
1180
os::strerror(errno));
1181
}
1182
return false;
1183
} else {
1184
log_info(cds)("Opened archive %s.", _full_path);
1185
}
1186
1187
_fd = fd;
1188
_file_open = true;
1189
return true;
1190
}
1191
1192
// Write the FileMapInfo information to the file.
1193
1194
void FileMapInfo::open_for_write(const char* path) {
1195
if (path == NULL) {
1196
_full_path = Arguments::GetSharedArchivePath();
1197
} else {
1198
_full_path = path;
1199
}
1200
LogMessage(cds) msg;
1201
if (msg.is_info()) {
1202
msg.info("Dumping shared data to file: ");
1203
msg.info(" %s", _full_path);
1204
}
1205
1206
#ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.
1207
chmod(_full_path, _S_IREAD | _S_IWRITE);
1208
#endif
1209
1210
// Use remove() to delete the existing file because, on Unix, this will
1211
// allow processes that have it open continued access to the file.
1212
remove(_full_path);
1213
int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1214
if (fd < 0) {
1215
fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
1216
os::strerror(errno));
1217
}
1218
_fd = fd;
1219
_file_open = true;
1220
1221
// Seek past the header. We will write the header after all regions are written
1222
// and their CRCs computed.
1223
size_t header_bytes = header()->header_size();
1224
if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1225
header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1;
1226
}
1227
1228
header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());
1229
_file_offset = header_bytes;
1230
seek_to_position(_file_offset);
1231
}
1232
1233
1234
// Write the header to the file, seek to the next allocation boundary.
1235
1236
void FileMapInfo::write_header() {
1237
_file_offset = 0;
1238
seek_to_position(_file_offset);
1239
assert(is_file_position_aligned(), "must be");
1240
write_bytes(header(), header()->header_size());
1241
1242
if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) {
1243
char* base_archive_name = (char*)Arguments::GetSharedArchivePath();
1244
if (base_archive_name != NULL) {
1245
write_bytes(base_archive_name, header()->base_archive_name_size());
1246
}
1247
}
1248
}
1249
1250
size_t FileMapRegion::used_aligned() const {
1251
return align_up(used(), MetaspaceShared::core_region_alignment());
1252
}
1253
1254
void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
1255
bool allow_exec, int crc) {
1256
_is_heap_region = HeapShared::is_heap_region(region_index);
1257
_is_bitmap_region = (region_index == MetaspaceShared::bm);
1258
_mapping_offset = mapping_offset;
1259
_used = size;
1260
_read_only = read_only;
1261
_allow_exec = allow_exec;
1262
_crc = crc;
1263
_mapped_from_file = false;
1264
_mapped_base = NULL;
1265
}
1266
1267
1268
static const char* region_name(int region_index) {
1269
static const char* names[] = {
1270
"rw", "ro", "bm", "ca0", "ca1", "oa0", "oa1"
1271
};
1272
const int num_regions = sizeof(names)/sizeof(names[0]);
1273
assert(0 <= region_index && region_index < num_regions, "sanity");
1274
1275
return names[region_index];
1276
}
1277
1278
void FileMapRegion::print(outputStream* st, int region_index) {
1279
st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
1280
st->print_cr("- crc: 0x%08x", _crc);
1281
st->print_cr("- read_only: %d", _read_only);
1282
st->print_cr("- allow_exec: %d", _allow_exec);
1283
st->print_cr("- is_heap_region: %d", _is_heap_region);
1284
st->print_cr("- is_bitmap_region: %d", _is_bitmap_region);
1285
st->print_cr("- mapped_from_file: %d", _mapped_from_file);
1286
st->print_cr("- file_offset: " SIZE_FORMAT_HEX, _file_offset);
1287
st->print_cr("- mapping_offset: " SIZE_FORMAT_HEX, _mapping_offset);
1288
st->print_cr("- used: " SIZE_FORMAT, _used);
1289
st->print_cr("- oopmap_offset: " SIZE_FORMAT_HEX, _oopmap_offset);
1290
st->print_cr("- oopmap_size_in_bits: " SIZE_FORMAT, _oopmap_size_in_bits);
1291
st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base));
1292
}
1293
1294
void FileMapInfo::write_region(int region, char* base, size_t size,
1295
bool read_only, bool allow_exec) {
1296
Arguments::assert_is_dumping_archive();
1297
1298
FileMapRegion* si = space_at(region);
1299
char* requested_base;
1300
size_t mapping_offset = 0;
1301
1302
if (region == MetaspaceShared::bm) {
1303
requested_base = NULL; // always NULL for bm region
1304
} else if (size == 0) {
1305
// This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
1306
requested_base = NULL;
1307
} else if (HeapShared::is_heap_region(region)) {
1308
assert(!DynamicDumpSharedSpaces, "must be");
1309
requested_base = base;
1310
mapping_offset = (size_t)CompressedOops::encode_not_null(cast_to_oop(base));
1311
assert(mapping_offset == (size_t)(uint32_t)mapping_offset, "must be 32-bit only");
1312
} else {
1313
char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();
1314
requested_base = ArchiveBuilder::current()->to_requested(base);
1315
assert(requested_base >= requested_SharedBaseAddress, "must be");
1316
mapping_offset = requested_base - requested_SharedBaseAddress;
1317
}
1318
1319
si->set_file_offset(_file_offset);
1320
int crc = ClassLoader::crc32(0, base, (jint)size);
1321
if (size > 0) {
1322
log_info(cds)("Shared file region (%-3s) %d: " SIZE_FORMAT_W(8)
1323
" bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08)
1324
" crc 0x%08x",
1325
region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1326
}
1327
si->init(region, mapping_offset, size, read_only, allow_exec, crc);
1328
1329
if (base != NULL) {
1330
write_bytes_aligned(base, size);
1331
}
1332
}
1333
1334
size_t FileMapInfo::set_oopmaps_offset(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_size) {
1335
for (int i = 0; i < oopmaps->length(); i++) {
1336
oopmaps->at(i)._offset = curr_size;
1337
curr_size += oopmaps->at(i)._oopmap_size_in_bytes;
1338
}
1339
return curr_size;
1340
}
1341
1342
size_t FileMapInfo::write_oopmaps(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_offset, char* buffer) {
1343
for (int i = 0; i < oopmaps->length(); i++) {
1344
memcpy(buffer + curr_offset, oopmaps->at(i)._oopmap, oopmaps->at(i)._oopmap_size_in_bytes);
1345
curr_offset += oopmaps->at(i)._oopmap_size_in_bytes;
1346
}
1347
return curr_offset;
1348
}
1349
1350
char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap,
1351
GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps,
1352
GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps,
1353
size_t &size_in_bytes) {
1354
size_t size_in_bits = ptrmap->size();
1355
size_in_bytes = ptrmap->size_in_bytes();
1356
1357
if (closed_oopmaps != NULL && open_oopmaps != NULL) {
1358
size_in_bytes = set_oopmaps_offset(closed_oopmaps, size_in_bytes);
1359
size_in_bytes = set_oopmaps_offset(open_oopmaps, size_in_bytes);
1360
}
1361
1362
char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1363
ptrmap->write_to((BitMap::bm_word_t*)buffer, ptrmap->size_in_bytes());
1364
header()->set_ptrmap_size_in_bits(size_in_bits);
1365
1366
if (closed_oopmaps != NULL && open_oopmaps != NULL) {
1367
size_t curr_offset = write_oopmaps(closed_oopmaps, ptrmap->size_in_bytes(), buffer);
1368
write_oopmaps(open_oopmaps, curr_offset, buffer);
1369
}
1370
1371
write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1372
return buffer;
1373
}
1374
1375
// Write out the given archive heap memory regions. GC code combines multiple
1376
// consecutive archive GC regions into one MemRegion whenever possible and
1377
// produces the 'heap_mem' array.
1378
//
1379
// If the archive heap memory size is smaller than a single dump time GC region
1380
// size, there is only one MemRegion in the array.
1381
//
1382
// If the archive heap memory size is bigger than one dump time GC region size,
1383
// the 'heap_mem' array may contain more than one consolidated MemRegions. When
1384
// the first/bottom archive GC region is a partial GC region (with the empty
1385
// portion at the higher address within the region), one MemRegion is used for
1386
// the bottom partial archive GC region. The rest of the consecutive archive
1387
// GC regions are combined into another MemRegion.
1388
//
1389
// Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
1390
// + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
1391
// + We have 1 or 2 consolidated heap memory regions: r0 and r1
1392
//
1393
// If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
1394
// Otherwise:
1395
//
1396
// "X" represented space that's occupied by heap objects.
1397
// "_" represented unused spaced in the heap region.
1398
//
1399
//
1400
// |ah0 | ah1 | ah2| ...... | ahn|
1401
// |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
1402
// |<-r0->| |<- r1 ----------------->|
1403
// ^^^
1404
// |
1405
// +-- gap
1406
size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
1407
GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
1408
int first_region_id, int max_num_regions) {
1409
assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
1410
1411
int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
1412
if(arr_len > max_num_regions) {
1413
fail_stop("Unable to write archive heap memory regions: "
1414
"number of memory regions exceeds maximum due to fragmentation. "
1415
"Please increase java heap size "
1416
"(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").",
1417
MaxHeapSize, InitialHeapSize);
1418
}
1419
1420
size_t total_size = 0;
1421
for (int i = 0; i < max_num_regions; i++) {
1422
char* start = NULL;
1423
size_t size = 0;
1424
if (i < arr_len) {
1425
start = (char*)heap_mem->at(i).start();
1426
size = heap_mem->at(i).byte_size();
1427
total_size += size;
1428
}
1429
1430
int region_idx = i + first_region_id;
1431
write_region(region_idx, start, size, false, false);
1432
if (size > 0) {
1433
space_at(region_idx)->init_oopmap(oopmaps->at(i)._offset,
1434
oopmaps->at(i)._oopmap_size_in_bits);
1435
}
1436
}
1437
return total_size;
1438
}
1439
1440
// Dump bytes to file -- at the current file position.
1441
1442
void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1443
assert(_file_open, "must be");
1444
size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
1445
if (n != nbytes) {
1446
// If the shared archive is corrupted, close it and remove it.
1447
close();
1448
remove(_full_path);
1449
fail_stop("Unable to write to shared archive file.");
1450
}
1451
_file_offset += nbytes;
1452
}
1453
1454
bool FileMapInfo::is_file_position_aligned() const {
1455
return _file_offset == align_up(_file_offset,
1456
MetaspaceShared::core_region_alignment());
1457
}
1458
1459
// Align file position to an allocation unit boundary.
1460
1461
void FileMapInfo::align_file_position() {
1462
assert(_file_open, "must be");
1463
size_t new_file_offset = align_up(_file_offset,
1464
MetaspaceShared::core_region_alignment());
1465
if (new_file_offset != _file_offset) {
1466
_file_offset = new_file_offset;
1467
// Seek one byte back from the target and write a byte to insure
1468
// that the written file is the correct length.
1469
_file_offset -= 1;
1470
seek_to_position(_file_offset);
1471
char zero = 0;
1472
write_bytes(&zero, 1);
1473
}
1474
}
1475
1476
1477
// Dump bytes to file -- at the current file position.
1478
1479
void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1480
align_file_position();
1481
write_bytes(buffer, nbytes);
1482
align_file_position();
1483
}
1484
1485
// Close the shared archive file. This does NOT unmap mapped regions.
1486
1487
void FileMapInfo::close() {
1488
if (_file_open) {
1489
if (::close(_fd) < 0) {
1490
fail_stop("Unable to close the shared archive file.");
1491
}
1492
_file_open = false;
1493
_fd = -1;
1494
}
1495
}
1496
1497
1498
// JVM/TI RedefineClasses() support:
1499
// Remap the shared readonly space to shared readwrite, private.
1500
bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1501
int idx = MetaspaceShared::ro;
1502
FileMapRegion* si = space_at(idx);
1503
if (!si->read_only()) {
1504
// the space is already readwrite so we are done
1505
return true;
1506
}
1507
size_t size = si->used_aligned();
1508
if (!open_for_read()) {
1509
return false;
1510
}
1511
char *addr = region_addr(idx);
1512
char *base = os::remap_memory(_fd, _full_path, si->file_offset(),
1513
addr, size, false /* !read_only */,
1514
si->allow_exec());
1515
close();
1516
// These have to be errors because the shared region is now unmapped.
1517
if (base == NULL) {
1518
log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1519
vm_exit(1);
1520
}
1521
if (base != addr) {
1522
log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1523
vm_exit(1);
1524
}
1525
si->set_read_only(false);
1526
return true;
1527
}
1528
1529
// Memory map a region in the address space.
1530
static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap",
1531
"String1", "String2", "OpenArchive1", "OpenArchive2" };
1532
1533
MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1534
DEBUG_ONLY(FileMapRegion* last_region = NULL);
1535
intx addr_delta = mapped_base_address - header()->requested_base_address();
1536
1537
// Make sure we don't attempt to use header()->mapped_base_address() unless
1538
// it's been successfully mapped.
1539
DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1540
1541
for (int r = 0; r < num_regions; r++) {
1542
int idx = regions[r];
1543
MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1544
if (result != MAP_ARCHIVE_SUCCESS) {
1545
return result;
1546
}
1547
FileMapRegion* si = space_at(idx);
1548
DEBUG_ONLY(if (last_region != NULL) {
1549
// Ensure that the OS won't be able to allocate new memory spaces between any mapped
1550
// regions, or else it would mess up the simple comparision in MetaspaceObj::is_shared().
1551
assert(si->mapped_base() == last_region->mapped_end(), "must have no gaps");
1552
}
1553
last_region = si;)
1554
log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1555
idx, p2i(si->mapped_base()), p2i(si->mapped_end()),
1556
shared_region_name[idx]);
1557
1558
}
1559
1560
header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1561
if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1562
return MAP_ARCHIVE_OTHER_FAILURE;
1563
}
1564
1565
return MAP_ARCHIVE_SUCCESS;
1566
}
1567
1568
bool FileMapInfo::read_region(int i, char* base, size_t size) {
1569
assert(MetaspaceShared::use_windows_memory_mapping(), "used by windows only");
1570
FileMapRegion* si = space_at(i);
1571
log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1572
is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1573
shared_region_name[i], si->allow_exec() ? " exec" : "");
1574
if (!os::commit_memory(base, size, si->allow_exec())) {
1575
log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1576
i, shared_region_name[i]);
1577
return false;
1578
}
1579
if (lseek(_fd, (long)si->file_offset(), SEEK_SET) != (int)si->file_offset() ||
1580
read_bytes(base, size) != size) {
1581
return false;
1582
}
1583
return true;
1584
}
1585
1586
MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1587
assert(!HeapShared::is_heap_region(i), "sanity");
1588
FileMapRegion* si = space_at(i);
1589
size_t size = si->used_aligned();
1590
char *requested_addr = mapped_base_address + si->mapping_offset();
1591
assert(si->mapped_base() == NULL, "must be not mapped yet");
1592
assert(requested_addr != NULL, "must be specified");
1593
1594
si->set_mapped_from_file(false);
1595
1596
if (MetaspaceShared::use_windows_memory_mapping()) {
1597
// Windows cannot remap read-only shared memory to read-write when required for
1598
// RedefineClasses, which is also used by JFR. Always map windows regions as RW.
1599
si->set_read_only(false);
1600
} else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1601
Arguments::has_jfr_option()) {
1602
// If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1603
si->set_read_only(false);
1604
} else if (addr_delta != 0) {
1605
si->set_read_only(false); // Need to patch the pointers
1606
}
1607
1608
if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {
1609
// This is the second time we try to map the archive(s). We have already created a ReservedSpace
1610
// that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1611
// can't mmap into a ReservedSpace, so we just os::read() the data. We're going to patch all the
1612
// regions anyway, so there's no benefit for mmap anyway.
1613
if (!read_region(i, requested_addr, size)) {
1614
log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1615
shared_region_name[i], p2i(requested_addr));
1616
return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1617
}
1618
} else {
1619
// Note that this may either be a "fresh" mapping into unreserved address
1620
// space (Windows, first mapping attempt), or a mapping into pre-reserved
1621
// space (Posix). See also comment in MetaspaceShared::map_archives().
1622
char* base = os::map_memory(_fd, _full_path, si->file_offset(),
1623
requested_addr, size, si->read_only(),
1624
si->allow_exec(), mtClassShared);
1625
if (base != requested_addr) {
1626
log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,
1627
shared_region_name[i], p2i(requested_addr));
1628
_memory_mapping_failed = true;
1629
return MAP_ARCHIVE_MMAP_FAILURE;
1630
}
1631
si->set_mapped_from_file(true);
1632
}
1633
si->set_mapped_base(requested_addr);
1634
1635
if (VerifySharedSpaces && !verify_region_checksum(i)) {
1636
return MAP_ARCHIVE_OTHER_FAILURE;
1637
}
1638
1639
return MAP_ARCHIVE_SUCCESS;
1640
}
1641
1642
// The return value is the location of the archive relocation bitmap.
1643
char* FileMapInfo::map_bitmap_region() {
1644
FileMapRegion* si = space_at(MetaspaceShared::bm);
1645
if (si->mapped_base() != NULL) {
1646
return si->mapped_base();
1647
}
1648
bool read_only = true, allow_exec = false;
1649
char* requested_addr = NULL; // allow OS to pick any location
1650
char* bitmap_base = os::map_memory(_fd, _full_path, si->file_offset(),
1651
requested_addr, si->used_aligned(), read_only, allow_exec, mtClassShared);
1652
if (bitmap_base == NULL) {
1653
log_info(cds)("failed to map relocation bitmap");
1654
return NULL;
1655
}
1656
1657
if (VerifySharedSpaces && !region_crc_check(bitmap_base, si->used(), si->crc())) {
1658
log_error(cds)("relocation bitmap CRC error");
1659
if (!os::unmap_memory(bitmap_base, si->used_aligned())) {
1660
fatal("os::unmap_memory of relocation bitmap failed");
1661
}
1662
return NULL;
1663
}
1664
1665
si->set_mapped_base(bitmap_base);
1666
si->set_mapped_from_file(true);
1667
log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1668
is_static() ? "static " : "dynamic",
1669
MetaspaceShared::bm, p2i(si->mapped_base()), p2i(si->mapped_end()),
1670
shared_region_name[MetaspaceShared::bm]);
1671
return bitmap_base;
1672
}
1673
1674
// This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
1675
// We relocate all pointers in the 2 core regions (ro, rw).
1676
bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
1677
log_debug(cds, reloc)("runtime archive relocation start");
1678
char* bitmap_base = map_bitmap_region();
1679
1680
if (bitmap_base == NULL) {
1681
return false; // OOM, or CRC check failure
1682
} else {
1683
size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits();
1684
log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",
1685
p2i(bitmap_base), ptrmap_size_in_bits);
1686
1687
BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits);
1688
1689
// Patch all pointers in the the mapped region that are marked by ptrmap.
1690
address patch_base = (address)mapped_base();
1691
address patch_end = (address)mapped_end();
1692
1693
// the current value of the pointers to be patched must be within this
1694
// range (i.e., must be between the requesed base address, and the of the current archive).
1695
// Note: top archive may point to objects in the base archive, but not the other way around.
1696
address valid_old_base = (address)header()->requested_base_address();
1697
address valid_old_end = valid_old_base + mapping_end_offset();
1698
1699
// after patching, the pointers must point inside this range
1700
// (the requested location of the archive, as mapped at runtime).
1701
address valid_new_base = (address)header()->mapped_base_address();
1702
address valid_new_end = (address)mapped_end();
1703
1704
SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1705
valid_new_base, valid_new_end, addr_delta);
1706
ptrmap.iterate(&patcher);
1707
1708
// The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().
1709
1710
log_debug(cds, reloc)("runtime archive relocation done");
1711
return true;
1712
}
1713
}
1714
1715
size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1716
assert(_file_open, "Archive file is not open");
1717
size_t n = os::read(_fd, buffer, (unsigned int)count);
1718
if (n != count) {
1719
// Close the file if there's a problem reading it.
1720
close();
1721
return 0;
1722
}
1723
_file_offset += count;
1724
return count;
1725
}
1726
1727
address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) {
1728
size_t offset = spc->mapping_offset();
1729
narrowOop n = CompressedOops::narrow_oop_cast(offset);
1730
if (with_current_oop_encoding_mode) {
1731
return cast_from_oop<address>(CompressedOops::decode_raw_not_null(n));
1732
} else {
1733
return cast_from_oop<address>(HeapShared::decode_from_archive(n));
1734
}
1735
}
1736
1737
static MemRegion *closed_archive_heap_ranges = NULL;
1738
static MemRegion *open_archive_heap_ranges = NULL;
1739
static int num_closed_archive_heap_ranges = 0;
1740
static int num_open_archive_heap_ranges = 0;
1741
1742
#if INCLUDE_CDS_JAVA_HEAP
1743
bool FileMapInfo::has_heap_regions() {
1744
return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0);
1745
}
1746
1747
// Returns the address range of the archived heap regions computed using the
1748
// current oop encoding mode. This range may be different than the one seen at
1749
// dump time due to encoding mode differences. The result is used in determining
1750
// if/how these regions should be relocated at run time.
1751
MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
1752
address start = (address) max_uintx;
1753
address end = NULL;
1754
1755
for (int i = MetaspaceShared::first_closed_archive_heap_region;
1756
i <= MetaspaceShared::last_valid_region;
1757
i++) {
1758
FileMapRegion* si = space_at(i);
1759
size_t size = si->used();
1760
if (size > 0) {
1761
address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
1762
address e = s + size;
1763
if (start > s) {
1764
start = s;
1765
}
1766
if (end < e) {
1767
end = e;
1768
}
1769
}
1770
}
1771
assert(end != NULL, "must have at least one used heap region");
1772
return MemRegion((HeapWord*)start, (HeapWord*)end);
1773
}
1774
1775
//
1776
// Map the closed and open archive heap objects to the runtime java heap.
1777
//
1778
// The shared objects are mapped at (or close to ) the java heap top in
1779
// closed archive regions. The mapped objects contain no out-going
1780
// references to any other java heap regions. GC does not write into the
1781
// mapped closed archive heap region.
1782
//
1783
// The open archive heap objects are mapped below the shared objects in
1784
// the runtime java heap. The mapped open archive heap data only contains
1785
// references to the shared objects and open archive objects initially.
1786
// During runtime execution, out-going references to any other java heap
1787
// regions may be added. GC may mark and update references in the mapped
1788
// open archive objects.
1789
void FileMapInfo::map_heap_regions_impl() {
1790
if (!HeapShared::is_heap_object_archiving_allowed()) {
1791
log_info(cds)("CDS heap data is being ignored. UseG1GC, "
1792
"UseCompressedOops and UseCompressedClassPointers are required.");
1793
return;
1794
}
1795
1796
if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1797
ShouldNotReachHere(); // CDS should have been disabled.
1798
// The archived objects are mapped at JVM start-up, but we don't know if
1799
// j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1800
// which would make the archived String or mirror objects invalid. Let's be safe and not
1801
// use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1802
//
1803
// If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1804
// in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1805
// because we won't install an archived object subgraph if the klass of any of the
1806
// referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1807
}
1808
1809
log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1810
max_heap_size()/M);
1811
log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1812
p2i(narrow_klass_base()), narrow_klass_shift());
1813
log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1814
narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1815
log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",
1816
p2i(header()->heap_begin()), p2i(header()->heap_end()));
1817
1818
log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
1819
MaxHeapSize/M, HeapRegion::GrainBytes);
1820
log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1821
p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
1822
log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1823
CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1824
log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",
1825
p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
1826
1827
if (narrow_klass_base() != CompressedKlassPointers::base() ||
1828
narrow_klass_shift() != CompressedKlassPointers::shift()) {
1829
log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1830
return;
1831
}
1832
1833
if (narrow_oop_mode() != CompressedOops::mode() ||
1834
narrow_oop_base() != CompressedOops::base() ||
1835
narrow_oop_shift() != CompressedOops::shift()) {
1836
log_info(cds)("CDS heap data needs to be relocated because the archive was created with an incompatible oop encoding mode.");
1837
_heap_pointers_need_patching = true;
1838
} else {
1839
MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1840
if (!CompressedOops::is_in(range)) {
1841
log_info(cds)("CDS heap data needs to be relocated because");
1842
log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1843
log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end()));
1844
_heap_pointers_need_patching = true;
1845
} else if (header()->heap_end() != CompressedOops::end()) {
1846
log_info(cds)("CDS heap data needs to be relocated to the end of the runtime heap to reduce fragmentation");
1847
_heap_pointers_need_patching = true;
1848
}
1849
}
1850
1851
ptrdiff_t delta = 0;
1852
if (_heap_pointers_need_patching) {
1853
// dumptime heap end ------------v
1854
// [ |archived heap regions| ] runtime heap end ------v
1855
// [ |archived heap regions| ]
1856
// |<-----delta-------------------->|
1857
//
1858
// At dump time, the archived heap regions were near the top of the heap.
1859
// At run time, they may not be inside the heap, so we move them so
1860
// that they are now near the top of the runtime time. This can be done by
1861
// the simple math of adding the delta as shown above.
1862
address dumptime_heap_end = header()->heap_end();
1863
address runtime_heap_end = CompressedOops::end();
1864
delta = runtime_heap_end - dumptime_heap_end;
1865
}
1866
1867
log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1868
HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1869
1870
FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region);
1871
address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1872
if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) {
1873
// Align the bottom of the closed archive heap regions at G1 region boundary.
1874
// This will avoid the situation where the highest open region and the lowest
1875
// closed region sharing the same G1 region. Otherwise we will fail to map the
1876
// open regions.
1877
size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes;
1878
delta -= align;
1879
log_info(cds)("CDS heap data needs to be relocated lower by a further " SIZE_FORMAT
1880
" bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes",
1881
align, delta);
1882
HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1883
_heap_pointers_need_patching = true;
1884
relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si);
1885
}
1886
assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes),
1887
"must be");
1888
1889
// Map the closed_archive_heap regions, GC does not write into the regions.
1890
if (map_heap_data(&closed_archive_heap_ranges,
1891
MetaspaceShared::first_closed_archive_heap_region,
1892
MetaspaceShared::max_closed_archive_heap_region,
1893
&num_closed_archive_heap_ranges)) {
1894
HeapShared::set_closed_archive_heap_region_mapped();
1895
1896
// Now, map open_archive heap regions, GC can write into the regions.
1897
if (map_heap_data(&open_archive_heap_ranges,
1898
MetaspaceShared::first_open_archive_heap_region,
1899
MetaspaceShared::max_open_archive_heap_region,
1900
&num_open_archive_heap_ranges,
1901
true /* open */)) {
1902
HeapShared::set_open_archive_heap_region_mapped();
1903
HeapShared::set_roots(header()->heap_obj_roots());
1904
}
1905
}
1906
}
1907
1908
void FileMapInfo::map_heap_regions() {
1909
if (has_heap_regions()) {
1910
map_heap_regions_impl();
1911
}
1912
1913
if (!HeapShared::closed_archive_heap_region_mapped()) {
1914
assert(closed_archive_heap_ranges == NULL &&
1915
num_closed_archive_heap_ranges == 0, "sanity");
1916
}
1917
1918
if (!HeapShared::open_archive_heap_region_mapped()) {
1919
assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1920
MetaspaceShared::disable_full_module_graph();
1921
}
1922
}
1923
1924
bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1925
int max, int* num, bool is_open_archive) {
1926
MemRegion* regions = MemRegion::create_array(max, mtInternal);
1927
1928
struct Cleanup {
1929
MemRegion* _regions;
1930
uint _length;
1931
bool _aborted;
1932
Cleanup(MemRegion* regions, uint length) : _regions(regions), _length(length), _aborted(true) { }
1933
~Cleanup() { if (_aborted) { MemRegion::destroy_array(_regions, _length); } }
1934
} cleanup(regions, max);
1935
1936
FileMapRegion* si;
1937
int region_num = 0;
1938
1939
for (int i = first;
1940
i < first + max; i++) {
1941
si = space_at(i);
1942
size_t size = si->used();
1943
if (size > 0) {
1944
HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1945
regions[region_num] = MemRegion(start, size / HeapWordSize);
1946
region_num ++;
1947
log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1948
i, p2i(start), size);
1949
}
1950
}
1951
1952
if (region_num == 0) {
1953
return false; // no archived java heap data
1954
}
1955
1956
// Check that ranges are within the java heap
1957
if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1958
log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1959
return false;
1960
}
1961
1962
// allocate from java heap
1963
if (!G1CollectedHeap::heap()->alloc_archive_regions(
1964
regions, region_num, is_open_archive)) {
1965
log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1966
return false;
1967
}
1968
1969
// Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1970
// for mapped regions as they are part of the reserved java heap, which is
1971
// already recorded.
1972
for (int i = 0; i < region_num; i++) {
1973
si = space_at(first + i);
1974
char* addr = (char*)regions[i].start();
1975
char* base = os::map_memory(_fd, _full_path, si->file_offset(),
1976
addr, regions[i].byte_size(), si->read_only(),
1977
si->allow_exec());
1978
if (base == NULL || base != addr) {
1979
// dealloc the regions from java heap
1980
dealloc_archive_heap_regions(regions, region_num);
1981
log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1982
INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1983
p2i(addr), regions[i].byte_size());
1984
return false;
1985
}
1986
1987
if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) {
1988
// dealloc the regions from java heap
1989
dealloc_archive_heap_regions(regions, region_num);
1990
log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1991
return false;
1992
}
1993
}
1994
1995
cleanup._aborted = false;
1996
// the shared heap data is mapped successfully
1997
*heap_mem = regions;
1998
*num = region_num;
1999
return true;
2000
}
2001
2002
void FileMapInfo::patch_archived_heap_embedded_pointers() {
2003
if (!_heap_pointers_need_patching) {
2004
return;
2005
}
2006
2007
log_info(cds)("patching heap embedded pointers");
2008
patch_archived_heap_embedded_pointers(closed_archive_heap_ranges,
2009
num_closed_archive_heap_ranges,
2010
MetaspaceShared::first_closed_archive_heap_region);
2011
2012
patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
2013
num_open_archive_heap_ranges,
2014
MetaspaceShared::first_open_archive_heap_region);
2015
}
2016
2017
void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
2018
int first_region_idx) {
2019
char* bitmap_base = map_bitmap_region();
2020
if (bitmap_base == NULL) {
2021
return;
2022
}
2023
for (int i=0; i<num_ranges; i++) {
2024
FileMapRegion* si = space_at(i + first_region_idx);
2025
HeapShared::patch_archived_heap_embedded_pointers(
2026
ranges[i],
2027
(address)(space_at(MetaspaceShared::bm)->mapped_base()) + si->oopmap_offset(),
2028
si->oopmap_size_in_bits());
2029
}
2030
}
2031
2032
// This internally allocates objects using vmClasses::Object_klass(), so it
2033
// must be called after the Object_klass is loaded
2034
void FileMapInfo::fixup_mapped_heap_regions() {
2035
assert(vmClasses::Object_klass_loaded(), "must be");
2036
// If any closed regions were found, call the fill routine to make them parseable.
2037
// Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found.
2038
if (num_closed_archive_heap_ranges != 0) {
2039
assert(closed_archive_heap_ranges != NULL,
2040
"Null closed_archive_heap_ranges array with non-zero count");
2041
G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges,
2042
num_closed_archive_heap_ranges);
2043
}
2044
2045
// do the same for mapped open archive heap regions
2046
if (num_open_archive_heap_ranges != 0) {
2047
assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
2048
G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
2049
num_open_archive_heap_ranges);
2050
2051
// Populate the open archive regions' G1BlockOffsetTableParts. That ensures
2052
// fast G1BlockOffsetTablePart::block_start operations for any given address
2053
// within the open archive regions when trying to find start of an object
2054
// (e.g. during card table scanning).
2055
//
2056
// This is only needed for open archive regions but not the closed archive
2057
// regions, because objects in closed archive regions never reference objects
2058
// outside the closed archive regions and they are immutable. So we never
2059
// need their BOT during garbage collection.
2060
G1CollectedHeap::heap()->populate_archive_regions_bot_part(open_archive_heap_ranges,
2061
num_open_archive_heap_ranges);
2062
}
2063
}
2064
2065
// dealloc the archive regions from java heap
2066
void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) {
2067
if (num > 0) {
2068
assert(regions != NULL, "Null archive ranges array with non-zero count");
2069
G1CollectedHeap::heap()->dealloc_archive_regions(regions, num);
2070
}
2071
}
2072
#endif // INCLUDE_CDS_JAVA_HEAP
2073
2074
bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) {
2075
int crc = ClassLoader::crc32(0, buf, (jint)size);
2076
if (crc != expected_crc) {
2077
fail_continue("Checksum verification failed.");
2078
return false;
2079
}
2080
return true;
2081
}
2082
2083
bool FileMapInfo::verify_region_checksum(int i) {
2084
assert(VerifySharedSpaces, "sanity");
2085
size_t sz = space_at(i)->used();
2086
2087
if (sz == 0) {
2088
return true; // no data
2089
} else {
2090
return region_crc_check(region_addr(i), sz, space_at(i)->crc());
2091
}
2092
}
2093
2094
void FileMapInfo::unmap_regions(int regions[], int num_regions) {
2095
for (int r = 0; r < num_regions; r++) {
2096
int idx = regions[r];
2097
unmap_region(idx);
2098
}
2099
}
2100
2101
// Unmap a memory region in the address space.
2102
2103
void FileMapInfo::unmap_region(int i) {
2104
assert(!HeapShared::is_heap_region(i), "sanity");
2105
FileMapRegion* si = space_at(i);
2106
char* mapped_base = si->mapped_base();
2107
size_t size = si->used_aligned();
2108
2109
if (mapped_base != NULL) {
2110
if (size > 0 && si->mapped_from_file()) {
2111
log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
2112
shared_region_name[i]);
2113
if (!os::unmap_memory(mapped_base, size)) {
2114
fatal("os::unmap_memory failed");
2115
}
2116
}
2117
si->set_mapped_base(NULL);
2118
}
2119
}
2120
2121
void FileMapInfo::assert_mark(bool check) {
2122
if (!check) {
2123
fail_stop("Mark mismatch while restoring from shared file.");
2124
}
2125
}
2126
2127
void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it, bool use_copy) {
2128
if (use_copy) {
2129
_saved_shared_path_table.metaspace_pointers_do(it);
2130
} else {
2131
_shared_path_table.metaspace_pointers_do(it);
2132
}
2133
}
2134
2135
FileMapInfo* FileMapInfo::_current_info = NULL;
2136
FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL;
2137
bool FileMapInfo::_heap_pointers_need_patching = false;
2138
SharedPathTable FileMapInfo::_shared_path_table;
2139
SharedPathTable FileMapInfo::_saved_shared_path_table;
2140
bool FileMapInfo::_validating_shared_path_table = false;
2141
bool FileMapInfo::_memory_mapping_failed = false;
2142
GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL;
2143
2144
// Open the shared archive file, read and validate the header
2145
// information (version, boot classpath, etc.). If initialization
2146
// fails, shared spaces are disabled and the file is closed. [See
2147
// fail_continue.]
2148
//
2149
// Validation of the archive is done in two steps:
2150
//
2151
// [1] validate_header() - done here.
2152
// [2] validate_shared_path_table - this is done later, because the table is in the RW
2153
// region of the archive, which is not mapped yet.
2154
bool FileMapInfo::initialize() {
2155
assert(UseSharedSpaces, "UseSharedSpaces expected.");
2156
2157
if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2158
// CDS assumes that no classes resolved in vmClasses::resolve_all()
2159
// are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
2160
// during the JVMTI "early" stage, so we can still use CDS if
2161
// JvmtiExport::has_early_class_hook_env() is false.
2162
FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
2163
return false;
2164
}
2165
2166
if (!open_for_read()) {
2167
return false;
2168
}
2169
if (!init_from_file(_fd)) {
2170
return false;
2171
}
2172
if (!validate_header()) {
2173
return false;
2174
}
2175
return true;
2176
}
2177
2178
char* FileMapInfo::region_addr(int idx) {
2179
FileMapRegion* si = space_at(idx);
2180
if (HeapShared::is_heap_region(idx)) {
2181
assert(DumpSharedSpaces, "The following doesn't work at runtime");
2182
return si->used() > 0 ?
2183
(char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
2184
} else {
2185
return si->mapped_base();
2186
}
2187
}
2188
2189
// The 2 core spaces are RW->RO
2190
FileMapRegion* FileMapInfo::first_core_space() const {
2191
return space_at(MetaspaceShared::rw);
2192
}
2193
2194
FileMapRegion* FileMapInfo::last_core_space() const {
2195
return space_at(MetaspaceShared::ro);
2196
}
2197
2198
void FileMapHeader::set_as_offset(char* p, size_t *offset) {
2199
*offset = ArchiveBuilder::current()->any_to_offset((address)p);
2200
}
2201
2202
int FileMapHeader::compute_crc() {
2203
char* start = (char*)this;
2204
// start computing from the field after _crc
2205
char* buf = (char*)&_crc + sizeof(_crc);
2206
size_t sz = _header_size - (buf - start);
2207
int crc = ClassLoader::crc32(0, buf, (jint)sz);
2208
return crc;
2209
}
2210
2211
// This function should only be called during run time with UseSharedSpaces enabled.
2212
bool FileMapHeader::validate() {
2213
if (_obj_alignment != ObjectAlignmentInBytes) {
2214
FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
2215
" does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
2216
_obj_alignment, ObjectAlignmentInBytes);
2217
return false;
2218
}
2219
if (_compact_strings != CompactStrings) {
2220
FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
2221
" does not equal the current CompactStrings setting (%s).",
2222
_compact_strings ? "enabled" : "disabled",
2223
CompactStrings ? "enabled" : "disabled");
2224
return false;
2225
}
2226
2227
// This must be done after header validation because it might change the
2228
// header data
2229
const char* prop = Arguments::get_property("java.system.class.loader");
2230
if (prop != NULL) {
2231
warning("Archived non-system classes are disabled because the "
2232
"java.system.class.loader property is specified (value = \"%s\"). "
2233
"To use archived non-system classes, this property must not be set", prop);
2234
_has_platform_or_app_classes = false;
2235
}
2236
2237
2238
if (!_verify_local && BytecodeVerificationLocal) {
2239
// we cannot load boot classes, so there's no point of using the CDS archive
2240
FileMapInfo::fail_continue("The shared archive file's BytecodeVerificationLocal setting (%s)"
2241
" does not equal the current BytecodeVerificationLocal setting (%s).",
2242
_verify_local ? "enabled" : "disabled",
2243
BytecodeVerificationLocal ? "enabled" : "disabled");
2244
return false;
2245
}
2246
2247
// For backwards compatibility, we don't check the BytecodeVerificationRemote setting
2248
// if the archive only contains system classes.
2249
if (_has_platform_or_app_classes
2250
&& !_verify_remote // we didn't verify the archived platform/app classes
2251
&& BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
2252
FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
2253
"verification setting than the current setting.");
2254
// Pretend that we didn't have any archived platform/app classes, so they won't be loaded
2255
// by SystemDictionaryShared.
2256
_has_platform_or_app_classes = false;
2257
}
2258
2259
// Java agents are allowed during run time. Therefore, the following condition is not
2260
// checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
2261
// Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
2262
// while AllowArchivingWithJavaAgent is set during the current run.
2263
if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
2264
FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different "
2265
"from the setting in the shared archive.");
2266
return false;
2267
}
2268
2269
if (_allow_archiving_with_java_agent) {
2270
warning("This archive was created with AllowArchivingWithJavaAgent. It should be used "
2271
"for testing purposes only and should not be used in a production environment");
2272
}
2273
2274
log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d",
2275
compressed_oops(), compressed_class_pointers());
2276
if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
2277
FileMapInfo::fail_continue("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
2278
"different from runtime, CDS will be disabled.");
2279
return false;
2280
}
2281
2282
if (!_use_optimized_module_handling) {
2283
MetaspaceShared::disable_optimized_module_handling();
2284
log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");
2285
}
2286
2287
if (!_use_full_module_graph) {
2288
MetaspaceShared::disable_full_module_graph();
2289
log_info(cds)("full module graph: disabled because archive was created without full module graph");
2290
}
2291
2292
return true;
2293
}
2294
2295
bool FileMapInfo::validate_header() {
2296
if (!header()->validate()) {
2297
return false;
2298
}
2299
if (_is_static) {
2300
return true;
2301
} else {
2302
return DynamicArchive::validate(this);
2303
}
2304
}
2305
2306
// Check if a given address is within one of the shared regions
2307
bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
2308
assert(idx == MetaspaceShared::ro ||
2309
idx == MetaspaceShared::rw, "invalid region index");
2310
char* base = region_addr(idx);
2311
if (p >= base && p < base + space_at(idx)->used()) {
2312
return true;
2313
}
2314
return false;
2315
}
2316
2317
// Unmap mapped regions of shared space.
2318
void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
2319
MetaspaceShared::set_shared_metaspace_range(NULL, NULL, NULL);
2320
2321
FileMapInfo *map_info = FileMapInfo::current_info();
2322
if (map_info) {
2323
map_info->fail_continue("%s", msg);
2324
for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
2325
if (!HeapShared::is_heap_region(i)) {
2326
map_info->unmap_region(i);
2327
}
2328
}
2329
// Dealloc the archive heap regions only without unmapping. The regions are part
2330
// of the java heap. Unmapping of the heap regions are managed by GC.
2331
map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
2332
num_open_archive_heap_ranges);
2333
map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges,
2334
num_closed_archive_heap_ranges);
2335
} else if (DumpSharedSpaces) {
2336
fail_stop("%s", msg);
2337
}
2338
}
2339
2340
#if INCLUDE_JVMTI
2341
ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL;
2342
2343
ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2344
ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2345
if (ent == NULL) {
2346
if (i == 0) {
2347
ent = ClassLoader::get_jrt_entry();
2348
assert(ent != NULL, "must be");
2349
} else {
2350
SharedClassPathEntry* scpe = shared_path(i);
2351
assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
2352
2353
const char* path = scpe->name();
2354
struct stat st;
2355
if (os::stat(path, &st) != 0) {
2356
char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2357
jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2358
THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
2359
} else {
2360
ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false);
2361
if (ent == NULL) {
2362
char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2363
jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2364
THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL);
2365
}
2366
}
2367
}
2368
2369
MutexLocker mu(THREAD, CDSClassFileStream_lock);
2370
if (_classpath_entries_for_jvmti[i] == NULL) {
2371
_classpath_entries_for_jvmti[i] = ent;
2372
} else {
2373
// Another thread has beat me to creating this entry
2374
delete ent;
2375
ent = _classpath_entries_for_jvmti[i];
2376
}
2377
}
2378
2379
return ent;
2380
}
2381
2382
ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2383
int path_index = ik->shared_classpath_index();
2384
assert(path_index >= 0, "should be called for shared built-in classes only");
2385
assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2386
2387
ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2388
assert(cpe != NULL, "must be");
2389
2390
Symbol* name = ik->name();
2391
const char* const class_name = name->as_C_string();
2392
const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2393
name->utf8_length());
2394
ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2395
ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2396
assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders.");
2397
log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2398
cfs->source(), cfs->length());
2399
return cfs;
2400
}
2401
2402
#endif
2403
2404