Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/linux/vm/perfMemory_linux.cpp
32285 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_linux.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>4445#ifdef __ANDROID__46# define S_IREAD S_IRUSR47# define S_IWRITE S_IWUSR48# define S_IEXEC S_IXUSR49#endif // __ANDROID__5051static char* backing_store_file_name = NULL; // name of the backing store52// file, if successfully created.5354// Standard Memory Implementation Details5556// create the PerfData memory region in standard memory.57//58static char* create_standard_memory(size_t size) {5960// allocate an aligned chuck of memory61char* mapAddress = os::reserve_memory(size);6263if (mapAddress == NULL) {64return NULL;65}6667// commit memory68if (!os::commit_memory(mapAddress, size, !ExecMem)) {69if (PrintMiscellaneous && Verbose) {70warning("Could not commit PerfData memory\n");71}72os::release_memory(mapAddress, size);73return NULL;74}7576return mapAddress;77}7879// delete the PerfData memory region80//81static void delete_standard_memory(char* addr, size_t size) {8283// there are no persistent external resources to cleanup for standard84// memory. since DestroyJavaVM does not support unloading of the JVM,85// cleanup of the memory resource is not performed. The memory will be86// reclaimed by the OS upon termination of the process.87//88return;89}9091// save the specified memory region to the given file92//93// Note: this function might be called from signal handler (by os::abort()),94// don't allocate heap memory.95//96static void save_memory_to_file(char* addr, size_t size) {9798const char* destfile = PerfMemory::get_perfdata_file_path();99assert(destfile[0] != '\0', "invalid PerfData file path");100101int result;102103RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),104result);;105if (result == OS_ERR) {106if (PrintMiscellaneous && Verbose) {107warning("Could not create Perfdata save file: %s: %s\n",108destfile, strerror(errno));109}110} else {111int fd = result;112113for (size_t remaining = size; remaining > 0;) {114115RESTARTABLE(::write(fd, addr, remaining), result);116if (result == OS_ERR) {117if (PrintMiscellaneous && Verbose) {118warning("Could not write Perfdata save file: %s: %s\n",119destfile, strerror(errno));120}121break;122}123124remaining -= (size_t)result;125addr += result;126}127128result = ::close(fd);129if (PrintMiscellaneous && Verbose) {130if (result == OS_ERR) {131warning("Could not close %s: %s\n", destfile, strerror(errno));132}133}134}135FREE_C_HEAP_ARRAY(char, destfile, mtInternal);136}137138139// Shared Memory Implementation Details140141// Note: the solaris and linux shared memory implementation uses the mmap142// interface with a backing store file to implement named shared memory.143// Using the file system as the name space for shared memory allows a144// common name space to be supported across a variety of platforms. It145// also provides a name space that Java applications can deal with through146// simple file apis.147//148// The solaris and linux implementations store the backing store file in149// a user specific temporary directory located in the /tmp file system,150// which is always a local file system and is sometimes a RAM based file151// system.152153// return the user specific temporary directory name.154//155// the caller is expected to free the allocated memory.156//157static char* get_user_tmp_dir(const char* user) {158159const char* tmpdir = os::get_temp_directory();160const char* perfdir = PERFDATA_NAME;161size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;162char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);163164// construct the path name to user specific tmp directory165snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);166167return dirname;168}169170// convert the given file name into a process id. if the file171// does not meet the file naming constraints, return 0.172//173static pid_t filename_to_pid(const char* filename) {174175// a filename that doesn't begin with a digit is not a176// candidate for conversion.177//178if (!isdigit(*filename)) {179return 0;180}181182// check if file name can be converted to an integer without183// any leftover characters.184//185char* remainder = NULL;186errno = 0;187pid_t pid = (pid_t)strtol(filename, &remainder, 10);188189if (errno != 0) {190return 0;191}192193// check for left over characters. If any, then the filename is194// not a candidate for conversion.195//196if (remainder != NULL && *remainder != '\0') {197return 0;198}199200// successful conversion, return the pid201return pid;202}203204205// Check if the given statbuf is considered a secure directory for206// the backing store files. Returns true if the directory is considered207// a secure location. Returns false if the statbuf is a symbolic link or208// if an error occurred.209//210static bool is_statbuf_secure(struct stat *statp) {211if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {212// The path represents a link or some non-directory file type,213// which is not what we expected. Declare it insecure.214//215return false;216}217// We have an existing directory, check if the permissions are safe.218//219if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {220// The directory is open for writing and could be subjected221// to a symlink or a hard link attack. Declare it insecure.222//223return false;224}225// If user is not root then see if the uid of the directory matches the effective uid of the process.226uid_t euid = geteuid();227if ((euid != 0) && (statp->st_uid != euid)) {228// The directory was not created by this user, declare it insecure.229//230return false;231}232return true;233}234235236// Check if the given path is considered a secure directory for237// the backing store files. Returns true if the directory exists238// and is considered a secure location. Returns false if the path239// is a symbolic link or if an error occurred.240//241static bool is_directory_secure(const char* path) {242struct stat statbuf;243int result = 0;244245RESTARTABLE(::lstat(path, &statbuf), result);246if (result == OS_ERR) {247return false;248}249250// The path exists, see if it is secure.251return is_statbuf_secure(&statbuf);252}253254255// Check if the given directory file descriptor is considered a secure256// directory for the backing store files. Returns true if the directory257// exists and is considered a secure location. Returns false if the path258// is a symbolic link or if an error occurred.259//260static bool is_dirfd_secure(int dir_fd) {261struct stat statbuf;262int result = 0;263264RESTARTABLE(::fstat(dir_fd, &statbuf), result);265if (result == OS_ERR) {266return false;267}268269// The path exists, now check its mode.270return is_statbuf_secure(&statbuf);271}272273274// Check to make sure fd1 and fd2 are referencing the same file system object.275//276static bool is_same_fsobject(int fd1, int fd2) {277struct stat statbuf1;278struct stat statbuf2;279int result = 0;280281RESTARTABLE(::fstat(fd1, &statbuf1), result);282if (result == OS_ERR) {283return false;284}285RESTARTABLE(::fstat(fd2, &statbuf2), result);286if (result == OS_ERR) {287return false;288}289290if ((statbuf1.st_ino == statbuf2.st_ino) &&291(statbuf1.st_dev == statbuf2.st_dev)) {292return true;293} else {294return false;295}296}297298299// Open the directory of the given path and validate it.300// Return a DIR * of the open directory.301//302static DIR *open_directory_secure(const char* dirname) {303// Open the directory using open() so that it can be verified304// to be secure by calling is_dirfd_secure(), opendir() and then check305// to see if they are the same file system object. This method does not306// introduce a window of opportunity for the directory to be attacked that307// calling opendir() and is_directory_secure() does.308int result;309DIR *dirp = NULL;310RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);311if (result == OS_ERR) {312if (PrintMiscellaneous && Verbose) {313if (errno == ELOOP) {314warning("directory %s is a symlink and is not secure\n", dirname);315} else {316warning("could not open directory %s: %s\n", dirname, strerror(errno));317}318}319return dirp;320}321int fd = result;322323// Determine if the open directory is secure.324if (!is_dirfd_secure(fd)) {325// The directory is not a secure directory.326os::close(fd);327return dirp;328}329330// Open the directory.331dirp = ::opendir(dirname);332if (dirp == NULL) {333// The directory doesn't exist, close fd and return.334os::close(fd);335return dirp;336}337338// Check to make sure fd and dirp are referencing the same file system object.339if (!is_same_fsobject(fd, dirfd(dirp))) {340// The directory is not secure.341os::close(fd);342os::closedir(dirp);343dirp = NULL;344return dirp;345}346347// Close initial open now that we know directory is secure348os::close(fd);349350return dirp;351}352353// NOTE: The code below uses fchdir(), open() and unlink() because354// fdopendir(), openat() and unlinkat() are not supported on all355// versions. Once the support for fdopendir(), openat() and unlinkat()356// is available on all supported versions the code can be changed357// to use these functions.358359// Open the directory of the given path, validate it and set the360// current working directory to it.361// Return a DIR * of the open directory and the saved cwd fd.362//363static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {364365// Open the directory.366DIR* dirp = open_directory_secure(dirname);367if (dirp == NULL) {368// Directory doesn't exist or is insecure, so there is nothing to cleanup.369return dirp;370}371int fd = dirfd(dirp);372373// Open a fd to the cwd and save it off.374int result;375RESTARTABLE(::open(".", O_RDONLY), result);376if (result == OS_ERR) {377*saved_cwd_fd = -1;378} else {379*saved_cwd_fd = result;380}381382// Set the current directory to dirname by using the fd of the directory and383// handle errors, otherwise shared memory files will be created in cwd.384result = fchdir(fd);385if (result == OS_ERR) {386if (PrintMiscellaneous && Verbose) {387warning("could not change to directory %s", dirname);388}389if (*saved_cwd_fd != -1) {390::close(*saved_cwd_fd);391*saved_cwd_fd = -1;392}393// Close the directory.394os::closedir(dirp);395return NULL;396} else {397return dirp;398}399}400401// Close the directory and restore the current working directory.402//403static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {404405int result;406// If we have a saved cwd change back to it and close the fd.407if (saved_cwd_fd != -1) {408result = fchdir(saved_cwd_fd);409::close(saved_cwd_fd);410}411412// Close the directory.413os::closedir(dirp);414}415416// Check if the given file descriptor is considered a secure.417//418static bool is_file_secure(int fd, const char *filename) {419420int result;421struct stat statbuf;422423// Determine if the file is secure.424RESTARTABLE(::fstat(fd, &statbuf), result);425if (result == OS_ERR) {426if (PrintMiscellaneous && Verbose) {427warning("fstat failed on %s: %s\n", filename, strerror(errno));428}429return false;430}431if (statbuf.st_nlink > 1) {432// A file with multiple links is not expected.433if (PrintMiscellaneous && Verbose) {434warning("file %s has multiple links\n", filename);435}436return false;437}438return true;439}440441442// return the user name for the given user id443//444// the caller is expected to free the allocated memory.445//446static char* get_user_name(uid_t uid) {447448struct passwd pwent;449450// determine the max pwbuf size from sysconf, and hardcode451// a default if this not available through sysconf.452//453long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);454if (bufsize == -1)455bufsize = 1024;456457char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);458459// POSIX interface to getpwuid_r is used on LINUX460struct passwd* p;461int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);462463if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {464if (PrintMiscellaneous && Verbose) {465if (result != 0) {466warning("Could not retrieve passwd entry: %s\n",467strerror(result));468}469else if (p == NULL) {470// this check is added to protect against an observed problem471// with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,472// indicating success, but has p == NULL. This was observed when473// inserting a file descriptor exhaustion fault prior to the call474// getpwuid_r() call. In this case, error is set to the appropriate475// error condition, but this is undocumented behavior. This check476// is safe under any condition, but the use of errno in the output477// message may result in an erroneous message.478// Bug Id 89052 was opened with RedHat.479//480warning("Could not retrieve passwd entry: %s\n",481strerror(errno));482}483else {484warning("Could not determine user name: %s\n",485p->pw_name == NULL ? "pw_name = NULL" :486"pw_name zero length");487}488}489FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);490return NULL;491}492493char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);494strcpy(user_name, p->pw_name);495496FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);497return user_name;498}499500// return the name of the user that owns the process identified by vmid.501//502// This method uses a slow directory search algorithm to find the backing503// store file for the specified vmid and returns the user name, as determined504// by the user name suffix of the hsperfdata_<username> directory name.505//506// the caller is expected to free the allocated memory.507//508static char* get_user_name_slow(int vmid, TRAPS) {509510// short circuit the directory search if the process doesn't even exist.511if (kill(vmid, 0) == OS_ERR) {512if (errno == ESRCH) {513THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),514"Process not found");515}516else /* EPERM */ {517THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));518}519}520521// directory search522char* oldest_user = NULL;523time_t oldest_ctime = 0;524525const char* tmpdirname = os::get_temp_directory();526527// open the temp directory528DIR* tmpdirp = os::opendir(tmpdirname);529530if (tmpdirp == NULL) {531// Cannot open the directory to get the user name, return.532return NULL;533}534535// for each entry in the directory that matches the pattern hsperfdata_*,536// open the directory and check if the file for the given vmid exists.537// The file with the expected name and the latest creation date is used538// to determine the user name for the process id.539//540struct dirent* dentry;541errno = 0;542while ((dentry = os::readdir(tmpdirp)) != NULL) {543544// check if the directory entry is a hsperfdata file545if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {546continue;547}548549char* usrdir_name = NEW_C_HEAP_ARRAY(char,550strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);551strcpy(usrdir_name, tmpdirname);552strcat(usrdir_name, "/");553strcat(usrdir_name, dentry->d_name);554555// open the user directory556DIR* subdirp = open_directory_secure(usrdir_name);557558if (subdirp == NULL) {559FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);560continue;561}562563// Since we don't create the backing store files in directories564// pointed to by symbolic links, we also don't follow them when565// looking for the files. We check for a symbolic link after the566// call to opendir in order to eliminate a small window where the567// symlink can be exploited.568//569if (!is_directory_secure(usrdir_name)) {570FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);571os::closedir(subdirp);572continue;573}574575struct dirent* udentry;576errno = 0;577while ((udentry = os::readdir(subdirp)) != NULL) {578579if (filename_to_pid(udentry->d_name) == vmid) {580struct stat statbuf;581int result;582583char* filename = NEW_C_HEAP_ARRAY(char,584strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);585586strcpy(filename, usrdir_name);587strcat(filename, "/");588strcat(filename, udentry->d_name);589590// don't follow symbolic links for the file591RESTARTABLE(::lstat(filename, &statbuf), result);592if (result == OS_ERR) {593FREE_C_HEAP_ARRAY(char, filename, mtInternal);594continue;595}596597// skip over files that are not regular files.598if (!S_ISREG(statbuf.st_mode)) {599FREE_C_HEAP_ARRAY(char, filename, mtInternal);600continue;601}602603// compare and save filename with latest creation time604if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {605606if (statbuf.st_ctime > oldest_ctime) {607char* user = strchr(dentry->d_name, '_') + 1;608609if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);610oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);611612strcpy(oldest_user, user);613oldest_ctime = statbuf.st_ctime;614}615}616617FREE_C_HEAP_ARRAY(char, filename, mtInternal);618}619}620os::closedir(subdirp);621FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);622}623os::closedir(tmpdirp);624625return(oldest_user);626}627628// return the name of the user that owns the JVM indicated by the given vmid.629//630static char* get_user_name(int vmid, TRAPS) {631return get_user_name_slow(vmid, THREAD);632}633634// return the file name of the backing store file for the named635// shared memory region for the given user name and vmid.636//637// the caller is expected to free the allocated memory.638//639static char* get_sharedmem_filename(const char* dirname, int vmid) {640641// add 2 for the file separator and a null terminator.642size_t nbytes = strlen(dirname) + UINT_CHARS + 2;643644char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);645snprintf(name, nbytes, "%s/%d", dirname, vmid);646647return name;648}649650651// remove file652//653// this method removes the file specified by the given path654//655static void remove_file(const char* path) {656657int result;658659// if the file is a directory, the following unlink will fail. since660// we don't expect to find directories in the user temp directory, we661// won't try to handle this situation. even if accidentially or662// maliciously planted, the directory's presence won't hurt anything.663//664RESTARTABLE(::unlink(path), result);665if (PrintMiscellaneous && Verbose && result == OS_ERR) {666if (errno != ENOENT) {667warning("Could not unlink shared memory backing"668" store file %s : %s\n", path, strerror(errno));669}670}671}672673674// cleanup stale shared memory resources675//676// This method attempts to remove all stale shared memory files in677// the named user temporary directory. It scans the named directory678// for files matching the pattern ^$[0-9]*$. For each file found, the679// process id is extracted from the file name and a test is run to680// determine if the process is alive. If the process is not alive,681// any stale file resources are removed.682//683static void cleanup_sharedmem_resources(const char* dirname) {684685int saved_cwd_fd;686// open the directory687DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);688if (dirp == NULL) {689// directory doesn't exist or is insecure, so there is nothing to cleanup690return;691}692693// for each entry in the directory that matches the expected file694// name pattern, determine if the file resources are stale and if695// so, remove the file resources. Note, instrumented HotSpot processes696// for this user may start and/or terminate during this search and697// remove or create new files in this directory. The behavior of this698// loop under these conditions is dependent upon the implementation of699// opendir/readdir.700//701struct dirent* entry;702errno = 0;703while ((entry = os::readdir(dirp)) != NULL) {704705pid_t pid = filename_to_pid(entry->d_name);706707if (pid == 0) {708709if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {710// attempt to remove all unexpected files, except "." and ".."711unlink(entry->d_name);712}713714errno = 0;715continue;716}717718// we now have a file name that converts to a valid integer719// that could represent a process id . if this process id720// matches the current process id or the process is not running,721// then remove the stale file resources.722//723// process liveness is detected by sending signal number 0 to724// the process id (see kill(2)). if kill determines that the725// process does not exist, then the file resources are removed.726// if kill determines that that we don't have permission to727// signal the process, then the file resources are assumed to728// be stale and are removed because the resources for such a729// process should be in a different user specific directory.730//731if ((pid == os::current_process_id()) ||732(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {733unlink(entry->d_name);734}735errno = 0;736}737738// close the directory and reset the current working directory739close_directory_secure_cwd(dirp, saved_cwd_fd);740}741742// make the user specific temporary directory. Returns true if743// the directory exists and is secure upon return. Returns false744// if the directory exists but is either a symlink, is otherwise745// insecure, or if an error occurred.746//747static bool make_user_tmp_dir(const char* dirname) {748749// create the directory with 0755 permissions. note that the directory750// will be owned by euid::egid, which may not be the same as uid::gid.751//752if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {753if (errno == EEXIST) {754// The directory already exists and was probably created by another755// JVM instance. However, this could also be the result of a756// deliberate symlink. Verify that the existing directory is safe.757//758if (!is_directory_secure(dirname)) {759// directory is not secure760if (PrintMiscellaneous && Verbose) {761warning("%s directory is insecure\n", dirname);762}763return false;764}765}766else {767// we encountered some other failure while attempting768// to create the directory769//770if (PrintMiscellaneous && Verbose) {771warning("could not create directory %s: %s\n",772dirname, strerror(errno));773}774return false;775}776}777return true;778}779780// create the shared memory file resources781//782// This method creates the shared memory file with the given size783// This method also creates the user specific temporary directory, if784// it does not yet exist.785//786static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {787788// make the user temporary directory789if (!make_user_tmp_dir(dirname)) {790// could not make/find the directory or the found directory791// was not secure792return -1;793}794795int saved_cwd_fd;796// open the directory and set the current working directory to it797DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);798if (dirp == NULL) {799// Directory doesn't exist or is insecure, so cannot create shared800// memory file.801return -1;802}803804// Open the filename in the current directory.805// Cannot use O_TRUNC here; truncation of an existing file has to happen806// after the is_file_secure() check below.807int result;808RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);809if (result == OS_ERR) {810if (PrintMiscellaneous && Verbose) {811if (errno == ELOOP) {812warning("file %s is a symlink and is not secure\n", filename);813} else {814warning("could not create file %s: %s\n", filename, strerror(errno));815}816}817// close the directory and reset the current working directory818close_directory_secure_cwd(dirp, saved_cwd_fd);819820return -1;821}822// close the directory and reset the current working directory823close_directory_secure_cwd(dirp, saved_cwd_fd);824825// save the file descriptor826int fd = result;827828// check to see if the file is secure829if (!is_file_secure(fd, filename)) {830::close(fd);831return -1;832}833834// truncate the file to get rid of any existing data835RESTARTABLE(::ftruncate(fd, (off_t)0), result);836if (result == OS_ERR) {837if (PrintMiscellaneous && Verbose) {838warning("could not truncate shared memory file: %s\n", strerror(errno));839}840::close(fd);841return -1;842}843// set the file size844RESTARTABLE(::ftruncate(fd, (off_t)size), result);845if (result == OS_ERR) {846if (PrintMiscellaneous && Verbose) {847warning("could not set shared memory file size: %s\n", strerror(errno));848}849::close(fd);850return -1;851}852853// Verify that we have enough disk space for this file.854// We'll get random SIGBUS crashes on memory accesses if855// we don't.856857for (size_t seekpos = 0; seekpos < size; seekpos += os::vm_page_size()) {858int zero_int = 0;859result = (int)os::seek_to_file_offset(fd, (jlong)(seekpos));860if (result == -1 ) break;861RESTARTABLE(::write(fd, &zero_int, 1), result);862if (result != 1) {863if (errno == ENOSPC) {864warning("Insufficient space for shared memory file:\n %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename);865}866break;867}868}869870if (result != -1) {871return fd;872} else {873::close(fd);874return -1;875}876}877878// open the shared memory file for the given user and vmid. returns879// the file descriptor for the open file or -1 if the file could not880// be opened.881//882static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {883884// open the file885int result;886RESTARTABLE(::open(filename, oflags), result);887if (result == OS_ERR) {888if (errno == ENOENT) {889THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),890"Process not found", OS_ERR);891}892else if (errno == EACCES) {893THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),894"Permission denied", OS_ERR);895}896else {897THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);898}899}900int fd = result;901902// check to see if the file is secure903if (!is_file_secure(fd, filename)) {904::close(fd);905return -1;906}907908return fd;909}910911// create a named shared memory region. returns the address of the912// memory region on success or NULL on failure. A return value of913// NULL will ultimately disable the shared memory feature.914//915// On Solaris and Linux, the name space for shared memory objects916// is the file system name space.917//918// A monitoring application attaching to a JVM does not need to know919// the file system name of the shared memory object. However, it may920// be convenient for applications to discover the existence of newly921// created and terminating JVMs by watching the file system name space922// for files being created or removed.923//924static char* mmap_create_shared(size_t size) {925926int result;927int fd;928char* mapAddress;929930int vmid = os::current_process_id();931932char* user_name = get_user_name(geteuid());933934if (user_name == NULL)935return NULL;936937char* dirname = get_user_tmp_dir(user_name);938char* filename = get_sharedmem_filename(dirname, vmid);939// get the short filename940char* short_filename = strrchr(filename, '/');941if (short_filename == NULL) {942short_filename = filename;943} else {944short_filename++;945}946947// cleanup any stale shared memory files948cleanup_sharedmem_resources(dirname);949950assert(((size > 0) && (size % os::vm_page_size() == 0)),951"unexpected PerfMemory region size");952953fd = create_sharedmem_resources(dirname, short_filename, size);954955FREE_C_HEAP_ARRAY(char, user_name, mtInternal);956FREE_C_HEAP_ARRAY(char, dirname, mtInternal);957958if (fd == -1) {959FREE_C_HEAP_ARRAY(char, filename, mtInternal);960return NULL;961}962963mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);964965result = ::close(fd);966assert(result != OS_ERR, "could not close file");967968if (mapAddress == MAP_FAILED) {969if (PrintMiscellaneous && Verbose) {970warning("mmap failed - %s\n", strerror(errno));971}972remove_file(filename);973FREE_C_HEAP_ARRAY(char, filename, mtInternal);974return NULL;975}976977// save the file name for use in delete_shared_memory()978backing_store_file_name = filename;979980// clear the shared memory region981(void)::memset((void*) mapAddress, 0, size);982983// it does not go through os api, the operation has to record from here984MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);985986return mapAddress;987}988989// release a named shared memory region990//991static void unmap_shared(char* addr, size_t bytes) {992os::release_memory(addr, bytes);993}994995// create the PerfData memory region in shared memory.996//997static char* create_shared_memory(size_t size) {998999// create the shared memory region.1000return mmap_create_shared(size);1001}10021003// delete the shared PerfData memory region1004//1005static void delete_shared_memory(char* addr, size_t size) {10061007// cleanup the persistent shared memory resources. since DestroyJavaVM does1008// not support unloading of the JVM, unmapping of the memory resource is1009// not performed. The memory will be reclaimed by the OS upon termination of1010// the process. The backing store file is deleted from the file system.10111012assert(!PerfDisableSharedMem, "shouldn't be here");10131014if (backing_store_file_name != NULL) {1015remove_file(backing_store_file_name);1016// Don't.. Free heap memory could deadlock os::abort() if it is called1017// from signal handler. OS will reclaim the heap memory.1018// FREE_C_HEAP_ARRAY(char, backing_store_file_name);1019backing_store_file_name = NULL;1020}1021}10221023// return the size of the file for the given file descriptor1024// or 0 if it is not a valid size for a shared memory file1025//1026static size_t sharedmem_filesize(int fd, TRAPS) {10271028struct stat statbuf;1029int result;10301031RESTARTABLE(::fstat(fd, &statbuf), result);1032if (result == OS_ERR) {1033if (PrintMiscellaneous && Verbose) {1034warning("fstat failed: %s\n", strerror(errno));1035}1036THROW_MSG_0(vmSymbols::java_io_IOException(),1037"Could not determine PerfMemory size");1038}10391040if ((statbuf.st_size == 0) ||1041((size_t)statbuf.st_size % os::vm_page_size() != 0)) {1042THROW_MSG_0(vmSymbols::java_lang_Exception(),1043"Invalid PerfMemory size");1044}10451046return (size_t)statbuf.st_size;1047}10481049// attach to a named shared memory region.1050//1051static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {10521053char* mapAddress;1054int result;1055int fd;1056size_t size = 0;1057const char* luser = NULL;10581059int mmap_prot;1060int file_flags;10611062ResourceMark rm;10631064// map the high level access mode to the appropriate permission1065// constructs for the file and the shared memory mapping.1066if (mode == PerfMemory::PERF_MODE_RO) {1067mmap_prot = PROT_READ;1068file_flags = O_RDONLY | O_NOFOLLOW;1069}1070else if (mode == PerfMemory::PERF_MODE_RW) {1071#ifdef LATER1072mmap_prot = PROT_READ | PROT_WRITE;1073file_flags = O_RDWR | O_NOFOLLOW;1074#else1075THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1076"Unsupported access mode");1077#endif1078}1079else {1080THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1081"Illegal access mode");1082}10831084if (user == NULL || strlen(user) == 0) {1085luser = get_user_name(vmid, CHECK);1086}1087else {1088luser = user;1089}10901091if (luser == NULL) {1092THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1093"Could not map vmid to user Name");1094}10951096char* dirname = get_user_tmp_dir(luser);10971098// since we don't follow symbolic links when creating the backing1099// store file, we don't follow them when attaching either.1100//1101if (!is_directory_secure(dirname)) {1102FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1103THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1104"Process not found");1105}11061107char* filename = get_sharedmem_filename(dirname, vmid);11081109// copy heap memory to resource memory. the open_sharedmem_file1110// method below need to use the filename, but could throw an1111// exception. using a resource array prevents the leak that1112// would otherwise occur.1113char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1114strcpy(rfilename, filename);11151116// free the c heap resources that are no longer needed1117if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);1118FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1119FREE_C_HEAP_ARRAY(char, filename, mtInternal);11201121// open the shared memory file for the give vmid1122fd = open_sharedmem_file(rfilename, file_flags, THREAD);11231124if (fd == OS_ERR) {1125return;1126}11271128if (HAS_PENDING_EXCEPTION) {1129::close(fd);1130return;1131}11321133if (*sizep == 0) {1134size = sharedmem_filesize(fd, CHECK);1135} else {1136size = *sizep;1137}11381139assert(size > 0, "unexpected size <= 0");11401141mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);11421143result = ::close(fd);1144assert(result != OS_ERR, "could not close file");11451146if (mapAddress == MAP_FAILED) {1147if (PrintMiscellaneous && Verbose) {1148warning("mmap failed: %s\n", strerror(errno));1149}1150THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1151"Could not map PerfMemory");1152}11531154// it does not go through os api, the operation has to record from here1155MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);11561157*addr = mapAddress;1158*sizep = size;11591160if (PerfTraceMemOps) {1161tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "1162INTPTR_FORMAT "\n", size, vmid, p2i((void*)mapAddress));1163}1164}11651166116711681169// create the PerfData memory region1170//1171// This method creates the memory region used to store performance1172// data for the JVM. The memory may be created in standard or1173// shared memory.1174//1175void PerfMemory::create_memory_region(size_t size) {11761177if (PerfDisableSharedMem) {1178// do not share the memory for the performance data.1179_start = create_standard_memory(size);1180}1181else {1182_start = create_shared_memory(size);1183if (_start == NULL) {11841185// creation of the shared memory region failed, attempt1186// to create a contiguous, non-shared memory region instead.1187//1188if (PrintMiscellaneous && Verbose) {1189warning("Reverting to non-shared PerfMemory region.\n");1190}1191PerfDisableSharedMem = true;1192_start = create_standard_memory(size);1193}1194}11951196if (_start != NULL) _capacity = size;11971198}11991200// delete the PerfData memory region1201//1202// This method deletes the memory region used to store performance1203// data for the JVM. The memory region indicated by the <address, size>1204// tuple will be inaccessible after a call to this method.1205//1206void PerfMemory::delete_memory_region() {12071208assert((start() != NULL && capacity() > 0), "verify proper state");12091210// If user specifies PerfDataSaveFile, it will save the performance data1211// to the specified file name no matter whether PerfDataSaveToFile is specified1212// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1213// -XX:+PerfDataSaveToFile.1214if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1215save_memory_to_file(start(), capacity());1216}12171218if (PerfDisableSharedMem) {1219delete_standard_memory(start(), capacity());1220}1221else {1222delete_shared_memory(start(), capacity());1223}1224}12251226// attach to the PerfData memory region for another JVM1227//1228// This method returns an <address, size> tuple that points to1229// a memory buffer that is kept reasonably synchronized with1230// the PerfData memory region for the indicated JVM. This1231// buffer may be kept in synchronization via shared memory1232// or some other mechanism that keeps the buffer updated.1233//1234// If the JVM chooses not to support the attachability feature,1235// this method should throw an UnsupportedOperation exception.1236//1237// This implementation utilizes named shared memory to map1238// the indicated process's PerfData memory region into this JVMs1239// address space.1240//1241void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {12421243if (vmid == 0 || vmid == os::current_process_id()) {1244*addrp = start();1245*sizep = capacity();1246return;1247}12481249mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);1250}12511252// detach from the PerfData memory region of another JVM1253//1254// This method detaches the PerfData memory region of another1255// JVM, specified as an <address, size> tuple of a buffer1256// in this process's address space. This method may perform1257// arbitrary actions to accomplish the detachment. The memory1258// region specified by <address, size> will be inaccessible after1259// a call to this method.1260//1261// If the JVM chooses not to support the attachability feature,1262// this method should throw an UnsupportedOperation exception.1263//1264// This implementation utilizes named shared memory to detach1265// the indicated process's PerfData memory region from this1266// process's address space.1267//1268void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {12691270assert(addr != 0, "address sanity check");1271assert(bytes > 0, "capacity sanity check");12721273if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1274// prevent accidental detachment of this process's PerfMemory region1275return;1276}12771278unmap_shared(addr, bytes);1279}12801281char* PerfMemory::backing_store_filename() {1282return backing_store_file_name;1283}128412851286