filemap.cpp revision 6412:53a41e7cbe05
1/*
2 * Copyright (c) 2003, 2014, 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 "classfile/classLoader.hpp"
27#include "classfile/symbolTable.hpp"
28#include "classfile/altHashing.hpp"
29#include "memory/filemap.hpp"
30#include "runtime/arguments.hpp"
31#include "runtime/java.hpp"
32#include "runtime/os.hpp"
33#include "services/memTracker.hpp"
34#include "utilities/defaultStream.hpp"
35
36# include <sys/stat.h>
37# include <errno.h>
38
39#ifndef O_BINARY       // if defined (Win32) use binary files.
40#define O_BINARY 0     // otherwise do nothing.
41#endif
42
43PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
44
45extern address JVM_FunctionAtStart();
46extern address JVM_FunctionAtEnd();
47
48// Complain and stop. All error conditions occurring during the writing of
49// an archive file should stop the process.  Unrecoverable errors during
50// the reading of the archive file should stop the process.
51
52static void fail(const char *msg, va_list ap) {
53  // This occurs very early during initialization: tty is not initialized.
54  jio_fprintf(defaultStream::error_stream(),
55              "An error has occurred while processing the"
56              " shared archive file.\n");
57  jio_vfprintf(defaultStream::error_stream(), msg, ap);
58  jio_fprintf(defaultStream::error_stream(), "\n");
59  // Do not change the text of the below message because some tests check for it.
60  vm_exit_during_initialization("Unable to use shared archive.", NULL);
61}
62
63
64void FileMapInfo::fail_stop(const char *msg, ...) {
65        va_list ap;
66  va_start(ap, msg);
67  fail(msg, ap);        // Never returns.
68  va_end(ap);           // for completeness.
69}
70
71
72// Complain and continue.  Recoverable errors during the reading of the
73// archive file may continue (with sharing disabled).
74//
75// If we continue, then disable shared spaces and close the file.
76
77void FileMapInfo::fail_continue(const char *msg, ...) {
78  va_list ap;
79  va_start(ap, msg);
80  if (RequireSharedSpaces) {
81    fail(msg, ap);
82  } else {
83    if (PrintSharedSpaces) {
84      tty->print_cr("UseSharedSpaces: %s", msg);
85    }
86  }
87  va_end(ap);
88  UseSharedSpaces = false;
89  close();
90}
91
92// Fill in the fileMapInfo structure with data about this VM instance.
93
94// This method copies the vm version info into header_version.  If the version is too
95// long then a truncated version, which has a hash code appended to it, is copied.
96//
97// Using a template enables this method to verify that header_version is an array of
98// length JVM_IDENT_MAX.  This ensures that the code that writes to the CDS file and
99// the code that reads the CDS file will both use the same size buffer.  Hence, will
100// use identical truncation.  This is necessary for matching of truncated versions.
101template <int N> static void get_header_version(char (&header_version) [N]) {
102  assert(N == JVM_IDENT_MAX, "Bad header_version size");
103
104  const char *vm_version = VM_Version::internal_vm_info_string();
105  const int version_len = (int)strlen(vm_version);
106
107  if (version_len < (JVM_IDENT_MAX-1)) {
108    strcpy(header_version, vm_version);
109
110  } else {
111    // Get the hash value.  Use a static seed because the hash needs to return the same
112    // value over multiple jvm invocations.
113    unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len);
114
115    // Truncate the ident, saving room for the 8 hex character hash value.
116    strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
117
118    // Append the hash code as eight hex digits.
119    sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash);
120    header_version[JVM_IDENT_MAX-1] = 0;  // Null terminate.
121  }
122}
123
124void FileMapInfo::populate_header(size_t alignment) {
125  _header._magic = 0xf00baba2;
126  _header._version = _current_version;
127  _header._alignment = alignment;
128  _header._obj_alignment = ObjectAlignmentInBytes;
129
130  // The following fields are for sanity checks for whether this archive
131  // will function correctly with this JVM and the bootclasspath it's
132  // invoked with.
133
134  // JVM version string ... changes on each build.
135  get_header_version(_header._jvm_ident);
136
137  // Build checks on classpath and jar files
138  _header._num_jars = 0;
139  ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
140  for ( ; cpe != NULL; cpe = cpe->next()) {
141
142    if (cpe->is_jar_file()) {
143      if (_header._num_jars >= JVM_SHARED_JARS_MAX) {
144        fail_stop("Too many jar files to share.", NULL);
145      }
146
147      // Jar file - record timestamp and file size.
148      struct stat st;
149      const char *path = cpe->name();
150      if (os::stat(path, &st) != 0) {
151        // If we can't access a jar file in the boot path, then we can't
152        // make assumptions about where classes get loaded from.
153        fail_stop("Unable to open jar file %s.", path);
154      }
155      _header._jar[_header._num_jars]._timestamp = st.st_mtime;
156      _header._jar[_header._num_jars]._filesize = st.st_size;
157      _header._num_jars++;
158    } else {
159
160      // If directories appear in boot classpath, they must be empty to
161      // avoid having to verify each individual class file.
162      const char* name = ((ClassPathDirEntry*)cpe)->name();
163      if (!os::dir_is_empty(name)) {
164        fail_stop("Boot classpath directory %s is not empty.", name);
165      }
166    }
167  }
168}
169
170
171// Read the FileMapInfo information from the file.
172
173bool FileMapInfo::init_from_file(int fd) {
174
175  size_t n = read(fd, &_header, sizeof(struct FileMapHeader));
176  if (n != sizeof(struct FileMapHeader)) {
177    fail_continue("Unable to read the file header.");
178    return false;
179  }
180  if (_header._version != current_version()) {
181    fail_continue("The shared archive file has the wrong version.");
182    return false;
183  }
184  _file_offset = (long)n;
185  return true;
186}
187
188
189// Read the FileMapInfo information from the file.
190bool FileMapInfo::open_for_read() {
191  _full_path = Arguments::GetSharedArchivePath();
192  int fd = open(_full_path, O_RDONLY | O_BINARY, 0);
193  if (fd < 0) {
194    if (errno == ENOENT) {
195      // Not locating the shared archive is ok.
196      fail_continue("Specified shared archive not found.");
197    } else {
198      fail_continue("Failed to open shared archive file (%s).",
199                    strerror(errno));
200    }
201    return false;
202  }
203
204  _fd = fd;
205  _file_open = true;
206  return true;
207}
208
209
210// Write the FileMapInfo information to the file.
211
212void FileMapInfo::open_for_write() {
213 _full_path = Arguments::GetSharedArchivePath();
214  if (PrintSharedSpaces) {
215    tty->print_cr("Dumping shared data to file: ");
216    tty->print_cr("   %s", _full_path);
217  }
218
219#ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
220  chmod(_full_path, _S_IREAD | _S_IWRITE);
221#endif
222
223  // Use remove() to delete the existing file because, on Unix, this will
224  // allow processes that have it open continued access to the file.
225  remove(_full_path);
226  int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
227  if (fd < 0) {
228    fail_stop("Unable to create shared archive file %s.", _full_path);
229  }
230  _fd = fd;
231  _file_offset = 0;
232  _file_open = true;
233}
234
235
236// Write the header to the file, seek to the next allocation boundary.
237
238void FileMapInfo::write_header() {
239  write_bytes_aligned(&_header, sizeof(FileMapHeader));
240}
241
242
243// Dump shared spaces to file.
244
245void FileMapInfo::write_space(int i, Metaspace* space, bool read_only) {
246  align_file_position();
247  size_t used = space->used_bytes_slow(Metaspace::NonClassType);
248  size_t capacity = space->capacity_bytes_slow(Metaspace::NonClassType);
249  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
250  write_region(i, (char*)space->bottom(), used, capacity, read_only, false);
251}
252
253
254// Dump region to file.
255
256void FileMapInfo::write_region(int region, char* base, size_t size,
257                               size_t capacity, bool read_only,
258                               bool allow_exec) {
259  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[region];
260
261  if (_file_open) {
262    guarantee(si->_file_offset == _file_offset, "file offset mismatch.");
263    if (PrintSharedSpaces) {
264      tty->print_cr("Shared file region %d: 0x%6x bytes, addr " INTPTR_FORMAT
265                    " file offset 0x%6x", region, size, base, _file_offset);
266    }
267  } else {
268    si->_file_offset = _file_offset;
269  }
270  si->_base = base;
271  si->_used = size;
272  si->_capacity = capacity;
273  si->_read_only = read_only;
274  si->_allow_exec = allow_exec;
275  write_bytes_aligned(base, (int)size);
276}
277
278
279// Dump bytes to file -- at the current file position.
280
281void FileMapInfo::write_bytes(const void* buffer, int nbytes) {
282  if (_file_open) {
283    int n = ::write(_fd, buffer, nbytes);
284    if (n != nbytes) {
285      // It is dangerous to leave the corrupted shared archive file around,
286      // close and remove the file. See bug 6372906.
287      close();
288      remove(_full_path);
289      fail_stop("Unable to write to shared archive file.", NULL);
290    }
291  }
292  _file_offset += nbytes;
293}
294
295
296// Align file position to an allocation unit boundary.
297
298void FileMapInfo::align_file_position() {
299  long new_file_offset = align_size_up(_file_offset, os::vm_allocation_granularity());
300  if (new_file_offset != _file_offset) {
301    _file_offset = new_file_offset;
302    if (_file_open) {
303      // Seek one byte back from the target and write a byte to insure
304      // that the written file is the correct length.
305      _file_offset -= 1;
306      if (lseek(_fd, _file_offset, SEEK_SET) < 0) {
307        fail_stop("Unable to seek.", NULL);
308      }
309      char zero = 0;
310      write_bytes(&zero, 1);
311    }
312  }
313}
314
315
316// Dump bytes to file -- at the current file position.
317
318void FileMapInfo::write_bytes_aligned(const void* buffer, int nbytes) {
319  align_file_position();
320  write_bytes(buffer, nbytes);
321  align_file_position();
322}
323
324
325// Close the shared archive file.  This does NOT unmap mapped regions.
326
327void FileMapInfo::close() {
328  if (_file_open) {
329    if (::close(_fd) < 0) {
330      fail_stop("Unable to close the shared archive file.");
331    }
332    _file_open = false;
333    _fd = -1;
334  }
335}
336
337
338// JVM/TI RedefineClasses() support:
339// Remap the shared readonly space to shared readwrite, private.
340bool FileMapInfo::remap_shared_readonly_as_readwrite() {
341  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0];
342  if (!si->_read_only) {
343    // the space is already readwrite so we are done
344    return true;
345  }
346  size_t used = si->_used;
347  size_t size = align_size_up(used, os::vm_allocation_granularity());
348  if (!open_for_read()) {
349    return false;
350  }
351  char *base = os::remap_memory(_fd, _full_path, si->_file_offset,
352                                si->_base, size, false /* !read_only */,
353                                si->_allow_exec);
354  close();
355  if (base == NULL) {
356    fail_continue("Unable to remap shared readonly space (errno=%d).", errno);
357    return false;
358  }
359  if (base != si->_base) {
360    fail_continue("Unable to remap shared readonly space at required address.");
361    return false;
362  }
363  si->_read_only = false;
364  return true;
365}
366
367// Map the whole region at once, assumed to be allocated contiguously.
368ReservedSpace FileMapInfo::reserve_shared_memory() {
369  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[0];
370  char* requested_addr = si->_base;
371
372  size_t size = FileMapInfo::shared_spaces_size();
373
374  // Reserve the space first, then map otherwise map will go right over some
375  // other reserved memory (like the code cache).
376  ReservedSpace rs(size, os::vm_allocation_granularity(), false, requested_addr);
377  if (!rs.is_reserved()) {
378    fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr));
379    return rs;
380  }
381  // the reserved virtual memory is for mapping class data sharing archive
382  MemTracker::record_virtual_memory_type((address)rs.base(), mtClassShared);
383
384  return rs;
385}
386
387// Memory map a region in the address space.
388static const char* shared_region_name[] = { "ReadOnly", "ReadWrite", "MiscData", "MiscCode"};
389
390char* FileMapInfo::map_region(int i) {
391  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
392  size_t used = si->_used;
393  size_t alignment = os::vm_allocation_granularity();
394  size_t size = align_size_up(used, alignment);
395  char *requested_addr = si->_base;
396
397  // map the contents of the CDS archive in this memory
398  char *base = os::map_memory(_fd, _full_path, si->_file_offset,
399                              requested_addr, size, si->_read_only,
400                              si->_allow_exec);
401  if (base == NULL || base != si->_base) {
402    fail_continue(err_msg("Unable to map %s shared space at required address.", shared_region_name[i]));
403    return NULL;
404  }
405#ifdef _WINDOWS
406  // This call is Windows-only because the memory_type gets recorded for the other platforms
407  // in method FileMapInfo::reserve_shared_memory(), which is not called on Windows.
408  MemTracker::record_virtual_memory_type((address)base, mtClassShared);
409#endif
410  return base;
411}
412
413
414// Unmap a memory region in the address space.
415
416void FileMapInfo::unmap_region(int i) {
417  struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
418  size_t used = si->_used;
419  size_t size = align_size_up(used, os::vm_allocation_granularity());
420  if (!os::unmap_memory(si->_base, size)) {
421    fail_stop("Unable to unmap shared space.");
422  }
423}
424
425
426void FileMapInfo::assert_mark(bool check) {
427  if (!check) {
428    fail_stop("Mark mismatch while restoring from shared file.", NULL);
429  }
430}
431
432
433FileMapInfo* FileMapInfo::_current_info = NULL;
434
435
436// Open the shared archive file, read and validate the header
437// information (version, boot classpath, etc.).  If initialization
438// fails, shared spaces are disabled and the file is closed. [See
439// fail_continue.]
440bool FileMapInfo::initialize() {
441  assert(UseSharedSpaces, "UseSharedSpaces expected.");
442
443  if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space()) {
444    fail_continue("Tool agent requires sharing to be disabled.");
445    return false;
446  }
447
448  if (!open_for_read()) {
449    return false;
450  }
451
452  init_from_file(_fd);
453  if (!validate()) {
454    return false;
455  }
456
457  SharedReadOnlySize =  _header._space[0]._capacity;
458  SharedReadWriteSize = _header._space[1]._capacity;
459  SharedMiscDataSize =  _header._space[2]._capacity;
460  SharedMiscCodeSize =  _header._space[3]._capacity;
461  return true;
462}
463
464
465bool FileMapInfo::validate() {
466  if (_header._version != current_version()) {
467    fail_continue("The shared archive file is the wrong version.");
468    return false;
469  }
470  if (_header._magic != (int)0xf00baba2) {
471    fail_continue("The shared archive file has a bad magic number.");
472    return false;
473  }
474  char header_version[JVM_IDENT_MAX];
475  get_header_version(header_version);
476  if (strncmp(_header._jvm_ident, header_version, JVM_IDENT_MAX-1) != 0) {
477    fail_continue("The shared archive file was created by a different"
478                  " version or build of HotSpot.");
479    return false;
480  }
481  if (_header._obj_alignment != ObjectAlignmentInBytes) {
482    fail_continue("The shared archive file's ObjectAlignmentInBytes of %d"
483                  " does not equal the current ObjectAlignmentInBytes of %d.",
484                  _header._obj_alignment, ObjectAlignmentInBytes);
485    return false;
486  }
487
488  // Cannot verify interpreter yet, as it can only be created after the GC
489  // heap has been initialized.
490
491  if (_header._num_jars >= JVM_SHARED_JARS_MAX) {
492    fail_continue("Too many jar files to share.");
493    return false;
494  }
495
496  // Build checks on classpath and jar files
497  int num_jars_now = 0;
498  ClassPathEntry *cpe = ClassLoader::classpath_entry(0);
499  for ( ; cpe != NULL; cpe = cpe->next()) {
500
501    if (cpe->is_jar_file()) {
502      if (num_jars_now < _header._num_jars) {
503
504        // Jar file - verify timestamp and file size.
505        struct stat st;
506        const char *path = cpe->name();
507        if (os::stat(path, &st) != 0) {
508          fail_continue("Unable to open jar file %s.", path);
509          return false;
510        }
511        if (_header._jar[num_jars_now]._timestamp != st.st_mtime ||
512            _header._jar[num_jars_now]._filesize != st.st_size) {
513          fail_continue("A jar file is not the one used while building"
514                        " the shared archive file.");
515          return false;
516        }
517      }
518      ++num_jars_now;
519    } else {
520
521      // If directories appear in boot classpath, they must be empty to
522      // avoid having to verify each individual class file.
523      const char* name = ((ClassPathDirEntry*)cpe)->name();
524      if (!os::dir_is_empty(name)) {
525        fail_continue("Boot classpath directory %s is not empty.", name);
526        return false;
527      }
528    }
529  }
530  if (num_jars_now < _header._num_jars) {
531    fail_continue("The number of jar files in the boot classpath is"
532                  " less than the number the shared archive was created with.");
533    return false;
534  }
535
536  return true;
537}
538
539// The following method is provided to see whether a given pointer
540// falls in the mapped shared space.
541// Param:
542// p, The given pointer
543// Return:
544// True if the p is within the mapped shared space, otherwise, false.
545bool FileMapInfo::is_in_shared_space(const void* p) {
546  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
547    if (p >= _header._space[i]._base &&
548        p < _header._space[i]._base + _header._space[i]._used) {
549      return true;
550    }
551  }
552
553  return false;
554}
555
556void FileMapInfo::print_shared_spaces() {
557  gclog_or_tty->print_cr("Shared Spaces:");
558  for (int i = 0; i < MetaspaceShared::n_regions; i++) {
559    struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i];
560    gclog_or_tty->print("  %s " INTPTR_FORMAT "-" INTPTR_FORMAT,
561                        shared_region_name[i],
562                        si->_base, si->_base + si->_used);
563  }
564}
565
566// Unmap mapped regions of shared space.
567void FileMapInfo::stop_sharing_and_unmap(const char* msg) {
568  FileMapInfo *map_info = FileMapInfo::current_info();
569  if (map_info) {
570    map_info->fail_continue(msg);
571    for (int i = 0; i < MetaspaceShared::n_regions; i++) {
572      if (map_info->_header._space[i]._base != NULL) {
573        map_info->unmap_region(i);
574        map_info->_header._space[i]._base = NULL;
575      }
576    }
577  } else if (DumpSharedSpaces) {
578    fail_stop(msg, NULL);
579  }
580}
581