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