Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp
32284 views
/*1* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/vmSymbols.hpp"26#include "memory/allocation.inline.hpp"27#include "memory/resourceArea.hpp"28#include "oops/oop.inline.hpp"29#include "os_bsd.inline.hpp"30#include "runtime/handles.inline.hpp"31#include "runtime/perfMemory.hpp"32#include "services/memTracker.hpp"33#include "utilities/exceptions.hpp"3435// put OS-includes here36# include <sys/types.h>37# include <sys/mman.h>38# include <errno.h>39# include <stdio.h>40# include <unistd.h>41# include <sys/stat.h>42# include <signal.h>43# include <pwd.h>4445static char* backing_store_file_name = NULL; // name of the backing store46// file, if successfully created.4748// Standard Memory Implementation Details4950// create the PerfData memory region in standard memory.51//52static char* create_standard_memory(size_t size) {5354// allocate an aligned chuck of memory55char* mapAddress = os::reserve_memory(size);5657if (mapAddress == NULL) {58return NULL;59}6061// commit memory62if (!os::commit_memory(mapAddress, size, !ExecMem)) {63if (PrintMiscellaneous && Verbose) {64warning("Could not commit PerfData memory\n");65}66os::release_memory(mapAddress, size);67return NULL;68}6970return mapAddress;71}7273// delete the PerfData memory region74//75static void delete_standard_memory(char* addr, size_t size) {7677// there are no persistent external resources to cleanup for standard78// memory. since DestroyJavaVM does not support unloading of the JVM,79// cleanup of the memory resource is not performed. The memory will be80// reclaimed by the OS upon termination of the process.81//82return;83}8485// save the specified memory region to the given file86//87// Note: this function might be called from signal handler (by os::abort()),88// don't allocate heap memory.89//90static void save_memory_to_file(char* addr, size_t size) {9192const char* destfile = PerfMemory::get_perfdata_file_path();93assert(destfile[0] != '\0', "invalid PerfData file path");9495int result;9697RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),98result);;99if (result == OS_ERR) {100if (PrintMiscellaneous && Verbose) {101warning("Could not create Perfdata save file: %s: %s\n",102destfile, strerror(errno));103}104} else {105int fd = result;106107for (size_t remaining = size; remaining > 0;) {108109RESTARTABLE(::write(fd, addr, remaining), result);110if (result == OS_ERR) {111if (PrintMiscellaneous && Verbose) {112warning("Could not write Perfdata save file: %s: %s\n",113destfile, strerror(errno));114}115break;116}117118remaining -= (size_t)result;119addr += result;120}121122result = ::close(fd);123if (PrintMiscellaneous && Verbose) {124if (result == OS_ERR) {125warning("Could not close %s: %s\n", destfile, strerror(errno));126}127}128}129FREE_C_HEAP_ARRAY(char, destfile, mtInternal);130}131132133// Shared Memory Implementation Details134135// Note: the solaris and bsd shared memory implementation uses the mmap136// interface with a backing store file to implement named shared memory.137// Using the file system as the name space for shared memory allows a138// common name space to be supported across a variety of platforms. It139// also provides a name space that Java applications can deal with through140// simple file apis.141//142// The solaris and bsd implementations store the backing store file in143// a user specific temporary directory located in the /tmp file system,144// which is always a local file system and is sometimes a RAM based file145// system.146147// return the user specific temporary directory name.148//149// the caller is expected to free the allocated memory.150//151static char* get_user_tmp_dir(const char* user) {152153const char* tmpdir = os::get_temp_directory();154const char* perfdir = PERFDATA_NAME;155size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;156char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);157158// construct the path name to user specific tmp directory159snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);160161return dirname;162}163164// convert the given file name into a process id. if the file165// does not meet the file naming constraints, return 0.166//167static pid_t filename_to_pid(const char* filename) {168169// a filename that doesn't begin with a digit is not a170// candidate for conversion.171//172if (!isdigit(*filename)) {173return 0;174}175176// check if file name can be converted to an integer without177// any leftover characters.178//179char* remainder = NULL;180errno = 0;181pid_t pid = (pid_t)strtol(filename, &remainder, 10);182183if (errno != 0) {184return 0;185}186187// check for left over characters. If any, then the filename is188// not a candidate for conversion.189//190if (remainder != NULL && *remainder != '\0') {191return 0;192}193194// successful conversion, return the pid195return pid;196}197198199// Check if the given statbuf is considered a secure directory for200// the backing store files. Returns true if the directory is considered201// a secure location. Returns false if the statbuf is a symbolic link or202// if an error occurred.203//204static bool is_statbuf_secure(struct stat *statp) {205if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {206// The path represents a link or some non-directory file type,207// which is not what we expected. Declare it insecure.208//209return false;210}211// We have an existing directory, check if the permissions are safe.212//213if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {214// The directory is open for writing and could be subjected215// to a symlink or a hard link attack. Declare it insecure.216//217return false;218}219// If user is not root then see if the uid of the directory matches the effective uid of the process.220uid_t euid = geteuid();221if ((euid != 0) && (statp->st_uid != euid)) {222// The directory was not created by this user, declare it insecure.223//224return false;225}226return true;227}228229230// Check if the given path is considered a secure directory for231// the backing store files. Returns true if the directory exists232// and is considered a secure location. Returns false if the path233// is a symbolic link or if an error occurred.234//235static bool is_directory_secure(const char* path) {236struct stat statbuf;237int result = 0;238239RESTARTABLE(::lstat(path, &statbuf), result);240if (result == OS_ERR) {241return false;242}243244// The path exists, see if it is secure.245return is_statbuf_secure(&statbuf);246}247248249// Check if the given directory file descriptor is considered a secure250// directory for the backing store files. Returns true if the directory251// exists and is considered a secure location. Returns false if the path252// is a symbolic link or if an error occurred.253//254static bool is_dirfd_secure(int dir_fd) {255struct stat statbuf;256int result = 0;257258RESTARTABLE(::fstat(dir_fd, &statbuf), result);259if (result == OS_ERR) {260return false;261}262263// The path exists, now check its mode.264return is_statbuf_secure(&statbuf);265}266267268// Check to make sure fd1 and fd2 are referencing the same file system object.269//270static bool is_same_fsobject(int fd1, int fd2) {271struct stat statbuf1;272struct stat statbuf2;273int result = 0;274275RESTARTABLE(::fstat(fd1, &statbuf1), result);276if (result == OS_ERR) {277return false;278}279RESTARTABLE(::fstat(fd2, &statbuf2), result);280if (result == OS_ERR) {281return false;282}283284if ((statbuf1.st_ino == statbuf2.st_ino) &&285(statbuf1.st_dev == statbuf2.st_dev)) {286return true;287} else {288return false;289}290}291292293// Open the directory of the given path and validate it.294// Return a DIR * of the open directory.295//296static DIR *open_directory_secure(const char* dirname) {297// Open the directory using open() so that it can be verified298// to be secure by calling is_dirfd_secure(), opendir() and then check299// to see if they are the same file system object. This method does not300// introduce a window of opportunity for the directory to be attacked that301// calling opendir() and is_directory_secure() does.302int result;303DIR *dirp = NULL;304RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);305if (result == OS_ERR) {306// Directory doesn't exist or is a symlink, so there is nothing to cleanup.307if (PrintMiscellaneous && Verbose) {308if (errno == ELOOP) {309warning("directory %s is a symlink and is not secure\n", dirname);310} else {311warning("could not open directory %s: %s\n", dirname, strerror(errno));312}313}314return dirp;315}316int fd = result;317318// Determine if the open directory is secure.319if (!is_dirfd_secure(fd)) {320// The directory is not a secure directory.321os::close(fd);322return dirp;323}324325// Open the directory.326dirp = ::opendir(dirname);327if (dirp == NULL) {328// The directory doesn't exist, close fd and return.329os::close(fd);330return dirp;331}332333// Check to make sure fd and dirp are referencing the same file system object.334if (!is_same_fsobject(fd, dirfd(dirp))) {335// The directory is not secure.336os::close(fd);337os::closedir(dirp);338dirp = NULL;339return dirp;340}341342// Close initial open now that we know directory is secure343os::close(fd);344345return dirp;346}347348// NOTE: The code below uses fchdir(), open() and unlink() because349// fdopendir(), openat() and unlinkat() are not supported on all350// versions. Once the support for fdopendir(), openat() and unlinkat()351// is available on all supported versions the code can be changed352// to use these functions.353354// Open the directory of the given path, validate it and set the355// current working directory to it.356// Return a DIR * of the open directory and the saved cwd fd.357//358static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {359360// Open the directory.361DIR* dirp = open_directory_secure(dirname);362if (dirp == NULL) {363// Directory doesn't exist or is insecure, so there is nothing to cleanup.364return dirp;365}366int fd = dirfd(dirp);367368// Open a fd to the cwd and save it off.369int result;370RESTARTABLE(::open(".", O_RDONLY), result);371if (result == OS_ERR) {372*saved_cwd_fd = -1;373} else {374*saved_cwd_fd = result;375}376377// Set the current directory to dirname by using the fd of the directory and378// handle errors, otherwise shared memory files will be created in cwd.379result = fchdir(fd);380if (result == OS_ERR) {381if (PrintMiscellaneous && Verbose) {382warning("could not change to directory %s", dirname);383}384if (*saved_cwd_fd != -1) {385::close(*saved_cwd_fd);386*saved_cwd_fd = -1;387}388// Close the directory.389os::closedir(dirp);390return NULL;391} else {392return dirp;393}394}395396// Close the directory and restore the current working directory.397//398static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {399400int result;401// If we have a saved cwd change back to it and close the fd.402if (saved_cwd_fd != -1) {403result = fchdir(saved_cwd_fd);404::close(saved_cwd_fd);405}406407// Close the directory.408os::closedir(dirp);409}410411// Check if the given file descriptor is considered a secure.412//413static bool is_file_secure(int fd, const char *filename) {414415int result;416struct stat statbuf;417418// Determine if the file is secure.419RESTARTABLE(::fstat(fd, &statbuf), result);420if (result == OS_ERR) {421if (PrintMiscellaneous && Verbose) {422warning("fstat failed on %s: %s\n", filename, strerror(errno));423}424return false;425}426if (statbuf.st_nlink > 1) {427// A file with multiple links is not expected.428if (PrintMiscellaneous && Verbose) {429warning("file %s has multiple links\n", filename);430}431return false;432}433return true;434}435436// return the user name for the given user id437//438// the caller is expected to free the allocated memory.439//440static char* get_user_name(uid_t uid) {441442struct passwd pwent;443444// determine the max pwbuf size from sysconf, and hardcode445// a default if this not available through sysconf.446//447long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);448if (bufsize == -1)449bufsize = 1024;450451char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);452453// POSIX interface to getpwuid_r is used on LINUX454struct passwd* p;455int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);456457if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {458if (PrintMiscellaneous && Verbose) {459if (result != 0) {460warning("Could not retrieve passwd entry: %s\n",461strerror(result));462}463else if (p == NULL) {464// this check is added to protect against an observed problem465// with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,466// indicating success, but has p == NULL. This was observed when467// inserting a file descriptor exhaustion fault prior to the call468// getpwuid_r() call. In this case, error is set to the appropriate469// error condition, but this is undocumented behavior. This check470// is safe under any condition, but the use of errno in the output471// message may result in an erroneous message.472// Bug Id 89052 was opened with RedHat.473//474warning("Could not retrieve passwd entry: %s\n",475strerror(errno));476}477else {478warning("Could not determine user name: %s\n",479p->pw_name == NULL ? "pw_name = NULL" :480"pw_name zero length");481}482}483FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);484return NULL;485}486487char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);488strcpy(user_name, p->pw_name);489490FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);491return user_name;492}493494// return the name of the user that owns the process identified by vmid.495//496// This method uses a slow directory search algorithm to find the backing497// store file for the specified vmid and returns the user name, as determined498// by the user name suffix of the hsperfdata_<username> directory name.499//500// the caller is expected to free the allocated memory.501//502static char* get_user_name_slow(int vmid, TRAPS) {503504// short circuit the directory search if the process doesn't even exist.505if (kill(vmid, 0) == OS_ERR) {506if (errno == ESRCH) {507THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),508"Process not found");509}510else /* EPERM */ {511THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));512}513}514515// directory search516char* oldest_user = NULL;517time_t oldest_ctime = 0;518519const char* tmpdirname = os::get_temp_directory();520521// open the temp directory522DIR* tmpdirp = os::opendir(tmpdirname);523524if (tmpdirp == NULL) {525// Cannot open the directory to get the user name, return.526return NULL;527}528529// for each entry in the directory that matches the pattern hsperfdata_*,530// open the directory and check if the file for the given vmid exists.531// The file with the expected name and the latest creation date is used532// to determine the user name for the process id.533//534struct dirent* dentry;535errno = 0;536while ((dentry = os::readdir(tmpdirp)) != NULL) {537538// check if the directory entry is a hsperfdata file539if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {540continue;541}542543char* usrdir_name = NEW_C_HEAP_ARRAY(char,544strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);545strcpy(usrdir_name, tmpdirname);546strcat(usrdir_name, "/");547strcat(usrdir_name, dentry->d_name);548549// open the user directory550DIR* subdirp = open_directory_secure(usrdir_name);551552if (subdirp == NULL) {553FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);554continue;555}556557struct dirent* udentry;558errno = 0;559while ((udentry = os::readdir(subdirp)) != NULL) {560561if (filename_to_pid(udentry->d_name) == vmid) {562struct stat statbuf;563int result;564565char* filename = NEW_C_HEAP_ARRAY(char,566strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);567568strcpy(filename, usrdir_name);569strcat(filename, "/");570strcat(filename, udentry->d_name);571572// don't follow symbolic links for the file573RESTARTABLE(::lstat(filename, &statbuf), result);574if (result == OS_ERR) {575FREE_C_HEAP_ARRAY(char, filename, mtInternal);576continue;577}578579// skip over files that are not regular files.580if (!S_ISREG(statbuf.st_mode)) {581FREE_C_HEAP_ARRAY(char, filename, mtInternal);582continue;583}584585// compare and save filename with latest creation time586if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {587588if (statbuf.st_ctime > oldest_ctime) {589char* user = strchr(dentry->d_name, '_') + 1;590591if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);592oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);593594strcpy(oldest_user, user);595oldest_ctime = statbuf.st_ctime;596}597}598599FREE_C_HEAP_ARRAY(char, filename, mtInternal);600}601}602os::closedir(subdirp);603FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);604}605os::closedir(tmpdirp);606607return(oldest_user);608}609610// return the name of the user that owns the JVM indicated by the given vmid.611//612static char* get_user_name(int vmid, TRAPS) {613return get_user_name_slow(vmid, THREAD);614}615616// return the file name of the backing store file for the named617// shared memory region for the given user name and vmid.618//619// the caller is expected to free the allocated memory.620//621static char* get_sharedmem_filename(const char* dirname, int vmid) {622623// add 2 for the file separator and a null terminator.624size_t nbytes = strlen(dirname) + UINT_CHARS + 2;625626char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);627snprintf(name, nbytes, "%s/%d", dirname, vmid);628629return name;630}631632633// remove file634//635// this method removes the file specified by the given path636//637static void remove_file(const char* path) {638639int result;640641// if the file is a directory, the following unlink will fail. since642// we don't expect to find directories in the user temp directory, we643// won't try to handle this situation. even if accidentially or644// maliciously planted, the directory's presence won't hurt anything.645//646RESTARTABLE(::unlink(path), result);647if (PrintMiscellaneous && Verbose && result == OS_ERR) {648if (errno != ENOENT) {649warning("Could not unlink shared memory backing"650" store file %s : %s\n", path, strerror(errno));651}652}653}654655656// cleanup stale shared memory resources657//658// This method attempts to remove all stale shared memory files in659// the named user temporary directory. It scans the named directory660// for files matching the pattern ^$[0-9]*$. For each file found, the661// process id is extracted from the file name and a test is run to662// determine if the process is alive. If the process is not alive,663// any stale file resources are removed.664//665static void cleanup_sharedmem_resources(const char* dirname) {666667int saved_cwd_fd;668// open the directory and set the current working directory to it669DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);670if (dirp == NULL) {671// directory doesn't exist or is insecure, so there is nothing to cleanup672return;673}674675// for each entry in the directory that matches the expected file676// name pattern, determine if the file resources are stale and if677// so, remove the file resources. Note, instrumented HotSpot processes678// for this user may start and/or terminate during this search and679// remove or create new files in this directory. The behavior of this680// loop under these conditions is dependent upon the implementation of681// opendir/readdir.682//683struct dirent* entry;684errno = 0;685while ((entry = os::readdir(dirp)) != NULL) {686687pid_t pid = filename_to_pid(entry->d_name);688689if (pid == 0) {690691if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {692693// attempt to remove all unexpected files, except "." and ".."694unlink(entry->d_name);695}696697errno = 0;698continue;699}700701// we now have a file name that converts to a valid integer702// that could represent a process id . if this process id703// matches the current process id or the process is not running,704// then remove the stale file resources.705//706// process liveness is detected by sending signal number 0 to707// the process id (see kill(2)). if kill determines that the708// process does not exist, then the file resources are removed.709// if kill determines that that we don't have permission to710// signal the process, then the file resources are assumed to711// be stale and are removed because the resources for such a712// process should be in a different user specific directory.713//714if ((pid == os::current_process_id()) ||715(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {716717unlink(entry->d_name);718}719errno = 0;720}721722// close the directory and reset the current working directory723close_directory_secure_cwd(dirp, saved_cwd_fd);724725}726727// make the user specific temporary directory. Returns true if728// the directory exists and is secure upon return. Returns false729// if the directory exists but is either a symlink, is otherwise730// insecure, or if an error occurred.731//732static bool make_user_tmp_dir(const char* dirname) {733734// create the directory with 0755 permissions. note that the directory735// will be owned by euid::egid, which may not be the same as uid::gid.736//737if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {738if (errno == EEXIST) {739// The directory already exists and was probably created by another740// JVM instance. However, this could also be the result of a741// deliberate symlink. Verify that the existing directory is safe.742//743if (!is_directory_secure(dirname)) {744// directory is not secure745if (PrintMiscellaneous && Verbose) {746warning("%s directory is insecure\n", dirname);747}748return false;749}750}751else {752// we encountered some other failure while attempting753// to create the directory754//755if (PrintMiscellaneous && Verbose) {756warning("could not create directory %s: %s\n",757dirname, strerror(errno));758}759return false;760}761}762return true;763}764765// create the shared memory file resources766//767// This method creates the shared memory file with the given size768// This method also creates the user specific temporary directory, if769// it does not yet exist.770//771static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {772773// make the user temporary directory774if (!make_user_tmp_dir(dirname)) {775// could not make/find the directory or the found directory776// was not secure777return -1;778}779780int saved_cwd_fd;781// open the directory and set the current working directory to it782DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);783if (dirp == NULL) {784// Directory doesn't exist or is insecure, so cannot create shared785// memory file.786return -1;787}788789// Open the filename in the current directory.790// Cannot use O_TRUNC here; truncation of an existing file has to happen791// after the is_file_secure() check below.792int result;793RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);794if (result == OS_ERR) {795if (PrintMiscellaneous && Verbose) {796if (errno == ELOOP) {797warning("file %s is a symlink and is not secure\n", filename);798} else {799warning("could not create file %s: %s\n", filename, strerror(errno));800}801}802// close the directory and reset the current working directory803close_directory_secure_cwd(dirp, saved_cwd_fd);804805return -1;806}807// close the directory and reset the current working directory808close_directory_secure_cwd(dirp, saved_cwd_fd);809810// save the file descriptor811int fd = result;812813// check to see if the file is secure814if (!is_file_secure(fd, filename)) {815::close(fd);816return -1;817}818819// truncate the file to get rid of any existing data820RESTARTABLE(::ftruncate(fd, (off_t)0), result);821if (result == OS_ERR) {822if (PrintMiscellaneous && Verbose) {823warning("could not truncate shared memory file: %s\n", strerror(errno));824}825::close(fd);826return -1;827}828// set the file size829RESTARTABLE(::ftruncate(fd, (off_t)size), result);830if (result == OS_ERR) {831if (PrintMiscellaneous && Verbose) {832warning("could not set shared memory file size: %s\n", strerror(errno));833}834::close(fd);835return -1;836}837838// Verify that we have enough disk space for this file.839// We'll get random SIGBUS crashes on memory accesses if840// we don't.841842for (size_t seekpos = 0; seekpos < size; seekpos += os::vm_page_size()) {843int zero_int = 0;844result = (int)os::seek_to_file_offset(fd, (jlong)(seekpos));845if (result == -1 ) break;846RESTARTABLE(::write(fd, &zero_int, 1), result);847if (result != 1) {848if (errno == ENOSPC) {849warning("Insufficient space for shared memory file:\n %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename);850}851break;852}853}854855if (result != -1) {856return fd;857} else {858::close(fd);859return -1;860}861}862863// open the shared memory file for the given user and vmid. returns864// the file descriptor for the open file or -1 if the file could not865// be opened.866//867static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {868869// open the file870int result;871RESTARTABLE(::open(filename, oflags), result);872if (result == OS_ERR) {873if (errno == ENOENT) {874THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),875"Process not found", OS_ERR);876}877else if (errno == EACCES) {878THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),879"Permission denied", OS_ERR);880}881else {882THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);883}884}885int fd = result;886887// check to see if the file is secure888if (!is_file_secure(fd, filename)) {889::close(fd);890return -1;891}892893return fd;894}895896// create a named shared memory region. returns the address of the897// memory region on success or NULL on failure. A return value of898// NULL will ultimately disable the shared memory feature.899//900// On Solaris and Bsd, the name space for shared memory objects901// is the file system name space.902//903// A monitoring application attaching to a JVM does not need to know904// the file system name of the shared memory object. However, it may905// be convenient for applications to discover the existence of newly906// created and terminating JVMs by watching the file system name space907// for files being created or removed.908//909static char* mmap_create_shared(size_t size) {910911int result;912int fd;913char* mapAddress;914915int vmid = os::current_process_id();916917char* user_name = get_user_name(geteuid());918919if (user_name == NULL)920return NULL;921922char* dirname = get_user_tmp_dir(user_name);923char* filename = get_sharedmem_filename(dirname, vmid);924925// get the short filename926char* short_filename = strrchr(filename, '/');927if (short_filename == NULL) {928short_filename = filename;929} else {930short_filename++;931}932933// cleanup any stale shared memory files934cleanup_sharedmem_resources(dirname);935936assert(((size > 0) && (size % os::vm_page_size() == 0)),937"unexpected PerfMemory region size");938939fd = create_sharedmem_resources(dirname, short_filename, size);940941FREE_C_HEAP_ARRAY(char, user_name, mtInternal);942FREE_C_HEAP_ARRAY(char, dirname, mtInternal);943944if (fd == -1) {945FREE_C_HEAP_ARRAY(char, filename, mtInternal);946return NULL;947}948949mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);950951result = ::close(fd);952assert(result != OS_ERR, "could not close file");953954if (mapAddress == MAP_FAILED) {955if (PrintMiscellaneous && Verbose) {956warning("mmap failed - %s\n", strerror(errno));957}958remove_file(filename);959FREE_C_HEAP_ARRAY(char, filename, mtInternal);960return NULL;961}962963// save the file name for use in delete_shared_memory()964backing_store_file_name = filename;965966// clear the shared memory region967(void)::memset((void*) mapAddress, 0, size);968969// it does not go through os api, the operation has to record from here970MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);971972return mapAddress;973}974975// release a named shared memory region976//977static void unmap_shared(char* addr, size_t bytes) {978os::release_memory(addr, bytes);979}980981// create the PerfData memory region in shared memory.982//983static char* create_shared_memory(size_t size) {984985// create the shared memory region.986return mmap_create_shared(size);987}988989// delete the shared PerfData memory region990//991static void delete_shared_memory(char* addr, size_t size) {992993// cleanup the persistent shared memory resources. since DestroyJavaVM does994// not support unloading of the JVM, unmapping of the memory resource is995// not performed. The memory will be reclaimed by the OS upon termination of996// the process. The backing store file is deleted from the file system.997998assert(!PerfDisableSharedMem, "shouldn't be here");9991000if (backing_store_file_name != NULL) {1001remove_file(backing_store_file_name);1002// Don't.. Free heap memory could deadlock os::abort() if it is called1003// from signal handler. OS will reclaim the heap memory.1004// FREE_C_HEAP_ARRAY(char, backing_store_file_name);1005backing_store_file_name = NULL;1006}1007}10081009// return the size of the file for the given file descriptor1010// or 0 if it is not a valid size for a shared memory file1011//1012static size_t sharedmem_filesize(int fd, TRAPS) {10131014struct stat statbuf;1015int result;10161017RESTARTABLE(::fstat(fd, &statbuf), result);1018if (result == OS_ERR) {1019if (PrintMiscellaneous && Verbose) {1020warning("fstat failed: %s\n", strerror(errno));1021}1022THROW_MSG_0(vmSymbols::java_io_IOException(),1023"Could not determine PerfMemory size");1024}10251026if ((statbuf.st_size == 0) ||1027((size_t)statbuf.st_size % os::vm_page_size() != 0)) {1028THROW_MSG_0(vmSymbols::java_lang_Exception(),1029"Invalid PerfMemory size");1030}10311032return (size_t)statbuf.st_size;1033}10341035// attach to a named shared memory region.1036//1037static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {10381039char* mapAddress;1040int result;1041int fd;1042size_t size = 0;1043const char* luser = NULL;10441045int mmap_prot;1046int file_flags;10471048ResourceMark rm;10491050// map the high level access mode to the appropriate permission1051// constructs for the file and the shared memory mapping.1052if (mode == PerfMemory::PERF_MODE_RO) {1053mmap_prot = PROT_READ;1054file_flags = O_RDONLY | O_NOFOLLOW;1055}1056else if (mode == PerfMemory::PERF_MODE_RW) {1057#ifdef LATER1058mmap_prot = PROT_READ | PROT_WRITE;1059file_flags = O_RDWR | O_NOFOLLOW;1060#else1061THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1062"Unsupported access mode");1063#endif1064}1065else {1066THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1067"Illegal access mode");1068}10691070if (user == NULL || strlen(user) == 0) {1071luser = get_user_name(vmid, CHECK);1072}1073else {1074luser = user;1075}10761077if (luser == NULL) {1078THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1079"Could not map vmid to user Name");1080}10811082char* dirname = get_user_tmp_dir(luser);10831084// since we don't follow symbolic links when creating the backing1085// store file, we don't follow them when attaching either.1086//1087if (!is_directory_secure(dirname)) {1088FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1089THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1090"Process not found");1091}10921093char* filename = get_sharedmem_filename(dirname, vmid);10941095// copy heap memory to resource memory. the open_sharedmem_file1096// method below need to use the filename, but could throw an1097// exception. using a resource array prevents the leak that1098// would otherwise occur.1099char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1100strcpy(rfilename, filename);11011102// free the c heap resources that are no longer needed1103if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);1104FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1105FREE_C_HEAP_ARRAY(char, filename, mtInternal);11061107// open the shared memory file for the give vmid1108fd = open_sharedmem_file(rfilename, file_flags, CHECK);1109assert(fd != OS_ERR, "unexpected value");11101111if (*sizep == 0) {1112size = sharedmem_filesize(fd, CHECK);1113} else {1114size = *sizep;1115}11161117assert(size > 0, "unexpected size <= 0");11181119mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);11201121// attempt to close the file - restart if it gets interrupted,1122// but ignore other failures1123result = ::close(fd);1124assert(result != OS_ERR, "could not close file");11251126if (mapAddress == MAP_FAILED) {1127if (PrintMiscellaneous && Verbose) {1128warning("mmap failed: %s\n", strerror(errno));1129}1130THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1131"Could not map PerfMemory");1132}11331134// it does not go through os api, the operation has to record from here1135MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);11361137*addr = mapAddress;1138*sizep = size;11391140if (PerfTraceMemOps) {1141tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "1142INTPTR_FORMAT "\n", size, vmid, p2i((void*)mapAddress));1143}1144}11451146114711481149// create the PerfData memory region1150//1151// This method creates the memory region used to store performance1152// data for the JVM. The memory may be created in standard or1153// shared memory.1154//1155void PerfMemory::create_memory_region(size_t size) {11561157if (PerfDisableSharedMem) {1158// do not share the memory for the performance data.1159_start = create_standard_memory(size);1160}1161else {1162_start = create_shared_memory(size);1163if (_start == NULL) {11641165// creation of the shared memory region failed, attempt1166// to create a contiguous, non-shared memory region instead.1167//1168if (PrintMiscellaneous && Verbose) {1169warning("Reverting to non-shared PerfMemory region.\n");1170}1171PerfDisableSharedMem = true;1172_start = create_standard_memory(size);1173}1174}11751176if (_start != NULL) _capacity = size;11771178}11791180// delete the PerfData memory region1181//1182// This method deletes the memory region used to store performance1183// data for the JVM. The memory region indicated by the <address, size>1184// tuple will be inaccessible after a call to this method.1185//1186void PerfMemory::delete_memory_region() {11871188assert((start() != NULL && capacity() > 0), "verify proper state");11891190// If user specifies PerfDataSaveFile, it will save the performance data1191// to the specified file name no matter whether PerfDataSaveToFile is specified1192// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1193// -XX:+PerfDataSaveToFile.1194if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1195save_memory_to_file(start(), capacity());1196}11971198if (PerfDisableSharedMem) {1199delete_standard_memory(start(), capacity());1200}1201else {1202delete_shared_memory(start(), capacity());1203}1204}12051206// attach to the PerfData memory region for another JVM1207//1208// This method returns an <address, size> tuple that points to1209// a memory buffer that is kept reasonably synchronized with1210// the PerfData memory region for the indicated JVM. This1211// buffer may be kept in synchronization via shared memory1212// or some other mechanism that keeps the buffer updated.1213//1214// If the JVM chooses not to support the attachability feature,1215// this method should throw an UnsupportedOperation exception.1216//1217// This implementation utilizes named shared memory to map1218// the indicated process's PerfData memory region into this JVMs1219// address space.1220//1221void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {12221223if (vmid == 0 || vmid == os::current_process_id()) {1224*addrp = start();1225*sizep = capacity();1226return;1227}12281229mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);1230}12311232// detach from the PerfData memory region of another JVM1233//1234// This method detaches the PerfData memory region of another1235// JVM, specified as an <address, size> tuple of a buffer1236// in this process's address space. This method may perform1237// arbitrary actions to accomplish the detachment. The memory1238// region specified by <address, size> will be inaccessible after1239// a call to this method.1240//1241// If the JVM chooses not to support the attachability feature,1242// this method should throw an UnsupportedOperation exception.1243//1244// This implementation utilizes named shared memory to detach1245// the indicated process's PerfData memory region from this1246// process's address space.1247//1248void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {12491250assert(addr != 0, "address sanity check");1251assert(bytes > 0, "capacity sanity check");12521253if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1254// prevent accidental detachment of this process's PerfMemory region1255return;1256}12571258unmap_shared(addr, bytes);1259}12601261char* PerfMemory::backing_store_filename() {1262return backing_store_file_name;1263}126412651266