Path: blob/master/src/hotspot/os/windows/perfMemory_windows.cpp
40930 views
/*1* Copyright (c) 2001, 2021, 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 "logging/log.hpp"27#include "memory/allocation.inline.hpp"28#include "memory/resourceArea.hpp"29#include "oops/oop.inline.hpp"30#include "os_windows.inline.hpp"31#include "runtime/handles.inline.hpp"32#include "runtime/os.hpp"33#include "runtime/perfMemory.hpp"34#include "services/memTracker.hpp"35#include "utilities/exceptions.hpp"36#include "utilities/formatBuffer.hpp"3738#include <windows.h>39#include <sys/types.h>40#include <sys/stat.h>41#include <errno.h>42#include <lmcons.h>4344typedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)(45IN PSECURITY_DESCRIPTOR pSecurityDescriptor,46IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,47IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet);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;8485}8687// save the specified memory region to the given file88//89static void save_memory_to_file(char* addr, size_t size) {9091const char* destfile = PerfMemory::get_perfdata_file_path();92assert(destfile[0] != '\0', "invalid Perfdata file path");9394int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC,95_S_IREAD|_S_IWRITE);9697if (fd == OS_ERR) {98if (PrintMiscellaneous && Verbose) {99warning("Could not create Perfdata save file: %s: %s\n",100destfile, os::strerror(errno));101}102} else {103for (size_t remaining = size; remaining > 0;) {104105int nbytes = ::_write(fd, addr, (unsigned int)remaining);106if (nbytes == OS_ERR) {107if (PrintMiscellaneous && Verbose) {108warning("Could not write Perfdata save file: %s: %s\n",109destfile, os::strerror(errno));110}111break;112}113114remaining -= (size_t)nbytes;115addr += nbytes;116}117118int result = ::_close(fd);119if (PrintMiscellaneous && Verbose) {120if (result == OS_ERR) {121warning("Could not close %s: %s\n", destfile, os::strerror(errno));122}123}124}125126FREE_C_HEAP_ARRAY(char, destfile);127}128129// Shared Memory Implementation Details130131// Note: the win32 shared memory implementation uses two objects to represent132// the shared memory: a windows kernel based file mapping object and a backing133// store file. On windows, the name space for shared memory is a kernel134// based name space that is disjoint from other win32 name spaces. Since Java135// is unaware of this name space, a parallel file system based name space is136// maintained, which provides a common file system based shared memory name137// space across the supported platforms and one that Java apps can deal with138// through simple file apis.139//140// For performance and resource cleanup reasons, it is recommended that the141// user specific directory and the backing store file be stored in either a142// RAM based file system or a local disk based file system. Network based143// file systems are not recommended for performance reasons. In addition,144// use of SMB network based file systems may result in unsuccesful cleanup145// of the disk based resource on exit of the VM. The Windows TMP and TEMP146// environement variables, as used by the GetTempPath() Win32 API (see147// os::get_temp_directory() in os_win32.cpp), control the location of the148// user specific directory and the shared memory backing store file.149150static HANDLE sharedmem_fileMapHandle = NULL;151static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE;152static char* sharedmem_fileName = NULL;153154// return the user specific temporary directory name.155//156// the caller is expected to free the allocated memory.157//158static char* get_user_tmp_dir(const char* user) {159160const char* tmpdir = os::get_temp_directory();161const char* perfdir = PERFDATA_NAME;162size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;163char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);164165// construct the path name to user specific tmp directory166_snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user);167168return dirname;169}170171// convert the given file name into a process id. if the file172// does not meet the file naming constraints, return 0.173//174static int filename_to_pid(const char* filename) {175176// a filename that doesn't begin with a digit is not a177// candidate for conversion.178//179if (!isdigit(*filename)) {180return 0;181}182183// check if file name can be converted to an integer without184// any leftover characters.185//186char* remainder = NULL;187errno = 0;188int pid = (int)strtol(filename, &remainder, 10);189190if (errno != 0) {191return 0;192}193194// check for left over characters. If any, then the filename is195// not a candidate for conversion.196//197if (remainder != NULL && *remainder != '\0') {198return 0;199}200201// successful conversion, return the pid202return pid;203}204205// check if the given path is considered a secure directory for206// the backing store files. Returns true if the directory exists207// and is considered a secure location. Returns false if the path208// is a symbolic link or if an error occurred.209//210static bool is_directory_secure(const char* path) {211212DWORD fa;213214fa = GetFileAttributes(path);215if (fa == 0xFFFFFFFF) {216DWORD lasterror = GetLastError();217if (lasterror == ERROR_FILE_NOT_FOUND) {218return false;219}220else {221// unexpected error, declare the path insecure222if (PrintMiscellaneous && Verbose) {223warning("could not get attributes for file %s: ",224" lasterror = %d\n", path, lasterror);225}226return false;227}228}229230if (fa & FILE_ATTRIBUTE_REPARSE_POINT) {231// we don't accept any redirection for the user specific directory232// so declare the path insecure. This may be too conservative,233// as some types of reparse points might be acceptable, but it234// is probably more secure to avoid these conditions.235//236if (PrintMiscellaneous && Verbose) {237warning("%s is a reparse point\n", path);238}239return false;240}241242if (fa & FILE_ATTRIBUTE_DIRECTORY) {243// this is the expected case. Since windows supports symbolic244// links to directories only, not to files, there is no need245// to check for open write permissions on the directory. If the246// directory has open write permissions, any files deposited that247// are not expected will be removed by the cleanup code.248//249return true;250}251else {252// this is either a regular file or some other type of file,253// any of which are unexpected and therefore insecure.254//255if (PrintMiscellaneous && Verbose) {256warning("%s is not a directory, file attributes = "257INTPTR_FORMAT "\n", path, fa);258}259return false;260}261}262263// return the user name for the owner of this process264//265// the caller is expected to free the allocated memory.266//267static char* get_user_name() {268269/* get the user name. This code is adapted from code found in270* the jdk in src/windows/native/java/lang/java_props_md.c271* java_props_md.c 1.29 02/02/06. According to the original272* source, the call to GetUserName is avoided because of a resulting273* increase in footprint of 100K.274*/275char* user = getenv("USERNAME");276char buf[UNLEN+1];277DWORD buflen = sizeof(buf);278if (user == NULL || strlen(user) == 0) {279if (GetUserName(buf, &buflen)) {280user = buf;281}282else {283return NULL;284}285}286287char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);288strcpy(user_name, user);289290return user_name;291}292293// return the name of the user that owns the process identified by vmid.294//295// This method uses a slow directory search algorithm to find the backing296// store file for the specified vmid and returns the user name, as determined297// by the user name suffix of the hsperfdata_<username> directory name.298//299// the caller is expected to free the allocated memory.300//301static char* get_user_name_slow(int vmid) {302303// directory search304char* latest_user = NULL;305time_t latest_ctime = 0;306307const char* tmpdirname = os::get_temp_directory();308309DIR* tmpdirp = os::opendir(tmpdirname);310311if (tmpdirp == NULL) {312return NULL;313}314315// for each entry in the directory that matches the pattern hsperfdata_*,316// open the directory and check if the file for the given vmid exists.317// The file with the expected name and the latest creation date is used318// to determine the user name for the process id.319//320struct dirent* dentry;321errno = 0;322while ((dentry = os::readdir(tmpdirp)) != NULL) {323324// check if the directory entry is a hsperfdata file325if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {326continue;327}328329char* usrdir_name = NEW_C_HEAP_ARRAY(char,330strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);331strcpy(usrdir_name, tmpdirname);332strcat(usrdir_name, "\\");333strcat(usrdir_name, dentry->d_name);334335DIR* subdirp = os::opendir(usrdir_name);336337if (subdirp == NULL) {338FREE_C_HEAP_ARRAY(char, usrdir_name);339continue;340}341342// Since we don't create the backing store files in directories343// pointed to by symbolic links, we also don't follow them when344// looking for the files. We check for a symbolic link after the345// call to opendir in order to eliminate a small window where the346// symlink can be exploited.347//348if (!is_directory_secure(usrdir_name)) {349FREE_C_HEAP_ARRAY(char, usrdir_name);350os::closedir(subdirp);351continue;352}353354struct dirent* udentry;355errno = 0;356while ((udentry = os::readdir(subdirp)) != NULL) {357358if (filename_to_pid(udentry->d_name) == vmid) {359struct stat statbuf;360361char* filename = NEW_C_HEAP_ARRAY(char,362strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);363364strcpy(filename, usrdir_name);365strcat(filename, "\\");366strcat(filename, udentry->d_name);367368if (::stat(filename, &statbuf) == OS_ERR) {369FREE_C_HEAP_ARRAY(char, filename);370continue;371}372373// skip over files that are not regular files.374if ((statbuf.st_mode & S_IFMT) != S_IFREG) {375FREE_C_HEAP_ARRAY(char, filename);376continue;377}378379// If we found a matching file with a newer creation time, then380// save the user name. The newer creation time indicates that381// we found a newer incarnation of the process associated with382// vmid. Due to the way that Windows recycles pids and the fact383// that we can't delete the file from the file system namespace384// until last close, it is possible for there to be more than385// one hsperfdata file with a name matching vmid (diff users).386//387// We no longer ignore hsperfdata files where (st_size == 0).388// In this function, all we're trying to do is determine the389// name of the user that owns the process associated with vmid390// so the size doesn't matter. Very rarely, we have observed391// hsperfdata files where (st_size == 0) and the st_size field392// later becomes the expected value.393//394if (statbuf.st_ctime > latest_ctime) {395char* user = strchr(dentry->d_name, '_') + 1;396397FREE_C_HEAP_ARRAY(char, latest_user);398latest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);399400strcpy(latest_user, user);401latest_ctime = statbuf.st_ctime;402}403404FREE_C_HEAP_ARRAY(char, filename);405}406}407os::closedir(subdirp);408FREE_C_HEAP_ARRAY(char, usrdir_name);409}410os::closedir(tmpdirp);411412return(latest_user);413}414415// return the name of the user that owns the process identified by vmid.416//417// note: this method should only be used via the Perf native methods.418// There are various costs to this method and limiting its use to the419// Perf native methods limits the impact to monitoring applications only.420//421static char* get_user_name(int vmid) {422423// A fast implementation is not provided at this time. It's possible424// to provide a fast process id to user name mapping function using425// the win32 apis, but the default ACL for the process object only426// allows processes with the same owner SID to acquire the process427// handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible428// to have the JVM change the ACL for the process object to allow arbitrary429// users to access the process handle and the process security token.430// The security ramifications need to be studied before providing this431// mechanism.432//433return get_user_name_slow(vmid);434}435436// return the name of the shared memory file mapping object for the437// named shared memory region for the given user name and vmid.438//439// The file mapping object's name is not the file name. It is a name440// in a separate name space.441//442// the caller is expected to free the allocated memory.443//444static char *get_sharedmem_objectname(const char* user, int vmid) {445446// construct file mapping object's name, add 3 for two '_' and a447// null terminator.448int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3;449450// the id is converted to an unsigned value here because win32 allows451// negative process ids. However, OpenFileMapping API complains452// about a name containing a '-' characters.453//454nbytes += UINT_CHARS;455char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);456_snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid);457458return name;459}460461// return the file name of the backing store file for the named462// shared memory region for the given user name and vmid.463//464// the caller is expected to free the allocated memory.465//466static char* get_sharedmem_filename(const char* dirname, int vmid) {467468// add 2 for the file separator and a null terminator.469size_t nbytes = strlen(dirname) + UINT_CHARS + 2;470471char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);472_snprintf(name, nbytes, "%s\\%d", dirname, vmid);473474return name;475}476477// remove file478//479// this method removes the file with the given file name.480//481// Note: if the indicated file is on an SMB network file system, this482// method may be unsuccessful in removing the file.483//484static void remove_file(const char* dirname, const char* filename) {485486size_t nbytes = strlen(dirname) + strlen(filename) + 2;487char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);488489strcpy(path, dirname);490strcat(path, "\\");491strcat(path, filename);492493if (::unlink(path) == OS_ERR) {494if (PrintMiscellaneous && Verbose) {495if (errno != ENOENT) {496warning("Could not unlink shared memory backing"497" store file %s : %s\n", path, os::strerror(errno));498}499}500}501502FREE_C_HEAP_ARRAY(char, path);503}504505// returns true if the process represented by pid is alive, otherwise506// returns false. the validity of the result is only accurate if the507// target process is owned by the same principal that owns this process.508// this method should not be used if to test the status of an otherwise509// arbitrary process unless it is know that this process has the appropriate510// privileges to guarantee a result valid.511//512static bool is_alive(int pid) {513514HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);515if (ph == NULL) {516// the process does not exist.517if (PrintMiscellaneous && Verbose) {518DWORD lastError = GetLastError();519if (lastError != ERROR_INVALID_PARAMETER) {520warning("OpenProcess failed: %d\n", GetLastError());521}522}523return false;524}525526DWORD exit_status;527if (!GetExitCodeProcess(ph, &exit_status)) {528if (PrintMiscellaneous && Verbose) {529warning("GetExitCodeProcess failed: %d\n", GetLastError());530}531CloseHandle(ph);532return false;533}534535CloseHandle(ph);536return (exit_status == STILL_ACTIVE) ? true : false;537}538539// check if the file system is considered secure for the backing store files540//541static bool is_filesystem_secure(const char* path) {542543char root_path[MAX_PATH];544char fs_type[MAX_PATH];545546if (PerfBypassFileSystemCheck) {547if (PrintMiscellaneous && Verbose) {548warning("bypassing file system criteria checks for %s\n", path);549}550return true;551}552553char* first_colon = strchr((char *)path, ':');554if (first_colon == NULL) {555if (PrintMiscellaneous && Verbose) {556warning("expected device specifier in path: %s\n", path);557}558return false;559}560561size_t len = (size_t)(first_colon - path);562assert(len + 2 <= MAX_PATH, "unexpected device specifier length");563strncpy(root_path, path, len + 1);564root_path[len + 1] = '\\';565root_path[len + 2] = '\0';566567// check that we have something like "C:\" or "AA:\"568assert(strlen(root_path) >= 3, "device specifier too short");569assert(strchr(root_path, ':') != NULL, "bad device specifier format");570assert(strchr(root_path, '\\') != NULL, "bad device specifier format");571572DWORD maxpath;573DWORD flags;574575if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath,576&flags, fs_type, MAX_PATH)) {577// we can't get information about the volume, so assume unsafe.578if (PrintMiscellaneous && Verbose) {579warning("could not get device information for %s: "580" path = %s: lasterror = %d\n",581root_path, path, GetLastError());582}583return false;584}585586if ((flags & FS_PERSISTENT_ACLS) == 0) {587// file system doesn't support ACLs, declare file system unsafe588if (PrintMiscellaneous && Verbose) {589warning("file system type %s on device %s does not support"590" ACLs\n", fs_type, root_path);591}592return false;593}594595if ((flags & FS_VOL_IS_COMPRESSED) != 0) {596// file system is compressed, declare file system unsafe597if (PrintMiscellaneous && Verbose) {598warning("file system type %s on device %s is compressed\n",599fs_type, root_path);600}601return false;602}603604return true;605}606607// cleanup stale shared memory resources608//609// This method attempts to remove all stale shared memory files in610// the named user temporary directory. It scans the named directory611// for files matching the pattern ^$[0-9]*$. For each file found, the612// process id is extracted from the file name and a test is run to613// determine if the process is alive. If the process is not alive,614// any stale file resources are removed.615//616static void cleanup_sharedmem_resources(const char* dirname) {617618// open the user temp directory619DIR* dirp = os::opendir(dirname);620621if (dirp == NULL) {622// directory doesn't exist, so there is nothing to cleanup623return;624}625626if (!is_directory_secure(dirname)) {627// the directory is not secure, don't attempt any cleanup628os::closedir(dirp);629return;630}631632// for each entry in the directory that matches the expected file633// name pattern, determine if the file resources are stale and if634// so, remove the file resources. Note, instrumented HotSpot processes635// for this user may start and/or terminate during this search and636// remove or create new files in this directory. The behavior of this637// loop under these conditions is dependent upon the implementation of638// opendir/readdir.639//640struct dirent* entry;641errno = 0;642while ((entry = os::readdir(dirp)) != NULL) {643644int pid = filename_to_pid(entry->d_name);645646if (pid == 0) {647648if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {649650// attempt to remove all unexpected files, except "." and ".."651remove_file(dirname, entry->d_name);652}653654errno = 0;655continue;656}657658// we now have a file name that converts to a valid integer659// that could represent a process id . if this process id660// matches the current process id or the process is not running,661// then remove the stale file resources.662//663// process liveness is detected by checking the exit status664// of the process. if the process id is valid and the exit status665// indicates that it is still running, the file file resources666// are not removed. If the process id is invalid, or if we don't667// have permissions to check the process status, or if the process668// id is valid and the process has terminated, the the file resources669// are assumed to be stale and are removed.670//671if (pid == os::current_process_id() || !is_alive(pid)) {672673// we can only remove the file resources. Any mapped views674// of the file can only be unmapped by the processes that675// opened those views and the file mapping object will not676// get removed until all views are unmapped.677//678remove_file(dirname, entry->d_name);679}680errno = 0;681}682os::closedir(dirp);683}684685// create a file mapping object with the requested name, and size686// from the file represented by the given Handle object687//688static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) {689690DWORD lowSize = (DWORD)size;691DWORD highSize = 0;692HANDLE fmh = NULL;693694// Create a file mapping object with the given name. This function695// will grow the file to the specified size.696//697fmh = CreateFileMapping(698fh, /* HANDLE file handle for backing store */699fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */700PAGE_READWRITE, /* DWORD protections */701highSize, /* DWORD High word of max size */702lowSize, /* DWORD Low word of max size */703name); /* LPCTSTR name for object */704705if (fmh == NULL) {706if (PrintMiscellaneous && Verbose) {707warning("CreateFileMapping failed, lasterror = %d\n", GetLastError());708}709return NULL;710}711712if (GetLastError() == ERROR_ALREADY_EXISTS) {713714// a stale file mapping object was encountered. This object may be715// owned by this or some other user and cannot be removed until716// the other processes either exit or close their mapping objects717// and/or mapped views of this mapping object.718//719if (PrintMiscellaneous && Verbose) {720warning("file mapping already exists, lasterror = %d\n", GetLastError());721}722723CloseHandle(fmh);724return NULL;725}726727return fmh;728}729730731// method to free the given security descriptor and the contained732// access control list.733//734static void free_security_desc(PSECURITY_DESCRIPTOR pSD) {735736BOOL success, exists, isdefault;737PACL pACL;738739if (pSD != NULL) {740741// get the access control list from the security descriptor742success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault);743744// if an ACL existed and it was not a default acl, then it must745// be an ACL we enlisted. free the resources.746//747if (success && exists && pACL != NULL && !isdefault) {748FREE_C_HEAP_ARRAY(char, pACL);749}750751// free the security descriptor752FREE_C_HEAP_ARRAY(char, pSD);753}754}755756// method to free up a security attributes structure and any757// contained security descriptors and ACL758//759static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) {760761if (lpSA != NULL) {762// free the contained security descriptor and the ACL763free_security_desc(lpSA->lpSecurityDescriptor);764lpSA->lpSecurityDescriptor = NULL;765766// free the security attributes structure767FREE_C_HEAP_OBJ(lpSA);768}769}770771// get the user SID for the process indicated by the process handle772//773static PSID get_user_sid(HANDLE hProcess) {774775HANDLE hAccessToken;776PTOKEN_USER token_buf = NULL;777DWORD rsize = 0;778779if (hProcess == NULL) {780return NULL;781}782783// get the process token784if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) {785if (PrintMiscellaneous && Verbose) {786warning("OpenProcessToken failure: lasterror = %d \n", GetLastError());787}788return NULL;789}790791// determine the size of the token structured needed to retrieve792// the user token information from the access token.793//794if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) {795DWORD lasterror = GetLastError();796if (lasterror != ERROR_INSUFFICIENT_BUFFER) {797if (PrintMiscellaneous && Verbose) {798warning("GetTokenInformation failure: lasterror = %d,"799" rsize = %d\n", lasterror, rsize);800}801CloseHandle(hAccessToken);802return NULL;803}804}805806token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal);807808// get the user token information809if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) {810if (PrintMiscellaneous && Verbose) {811warning("GetTokenInformation failure: lasterror = %d,"812" rsize = %d\n", GetLastError(), rsize);813}814FREE_C_HEAP_ARRAY(char, token_buf);815CloseHandle(hAccessToken);816return NULL;817}818819DWORD nbytes = GetLengthSid(token_buf->User.Sid);820PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);821822if (!CopySid(nbytes, pSID, token_buf->User.Sid)) {823if (PrintMiscellaneous && Verbose) {824warning("GetTokenInformation failure: lasterror = %d,"825" rsize = %d\n", GetLastError(), rsize);826}827FREE_C_HEAP_ARRAY(char, token_buf);828FREE_C_HEAP_ARRAY(char, pSID);829CloseHandle(hAccessToken);830return NULL;831}832833// close the access token.834CloseHandle(hAccessToken);835FREE_C_HEAP_ARRAY(char, token_buf);836837return pSID;838}839840// structure used to consolidate access control entry information841//842typedef struct ace_data {843PSID pSid; // SID of the ACE844DWORD mask; // mask for the ACE845} ace_data_t;846847848// method to add an allow access control entry with the access rights849// indicated in mask for the principal indicated in SID to the given850// security descriptor. Much of the DACL handling was adapted from851// the example provided here:852// http://support.microsoft.com/kb/102102/EN-US/853//854855static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD,856ace_data_t aces[], int ace_count) {857PACL newACL = NULL;858PACL oldACL = NULL;859860if (pSD == NULL) {861return false;862}863864BOOL exists, isdefault;865866// retrieve any existing access control list.867if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) {868if (PrintMiscellaneous && Verbose) {869warning("GetSecurityDescriptor failure: lasterror = %d \n",870GetLastError());871}872return false;873}874875// get the size of the DACL876ACL_SIZE_INFORMATION aclinfo;877878// GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent)879// while oldACL is NULL for some case.880if (oldACL == NULL) {881exists = FALSE;882}883884if (exists) {885if (!GetAclInformation(oldACL, &aclinfo,886sizeof(ACL_SIZE_INFORMATION),887AclSizeInformation)) {888if (PrintMiscellaneous && Verbose) {889warning("GetAclInformation failure: lasterror = %d \n", GetLastError());890return false;891}892}893} else {894aclinfo.AceCount = 0; // assume NULL DACL895aclinfo.AclBytesFree = 0;896aclinfo.AclBytesInUse = sizeof(ACL);897}898899// compute the size needed for the new ACL900// initial size of ACL is sum of the following:901// * size of ACL structure.902// * size of each ACE structure that ACL is to contain minus the sid903// sidStart member (DWORD) of the ACE.904// * length of the SID that each ACE is to contain.905DWORD newACLsize = aclinfo.AclBytesInUse +906(sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count;907for (int i = 0; i < ace_count; i++) {908assert(aces[i].pSid != 0, "pSid should not be 0");909newACLsize += GetLengthSid(aces[i].pSid);910}911912// create the new ACL913newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal);914915if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) {916if (PrintMiscellaneous && Verbose) {917warning("InitializeAcl failure: lasterror = %d \n", GetLastError());918}919FREE_C_HEAP_ARRAY(char, newACL);920return false;921}922923unsigned int ace_index = 0;924// copy any existing ACEs from the old ACL (if any) to the new ACL.925if (aclinfo.AceCount != 0) {926while (ace_index < aclinfo.AceCount) {927LPVOID ace;928if (!GetAce(oldACL, ace_index, &ace)) {929if (PrintMiscellaneous && Verbose) {930warning("InitializeAcl failure: lasterror = %d \n", GetLastError());931}932FREE_C_HEAP_ARRAY(char, newACL);933return false;934}935if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) {936// this is an inherited, allowed ACE; break from loop so we can937// add the new access allowed, non-inherited ACE in the correct938// position, immediately following all non-inherited ACEs.939break;940}941942// determine if the SID of this ACE matches any of the SIDs943// for which we plan to set ACEs.944int matches = 0;945for (int i = 0; i < ace_count; i++) {946if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) {947matches++;948break;949}950}951952// if there are no SID matches, then add this existing ACE to the new ACL953if (matches == 0) {954if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,955((PACE_HEADER)ace)->AceSize)) {956if (PrintMiscellaneous && Verbose) {957warning("AddAce failure: lasterror = %d \n", GetLastError());958}959FREE_C_HEAP_ARRAY(char, newACL);960return false;961}962}963ace_index++;964}965}966967// add the passed-in access control entries to the new ACL968for (int i = 0; i < ace_count; i++) {969if (!AddAccessAllowedAce(newACL, ACL_REVISION,970aces[i].mask, aces[i].pSid)) {971if (PrintMiscellaneous && Verbose) {972warning("AddAccessAllowedAce failure: lasterror = %d \n",973GetLastError());974}975FREE_C_HEAP_ARRAY(char, newACL);976return false;977}978}979980// now copy the rest of the inherited ACEs from the old ACL981if (aclinfo.AceCount != 0) {982// picking up at ace_index, where we left off in the983// previous ace_index loop984while (ace_index < aclinfo.AceCount) {985LPVOID ace;986if (!GetAce(oldACL, ace_index, &ace)) {987if (PrintMiscellaneous && Verbose) {988warning("InitializeAcl failure: lasterror = %d \n", GetLastError());989}990FREE_C_HEAP_ARRAY(char, newACL);991return false;992}993if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,994((PACE_HEADER)ace)->AceSize)) {995if (PrintMiscellaneous && Verbose) {996warning("AddAce failure: lasterror = %d \n", GetLastError());997}998FREE_C_HEAP_ARRAY(char, newACL);999return false;1000}1001ace_index++;1002}1003}10041005// add the new ACL to the security descriptor.1006if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) {1007if (PrintMiscellaneous && Verbose) {1008warning("SetSecurityDescriptorDacl failure:"1009" lasterror = %d \n", GetLastError());1010}1011FREE_C_HEAP_ARRAY(char, newACL);1012return false;1013}10141015// if running on windows 2000 or later, set the automatic inheritance1016// control flags.1017SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl;1018_SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr)1019GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")),1020"SetSecurityDescriptorControl");10211022if (_SetSecurityDescriptorControl != NULL) {1023// We do not want to further propagate inherited DACLs, so making them1024// protected prevents that.1025if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED,1026SE_DACL_PROTECTED)) {1027if (PrintMiscellaneous && Verbose) {1028warning("SetSecurityDescriptorControl failure:"1029" lasterror = %d \n", GetLastError());1030}1031FREE_C_HEAP_ARRAY(char, newACL);1032return false;1033}1034}1035// Note, the security descriptor maintains a reference to the newACL, not1036// a copy of it. Therefore, the newACL is not freed here. It is freed when1037// the security descriptor containing its reference is freed.1038//1039return true;1040}10411042// method to create a security attributes structure, which contains a1043// security descriptor and an access control list comprised of 0 or more1044// access control entries. The method take an array of ace_data structures1045// that indicate the ACE to be added to the security descriptor.1046//1047// the caller must free the resources associated with the security1048// attributes structure created by this method by calling the1049// free_security_attr() method.1050//1051static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) {10521053// allocate space for a security descriptor1054PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)1055NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal);10561057// initialize the security descriptor1058if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {1059if (PrintMiscellaneous && Verbose) {1060warning("InitializeSecurityDescriptor failure: "1061"lasterror = %d \n", GetLastError());1062}1063free_security_desc(pSD);1064return NULL;1065}10661067// add the access control entries1068if (!add_allow_aces(pSD, aces, count)) {1069free_security_desc(pSD);1070return NULL;1071}10721073// allocate and initialize the security attributes structure and1074// return it to the caller.1075//1076LPSECURITY_ATTRIBUTES lpSA =1077NEW_C_HEAP_OBJ(SECURITY_ATTRIBUTES, mtInternal);1078lpSA->nLength = sizeof(SECURITY_ATTRIBUTES);1079lpSA->lpSecurityDescriptor = pSD;1080lpSA->bInheritHandle = FALSE;10811082return(lpSA);1083}10841085// method to create a security attributes structure with a restrictive1086// access control list that creates a set access rights for the user/owner1087// of the securable object and a separate set access rights for everyone else.1088// also provides for full access rights for the administrator group.1089//1090// the caller must free the resources associated with the security1091// attributes structure created by this method by calling the1092// free_security_attr() method.1093//10941095static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr(1096DWORD umask, DWORD emask, DWORD amask) {10971098ace_data_t aces[3];10991100// initialize the user ace data1101aces[0].pSid = get_user_sid(GetCurrentProcess());1102aces[0].mask = umask;11031104if (aces[0].pSid == 0)1105return NULL;11061107// get the well known SID for BUILTIN\Administrators1108PSID administratorsSid = NULL;1109SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY;11101111if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2,1112SECURITY_BUILTIN_DOMAIN_RID,1113DOMAIN_ALIAS_RID_ADMINS,11140, 0, 0, 0, 0, 0, &administratorsSid)) {11151116if (PrintMiscellaneous && Verbose) {1117warning("AllocateAndInitializeSid failure: "1118"lasterror = %d \n", GetLastError());1119}1120return NULL;1121}11221123// initialize the ace data for administrator group1124aces[1].pSid = administratorsSid;1125aces[1].mask = amask;11261127// get the well known SID for the universal Everybody1128PSID everybodySid = NULL;1129SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY;11301131if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID,11320, 0, 0, 0, 0, 0, 0, &everybodySid)) {11331134if (PrintMiscellaneous && Verbose) {1135warning("AllocateAndInitializeSid failure: "1136"lasterror = %d \n", GetLastError());1137}1138return NULL;1139}11401141// initialize the ace data for everybody else.1142aces[2].pSid = everybodySid;1143aces[2].mask = emask;11441145// create a security attributes structure with access control1146// entries as initialized above.1147LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3);1148FREE_C_HEAP_ARRAY(char, aces[0].pSid);1149FreeSid(everybodySid);1150FreeSid(administratorsSid);1151return(lpSA);1152}115311541155// method to create the security attributes structure for restricting1156// access to the user temporary directory.1157//1158// the caller must free the resources associated with the security1159// attributes structure created by this method by calling the1160// free_security_attr() method.1161//1162static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() {11631164// create full access rights for the user/owner of the directory1165// and read-only access rights for everybody else. This is1166// effectively equivalent to UNIX 755 permissions on a directory.1167//1168DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS;1169DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE;1170DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;11711172return make_user_everybody_admin_security_attr(umask, emask, amask);1173}11741175// method to create the security attributes structure for restricting1176// access to the shared memory backing store file.1177//1178// the caller must free the resources associated with the security1179// attributes structure created by this method by calling the1180// free_security_attr() method.1181//1182static LPSECURITY_ATTRIBUTES make_file_security_attr() {11831184// create extensive access rights for the user/owner of the file1185// and attribute read-only access rights for everybody else. This1186// is effectively equivalent to UNIX 600 permissions on a file.1187//1188DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;1189DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES |1190FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE;1191DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;11921193return make_user_everybody_admin_security_attr(umask, emask, amask);1194}11951196// method to create the security attributes structure for restricting1197// access to the name shared memory file mapping object.1198//1199// the caller must free the resources associated with the security1200// attributes structure created by this method by calling the1201// free_security_attr() method.1202//1203static LPSECURITY_ATTRIBUTES make_smo_security_attr() {12041205// create extensive access rights for the user/owner of the shared1206// memory object and attribute read-only access rights for everybody1207// else. This is effectively equivalent to UNIX 600 permissions on1208// on the shared memory object.1209//1210DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS;1211DWORD emask = STANDARD_RIGHTS_READ; // attributes only1212DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS;12131214return make_user_everybody_admin_security_attr(umask, emask, amask);1215}12161217// make the user specific temporary directory1218//1219static bool make_user_tmp_dir(const char* dirname) {122012211222LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr();1223if (pDirSA == NULL) {1224return false;1225}122612271228// create the directory with the given security attributes1229if (!CreateDirectory(dirname, pDirSA)) {1230DWORD lasterror = GetLastError();1231if (lasterror == ERROR_ALREADY_EXISTS) {1232// The directory already exists and was probably created by another1233// JVM instance. However, this could also be the result of a1234// deliberate symlink. Verify that the existing directory is safe.1235//1236if (!is_directory_secure(dirname)) {1237// directory is not secure1238if (PrintMiscellaneous && Verbose) {1239warning("%s directory is insecure\n", dirname);1240}1241return false;1242}1243// The administrator should be able to delete this directory.1244// But the directory created by previous version of JVM may not1245// have permission for administrators to delete this directory.1246// So add full permission to the administrator. Also setting new1247// DACLs might fix the corrupted the DACLs.1248SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION;1249if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) {1250if (PrintMiscellaneous && Verbose) {1251lasterror = GetLastError();1252warning("SetFileSecurity failed for %s directory. lasterror %d \n",1253dirname, lasterror);1254}1255}1256}1257else {1258if (PrintMiscellaneous && Verbose) {1259warning("CreateDirectory failed: %d\n", GetLastError());1260}1261return false;1262}1263}12641265// free the security attributes structure1266free_security_attr(pDirSA);12671268return true;1269}12701271// create the shared memory resources1272//1273// This function creates the shared memory resources. This includes1274// the backing store file and the file mapping shared memory object.1275//1276static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) {12771278HANDLE fh = INVALID_HANDLE_VALUE;1279HANDLE fmh = NULL;128012811282// create the security attributes for the backing store file1283LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr();1284if (lpFileSA == NULL) {1285return NULL;1286}12871288// create the security attributes for the shared memory object1289LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr();1290if (lpSmoSA == NULL) {1291free_security_attr(lpFileSA);1292return NULL;1293}12941295// create the user temporary directory1296if (!make_user_tmp_dir(dirname)) {1297// could not make/find the directory or the found directory1298// was not secure1299return NULL;1300}13011302// Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the1303// file to be deleted by the last process that closes its handle to1304// the file. This is important as the apis do not allow a terminating1305// JVM being monitored by another process to remove the file name.1306//1307fh = CreateFile(1308filename, /* LPCTSTR file name */13091310GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */1311FILE_SHARE_DELETE|FILE_SHARE_READ, /* DWORD share mode, future READONLY1312* open operations allowed1313*/1314lpFileSA, /* LPSECURITY security attributes */1315CREATE_ALWAYS, /* DWORD creation disposition1316* create file, if it already1317* exists, overwrite it.1318*/1319FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */13201321NULL); /* HANDLE template file access */13221323free_security_attr(lpFileSA);13241325if (fh == INVALID_HANDLE_VALUE) {1326DWORD lasterror = GetLastError();1327if (PrintMiscellaneous && Verbose) {1328warning("could not create file %s: %d\n", filename, lasterror);1329}1330return NULL;1331}13321333// try to create the file mapping1334fmh = create_file_mapping(objectname, fh, lpSmoSA, size);13351336free_security_attr(lpSmoSA);13371338if (fmh == NULL) {1339// closing the file handle here will decrement the reference count1340// on the file. When all processes accessing the file close their1341// handle to it, the reference count will decrement to 0 and the1342// OS will delete the file. These semantics are requested by the1343// FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above.1344CloseHandle(fh);1345fh = NULL;1346return NULL;1347} else {1348// We created the file mapping, but rarely the size of the1349// backing store file is reported as zero (0) which can cause1350// failures when trying to use the hsperfdata file.1351struct stat statbuf;1352int ret_code = ::stat(filename, &statbuf);1353if (ret_code == OS_ERR) {1354if (PrintMiscellaneous && Verbose) {1355warning("Could not get status information from file %s: %s\n",1356filename, os::strerror(errno));1357}1358CloseHandle(fmh);1359CloseHandle(fh);1360fh = NULL;1361fmh = NULL;1362return NULL;1363}13641365// We could always call FlushFileBuffers() but the Microsoft1366// docs indicate that it is considered expensive so we only1367// call it when we observe the size as zero (0).1368if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) {1369DWORD lasterror = GetLastError();1370if (PrintMiscellaneous && Verbose) {1371warning("could not flush file %s: %d\n", filename, lasterror);1372}1373CloseHandle(fmh);1374CloseHandle(fh);1375fh = NULL;1376fmh = NULL;1377return NULL;1378}1379}13801381// the file has been successfully created and the file mapping1382// object has been created.1383sharedmem_fileHandle = fh;1384sharedmem_fileName = os::strdup(filename);13851386return fmh;1387}13881389// open the shared memory object for the given vmid.1390//1391static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) {13921393HANDLE fmh;13941395// open the file mapping with the requested mode1396fmh = OpenFileMapping(1397ofm_access, /* DWORD access mode */1398FALSE, /* BOOL inherit flag - Do not allow inherit */1399objectname); /* name for object */14001401if (fmh == NULL) {1402DWORD lasterror = GetLastError();1403if (PrintMiscellaneous && Verbose) {1404warning("OpenFileMapping failed for shared memory object %s:"1405" lasterror = %d\n", objectname, lasterror);1406}1407THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1408err_msg("Could not open PerfMemory, error %d", lasterror),1409INVALID_HANDLE_VALUE);1410}14111412return fmh;;1413}14141415// create a named shared memory region1416//1417// On Win32, a named shared memory object has a name space that1418// is independent of the file system name space. Shared memory object,1419// or more precisely, file mapping objects, provide no mechanism to1420// inquire the size of the memory region. There is also no api to1421// enumerate the memory regions for various processes.1422//1423// This implementation utilizes the shared memory name space in parallel1424// with the file system name space. This allows us to determine the1425// size of the shared memory region from the size of the file and it1426// allows us to provide a common, file system based name space for1427// shared memory across platforms.1428//1429static char* mapping_create_shared(size_t size) {14301431void *mapAddress;1432int vmid = os::current_process_id();14331434// get the name of the user associated with this process1435char* user = get_user_name();14361437if (user == NULL) {1438return NULL;1439}14401441// construct the name of the user specific temporary directory1442char* dirname = get_user_tmp_dir(user);14431444// check that the file system is secure - i.e. it supports ACLs.1445if (!is_filesystem_secure(dirname)) {1446FREE_C_HEAP_ARRAY(char, dirname);1447FREE_C_HEAP_ARRAY(char, user);1448return NULL;1449}14501451// create the names of the backing store files and for the1452// share memory object.1453//1454char* filename = get_sharedmem_filename(dirname, vmid);1455char* objectname = get_sharedmem_objectname(user, vmid);14561457// cleanup any stale shared memory resources1458cleanup_sharedmem_resources(dirname);14591460assert(((size != 0) && (size % os::vm_page_size() == 0)),1461"unexpected PerfMemry region size");14621463FREE_C_HEAP_ARRAY(char, user);14641465// create the shared memory resources1466sharedmem_fileMapHandle =1467create_sharedmem_resources(dirname, filename, objectname, size);14681469FREE_C_HEAP_ARRAY(char, filename);1470FREE_C_HEAP_ARRAY(char, objectname);1471FREE_C_HEAP_ARRAY(char, dirname);14721473if (sharedmem_fileMapHandle == NULL) {1474return NULL;1475}14761477// map the file into the address space1478mapAddress = MapViewOfFile(1479sharedmem_fileMapHandle, /* HANDLE = file mapping object */1480FILE_MAP_ALL_ACCESS, /* DWORD access flags */14810, /* DWORD High word of offset */14820, /* DWORD Low word of offset */1483(DWORD)size); /* DWORD Number of bytes to map */14841485if (mapAddress == NULL) {1486if (PrintMiscellaneous && Verbose) {1487warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());1488}1489CloseHandle(sharedmem_fileMapHandle);1490sharedmem_fileMapHandle = NULL;1491return NULL;1492}14931494// clear the shared memory region1495(void)memset(mapAddress, '\0', size);14961497// it does not go through os api, the operation has to record from here1498MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,1499size, CURRENT_PC, mtInternal);15001501return (char*) mapAddress;1502}15031504// this method deletes the file mapping object.1505//1506static void delete_file_mapping(char* addr, size_t size) {15071508// cleanup the persistent shared memory resources. since DestroyJavaVM does1509// not support unloading of the JVM, unmapping of the memory resource is not1510// performed. The memory will be reclaimed by the OS upon termination of all1511// processes mapping the resource. The file mapping handle and the file1512// handle are closed here to expedite the remove of the file by the OS. The1513// file is not removed directly because it was created with1514// FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would1515// be unsuccessful.15161517// close the fileMapHandle. the file mapping will still be retained1518// by the OS as long as any other JVM processes has an open file mapping1519// handle or a mapped view of the file.1520//1521if (sharedmem_fileMapHandle != NULL) {1522CloseHandle(sharedmem_fileMapHandle);1523sharedmem_fileMapHandle = NULL;1524}15251526// close the file handle. This will decrement the reference count on the1527// backing store file. When the reference count decrements to 0, the OS1528// will delete the file. These semantics apply because the file was1529// created with the FILE_FLAG_DELETE_ON_CLOSE flag.1530//1531if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) {1532CloseHandle(sharedmem_fileHandle);1533sharedmem_fileHandle = INVALID_HANDLE_VALUE;1534}1535}15361537// this method determines the size of the shared memory file1538//1539static size_t sharedmem_filesize(const char* filename, TRAPS) {15401541struct stat statbuf;15421543// get the file size1544//1545// on win95/98/me, _stat returns a file size of 0 bytes, but on1546// winnt/2k the appropriate file size is returned. support for1547// the sharable aspects of performance counters was abandonded1548// on the non-nt win32 platforms due to this and other api1549// inconsistencies1550//1551if (::stat(filename, &statbuf) == OS_ERR) {1552if (PrintMiscellaneous && Verbose) {1553warning("stat %s failed: %s\n", filename, os::strerror(errno));1554}1555THROW_MSG_0(vmSymbols::java_io_IOException(),1556"Could not determine PerfMemory size");1557}15581559if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) {1560if (PrintMiscellaneous && Verbose) {1561warning("unexpected file size: size = " SIZE_FORMAT "\n",1562statbuf.st_size);1563}1564THROW_MSG_0(vmSymbols::java_io_IOException(),1565"Invalid PerfMemory size");1566}15671568return statbuf.st_size;1569}15701571// this method opens a file mapping object and maps the object1572// into the address space of the process1573//1574static void open_file_mapping(const char* user, int vmid,1575PerfMemory::PerfMemoryMode mode,1576char** addrp, size_t* sizep, TRAPS) {15771578ResourceMark rm;15791580void *mapAddress = 0;1581size_t size = 0;1582HANDLE fmh;1583DWORD ofm_access;1584DWORD mv_access;1585const char* luser = NULL;15861587if (mode == PerfMemory::PERF_MODE_RO) {1588ofm_access = FILE_MAP_READ;1589mv_access = FILE_MAP_READ;1590}1591else if (mode == PerfMemory::PERF_MODE_RW) {1592#ifdef LATER1593ofm_access = FILE_MAP_READ | FILE_MAP_WRITE;1594mv_access = FILE_MAP_READ | FILE_MAP_WRITE;1595#else1596THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1597"Unsupported access mode");1598#endif1599}1600else {1601THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1602"Illegal access mode");1603}16041605// if a user name wasn't specified, then find the user name for1606// the owner of the target vm.1607if (user == NULL || strlen(user) == 0) {1608luser = get_user_name(vmid);1609}1610else {1611luser = user;1612}16131614if (luser == NULL) {1615THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1616"Could not map vmid to user name");1617}16181619// get the names for the resources for the target vm1620char* dirname = get_user_tmp_dir(luser);16211622// since we don't follow symbolic links when creating the backing1623// store file, we also don't following them when attaching1624//1625if (!is_directory_secure(dirname)) {1626FREE_C_HEAP_ARRAY(char, dirname);1627if (luser != user) FREE_C_HEAP_ARRAY(char, luser);1628THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1629"Process not found");1630}16311632char* filename = get_sharedmem_filename(dirname, vmid);1633char* objectname = get_sharedmem_objectname(luser, vmid);16341635// copy heap memory to resource memory. the objectname and1636// filename are passed to methods that may throw exceptions.1637// using resource arrays for these names prevents the leaks1638// that would otherwise occur.1639//1640char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);1641char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1);1642strcpy(rfilename, filename);1643strcpy(robjectname, objectname);16441645// free the c heap resources that are no longer needed1646if (luser != user) FREE_C_HEAP_ARRAY(char, luser);1647FREE_C_HEAP_ARRAY(char, dirname);1648FREE_C_HEAP_ARRAY(char, filename);1649FREE_C_HEAP_ARRAY(char, objectname);16501651if (*sizep == 0) {1652size = sharedmem_filesize(rfilename, CHECK);1653} else {1654size = *sizep;1655}16561657assert(size > 0, "unexpected size <= 0");16581659// Open the file mapping object with the given name1660fmh = open_sharedmem_object(robjectname, ofm_access, CHECK);16611662assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value");16631664// map the entire file into the address space1665mapAddress = MapViewOfFile(1666fmh, /* HANDLE Handle of file mapping object */1667mv_access, /* DWORD access flags */16680, /* DWORD High word of offset */16690, /* DWORD Low word of offset */1670size); /* DWORD Number of bytes to map */16711672if (mapAddress == NULL) {1673if (PrintMiscellaneous && Verbose) {1674warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());1675}1676CloseHandle(fmh);1677THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),1678"Could not map PerfMemory");1679}16801681// it does not go through os api, the operation has to record from here1682MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size,1683CURRENT_PC, mtInternal);168416851686*addrp = (char*)mapAddress;1687*sizep = size;16881689// File mapping object can be closed at this time without1690// invalidating the mapped view of the file1691CloseHandle(fmh);16921693log_debug(perf, memops)("mapped " SIZE_FORMAT " bytes for vmid %d at "1694INTPTR_FORMAT, size, vmid, mapAddress);1695}16961697// this method unmaps the the mapped view of the the1698// file mapping object.1699//1700static void remove_file_mapping(char* addr) {17011702// the file mapping object was closed in open_file_mapping()1703// after the file map view was created. We only need to1704// unmap the file view here.1705UnmapViewOfFile(addr);1706}17071708// create the PerfData memory region in shared memory.1709static char* create_shared_memory(size_t size) {17101711return mapping_create_shared(size);1712}17131714// release a named, shared memory region1715//1716void delete_shared_memory(char* addr, size_t size) {17171718delete_file_mapping(addr, size);1719}17201721172217231724// create the PerfData memory region1725//1726// This method creates the memory region used to store performance1727// data for the JVM. The memory may be created in standard or1728// shared memory.1729//1730void PerfMemory::create_memory_region(size_t size) {17311732if (PerfDisableSharedMem) {1733// do not share the memory for the performance data.1734PerfDisableSharedMem = true;1735_start = create_standard_memory(size);1736}1737else {1738_start = create_shared_memory(size);1739if (_start == NULL) {17401741// creation of the shared memory region failed, attempt1742// to create a contiguous, non-shared memory region instead.1743//1744if (PrintMiscellaneous && Verbose) {1745warning("Reverting to non-shared PerfMemory region.\n");1746}1747PerfDisableSharedMem = true;1748_start = create_standard_memory(size);1749}1750}17511752if (_start != NULL) _capacity = size;17531754}17551756// delete the PerfData memory region1757//1758// This method deletes the memory region used to store performance1759// data for the JVM. The memory region indicated by the <address, size>1760// tuple will be inaccessible after a call to this method.1761//1762void PerfMemory::delete_memory_region() {17631764assert((start() != NULL && capacity() > 0), "verify proper state");17651766// If user specifies PerfDataSaveFile, it will save the performance data1767// to the specified file name no matter whether PerfDataSaveToFile is specified1768// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag1769// -XX:+PerfDataSaveToFile.1770if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {1771save_memory_to_file(start(), capacity());1772}17731774if (PerfDisableSharedMem) {1775delete_standard_memory(start(), capacity());1776}1777else {1778delete_shared_memory(start(), capacity());1779}1780}17811782// attach to the PerfData memory region for another JVM1783//1784// This method returns an <address, size> tuple that points to1785// a memory buffer that is kept reasonably synchronized with1786// the PerfData memory region for the indicated JVM. This1787// buffer may be kept in synchronization via shared memory1788// or some other mechanism that keeps the buffer updated.1789//1790// If the JVM chooses not to support the attachability feature,1791// this method should throw an UnsupportedOperation exception.1792//1793// This implementation utilizes named shared memory to map1794// the indicated process's PerfData memory region into this JVMs1795// address space.1796//1797void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode,1798char** addrp, size_t* sizep, TRAPS) {17991800if (vmid == 0 || vmid == os::current_process_id()) {1801*addrp = start();1802*sizep = capacity();1803return;1804}18051806open_file_mapping(user, vmid, mode, addrp, sizep, CHECK);1807}18081809// detach from the PerfData memory region of another JVM1810//1811// This method detaches the PerfData memory region of another1812// JVM, specified as an <address, size> tuple of a buffer1813// in this process's address space. This method may perform1814// arbitrary actions to accomplish the detachment. The memory1815// region specified by <address, size> will be inaccessible after1816// a call to this method.1817//1818// If the JVM chooses not to support the attachability feature,1819// this method should throw an UnsupportedOperation exception.1820//1821// This implementation utilizes named shared memory to detach1822// the indicated process's PerfData memory region from this1823// process's address space.1824//1825void PerfMemory::detach(char* addr, size_t bytes) {18261827assert(addr != 0, "address sanity check");1828assert(bytes > 0, "capacity sanity check");18291830if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {1831// prevent accidental detachment of this process's PerfMemory region1832return;1833}18341835if (MemTracker::tracking_level() > NMT_minimal) {1836// it does not go through os api, the operation has to record from here1837Tracker tkr(Tracker::release);1838remove_file_mapping(addr);1839tkr.record((address)addr, bytes);1840} else {1841remove_file_mapping(addr);1842}1843}184418451846