Path: blob/master/src/hotspot/os/posix/perfMemory_posix.cpp
40930 views
/*1* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2012, 2021 SAP SE. All rights reserved.3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4*5* This code is free software; you can redistribute it and/or modify it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*23*/2425#include "precompiled.hpp"26#include "jvm_io.h"27#include "classfile/vmSymbols.hpp"28#include "logging/log.hpp"29#include "memory/allocation.inline.hpp"30#include "memory/resourceArea.hpp"31#include "oops/oop.inline.hpp"32#include "os_posix.inline.hpp"33#include "runtime/handles.inline.hpp"34#include "runtime/os.hpp"35#include "runtime/perfMemory.hpp"36#include "services/memTracker.hpp"37#include "utilities/exceptions.hpp"3839// put OS-includes here40# include <sys/types.h>41# include <sys/mman.h>42# include <errno.h>43# include <stdio.h>44# include <unistd.h>45# include <sys/stat.h>46# include <signal.h>47# include <pwd.h>4849static char* backing_store_file_name = NULL; // name of the backing store50// file, if successfully created.5152// Standard Memory Implementation Details5354// create the PerfData memory region in standard memory.55//56static char* create_standard_memory(size_t size) {5758// allocate an aligned chuck of memory59char* mapAddress = os::reserve_memory(size);6061if (mapAddress == NULL) {62return NULL;63}6465// commit memory66if (!os::commit_memory(mapAddress, size, !ExecMem)) {67if (PrintMiscellaneous && Verbose) {68warning("Could not commit PerfData memory\n");69}70os::release_memory(mapAddress, size);71return NULL;72}7374return mapAddress;75}7677// delete the PerfData memory region78//79static void delete_standard_memory(char* addr, size_t size) {8081// there are no persistent external resources to cleanup for standard82// memory. since DestroyJavaVM does not support unloading of the JVM,83// cleanup of the memory resource is not performed. The memory will be84// reclaimed by the OS upon termination of the process.85//86return;87}8889// save the specified memory region to the given file90//91// Note: this function might be called from signal handler (by os::abort()),92// don't allocate heap memory.93//94static void save_memory_to_file(char* addr, size_t size) {9596const char* destfile = PerfMemory::get_perfdata_file_path();97assert(destfile[0] != '\0', "invalid PerfData file path");9899int result;100101RESTARTABLE(os::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR),102result);103if (result == OS_ERR) {104if (PrintMiscellaneous && Verbose) {105warning("Could not create Perfdata save file: %s: %s\n",106destfile, os::strerror(errno));107}108} else {109int fd = result;110111for (size_t remaining = size; remaining > 0;) {112113RESTARTABLE(::write(fd, addr, remaining), result);114if (result == OS_ERR) {115if (PrintMiscellaneous && Verbose) {116warning("Could not write Perfdata save file: %s: %s\n",117destfile, os::strerror(errno));118}119break;120}121122remaining -= (size_t)result;123addr += result;124}125126result = ::close(fd);127if (PrintMiscellaneous && Verbose) {128if (result == OS_ERR) {129warning("Could not close %s: %s\n", destfile, os::strerror(errno));130}131}132}133FREE_C_HEAP_ARRAY(char, destfile);134}135136137// Shared Memory Implementation Details138139// Note: the Posix shared memory implementation uses the mmap140// interface with a backing store file to implement named shared memory.141// Using the file system as the name space for shared memory allows a142// common name space to be supported across a variety of platforms. It143// also provides a name space that Java applications can deal with through144// simple file apis.145//146147// return the user specific temporary directory name.148// the caller is expected to free the allocated memory.149//150#define TMP_BUFFER_LEN (4+22)151static char* get_user_tmp_dir(const char* user, int vmid, int nspid) {152char* tmpdir = (char *)os::get_temp_directory();153#if defined(LINUX)154// On linux, if containerized process, get dirname of155// /proc/{vmid}/root/tmp/{PERFDATA_NAME_user}156// otherwise /tmp/{PERFDATA_NAME_user}157char buffer[TMP_BUFFER_LEN];158assert(strlen(tmpdir) == 4, "No longer using /tmp - update buffer size");159160if (nspid != -1) {161jio_snprintf(buffer, TMP_BUFFER_LEN, "/proc/%d/root%s", vmid, tmpdir);162tmpdir = buffer;163}164#endif165const char* perfdir = PERFDATA_NAME;166size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;167char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);168169// construct the path name to user specific tmp directory170snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);171172return dirname;173}174175// convert the given file name into a process id. if the file176// does not meet the file naming constraints, return 0.177//178static pid_t filename_to_pid(const char* filename) {179180// a filename that doesn't begin with a digit is not a181// candidate for conversion.182//183if (!isdigit(*filename)) {184return 0;185}186187// check if file name can be converted to an integer without188// any leftover characters.189//190char* remainder = NULL;191errno = 0;192pid_t pid = (pid_t)strtol(filename, &remainder, 10);193194if (errno != 0) {195return 0;196}197198// check for left over characters. If any, then the filename is199// not a candidate for conversion.200//201if (remainder != NULL && *remainder != '\0') {202return 0;203}204205// successful conversion, return the pid206return pid;207}208209210// Check if the given statbuf is considered a secure directory for211// the backing store files. Returns true if the directory is considered212// a secure location. Returns false if the statbuf is a symbolic link or213// if an error occurred.214//215static bool is_statbuf_secure(struct stat *statp) {216if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {217// The path represents a link or some non-directory file type,218// which is not what we expected. Declare it insecure.219//220return false;221}222// We have an existing directory, check if the permissions are safe.223//224if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {225// The directory is open for writing and could be subjected226// to a symlink or a hard link attack. Declare it insecure.227//228return false;229}230// If user is not root then see if the uid of the directory matches the effective uid of the process.231uid_t euid = geteuid();232if ((euid != 0) && (statp->st_uid != euid)) {233// The directory was not created by this user, declare it insecure.234//235return false;236}237return true;238}239240241// Check if the given path is considered a secure directory for242// the backing store files. Returns true if the directory exists243// and is considered a secure location. Returns false if the path244// is a symbolic link or if an error occurred.245//246static bool is_directory_secure(const char* path) {247struct stat statbuf;248int result = 0;249250RESTARTABLE(::lstat(path, &statbuf), result);251if (result == OS_ERR) {252return false;253}254255// The path exists, see if it is secure.256return is_statbuf_secure(&statbuf);257}258259260// Check if the given directory file descriptor is considered a secure261// directory for the backing store files. Returns true if the directory262// exists and is considered a secure location. Returns false if the path263// is a symbolic link or if an error occurred.264//265static bool is_dirfd_secure(int dir_fd) {266struct stat statbuf;267int result = 0;268269RESTARTABLE(::fstat(dir_fd, &statbuf), result);270if (result == OS_ERR) {271return false;272}273274// The path exists, now check its mode.275return is_statbuf_secure(&statbuf);276}277278279// Check to make sure fd1 and fd2 are referencing the same file system object.280//281static bool is_same_fsobject(int fd1, int fd2) {282struct stat statbuf1;283struct stat statbuf2;284int result = 0;285286RESTARTABLE(::fstat(fd1, &statbuf1), result);287if (result == OS_ERR) {288return false;289}290RESTARTABLE(::fstat(fd2, &statbuf2), result);291if (result == OS_ERR) {292return false;293}294295if ((statbuf1.st_ino == statbuf2.st_ino) &&296(statbuf1.st_dev == statbuf2.st_dev)) {297return true;298} else {299return false;300}301}302303304// Open the directory of the given path and validate it.305// Return a DIR * of the open directory.306//307static DIR *open_directory_secure(const char* dirname) {308// Open the directory using open() so that it can be verified309// to be secure by calling is_dirfd_secure(), opendir() and then check310// to see if they are the same file system object. This method does not311// introduce a window of opportunity for the directory to be attacked that312// calling opendir() and is_directory_secure() does.313int result;314DIR *dirp = NULL;315RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);316if (result == OS_ERR) {317// Directory doesn't exist or is a symlink, so there is nothing to cleanup.318if (PrintMiscellaneous && Verbose) {319if (errno == ELOOP) {320warning("directory %s is a symlink and is not secure\n", dirname);321} else {322warning("could not open directory %s: %s\n", dirname, os::strerror(errno));323}324}325return dirp;326}327int fd = result;328329// Determine if the open directory is secure.330if (!is_dirfd_secure(fd)) {331// The directory is not a secure directory.332os::close(fd);333return dirp;334}335336// Open the directory.337dirp = ::opendir(dirname);338if (dirp == NULL) {339// The directory doesn't exist, close fd and return.340os::close(fd);341return dirp;342}343344// Check to make sure fd and dirp are referencing the same file system object.345if (!is_same_fsobject(fd, AIX_ONLY(dirp->dd_fd) NOT_AIX(dirfd(dirp)))) {346// The directory is not secure.347os::close(fd);348os::closedir(dirp);349dirp = NULL;350return dirp;351}352353// Close initial open now that we know directory is secure354os::close(fd);355356return dirp;357}358359// NOTE: The code below uses fchdir(), open() and unlink() because360// fdopendir(), openat() and unlinkat() are not supported on all361// versions. Once the support for fdopendir(), openat() and unlinkat()362// is available on all supported versions the code can be changed363// to use these functions.364365// Open the directory of the given path, validate it and set the366// current working directory to it.367// Return a DIR * of the open directory and the saved cwd fd.368//369static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {370371// Open the directory.372DIR* dirp = open_directory_secure(dirname);373if (dirp == NULL) {374// Directory doesn't exist or is insecure, so there is nothing to cleanup.375return dirp;376}377int fd = AIX_ONLY(dirp->dd_fd) NOT_AIX(dirfd(dirp));378379// Open a fd to the cwd and save it off.380int result;381RESTARTABLE(::open(".", O_RDONLY), result);382if (result == OS_ERR) {383*saved_cwd_fd = -1;384} else {385*saved_cwd_fd = result;386}387388// Set the current directory to dirname by using the fd of the directory and389// handle errors, otherwise shared memory files will be created in cwd.390result = fchdir(fd);391if (result == OS_ERR) {392if (PrintMiscellaneous && Verbose) {393warning("could not change to directory %s", dirname);394}395if (*saved_cwd_fd != -1) {396::close(*saved_cwd_fd);397*saved_cwd_fd = -1;398}399// Close the directory.400os::closedir(dirp);401return NULL;402} else {403return dirp;404}405}406407// Close the directory and restore the current working directory.408//409static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {410411int result;412// If we have a saved cwd change back to it and close the fd.413if (saved_cwd_fd != -1) {414result = fchdir(saved_cwd_fd);415::close(saved_cwd_fd);416}417418// Close the directory.419os::closedir(dirp);420}421422// Check if the given file descriptor is considered a secure.423//424static bool is_file_secure(int fd, const char *filename) {425426int result;427struct stat statbuf;428429// Determine if the file is secure.430RESTARTABLE(::fstat(fd, &statbuf), result);431if (result == OS_ERR) {432if (PrintMiscellaneous && Verbose) {433warning("fstat failed on %s: %s\n", filename, os::strerror(errno));434}435return false;436}437if (statbuf.st_nlink > 1) {438// A file with multiple links is not expected.439if (PrintMiscellaneous && Verbose) {440warning("file %s has multiple links\n", filename);441}442return false;443}444return true;445}446447448// return the user name for the given user id449//450// the caller is expected to free the allocated memory.451//452static char* get_user_name(uid_t uid) {453454struct passwd pwent;455456// Determine the max pwbuf size from sysconf, and hardcode457// a default if this not available through sysconf.458long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);459if (bufsize == -1)460bufsize = 1024;461462char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);463464struct passwd* p = NULL;465int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);466467if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {468if (PrintMiscellaneous && Verbose) {469if (result != 0) {470warning("Could not retrieve passwd entry: %s\n",471os::strerror(result));472}473else if (p == NULL) {474// this check is added to protect against an observed problem475// with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,476// indicating success, but has p == NULL. This was observed when477// inserting a file descriptor exhaustion fault prior to the call478// getpwuid_r() call. In this case, error is set to the appropriate479// error condition, but this is undocumented behavior. This check480// is safe under any condition, but the use of errno in the output481// message may result in an erroneous message.482// Bug Id 89052 was opened with RedHat.483//484warning("Could not retrieve passwd entry: %s\n",485os::strerror(errno));486}487else {488warning("Could not determine user name: %s\n",489p->pw_name == NULL ? "pw_name = NULL" :490"pw_name zero length");491}492}493FREE_C_HEAP_ARRAY(char, pwbuf);494return NULL;495}496497char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);498strcpy(user_name, p->pw_name);499500FREE_C_HEAP_ARRAY(char, pwbuf);501return user_name;502}503504// return the name of the user that owns the process identified by vmid.505//506// This method uses a slow directory search algorithm to find the backing507// store file for the specified vmid and returns the user name, as determined508// by the user name suffix of the hsperfdata_<username> directory name.509//510// the caller is expected to free the allocated memory.511//512//513static char* get_user_name_slow(int vmid, int nspid, TRAPS) {514515// short circuit the directory search if the process doesn't even exist.516if (kill(vmid, 0) == OS_ERR) {517if (errno == ESRCH) {518THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),519"Process not found");520}521else /* EPERM */ {522THROW_MSG_0(vmSymbols::java_io_IOException(), os::strerror(errno));523}524}525526// directory search527char* oldest_user = NULL;528time_t oldest_ctime = 0;529int searchpid;530char* tmpdirname = (char *)os::get_temp_directory();531#if defined(LINUX)532char buffer[MAXPATHLEN + 1];533assert(strlen(tmpdirname) == 4, "No longer using /tmp - update buffer size");534535// On Linux, if nspid != -1, look in /proc/{vmid}/root/tmp for directories536// containing nspid, otherwise just look for vmid in /tmp.537if (nspid == -1) {538searchpid = vmid;539} else {540jio_snprintf(buffer, MAXPATHLEN, "/proc/%d/root%s", vmid, tmpdirname);541tmpdirname = buffer;542searchpid = nspid;543}544#else545searchpid = vmid;546#endif547548// open the temp directory549DIR* tmpdirp = os::opendir(tmpdirname);550551if (tmpdirp == NULL) {552// Cannot open the directory to get the user name, return.553return NULL;554}555556// for each entry in the directory that matches the pattern hsperfdata_*,557// open the directory and check if the file for the given vmid (or nspid) exists.558// The file with the expected name and the latest creation date is used559// to determine the user name for the process id.560//561struct dirent* dentry;562errno = 0;563while ((dentry = os::readdir(tmpdirp)) != NULL) {564565// check if the directory entry is a hsperfdata file566if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {567continue;568}569570char* usrdir_name = NEW_C_HEAP_ARRAY(char,571strlen(tmpdirname) + strlen(dentry->d_name) + 2,572mtInternal);573strcpy(usrdir_name, tmpdirname);574strcat(usrdir_name, "/");575strcat(usrdir_name, dentry->d_name);576577// open the user directory578DIR* subdirp = open_directory_secure(usrdir_name);579580if (subdirp == NULL) {581FREE_C_HEAP_ARRAY(char, usrdir_name);582continue;583}584585// Since we don't create the backing store files in directories586// pointed to by symbolic links, we also don't follow them when587// looking for the files. We check for a symbolic link after the588// call to opendir in order to eliminate a small window where the589// symlink can be exploited.590//591if (!is_directory_secure(usrdir_name)) {592FREE_C_HEAP_ARRAY(char, usrdir_name);593os::closedir(subdirp);594continue;595}596597struct dirent* udentry;598errno = 0;599while ((udentry = os::readdir(subdirp)) != NULL) {600601if (filename_to_pid(udentry->d_name) == searchpid) {602struct stat statbuf;603int result;604605char* filename = NEW_C_HEAP_ARRAY(char,606strlen(usrdir_name) + strlen(udentry->d_name) + 2,607mtInternal);608609strcpy(filename, usrdir_name);610strcat(filename, "/");611strcat(filename, udentry->d_name);612613// don't follow symbolic links for the file614RESTARTABLE(::lstat(filename, &statbuf), result);615if (result == OS_ERR) {616FREE_C_HEAP_ARRAY(char, filename);617continue;618}619620// skip over files that are not regular files.621if (!S_ISREG(statbuf.st_mode)) {622FREE_C_HEAP_ARRAY(char, filename);623continue;624}625626// compare and save filename with latest creation time627if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {628629if (statbuf.st_ctime > oldest_ctime) {630char* user = strchr(dentry->d_name, '_') + 1;631632FREE_C_HEAP_ARRAY(char, oldest_user);633oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);634635strcpy(oldest_user, user);636oldest_ctime = statbuf.st_ctime;637}638}639640FREE_C_HEAP_ARRAY(char, filename);641}642}643os::closedir(subdirp);644FREE_C_HEAP_ARRAY(char, usrdir_name);645}646os::closedir(tmpdirp);647648return(oldest_user);649}650651// return the name of the user that owns the JVM indicated by the given vmid.652//653static char* get_user_name(int vmid, int *nspid, TRAPS) {654char *result = get_user_name_slow(vmid, *nspid, THREAD);655656#if defined(LINUX)657// If we are examining a container process without PID namespaces enabled658// we need to use /proc/{pid}/root/tmp to find hsperfdata files.659if (result == NULL) {660result = get_user_name_slow(vmid, vmid, THREAD);661// Enable nspid logic going forward662if (result != NULL) *nspid = vmid;663}664#endif665return result;666}667668// return the file name of the backing store file for the named669// shared memory region for the given user name and vmid.670//671// the caller is expected to free the allocated memory.672//673static char* get_sharedmem_filename(const char* dirname, int vmid, int nspid) {674675int pid = LINUX_ONLY((nspid == -1) ? vmid : nspid) NOT_LINUX(vmid);676677// add 2 for the file separator and a null terminator.678size_t nbytes = strlen(dirname) + UINT_CHARS + 2;679680char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);681snprintf(name, nbytes, "%s/%d", dirname, pid);682683return name;684}685686687// remove file688//689// this method removes the file specified by the given path690//691static void remove_file(const char* path) {692693int result;694695// if the file is a directory, the following unlink will fail. since696// we don't expect to find directories in the user temp directory, we697// won't try to handle this situation. even if accidentially or698// maliciously planted, the directory's presence won't hurt anything.699//700RESTARTABLE(::unlink(path), result);701if (PrintMiscellaneous && Verbose && result == OS_ERR) {702if (errno != ENOENT) {703warning("Could not unlink shared memory backing"704" store file %s : %s\n", path, os::strerror(errno));705}706}707}708709710// cleanup stale shared memory resources711//712// This method attempts to remove all stale shared memory files in713// the named user temporary directory. It scans the named directory714// for files matching the pattern ^$[0-9]*$. For each file found, the715// process id is extracted from the file name and a test is run to716// determine if the process is alive. If the process is not alive,717// any stale file resources are removed.718//719static void cleanup_sharedmem_resources(const char* dirname) {720721int saved_cwd_fd;722// open the directory and set the current working directory to it723DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);724if (dirp == NULL) {725// directory doesn't exist or is insecure, so there is nothing to cleanup726return;727}728729// for each entry in the directory that matches the expected file730// name pattern, determine if the file resources are stale and if731// so, remove the file resources. Note, instrumented HotSpot processes732// for this user may start and/or terminate during this search and733// remove or create new files in this directory. The behavior of this734// loop under these conditions is dependent upon the implementation of735// opendir/readdir.736//737struct dirent* entry;738errno = 0;739while ((entry = os::readdir(dirp)) != NULL) {740741pid_t pid = filename_to_pid(entry->d_name);742743if (pid == 0) {744745if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {746// attempt to remove all unexpected files, except "." and ".."747unlink(entry->d_name);748}749750errno = 0;751continue;752}753754// we now have a file name that converts to a valid integer755// that could represent a process id . if this process id756// matches the current process id or the process is not running,757// then remove the stale file resources.758//759// process liveness is detected by sending signal number 0 to760// the process id (see kill(2)). if kill determines that the761// process does not exist, then the file resources are removed.762// if kill determines that that we don't have permission to763// signal the process, then the file resources are assumed to764// be stale and are removed because the resources for such a765// process should be in a different user specific directory.766//767if ((pid == os::current_process_id()) ||768(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {769unlink(entry->d_name);770}771errno = 0;772}773774// close the directory and reset the current working directory775close_directory_secure_cwd(dirp, saved_cwd_fd);776}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, os::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(os::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR), 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, os::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", os::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", os::strerror(errno));884}885::close(fd);886return -1;887}888889// Verify that we have enough disk space for this file.890// We'll get random SIGBUS crashes on memory accesses if891// we don't.892for (size_t seekpos = 0; seekpos < size; seekpos += os::vm_page_size()) {893int zero_int = 0;894result = (int)os::seek_to_file_offset(fd, (jlong)(seekpos));895if (result == -1 ) break;896RESTARTABLE(::write(fd, &zero_int, 1), result);897if (result != 1) {898if (errno == ENOSPC) {899warning("Insufficient space for shared memory file:\n %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename);900}901break;902}903}904905if (result != -1) {906return fd;907} else {908::close(fd);909return -1;910}911}912913// open the shared memory file for the given user and vmid. returns914// the file descriptor for the open file or -1 if the file could not915// be opened.916//917static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {918919// open the file920int result;921RESTARTABLE(os::open(filename, oflags, 0), result);922if (result == OS_ERR) {923if (errno == ENOENT) {924THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),925"Process not found", OS_ERR);926}927else if (errno == EACCES) {928THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),929"Permission denied", OS_ERR);930}931else {932THROW_MSG_(vmSymbols::java_io_IOException(),933os::strerror(errno), OS_ERR);934}935}936int fd = result;937938// check to see if the file is secure939if (!is_file_secure(fd, filename)) {940::close(fd);941return -1;942}943944return fd;945}946947// create a named shared memory region. returns the address of the948// memory region on success or NULL on failure. A return value of949// NULL will ultimately disable the shared memory feature.950//951// The name space for shared memory objects is the file system name space.952//953// A monitoring application attaching to a JVM does not need to know954// the file system name of the shared memory object. However, it may955// be convenient for applications to discover the existence of newly956// created and terminating JVMs by watching the file system name space957// for files being created or removed.958//959static char* mmap_create_shared(size_t size) {960961int result;962int fd;963char* mapAddress;964965int vmid = os::current_process_id();966967char* user_name = get_user_name(geteuid());968969if (user_name == NULL)970return NULL;971972char* dirname = get_user_tmp_dir(user_name, vmid, -1);973char* filename = get_sharedmem_filename(dirname, vmid, -1);974975// get the short filename976char* short_filename = strrchr(filename, '/');977if (short_filename == NULL) {978short_filename = filename;979} else {980short_filename++;981}982983// cleanup any stale shared memory files984cleanup_sharedmem_resources(dirname);985986assert(((size > 0) && (size % os::vm_page_size() == 0)),987"unexpected PerfMemory region size");988989fd = create_sharedmem_resources(dirname, short_filename, size);990991FREE_C_HEAP_ARRAY(char, user_name);992FREE_C_HEAP_ARRAY(char, dirname);993994if (fd == -1) {995FREE_C_HEAP_ARRAY(char, filename);996return NULL;997}998999mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);10001001result = ::close(fd);1002assert(result != OS_ERR, "could not close file");10031004if (mapAddress == MAP_FAILED) {1005if (PrintMiscellaneous && Verbose) {1006warning("mmap failed - %s\n", os::strerror(errno));1007}1008remove_file(filename);1009FREE_C_HEAP_ARRAY(char, filename);1010return NULL;1011}10121013// save the file name for use in delete_shared_memory()1014backing_store_file_name = filename;10151016// clear the shared memory region1017(void)::memset((void*) mapAddress, 0, size);10181019// it does not go through os api, the operation has to record from here1020MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);10211022return mapAddress;1023}10241025// release a named shared memory region1026//1027static void unmap_shared(char* addr, size_t bytes) {1028#if defined(_AIX)1029// Do not rely on os::reserve_memory/os::release_memory to use mmap.1030// Use os::reserve_memory/os::release_memory for PerfDisableSharedMem=1, mmap/munmap for PerfDisableSharedMem=01031if (::munmap(addr, bytes) == -1) {1032warning("perfmemory: munmap failed (%d)\n", errno);1033}1034#else1035os::release_memory(addr, bytes);1036#endif1037}10381039// create the PerfData memory region in shared memory.1040//1041static char* create_shared_memory(size_t size) {10421043// create the shared memory region.1044return mmap_create_shared(size);1045}10461047// delete the shared PerfData memory region1048//1049static void delete_shared_memory(char* addr, size_t size) {10501051// cleanup the persistent shared memory resources. since DestroyJavaVM does1052// not support unloading of the JVM, unmapping of the memory resource is1053// not performed. The memory will be reclaimed by the OS upon termination of1054// the process. The backing store file is deleted from the file system.10551056assert(!PerfDisableSharedMem, "shouldn't be here");10571058if (backing_store_file_name != NULL) {1059remove_file(backing_store_file_name);1060// Don't.. Free heap memory could deadlock os::abort() if it is called1061// from signal handler. OS will reclaim the heap memory.1062// FREE_C_HEAP_ARRAY(char, backing_store_file_name);1063backing_store_file_name = NULL;1064}1065}10661067// return the size of the file for the given file descriptor1068// or 0 if it is not a valid size for a shared memory file1069//1070static size_t sharedmem_filesize(int fd, TRAPS) {10711072struct stat statbuf;1073int result;10741075RESTARTABLE(::fstat(fd, &statbuf), result);1076if (result == OS_ERR) {1077if (PrintMiscellaneous && Verbose) {1078warning("fstat failed: %s\n", os::strerror(errno));1079}1080THROW_MSG_0(vmSymbols::java_io_IOException(),1081"Could not determine PerfMemory size");1082}10831084if ((statbuf.st_size == 0) ||1085((size_t)statbuf.st_size % os::vm_page_size() != 0)) {1086THROW_MSG_0(vmSymbols::java_io_IOException(),1087"Invalid PerfMemory size");1088}10891090return (size_t)statbuf.st_size;1091}10921093// attach to a named shared memory region.1094//1095static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {10961097char* mapAddress;1098int result;1099int fd;1100size_t size = 0;1101const char* luser = NULL;11021103int mmap_prot;1104int file_flags;11051106ResourceMark rm;11071108// map the high level access mode to the appropriate permission1109// constructs for the file and the shared memory mapping.1110if (mode == PerfMemory::PERF_MODE_RO) {1111mmap_prot = PROT_READ;1112file_flags = O_RDONLY | O_NOFOLLOW;1113}1114else if (mode == PerfMemory::PERF_MODE_RW) {1115#ifdef LATER1116mmap_prot = PROT_READ | PROT_WRITE;1117file_flags = O_RDWR | O_NOFOLLOW;1118#else1119THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1120"Unsupported access mode");1121#endif1122}1123else {1124THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1125"Illegal access mode");1126}11271128// for linux, determine if vmid is for a containerized process1129int nspid = LINUX_ONLY(os::Linux::get_namespace_pid(vmid)) NOT_LINUX(-1);11301131if (user == NULL || strlen(user) == 0) {1132luser = get_user_name(vmid, &nspid, CHECK);1133}1134else {1135luser = user;1136}11371138if (luser == NULL) {1139THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1140"Could not map vmid to user Name");1141}11421143char* dirname = get_user_tmp_dir(luser, vmid, nspid);11441145// since we don't follow symbolic links when creating the backing1146// store file, we don't follow them when attaching either.1147//1148if (!is_directory_secure(dirname)) {1149FREE_C_HEAP_ARRAY(char, dirname);1150if (luser != user) {1151FREE_C_HEAP_ARRAY(char, luser);1152}1153THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1154"Process not found");1155}11561157char* filename = get_sharedmem_filename(dirname, vmid, nspid);11581159// copy heap memory to resource memory. the open_sharedmem_file1160// method below need to use the filename, but could throw an1161// exception. using a resource array prevents the leak that1162// would otherwise occur.1163char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1164strcpy(rfilename, filename);11651166// free the c heap resources that are no longer needed1167if (luser != user) FREE_C_HEAP_ARRAY(char, luser);1168FREE_C_HEAP_ARRAY(char, dirname);1169FREE_C_HEAP_ARRAY(char, filename);11701171// open the shared memory file for the give vmid1172fd = open_sharedmem_file(rfilename, file_flags, THREAD);11731174if (fd == OS_ERR) {1175return;1176}11771178if (HAS_PENDING_EXCEPTION) {1179::close(fd);1180return;1181}11821183if (*sizep == 0) {1184size = sharedmem_filesize(fd, CHECK);1185} else {1186size = *sizep;1187}11881189assert(size > 0, "unexpected size <= 0");11901191mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);11921193result = ::close(fd);1194assert(result != OS_ERR, "could not close file");11951196if (mapAddress == MAP_FAILED) {1197if (PrintMiscellaneous && Verbose) {1198warning("mmap failed: %s\n", os::strerror(errno));1199}1200THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1201"Could not map PerfMemory");1202}12031204// it does not go through os api, the operation has to record from here1205MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);12061207*addr = mapAddress;1208*sizep = size;12091210log_debug(perf, memops)("mapped " SIZE_FORMAT " bytes for vmid %d at "1211INTPTR_FORMAT, size, vmid, p2i((void*)mapAddress));1212}12131214// create the PerfData memory region1215//1216// This method creates the memory region used to store performance1217// data for the JVM. The memory may be created in standard or1218// shared memory.1219//1220void PerfMemory::create_memory_region(size_t size) {12211222if (PerfDisableSharedMem) {1223// do not share the memory for the performance data.1224_start = create_standard_memory(size);1225}1226else {1227_start = create_shared_memory(size);1228if (_start == NULL) {12291230// creation of the shared memory region failed, attempt1231// to create a contiguous, non-shared memory region instead.1232//1233if (PrintMiscellaneous && Verbose) {1234warning("Reverting to non-shared PerfMemory region.\n");1235}1236PerfDisableSharedMem = true;1237_start = create_standard_memory(size);1238}1239}12401241if (_start != NULL) _capacity = size;12421243}12441245// delete the PerfData memory region1246//1247// This method deletes the memory region used to store performance1248// data for the JVM. The memory region indicated by the <address, size>1249// tuple will be inaccessible after a call to this method.1250//1251void PerfMemory::delete_memory_region() {12521253assert((start() != NULL && capacity() > 0), "verify proper state");12541255// If user specifies PerfDataSaveFile, it will save the performance data1256// to the specified file name no matter whether PerfDataSaveToFile is specified1257// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1258// -XX:+PerfDataSaveToFile.1259if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1260save_memory_to_file(start(), capacity());1261}12621263if (PerfDisableSharedMem) {1264delete_standard_memory(start(), capacity());1265}1266else {1267delete_shared_memory(start(), capacity());1268}1269}12701271// attach to the PerfData memory region for another JVM1272//1273// This method returns an <address, size> tuple that points to1274// a memory buffer that is kept reasonably synchronized with1275// the PerfData memory region for the indicated JVM. This1276// buffer may be kept in synchronization via shared memory1277// or some other mechanism that keeps the buffer updated.1278//1279// If the JVM chooses not to support the attachability feature,1280// this method should throw an UnsupportedOperation exception.1281//1282// This implementation utilizes named shared memory to map1283// the indicated process's PerfData memory region into this JVMs1284// address space.1285//1286void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {12871288if (vmid == 0 || vmid == os::current_process_id()) {1289*addrp = start();1290*sizep = capacity();1291return;1292}12931294mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);1295}12961297// detach from the PerfData memory region of another JVM1298//1299// This method detaches the PerfData memory region of another1300// JVM, specified as an <address, size> tuple of a buffer1301// in this process's address space. This method may perform1302// arbitrary actions to accomplish the detachment. The memory1303// region specified by <address, size> will be inaccessible after1304// a call to this method.1305//1306// If the JVM chooses not to support the attachability feature,1307// this method should throw an UnsupportedOperation exception.1308//1309// This implementation utilizes named shared memory to detach1310// the indicated process's PerfData memory region from this1311// process's address space.1312//1313void PerfMemory::detach(char* addr, size_t bytes) {13141315assert(addr != 0, "address sanity check");1316assert(bytes > 0, "capacity sanity check");13171318if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1319// prevent accidental detachment of this process's PerfMemory region1320return;1321}13221323unmap_shared(addr, bytes);1324}132513261327