Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/aix/vm/perfMemory_aix.cpp
32284 views
/*1* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.2* Copyright 2012, 2013 SAP AG. 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 "classfile/vmSymbols.hpp"27#include "memory/allocation.inline.hpp"28#include "memory/resourceArea.hpp"29#include "oops/oop.inline.hpp"30#include "os_aix.inline.hpp"31#include "runtime/handles.inline.hpp"32#include "runtime/perfMemory.hpp"33#include "services/memTracker.hpp"34#include "utilities/exceptions.hpp"3536// put OS-includes here37# include <sys/types.h>38# include <sys/mman.h>39# include <errno.h>40# include <stdio.h>41# include <unistd.h>42# include <sys/stat.h>43# include <signal.h>44# include <pwd.h>4546static char* backing_store_file_name = NULL; // name of the backing store47// file, if successfully created.4849// Standard Memory Implementation Details5051// create the PerfData memory region in standard memory.52//53static char* create_standard_memory(size_t size) {5455// allocate an aligned chuck of memory56char* mapAddress = os::reserve_memory(size);5758if (mapAddress == NULL) {59return NULL;60}6162// commit memory63if (!os::commit_memory(mapAddress, size, !ExecMem)) {64if (PrintMiscellaneous && Verbose) {65warning("Could not commit PerfData memory\n");66}67os::release_memory(mapAddress, size);68return NULL;69}7071return mapAddress;72}7374// delete the PerfData memory region75//76static void delete_standard_memory(char* addr, size_t size) {7778// there are no persistent external resources to cleanup for standard79// memory. since DestroyJavaVM does not support unloading of the JVM,80// cleanup of the memory resource is not performed. The memory will be81// reclaimed by the OS upon termination of the process.82//83return;84}8586// save the specified memory region to the given file87//88// Note: this function might be called from signal handler (by os::abort()),89// don't allocate heap memory.90//91static void save_memory_to_file(char* addr, size_t size) {9293const char* destfile = PerfMemory::get_perfdata_file_path();94assert(destfile[0] != '\0', "invalid PerfData file path");9596int result;9798RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),99result);;100if (result == OS_ERR) {101if (PrintMiscellaneous && Verbose) {102warning("Could not create Perfdata save file: %s: %s\n",103destfile, strerror(errno));104}105} else {106int fd = result;107108for (size_t remaining = size; remaining > 0;) {109110RESTARTABLE(::write(fd, addr, remaining), result);111if (result == OS_ERR) {112if (PrintMiscellaneous && Verbose) {113warning("Could not write Perfdata save file: %s: %s\n",114destfile, strerror(errno));115}116break;117}118119remaining -= (size_t)result;120addr += result;121}122123RESTARTABLE(::close(fd), result);124if (PrintMiscellaneous && Verbose) {125if (result == OS_ERR) {126warning("Could not close %s: %s\n", destfile, strerror(errno));127}128}129}130FREE_C_HEAP_ARRAY(char, destfile, mtInternal);131}132133134// Shared Memory Implementation Details135136// Note: the solaris and linux shared memory implementation uses the mmap137// interface with a backing store file to implement named shared memory.138// Using the file system as the name space for shared memory allows a139// common name space to be supported across a variety of platforms. It140// also provides a name space that Java applications can deal with through141// simple file apis.142//143// The solaris and linux implementations store the backing store file in144// a user specific temporary directory located in the /tmp file system,145// which is always a local file system and is sometimes a RAM based file146// system.147148// return the user specific temporary directory name.149//150// the caller is expected to free the allocated memory.151//152static char* get_user_tmp_dir(const char* user) {153154const char* tmpdir = os::get_temp_directory();155const char* perfdir = PERFDATA_NAME;156size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;157char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);158159// construct the path name to user specific tmp directory160snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);161162return dirname;163}164165// convert the given file name into a process id. if the file166// does not meet the file naming constraints, return 0.167//168static pid_t filename_to_pid(const char* filename) {169170// a filename that doesn't begin with a digit is not a171// candidate for conversion.172//173if (!isdigit(*filename)) {174return 0;175}176177// check if file name can be converted to an integer without178// any leftover characters.179//180char* remainder = NULL;181errno = 0;182pid_t pid = (pid_t)strtol(filename, &remainder, 10);183184if (errno != 0) {185return 0;186}187188// check for left over characters. If any, then the filename is189// not a candidate for conversion.190//191if (remainder != NULL && *remainder != '\0') {192return 0;193}194195// successful conversion, return the pid196return pid;197}198199// Check if the given statbuf is considered a secure directory for200// the backing store files. Returns true if the directory is considered201// a secure location. Returns false if the statbuf is a symbolic link or202// if an error occurred.203//204static bool is_statbuf_secure(struct stat *statp) {205if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {206// The path represents a link or some non-directory file type,207// which is not what we expected. Declare it insecure.208//209return false;210}211// We have an existing directory, check if the permissions are safe.212//213if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {214// The directory is open for writing and could be subjected215// to a symlink or a hard link attack. Declare it insecure.216//217return false;218}219// If user is not root then see if the uid of the directory matches the effective uid of the process.220uid_t euid = geteuid();221if ((euid != 0) && (statp->st_uid != euid)) {222// The directory was not created by this user, declare it insecure.223//224return false;225}226return true;227}228229230// Check if the given path is considered a secure directory for231// the backing store files. Returns true if the directory exists232// and is considered a secure location. Returns false if the path233// is a symbolic link or if an error occurred.234//235static bool is_directory_secure(const char* path) {236struct stat statbuf;237int result = 0;238239RESTARTABLE(::lstat(path, &statbuf), result);240if (result == OS_ERR) {241return false;242}243244// The path exists, see if it is secure.245return is_statbuf_secure(&statbuf);246}247248// (Taken over from Solaris to support the O_NOFOLLOW case on AIX.)249// Check if the given directory file descriptor is considered a secure250// directory for the backing store files. Returns true if the directory251// exists and is considered a secure location. Returns false if the path252// is a symbolic link or if an error occurred.253static bool is_dirfd_secure(int dir_fd) {254struct stat statbuf;255int result = 0;256257RESTARTABLE(::fstat(dir_fd, &statbuf), result);258if (result == OS_ERR) {259return false;260}261262// The path exists, now check its mode.263return is_statbuf_secure(&statbuf);264}265266267// Check to make sure fd1 and fd2 are referencing the same file system object.268static bool is_same_fsobject(int fd1, int fd2) {269struct stat statbuf1;270struct stat statbuf2;271int result = 0;272273RESTARTABLE(::fstat(fd1, &statbuf1), result);274if (result == OS_ERR) {275return false;276}277RESTARTABLE(::fstat(fd2, &statbuf2), result);278if (result == OS_ERR) {279return false;280}281282if ((statbuf1.st_ino == statbuf2.st_ino) &&283(statbuf1.st_dev == statbuf2.st_dev)) {284return true;285} else {286return false;287}288}289290// Helper functions for open without O_NOFOLLOW which is not present on AIX 5.3/6.1.291// We use the jdk6 implementation here.292#ifndef O_NOFOLLOW293// The O_NOFOLLOW oflag doesn't exist before solaris 5.10, this is to simulate that behaviour294// was done in jdk 5/6 hotspot by Oracle this way295static int open_o_nofollow_impl(const char* path, int oflag, mode_t mode, bool use_mode) {296struct stat orig_st;297struct stat new_st;298bool create;299int error;300int fd;301302create = false;303304if (lstat(path, &orig_st) != 0) {305if (errno == ENOENT && (oflag & O_CREAT) != 0) {306// File doesn't exist, but_we want to create it, add O_EXCL flag307// to make sure no-one creates it (or a symlink) before us308// This works as we expect with symlinks, from posix man page:309// 'If O_EXCL and O_CREAT are set, and path names a symbolic310// link, open() shall fail and set errno to [EEXIST]'.311oflag |= O_EXCL;312create = true;313} else {314// File doesn't exist, and we are not creating it.315return OS_ERR;316}317} else {318// Lstat success, check if existing file is a link.319if ((orig_st.st_mode & S_IFMT) == S_IFLNK) {320// File is a symlink.321errno = ELOOP;322return OS_ERR;323}324}325326if (use_mode == true) {327fd = open(path, oflag, mode);328} else {329fd = open(path, oflag);330}331332if (fd == OS_ERR) {333return fd;334}335336// Can't do inode checks on before/after if we created the file.337if (create == false) {338if (fstat(fd, &new_st) != 0) {339// Keep errno from fstat, in case close also fails.340error = errno;341::close(fd);342errno = error;343return OS_ERR;344}345346if (orig_st.st_dev != new_st.st_dev || orig_st.st_ino != new_st.st_ino) {347// File was tampered with during race window.348::close(fd);349errno = EEXIST;350if (PrintMiscellaneous && Verbose) {351warning("possible file tampering attempt detected when opening %s", path);352}353return OS_ERR;354}355}356357return fd;358}359360static int open_o_nofollow(const char* path, int oflag, mode_t mode) {361return open_o_nofollow_impl(path, oflag, mode, true);362}363364static int open_o_nofollow(const char* path, int oflag) {365return open_o_nofollow_impl(path, oflag, 0, false);366}367#endif368369// Open the directory of the given path and validate it.370// Return a DIR * of the open directory.371static DIR *open_directory_secure(const char* dirname) {372// Open the directory using open() so that it can be verified373// to be secure by calling is_dirfd_secure(), opendir() and then check374// to see if they are the same file system object. This method does not375// introduce a window of opportunity for the directory to be attacked that376// calling opendir() and is_directory_secure() does.377int result;378DIR *dirp = NULL;379380// No O_NOFOLLOW defined at buildtime, and it is not documented for open;381// so provide a workaround in this case.382#ifdef O_NOFOLLOW383RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);384#else385// workaround (jdk6 coding)386RESTARTABLE(::open_o_nofollow(dirname, O_RDONLY), result);387#endif388389if (result == OS_ERR) {390// Directory doesn't exist or is a symlink, so there is nothing to cleanup.391if (PrintMiscellaneous && Verbose) {392if (errno == ELOOP) {393warning("directory %s is a symlink and is not secure\n", dirname);394} else {395warning("could not open directory %s: %s\n", dirname, strerror(errno));396}397}398return dirp;399}400int fd = result;401402// Determine if the open directory is secure.403if (!is_dirfd_secure(fd)) {404// The directory is not a secure directory.405os::close(fd);406return dirp;407}408409// Open the directory.410dirp = ::opendir(dirname);411if (dirp == NULL) {412// The directory doesn't exist, close fd and return.413os::close(fd);414return dirp;415}416417// Check to make sure fd and dirp are referencing the same file system object.418if (!is_same_fsobject(fd, dirp->dd_fd)) {419// The directory is not secure.420os::close(fd);421os::closedir(dirp);422dirp = NULL;423return dirp;424}425426// Close initial open now that we know directory is secure427os::close(fd);428429return dirp;430}431432// NOTE: The code below uses fchdir(), open() and unlink() because433// fdopendir(), openat() and unlinkat() are not supported on all434// versions. Once the support for fdopendir(), openat() and unlinkat()435// is available on all supported versions the code can be changed436// to use these functions.437438// Open the directory of the given path, validate it and set the439// current working directory to it.440// Return a DIR * of the open directory and the saved cwd fd.441//442static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {443444// Open the directory.445DIR* dirp = open_directory_secure(dirname);446if (dirp == NULL) {447// Directory doesn't exist or is insecure, so there is nothing to cleanup.448return dirp;449}450int fd = dirp->dd_fd;451452// Open a fd to the cwd and save it off.453int result;454RESTARTABLE(::open(".", O_RDONLY), result);455if (result == OS_ERR) {456*saved_cwd_fd = -1;457} else {458*saved_cwd_fd = result;459}460461// Set the current directory to dirname by using the fd of the directory and462// handle errors, otherwise shared memory files will be created in cwd.463result = fchdir(fd);464if (result == OS_ERR) {465if (PrintMiscellaneous && Verbose) {466warning("could not change to directory %s", dirname);467}468if (*saved_cwd_fd != -1) {469::close(*saved_cwd_fd);470*saved_cwd_fd = -1;471}472// Close the directory.473os::closedir(dirp);474return NULL;475} else {476return dirp;477}478}479480// Close the directory and restore the current working directory.481//482static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {483484int result;485// If we have a saved cwd change back to it and close the fd.486if (saved_cwd_fd != -1) {487result = fchdir(saved_cwd_fd);488::close(saved_cwd_fd);489}490491// Close the directory.492os::closedir(dirp);493}494495// Check if the given file descriptor is considered a secure.496static bool is_file_secure(int fd, const char *filename) {497498int result;499struct stat statbuf;500501// Determine if the file is secure.502RESTARTABLE(::fstat(fd, &statbuf), result);503if (result == OS_ERR) {504if (PrintMiscellaneous && Verbose) {505warning("fstat failed on %s: %s\n", filename, strerror(errno));506}507return false;508}509if (statbuf.st_nlink > 1) {510// A file with multiple links is not expected.511if (PrintMiscellaneous && Verbose) {512warning("file %s has multiple links\n", filename);513}514return false;515}516return true;517}518519// Return the user name for the given user id.520//521// The caller is expected to free the allocated memory.522static char* get_user_name(uid_t uid) {523524struct passwd pwent;525526// Determine the max pwbuf size from sysconf, and hardcode527// a default if this not available through sysconf.528long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);529if (bufsize == -1)530bufsize = 1024;531532char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);533534// POSIX interface to getpwuid_r is used on LINUX535struct passwd* p;536int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);537538if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {539if (PrintMiscellaneous && Verbose) {540if (result != 0) {541warning("Could not retrieve passwd entry: %s\n",542strerror(result));543}544else if (p == NULL) {545// this check is added to protect against an observed problem546// with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,547// indicating success, but has p == NULL. This was observed when548// inserting a file descriptor exhaustion fault prior to the call549// getpwuid_r() call. In this case, error is set to the appropriate550// error condition, but this is undocumented behavior. This check551// is safe under any condition, but the use of errno in the output552// message may result in an erroneous message.553// Bug Id 89052 was opened with RedHat.554//555warning("Could not retrieve passwd entry: %s\n",556strerror(errno));557}558else {559warning("Could not determine user name: %s\n",560p->pw_name == NULL ? "pw_name = NULL" :561"pw_name zero length");562}563}564FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);565return NULL;566}567568char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);569strcpy(user_name, p->pw_name);570571FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);572return user_name;573}574575// return the name of the user that owns the process identified by vmid.576//577// This method uses a slow directory search algorithm to find the backing578// store file for the specified vmid and returns the user name, as determined579// by the user name suffix of the hsperfdata_<username> directory name.580//581// the caller is expected to free the allocated memory.582//583static char* get_user_name_slow(int vmid, TRAPS) {584585// short circuit the directory search if the process doesn't even exist.586if (kill(vmid, 0) == OS_ERR) {587if (errno == ESRCH) {588THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),589"Process not found");590}591else /* EPERM */ {592THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));593}594}595596// directory search597char* oldest_user = NULL;598time_t oldest_ctime = 0;599600const char* tmpdirname = os::get_temp_directory();601602DIR* tmpdirp = os::opendir(tmpdirname);603604if (tmpdirp == NULL) {605return NULL;606}607608// for each entry in the directory that matches the pattern hsperfdata_*,609// open the directory and check if the file for the given vmid exists.610// The file with the expected name and the latest creation date is used611// to determine the user name for the process id.612//613struct dirent* dentry;614errno = 0;615while ((dentry = os::readdir(tmpdirp)) != NULL) {616617// check if the directory entry is a hsperfdata file618if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {619continue;620}621622char* usrdir_name = NEW_C_HEAP_ARRAY(char,623strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);624strcpy(usrdir_name, tmpdirname);625strcat(usrdir_name, "/");626strcat(usrdir_name, dentry->d_name);627628// Open the user directory.629DIR* subdirp = open_directory_secure(usrdir_name);630631if (subdirp == NULL) {632FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);633continue;634}635636// Since we don't create the backing store files in directories637// pointed to by symbolic links, we also don't follow them when638// looking for the files. We check for a symbolic link after the639// call to opendir in order to eliminate a small window where the640// symlink can be exploited.641//642if (!is_directory_secure(usrdir_name)) {643FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);644os::closedir(subdirp);645continue;646}647648struct dirent* udentry;649errno = 0;650while ((udentry = os::readdir(subdirp)) != NULL) {651652if (filename_to_pid(udentry->d_name) == vmid) {653struct stat statbuf;654int result;655656char* filename = NEW_C_HEAP_ARRAY(char,657strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);658659strcpy(filename, usrdir_name);660strcat(filename, "/");661strcat(filename, udentry->d_name);662663// don't follow symbolic links for the file664RESTARTABLE(::lstat(filename, &statbuf), result);665if (result == OS_ERR) {666FREE_C_HEAP_ARRAY(char, filename, mtInternal);667continue;668}669670// skip over files that are not regular files.671if (!S_ISREG(statbuf.st_mode)) {672FREE_C_HEAP_ARRAY(char, filename, mtInternal);673continue;674}675676// compare and save filename with latest creation time677if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {678679if (statbuf.st_ctime > oldest_ctime) {680char* user = strchr(dentry->d_name, '_') + 1;681682if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);683oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);684685strcpy(oldest_user, user);686oldest_ctime = statbuf.st_ctime;687}688}689690FREE_C_HEAP_ARRAY(char, filename, mtInternal);691}692}693os::closedir(subdirp);694FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);695}696os::closedir(tmpdirp);697698return(oldest_user);699}700701// return the name of the user that owns the JVM indicated by the given vmid.702//703static char* get_user_name(int vmid, TRAPS) {704return get_user_name_slow(vmid, THREAD);705}706707// return the file name of the backing store file for the named708// shared memory region for the given user name and vmid.709//710// the caller is expected to free the allocated memory.711//712static char* get_sharedmem_filename(const char* dirname, int vmid) {713714// add 2 for the file separator and a null terminator.715size_t nbytes = strlen(dirname) + UINT_CHARS + 2;716717char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);718snprintf(name, nbytes, "%s/%d", dirname, vmid);719720return name;721}722723724// remove file725//726// this method removes the file specified by the given path727//728static void remove_file(const char* path) {729730int result;731732// if the file is a directory, the following unlink will fail. since733// we don't expect to find directories in the user temp directory, we734// won't try to handle this situation. even if accidentially or735// maliciously planted, the directory's presence won't hurt anything.736//737RESTARTABLE(::unlink(path), result);738if (PrintMiscellaneous && Verbose && result == OS_ERR) {739if (errno != ENOENT) {740warning("Could not unlink shared memory backing"741" store file %s : %s\n", path, strerror(errno));742}743}744}745746// Cleanup stale shared memory resources747//748// This method attempts to remove all stale shared memory files in749// the named user temporary directory. It scans the named directory750// for files matching the pattern ^$[0-9]*$. For each file found, the751// process id is extracted from the file name and a test is run to752// determine if the process is alive. If the process is not alive,753// any stale file resources are removed.754static void cleanup_sharedmem_resources(const char* dirname) {755756int saved_cwd_fd;757// Open the directory.758DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);759if (dirp == NULL) {760// Directory doesn't exist or is insecure, so there is nothing to cleanup.761return;762}763764// For each entry in the directory that matches the expected file765// name pattern, determine if the file resources are stale and if766// so, remove the file resources. Note, instrumented HotSpot processes767// for this user may start and/or terminate during this search and768// remove or create new files in this directory. The behavior of this769// loop under these conditions is dependent upon the implementation of770// opendir/readdir.771struct dirent* entry;772errno = 0;773while ((entry = os::readdir(dirp)) != NULL) {774775pid_t pid = filename_to_pid(entry->d_name);776777if (pid == 0) {778779if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {780781// Attempt to remove all unexpected files, except "." and "..".782unlink(entry->d_name);783}784785errno = 0;786continue;787}788789// We now have a file name that converts to a valid integer790// that could represent a process id . if this process id791// matches the current process id or the process is not running,792// then remove the stale file resources.793//794// Process liveness is detected by sending signal number 0 to795// the process id (see kill(2)). if kill determines that the796// process does not exist, then the file resources are removed.797// if kill determines that that we don't have permission to798// signal the process, then the file resources are assumed to799// be stale and are removed because the resources for such a800// process should be in a different user specific directory.801if ((pid == os::current_process_id()) ||802(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {803804unlink(entry->d_name);805}806errno = 0;807}808809// Close the directory and reset the current working directory.810close_directory_secure_cwd(dirp, saved_cwd_fd);811812}813814// Make the user specific temporary directory. Returns true if815// the directory exists and is secure upon return. Returns false816// if the directory exists but is either a symlink, is otherwise817// insecure, or if an error occurred.818static bool make_user_tmp_dir(const char* dirname) {819820// Create the directory with 0755 permissions. note that the directory821// will be owned by euid::egid, which may not be the same as uid::gid.822if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {823if (errno == EEXIST) {824// The directory already exists and was probably created by another825// JVM instance. However, this could also be the result of a826// deliberate symlink. Verify that the existing directory is safe.827if (!is_directory_secure(dirname)) {828// Directory is not secure.829if (PrintMiscellaneous && Verbose) {830warning("%s directory is insecure\n", dirname);831}832return false;833}834}835else {836// we encountered some other failure while attempting837// to create the directory838//839if (PrintMiscellaneous && Verbose) {840warning("could not create directory %s: %s\n",841dirname, strerror(errno));842}843return false;844}845}846return true;847}848849// create the shared memory file resources850//851// This method creates the shared memory file with the given size852// This method also creates the user specific temporary directory, if853// it does not yet exist.854//855static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {856857// make the user temporary directory858if (!make_user_tmp_dir(dirname)) {859// could not make/find the directory or the found directory860// was not secure861return -1;862}863864int saved_cwd_fd;865// Open the directory and set the current working directory to it.866DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);867if (dirp == NULL) {868// Directory doesn't exist or is insecure, so cannot create shared869// memory file.870return -1;871}872873// Open the filename in the current directory.874// Cannot use O_TRUNC here; truncation of an existing file has to happen875// after the is_file_secure() check below.876int result;877878// No O_NOFOLLOW defined at buildtime, and it is not documented for open;879// so provide a workaround in this case.880#ifdef O_NOFOLLOW881RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);882#else883// workaround function (jdk6 code)884RESTARTABLE(::open_o_nofollow(filename, O_RDWR|O_CREAT, S_IREAD|S_IWRITE), result);885#endif886887if (result == OS_ERR) {888if (PrintMiscellaneous && Verbose) {889if (errno == ELOOP) {890warning("file %s is a symlink and is not secure\n", filename);891} else {892warning("could not create file %s: %s\n", filename, strerror(errno));893}894}895// Close the directory and reset the current working directory.896close_directory_secure_cwd(dirp, saved_cwd_fd);897898return -1;899}900// Close the directory and reset the current working directory.901close_directory_secure_cwd(dirp, saved_cwd_fd);902903// save the file descriptor904int fd = result;905906// Check to see if the file is secure.907if (!is_file_secure(fd, filename)) {908::close(fd);909return -1;910}911912// Truncate the file to get rid of any existing data.913RESTARTABLE(::ftruncate(fd, (off_t)0), result);914if (result == OS_ERR) {915if (PrintMiscellaneous && Verbose) {916warning("could not truncate shared memory file: %s\n", strerror(errno));917}918::close(fd);919return -1;920}921// set the file size922RESTARTABLE(::ftruncate(fd, (off_t)size), result);923if (result == OS_ERR) {924if (PrintMiscellaneous && Verbose) {925warning("could not set shared memory file size: %s\n", strerror(errno));926}927RESTARTABLE(::close(fd), result);928return -1;929}930931return fd;932}933934// open the shared memory file for the given user and vmid. returns935// the file descriptor for the open file or -1 if the file could not936// be opened.937//938static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {939940// open the file941int result;942// No O_NOFOLLOW defined at buildtime, and it is not documented for open;943// so provide a workaround in this case944#ifdef O_NOFOLLOW945RESTARTABLE(::open(filename, oflags), result);946#else947RESTARTABLE(::open_o_nofollow(filename, oflags), result);948#endif949950if (result == OS_ERR) {951if (errno == ENOENT) {952THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),953"Process not found");954}955else if (errno == EACCES) {956THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),957"Permission denied");958}959else {960THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));961}962}963int fd = result;964965// Check to see if the file is secure.966if (!is_file_secure(fd, filename)) {967::close(fd);968return -1;969}970971return fd;972}973974// create a named shared memory region. returns the address of the975// memory region on success or NULL on failure. A return value of976// NULL will ultimately disable the shared memory feature.977//978// On Solaris and Linux, the name space for shared memory objects979// is the file system name space.980//981// A monitoring application attaching to a JVM does not need to know982// the file system name of the shared memory object. However, it may983// be convenient for applications to discover the existence of newly984// created and terminating JVMs by watching the file system name space985// for files being created or removed.986//987static char* mmap_create_shared(size_t size) {988989int result;990int fd;991char* mapAddress;992993int vmid = os::current_process_id();994995char* user_name = get_user_name(geteuid());996997if (user_name == NULL)998return NULL;9991000char* dirname = get_user_tmp_dir(user_name);1001char* filename = get_sharedmem_filename(dirname, vmid);10021003// Get the short filename.1004char* short_filename = strrchr(filename, '/');1005if (short_filename == NULL) {1006short_filename = filename;1007} else {1008short_filename++;1009}10101011// cleanup any stale shared memory files1012cleanup_sharedmem_resources(dirname);10131014assert(((size > 0) && (size % os::vm_page_size() == 0)),1015"unexpected PerfMemory region size");10161017fd = create_sharedmem_resources(dirname, short_filename, size);10181019FREE_C_HEAP_ARRAY(char, user_name, mtInternal);1020FREE_C_HEAP_ARRAY(char, dirname, mtInternal);10211022if (fd == -1) {1023FREE_C_HEAP_ARRAY(char, filename, mtInternal);1024return NULL;1025}10261027mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);10281029// attempt to close the file - restart it if it was interrupted,1030// but ignore other failures1031RESTARTABLE(::close(fd), result);1032assert(result != OS_ERR, "could not close file");10331034if (mapAddress == MAP_FAILED) {1035if (PrintMiscellaneous && Verbose) {1036warning("mmap failed - %s\n", strerror(errno));1037}1038remove_file(filename);1039FREE_C_HEAP_ARRAY(char, filename, mtInternal);1040return NULL;1041}10421043// save the file name for use in delete_shared_memory()1044backing_store_file_name = filename;10451046// clear the shared memory region1047(void)::memset((void*) mapAddress, 0, size);10481049// It does not go through os api, the operation has to record from here.1050MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);10511052return mapAddress;1053}10541055// release a named shared memory region1056//1057static void unmap_shared(char* addr, size_t bytes) {1058// Do not rely on os::reserve_memory/os::release_memory to use mmap.1059// Use os::reserve_memory/os::release_memory for PerfDisableSharedMem=1, mmap/munmap for PerfDisableSharedMem=01060if (::munmap(addr, bytes) == -1) {1061warning("perfmemory: munmap failed (%d)\n", errno);1062}1063}10641065// create the PerfData memory region in shared memory.1066//1067static char* create_shared_memory(size_t size) {10681069// create the shared memory region.1070return mmap_create_shared(size);1071}10721073// delete the shared PerfData memory region1074//1075static void delete_shared_memory(char* addr, size_t size) {10761077// cleanup the persistent shared memory resources. since DestroyJavaVM does1078// not support unloading of the JVM, unmapping of the memory resource is1079// not performed. The memory will be reclaimed by the OS upon termination of1080// the process. The backing store file is deleted from the file system.10811082assert(!PerfDisableSharedMem, "shouldn't be here");10831084if (backing_store_file_name != NULL) {1085remove_file(backing_store_file_name);1086// Don't.. Free heap memory could deadlock os::abort() if it is called1087// from signal handler. OS will reclaim the heap memory.1088// FREE_C_HEAP_ARRAY(char, backing_store_file_name, mtInternal);1089backing_store_file_name = NULL;1090}1091}10921093// return the size of the file for the given file descriptor1094// or 0 if it is not a valid size for a shared memory file1095//1096static size_t sharedmem_filesize(int fd, TRAPS) {10971098struct stat statbuf;1099int result;11001101RESTARTABLE(::fstat(fd, &statbuf), result);1102if (result == OS_ERR) {1103if (PrintMiscellaneous && Verbose) {1104warning("fstat failed: %s\n", strerror(errno));1105}1106THROW_MSG_0(vmSymbols::java_io_IOException(),1107"Could not determine PerfMemory size");1108}11091110if ((statbuf.st_size == 0) ||1111((size_t)statbuf.st_size % os::vm_page_size() != 0)) {1112THROW_MSG_0(vmSymbols::java_lang_Exception(),1113"Invalid PerfMemory size");1114}11151116return (size_t)statbuf.st_size;1117}11181119// attach to a named shared memory region.1120//1121static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {11221123char* mapAddress;1124int result;1125int fd;1126size_t size = 0;1127const char* luser = NULL;11281129int mmap_prot;1130int file_flags;11311132ResourceMark rm;11331134// map the high level access mode to the appropriate permission1135// constructs for the file and the shared memory mapping.1136if (mode == PerfMemory::PERF_MODE_RO) {1137mmap_prot = PROT_READ;11381139// No O_NOFOLLOW defined at buildtime, and it is not documented for open.1140#ifdef O_NOFOLLOW1141file_flags = O_RDONLY | O_NOFOLLOW;1142#else1143file_flags = O_RDONLY;1144#endif1145}1146else if (mode == PerfMemory::PERF_MODE_RW) {1147#ifdef LATER1148mmap_prot = PROT_READ | PROT_WRITE;1149file_flags = O_RDWR | O_NOFOLLOW;1150#else1151THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1152"Unsupported access mode");1153#endif1154}1155else {1156THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1157"Illegal access mode");1158}11591160if (user == NULL || strlen(user) == 0) {1161luser = get_user_name(vmid, CHECK);1162}1163else {1164luser = user;1165}11661167if (luser == NULL) {1168THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1169"Could not map vmid to user Name");1170}11711172char* dirname = get_user_tmp_dir(luser);11731174// since we don't follow symbolic links when creating the backing1175// store file, we don't follow them when attaching either.1176//1177if (!is_directory_secure(dirname)) {1178FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1179if (luser != user) {1180FREE_C_HEAP_ARRAY(char, luser, mtInternal);1181}1182THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1183"Process not found");1184}11851186char* filename = get_sharedmem_filename(dirname, vmid);11871188// copy heap memory to resource memory. the open_sharedmem_file1189// method below need to use the filename, but could throw an1190// exception. using a resource array prevents the leak that1191// would otherwise occur.1192char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1193strcpy(rfilename, filename);11941195// free the c heap resources that are no longer needed1196if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);1197FREE_C_HEAP_ARRAY(char, dirname, mtInternal);1198FREE_C_HEAP_ARRAY(char, filename, mtInternal);11991200// open the shared memory file for the give vmid1201fd = open_sharedmem_file(rfilename, file_flags, CHECK);1202assert(fd != OS_ERR, "unexpected value");12031204if (*sizep == 0) {1205size = sharedmem_filesize(fd, CHECK);1206assert(size != 0, "unexpected size");1207} else {1208size = *sizep;1209}12101211mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);12121213// attempt to close the file - restart if it gets interrupted,1214// but ignore other failures1215RESTARTABLE(::close(fd), result);1216assert(result != OS_ERR, "could not close file");12171218if (mapAddress == MAP_FAILED) {1219if (PrintMiscellaneous && Verbose) {1220warning("mmap failed: %s\n", strerror(errno));1221}1222THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1223"Could not map PerfMemory");1224}12251226// It does not go through os api, the operation has to record from here.1227MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);12281229*addr = mapAddress;1230*sizep = size;12311232if (PerfTraceMemOps) {1233tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "1234INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);1235}1236}12371238123912401241// create the PerfData memory region1242//1243// This method creates the memory region used to store performance1244// data for the JVM. The memory may be created in standard or1245// shared memory.1246//1247void PerfMemory::create_memory_region(size_t size) {12481249if (PerfDisableSharedMem) {1250// do not share the memory for the performance data.1251_start = create_standard_memory(size);1252}1253else {1254_start = create_shared_memory(size);1255if (_start == NULL) {12561257// creation of the shared memory region failed, attempt1258// to create a contiguous, non-shared memory region instead.1259//1260if (PrintMiscellaneous && Verbose) {1261warning("Reverting to non-shared PerfMemory region.\n");1262}1263PerfDisableSharedMem = true;1264_start = create_standard_memory(size);1265}1266}12671268if (_start != NULL) _capacity = size;12691270}12711272// delete the PerfData memory region1273//1274// This method deletes the memory region used to store performance1275// data for the JVM. The memory region indicated by the <address, size>1276// tuple will be inaccessible after a call to this method.1277//1278void PerfMemory::delete_memory_region() {12791280assert((start() != NULL && capacity() > 0), "verify proper state");12811282// If user specifies PerfDataSaveFile, it will save the performance data1283// to the specified file name no matter whether PerfDataSaveToFile is specified1284// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1285// -XX:+PerfDataSaveToFile.1286if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1287save_memory_to_file(start(), capacity());1288}12891290if (PerfDisableSharedMem) {1291delete_standard_memory(start(), capacity());1292}1293else {1294delete_shared_memory(start(), capacity());1295}1296}12971298// attach to the PerfData memory region for another JVM1299//1300// This method returns an <address, size> tuple that points to1301// a memory buffer that is kept reasonably synchronized with1302// the PerfData memory region for the indicated JVM. This1303// buffer may be kept in synchronization via shared memory1304// or some other mechanism that keeps the buffer updated.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 map1310// the indicated process's PerfData memory region into this JVMs1311// address space.1312//1313void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {13141315if (vmid == 0 || vmid == os::current_process_id()) {1316*addrp = start();1317*sizep = capacity();1318return;1319}13201321mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);1322}13231324// detach from the PerfData memory region of another JVM1325//1326// This method detaches the PerfData memory region of another1327// JVM, specified as an <address, size> tuple of a buffer1328// in this process's address space. This method may perform1329// arbitrary actions to accomplish the detachment. The memory1330// region specified by <address, size> will be inaccessible after1331// a call to this method.1332//1333// If the JVM chooses not to support the attachability feature,1334// this method should throw an UnsupportedOperation exception.1335//1336// This implementation utilizes named shared memory to detach1337// the indicated process's PerfData memory region from this1338// process's address space.1339//1340void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {13411342assert(addr != 0, "address sanity check");1343assert(bytes > 0, "capacity sanity check");13441345if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1346// prevent accidental detachment of this process's PerfMemory region1347return;1348}13491350unmap_shared(addr, bytes);1351}13521353char* PerfMemory::backing_store_filename() {1354return backing_store_file_name;1355}135613571358