Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/solaris/vm/perfMemory_solaris.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_solaris.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>44# include <procfs.h>454647static char* backing_store_file_name = NULL; // name of the backing store48// file, if successfully created.4950// Standard Memory Implementation Details5152// create the PerfData memory region in standard memory.53//54static char* create_standard_memory(size_t size) {5556// allocate an aligned chuck of memory57char* mapAddress = os::reserve_memory(size);5859if (mapAddress == NULL) {60return NULL;61}6263// commit memory64if (!os::commit_memory(mapAddress, size, !ExecMem)) {65if (PrintMiscellaneous && Verbose) {66warning("Could not commit PerfData memory\n");67}68os::release_memory(mapAddress, size);69return NULL;70}7172return mapAddress;73}7475// delete the PerfData memory region76//77static void delete_standard_memory(char* addr, size_t size) {7879// there are no persistent external resources to cleanup for standard80// memory. since DestroyJavaVM does not support unloading of the JVM,81// cleanup of the memory resource is not performed. The memory will be82// reclaimed by the OS upon termination of the process.83//84return;85}8687// save the specified memory region to the given file88//89// Note: this function might be called from signal handler (by os::abort()),90// don't allocate heap memory.91//92static void save_memory_to_file(char* addr, size_t size) {9394const char* destfile = PerfMemory::get_perfdata_file_path();95assert(destfile[0] != '\0', "invalid PerfData file path");9697int result;9899RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),100result);;101if (result == OS_ERR) {102if (PrintMiscellaneous && Verbose) {103warning("Could not create Perfdata save file: %s: %s\n",104destfile, strerror(errno));105}106} else {107108int fd = result;109110for (size_t remaining = size; remaining > 0;) {111112RESTARTABLE(::write(fd, addr, remaining), result);113if (result == OS_ERR) {114if (PrintMiscellaneous && Verbose) {115warning("Could not write Perfdata save file: %s: %s\n",116destfile, strerror(errno));117}118break;119}120remaining -= (size_t)result;121addr += result;122}123124result = ::close(fd);125if (PrintMiscellaneous && Verbose) {126if (result == OS_ERR) {127warning("Could not close %s: %s\n", destfile, strerror(errno));128}129}130}131FREE_C_HEAP_ARRAY(char, destfile, mtInternal);132}133134135// Shared Memory Implementation Details136137// Note: the solaris and linux shared memory implementation uses the mmap138// interface with a backing store file to implement named shared memory.139// Using the file system as the name space for shared memory allows a140// common name space to be supported across a variety of platforms. It141// also provides a name space that Java applications can deal with through142// simple file apis.143//144// The solaris and linux implementations store the backing store file in145// a user specific temporary directory located in the /tmp file system,146// which is always a local file system and is sometimes a RAM based file147// system.148149// return the user specific temporary directory name.150//151// the caller is expected to free the allocated memory.152//153static char* get_user_tmp_dir(const char* user) {154155const char* tmpdir = os::get_temp_directory();156const char* perfdir = PERFDATA_NAME;157size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;158char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);159160// construct the path name to user specific tmp directory161snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);162163return dirname;164}165166// convert the given file name into a process id. if the file167// does not meet the file naming constraints, return 0.168//169static pid_t filename_to_pid(const char* filename) {170171// a filename that doesn't begin with a digit is not a172// candidate for conversion.173//174if (!isdigit(*filename)) {175return 0;176}177178// check if file name can be converted to an integer without179// any leftover characters.180//181char* remainder = NULL;182errno = 0;183pid_t pid = (pid_t)strtol(filename, &remainder, 10);184185if (errno != 0) {186return 0;187}188189// check for left over characters. If any, then the filename is190// not a candidate for conversion.191//192if (remainder != NULL && *remainder != '\0') {193return 0;194}195196// successful conversion, return the pid197return pid;198}199200201// Check if the given statbuf is considered a secure directory for202// the backing store files. Returns true if the directory is considered203// a secure location. Returns false if the statbuf is a symbolic link or204// if an error occurred.205//206static bool is_statbuf_secure(struct stat *statp) {207if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {208// The path represents a link or some non-directory file type,209// which is not what we expected. Declare it insecure.210//211return false;212}213// We have an existing directory, check if the permissions are safe.214//215if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {216// The directory is open for writing and could be subjected217// to a symlink or a hard link attack. Declare it insecure.218//219return false;220}221// If user is not root then see if the uid of the directory matches the effective uid of the process.222uid_t euid = geteuid();223if ((euid != 0) && (statp->st_uid != euid)) {224// The directory was not created by this user, declare it insecure.225//226return false;227}228return true;229}230231232// Check if the given path is considered a secure directory for233// the backing store files. Returns true if the directory exists234// and is considered a secure location. Returns false if the path235// is a symbolic link or if an error occurred.236//237static bool is_directory_secure(const char* path) {238struct stat statbuf;239int result = 0;240241RESTARTABLE(::lstat(path, &statbuf), result);242if (result == OS_ERR) {243return false;244}245246// The path exists, see if it is secure.247return is_statbuf_secure(&statbuf);248}249250251// Check if the given directory file descriptor is considered a secure252// directory for the backing store files. Returns true if the directory253// exists and is considered a secure location. Returns false if the path254// is a symbolic link or if an error occurred.255//256static bool is_dirfd_secure(int dir_fd) {257struct stat statbuf;258int result = 0;259260RESTARTABLE(::fstat(dir_fd, &statbuf), result);261if (result == OS_ERR) {262return false;263}264265// The path exists, now check its mode.266return is_statbuf_secure(&statbuf);267}268269270// Check to make sure fd1 and fd2 are referencing the same file system object.271//272static bool is_same_fsobject(int fd1, int fd2) {273struct stat statbuf1;274struct stat statbuf2;275int result = 0;276277RESTARTABLE(::fstat(fd1, &statbuf1), result);278if (result == OS_ERR) {279return false;280}281RESTARTABLE(::fstat(fd2, &statbuf2), result);282if (result == OS_ERR) {283return false;284}285286if ((statbuf1.st_ino == statbuf2.st_ino) &&287(statbuf1.st_dev == statbuf2.st_dev)) {288return true;289} else {290return false;291}292}293294295// Open the directory of the given path and validate it.296// Return a DIR * of the open directory.297//298static DIR *open_directory_secure(const char* dirname) {299// Open the directory using open() so that it can be verified300// to be secure by calling is_dirfd_secure(), opendir() and then check301// to see if they are the same file system object. This method does not302// introduce a window of opportunity for the directory to be attacked that303// calling opendir() and is_directory_secure() does.304int result;305DIR *dirp = NULL;306RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);307if (result == OS_ERR) {308// Directory doesn't exist or is a symlink, so there is nothing to cleanup.309if (PrintMiscellaneous && Verbose) {310if (errno == ELOOP) {311warning("directory %s is a symlink and is not secure\n", dirname);312} else {313warning("could not open directory %s: %s\n", dirname, strerror(errno));314}315}316return dirp;317}318int fd = result;319320// Determine if the open directory is secure.321if (!is_dirfd_secure(fd)) {322// The directory is not a secure directory.323os::close(fd);324return dirp;325}326327// Open the directory.328dirp = ::opendir(dirname);329if (dirp == NULL) {330// The directory doesn't exist, close fd and return.331os::close(fd);332return dirp;333}334335// Check to make sure fd and dirp are referencing the same file system object.336if (!is_same_fsobject(fd, dirp->dd_fd)) {337// The directory is not secure.338os::close(fd);339os::closedir(dirp);340dirp = NULL;341return dirp;342}343344// Close initial open now that we know directory is secure345os::close(fd);346347return dirp;348}349350// NOTE: The code below uses fchdir(), open() and unlink() because351// fdopendir(), openat() and unlinkat() are not supported on all352// versions. Once the support for fdopendir(), openat() and unlinkat()353// is available on all supported versions the code can be changed354// to use these functions.355356// Open the directory of the given path, validate it and set the357// current working directory to it.358// Return a DIR * of the open directory and the saved cwd fd.359//360static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {361362// Open the directory.363DIR* dirp = open_directory_secure(dirname);364if (dirp == NULL) {365// Directory doesn't exist or is insecure, so there is nothing to cleanup.366return dirp;367}368int fd = dirp->dd_fd;369370// Open a fd to the cwd and save it off.371int result;372RESTARTABLE(::open(".", O_RDONLY), result);373if (result == OS_ERR) {374*saved_cwd_fd = -1;375} else {376*saved_cwd_fd = result;377}378379// Set the current directory to dirname by using the fd of the directory and380// handle errors, otherwise shared memory files will be created in cwd.381result = fchdir(fd);382if (result == OS_ERR) {383if (PrintMiscellaneous && Verbose) {384warning("could not change to directory %s", dirname);385}386if (*saved_cwd_fd != -1) {387::close(*saved_cwd_fd);388*saved_cwd_fd = -1;389}390// Close the directory.391os::closedir(dirp);392return NULL;393} else {394return dirp;395}396}397398// Close the directory and restore the current working directory.399//400static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {401402int result;403// If we have a saved cwd change back to it and close the fd.404if (saved_cwd_fd != -1) {405result = fchdir(saved_cwd_fd);406::close(saved_cwd_fd);407}408409// Close the directory.410os::closedir(dirp);411}412413// Check if the given file descriptor is considered a secure.414//415static bool is_file_secure(int fd, const char *filename) {416417int result;418struct stat statbuf;419420// Determine if the file is secure.421RESTARTABLE(::fstat(fd, &statbuf), result);422if (result == OS_ERR) {423if (PrintMiscellaneous && Verbose) {424warning("fstat failed on %s: %s\n", filename, strerror(errno));425}426return false;427}428if (statbuf.st_nlink > 1) {429// A file with multiple links is not expected.430if (PrintMiscellaneous && Verbose) {431warning("file %s has multiple links\n", filename);432}433return false;434}435return true;436}437438// return the user name for the given user id439//440// the caller is expected to free the allocated memory.441//442static char* get_user_name(uid_t uid) {443444struct passwd pwent;445446// determine the max pwbuf size from sysconf, and hardcode447// a default if this not available through sysconf.448//449long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);450if (bufsize == -1)451bufsize = 1024;452453char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);454455#ifdef _GNU_SOURCE456struct passwd* p = NULL;457int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);458#else // _GNU_SOURCE459struct passwd* p = getpwuid_r(uid, &pwent, pwbuf, (int)bufsize);460#endif // _GNU_SOURCE461462if (p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {463if (PrintMiscellaneous && Verbose) {464if (p == NULL) {465warning("Could not retrieve passwd entry: %s\n",466strerror(errno));467}468else {469warning("Could not determine user name: %s\n",470p->pw_name == NULL ? "pw_name = NULL" :471"pw_name zero length");472}473}474FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);475return NULL;476}477478char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);479strcpy(user_name, p->pw_name);480481FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);482return user_name;483}484485// return the name of the user that owns the process identified by vmid.486//487// This method uses a slow directory search algorithm to find the backing488// store file for the specified vmid and returns the user name, as determined489// by the user name suffix of the hsperfdata_<username> directory name.490//491// the caller is expected to free the allocated memory.492//493static char* get_user_name_slow(int vmid, TRAPS) {494495// short circuit the directory search if the process doesn't even exist.496if (kill(vmid, 0) == OS_ERR) {497if (errno == ESRCH) {498THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),499"Process not found");500}501else /* EPERM */ {502THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));503}504}505506// directory search507char* oldest_user = NULL;508time_t oldest_ctime = 0;509510const char* tmpdirname = os::get_temp_directory();511512// open the temp directory513DIR* tmpdirp = os::opendir(tmpdirname);514515if (tmpdirp == NULL) {516// Cannot open the directory to get the user name, return.517return NULL;518}519520// for each entry in the directory that matches the pattern hsperfdata_*,521// open the directory and check if the file for the given vmid exists.522// The file with the expected name and the latest creation date is used523// to determine the user name for the process id.524//525struct dirent* dentry;526errno = 0;527while ((dentry = os::readdir(tmpdirp)) != NULL) {528529// check if the directory entry is a hsperfdata file530if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {531continue;532}533534char* usrdir_name = NEW_C_HEAP_ARRAY(char,535strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);536strcpy(usrdir_name, tmpdirname);537strcat(usrdir_name, "/");538strcat(usrdir_name, dentry->d_name);539540// open the user directory541DIR* subdirp = open_directory_secure(usrdir_name);542543if (subdirp == NULL) {544FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);545continue;546}547548// Since we don't create the backing store files in directories549// pointed to by symbolic links, we also don't follow them when550// looking for the files. We check for a symbolic link after the551// call to opendir in order to eliminate a small window where the552// symlink can be exploited.553//554if (!is_directory_secure(usrdir_name)) {555FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);556os::closedir(subdirp);557continue;558}559560struct dirent* udentry;561errno = 0;562while ((udentry = os::readdir(subdirp)) != NULL) {563564if (filename_to_pid(udentry->d_name) == vmid) {565struct stat statbuf;566int result;567568char* filename = NEW_C_HEAP_ARRAY(char,569strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);570571strcpy(filename, usrdir_name);572strcat(filename, "/");573strcat(filename, udentry->d_name);574575// don't follow symbolic links for the file576RESTARTABLE(::lstat(filename, &statbuf), result);577if (result == OS_ERR) {578FREE_C_HEAP_ARRAY(char, filename, mtInternal);579continue;580}581582// skip over files that are not regular files.583if (!S_ISREG(statbuf.st_mode)) {584FREE_C_HEAP_ARRAY(char, filename, mtInternal);585continue;586}587588// compare and save filename with latest creation time589if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {590591if (statbuf.st_ctime > oldest_ctime) {592char* user = strchr(dentry->d_name, '_') + 1;593594if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);595oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);596597strcpy(oldest_user, user);598oldest_ctime = statbuf.st_ctime;599}600}601602FREE_C_HEAP_ARRAY(char, filename, mtInternal);603}604}605os::closedir(subdirp);606FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);607}608os::closedir(tmpdirp);609610return(oldest_user);611}612613// return the name of the user that owns the JVM indicated by the given vmid.614//615static char* get_user_name(int vmid, TRAPS) {616617char psinfo_name[PATH_MAX];618int result;619620snprintf(psinfo_name, PATH_MAX, "/proc/%d/psinfo", vmid);621622RESTARTABLE(::open(psinfo_name, O_RDONLY), result);623624if (result != OS_ERR) {625int fd = result;626627psinfo_t psinfo;628char* addr = (char*)&psinfo;629630for (size_t remaining = sizeof(psinfo_t); remaining > 0;) {631632RESTARTABLE(::read(fd, addr, remaining), result);633if (result == OS_ERR) {634::close(fd);635THROW_MSG_0(vmSymbols::java_io_IOException(), "Read error");636} else {637remaining-=result;638addr+=result;639}640}641642::close(fd);643644// get the user name for the effective user id of the process645char* user_name = get_user_name(psinfo.pr_euid);646647return user_name;648}649650if (result == OS_ERR && errno == EACCES) {651652// In this case, the psinfo file for the process id existed,653// but we didn't have permission to access it.654THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),655strerror(errno));656}657658// at this point, we don't know if the process id itself doesn't659// exist or if the psinfo file doesn't exit. If the psinfo file660// doesn't exist, then we are running on Solaris 2.5.1 or earlier.661// since the structured procfs and old procfs interfaces can't be662// mixed, we attempt to find the file through a directory search.663664return get_user_name_slow(vmid, THREAD);665}666667// return the file name of the backing store file for the named668// shared memory region for the given user name and vmid.669//670// the caller is expected to free the allocated memory.671//672static char* get_sharedmem_filename(const char* dirname, int vmid) {673674// add 2 for the file separator and a NULL terminator.675size_t nbytes = strlen(dirname) + UINT_CHARS + 2;676677char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);678snprintf(name, nbytes, "%s/%d", dirname, vmid);679680return name;681}682683684// remove file685//686// this method removes the file specified by the given path687//688static void remove_file(const char* path) {689690int result;691692// if the file is a directory, the following unlink will fail. since693// we don't expect to find directories in the user temp directory, we694// won't try to handle this situation. even if accidentially or695// maliciously planted, the directory's presence won't hurt anything.696//697RESTARTABLE(::unlink(path), result);698if (PrintMiscellaneous && Verbose && result == OS_ERR) {699if (errno != ENOENT) {700warning("Could not unlink shared memory backing"701" store file %s : %s\n", path, strerror(errno));702}703}704}705706707// cleanup stale shared memory resources708//709// This method attempts to remove all stale shared memory files in710// the named user temporary directory. It scans the named directory711// for files matching the pattern ^$[0-9]*$. For each file found, the712// process id is extracted from the file name and a test is run to713// determine if the process is alive. If the process is not alive,714// any stale file resources are removed.715//716static void cleanup_sharedmem_resources(const char* dirname) {717718int saved_cwd_fd;719// open the directory720DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);721if (dirp == NULL) {722// directory doesn't exist or is insecure, so there is nothing to cleanup723return;724}725726// for each entry in the directory that matches the expected file727// name pattern, determine if the file resources are stale and if728// so, remove the file resources. Note, instrumented HotSpot processes729// for this user may start and/or terminate during this search and730// remove or create new files in this directory. The behavior of this731// loop under these conditions is dependent upon the implementation of732// opendir/readdir.733//734struct dirent* entry;735errno = 0;736while ((entry = os::readdir(dirp)) != NULL) {737738pid_t pid = filename_to_pid(entry->d_name);739740if (pid == 0) {741742if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {743744// attempt to remove all unexpected files, except "." and ".."745unlink(entry->d_name);746}747748errno = 0;749continue;750}751752// we now have a file name that converts to a valid integer753// that could represent a process id . if this process id754// matches the current process id or the process is not running,755// then remove the stale file resources.756//757// process liveness is detected by sending signal number 0 to758// the process id (see kill(2)). if kill determines that the759// process does not exist, then the file resources are removed.760// if kill determines that that we don't have permission to761// signal the process, then the file resources are assumed to762// be stale and are removed because the resources for such a763// process should be in a different user specific directory.764//765if ((pid == os::current_process_id()) ||766(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {767768unlink(entry->d_name);769}770errno = 0;771}772773// close the directory and reset the current working directory774close_directory_secure_cwd(dirp, saved_cwd_fd);775776}777778// make the user specific temporary directory. Returns true if779// the directory exists and is secure upon return. Returns false780// if the directory exists but is either a symlink, is otherwise781// insecure, or if an error occurred.782//783static bool make_user_tmp_dir(const char* dirname) {784785// create the directory with 0755 permissions. note that the directory786// will be owned by euid::egid, which may not be the same as uid::gid.787//788if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {789if (errno == EEXIST) {790// The directory already exists and was probably created by another791// JVM instance. However, this could also be the result of a792// deliberate symlink. Verify that the existing directory is safe.793//794if (!is_directory_secure(dirname)) {795// directory is not secure796if (PrintMiscellaneous && Verbose) {797warning("%s directory is insecure\n", dirname);798}799return false;800}801}802else {803// we encountered some other failure while attempting804// to create the directory805//806if (PrintMiscellaneous && Verbose) {807warning("could not create directory %s: %s\n",808dirname, strerror(errno));809}810return false;811}812}813return true;814}815816// create the shared memory file resources817//818// This method creates the shared memory file with the given size819// This method also creates the user specific temporary directory, if820// it does not yet exist.821//822static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {823824// make the user temporary directory825if (!make_user_tmp_dir(dirname)) {826// could not make/find the directory or the found directory827// was not secure828return -1;829}830831int saved_cwd_fd;832// open the directory and set the current working directory to it833DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);834if (dirp == NULL) {835// Directory doesn't exist or is insecure, so cannot create shared836// memory file.837return -1;838}839840// Open the filename in the current directory.841// Cannot use O_TRUNC here; truncation of an existing file has to happen842// after the is_file_secure() check below.843int result;844RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);845if (result == OS_ERR) {846if (PrintMiscellaneous && Verbose) {847if (errno == ELOOP) {848warning("file %s is a symlink and is not secure\n", filename);849} else {850warning("could not create file %s: %s\n", filename, strerror(errno));851}852}853// close the directory and reset the current working directory854close_directory_secure_cwd(dirp, saved_cwd_fd);855856return -1;857}858// close the directory and reset the current working directory859close_directory_secure_cwd(dirp, saved_cwd_fd);860861// save the file descriptor862int fd = result;863864// check to see if the file is secure865if (!is_file_secure(fd, filename)) {866::close(fd);867return -1;868}869870// truncate the file to get rid of any existing data871RESTARTABLE(::ftruncate(fd, (off_t)0), result);872if (result == OS_ERR) {873if (PrintMiscellaneous && Verbose) {874warning("could not truncate shared memory file: %s\n", strerror(errno));875}876::close(fd);877return -1;878}879// set the file size880RESTARTABLE(::ftruncate(fd, (off_t)size), result);881if (result == OS_ERR) {882if (PrintMiscellaneous && Verbose) {883warning("could not set shared memory file size: %s\n", strerror(errno));884}885::close(fd);886return -1;887}888889return fd;890}891892// open the shared memory file for the given user and vmid. returns893// the file descriptor for the open file or -1 if the file could not894// be opened.895//896static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {897898// open the file899int result;900RESTARTABLE(::open(filename, oflags), result);901if (result == OS_ERR) {902if (errno == ENOENT) {903THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),904"Process not found", OS_ERR);905}906else if (errno == EACCES) {907THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),908"Permission denied", OS_ERR);909}910else {911THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);912}913}914int fd = result;915916// check to see if the file is secure917if (!is_file_secure(fd, filename)) {918::close(fd);919return -1;920}921922return fd;923}924925// create a named shared memory region. returns the address of the926// memory region on success or NULL on failure. A return value of927// NULL will ultimately disable the shared memory feature.928//929// On Solaris and Linux, the name space for shared memory objects930// is the file system name space.931//932// A monitoring application attaching to a JVM does not need to know933// the file system name of the shared memory object. However, it may934// be convenient for applications to discover the existence of newly935// created and terminating JVMs by watching the file system name space936// for files being created or removed.937//938static char* mmap_create_shared(size_t size) {939940int result;941int fd;942char* mapAddress;943944int vmid = os::current_process_id();945946char* user_name = get_user_name(geteuid());947948if (user_name == NULL)949return NULL;950951char* dirname = get_user_tmp_dir(user_name);952char* filename = get_sharedmem_filename(dirname, vmid);953954// get the short filename955char* short_filename = strrchr(filename, '/');956if (short_filename == NULL) {957short_filename = filename;958} else {959short_filename++;960}961962// cleanup any stale shared memory files963cleanup_sharedmem_resources(dirname);964965assert(((size > 0) && (size % os::vm_page_size() == 0)),966"unexpected PerfMemory region size");967968fd = create_sharedmem_resources(dirname, short_filename, size);969970FREE_C_HEAP_ARRAY(char, user_name, mtInternal);971FREE_C_HEAP_ARRAY(char, dirname, mtInternal);972973if (fd == -1) {974FREE_C_HEAP_ARRAY(char, filename, mtInternal);975return NULL;976}977978mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);979980result = ::close(fd);981assert(result != OS_ERR, "could not close file");982983if (mapAddress == MAP_FAILED) {984if (PrintMiscellaneous && Verbose) {985warning("mmap failed - %s\n", strerror(errno));986}987remove_file(filename);988FREE_C_HEAP_ARRAY(char, filename, mtInternal);989return NULL;990}991992// save the file name for use in delete_shared_memory()993backing_store_file_name = filename;994995// clear the shared memory region996(void)::memset((void*) mapAddress, 0, size);997998// it does not go through os api, the operation has to record from here999MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,1000size, CURRENT_PC, mtInternal);10011002return mapAddress;1003}10041005// release a named shared memory region1006//1007static void unmap_shared(char* addr, size_t bytes) {1008os::release_memory(addr, bytes);1009}10101011// create the PerfData memory region in shared memory.1012//1013static char* create_shared_memory(size_t size) {10141015// create the shared memory region.1016return mmap_create_shared(size);1017}10181019// delete the shared PerfData memory region1020//1021static void delete_shared_memory(char* addr, size_t size) {10221023// cleanup the persistent shared memory resources. since DestroyJavaVM does1024// not support unloading of the JVM, unmapping of the memory resource is1025// not performed. The memory will be reclaimed by the OS upon termination of1026// the process. The backing store file is deleted from the file system.10271028assert(!PerfDisableSharedMem, "shouldn't be here");10291030if (backing_store_file_name != NULL) {1031remove_file(backing_store_file_name);1032// Don't.. Free heap memory could deadlock os::abort() if it is called1033// from signal handler. OS will reclaim the heap memory.1034// FREE_C_HEAP_ARRAY(char, backing_store_file_name);1035backing_store_file_name = NULL;1036}1037}10381039// return the size of the file for the given file descriptor1040// or 0 if it is not a valid size for a shared memory file1041//1042static size_t sharedmem_filesize(int fd, TRAPS) {10431044struct stat statbuf;1045int result;10461047RESTARTABLE(::fstat(fd, &statbuf), result);1048if (result == OS_ERR) {1049if (PrintMiscellaneous && Verbose) {1050warning("fstat failed: %s\n", strerror(errno));1051}1052THROW_MSG_0(vmSymbols::java_io_IOException(),1053"Could not determine PerfMemory size");1054}10551056if ((statbuf.st_size == 0) ||1057((size_t)statbuf.st_size % os::vm_page_size() != 0)) {1058THROW_MSG_0(vmSymbols::java_lang_Exception(),1059"Invalid PerfMemory size");1060}10611062return (size_t)statbuf.st_size;1063}10641065// attach to a named shared memory region.1066//1067static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {10681069char* mapAddress;1070int result;1071int fd;1072size_t size = 0;1073const char* luser = NULL;10741075int mmap_prot;1076int file_flags;10771078ResourceMark rm;10791080// map the high level access mode to the appropriate permission1081// constructs for the file and the shared memory mapping.1082if (mode == PerfMemory::PERF_MODE_RO) {1083mmap_prot = PROT_READ;1084file_flags = O_RDONLY | O_NOFOLLOW;1085}1086else if (mode == PerfMemory::PERF_MODE_RW) {1087#ifdef LATER1088mmap_prot = PROT_READ | PROT_WRITE;1089file_flags = O_RDWR | O_NOFOLLOW;1090#else1091THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1092"Unsupported access mode");1093#endif1094}1095else {1096THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1097"Illegal access mode");1098}10991100if (user == NULL || strlen(user) == 0) {1101luser = get_user_name(vmid, CHECK);1102}1103else {1104luser = user;1105}11061107if (luser == NULL) {1108THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1109"Could not map vmid to user Name");1110}11111112char* dirname = get_user_tmp_dir(luser);11131114// since we don't follow symbolic links when creating the backing1115// store file, we don't follow them when attaching either.1116//1117if (!is_directory_secure(dirname)) {1118FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1119THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1120"Process not found");1121}11221123char* filename = get_sharedmem_filename(dirname, vmid);11241125// copy heap memory to resource memory. the open_sharedmem_file1126// method below need to use the filename, but could throw an1127// exception. using a resource array prevents the leak that1128// would otherwise occur.1129char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1130strcpy(rfilename, filename);11311132// free the c heap resources that are no longer needed1133if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);1134FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1135FREE_C_HEAP_ARRAY(char, filename, mtInternal);11361137// open the shared memory file for the give vmid1138fd = open_sharedmem_file(rfilename, file_flags, THREAD);11391140if (fd == OS_ERR) {1141return;1142}11431144if (HAS_PENDING_EXCEPTION) {1145::close(fd);1146return;1147}11481149if (*sizep == 0) {1150size = sharedmem_filesize(fd, CHECK);1151} else {1152size = *sizep;1153}11541155assert(size > 0, "unexpected size <= 0");11561157mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);11581159result = ::close(fd);1160assert(result != OS_ERR, "could not close file");11611162if (mapAddress == MAP_FAILED) {1163if (PrintMiscellaneous && Verbose) {1164warning("mmap failed: %s\n", strerror(errno));1165}1166THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1167"Could not map PerfMemory");1168}11691170// it does not go through os api, the operation has to record from here1171MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,1172size, CURRENT_PC, mtInternal);11731174*addr = mapAddress;1175*sizep = size;11761177if (PerfTraceMemOps) {1178tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "1179INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);1180}1181}11821183118411851186// create the PerfData memory region1187//1188// This method creates the memory region used to store performance1189// data for the JVM. The memory may be created in standard or1190// shared memory.1191//1192void PerfMemory::create_memory_region(size_t size) {11931194if (PerfDisableSharedMem) {1195// do not share the memory for the performance data.1196_start = create_standard_memory(size);1197}1198else {1199_start = create_shared_memory(size);1200if (_start == NULL) {12011202// creation of the shared memory region failed, attempt1203// to create a contiguous, non-shared memory region instead.1204//1205if (PrintMiscellaneous && Verbose) {1206warning("Reverting to non-shared PerfMemory region.\n");1207}1208PerfDisableSharedMem = true;1209_start = create_standard_memory(size);1210}1211}12121213if (_start != NULL) _capacity = size;12141215}12161217// delete the PerfData memory region1218//1219// This method deletes the memory region used to store performance1220// data for the JVM. The memory region indicated by the <address, size>1221// tuple will be inaccessible after a call to this method.1222//1223void PerfMemory::delete_memory_region() {12241225assert((start() != NULL && capacity() > 0), "verify proper state");12261227// If user specifies PerfDataSaveFile, it will save the performance data1228// to the specified file name no matter whether PerfDataSaveToFile is specified1229// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1230// -XX:+PerfDataSaveToFile.1231if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1232save_memory_to_file(start(), capacity());1233}12341235if (PerfDisableSharedMem) {1236delete_standard_memory(start(), capacity());1237}1238else {1239delete_shared_memory(start(), capacity());1240}1241}12421243// attach to the PerfData memory region for another JVM1244//1245// This method returns an <address, size> tuple that points to1246// a memory buffer that is kept reasonably synchronized with1247// the PerfData memory region for the indicated JVM. This1248// buffer may be kept in synchronization via shared memory1249// or some other mechanism that keeps the buffer updated.1250//1251// If the JVM chooses not to support the attachability feature,1252// this method should throw an UnsupportedOperation exception.1253//1254// This implementation utilizes named shared memory to map1255// the indicated process's PerfData memory region into this JVMs1256// address space.1257//1258void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {12591260if (vmid == 0 || vmid == os::current_process_id()) {1261*addrp = start();1262*sizep = capacity();1263return;1264}12651266mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);1267}12681269// detach from the PerfData memory region of another JVM1270//1271// This method detaches the PerfData memory region of another1272// JVM, specified as an <address, size> tuple of a buffer1273// in this process's address space. This method may perform1274// arbitrary actions to accomplish the detachment. The memory1275// region specified by <address, size> will be inaccessible after1276// a call to this method.1277//1278// If the JVM chooses not to support the attachability feature,1279// this method should throw an UnsupportedOperation exception.1280//1281// This implementation utilizes named shared memory to detach1282// the indicated process's PerfData memory region from this1283// process's address space.1284//1285void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {12861287assert(addr != 0, "address sanity check");1288assert(bytes > 0, "capacity sanity check");12891290if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1291// prevent accidental detachment of this process's PerfMemory region1292return;1293}12941295unmap_shared(addr, bytes);1296}12971298char* PerfMemory::backing_store_filename() {1299return backing_store_file_name;1300}130113021303