filemap.cpp revision 10627:1537c752a7f5
1193326Sed/*
2193326Sed * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
3193326Sed * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4193326Sed *
5193326Sed * This code is free software; you can redistribute it and/or modify it
6193326Sed * under the terms of the GNU General Public License version 2 only, as
7193326Sed * published by the Free Software Foundation.
8193326Sed *
9193326Sed * This code is distributed in the hope that it will be useful, but WITHOUT
10193326Sed * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11193326Sed * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12193326Sed * version 2 for more details (a copy is included in the LICENSE file that
13193326Sed * accompanied this code).
14193326Sed *
15193326Sed * You should have received a copy of the GNU General Public License version
16193326Sed * 2 along with this work; if not, write to the Free Software Foundation,
17193326Sed * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18193326Sed *
19193326Sed * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20198092Srdivacky * or visit www.oracle.com if you need additional information or have any
21193326Sed * questions.
22193326Sed *
23193326Sed */
24193326Sed
25193326Sed#include "precompiled.hpp"
26193326Sed#include "classfile/classLoader.hpp"
27193326Sed#include "classfile/compactHashtable.inline.hpp"
28193326Sed#include "classfile/sharedClassUtil.hpp"
29198092Srdivacky#include "classfile/symbolTable.hpp"
30193326Sed#include "classfile/systemDictionaryShared.hpp"
31198092Srdivacky#include "classfile/altHashing.hpp"
32198092Srdivacky#if INCLUDE_ALL_GCS
33198092Srdivacky#include "gc/g1/g1CollectedHeap.hpp"
34198092Srdivacky#endif
35198092Srdivacky#include "memory/filemap.hpp"
36193326Sed#include "memory/metadataFactory.hpp"
37193326Sed#include "memory/oopFactory.hpp"
38193326Sed#include "oops/objArrayOop.hpp"
39198092Srdivacky#include "prims/jvmtiExport.hpp"
40198092Srdivacky#include "runtime/arguments.hpp"
41198092Srdivacky#include "runtime/java.hpp"
42198092Srdivacky#include "runtime/os.hpp"
43198092Srdivacky#include "runtime/vm_version.hpp"
44198092Srdivacky#include "services/memTracker.hpp"
45198092Srdivacky#include "utilities/defaultStream.hpp"
46198092Srdivacky
47198092Srdivacky# include <sys/stat.h>
48198092Srdivacky# include <errno.h>
49198092Srdivacky
50198092Srdivacky#ifndef O_BINARY       // if defined (Win32) use binary files.
51198092Srdivacky#define O_BINARY 0     // otherwise do nothing.
52193326Sed#endif
53193326Sed
54193326Sedextern address JVM_FunctionAtStart();
55193326Sedextern address JVM_FunctionAtEnd();
56198092Srdivacky
57193326Sed// Complain and stop. All error conditions occurring during the writing of
58193326Sed// an archive file should stop the process.  Unrecoverable errors during
59193326Sed// the reading of the archive file should stop the process.
60193326Sed
61193326Sedstatic void fail(const char *msg, va_list ap) {
62193326Sed  // This occurs very early during initialization: tty is not initialized.
63193326Sed  jio_fprintf(defaultStream::error_stream(),
64193326Sed              "An error has occurred while processing the"
65193326Sed              " shared archive file.\n");
66193326Sed  jio_vfprintf(defaultStream::error_stream(), msg, ap);
67193326Sed  jio_fprintf(defaultStream::error_stream(), "\n");
68193326Sed  // Do not change the text of the below message because some tests check for it.
69193326Sed  vm_exit_during_initialization("Unable to use shared archive.", NULL);
70193326Sed}
71198092Srdivacky
72193326Sed
73193326Sedvoid FileMapInfo::fail_stop(const char *msg, ...) {
74193326Sed        va_list ap;
75193326Sed  va_start(ap, msg);
76198092Srdivacky  fail(msg, ap);        // Never returns.
77193326Sed  va_end(ap);           // for completeness.
78193326Sed}
79193326Sed
80198092Srdivacky
81193326Sed// Complain and continue.  Recoverable errors during the reading of the
82193326Sed// archive file may continue (with sharing disabled).
83198092Srdivacky//
84193326Sed// If we continue, then disable shared spaces and close the file.
85193326Sed
86193326Sedvoid FileMapInfo::fail_continue(const char *msg, ...) {
87198092Srdivacky  va_list ap;
88193326Sed  va_start(ap, msg);
89193326Sed  MetaspaceShared::set_archive_loading_failed();
90193326Sed  if (PrintSharedArchiveAndExit && _validating_classpath_entry_table) {
91193326Sed    // If we are doing PrintSharedArchiveAndExit and some of the classpath entries
92198092Srdivacky    // do not validate, we can still continue "limping" to validate the remaining
93193326Sed    // entries. No need to quit.
94193326Sed    tty->print("[");
95193326Sed    tty->vprint(msg, ap);
96198092Srdivacky    tty->print_cr("]");
97193326Sed  } else {
98193326Sed    if (RequireSharedSpaces) {
99193326Sed      fail(msg, ap);
100193326Sed    } else {
101193326Sed      if (PrintSharedSpaces) {
102193326Sed        tty->print_cr("UseSharedSpaces: %s", msg);
103193326Sed      }
104193326Sed    }
105193326Sed    UseSharedSpaces = false;
106198092Srdivacky    assert(current_info() != NULL, "singleton must be registered");
107193326Sed    current_info()->close();
108193326Sed  }
109193326Sed  va_end(ap);
110193326Sed}
111193326Sed
112193326Sed// Fill in the fileMapInfo structure with data about this VM instance.
113198092Srdivacky
114193326Sed// This method copies the vm version info into header_version.  If the version is too
115198092Srdivacky// long then a truncated version, which has a hash code appended to it, is copied.
116193326Sed//
117193326Sed// Using a template enables this method to verify that header_version is an array of
118193326Sed// length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
119193326Sed// the code that reads the CDS file will both use the same size buffer.  Hence, will
120193326Sed// use identical truncation.  This is necessary for matching of truncated versions.
121193326Sedtemplate <int N> static void get_header_version(char (&header_version) [N]) {
122193326Sed  assert(N == JVM_IDENT_MAX, "Bad header_version size");
123193326Sed
124193326Sed  const char *vm_version = VM_Version::internal_vm_info_string();
125193326Sed  const int version_len = (int)strlen(vm_version);
126193326Sed
127193326Sed  if (version_len < (JVM_IDENT_MAX-1)) {
128193326Sed    strcpy(header_version, vm_version);
129193326Sed
130193326Sed  } else {
131193326Sed    // Get the hash value.  Use a static seed because the hash needs to return the same
132193326Sed    // value over multiple jvm invocations.
133193326Sed    unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
134193326Sed
135193326Sed    // Truncate the ident, saving room for the 8 hex character hash value.
136198092Srdivacky    strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
137193326Sed
138193326Sed    // Append the hash code as eight hex digits.
139193326Sed    sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
140193326Sed    header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
141193326Sed  }
142193326Sed}
143193326Sed
144193326SedFileMapInfo::FileMapInfo() {
145198092Srdivacky  assert(_current_info == NULL, "must be singleton"); // not thread safe
146198092Srdivacky  _current_info = this;
147198092Srdivacky  memset(this, 0, sizeof(FileMapInfo));
148198092Srdivacky  _file_offset = 0;
149198092Srdivacky  _file_open = false;
150198092Srdivacky  _header = SharedClassUtil::allocate_file_map_header();
151198092Srdivacky  _header->_version = _invalid_version;
152198092Srdivacky}
153198092Srdivacky
154198092SrdivackyFileMapInfo::~FileMapInfo() {
155198092Srdivacky  assert(_current_info == this, "must be singleton"); // not thread safe
156198092Srdivacky  _current_info = NULL;
157198092Srdivacky}
158198092Srdivacky
159198092Srdivackyvoid FileMapInfo::populate_header(size_t alignment) {
160198092Srdivacky  _header->populate(this, alignment);
161198092Srdivacky}
162198092Srdivacky
163198092Srdivackysize_t FileMapInfo::FileMapHeader::data_size() {
164198092Srdivacky  return SharedClassUtil::file_map_header_size() - sizeof(FileMapInfo::FileMapHeaderBase);
165198092Srdivacky}
166198092Srdivacky
167198092Srdivackyvoid FileMapInfo::FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) {
168198092Srdivacky  _magic = 0xf00baba2;
169198092Srdivacky  _version = _current_version;
170198092Srdivacky  _alignment = alignment;
171198092Srdivacky  _obj_alignment = ObjectAlignmentInBytes;
172198092Srdivacky  _compact_strings = CompactStrings;
173198092Srdivacky  _narrow_oop_mode = Universe::narrow_oop_mode();
174198092Srdivacky  _narrow_oop_shift = Universe::narrow_oop_shift();
175198092Srdivacky  _max_heap_size = MaxHeapSize;
176198092Srdivacky  _narrow_klass_base = Universe::narrow_klass_base();
177198092Srdivacky  _narrow_klass_shift = Universe::narrow_klass_shift();
178198092Srdivacky  _classpath_entry_table_size = mapinfo->_classpath_entry_table_size;
179198092Srdivacky  _classpath_entry_table = mapinfo->_classpath_entry_table;
180198092Srdivacky  _classpath_entry_size = mapinfo->_classpath_entry_size;
181198092Srdivacky
182198092Srdivacky  // The following fields are for sanity checks for whether this archive
183198092Srdivacky  // will function correctly with this JVM and the bootclasspath it's
184198092Srdivacky  // invoked with.
185198092Srdivacky
186198092Srdivacky  // JVM version string ... changes on each build.
187198092Srdivacky  get_header_version(_jvm_ident);
188198092Srdivacky}
189198092Srdivacky
190198092Srdivackyvoid FileMapInfo::allocate_classpath_entry_table() {
191198092Srdivacky  int bytes = 0;
192198092Srdivacky  int count = 0;
193198092Srdivacky  char* strptr = NULL;
194198092Srdivacky  char* strptr_max = NULL;
195198092Srdivacky  Thread* THREAD = Thread::current();
196198092Srdivacky
197198092Srdivacky  ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
198198092Srdivacky  size_t entry_size = SharedClassUtil::shared_class_path_entry_size();
199198092Srdivacky
200198092Srdivacky  for (int pass=0; pass<2; pass++) {
201198092Srdivacky    ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
202198092Srdivacky
203198092Srdivacky    for (int cur_entry = 0 ; cpe != NULL; cpe = cpe->next(), cur_entry++) {
204198092Srdivacky      const char *name = cpe->name();
205198092Srdivacky      int name_bytes = (int)(strlen(name) + 1);
206198092Srdivacky
207198092Srdivacky      if (pass == 0) {
208198092Srdivacky        count ++;
209198092Srdivacky        bytes += (int)entry_size;
210198092Srdivacky        bytes += name_bytes;
211198092Srdivacky        log_info(classpath)("add main shared path (%s) %s", (cpe->is_jar_file() ? "jar" : "dir"), name);
212198092Srdivacky      } else {
213198092Srdivacky        SharedClassPathEntry* ent = shared_classpath(cur_entry);
214198092Srdivacky        if (cpe->is_jar_file()) {
215198092Srdivacky          struct stat st;
216198092Srdivacky          if (os::stat(name, &st) != 0) {
217198092Srdivacky            // The file/dir must exist, or it would not have been added
218198092Srdivacky            // into ClassLoader::classpath_entry().
219198092Srdivacky            //
220198092Srdivacky            // If we can't access a jar file in the boot path, then we can't
221198092Srdivacky            // make assumptions about where classes get loaded from.
222198092Srdivacky            FileMapInfo::fail_stop("Unable to open jar file %s.", name);
223198092Srdivacky          }
224198092Srdivacky
225198092Srdivacky          EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
226198092Srdivacky          SharedClassUtil::update_shared_classpath(cpe, ent, st.st_mtime, st.st_size, THREAD);
227198092Srdivacky        } else {
228198092Srdivacky          struct stat st;
229198092Srdivacky          if ((os::stat(name, &st) == 0) && ((st.st_mode & S_IFDIR) == S_IFDIR)) {
230198092Srdivacky            if (!os::dir_is_empty(name)) {
231198092Srdivacky              ClassLoader::exit_with_path_failure("Cannot have non-empty directory in archived classpaths", name);
232198092Srdivacky            }
233198092Srdivacky            ent->_filesize = -1;
234198092Srdivacky          } else {
235198092Srdivacky            ent->_filesize = -2;
236198092Srdivacky          }
237198092Srdivacky        }
238198092Srdivacky        ent->_name = strptr;
239198092Srdivacky        if (strptr + name_bytes <= strptr_max) {
240198092Srdivacky          strncpy(strptr, name, (size_t)name_bytes); // name_bytes includes trailing 0.
241198092Srdivacky          strptr += name_bytes;
242198092Srdivacky        } else {
243198092Srdivacky          assert(0, "miscalculated buffer size");
244198092Srdivacky        }
245198092Srdivacky      }
246198092Srdivacky    }
247198092Srdivacky
248198092Srdivacky    if (pass == 0) {
249198092Srdivacky      EXCEPTION_MARK; // The following call should never throw, but would exit VM on error.
250198092Srdivacky      Array<u8>* arr = MetadataFactory::new_array<u8>(loader_data, (bytes + 7)/8, THREAD);
251198092Srdivacky      strptr = (char*)(arr->data());
252198092Srdivacky      strptr_max = strptr + bytes;
253198092Srdivacky      SharedClassPathEntry* table = (SharedClassPathEntry*)strptr;
254198092Srdivacky      strptr += entry_size * count;
255198092Srdivacky
256198092Srdivacky      _classpath_entry_table_size = count;
257198092Srdivacky      _classpath_entry_table = table;
258198092Srdivacky      _classpath_entry_size = entry_size;
259198092Srdivacky    }
260198092Srdivacky  }
261198092Srdivacky}
262198092Srdivacky
263198092Srdivackybool FileMapInfo::validate_classpath_entry_table() {
264198092Srdivacky  _validating_classpath_entry_table = true;
265198092Srdivacky
266198092Srdivacky  int count = _header->_classpath_entry_table_size;
267198092Srdivacky
268198092Srdivacky  _classpath_entry_table = _header->_classpath_entry_table;
269198092Srdivacky  _classpath_entry_size = _header->_classpath_entry_size;
270198092Srdivacky
271198092Srdivacky  for (int i=0; i<count; i++) {
272198092Srdivacky    SharedClassPathEntry* ent = shared_classpath(i);
273198092Srdivacky    struct stat st;
274198092Srdivacky    const char* name = ent->_name;
275193326Sed    bool ok = true;
276193326Sed    log_info(classpath)("checking shared classpath entry: %s", name);
277193326Sed    if (os::stat(name, &st) != 0) {
278193326Sed      fail_continue("Required classpath entry does not exist: %s", name);
279193326Sed      ok = false;
280193326Sed    } else if (ent->is_dir()) {
281193326Sed      if (!os::dir_is_empty(name)) {
282193326Sed        fail_continue("directory is not empty: %s", name);
283198092Srdivacky        ok = false;
284193326Sed      }
285198092Srdivacky    } else if (ent->is_jar()) {
286193326Sed      if (ent->_timestamp != st.st_mtime ||
287193326Sed          ent->_filesize != st.st_size) {
288198092Srdivacky        ok = false;
289193326Sed        if (PrintSharedArchiveAndExit) {
290193326Sed          fail_continue(ent->_timestamp != st.st_mtime ?
291193326Sed                        "Timestamp mismatch" :
292198092Srdivacky                        "File size mismatch");
293193326Sed        } else {
294193326Sed          fail_continue("A jar file is not the one used while building"
295193326Sed                        " the shared archive file: %s", name);
296198092Srdivacky        }
297193326Sed      }
298198092Srdivacky    }
299198092Srdivacky    if (ok) {
300198092Srdivacky      log_info(classpath)("ok");
301198092Srdivacky    } else if (!PrintSharedArchiveAndExit) {
302198092Srdivacky      _validating_classpath_entry_table = false;
303198092Srdivacky      return false;
304198092Srdivacky    }
305198092Srdivacky  }
306198092Srdivacky
307198092Srdivacky  _classpath_entry_table_size = _header->_classpath_entry_table_size;
308198092Srdivacky  _validating_classpath_entry_table = false;
309198092Srdivacky  return true;
310198092Srdivacky}
311193326Sed
312198092Srdivacky
313193326Sed// Read the FileMapInfo information from the file.
314193326Sed
315193326Sedbool FileMapInfo::init_from_file(int fd) {
316193326Sed  size_t sz = _header->data_size();
317193326Sed  char* addr = _header->data();
318193326Sed  size_t n = os::read(fd, addr, (unsigned int)sz);
319193326Sed  if (n != sz) {
320193326Sed    fail_continue("Unable to read the file header.");
321193326Sed    return false;
322193326Sed  }
323193326Sed  if (_header->_version != current_version()) {
324193326Sed    fail_continue("The shared archive file has the wrong version.");
325198092Srdivacky    return false;
326193326Sed  }
327193326Sed  _file_offset = (long)n;
328193326Sed
329193326Sed  size_t info_size = _header->_paths_misc_info_size;
330193326Sed  _paths_misc_info = NEW_C_HEAP_ARRAY_RETURN_NULL(char, info_size, mtClass);
331193326Sed  if (_paths_misc_info == NULL) {
332193326Sed    fail_continue("Unable to read the file header.");
333193326Sed    return false;
334198092Srdivacky  }
335193326Sed  n = os::read(fd, _paths_misc_info, (unsigned int)info_size);
336193326Sed  if (n != info_size) {
337193326Sed    fail_continue("Unable to read the shared path info header.");
338193326Sed    FREE_C_HEAP_ARRAY(char, _paths_misc_info);
339193326Sed    _paths_misc_info = NULL;
340193326Sed    return false;
341193326Sed  }
342193326Sed
343198092Srdivacky  size_t len = lseek(fd, 0, SEEK_END);
344193326Sed  struct FileMapInfo::FileMapHeader::space_info* si =
345193326Sed    &_header->_space[MetaspaceShared::mc];
346193326Sed  if (si->_file_offset >= len || len - si->_file_offset < si->_used) {
347193326Sed    fail_continue("The shared archive file has been truncated.");
348193326Sed    return false;
349193326Sed  }
350193326Sed
351193326Sed  _file_offset += (long)n;
352193326Sed  return true;
353193326Sed}
354193326Sed
355193326Sed
356193326Sed// Read the FileMapInfo information from the file.
357193326Sedbool FileMapInfo::open_for_read() {
358193326Sed  _full_path = Arguments::GetSharedArchivePath();
359193326Sed  int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
360198092Srdivacky  if (fd < 0) {
361193326Sed    if (errno == ENOENT) {
362193326Sed      // Not locating the shared archive is ok.
363193326Sed      fail_continue("Specified shared archive not found.");
364193326Sed    } else {
365193326Sed      fail_continue("Failed to open shared archive file (%s).",
366193326Sed                    os::strerror(errno));
367193326Sed    }
368193326Sed    return false;
369193326Sed  }
370193326Sed
371193326Sed  _fd = fd;
372193326Sed  _file_open = true;
373193326Sed  return true;
374193326Sed}
375193326Sed
376193326Sed
377193326Sed// Write the FileMapInfo information to the file.
378193326Sed
379193326Sedvoid FileMapInfo::open_for_write() {
380193326Sed _full_path = Arguments::GetSharedArchivePath();
381193326Sed  if (PrintSharedSpaces) {
382193326Sed    tty->print_cr("Dumping shared data to file: ");
383193326Sed    tty->print_cr("   %s", _full_path);
384193326Sed  }
385193326Sed
386193326Sed#ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
387193326Sed  chmod(_full_path, _S_IREAD | _S_IWRITE);
388193326Sed#endif
389193326Sed
390193326Sed  // Use remove() to delete the existing file because, on Unix, this will
391193326Sed  // allow processes that have it open continued access to the file.
392193326Sed  remove(_full_path);
393193326Sed  int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
394193326Sed  if (fd < 0) {
395193326Sed    fail_stop("Unable to create shared archive file %s: (%s).", _full_path,
396193326Sed              os::strerror(errno));
397193326Sed  }
398193326Sed  _fd = fd;
399193326Sed  _file_offset = 0;
400193326Sed  _file_open = true;
401193326Sed}
402193326Sed
403193326Sed
404193326Sed// Write the header to the file, seek to the next allocation boundary.
405193326Sed
406193326Sedvoid FileMapInfo::write_header() {
407193326Sed  int info_size = ClassLoader::get_shared_paths_misc_info_size();
408193326Sed
409193326Sed  _header->_paths_misc_info_size = info_size;
410193326Sed
411193326Sed  align_file_position();
412193326Sed  size_t sz = _header->data_size();
413193326Sed  char* addr = _header->data();
414193326Sed  write_bytes(addr, (int)sz); // skip the C++ vtable
415193326Sed  write_bytes(ClassLoader::get_shared_paths_misc_info(), info_size);
416193326Sed  align_file_position();
417193326Sed}
418193326Sed
419193326Sed
420193326Sed// Dump shared spaces to file.
421198092Srdivacky
422198092Srdivackyvoid FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
423198092Srdivacky  align_file_position();
424198092Srdivacky  size_t used = space->used_bytes_slow(Metaspace::NonClassType);
425198092Srdivacky  size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
426198092Srdivacky  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
427198092Srdivacky  write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
428198092Srdivacky}
429198092Srdivacky
430198092Srdivacky
431198092Srdivacky// Dump region to file.
432198092Srdivacky
433198092Srdivackyvoid FileMapInfo::write_region(int region, char* base, size_t size,
434198092Srdivacky                               size_t capacity, bool read_only,
435198092Srdivacky                               bool allow_exec) {
436198092Srdivacky  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[region];
437198092Srdivacky
438198092Srdivacky  if (_file_open) {
439198092Srdivacky    guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
440198092Srdivacky    if (PrintSharedSpaces) {
441198092Srdivacky      tty->print_cr("Shared file region %d: " SIZE_FORMAT_HEX_W(6) " bytes, addr " INTPTR_FORMAT
442198092Srdivacky                    " file offset " SIZE_FORMAT_HEX_W(6), region, size, p2i(base), _file_offset);
443198092Srdivacky    }
444198092Srdivacky  } else {
445198092Srdivacky    si->_file_offset = _file_offset;
446198092Srdivacky  }
447198092Srdivacky  if (MetaspaceShared::is_string_region(region)) {
448198092Srdivacky    assert((base - (char*)Universe::narrow_oop_base()) % HeapWordSize == 0, "Sanity");
449198092Srdivacky    if (base != NULL) {
450198092Srdivacky      si->_addr._offset = (intx)oopDesc::encode_heap_oop_not_null((oop)base);
451198092Srdivacky    } else {
452198092Srdivacky      si->_addr._offset = 0;
453198092Srdivacky    }
454198092Srdivacky  } else {
455198092Srdivacky    si->_addr._base = base;
456193326Sed  }
457193326Sed  si->_used = size;
458198092Srdivacky  si->_capacity = capacity;
459198092Srdivacky  si->_read_only = read_only;
460198092Srdivacky  si->_allow_exec = allow_exec;
461198092Srdivacky  si->_crc = ClassLoader::crc32(0, base, (jint)size);
462198092Srdivacky  write_bytes_aligned(base, (int)size);
463198092Srdivacky}
464198092Srdivacky
465198092Srdivacky// Write the string space. The string space contains one or multiple GC(G1) regions.
466198092Srdivacky// When the total string space size is smaller than one GC region of the dump time,
467198092Srdivacky// only one string region is used for shared strings.
468198092Srdivacky//
469198092Srdivacky// If the total string space size is bigger than one GC region, there would be more
470198092Srdivacky// than one GC regions allocated for shared strings. The first/bottom GC region might
471198092Srdivacky// be a partial GC region with the empty portion at the higher address within that region.
472198092Srdivacky// The non-empty portion of the first region is written into the archive as one string
473198092Srdivacky// region. The rest are consecutive full GC regions if they exist, which can be written
474193326Sed// out in one chunk as another string region.
475198092Srdivackyvoid FileMapInfo::write_string_regions(GrowableArray<MemRegion> *regions) {
476198092Srdivacky  for (int i = MetaspaceShared::first_string;
477198092Srdivacky           i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
478198092Srdivacky    char* start = NULL;
479198092Srdivacky    size_t size = 0;
480198092Srdivacky    if (regions->is_nonempty()) {
481198092Srdivacky      if (i == MetaspaceShared::first_string) {
482198092Srdivacky        MemRegion first = regions->first();
483198092Srdivacky        start = (char*)first.start();
484198092Srdivacky        size = first.byte_size();
485198092Srdivacky      } else {
486198092Srdivacky        int len = regions->length();
487198092Srdivacky        if (len > 1) {
488198092Srdivacky          start = (char*)regions->at(1).start();
489198092Srdivacky          size = (char*)regions->at(len - 1).end() - start;
490198092Srdivacky        }
491198092Srdivacky      }
492198092Srdivacky    }
493198092Srdivacky    write_region(i, start, size, size, false, false);
494198092Srdivacky  }
495193326Sed}
496198092Srdivacky
497193326Sed
498198092Srdivacky// Dump bytes to file -- at the current file position.
499198092Srdivacky
500193326Sedvoid FileMapInfo::write_bytes(const void* buffer, int nbytes) {
501193326Sed  if (_file_open) {
502198092Srdivacky    int n = ::write(_fd, buffer, nbytes);
503193326Sed    if (n != nbytes) {
504193326Sed      // It is dangerous to leave the corrupted shared archive file around,
505193326Sed      // close and remove the file. See bug 6372906.
506193326Sed      close();
507193326Sed      remove(_full_path);
508198092Srdivacky      fail_stop("Unable to write to shared archive file.");
509193326Sed    }
510193326Sed  }
511193326Sed  _file_offset += nbytes;
512198092Srdivacky}
513193326Sed
514193326Sed
515193326Sed// Align file position to an allocation unit boundary.
516193326Sed
517193326Sedvoid FileMapInfo::align_file_position() {
518193326Sed  size_t new_file_offset = align_size_up(_file_offset,
519193326Sed                                         os::vm_allocation_granularity());
520193326Sed  if (new_file_offset != _file_offset) {
521193326Sed    _file_offset = new_file_offset;
522193326Sed    if (_file_open) {
523198092Srdivacky      // Seek one byte back from the target and write a byte to insure
524193326Sed      // that the written file is the correct length.
525193326Sed      _file_offset -= 1;
526193326Sed      if (lseek(_fd, (long)_file_offset, SEEK_SET) < 0) {
527193326Sed        fail_stop("Unable to seek.");
528198092Srdivacky      }
529193326Sed      char zero = 0;
530193326Sed      write_bytes(&zero, 1);
531193326Sed    }
532193326Sed  }
533193326Sed}
534193326Sed
535193326Sed
536193326Sed// Dump bytes to file -- at the current file position.
537193326Sed
538198092Srdivackyvoid FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
539193326Sed  align_file_position();
540193326Sed  write_bytes(buffer, nbytes);
541198092Srdivacky  align_file_position();
542193326Sed}
543193326Sed
544193326Sed
545193326Sed// Close the shared archive file.  This does NOT unmap mapped regions.
546193326Sed
547193326Sedvoid FileMapInfo::close() {
548193326Sed  if (_file_open) {
549193326Sed    if (::close(_fd) < 0) {
550193326Sed      fail_stop("Unable to close the shared archive file.");
551193326Sed    }
552193326Sed    _file_open = false;
553193326Sed    _fd = -1;
554193326Sed  }
555193326Sed}
556193326Sed
557193326Sed
558193326Sed// JVM/TI RedefineClasses() support:
559193326Sed// Remap the shared readonly space to shared readwrite, private.
560193326Sedbool FileMapInfo::remap_shared_readonly_as_readwrite() {
561193326Sed  int idx = 0;
562193326Sed  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[idx];
563193326Sed  if (!si->_read_only) {
564198092Srdivacky    // the space is already readwrite so we are done
565193326Sed    return true;
566193326Sed  }
567193326Sed  size_t used = si->_used;
568193326Sed  size_t size = align_size_up(used, os::vm_allocation_granularity());
569193326Sed  if (!open_for_read()) {
570193326Sed    return false;
571193326Sed  }
572193326Sed  char *addr = _header->region_addr(idx);
573193326Sed  char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
574193326Sed                                addr, size, false /* !read_only */,
575198092Srdivacky                                si->_allow_exec);
576198092Srdivacky  close();
577193326Sed  if (base == NULL) {
578193326Sed    fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
579193326Sed    return false;
580193326Sed  }
581193326Sed  if (base != addr) {
582193326Sed    fail_continue("Unable to remap shared readonly space at required address.");
583193326Sed    return false;
584193326Sed  }
585193326Sed  si->_read_only = false;
586193326Sed  return true;
587193326Sed}
588193326Sed
589193326Sed// Map the whole region at once, assumed to be allocated contiguously.
590193326SedReservedSpace FileMapInfo::reserve_shared_memory() {
591193326Sed  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[0];
592193326Sed  char* requested_addr = _header->region_addr(0);
593198092Srdivacky
594198092Srdivacky  size_t size = FileMapInfo::shared_spaces_size();
595193326Sed
596193326Sed  // Reserve the space first, then map otherwise map will go right over some
597193326Sed  // other reserved memory (like the code cache).
598195341Sed  ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
599195341Sed  if (!rs.is_reserved()) {
600195341Sed    fail_continue("Unable to reserve shared space at required address "
601195341Sed                  INTPTR_FORMAT, p2i(requested_addr));
602195341Sed    return rs;
603195341Sed  }
604195341Sed  // the reserved virtual memory is for mapping class data sharing archive
605195341Sed  MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
606195341Sed
607195341Sed  return rs;
608198092Srdivacky}
609195341Sed
610195341Sed// Memory map a region in the address space.
611195341Sedstatic const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode",
612195341Sed                                            "String1", "String2" };
613195341Sed
614195341Sedchar* FileMapInfo::map_region(int i) {
615195341Sed  assert(!MetaspaceShared::is_string_region(i), "sanity");
616195341Sed  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
617195341Sed  size_t used = si->_used;
618195341Sed  size_t alignment = os::vm_allocation_granularity();
619195341Sed  size_t size = align_size_up(used, alignment);
620195341Sed  char *requested_addr = _header->region_addr(i);
621195341Sed
622195341Sed  // If a tool agent is in use (debugging enabled), we must map the address space RW
623195341Sed  if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
624195341Sed    si->_read_only = false;
625195341Sed  }
626195341Sed
627195341Sed  // map the contents of the CDS archive in this memory
628193326Sed  char *base = os::map_memory(_fd, _full_path, si->_file_offset,
629193326Sed                              requested_addr, size, si->_read_only,
630193326Sed                              si->_allow_exec);
631193326Sed  if (base == NULL || base != requested_addr) {
632193326Sed    fail_continue("Unable to map %s shared space at required address.", shared_region_name[i]);
633193326Sed    return NULL;
634193326Sed  }
635193326Sed#ifdef _WINDOWS
636193326Sed  // This call is Windows-only because the memory_type gets recorded for the other platforms
637193326Sed  // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
638193326Sed  MemTracker::record_virtual_memory_type((address)base, mtClassShared);
639193326Sed#endif
640193326Sed
641193326Sed  return base;
642193326Sed}
643198092Srdivacky
644193326Sedstatic MemRegion *string_ranges = NULL;
645193326Sedstatic int num_ranges = 0;
646193326Sedbool FileMapInfo::map_string_regions() {
647193326Sed#if INCLUDE_ALL_GCS
648193326Sed  if (UseG1GC && UseCompressedOops && UseCompressedClassPointers) {
649193326Sed    // Check that all the narrow oop and klass encodings match the archive
650193326Sed    if (narrow_oop_mode() != Universe::narrow_oop_mode() ||
651193326Sed        narrow_oop_shift() != Universe::narrow_oop_shift() ||
652193326Sed        narrow_klass_base() != Universe::narrow_klass_base() ||
653193326Sed        narrow_klass_shift() != Universe::narrow_klass_shift()) {
654193326Sed      if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
655193326Sed        tty->print_cr("Shared string data from the CDS archive is being ignored. "
656193326Sed                     "The current CompressedOops/CompressedClassPointers encoding differs from "
657193326Sed                     "that archived due to heap size change. The archive was dumped using max heap "
658193326Sed                     "size " UINTX_FORMAT "M.", max_heap_size()/M);
659193326Sed      }
660193326Sed    } else {
661193326Sed      string_ranges = new MemRegion[MetaspaceShared::max_strings];
662193326Sed      struct FileMapInfo::FileMapHeader::space_info* si;
663198092Srdivacky
664198092Srdivacky      for (int i = MetaspaceShared::first_string;
665198092Srdivacky               i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
666198092Srdivacky        si = &_header->_space[i];
667198092Srdivacky        size_t used = si->_used;
668198092Srdivacky        if (used > 0) {
669198092Srdivacky          size_t size = used;
670198092Srdivacky          char* requested_addr = (char*)((void*)oopDesc::decode_heap_oop_not_null(
671198092Srdivacky                                                 (narrowOop)si->_addr._offset));
672198092Srdivacky          string_ranges[num_ranges] = MemRegion((HeapWord*)requested_addr, size / HeapWordSize);
673198092Srdivacky          num_ranges ++;
674198092Srdivacky        }
675198092Srdivacky      }
676198092Srdivacky
677198092Srdivacky      if (num_ranges == 0) {
678198092Srdivacky        StringTable::ignore_shared_strings(true);
679198092Srdivacky        return true; // no shared string data
680198092Srdivacky      }
681198092Srdivacky
682198092Srdivacky      // Check that ranges are within the java heap
683198092Srdivacky      if (!G1CollectedHeap::heap()->check_archive_addresses(string_ranges, num_ranges)) {
684198092Srdivacky        fail_continue("Unable to allocate shared string space: range is not "
685198092Srdivacky                      "within java heap.");
686198092Srdivacky        return false;
687198092Srdivacky      }
688198092Srdivacky
689198092Srdivacky      // allocate from java heap
690198092Srdivacky      if (!G1CollectedHeap::heap()->alloc_archive_regions(string_ranges, num_ranges)) {
691198092Srdivacky        fail_continue("Unable to allocate shared string space: range is "
692198092Srdivacky                      "already in use.");
693198092Srdivacky        return false;
694198092Srdivacky      }
695198092Srdivacky
696198092Srdivacky      // Map the string data. No need to call MemTracker::record_virtual_memory_type()
697198092Srdivacky      // for mapped string regions as they are part of the reserved java heap, which
698198092Srdivacky      // is already recorded.
699198092Srdivacky      for (int i = 0; i < num_ranges; i++) {
700198092Srdivacky        si = &_header->_space[MetaspaceShared::first_string + i];
701198092Srdivacky        char* addr = (char*)string_ranges[i].start();
702198092Srdivacky        char* base = os::map_memory(_fd, _full_path, si->_file_offset,
703198092Srdivacky                                    addr, string_ranges[i].byte_size(), si->_read_only,
704198092Srdivacky                                    si->_allow_exec);
705193326Sed        if (base == NULL || base != addr) {
706193326Sed          // dealloc the string regions from java heap
707193326Sed          dealloc_string_regions();
708193326Sed          fail_continue("Unable to map shared string space at required address.");
709193326Sed          return false;
710193326Sed        }
711193326Sed      }
712198092Srdivacky
713198092Srdivacky      if (!verify_string_regions()) {
714198092Srdivacky        // dealloc the string regions from java heap
715198092Srdivacky        dealloc_string_regions();
716198092Srdivacky        fail_continue("Shared string regions are corrupt");
717198092Srdivacky        return false;
718198092Srdivacky      }
719198092Srdivacky
720198092Srdivacky      // the shared string data is mapped successfully
721193326Sed      return true;
722193326Sed    }
723193326Sed  } else {
724193326Sed    if (PrintSharedSpaces && _header->_space[MetaspaceShared::first_string]._used > 0) {
725193326Sed      tty->print_cr("Shared string data from the CDS archive is being ignored. UseG1GC, "
726193326Sed                    "UseCompressedOops and UseCompressedClassPointers are required.");
727193326Sed    }
728193326Sed  }
729193326Sed
730193326Sed  // if we get here, the shared string data is not mapped
731193326Sed  assert(string_ranges == NULL && num_ranges == 0, "sanity");
732193326Sed  StringTable::ignore_shared_strings(true);
733193326Sed#endif
734193326Sed  return true;
735193326Sed}
736193326Sed
737193326Sedbool FileMapInfo::verify_string_regions() {
738193326Sed  for (int i = MetaspaceShared::first_string;
739193326Sed           i < MetaspaceShared::first_string + MetaspaceShared::max_strings; i++) {
740198092Srdivacky    if (!verify_region_checksum(i)) {
741193326Sed      return false;
742193326Sed    }
743193326Sed  }
744193326Sed  return true;
745193326Sed}
746193326Sed
747193326Sedvoid FileMapInfo::fixup_string_regions() {
748193326Sed#if INCLUDE_ALL_GCS
749198092Srdivacky  // If any string regions were found, call the fill routine to make them parseable.
750193326Sed  // Note that string_ranges may be non-NULL even if no ranges were found.
751193326Sed  if (num_ranges != 0) {
752193326Sed    assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
753193326Sed    G1CollectedHeap::heap()->fill_archive_regions(string_ranges, num_ranges);
754193326Sed  }
755193326Sed#endif
756193326Sed}
757193326Sed
758193326Sedbool FileMapInfo::verify_region_checksum(int i) {
759193326Sed  if (!VerifySharedSpaces) {
760193326Sed    return true;
761193326Sed  }
762193326Sed
763193326Sed  size_t sz = _header->_space[i]._used;
764193326Sed
765193326Sed  if (sz == 0) {
766193326Sed    return true; // no data
767193326Sed  }
768  if (MetaspaceShared::is_string_region(i) && StringTable::shared_string_ignored()) {
769    return true; // shared string data are not mapped
770  }
771  const char* buf = _header->region_addr(i);
772  int crc = ClassLoader::crc32(0, buf, (jint)sz);
773  if (crc != _header->_space[i]._crc) {
774    fail_continue("Checksum verification failed.");
775    return false;
776  }
777  return true;
778}
779
780// Unmap a memory region in the address space.
781
782void FileMapInfo::unmap_region(int i) {
783  assert(!MetaspaceShared::is_string_region(i), "sanity");
784  struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
785  size_t used = si->_used;
786  size_t size = align_size_up(used, os::vm_allocation_granularity());
787
788  if (used == 0) {
789    return;
790  }
791
792  char* addr = _header->region_addr(i);
793  if (!os::unmap_memory(addr, size)) {
794    fail_stop("Unable to unmap shared space.");
795  }
796}
797
798// dealloc the archived string region from java heap
799void FileMapInfo::dealloc_string_regions() {
800#if INCLUDE_ALL_GCS
801  if (num_ranges > 0) {
802    assert(string_ranges != NULL, "Null string_ranges array with non-zero count");
803    G1CollectedHeap::heap()->dealloc_archive_regions(string_ranges, num_ranges);
804  }
805#endif
806}
807
808void FileMapInfo::assert_mark(bool check) {
809  if (!check) {
810    fail_stop("Mark mismatch while restoring from shared file.");
811  }
812}
813
814
815FileMapInfo* FileMapInfo::_current_info = NULL;
816SharedClassPathEntry* FileMapInfo::_classpath_entry_table = NULL;
817int FileMapInfo::_classpath_entry_table_size = 0;
818size_t FileMapInfo::_classpath_entry_size = 0x1234baad;
819bool FileMapInfo::_validating_classpath_entry_table = false;
820
821// Open the shared archive file, read and validate the header
822// information (version, boot classpath, etc.).  If initialization
823// fails, shared spaces are disabled and the file is closed. [See
824// fail_continue.]
825//
826// Validation of the archive is done in two steps:
827//
828// [1] validate_header() - done here. This checks the header, including _paths_misc_info.
829// [2] validate_classpath_entry_table - this is done later, because the table is in the RW
830//     region of the archive, which is not mapped yet.
831bool FileMapInfo::initialize() {
832  assert(UseSharedSpaces, "UseSharedSpaces expected.");
833
834  if (!open_for_read()) {
835    return false;
836  }
837
838  init_from_file(_fd);
839  if (!validate_header()) {
840    return false;
841  }
842
843  SharedReadOnlySize =  _header->_space[0]._capacity;
844  SharedReadWriteSize = _header->_space[1]._capacity;
845  SharedMiscDataSize =  _header->_space[2]._capacity;
846  SharedMiscCodeSize =  _header->_space[3]._capacity;
847  return true;
848}
849
850char* FileMapInfo::FileMapHeader::region_addr(int idx) {
851  if (MetaspaceShared::is_string_region(idx)) {
852    return (char*)((void*)oopDesc::decode_heap_oop_not_null(
853              (narrowOop)_space[idx]._addr._offset));
854  } else {
855    return _space[idx]._addr._base;
856  }
857}
858
859int FileMapInfo::FileMapHeader::compute_crc() {
860  char* header = data();
861  // start computing from the field after _crc
862  char* buf = (char*)&_crc + sizeof(int);
863  size_t sz = data_size() - (buf - header);
864  int crc = ClassLoader::crc32(0, buf, (jint)sz);
865  return crc;
866}
867
868bool FileMapInfo::FileMapHeader::validate() {
869  if (VerifySharedSpaces && compute_crc() != _crc) {
870    fail_continue("Header checksum verification failed.");
871    return false;
872  }
873
874  if (_version != current_version()) {
875    FileMapInfo::fail_continue("The shared archive file is the wrong version.");
876    return false;
877  }
878  if (_magic != (int)0xf00baba2) {
879    FileMapInfo::fail_continue("The shared archive file has a bad magic number.");
880    return false;
881  }
882  char header_version[JVM_IDENT_MAX];
883  get_header_version(header_version);
884  if (strncmp(_jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
885    log_info(classpath)("expected: %s", header_version);
886    log_info(classpath)("actual:   %s", _jvm_ident);
887    FileMapInfo::fail_continue("The shared archive file was created by a different"
888                  " version or build of HotSpot");
889    return false;
890  }
891  if (_obj_alignment != ObjectAlignmentInBytes) {
892    FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
893                  " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".",
894                  _obj_alignment, ObjectAlignmentInBytes);
895    return false;
896  }
897  if (_compact_strings != CompactStrings) {
898    FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)"
899                  " does not equal the current CompactStrings setting (%s).",
900                  _compact_strings ? "enabled" : "disabled",
901                  CompactStrings   ? "enabled" : "disabled");
902    return false;
903  }
904
905  return true;
906}
907
908bool FileMapInfo::validate_header() {
909  bool status = _header->validate();
910
911  if (status) {
912    if (!ClassLoader::check_shared_paths_misc_info(_paths_misc_info, _header->_paths_misc_info_size)) {
913      if (!PrintSharedArchiveAndExit) {
914        fail_continue("shared class paths mismatch (hint: enable -Xlog:classpath=info to diagnose the failure)");
915        status = false;
916      }
917    }
918  }
919
920  if (_paths_misc_info != NULL) {
921    FREE_C_HEAP_ARRAY(char, _paths_misc_info);
922    _paths_misc_info = NULL;
923  }
924  return status;
925}
926
927// The following method is provided to see whether a given pointer
928// falls in the mapped shared space.
929// Param:
930// p, The given pointer
931// Return:
932// True if the p is within the mapped shared space, otherwise, false.
933bool FileMapInfo::is_in_shared_space(const void* p) {
934  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
935    char *base;
936    if (MetaspaceShared::is_string_region(i) && _header->_space[i]._used == 0) {
937      continue;
938    }
939    base = _header->region_addr(i);
940    if (p >= base && p < base + _header->_space[i]._used) {
941      return true;
942    }
943  }
944
945  return false;
946}
947
948void FileMapInfo::print_shared_spaces() {
949  tty->print_cr("Shared Spaces:");
950  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
951    struct FileMapInfo::FileMapHeader::space_info* si = &_header->_space[i];
952    char *base = _header->region_addr(i);
953    tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
954                        shared_region_name[i],
955                        p2i(base), p2i(base + si->_used));
956  }
957}
958
959// Unmap mapped regions of shared space.
960void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
961  FileMapInfo *map_info = FileMapInfo::current_info();
962  if (map_info) {
963    map_info->fail_continue("%s", msg);
964    for (int i = 0; i < MetaspaceShared::num_non_strings; i++) {
965      char *addr = map_info->_header->region_addr(i);
966      if (addr != NULL && !MetaspaceShared::is_string_region(i)) {
967        map_info->unmap_region(i);
968        map_info->_header->_space[i]._addr._base = NULL;
969      }
970    }
971    // Dealloc the string regions only without unmapping. The string regions are part
972    // of the java heap. Unmapping of the heap regions are managed by GC.
973    map_info->dealloc_string_regions();
974  } else if (DumpSharedSpaces) {
975    fail_stop("%s", msg);
976  }
977}
978