1 /*
2 * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "classfile/classLoader.inline.hpp"
28 #include "classfile/classLoaderExt.hpp"
29 #include "classfile/compactHashtable.inline.hpp"
30 #include "classfile/stringTable.hpp"
31 #include "classfile/symbolTable.hpp"
32 #include "classfile/systemDictionaryShared.hpp"
33 #include "classfile/altHashing.hpp"
34 #include "logging/log.hpp"
35 #include "logging/logStream.hpp"
36 #include "logging/logMessage.hpp"
37 #include "memory/filemap.hpp"
38 #include "memory/heapShared.inline.hpp"
39 #include "memory/iterator.inline.hpp"
40 #include "memory/metadataFactory.hpp"
41 #include "memory/metaspaceClosure.hpp"
42 #include "memory/metaspaceShared.hpp"
43 #include "memory/oopFactory.hpp"
44 #include "oops/compressedOops.inline.hpp"
45 #include "oops/objArrayOop.hpp"
46 #include "oops/oop.inline.hpp"
47 #include "prims/jvmtiExport.hpp"
48 #include "runtime/arguments.hpp"
49 #include "runtime/java.hpp"
50 #include "runtime/os.inline.hpp"
51 #include "runtime/vm_version.hpp"
52 #include "services/memTracker.hpp"
53 #include "utilities/align.hpp"
54 #include "utilities/defaultStream.hpp"
55 #if INCLUDE_G1GC
56 #include "gc/g1/g1CollectedHeap.hpp"
57 #include "gc/g1/heapRegion.hpp"
58 #endif
59
60 # include <sys/stat.h>
61 # include <errno.h>
62
63 #ifndef O_BINARY // if defined (Win32) use binary files.
64 #define O_BINARY 0 // otherwise do nothing.
65 #endif
66
67 extern address JVM_FunctionAtStart();
68 extern address JVM_FunctionAtEnd();
69
70 // Complain and stop. All error conditions occurring during the writing of
71 // an archive file should stop the process. Unrecoverable errors during
72 // the reading of the archive file should stop the process.
73
fail(const char * msg,va_list ap)74 static void fail(const char *msg, va_list ap) {
75 // This occurs very early during initialization: tty is not initialized.
76 jio_fprintf(defaultStream::error_stream(),
77 "An error has occurred while processing the"
78 " shared archive file.\n");
79 jio_vfprintf(defaultStream::error_stream(), msg, ap);
80 jio_fprintf(defaultStream::error_stream(), "\n");
81 // Do not change the text of the below message because some tests check for it.
82 vm_exit_during_initialization("Unable to use shared archive.", NULL);
83 }
84
85
fail_stop(const char * msg,...)86 void FileMapInfo::fail_stop(const char *msg, ...) {
87 va_list ap;
88 va_start(ap, msg);
89 fail(msg, ap); // Never returns.
90 va_end(ap); // for completeness.
91 }
92
93
94 // Complain and continue. Recoverable errors during the reading of the
95 // archive file may continue (with sharing disabled).
96 //
97 // If we continue, then disable shared spaces and close the file.
98
fail_continue(const char * msg,...)99 void FileMapInfo::fail_continue(const char *msg, ...) {
100 va_list ap;
101 va_start(ap, msg);
102 MetaspaceShared::set_archive_loading_failed();
103 if (PrintSharedArchiveAndExit && _validating_shared_path_table) {
104 // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
105 // do not validate, we can still continue "limping" to validate the remaining
106 // entries. No need to quit.
107 tty->print("[");
108 tty->vprint(msg, ap);
109 tty->print_cr("]");
110 } else {
111 if (RequireSharedSpaces) {
112 fail(msg, ap);
113 } else {
114 if (log_is_enabled(Info, cds)) {
115 ResourceMark rm;
116 LogStream ls(Log(cds)::info());
117 ls.print("UseSharedSpaces: ");
118 ls.vprint_cr(msg, ap);
119 }
120 }
121 UseSharedSpaces = false;
122 assert(current_info() != NULL, "singleton must be registered");
123 current_info()->close();
124 }
125 va_end(ap);
126 }
127
128 // Fill in the fileMapInfo structure with data about this VM instance.
129
130 // This method copies the vm version info into header_version. If the version is too
131 // long then a truncated version, which has a hash code appended to it, is copied.
132 //
133 // Using a template enables this method to verify that header_version is an array of
134 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and
135 // the code that reads the CDS file will both use the same size buffer. Hence, will
136 // use identical truncation. This is necessary for matching of truncated versions.
get_header_version(char (& header_version)[N])137 template <int N> static void get_header_version(char (&header_version) [N]) {
138 assert(N == JVM_IDENT_MAX, "Bad header_version size");
139
140 const char *vm_version = VM_Version::internal_vm_info_string();
141 const int version_len = (int)strlen(vm_version);
142
143 memset(header_version, 0, JVM_IDENT_MAX);
144
145 if (version_len < (JVM_IDENT_MAX-1)) {
146 strcpy(header_version, vm_version);
147
148 } else {
149 // Get the hash value. Use a static seed because the hash needs to return the same
150 // value over multiple jvm invocations.
151 uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
152
153 // Truncate the ident, saving room for the 8 hex character hash value.
154 strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
155
156 // Append the hash code as eight hex digits.
157 sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
158 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate.
159 }
160
161 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
162 }
163
FileMapInfo()164 FileMapInfo::FileMapInfo() {
165 assert(_current_info == NULL, "must be singleton"); // not thread safe
166 _current_info = this;
167 memset((void*)this, 0, sizeof(FileMapInfo));
168 _file_offset = 0;
169 _file_open = false;
170 _header = (FileMapHeader*)os::malloc(sizeof(FileMapHeader), mtInternal);
171 _header->_version = INVALID_CDS_ARCHIVE_VERSION;
172 _header->_has_platform_or_app_classes = true;
173 }
174
~FileMapInfo()175 FileMapInfo::~FileMapInfo() {
176 assert(_current_info == this, "must be singleton"); // not thread safe
177 _current_info = NULL;
178 }
179
populate_header(size_t alignment)180 void FileMapInfo::populate_header(size_t alignment) {
181 _header->populate(this, alignment);
182 }
183
populate(FileMapInfo * mapinfo,size_t alignment)184 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
185 _magic = CDS_ARCHIVE_MAGIC;
186 _version = CURRENT_CDS_ARCHIVE_VERSION;
187 _alignment = alignment;
188 _obj_alignment = ObjectAlignmentInBytes;
189 _compact_strings = CompactStrings;
190 _narrow_oop_mode = Universe::narrow_oop_mode();
191 _narrow_oop_base = Universe::narrow_oop_base();
192 _narrow_oop_shift = Universe::narrow_oop_shift();
193 _max_heap_size = MaxHeapSize;
194 _narrow_klass_base = Universe::narrow_klass_base();
195 _narrow_klass_shift = Universe::narrow_klass_shift();
196 _shared_path_table_size = mapinfo->_shared_path_table_size;
197 _shared_path_table = mapinfo->_shared_path_table;
198 _shared_path_entry_size = mapinfo->_shared_path_entry_size;
199 if (MetaspaceShared::is_heap_object_archiving_allowed()) {
200 _heap_reserved = Universe::heap()->reserved_region();
201 }
202
203 // The following fields are for sanity checks for whether this archive
204 // will function correctly with this JVM and the bootclasspath it's
205 // invoked with.
206
207 // JVM version string ... changes on each build.
208 get_header_version(_jvm_ident);
209
210 ClassLoaderExt::finalize_shared_paths_misc_info();
211 _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
212 _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
213 _max_used_path_index = ClassLoaderExt::max_used_path_index();
214
215 _verify_local = BytecodeVerificationLocal;
216 _verify_remote = BytecodeVerificationRemote;
217 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
218 }
219
init(const char * name,bool is_modules_image,TRAPS)220 void SharedClassPathEntry::init(const char* name, bool is_modules_image, TRAPS) {
221 assert(DumpSharedSpaces, "dump time only");
222 _timestamp = 0;
223 _filesize = 0;
224
225 struct stat st;
226 if (os::stat(name, &st) == 0) {
227 if ((st.st_mode & S_IFMT) == S_IFDIR) {
228 _type = dir_entry;
229 } else {
230 // The timestamp of the modules_image is not checked at runtime.
231 if (is_modules_image) {
232 _type = modules_image_entry;
233 } else {
234 _type = jar_entry;
235 _timestamp = st.st_mtime;
236 }
237 _filesize = st.st_size;
238 }
239 } else {
240 // The file/dir must exist, or it would not have been added
241 // into ClassLoader::classpath_entry().
242 //
243 // If we can't access a jar file in the boot path, then we can't
244 // make assumptions about where classes get loaded from.
245 FileMapInfo::fail_stop("Unable to open file %s.", name);
246 }
247
248 size_t len = strlen(name) + 1;
249 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD);
250 strcpy(_name->data(), name);
251 }
252
validate(bool is_class_path)253 bool SharedClassPathEntry::validate(bool is_class_path) {
254 assert(UseSharedSpaces, "runtime only");
255
256 struct stat st;
257 const char* name;
258
259 // In order to validate the runtime modules image file size against the archived
260 // size information, we need to obtain the runtime modules image path. The recorded
261 // dump time modules image path in the archive may be different from the runtime path
262 // if the JDK image has beed moved after generating the archive.
263 if (is_modules_image()) {
264 name = ClassLoader::get_jrt_entry()->name();
265 } else {
266 name = this->name();
267 }
268
269 bool ok = true;
270 log_info(class, path)("checking shared classpath entry: %s", name);
271 if (os::stat(name, &st) != 0 && is_class_path) {
272 // If the archived module path entry does not exist at runtime, it is not fatal
273 // (no need to invalid the shared archive) because the shared runtime visibility check
274 // filters out any archived module classes that do not have a matching runtime
275 // module path location.
276 FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name);
277 ok = false;
278 } else if (is_dir()) {
279 if (!os::dir_is_empty(name)) {
280 FileMapInfo::fail_continue("directory is not empty: %s", name);
281 ok = false;
282 }
283 } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
284 _filesize != st.st_size) {
285 ok = false;
286 if (PrintSharedArchiveAndExit) {
287 FileMapInfo::fail_continue(_timestamp != st.st_mtime ?
288 "Timestamp mismatch" :
289 "File size mismatch");
290 } else {
291 FileMapInfo::fail_continue("A jar file is not the one used while building"
292 " the shared archive file: %s", name);
293 }
294 }
295 return ok;
296 }
297
metaspace_pointers_do(MetaspaceClosure * it)298 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
299 it->push(&_name);
300 it->push(&_manifest);
301 }
302
allocate_shared_path_table()303 void FileMapInfo::allocate_shared_path_table() {
304 assert(DumpSharedSpaces, "Sanity");
305
306 Thread* THREAD = Thread::current();
307 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
308 ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
309
310 assert(jrt != NULL,
311 "No modular java runtime image present when allocating the CDS classpath entry table");
312
313 size_t entry_size = sizeof(SharedClassPathEntry); // assert ( should be 8 byte aligned??)
314 int num_boot_classpath_entries = ClassLoader::num_boot_classpath_entries();
315 int num_app_classpath_entries = ClassLoader::num_app_classpath_entries();
316 int num_module_path_entries = ClassLoader::num_module_path_entries();
317 int num_entries = num_boot_classpath_entries + num_app_classpath_entries + num_module_path_entries;
318 size_t bytes = entry_size * num_entries;
319
320 _shared_path_table = MetadataFactory::new_array<u8>(loader_data, (int)(bytes + 7 / 8), THREAD);
321 _shared_path_table_size = num_entries;
322 _shared_path_entry_size = entry_size;
323
324 // 1. boot class path
325 int i = 0;
326 ClassPathEntry* cpe = jrt;
327 while (cpe != NULL) {
328 bool is_jrt = (cpe == jrt);
329 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
330 log_info(class, path)("add main shared path (%s) %s", type, cpe->name());
331 SharedClassPathEntry* ent = shared_path(i);
332 ent->init(cpe->name(), is_jrt, THREAD);
333 if (!is_jrt) { // No need to do the modules image.
334 EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
335 update_shared_classpath(cpe, ent, THREAD);
336 }
337 cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
338 i++;
339 }
340 assert(i == num_boot_classpath_entries,
341 "number of boot class path entry mismatch");
342
343 // 2. app class path
344 ClassPathEntry *acpe = ClassLoader::app_classpath_entries();
345 while (acpe != NULL) {
346 log_info(class, path)("add app shared path %s", acpe->name());
347 SharedClassPathEntry* ent = shared_path(i);
348 ent->init(acpe->name(), false, THREAD);
349 EXCEPTION_MARK;
350 update_shared_classpath(acpe, ent, THREAD);
351 acpe = acpe->next();
352 i++;
353 }
354
355 // 3. module path
356 ClassPathEntry *mpe = ClassLoader::module_path_entries();
357 while (mpe != NULL) {
358 log_info(class, path)("add module path %s",mpe->name());
359 SharedClassPathEntry* ent = shared_path(i);
360 ent->init(mpe->name(), false, THREAD);
361 EXCEPTION_MARK;
362 update_shared_classpath(mpe, ent, THREAD);
363 mpe = mpe->next();
364 i++;
365 }
366 assert(i == num_entries, "number of shared path entry mismatch");
367 }
368
check_nonempty_dir_in_shared_path_table()369 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
370 assert(DumpSharedSpaces, "dump time only");
371
372 bool has_nonempty_dir = false;
373
374 int last = _shared_path_table_size - 1;
375 if (last > ClassLoaderExt::max_used_path_index()) {
376 // no need to check any path beyond max_used_path_index
377 last = ClassLoaderExt::max_used_path_index();
378 }
379
380 for (int i = 0; i <= last; i++) {
381 SharedClassPathEntry *e = shared_path(i);
382 if (e->is_dir()) {
383 const char* path = e->name();
384 if (!os::dir_is_empty(path)) {
385 tty->print_cr("Error: non-empty directory '%s'", path);
386 has_nonempty_dir = true;
387 }
388 }
389 }
390
391 if (has_nonempty_dir) {
392 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL);
393 }
394 }
395
396 class ManifestStream: public ResourceObj {
397 private:
398 u1* _buffer_start; // Buffer bottom
399 u1* _buffer_end; // Buffer top (one past last element)
400 u1* _current; // Current buffer position
401
402 public:
403 // Constructor
ManifestStream(u1 * buffer,int length)404 ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
405 _current(buffer) {
406 _buffer_end = buffer + length;
407 }
408
is_attr(u1 * attr,const char * name)409 static bool is_attr(u1* attr, const char* name) {
410 return strncmp((const char*)attr, name, strlen(name)) == 0;
411 }
412
copy_attr(u1 * value,size_t len)413 static char* copy_attr(u1* value, size_t len) {
414 char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
415 strncpy(buf, (char*)value, len);
416 buf[len] = 0;
417 return buf;
418 }
419
420 // The return value indicates if the JAR is signed or not
check_is_signed()421 bool check_is_signed() {
422 u1* attr = _current;
423 bool isSigned = false;
424 while (_current < _buffer_end) {
425 if (*_current == '\n') {
426 *_current = '\0';
427 u1* value = (u1*)strchr((char*)attr, ':');
428 if (value != NULL) {
429 assert(*(value+1) == ' ', "Unrecognized format" );
430 if (strstr((char*)attr, "-Digest") != NULL) {
431 isSigned = true;
432 break;
433 }
434 }
435 *_current = '\n'; // restore
436 attr = _current + 1;
437 }
438 _current ++;
439 }
440 return isSigned;
441 }
442 };
443
update_shared_classpath(ClassPathEntry * cpe,SharedClassPathEntry * ent,TRAPS)444 void FileMapInfo::update_shared_classpath(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
445 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
446 ResourceMark rm(THREAD);
447 jint manifest_size;
448
449 if (cpe->is_jar_file()) {
450 assert(ent->is_jar(), "the shared class path entry is not a JAR file");
451 char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK);
452 if (manifest != NULL) {
453 ManifestStream* stream = new ManifestStream((u1*)manifest,
454 manifest_size);
455 if (stream->check_is_signed()) {
456 ent->set_is_signed();
457 } else {
458 // Copy the manifest into the shared archive
459 manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK);
460 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
461 manifest_size,
462 THREAD);
463 char* p = (char*)(buf->data());
464 memcpy(p, manifest, manifest_size);
465 ent->set_manifest(buf);
466 }
467 }
468 }
469 }
470
471
validate_shared_path_table()472 bool FileMapInfo::validate_shared_path_table() {
473 assert(UseSharedSpaces, "runtime only");
474
475 _validating_shared_path_table = true;
476 _shared_path_table = _header->_shared_path_table;
477 _shared_path_entry_size = _header->_shared_path_entry_size;
478 _shared_path_table_size = _header->_shared_path_table_size;
479
480 int module_paths_start_index = _header->_app_module_paths_start_index;
481
482 // validate the path entries up to the _max_used_path_index
483 for (int i=0; i < _header->_max_used_path_index + 1; i++) {
484 if (i < module_paths_start_index) {
485 if (shared_path(i)->validate()) {
486 log_info(class, path)("ok");
487 }
488 } else if (i >= module_paths_start_index) {
489 if (shared_path(i)->validate(false /* not a class path entry */)) {
490 log_info(class, path)("ok");
491 }
492 } else if (!PrintSharedArchiveAndExit) {
493 _validating_shared_path_table = false;
494 _shared_path_table = NULL;
495 _shared_path_table_size = 0;
496 return false;
497 }
498 }
499
500 _validating_shared_path_table = false;
501 return true;
502 }
503
504 // Read the FileMapInfo information from the file.
505
init_from_file(int fd)506 bool FileMapInfo::init_from_file(int fd) {
507 size_t sz = sizeof(FileMapHeader);
508 size_t n = os::read(fd, _header, (unsigned int)sz);
509 if (n != sz) {
510 fail_continue("Unable to read the file header.");
511 return false;
512 }
513
514 if (!Arguments::has_jimage()) {
515 FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build.");
516 return false;
517 }
518
519 unsigned int expected_magic = CDS_ARCHIVE_MAGIC; // is_static ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC;
520 if (_header->_magic != expected_magic) {
521 log_info(cds)("_magic expected: 0x%08x", expected_magic);
522 log_info(cds)(" actual: 0x%08x", _header->_magic);
523 FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
524 return false;
525 }
526
527 if (_header->_version != CURRENT_CDS_ARCHIVE_VERSION) {
528 log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION);
529 log_info(cds)(" actual: %d", _header->_version);
530 fail_continue("The shared archive file has the wrong version.");
531 return false;
532 }
533
534 // From downport of "8226406: JVM fails to detect mismatched or corrupt CDS archive"
535 // Not applicable in 11 currently.
536 //if (_header->_header_size != sz) {
537 // log_info(cds)("_header_size expected: " SIZE_FORMAT, sz);
538 // log_info(cds)(" actual: " SIZE_FORMAT, _header->_header_size);
539 // FileMapInfo::fail_continue("The shared archive file has an incorrect header size.");
540 // return false;
541 // }
542
543 if (_header->_jvm_ident[JVM_IDENT_MAX-1] != 0) {
544 FileMapInfo::fail_continue("JVM version identifier is corrupted.");
545 return false;
546 }
547
548 char header_version[JVM_IDENT_MAX];
549 get_header_version(header_version);
550 if (strncmp(_header->_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
551 log_info(cds)("_jvm_ident expected: %s", header_version);
552 log_info(cds)(" actual: %s", _header->_jvm_ident);
553 FileMapInfo::fail_continue("The shared archive file was created by a different"
554 " version or build of HotSpot");
555 return false;
556 }
557
558 if (VerifySharedSpaces) {
559 int expected_crc = _header->compute_crc();
560 if (expected_crc != _header->_crc) {
561 log_info(cds)("_crc expected: %d", expected_crc);
562 log_info(cds)(" actual: %d", _header->_crc);
563 FileMapInfo::fail_continue("Header checksum verification failed.");
564 return false;
565 }
566 }
567
568 _file_offset = (long)n;
569
570 size_t info_size = _header->_paths_misc_info_size;
571 _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
572 if (_paths_misc_info == NULL) {
573 fail_continue("Unable to read the file header.");
574 return false;
575 }
576 n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
577 if (n != info_size) {
578 fail_continue("Unable to read the shared path info header.");
579 FREE_C_HEAP_ARRAY(char, _paths_misc_info);
580 _paths_misc_info = NULL;
581 return false;
582 }
583
584 size_t len = lseek(fd, 0, SEEK_END);
585 CDSFileMapRegion* si = space_at(MetaspaceShared::last_valid_region);
586 // The last space might be empty
587 if (si->_file_offset > len || len - si->_file_offset < si->_used) {
588 fail_continue("The shared archive file has been truncated.");
589 return false;
590 }
591
592 _file_offset += (long)n;
593
594 return true;
595 }
596
597
598 // Read the FileMapInfo information from the file.
open_for_read()599 bool FileMapInfo::open_for_read() {
600 _full_path = Arguments::GetSharedArchivePath();
601 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
602 if (fd < 0) {
603 if (errno == ENOENT) {
604 // Not locating the shared archive is ok.
605 fail_continue("Specified shared archive not found.");
606 } else {
607 fail_continue("Failed to open shared archive file (%s).",
608 os::strerror(errno));
609 }
610 return false;
611 }
612
613 _fd = fd;
614 _file_open = true;
615 return true;
616 }
617
618
619 // Write the FileMapInfo information to the file.
620
open_for_write()621 void FileMapInfo::open_for_write() {
622 _full_path = Arguments::GetSharedArchivePath();
623 LogMessage(cds) msg;
624 if (msg.is_info()) {
625 msg.info("Dumping shared data to file: ");
626 msg.info(" %s", _full_path);
627 }
628
629 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.
630 chmod(_full_path, _S_IREAD | _S_IWRITE);
631 #endif
632
633 // Use remove() to delete the existing file because, on Unix, this will
634 // allow processes that have it open continued access to the file.
635 remove(_full_path);
636 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
637 if (fd < 0) {
638 fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
639 os::strerror(errno));
640 }
641 _fd = fd;
642 _file_offset = 0;
643 _file_open = true;
644 }
645
646
647 // Write the header to the file, seek to the next allocation boundary.
648
write_header()649 void FileMapInfo::write_header() {
650 int info_size = ClassLoader::get_shared_paths_misc_info_size();
651
652 _header->_paths_misc_info_size = info_size;
653
654 align_file_position();
655 write_bytes(_header, sizeof(FileMapHeader));
656 write_bytes(ClassLoader::get_shared_paths_misc_info(), (size_t)info_size);
657 align_file_position();
658 }
659
660
661 // Dump region to file.
662
write_region(int region,char * base,size_t size,bool read_only,bool allow_exec)663 void FileMapInfo::write_region(int region, char* base, size_t size,
664 bool read_only, bool allow_exec) {
665 CDSFileMapRegion* si = space_at(region);
666
667 if (_file_open) {
668 guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
669 log_info(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08)
670 " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08),
671 region, size, p2i(base), _file_offset);
672 } else {
673 si->_file_offset = _file_offset;
674 }
675 if (MetaspaceShared::is_heap_region(region)) {
676 assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
677 if (base != NULL) {
678 si->_addr._offset = (intx)CompressedOops::encode_not_null((oop)base);
679 } else {
680 si->_addr._offset = 0;
681 }
682 } else {
683 si->_addr._base = base;
684 }
685 si->_used = size;
686 si->_read_only = read_only;
687 si->_allow_exec = allow_exec;
688 si->_crc = ClassLoader::crc32(0, base, (jint)size);
689 if (base != NULL) {
690 write_bytes_aligned(base, size);
691 }
692 }
693
694 // Write out the given archive heap memory regions. GC code combines multiple
695 // consecutive archive GC regions into one MemRegion whenever possible and
696 // produces the 'heap_mem' array.
697 //
698 // If the archive heap memory size is smaller than a single dump time GC region
699 // size, there is only one MemRegion in the array.
700 //
701 // If the archive heap memory size is bigger than one dump time GC region size,
702 // the 'heap_mem' array may contain more than one consolidated MemRegions. When
703 // the first/bottom archive GC region is a partial GC region (with the empty
704 // portion at the higher address within the region), one MemRegion is used for
705 // the bottom partial archive GC region. The rest of the consecutive archive
706 // GC regions are combined into another MemRegion.
707 //
708 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions).
709 // + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn
710 // + We have 1 or 2 consolidated heap memory regions: r0 and r1
711 //
712 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty.
713 // Otherwise:
714 //
715 // "X" represented space that's occupied by heap objects.
716 // "_" represented unused spaced in the heap region.
717 //
718 //
719 // |ah0 | ah1 | ah2| ...... | ahn|
720 // |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX|
721 // |<-r0->| |<- r1 ----------------->|
722 // ^^^
723 // |
724 // +-- gap
write_archive_heap_regions(GrowableArray<MemRegion> * heap_mem,GrowableArray<ArchiveHeapOopmapInfo> * oopmaps,int first_region_id,int max_num_regions)725 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem,
726 GrowableArray<ArchiveHeapOopmapInfo> *oopmaps,
727 int first_region_id, int max_num_regions) {
728 assert(max_num_regions <= 2, "Only support maximum 2 memory regions");
729
730 int arr_len = heap_mem == NULL ? 0 : heap_mem->length();
731 if(arr_len > max_num_regions) {
732 fail_stop("Unable to write archive heap memory regions: "
733 "number of memory regions exceeds maximum due to fragmentation");
734 }
735
736 size_t total_size = 0;
737 for (int i = first_region_id, arr_idx = 0;
738 i < first_region_id + max_num_regions;
739 i++, arr_idx++) {
740 char* start = NULL;
741 size_t size = 0;
742 if (arr_idx < arr_len) {
743 start = (char*)heap_mem->at(arr_idx).start();
744 size = heap_mem->at(arr_idx).byte_size();
745 total_size += size;
746 }
747
748 log_info(cds)("Archive heap region %d " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes",
749 i, p2i(start), p2i(start + size), size);
750 write_region(i, start, size, false, false);
751 if (size > 0) {
752 space_at(i)->_oopmap = oopmaps->at(arr_idx)._oopmap;
753 space_at(i)->_oopmap_size_in_bits = oopmaps->at(arr_idx)._oopmap_size_in_bits;
754 }
755 }
756 return total_size;
757 }
758
759 // Dump bytes to file -- at the current file position.
760
write_bytes(const void * buffer,size_t nbytes)761 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
762 if (_file_open) {
763 size_t n = os::write(_fd, buffer, (unsigned int)nbytes);
764 if (n != nbytes) {
765 // It is dangerous to leave the corrupted shared archive file around,
766 // close and remove the file. See bug 6372906.
767 close();
768 remove(_full_path);
769 fail_stop("Unable to write to shared archive file.");
770 }
771 }
772 _file_offset += nbytes;
773 }
774
775
776 // Align file position to an allocation unit boundary.
777
align_file_position()778 void FileMapInfo::align_file_position() {
779 size_t new_file_offset = align_up(_file_offset,
780 os::vm_allocation_granularity());
781 if (new_file_offset != _file_offset) {
782 _file_offset = new_file_offset;
783 if (_file_open) {
784 // Seek one byte back from the target and write a byte to insure
785 // that the written file is the correct length.
786 _file_offset -= 1;
787 if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
788 fail_stop("Unable to seek.");
789 }
790 char zero = 0;
791 write_bytes(&zero, 1);
792 }
793 }
794 }
795
796
797 // Dump bytes to file -- at the current file position.
798
write_bytes_aligned(const void * buffer,size_t nbytes)799 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
800 align_file_position();
801 write_bytes(buffer, nbytes);
802 align_file_position();
803 }
804
805
806 // Close the shared archive file. This does NOT unmap mapped regions.
807
close()808 void FileMapInfo::close() {
809 if (_file_open) {
810 if (::close(_fd) < 0) {
811 fail_stop("Unable to close the shared archive file.");
812 }
813 _file_open = false;
814 _fd = -1;
815 }
816 }
817
818
819 // JVM/TI RedefineClasses() support:
820 // Remap the shared readonly space to shared readwrite, private.
remap_shared_readonly_as_readwrite()821 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
822 int idx = MetaspaceShared::ro;
823 CDSFileMapRegion* si = space_at(idx);
824 if (!si->_read_only) {
825 // the space is already readwrite so we are done
826 return true;
827 }
828 size_t used = si->_used;
829 size_t size = align_up(used, os::vm_allocation_granularity());
830 if (!open_for_read()) {
831 return false;
832 }
833 char *addr = region_addr(idx);
834 char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
835 addr, size, false /* !read_only */,
836 si->_allow_exec);
837 close();
838 if (base == NULL) {
839 fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
840 return false;
841 }
842 if (base != addr) {
843 fail_continue("Unable to remap shared readonly space at required address.");
844 return false;
845 }
846 si->_read_only = false;
847 return true;
848 }
849
850 // Map the whole region at once, assumed to be allocated contiguously.
reserve_shared_memory()851 ReservedSpace FileMapInfo::reserve_shared_memory() {
852 char* requested_addr = region_addr(0);
853 size_t size = FileMapInfo::core_spaces_size();
854
855 // Reserve the space first, then map otherwise map will go right over some
856 // other reserved memory (like the code cache).
857 ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
858 if (!rs.is_reserved()) {
859 fail_continue("Unable to reserve shared space at required address "
860 INTPTR_FORMAT, p2i(requested_addr));
861 return rs;
862 }
863 // the reserved virtual memory is for mapping class data sharing archive
864 MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
865
866 return rs;
867 }
868
869 // Memory map a region in the address space.
870 static const char* shared_region_name[] = { "MiscData", "ReadWrite", "ReadOnly", "MiscCode", "OptionalData",
871 "String1", "String2", "OpenArchive1", "OpenArchive2" };
872
map_region(int i,char ** top_ret)873 char* FileMapInfo::map_region(int i, char** top_ret) {
874 assert(!MetaspaceShared::is_heap_region(i), "sanity");
875 CDSFileMapRegion* si = space_at(i);
876 size_t used = si->_used;
877 size_t alignment = os::vm_allocation_granularity();
878 size_t size = align_up(used, alignment);
879 char *requested_addr = region_addr(i);
880
881 // If a tool agent is in use (debugging enabled), we must map the address space RW
882 if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
883 si->_read_only = false;
884 }
885
886 // map the contents of the CDS archive in this memory
887 char *base = os::map_memory(_fd, _full_path, si->_file_offset,
888 requested_addr, size, si->_read_only,
889 si->_allow_exec);
890 if (base == NULL || base != requested_addr) {
891 fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
892 return NULL;
893 }
894 #ifdef _WINDOWS
895 // This call is Windows-only because the memory_type gets recorded for the other platforms
896 // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
897 MemTracker::record_virtual_memory_type((address)base, mtClassShared);
898 #endif
899
900
901 if (!verify_region_checksum(i)) {
902 return NULL;
903 }
904
905 *top_ret = base + size;
906 return base;
907 }
908
decode_start_address(CDSFileMapRegion * spc,bool with_current_oop_encoding_mode)909 address FileMapInfo::decode_start_address(CDSFileMapRegion* spc, bool with_current_oop_encoding_mode) {
910 if (with_current_oop_encoding_mode) {
911 return (address)CompressedOops::decode_not_null(offset_of_space(spc));
912 } else {
913 return (address)HeapShared::decode_from_archive(offset_of_space(spc));
914 }
915 }
916
917 static MemRegion *string_ranges = NULL;
918 static MemRegion *open_archive_heap_ranges = NULL;
919 static int num_string_ranges = 0;
920 static int num_open_archive_heap_ranges = 0;
921
922 #if INCLUDE_CDS_JAVA_HEAP
has_heap_regions()923 bool FileMapInfo::has_heap_regions() {
924 return (_header->_space[MetaspaceShared::first_string]._used > 0);
925 }
926
927 // Returns the address range of the archived heap regions computed using the
928 // current oop encoding mode. This range may be different than the one seen at
929 // dump time due to encoding mode differences. The result is used in determining
930 // if/how these regions should be relocated at run time.
get_heap_regions_range_with_current_oop_encoding_mode()931 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() {
932 address start = (address) max_uintx;
933 address end = NULL;
934
935 for (int i = MetaspaceShared::first_string; i <= MetaspaceShared::last_valid_region; i++) {
936 CDSFileMapRegion* si = space_at(i);
937 size_t size = si->_used;
938 if (size > 0) {
939 address s = start_address_as_decoded_with_current_oop_encoding_mode(si);
940 address e = s + size;
941 if (start > s) {
942 start = s;
943 }
944 if (end < e) {
945 end = e;
946 }
947 }
948 }
949 assert(end != NULL, "must have at least one used heap region");
950 return MemRegion((HeapWord*)start, (HeapWord*)end);
951 }
952
953 //
954 // Map the shared string objects and open archive heap objects to the runtime
955 // java heap.
956 //
957 // The shared strings are mapped close to the end of the java heap top in
958 // closed archive regions. The mapped strings contain no out-going references
959 // to any other java heap regions. GC does not write into the mapped shared strings.
960 //
961 // The open archive heap objects are mapped below the shared strings in
962 // the runtime java heap. The mapped open archive heap data only contain
963 // references to the shared strings and open archive objects initially.
964 // During runtime execution, out-going references to any other java heap
965 // regions may be added. GC may mark and update references in the mapped
966 // open archive objects.
map_heap_regions_impl()967 void FileMapInfo::map_heap_regions_impl() {
968 if (!MetaspaceShared::is_heap_object_archiving_allowed()) {
969 log_info(cds)("CDS heap data is being ignored. UseG1GC, "
970 "UseCompressedOops and UseCompressedClassPointers are required.");
971 return;
972 }
973
974 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
975 ShouldNotReachHere(); // CDS should have been disabled.
976 // The archived objects are mapped at JVM start-up, but we don't know if
977 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
978 // which would make the archived String or mirror objects invalid. Let's be safe and not
979 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
980 //
981 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
982 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
983 // because we won't install an archived object subgraph if the klass of any of the
984 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
985 }
986
987 MemRegion heap_reserved = Universe::heap()->reserved_region();
988
989 log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
990 max_heap_size()/M);
991 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
992 p2i(narrow_klass_base()), narrow_klass_shift());
993 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
994 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
995
996 log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
997 heap_reserved.byte_size()/M, HeapRegion::GrainBytes);
998 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
999 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
1000 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1001 Universe::narrow_oop_mode(), p2i(Universe::narrow_oop_base()), Universe::narrow_oop_shift());
1002
1003 if (narrow_klass_base() != Universe::narrow_klass_base() ||
1004 narrow_klass_shift() != Universe::narrow_klass_shift()) {
1005 log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
1006 return;
1007 }
1008
1009 if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
1010 narrow_oop_base() != Universe::narrow_oop_base() ||
1011 narrow_oop_shift() != Universe::narrow_oop_shift()) {
1012 log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode.");
1013 _heap_pointers_need_patching = true;
1014 } else {
1015 MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode();
1016 if (!heap_reserved.contains(range)) {
1017 log_info(cds)("CDS heap data need to be relocated because");
1018 log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end()));
1019 log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(heap_reserved.start()), p2i(heap_reserved.end()));
1020 _heap_pointers_need_patching = true;
1021 }
1022 }
1023
1024 ptrdiff_t delta = 0;
1025 if (_heap_pointers_need_patching) {
1026 // dumptime heap end ------------v
1027 // [ |archived heap regions| ] runtime heap end ------v
1028 // [ |archived heap regions| ]
1029 // |<-----delta-------------------->|
1030 //
1031 // At dump time, the archived heap regions were near the top of the heap.
1032 // At run time, they may not be inside the heap, so we move them so
1033 // that they are now near the top of the runtime time. This can be done by
1034 // the simple math of adding the delta as shown above.
1035 address dumptime_heap_end = (address)_header->_heap_reserved.end();
1036 address runtime_heap_end = (address)heap_reserved.end();
1037 delta = runtime_heap_end - dumptime_heap_end;
1038 }
1039
1040 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
1041 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1042
1043 CDSFileMapRegion* si = space_at(MetaspaceShared::first_string);
1044 address relocated_strings_bottom = start_address_as_decoded_from_archive(si);
1045 if (!is_aligned(relocated_strings_bottom, HeapRegion::GrainBytes)) {
1046 // Align the bottom of the string regions at G1 region boundary. This will avoid
1047 // the situation where the highest open region and the lowest string region sharing
1048 // the same G1 region. Otherwise we will fail to map the open regions.
1049 size_t align = size_t(relocated_strings_bottom) % HeapRegion::GrainBytes;
1050 delta -= align;
1051 log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT
1052 " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes", align, delta);
1053 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift());
1054 _heap_pointers_need_patching = true;
1055 relocated_strings_bottom = start_address_as_decoded_from_archive(si);
1056 }
1057 assert(is_aligned(relocated_strings_bottom, HeapRegion::GrainBytes), "must be");
1058
1059 // First, map string regions as closed archive heap regions.
1060 // GC does not write into the regions.
1061 if (map_heap_data(&string_ranges,
1062 MetaspaceShared::first_string,
1063 MetaspaceShared::max_strings,
1064 &num_string_ranges)) {
1065 StringTable::set_shared_string_mapped();
1066
1067 // Now, map open_archive heap regions, GC can write into the regions.
1068 if (map_heap_data(&open_archive_heap_ranges,
1069 MetaspaceShared::first_open_archive_heap_region,
1070 MetaspaceShared::max_open_archive_heap_region,
1071 &num_open_archive_heap_ranges,
1072 true /* open */)) {
1073 MetaspaceShared::set_open_archive_heap_region_mapped();
1074 }
1075 }
1076 }
1077
map_heap_regions()1078 void FileMapInfo::map_heap_regions() {
1079 if (has_heap_regions()) {
1080 map_heap_regions_impl();
1081 }
1082
1083 if (!StringTable::shared_string_mapped()) {
1084 assert(string_ranges == NULL && num_string_ranges == 0, "sanity");
1085 }
1086
1087 if (!MetaspaceShared::open_archive_heap_region_mapped()) {
1088 assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity");
1089 }
1090 }
1091
map_heap_data(MemRegion ** heap_mem,int first,int max,int * num,bool is_open_archive)1092 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first,
1093 int max, int* num, bool is_open_archive) {
1094 MemRegion * regions = new MemRegion[max];
1095 CDSFileMapRegion* si;
1096 int region_num = 0;
1097
1098 for (int i = first;
1099 i < first + max; i++) {
1100 si = space_at(i);
1101 size_t size = si->_used;
1102 if (size > 0) {
1103 HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si);
1104 regions[region_num] = MemRegion(start, size / HeapWordSize);
1105 region_num ++;
1106 log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
1107 i, p2i(start), size);
1108 }
1109 }
1110
1111 if (region_num == 0) {
1112 return false; // no archived java heap data
1113 }
1114
1115 // Check that ranges are within the java heap
1116 if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) {
1117 log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap.");
1118 return false;
1119 }
1120
1121 // allocate from java heap
1122 if (!G1CollectedHeap::heap()->alloc_archive_regions(
1123 regions, region_num, is_open_archive)) {
1124 log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use.");
1125 return false;
1126 }
1127
1128 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
1129 // for mapped regions as they are part of the reserved java heap, which is
1130 // already recorded.
1131 for (int i = 0; i < region_num; i++) {
1132 si = space_at(first + i);
1133 char* addr = (char*)regions[i].start();
1134 char* base = os::map_memory(_fd, _full_path, si->_file_offset,
1135 addr, regions[i].byte_size(), si->_read_only,
1136 si->_allow_exec);
1137 if (base == NULL || base != addr) {
1138 // dealloc the regions from java heap
1139 dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1140 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
1141 INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
1142 p2i(addr), regions[i].byte_size());
1143 return false;
1144 }
1145 }
1146
1147 if (!verify_mapped_heap_regions(first, region_num)) {
1148 // dealloc the regions from java heap
1149 dealloc_archive_heap_regions(regions, region_num, is_open_archive);
1150 log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt");
1151 return false;
1152 }
1153
1154 // the shared heap data is mapped successfully
1155 *heap_mem = regions;
1156 *num = region_num;
1157 return true;
1158 }
1159
verify_mapped_heap_regions(int first,int num)1160 bool FileMapInfo::verify_mapped_heap_regions(int first, int num) {
1161 assert(num > 0, "sanity");
1162 for (int i = first; i < first + num; i++) {
1163 if (!verify_region_checksum(i)) {
1164 return false;
1165 }
1166 }
1167 return true;
1168 }
1169
patch_archived_heap_embedded_pointers()1170 void FileMapInfo::patch_archived_heap_embedded_pointers() {
1171 if (!_heap_pointers_need_patching) {
1172 return;
1173 }
1174
1175 patch_archived_heap_embedded_pointers(string_ranges,
1176 num_string_ranges,
1177 MetaspaceShared::first_string);
1178
1179 patch_archived_heap_embedded_pointers(open_archive_heap_ranges,
1180 num_open_archive_heap_ranges,
1181 MetaspaceShared::first_open_archive_heap_region);
1182 }
1183
patch_archived_heap_embedded_pointers(MemRegion * ranges,int num_ranges,int first_region_idx)1184 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges,
1185 int first_region_idx) {
1186 for (int i=0; i<num_ranges; i++) {
1187 CDSFileMapRegion* si = space_at(i + first_region_idx);
1188 HeapShared::patch_archived_heap_embedded_pointers(ranges[i], (address)si->_oopmap,
1189 si->_oopmap_size_in_bits);
1190 }
1191 }
1192
1193 // This internally allocates objects using SystemDictionary::Object_klass(), so it
1194 // must be called after the well-known classes are resolved.
fixup_mapped_heap_regions()1195 void FileMapInfo::fixup_mapped_heap_regions() {
1196 // If any string regions were found, call the fill routine to make them parseable.
1197 // Note that string_ranges may be non-NULL even if no ranges were found.
1198 if (num_string_ranges != 0) {
1199 assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
1200 G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_string_ranges);
1201 }
1202
1203 // do the same for mapped open archive heap regions
1204 if (num_open_archive_heap_ranges != 0) {
1205 assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count");
1206 G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges,
1207 num_open_archive_heap_ranges);
1208 }
1209 }
1210
1211 // dealloc the archive regions from java heap
dealloc_archive_heap_regions(MemRegion * regions,int num,bool is_open)1212 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num, bool is_open) {
1213 if (num > 0) {
1214 assert(regions != NULL, "Null archive ranges array with non-zero count");
1215 G1CollectedHeap::heap()->dealloc_archive_regions(regions, num, is_open);
1216 }
1217 }
1218 #endif // INCLUDE_CDS_JAVA_HEAP
1219
verify_region_checksum(int i)1220 bool FileMapInfo::verify_region_checksum(int i) {
1221 assert(i >= 0 && i < MetaspaceShared::n_regions, "invalid region");
1222 if (!VerifySharedSpaces) {
1223 return true;
1224 }
1225
1226 size_t sz = space_at(i)->_used;
1227
1228 if (sz == 0) {
1229 return true; // no data
1230 }
1231 if ((MetaspaceShared::is_string_region(i) &&
1232 !StringTable::shared_string_mapped()) ||
1233 (MetaspaceShared::is_open_archive_heap_region(i) &&
1234 !MetaspaceShared::open_archive_heap_region_mapped())) {
1235 return true; // archived heap data is not mapped
1236 }
1237 const char* buf = region_addr(i);
1238 int crc = ClassLoader::crc32(0, buf, (jint)sz);
1239 if (crc != space_at(i)->_crc) {
1240 fail_continue("Checksum verification failed.");
1241 return false;
1242 }
1243 return true;
1244 }
1245
1246 // Unmap a memory region in the address space.
1247
unmap_region(int i)1248 void FileMapInfo::unmap_region(int i) {
1249 assert(!MetaspaceShared::is_heap_region(i), "sanity");
1250 CDSFileMapRegion* si = space_at(i);
1251 size_t used = si->_used;
1252 size_t size = align_up(used, os::vm_allocation_granularity());
1253
1254 if (used == 0) {
1255 return;
1256 }
1257
1258 char* addr = region_addr(i);
1259 if (!os::unmap_memory(addr, size)) {
1260 fail_stop("Unable to unmap shared space.");
1261 }
1262 }
1263
assert_mark(bool check)1264 void FileMapInfo::assert_mark(bool check) {
1265 if (!check) {
1266 fail_stop("Mark mismatch while restoring from shared file.");
1267 }
1268 }
1269
metaspace_pointers_do(MetaspaceClosure * it)1270 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it) {
1271 it->push(&_shared_path_table);
1272 for (int i=0; i<_shared_path_table_size; i++) {
1273 shared_path(i)->metaspace_pointers_do(it);
1274 }
1275 }
1276
1277
1278 FileMapInfo* FileMapInfo::_current_info = NULL;
1279 bool FileMapInfo::_heap_pointers_need_patching = false;
1280 Array<u8>* FileMapInfo::_shared_path_table = NULL;
1281 int FileMapInfo::_shared_path_table_size = 0;
1282 size_t FileMapInfo::_shared_path_entry_size = 0x1234baad;
1283 bool FileMapInfo::_validating_shared_path_table = false;
1284
1285 // Open the shared archive file, read and validate the header
1286 // information (version, boot classpath, etc.). If initialization
1287 // fails, shared spaces are disabled and the file is closed. [See
1288 // fail_continue.]
1289 //
1290 // Validation of the archive is done in two steps:
1291 //
1292 // [1] validate_header() - done here. This checks the header, including _paths_misc_info.
1293 // [2] validate_shared_path_table - this is done later, because the table is in the RW
1294 // region of the archive, which is not mapped yet.
initialize()1295 bool FileMapInfo::initialize() {
1296 assert(UseSharedSpaces, "UseSharedSpaces expected.");
1297
1298 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1299 // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes
1300 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1301 // during the JVMTI "early" stage, so we can still use CDS if
1302 // JvmtiExport::has_early_class_hook_env() is false.
1303 FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1304 return false;
1305 }
1306
1307 if (!open_for_read()) {
1308 return false;
1309 }
1310
1311 init_from_file(_fd);
1312 // UseSharedSpaces could be disabled if the checking of some of the header fields in
1313 // init_from_file has failed.
1314 if (!UseSharedSpaces || !validate_header()) {
1315 return false;
1316 }
1317 return true;
1318 }
1319
region_addr(int idx)1320 char* FileMapInfo::region_addr(int idx) {
1321 CDSFileMapRegion* si = space_at(idx);
1322 if (MetaspaceShared::is_heap_region(idx)) {
1323 assert(DumpSharedSpaces, "The following doesn't work at runtime");
1324 return si->_used > 0 ?
1325 (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL;
1326 } else {
1327 return si->_addr._base;
1328 }
1329 }
1330
compute_crc()1331 int FileMapHeader::compute_crc() {
1332 char* start = (char*)this;
1333 // start computing from the field after _crc
1334 char* buf = (char*)&_crc + sizeof(_crc);
1335 size_t sz = sizeof(FileMapHeader) - (buf - start);
1336 int crc = ClassLoader::crc32(0, buf, (jint)sz);
1337 return crc;
1338 }
1339
1340 // This function should only be called during run time with UseSharedSpaces enabled.
validate()1341 bool FileMapHeader::validate() {
1342 if (_obj_alignment != ObjectAlignmentInBytes) {
1343 FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
1344 " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
1345 _obj_alignment, ObjectAlignmentInBytes);
1346 return false;
1347 }
1348 if (_compact_strings != CompactStrings) {
1349 FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
1350 " does not equal the current CompactStrings setting (%s).",
1351 _compact_strings ? "enabled" : "disabled",
1352 CompactStrings ? "enabled" : "disabled");
1353 return false;
1354 }
1355
1356 // This must be done after header validation because it might change the
1357 // header data
1358 const char* prop = Arguments::get_property("java.system.class.loader");
1359 if (prop != NULL) {
1360 warning("Archived non-system classes are disabled because the "
1361 "java.system.class.loader property is specified (value = \"%s\"). "
1362 "To use archived non-system classes, this property must be not be set", prop);
1363 _has_platform_or_app_classes = false;
1364 }
1365
1366 // For backwards compatibility, we don't check the verification setting
1367 // if the archive only contains system classes.
1368 if (_has_platform_or_app_classes &&
1369 ((!_verify_local && BytecodeVerificationLocal) ||
1370 (!_verify_remote && BytecodeVerificationRemote))) {
1371 FileMapInfo::fail_continue("The shared archive file was created with less restrictive "
1372 "verification setting than the current setting.");
1373 return false;
1374 }
1375
1376 return true;
1377 }
1378
validate_header()1379 bool FileMapInfo::validate_header() {
1380 bool status = _header->validate();
1381
1382 if (status) {
1383 if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
1384 if (!PrintSharedArchiveAndExit) {
1385 fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)");
1386 status = false;
1387 }
1388 }
1389 }
1390
1391 if (_paths_misc_info != NULL) {
1392 FREE_C_HEAP_ARRAY(char, _paths_misc_info);
1393 _paths_misc_info = NULL;
1394 }
1395 return status;
1396 }
1397
1398 // Check if a given address is within one of the shared regions
is_in_shared_region(const void * p,int idx)1399 bool FileMapInfo::is_in_shared_region(const void* p, int idx) {
1400 assert(idx == MetaspaceShared::ro ||
1401 idx == MetaspaceShared::rw ||
1402 idx == MetaspaceShared::mc ||
1403 idx == MetaspaceShared::md, "invalid region index");
1404 char* base = region_addr(idx);
1405 if (p >= base && p < base + space_at(idx)->_used) {
1406 return true;
1407 }
1408 return false;
1409 }
1410
1411 // Unmap mapped regions of shared space.
stop_sharing_and_unmap(const char * msg)1412 void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
1413 MetaspaceObj::set_shared_metaspace_range(NULL, NULL);
1414
1415 FileMapInfo *map_info = FileMapInfo::current_info();
1416 if (map_info) {
1417 map_info->fail_continue("%s", msg);
1418 for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) {
1419 if (!MetaspaceShared::is_heap_region(i)) {
1420 char *addr = map_info->region_addr(i);
1421 if (addr != NULL) {
1422 map_info->unmap_region(i);
1423 map_info->space_at(i)->_addr._base = NULL;
1424 }
1425 }
1426 }
1427 // Dealloc the archive heap regions only without unmapping. The regions are part
1428 // of the java heap. Unmapping of the heap regions are managed by GC.
1429 map_info->dealloc_archive_heap_regions(open_archive_heap_ranges,
1430 num_open_archive_heap_ranges,
1431 true);
1432 map_info->dealloc_archive_heap_regions(string_ranges,
1433 num_string_ranges,
1434 false);
1435 } else if (DumpSharedSpaces) {
1436 fail_stop("%s", msg);
1437 }
1438 }
1439