perfMemory_windows.cpp revision 0:a61af66fc99e
1139823Simp/* 298402Sjulian * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved. 3143593Sglebius * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 498402Sjulian * 598402Sjulian * This code is free software; you can redistribute it and/or modify it 698402Sjulian * under the terms of the GNU General Public License version 2 only, as 798402Sjulian * published by the Free Software Foundation. 898402Sjulian * 998402Sjulian * This code is distributed in the hope that it will be useful, but WITHOUT 1098402Sjulian * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1198402Sjulian * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1298402Sjulian * version 2 for more details (a copy is included in the LICENSE file that 1398402Sjulian * accompanied this code). 1498402Sjulian * 1598402Sjulian * You should have received a copy of the GNU General Public License version 1698402Sjulian * 2 along with this work; if not, write to the Free Software Foundation, 1798402Sjulian * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1898402Sjulian * 1998402Sjulian * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 2098402Sjulian * CA 95054 USA or visit www.sun.com if you need additional information or 2198402Sjulian * have any questions. 2298402Sjulian * 2398402Sjulian */ 2498402Sjulian 2598402Sjulian# include "incls/_precompiled.incl" 2698402Sjulian# include "incls/_perfMemory_windows.cpp.incl" 27136673Sglebius 2898402Sjulian#include <windows.h> 2998402Sjulian#include <sys/types.h> 3098402Sjulian#include <sys/stat.h> 3198402Sjulian#include <errno.h> 3298402Sjulian#include <lmcons.h> 3398402Sjulian 34136673Sglebiustypedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)( 35137100Sglebius IN PSECURITY_DESCRIPTOR pSecurityDescriptor, 36136673Sglebius IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest, 37137100Sglebius IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet); 38136673Sglebius 39136673Sglebius// Standard Memory Implementation Details 4098402Sjulian 41132446Sglebius// create the PerfData memory region in standard memory. 42132446Sglebius// 4398402Sjulianstatic char* create_standard_memory(size_t size) { 44132446Sglebius 4598402Sjulian // allocate an aligned chuck of memory 46132446Sglebius char* mapAddress = os::reserve_memory(size); 47132446Sglebius 48136673Sglebius if (mapAddress == NULL) { 49132446Sglebius return NULL; 5098402Sjulian } 51136673Sglebius 5298402Sjulian // commit memory 53136673Sglebius if (!os::commit_memory(mapAddress, size)) { 54136673Sglebius if (PrintMiscellaneous && Verbose) { 55136673Sglebius warning("Could not commit PerfData memory\n"); 56136673Sglebius } 57136673Sglebius os::release_memory(mapAddress, size); 58136673Sglebius return NULL; 5998402Sjulian } 6098402Sjulian 61132446Sglebius return mapAddress; 6298402Sjulian} 63132448Sglebius 64132448Sglebius// delete the PerfData memory region 6598402Sjulian// 66141341Srustatic void delete_standard_memory(char* addr, size_t size) { 67136673Sglebius 6898402Sjulian // there are no persistent external resources to cleanup for standard 69136673Sglebius // memory. since DestroyJavaVM does not support unloading of the JVM, 7098402Sjulian // cleanup of the memory resource is not performed. The memory will be 7198402Sjulian // reclaimed by the OS upon termination of the process. 7298402Sjulian // 7398402Sjulian return; 7498402Sjulian 75136673Sglebius} 76129823Sjulian 77129823Sjulian// save the specified memory region to the given file 78141341Sru// 79136673Sglebiusstatic void save_memory_to_file(char* addr, size_t size) { 80136673Sglebius 81136673Sglebius const char* destfile = PerfMemory::get_perfdata_file_path(); 82129823Sjulian assert(destfile[0] != '\0', "invalid Perfdata file path"); 83129823Sjulian 84129823Sjulian int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC, 8598402Sjulian _S_IREAD|_S_IWRITE); 86136673Sglebius 8798402Sjulian if (fd == OS_ERR) { 88136673Sglebius if (PrintMiscellaneous && Verbose) { 89136673Sglebius warning("Could not create Perfdata save file: %s: %s\n", 90136673Sglebius destfile, strerror(errno)); 91136673Sglebius } 92136673Sglebius } else { 93136673Sglebius for (size_t remaining = size; remaining > 0;) { 94136673Sglebius 95136673Sglebius int nbytes = ::_write(fd, addr, (unsigned int)remaining); 96136673Sglebius if (nbytes == OS_ERR) { 97136673Sglebius if (PrintMiscellaneous && Verbose) { 98136673Sglebius warning("Could not write Perfdata save file: %s: %s\n", 9998402Sjulian destfile, strerror(errno)); 100136673Sglebius } 10198402Sjulian break; 102143593Sglebius } 103143593Sglebius 10498402Sjulian remaining -= (size_t)nbytes; 10598402Sjulian addr += nbytes; 106143593Sglebius } 10798402Sjulian 10898402Sjulian int result = ::_close(fd); 10998402Sjulian if (PrintMiscellaneous && Verbose) { 11098402Sjulian if (result == OS_ERR) { 11198402Sjulian warning("Could not close %s: %s\n", destfile, strerror(errno)); 112136673Sglebius } 11398402Sjulian } 114136673Sglebius } 11598402Sjulian 11698402Sjulian FREE_C_HEAP_ARRAY(char, destfile); 11798402Sjulian} 118126080Sphk 119111815Sphk// Shared Memory Implementation Details 120111815Sphk 121111815Sphk// Note: the win32 shared memory implementation uses two objects to represent 122111815Sphk// the shared memory: a windows kernel based file mapping object and a backing 123136673Sglebius// store file. On windows, the name space for shared memory is a kernel 124111815Sphk// based name space that is disjoint from other win32 name spaces. Since Java 125136673Sglebius// is unaware of this name space, a parallel file system based name space is 126111815Sphk// maintained, which provides a common file system based shared memory name 127136673Sglebius// space across the supported platforms and one that Java apps can deal with 12898402Sjulian// through simple file apis. 12998402Sjulian// 130136673Sglebius// For performance and resource cleanup reasons, it is recommended that the 131136673Sglebius// user specific directory and the backing store file be stored in either a 132136673Sglebius// RAM based file system or a local disk based file system. Network based 133136673Sglebius// file systems are not recommended for performance reasons. In addition, 134136673Sglebius// use of SMB network based file systems may result in unsuccesful cleanup 135143593Sglebius// of the disk based resource on exit of the VM. The Windows TMP and TEMP 136143593Sglebius// environement variables, as used by the GetTempPath() Win32 API (see 137143593Sglebius// os::get_temp_directory() in os_win32.cpp), control the location of the 138143593Sglebius// user specific directory and the shared memory backing store file. 139143593Sglebius 140143593Sglebiusstatic HANDLE sharedmem_fileMapHandle = NULL; 141143593Sglebiusstatic HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE; 142143593Sglebiusstatic char* sharedmem_fileName = NULL; 143143593Sglebius 144143593Sglebius// return the user specific temporary directory name. 145143593Sglebius// 146143593Sglebius// the caller is expected to free the allocated memory. 147143593Sglebius// 148143593Sglebiusstatic char* get_user_tmp_dir(const char* user) { 149143593Sglebius 150143593Sglebius const char* tmpdir = os::get_temp_directory(); 151143593Sglebius const char* perfdir = PERFDATA_NAME; 152143593Sglebius size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 2; 153143593Sglebius char* dirname = NEW_C_HEAP_ARRAY(char, nbytes); 154143593Sglebius 155143593Sglebius // construct the path name to user specific tmp directory 156143593Sglebius _snprintf(dirname, nbytes, "%s%s_%s", tmpdir, perfdir, user); 157136673Sglebius 15898402Sjulian return dirname; 15998402Sjulian} 160136673Sglebius 16198402Sjulian// convert the given file name into a process id. if the file 162136673Sglebius// does not meet the file naming constraints, return 0. 16398402Sjulian// 164137022Sglebiusstatic int filename_to_pid(const char* filename) { 16598402Sjulian 166220768Sglebius // a filename that doesn't begin with a digit is not a 16798402Sjulian // candidate for conversion. 168143593Sglebius // 169143593Sglebius if (!isdigit(*filename)) { 17098402Sjulian return 0; 171141914Sglebius } 172141914Sglebius 173141914Sglebius // check if file name can be converted to an integer without 174141914Sglebius // any leftover characters. 175141914Sglebius // 176141914Sglebius char* remainder = NULL; 177141914Sglebius errno = 0; 178141914Sglebius int pid = (int)strtol(filename, &remainder, 10); 179141914Sglebius 180183381Sed if (errno != 0) { 181136673Sglebius return 0; 182136673Sglebius } 183136673Sglebius 184136673Sglebius // check for left over characters. If any, then the filename is 185141914Sglebius // not a candidate for conversion. 186143593Sglebius // 187184205Sdes if (remainder != NULL && *remainder != '\0') { 188136673Sglebius return 0; 189136673Sglebius } 190141914Sglebius 191136673Sglebius // successful conversion, return the pid 19298402Sjulian return pid; 19398402Sjulian} 19498402Sjulian 19598402Sjulian// check if the given path is considered a secure directory for 196136673Sglebius// the backing store files. Returns true if the directory exists 197136673Sglebius// and is considered a secure location. Returns false if the path 19898402Sjulian// is a symbolic link or if an error occured. 19998402Sjulian// 20098402Sjulianstatic bool is_directory_secure(const char* path) { 20198402Sjulian 20298402Sjulian DWORD fa; 203136673Sglebius 20498402Sjulian fa = GetFileAttributes(path); 205136673Sglebius if (fa == 0xFFFFFFFF) { 206231378Sed DWORD lasterror = GetLastError(); 20798402Sjulian if (lasterror == ERROR_FILE_NOT_FOUND) { 20898402Sjulian return false; 209136673Sglebius } 21098402Sjulian else { 211136673Sglebius // unexpected error, declare the path insecure 212136673Sglebius if (PrintMiscellaneous && Verbose) { 213136673Sglebius warning("could not get attributes for file %s: ", 214143593Sglebius " lasterror = %d\n", path, lasterror); 215136673Sglebius } 216143593Sglebius return false; 21798402Sjulian } 218136673Sglebius } 219136673Sglebius 22098402Sjulian if (fa & FILE_ATTRIBUTE_REPARSE_POINT) { 221231378Sed // we don't accept any redirection for the user specific directory 222231378Sed // so declare the path insecure. This may be too conservative, 223136673Sglebius // as some types of reparse points might be acceptable, but it 22498402Sjulian // is probably more secure to avoid these conditions. 225136673Sglebius // 226136673Sglebius if (PrintMiscellaneous && Verbose) { 227136673Sglebius warning("%s is a reparse point\n", path); 22898402Sjulian } 229136673Sglebius return false; 230136673Sglebius } 23198402Sjulian 232136673Sglebius if (fa & FILE_ATTRIBUTE_DIRECTORY) { 233136673Sglebius // this is the expected case. Since windows supports symbolic 234136673Sglebius // links to directories only, not to files, there is no need 235136673Sglebius // to check for open write permissions on the directory. If the 23698402Sjulian // directory has open write permissions, any files deposited that 23798402Sjulian // are not expected will be removed by the cleanup code. 23898402Sjulian // 239136673Sglebius return true; 24098402Sjulian } 24198402Sjulian else { 24298402Sjulian // this is either a regular file or some other type of file, 24398402Sjulian // any of which are unexpected and therefore insecure. 244136673Sglebius // 24598402Sjulian if (PrintMiscellaneous && Verbose) { 246137022Sglebius warning("%s is not a directory, file attributes = " 24798402Sjulian INTPTR_FORMAT "\n", path, fa); 248136673Sglebius } 249136673Sglebius return false; 250136673Sglebius } 25198402Sjulian} 252136673Sglebius 25398402Sjulian// return the user name for the owner of this process 25498402Sjulian// 25598402Sjulian// the caller is expected to free the allocated memory. 25698402Sjulian// 25798402Sjulianstatic char* get_user_name() { 258136673Sglebius 25998402Sjulian /* get the user name. This code is adapted from code found in 26098402Sjulian * the jdk in src/windows/native/java/lang/java_props_md.c 26198402Sjulian * java_props_md.c 1.29 02/02/06. According to the original 26298402Sjulian * source, the call to GetUserName is avoided because of a resulting 263136673Sglebius * increase in footprint of 100K. 26498402Sjulian */ 26598402Sjulian char* user = getenv("USERNAME"); 266137022Sglebius char buf[UNLEN+1]; 26798402Sjulian DWORD buflen = sizeof(buf); 268132448Sglebius if (user == NULL || strlen(user) == 0) { 269132448Sglebius if (GetUserName(buf, &buflen)) { 270132448Sglebius user = buf; 271136673Sglebius } 272136673Sglebius else { 273136673Sglebius return NULL; 274136673Sglebius } 275136673Sglebius } 276136673Sglebius 27798402Sjulian char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1); 27898402Sjulian strcpy(user_name, user); 279136673Sglebius 280136673Sglebius return user_name; 281136673Sglebius} 282136673Sglebius 283136673Sglebius// return the name of the user that owns the process identified by vmid. 284136673Sglebius// 28598402Sjulian// This method uses a slow directory search algorithm to find the backing 286136673Sglebius// store file for the specified vmid and returns the user name, as determined 28798402Sjulian// by the user name suffix of the hsperfdata_<username> directory name. 288136673Sglebius// 28998402Sjulian// the caller is expected to free the allocated memory. 29098402Sjulian// 29198402Sjulianstatic char* get_user_name_slow(int vmid) { 292136673Sglebius 29398402Sjulian // directory search 29498402Sjulian char* oldest_user = NULL; 29598402Sjulian time_t oldest_ctime = 0; 29698402Sjulian 297136673Sglebius const char* tmpdirname = os::get_temp_directory(); 29898402Sjulian 299137022Sglebius DIR* tmpdirp = os::opendir(tmpdirname); 30098402Sjulian 301136673Sglebius if (tmpdirp == NULL) { 302136673Sglebius return NULL; 303132448Sglebius } 304136673Sglebius 305136673Sglebius // for each entry in the directory that matches the pattern hsperfdata_*, 30698402Sjulian // open the directory and check if the file for the given vmid exists. 307143593Sglebius // The file with the expected name and the latest creation date is used 308143593Sglebius // to determine the user name for the process id. 309184205Sdes // 31098402Sjulian struct dirent* dentry; 311136673Sglebius char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname)); 31298402Sjulian errno = 0; 31398402Sjulian while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) { 31498402Sjulian 315136673Sglebius // check if the directory entry is a hsperfdata file 31698402Sjulian if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) { 317136673Sglebius continue; 31898402Sjulian } 31998402Sjulian 320136673Sglebius char* usrdir_name = NEW_C_HEAP_ARRAY(char, 321136673Sglebius strlen(tmpdirname) + strlen(dentry->d_name) + 1); 322136673Sglebius strcpy(usrdir_name, tmpdirname); 323136673Sglebius strcat(usrdir_name, dentry->d_name); 324136673Sglebius 325136673Sglebius DIR* subdirp = os::opendir(usrdir_name); 326136673Sglebius 327136673Sglebius if (subdirp == NULL) { 328136673Sglebius FREE_C_HEAP_ARRAY(char, usrdir_name); 329136673Sglebius continue; 330136673Sglebius } 331136673Sglebius 332136673Sglebius // Since we don't create the backing store files in directories 333136673Sglebius // pointed to by symbolic links, we also don't follow them when 334130585Sphk // looking for the files. We check for a symbolic link after the 33598402Sjulian // call to opendir in order to eliminate a small window where the 336136673Sglebius // symlink can be exploited. 33798402Sjulian // 338137022Sglebius if (!is_directory_secure(usrdir_name)) { 339137022Sglebius FREE_C_HEAP_ARRAY(char, usrdir_name); 340136673Sglebius os::closedir(subdirp); 341136673Sglebius continue; 342136673Sglebius } 34398402Sjulian 34498402Sjulian struct dirent* udentry; 34598402Sjulian char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name)); 34698402Sjulian errno = 0; 34798402Sjulian while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) { 348136673Sglebius 34998402Sjulian if (filename_to_pid(udentry->d_name) == vmid) { 35098402Sjulian struct stat statbuf; 351130585Sphk 35298402Sjulian char* filename = NEW_C_HEAP_ARRAY(char, 353136673Sglebius strlen(usrdir_name) + strlen(udentry->d_name) + 2); 35498402Sjulian 355137022Sglebius strcpy(filename, usrdir_name); 356136673Sglebius strcat(filename, "\\"); 357136673Sglebius strcat(filename, udentry->d_name); 358136673Sglebius 35998402Sjulian if (::stat(filename, &statbuf) == OS_ERR) { 36098402Sjulian FREE_C_HEAP_ARRAY(char, filename); 36198402Sjulian continue; 36298402Sjulian } 363136673Sglebius 364136673Sglebius // skip over files that are not regular files. 365136673Sglebius if ((statbuf.st_mode & S_IFMT) != S_IFREG) { 366136673Sglebius FREE_C_HEAP_ARRAY(char, filename); 36798402Sjulian continue; 36898402Sjulian } 36998402Sjulian 37098402Sjulian // compare and save filename with latest creation time 371136673Sglebius if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) { 37298402Sjulian 37398402Sjulian if (statbuf.st_ctime > oldest_ctime) { 374130585Sphk char* user = strchr(dentry->d_name, '_') + 1; 37598402Sjulian 37698402Sjulian if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user); 37798402Sjulian oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1); 37898402Sjulian 37998402Sjulian strcpy(oldest_user, user); 38098402Sjulian oldest_ctime = statbuf.st_ctime; 381136673Sglebius } 38298402Sjulian } 383137022Sglebius 38498402Sjulian FREE_C_HEAP_ARRAY(char, filename); 385136673Sglebius } 38698402Sjulian } 38798402Sjulian os::closedir(subdirp); 38898402Sjulian FREE_C_HEAP_ARRAY(char, udbuf); 38998402Sjulian FREE_C_HEAP_ARRAY(char, usrdir_name); 39098402Sjulian } 39198402Sjulian os::closedir(tmpdirp); 39298402Sjulian FREE_C_HEAP_ARRAY(char, tdbuf); 39398402Sjulian 394136673Sglebius return(oldest_user); 39598402Sjulian} 396132446Sglebius 39798402Sjulian// return the name of the user that owns the process identified by vmid. 39898402Sjulian// 39998402Sjulian// note: this method should only be used via the Perf native methods. 40098402Sjulian// There are various costs to this method and limiting its use to the 40198402Sjulian// Perf native methods limits the impact to monitoring applications only. 40298402Sjulian// 40398402Sjulianstatic char* get_user_name(int vmid) { 404136673Sglebius 40598402Sjulian // A fast implementation is not provided at this time. It's possible 40698402Sjulian // to provide a fast process id to user name mapping function using 40798402Sjulian // the win32 apis, but the default ACL for the process object only 408136673Sglebius // allows processes with the same owner SID to acquire the process 40998402Sjulian // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible 41098402Sjulian // to have the JVM change the ACL for the process object to allow arbitrary 411130585Sphk // users to access the process handle and the process security token. 41298402Sjulian // The security ramifications need to be studied before providing this 413136673Sglebius // mechanism. 414136673Sglebius // 415136673Sglebius return get_user_name_slow(vmid); 41698402Sjulian} 417137022Sglebius 41898402Sjulian// return the name of the shared memory file mapping object for the 419136673Sglebius// named shared memory region for the given user name and vmid. 420136673Sglebius// 421136673Sglebius// The file mapping object's name is not the file name. It is a name 422136673Sglebius// in a separate name space. 423136673Sglebius// 424136673Sglebius// the caller is expected to free the allocated memory. 425136673Sglebius// 426136673Sglebiusstatic char *get_sharedmem_objectname(const char* user, int vmid) { 427139331Srik 428139331Srik // construct file mapping object's name, add 3 for two '_' and a 429136673Sglebius // null terminator. 430136673Sglebius int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3; 43198402Sjulian 432136673Sglebius // the id is converted to an unsigned value here because win32 allows 433136673Sglebius // negative process ids. However, OpenFileMapping API complains 434136673Sglebius // about a name containing a '-' characters. 435136673Sglebius // 436136673Sglebius nbytes += UINT_CHARS; 437136673Sglebius char* name = NEW_C_HEAP_ARRAY(char, nbytes); 438136673Sglebius _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid); 43998402Sjulian 44098402Sjulian return name; 441136673Sglebius} 442136673Sglebius 44398402Sjulian// return the file name of the backing store file for the named 444136673Sglebius// shared memory region for the given user name and vmid. 44598402Sjulian// 44698402Sjulian// the caller is expected to free the allocated memory. 44798402Sjulian// 448136673Sglebiusstatic char* get_sharedmem_filename(const char* dirname, int vmid) { 44998402Sjulian 450136673Sglebius // add 2 for the file separator and a null terminator. 45198402Sjulian size_t nbytes = strlen(dirname) + UINT_CHARS + 2; 45298402Sjulian 45398402Sjulian char* name = NEW_C_HEAP_ARRAY(char, nbytes); 454130585Sphk _snprintf(name, nbytes, "%s\\%d", dirname, vmid); 45598402Sjulian 456136673Sglebius return name; 457136673Sglebius} 45898402Sjulian 45998402Sjulian// remove file 460137022Sglebius// 46198402Sjulian// this method removes the file with the given file name. 462136673Sglebius// 463136673Sglebius// Note: if the indicated file is on an SMB network file system, this 46498402Sjulian// method may be unsuccessful in removing the file. 465136673Sglebius// 466136673Sglebiusstatic void remove_file(const char* dirname, const char* filename) { 46798402Sjulian 468243882Sglebius size_t nbytes = strlen(dirname) + strlen(filename) + 2; 469136673Sglebius char* path = NEW_C_HEAP_ARRAY(char, nbytes); 47098402Sjulian 471136673Sglebius strcpy(path, dirname); 47298402Sjulian strcat(path, "\\"); 473136673Sglebius strcat(path, filename); 47498402Sjulian 47598402Sjulian if (::unlink(path) == OS_ERR) { 47698402Sjulian if (PrintMiscellaneous && Verbose) { 47798402Sjulian if (errno != ENOENT) { 47898402Sjulian warning("Could not unlink shared memory backing" 47998402Sjulian " store file %s : %s\n", path, strerror(errno)); 48098402Sjulian } 481130585Sphk } 48298402Sjulian } 483136673Sglebius 48498402Sjulian FREE_C_HEAP_ARRAY(char, path); 48598402Sjulian} 486136673Sglebius 487136673Sglebius// returns true if the process represented by pid is alive, otherwise 488136673Sglebius// returns false. the validity of the result is only accurate if the 48998402Sjulian// target process is owned by the same principal that owns this process. 490136673Sglebius// this method should not be used if to test the status of an otherwise 491136673Sglebius// arbitrary process unless it is know that this process has the appropriate 492// privileges to guarantee a result valid. 493// 494static bool is_alive(int pid) { 495 496 HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); 497 if (ph == NULL) { 498 // the process does not exist. 499 if (PrintMiscellaneous && Verbose) { 500 DWORD lastError = GetLastError(); 501 if (lastError != ERROR_INVALID_PARAMETER) { 502 warning("OpenProcess failed: %d\n", GetLastError()); 503 } 504 } 505 return false; 506 } 507 508 DWORD exit_status; 509 if (!GetExitCodeProcess(ph, &exit_status)) { 510 if (PrintMiscellaneous && Verbose) { 511 warning("GetExitCodeProcess failed: %d\n", GetLastError()); 512 } 513 CloseHandle(ph); 514 return false; 515 } 516 517 CloseHandle(ph); 518 return (exit_status == STILL_ACTIVE) ? true : false; 519} 520 521// check if the file system is considered secure for the backing store files 522// 523static bool is_filesystem_secure(const char* path) { 524 525 char root_path[MAX_PATH]; 526 char fs_type[MAX_PATH]; 527 528 if (PerfBypassFileSystemCheck) { 529 if (PrintMiscellaneous && Verbose) { 530 warning("bypassing file system criteria checks for %s\n", path); 531 } 532 return true; 533 } 534 535 char* first_colon = strchr((char *)path, ':'); 536 if (first_colon == NULL) { 537 if (PrintMiscellaneous && Verbose) { 538 warning("expected device specifier in path: %s\n", path); 539 } 540 return false; 541 } 542 543 size_t len = (size_t)(first_colon - path); 544 assert(len + 2 <= MAX_PATH, "unexpected device specifier length"); 545 strncpy(root_path, path, len + 1); 546 root_path[len + 1] = '\\'; 547 root_path[len + 2] = '\0'; 548 549 // check that we have something like "C:\" or "AA:\" 550 assert(strlen(root_path) >= 3, "device specifier too short"); 551 assert(strchr(root_path, ':') != NULL, "bad device specifier format"); 552 assert(strchr(root_path, '\\') != NULL, "bad device specifier format"); 553 554 DWORD maxpath; 555 DWORD flags; 556 557 if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath, 558 &flags, fs_type, MAX_PATH)) { 559 // we can't get information about the volume, so assume unsafe. 560 if (PrintMiscellaneous && Verbose) { 561 warning("could not get device information for %s: " 562 " path = %s: lasterror = %d\n", 563 root_path, path, GetLastError()); 564 } 565 return false; 566 } 567 568 if ((flags & FS_PERSISTENT_ACLS) == 0) { 569 // file system doesn't support ACLs, declare file system unsafe 570 if (PrintMiscellaneous && Verbose) { 571 warning("file system type %s on device %s does not support" 572 " ACLs\n", fs_type, root_path); 573 } 574 return false; 575 } 576 577 if ((flags & FS_VOL_IS_COMPRESSED) != 0) { 578 // file system is compressed, declare file system unsafe 579 if (PrintMiscellaneous && Verbose) { 580 warning("file system type %s on device %s is compressed\n", 581 fs_type, root_path); 582 } 583 return false; 584 } 585 586 return true; 587} 588 589// cleanup stale shared memory resources 590// 591// This method attempts to remove all stale shared memory files in 592// the named user temporary directory. It scans the named directory 593// for files matching the pattern ^$[0-9]*$. For each file found, the 594// process id is extracted from the file name and a test is run to 595// determine if the process is alive. If the process is not alive, 596// any stale file resources are removed. 597// 598static void cleanup_sharedmem_resources(const char* dirname) { 599 600 // open the user temp directory 601 DIR* dirp = os::opendir(dirname); 602 603 if (dirp == NULL) { 604 // directory doesn't exist, so there is nothing to cleanup 605 return; 606 } 607 608 if (!is_directory_secure(dirname)) { 609 // the directory is not secure, don't attempt any cleanup 610 return; 611 } 612 613 // for each entry in the directory that matches the expected file 614 // name pattern, determine if the file resources are stale and if 615 // so, remove the file resources. Note, instrumented HotSpot processes 616 // for this user may start and/or terminate during this search and 617 // remove or create new files in this directory. The behavior of this 618 // loop under these conditions is dependent upon the implementation of 619 // opendir/readdir. 620 // 621 struct dirent* entry; 622 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname)); 623 errno = 0; 624 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 625 626 int pid = filename_to_pid(entry->d_name); 627 628 if (pid == 0) { 629 630 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 631 632 // attempt to remove all unexpected files, except "." and ".." 633 remove_file(dirname, entry->d_name); 634 } 635 636 errno = 0; 637 continue; 638 } 639 640 // we now have a file name that converts to a valid integer 641 // that could represent a process id . if this process id 642 // matches the current process id or the process is not running, 643 // then remove the stale file resources. 644 // 645 // process liveness is detected by checking the exit status 646 // of the process. if the process id is valid and the exit status 647 // indicates that it is still running, the file file resources 648 // are not removed. If the process id is invalid, or if we don't 649 // have permissions to check the process status, or if the process 650 // id is valid and the process has terminated, the the file resources 651 // are assumed to be stale and are removed. 652 // 653 if (pid == os::current_process_id() || !is_alive(pid)) { 654 655 // we can only remove the file resources. Any mapped views 656 // of the file can only be unmapped by the processes that 657 // opened those views and the file mapping object will not 658 // get removed until all views are unmapped. 659 // 660 remove_file(dirname, entry->d_name); 661 } 662 errno = 0; 663 } 664 os::closedir(dirp); 665 FREE_C_HEAP_ARRAY(char, dbuf); 666} 667 668// create a file mapping object with the requested name, and size 669// from the file represented by the given Handle object 670// 671static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) { 672 673 DWORD lowSize = (DWORD)size; 674 DWORD highSize = 0; 675 HANDLE fmh = NULL; 676 677 // Create a file mapping object with the given name. This function 678 // will grow the file to the specified size. 679 // 680 fmh = CreateFileMapping( 681 fh, /* HANDLE file handle for backing store */ 682 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */ 683 PAGE_READWRITE, /* DWORD protections */ 684 highSize, /* DWORD High word of max size */ 685 lowSize, /* DWORD Low word of max size */ 686 name); /* LPCTSTR name for object */ 687 688 if (fmh == NULL) { 689 if (PrintMiscellaneous && Verbose) { 690 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError()); 691 } 692 return NULL; 693 } 694 695 if (GetLastError() == ERROR_ALREADY_EXISTS) { 696 697 // a stale file mapping object was encountered. This object may be 698 // owned by this or some other user and cannot be removed until 699 // the other processes either exit or close their mapping objects 700 // and/or mapped views of this mapping object. 701 // 702 if (PrintMiscellaneous && Verbose) { 703 warning("file mapping already exists, lasterror = %d\n", GetLastError()); 704 } 705 706 CloseHandle(fmh); 707 return NULL; 708 } 709 710 return fmh; 711} 712 713 714// method to free the given security descriptor and the contained 715// access control list. 716// 717static void free_security_desc(PSECURITY_DESCRIPTOR pSD) { 718 719 BOOL success, exists, isdefault; 720 PACL pACL; 721 722 if (pSD != NULL) { 723 724 // get the access control list from the security descriptor 725 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault); 726 727 // if an ACL existed and it was not a default acl, then it must 728 // be an ACL we enlisted. free the resources. 729 // 730 if (success && exists && pACL != NULL && !isdefault) { 731 FREE_C_HEAP_ARRAY(char, pACL); 732 } 733 734 // free the security descriptor 735 FREE_C_HEAP_ARRAY(char, pSD); 736 } 737} 738 739// method to free up a security attributes structure and any 740// contained security descriptors and ACL 741// 742static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) { 743 744 if (lpSA != NULL) { 745 // free the contained security descriptor and the ACL 746 free_security_desc(lpSA->lpSecurityDescriptor); 747 lpSA->lpSecurityDescriptor = NULL; 748 749 // free the security attributes structure 750 FREE_C_HEAP_ARRAY(char, lpSA); 751 } 752} 753 754// get the user SID for the process indicated by the process handle 755// 756static PSID get_user_sid(HANDLE hProcess) { 757 758 HANDLE hAccessToken; 759 PTOKEN_USER token_buf = NULL; 760 DWORD rsize = 0; 761 762 if (hProcess == NULL) { 763 return NULL; 764 } 765 766 // get the process token 767 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) { 768 if (PrintMiscellaneous && Verbose) { 769 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError()); 770 } 771 return NULL; 772 } 773 774 // determine the size of the token structured needed to retrieve 775 // the user token information from the access token. 776 // 777 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) { 778 DWORD lasterror = GetLastError(); 779 if (lasterror != ERROR_INSUFFICIENT_BUFFER) { 780 if (PrintMiscellaneous && Verbose) { 781 warning("GetTokenInformation failure: lasterror = %d," 782 " rsize = %d\n", lasterror, rsize); 783 } 784 CloseHandle(hAccessToken); 785 return NULL; 786 } 787 } 788 789 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize); 790 791 // get the user token information 792 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) { 793 if (PrintMiscellaneous && Verbose) { 794 warning("GetTokenInformation failure: lasterror = %d," 795 " rsize = %d\n", GetLastError(), rsize); 796 } 797 FREE_C_HEAP_ARRAY(char, token_buf); 798 CloseHandle(hAccessToken); 799 return NULL; 800 } 801 802 DWORD nbytes = GetLengthSid(token_buf->User.Sid); 803 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes); 804 805 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) { 806 if (PrintMiscellaneous && Verbose) { 807 warning("GetTokenInformation failure: lasterror = %d," 808 " rsize = %d\n", GetLastError(), rsize); 809 } 810 FREE_C_HEAP_ARRAY(char, token_buf); 811 FREE_C_HEAP_ARRAY(char, pSID); 812 CloseHandle(hAccessToken); 813 return NULL; 814 } 815 816 // close the access token. 817 CloseHandle(hAccessToken); 818 FREE_C_HEAP_ARRAY(char, token_buf); 819 820 return pSID; 821} 822 823// structure used to consolidate access control entry information 824// 825typedef struct ace_data { 826 PSID pSid; // SID of the ACE 827 DWORD mask; // mask for the ACE 828} ace_data_t; 829 830 831// method to add an allow access control entry with the access rights 832// indicated in mask for the principal indicated in SID to the given 833// security descriptor. Much of the DACL handling was adapted from 834// the example provided here: 835// http://support.microsoft.com/kb/102102/EN-US/ 836// 837 838static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD, 839 ace_data_t aces[], int ace_count) { 840 PACL newACL = NULL; 841 PACL oldACL = NULL; 842 843 if (pSD == NULL) { 844 return false; 845 } 846 847 BOOL exists, isdefault; 848 849 // retrieve any existing access control list. 850 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) { 851 if (PrintMiscellaneous && Verbose) { 852 warning("GetSecurityDescriptor failure: lasterror = %d \n", 853 GetLastError()); 854 } 855 return false; 856 } 857 858 // get the size of the DACL 859 ACL_SIZE_INFORMATION aclinfo; 860 861 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent) 862 // while oldACL is NULL for some case. 863 if (oldACL == NULL) { 864 exists = FALSE; 865 } 866 867 if (exists) { 868 if (!GetAclInformation(oldACL, &aclinfo, 869 sizeof(ACL_SIZE_INFORMATION), 870 AclSizeInformation)) { 871 if (PrintMiscellaneous && Verbose) { 872 warning("GetAclInformation failure: lasterror = %d \n", GetLastError()); 873 return false; 874 } 875 } 876 } else { 877 aclinfo.AceCount = 0; // assume NULL DACL 878 aclinfo.AclBytesFree = 0; 879 aclinfo.AclBytesInUse = sizeof(ACL); 880 } 881 882 // compute the size needed for the new ACL 883 // initial size of ACL is sum of the following: 884 // * size of ACL structure. 885 // * size of each ACE structure that ACL is to contain minus the sid 886 // sidStart member (DWORD) of the ACE. 887 // * length of the SID that each ACE is to contain. 888 DWORD newACLsize = aclinfo.AclBytesInUse + 889 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count; 890 for (int i = 0; i < ace_count; i++) { 891 newACLsize += GetLengthSid(aces[i].pSid); 892 } 893 894 // create the new ACL 895 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize); 896 897 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) { 898 if (PrintMiscellaneous && Verbose) { 899 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 900 } 901 FREE_C_HEAP_ARRAY(char, newACL); 902 return false; 903 } 904 905 unsigned int ace_index = 0; 906 // copy any existing ACEs from the old ACL (if any) to the new ACL. 907 if (aclinfo.AceCount != 0) { 908 while (ace_index < aclinfo.AceCount) { 909 LPVOID ace; 910 if (!GetAce(oldACL, ace_index, &ace)) { 911 if (PrintMiscellaneous && Verbose) { 912 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 913 } 914 FREE_C_HEAP_ARRAY(char, newACL); 915 return false; 916 } 917 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) { 918 // this is an inherited, allowed ACE; break from loop so we can 919 // add the new access allowed, non-inherited ACE in the correct 920 // position, immediately following all non-inherited ACEs. 921 break; 922 } 923 924 // determine if the SID of this ACE matches any of the SIDs 925 // for which we plan to set ACEs. 926 int matches = 0; 927 for (int i = 0; i < ace_count; i++) { 928 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) { 929 matches++; 930 break; 931 } 932 } 933 934 // if there are no SID matches, then add this existing ACE to the new ACL 935 if (matches == 0) { 936 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 937 ((PACE_HEADER)ace)->AceSize)) { 938 if (PrintMiscellaneous && Verbose) { 939 warning("AddAce failure: lasterror = %d \n", GetLastError()); 940 } 941 FREE_C_HEAP_ARRAY(char, newACL); 942 return false; 943 } 944 } 945 ace_index++; 946 } 947 } 948 949 // add the passed-in access control entries to the new ACL 950 for (int i = 0; i < ace_count; i++) { 951 if (!AddAccessAllowedAce(newACL, ACL_REVISION, 952 aces[i].mask, aces[i].pSid)) { 953 if (PrintMiscellaneous && Verbose) { 954 warning("AddAccessAllowedAce failure: lasterror = %d \n", 955 GetLastError()); 956 } 957 FREE_C_HEAP_ARRAY(char, newACL); 958 return false; 959 } 960 } 961 962 // now copy the rest of the inherited ACEs from the old ACL 963 if (aclinfo.AceCount != 0) { 964 // picking up at ace_index, where we left off in the 965 // previous ace_index loop 966 while (ace_index < aclinfo.AceCount) { 967 LPVOID ace; 968 if (!GetAce(oldACL, ace_index, &ace)) { 969 if (PrintMiscellaneous && Verbose) { 970 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 971 } 972 FREE_C_HEAP_ARRAY(char, newACL); 973 return false; 974 } 975 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 976 ((PACE_HEADER)ace)->AceSize)) { 977 if (PrintMiscellaneous && Verbose) { 978 warning("AddAce failure: lasterror = %d \n", GetLastError()); 979 } 980 FREE_C_HEAP_ARRAY(char, newACL); 981 return false; 982 } 983 ace_index++; 984 } 985 } 986 987 // add the new ACL to the security descriptor. 988 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) { 989 if (PrintMiscellaneous && Verbose) { 990 warning("SetSecurityDescriptorDacl failure:" 991 " lasterror = %d \n", GetLastError()); 992 } 993 FREE_C_HEAP_ARRAY(char, newACL); 994 return false; 995 } 996 997 // if running on windows 2000 or later, set the automatic inheritence 998 // control flags. 999 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl; 1000 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr) 1001 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")), 1002 "SetSecurityDescriptorControl"); 1003 1004 if (_SetSecurityDescriptorControl != NULL) { 1005 // We do not want to further propogate inherited DACLs, so making them 1006 // protected prevents that. 1007 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, 1008 SE_DACL_PROTECTED)) { 1009 if (PrintMiscellaneous && Verbose) { 1010 warning("SetSecurityDescriptorControl failure:" 1011 " lasterror = %d \n", GetLastError()); 1012 } 1013 FREE_C_HEAP_ARRAY(char, newACL); 1014 return false; 1015 } 1016 } 1017 // Note, the security descriptor maintains a reference to the newACL, not 1018 // a copy of it. Therefore, the newACL is not freed here. It is freed when 1019 // the security descriptor containing its reference is freed. 1020 // 1021 return true; 1022} 1023 1024// method to create a security attributes structure, which contains a 1025// security descriptor and an access control list comprised of 0 or more 1026// access control entries. The method take an array of ace_data structures 1027// that indicate the ACE to be added to the security descriptor. 1028// 1029// the caller must free the resources associated with the security 1030// attributes structure created by this method by calling the 1031// free_security_attr() method. 1032// 1033static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) { 1034 1035 // allocate space for a security descriptor 1036 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) 1037 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH); 1038 1039 // initialize the security descriptor 1040 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { 1041 if (PrintMiscellaneous && Verbose) { 1042 warning("InitializeSecurityDescriptor failure: " 1043 "lasterror = %d \n", GetLastError()); 1044 } 1045 free_security_desc(pSD); 1046 return NULL; 1047 } 1048 1049 // add the access control entries 1050 if (!add_allow_aces(pSD, aces, count)) { 1051 free_security_desc(pSD); 1052 return NULL; 1053 } 1054 1055 // allocate and initialize the security attributes structure and 1056 // return it to the caller. 1057 // 1058 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES) 1059 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES)); 1060 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES); 1061 lpSA->lpSecurityDescriptor = pSD; 1062 lpSA->bInheritHandle = FALSE; 1063 1064 return(lpSA); 1065} 1066 1067// method to create a security attributes structure with a restrictive 1068// access control list that creates a set access rights for the user/owner 1069// of the securable object and a separate set access rights for everyone else. 1070// also provides for full access rights for the administrator group. 1071// 1072// the caller must free the resources associated with the security 1073// attributes structure created by this method by calling the 1074// free_security_attr() method. 1075// 1076 1077static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr( 1078 DWORD umask, DWORD emask, DWORD amask) { 1079 1080 ace_data_t aces[3]; 1081 1082 // initialize the user ace data 1083 aces[0].pSid = get_user_sid(GetCurrentProcess()); 1084 aces[0].mask = umask; 1085 1086 // get the well known SID for BUILTIN\Administrators 1087 PSID administratorsSid = NULL; 1088 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY; 1089 1090 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2, 1091 SECURITY_BUILTIN_DOMAIN_RID, 1092 DOMAIN_ALIAS_RID_ADMINS, 1093 0, 0, 0, 0, 0, 0, &administratorsSid)) { 1094 1095 if (PrintMiscellaneous && Verbose) { 1096 warning("AllocateAndInitializeSid failure: " 1097 "lasterror = %d \n", GetLastError()); 1098 } 1099 return NULL; 1100 } 1101 1102 // initialize the ace data for administrator group 1103 aces[1].pSid = administratorsSid; 1104 aces[1].mask = amask; 1105 1106 // get the well known SID for the universal Everybody 1107 PSID everybodySid = NULL; 1108 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY; 1109 1110 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID, 1111 0, 0, 0, 0, 0, 0, 0, &everybodySid)) { 1112 1113 if (PrintMiscellaneous && Verbose) { 1114 warning("AllocateAndInitializeSid failure: " 1115 "lasterror = %d \n", GetLastError()); 1116 } 1117 return NULL; 1118 } 1119 1120 // initialize the ace data for everybody else. 1121 aces[2].pSid = everybodySid; 1122 aces[2].mask = emask; 1123 1124 // create a security attributes structure with access control 1125 // entries as initialized above. 1126 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3); 1127 FREE_C_HEAP_ARRAY(char, aces[0].pSid); 1128 FreeSid(everybodySid); 1129 FreeSid(administratorsSid); 1130 return(lpSA); 1131} 1132 1133 1134// method to create the security attributes structure for restricting 1135// access to the user temporary directory. 1136// 1137// the caller must free the resources associated with the security 1138// attributes structure created by this method by calling the 1139// free_security_attr() method. 1140// 1141static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() { 1142 1143 // create full access rights for the user/owner of the directory 1144 // and read-only access rights for everybody else. This is 1145 // effectively equivalent to UNIX 755 permissions on a directory. 1146 // 1147 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS; 1148 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1149 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1150 1151 return make_user_everybody_admin_security_attr(umask, emask, amask); 1152} 1153 1154// method to create the security attributes structure for restricting 1155// access to the shared memory backing store file. 1156// 1157// the caller must free the resources associated with the security 1158// attributes structure created by this method by calling the 1159// free_security_attr() method. 1160// 1161static LPSECURITY_ATTRIBUTES make_file_security_attr() { 1162 1163 // create extensive access rights for the user/owner of the file 1164 // and attribute read-only access rights for everybody else. This 1165 // is effectively equivalent to UNIX 600 permissions on a file. 1166 // 1167 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1168 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | 1169 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1170 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1171 1172 return make_user_everybody_admin_security_attr(umask, emask, amask); 1173} 1174 1175// method to create the security attributes structure for restricting 1176// access to the name shared memory file mapping object. 1177// 1178// the caller must free the resources associated with the security 1179// attributes structure created by this method by calling the 1180// free_security_attr() method. 1181// 1182static LPSECURITY_ATTRIBUTES make_smo_security_attr() { 1183 1184 // create extensive access rights for the user/owner of the shared 1185 // memory object and attribute read-only access rights for everybody 1186 // else. This is effectively equivalent to UNIX 600 permissions on 1187 // on the shared memory object. 1188 // 1189 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS; 1190 DWORD emask = STANDARD_RIGHTS_READ; // attributes only 1191 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS; 1192 1193 return make_user_everybody_admin_security_attr(umask, emask, amask); 1194} 1195 1196// make the user specific temporary directory 1197// 1198static bool make_user_tmp_dir(const char* dirname) { 1199 1200 1201 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr(); 1202 if (pDirSA == NULL) { 1203 return false; 1204 } 1205 1206 1207 // create the directory with the given security attributes 1208 if (!CreateDirectory(dirname, pDirSA)) { 1209 DWORD lasterror = GetLastError(); 1210 if (lasterror == ERROR_ALREADY_EXISTS) { 1211 // The directory already exists and was probably created by another 1212 // JVM instance. However, this could also be the result of a 1213 // deliberate symlink. Verify that the existing directory is safe. 1214 // 1215 if (!is_directory_secure(dirname)) { 1216 // directory is not secure 1217 if (PrintMiscellaneous && Verbose) { 1218 warning("%s directory is insecure\n", dirname); 1219 } 1220 return false; 1221 } 1222 // The administrator should be able to delete this directory. 1223 // But the directory created by previous version of JVM may not 1224 // have permission for administrators to delete this directory. 1225 // So add full permission to the administrator. Also setting new 1226 // DACLs might fix the corrupted the DACLs. 1227 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1228 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) { 1229 if (PrintMiscellaneous && Verbose) { 1230 lasterror = GetLastError(); 1231 warning("SetFileSecurity failed for %s directory. lasterror %d \n", 1232 dirname, lasterror); 1233 } 1234 } 1235 } 1236 else { 1237 if (PrintMiscellaneous && Verbose) { 1238 warning("CreateDirectory failed: %d\n", GetLastError()); 1239 } 1240 return false; 1241 } 1242 } 1243 1244 // free the security attributes structure 1245 free_security_attr(pDirSA); 1246 1247 return true; 1248} 1249 1250// create the shared memory resources 1251// 1252// This function creates the shared memory resources. This includes 1253// the backing store file and the file mapping shared memory object. 1254// 1255static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) { 1256 1257 HANDLE fh = INVALID_HANDLE_VALUE; 1258 HANDLE fmh = NULL; 1259 1260 1261 // create the security attributes for the backing store file 1262 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr(); 1263 if (lpFileSA == NULL) { 1264 return NULL; 1265 } 1266 1267 // create the security attributes for the shared memory object 1268 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr(); 1269 if (lpSmoSA == NULL) { 1270 free_security_attr(lpFileSA); 1271 return NULL; 1272 } 1273 1274 // create the user temporary directory 1275 if (!make_user_tmp_dir(dirname)) { 1276 // could not make/find the directory or the found directory 1277 // was not secure 1278 return NULL; 1279 } 1280 1281 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the 1282 // file to be deleted by the last process that closes its handle to 1283 // the file. This is important as the apis do not allow a terminating 1284 // JVM being monitored by another process to remove the file name. 1285 // 1286 // the FILE_SHARE_DELETE share mode is valid only in winnt 1287 // 1288 fh = CreateFile( 1289 filename, /* LPCTSTR file name */ 1290 1291 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */ 1292 1293 (os::win32::is_nt() ? FILE_SHARE_DELETE : 0)| 1294 FILE_SHARE_READ, /* DWORD share mode, future READONLY 1295 * open operations allowed 1296 */ 1297 lpFileSA, /* LPSECURITY security attributes */ 1298 CREATE_ALWAYS, /* DWORD creation disposition 1299 * create file, if it already 1300 * exists, overwrite it. 1301 */ 1302 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */ 1303 1304 NULL); /* HANDLE template file access */ 1305 1306 free_security_attr(lpFileSA); 1307 1308 if (fh == INVALID_HANDLE_VALUE) { 1309 DWORD lasterror = GetLastError(); 1310 if (PrintMiscellaneous && Verbose) { 1311 warning("could not create file %s: %d\n", filename, lasterror); 1312 } 1313 return NULL; 1314 } 1315 1316 // try to create the file mapping 1317 fmh = create_file_mapping(objectname, fh, lpSmoSA, size); 1318 1319 free_security_attr(lpSmoSA); 1320 1321 if (fmh == NULL) { 1322 // closing the file handle here will decrement the reference count 1323 // on the file. When all processes accessing the file close their 1324 // handle to it, the reference count will decrement to 0 and the 1325 // OS will delete the file. These semantics are requested by the 1326 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above. 1327 CloseHandle(fh); 1328 fh = NULL; 1329 return NULL; 1330 } 1331 1332 // the file has been successfully created and the file mapping 1333 // object has been created. 1334 sharedmem_fileHandle = fh; 1335 sharedmem_fileName = strdup(filename); 1336 1337 return fmh; 1338} 1339 1340// open the shared memory object for the given vmid. 1341// 1342static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) { 1343 1344 HANDLE fmh; 1345 1346 // open the file mapping with the requested mode 1347 fmh = OpenFileMapping( 1348 ofm_access, /* DWORD access mode */ 1349 FALSE, /* BOOL inherit flag - Do not allow inherit */ 1350 objectname); /* name for object */ 1351 1352 if (fmh == NULL) { 1353 if (PrintMiscellaneous && Verbose) { 1354 warning("OpenFileMapping failed for shared memory object %s:" 1355 " lasterror = %d\n", objectname, GetLastError()); 1356 } 1357 THROW_MSG_(vmSymbols::java_lang_Exception(), 1358 "Could not open PerfMemory", INVALID_HANDLE_VALUE); 1359 } 1360 1361 return fmh;; 1362} 1363 1364// create a named shared memory region 1365// 1366// On Win32, a named shared memory object has a name space that 1367// is independent of the file system name space. Shared memory object, 1368// or more precisely, file mapping objects, provide no mechanism to 1369// inquire the size of the memory region. There is also no api to 1370// enumerate the memory regions for various processes. 1371// 1372// This implementation utilizes the shared memory name space in parallel 1373// with the file system name space. This allows us to determine the 1374// size of the shared memory region from the size of the file and it 1375// allows us to provide a common, file system based name space for 1376// shared memory across platforms. 1377// 1378static char* mapping_create_shared(size_t size) { 1379 1380 void *mapAddress; 1381 int vmid = os::current_process_id(); 1382 1383 // get the name of the user associated with this process 1384 char* user = get_user_name(); 1385 1386 if (user == NULL) { 1387 return NULL; 1388 } 1389 1390 // construct the name of the user specific temporary directory 1391 char* dirname = get_user_tmp_dir(user); 1392 1393 // check that the file system is secure - i.e. it supports ACLs. 1394 if (!is_filesystem_secure(dirname)) { 1395 return NULL; 1396 } 1397 1398 // create the names of the backing store files and for the 1399 // share memory object. 1400 // 1401 char* filename = get_sharedmem_filename(dirname, vmid); 1402 char* objectname = get_sharedmem_objectname(user, vmid); 1403 1404 // cleanup any stale shared memory resources 1405 cleanup_sharedmem_resources(dirname); 1406 1407 assert(((size != 0) && (size % os::vm_page_size() == 0)), 1408 "unexpected PerfMemry region size"); 1409 1410 FREE_C_HEAP_ARRAY(char, user); 1411 1412 // create the shared memory resources 1413 sharedmem_fileMapHandle = 1414 create_sharedmem_resources(dirname, filename, objectname, size); 1415 1416 FREE_C_HEAP_ARRAY(char, filename); 1417 FREE_C_HEAP_ARRAY(char, objectname); 1418 FREE_C_HEAP_ARRAY(char, dirname); 1419 1420 if (sharedmem_fileMapHandle == NULL) { 1421 return NULL; 1422 } 1423 1424 // map the file into the address space 1425 mapAddress = MapViewOfFile( 1426 sharedmem_fileMapHandle, /* HANDLE = file mapping object */ 1427 FILE_MAP_ALL_ACCESS, /* DWORD access flags */ 1428 0, /* DWORD High word of offset */ 1429 0, /* DWORD Low word of offset */ 1430 (DWORD)size); /* DWORD Number of bytes to map */ 1431 1432 if (mapAddress == NULL) { 1433 if (PrintMiscellaneous && Verbose) { 1434 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1435 } 1436 CloseHandle(sharedmem_fileMapHandle); 1437 sharedmem_fileMapHandle = NULL; 1438 return NULL; 1439 } 1440 1441 // clear the shared memory region 1442 (void)memset(mapAddress, '\0', size); 1443 1444 return (char*) mapAddress; 1445} 1446 1447// this method deletes the file mapping object. 1448// 1449static void delete_file_mapping(char* addr, size_t size) { 1450 1451 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1452 // not support unloading of the JVM, unmapping of the memory resource is not 1453 // performed. The memory will be reclaimed by the OS upon termination of all 1454 // processes mapping the resource. The file mapping handle and the file 1455 // handle are closed here to expedite the remove of the file by the OS. The 1456 // file is not removed directly because it was created with 1457 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would 1458 // be unsuccessful. 1459 1460 // close the fileMapHandle. the file mapping will still be retained 1461 // by the OS as long as any other JVM processes has an open file mapping 1462 // handle or a mapped view of the file. 1463 // 1464 if (sharedmem_fileMapHandle != NULL) { 1465 CloseHandle(sharedmem_fileMapHandle); 1466 sharedmem_fileMapHandle = NULL; 1467 } 1468 1469 // close the file handle. This will decrement the reference count on the 1470 // backing store file. When the reference count decrements to 0, the OS 1471 // will delete the file. These semantics apply because the file was 1472 // created with the FILE_FLAG_DELETE_ON_CLOSE flag. 1473 // 1474 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) { 1475 CloseHandle(sharedmem_fileHandle); 1476 sharedmem_fileHandle = INVALID_HANDLE_VALUE; 1477 } 1478} 1479 1480// this method determines the size of the shared memory file 1481// 1482static size_t sharedmem_filesize(const char* filename, TRAPS) { 1483 1484 struct stat statbuf; 1485 1486 // get the file size 1487 // 1488 // on win95/98/me, _stat returns a file size of 0 bytes, but on 1489 // winnt/2k the appropriate file size is returned. support for 1490 // the sharable aspects of performance counters was abandonded 1491 // on the non-nt win32 platforms due to this and other api 1492 // inconsistencies 1493 // 1494 if (::stat(filename, &statbuf) == OS_ERR) { 1495 if (PrintMiscellaneous && Verbose) { 1496 warning("stat %s failed: %s\n", filename, strerror(errno)); 1497 } 1498 THROW_MSG_0(vmSymbols::java_io_IOException(), 1499 "Could not determine PerfMemory size"); 1500 } 1501 1502 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) { 1503 if (PrintMiscellaneous && Verbose) { 1504 warning("unexpected file size: size = " SIZE_FORMAT "\n", 1505 statbuf.st_size); 1506 } 1507 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1508 "Invalid PerfMemory size"); 1509 } 1510 1511 return statbuf.st_size; 1512} 1513 1514// this method opens a file mapping object and maps the object 1515// into the address space of the process 1516// 1517static void open_file_mapping(const char* user, int vmid, 1518 PerfMemory::PerfMemoryMode mode, 1519 char** addrp, size_t* sizep, TRAPS) { 1520 1521 ResourceMark rm; 1522 1523 void *mapAddress = 0; 1524 size_t size; 1525 HANDLE fmh; 1526 DWORD ofm_access; 1527 DWORD mv_access; 1528 const char* luser = NULL; 1529 1530 if (mode == PerfMemory::PERF_MODE_RO) { 1531 ofm_access = FILE_MAP_READ; 1532 mv_access = FILE_MAP_READ; 1533 } 1534 else if (mode == PerfMemory::PERF_MODE_RW) { 1535#ifdef LATER 1536 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE; 1537 mv_access = FILE_MAP_READ | FILE_MAP_WRITE; 1538#else 1539 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1540 "Unsupported access mode"); 1541#endif 1542 } 1543 else { 1544 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1545 "Illegal access mode"); 1546 } 1547 1548 // if a user name wasn't specified, then find the user name for 1549 // the owner of the target vm. 1550 if (user == NULL || strlen(user) == 0) { 1551 luser = get_user_name(vmid); 1552 } 1553 else { 1554 luser = user; 1555 } 1556 1557 if (luser == NULL) { 1558 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1559 "Could not map vmid to user name"); 1560 } 1561 1562 // get the names for the resources for the target vm 1563 char* dirname = get_user_tmp_dir(luser); 1564 1565 // since we don't follow symbolic links when creating the backing 1566 // store file, we also don't following them when attaching 1567 // 1568 if (!is_directory_secure(dirname)) { 1569 FREE_C_HEAP_ARRAY(char, dirname); 1570 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1571 "Process not found"); 1572 } 1573 1574 char* filename = get_sharedmem_filename(dirname, vmid); 1575 char* objectname = get_sharedmem_objectname(luser, vmid); 1576 1577 // copy heap memory to resource memory. the objectname and 1578 // filename are passed to methods that may throw exceptions. 1579 // using resource arrays for these names prevents the leaks 1580 // that would otherwise occur. 1581 // 1582 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 1583 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1); 1584 strcpy(rfilename, filename); 1585 strcpy(robjectname, objectname); 1586 1587 // free the c heap resources that are no longer needed 1588 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 1589 FREE_C_HEAP_ARRAY(char, dirname); 1590 FREE_C_HEAP_ARRAY(char, filename); 1591 FREE_C_HEAP_ARRAY(char, objectname); 1592 1593 if (*sizep == 0) { 1594 size = sharedmem_filesize(rfilename, CHECK); 1595 assert(size != 0, "unexpected size"); 1596 } 1597 1598 // Open the file mapping object with the given name 1599 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK); 1600 1601 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value"); 1602 1603 // map the entire file into the address space 1604 mapAddress = MapViewOfFile( 1605 fmh, /* HANDLE Handle of file mapping object */ 1606 mv_access, /* DWORD access flags */ 1607 0, /* DWORD High word of offset */ 1608 0, /* DWORD Low word of offset */ 1609 size); /* DWORD Number of bytes to map */ 1610 1611 if (mapAddress == NULL) { 1612 if (PrintMiscellaneous && Verbose) { 1613 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1614 } 1615 CloseHandle(fmh); 1616 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 1617 "Could not map PerfMemory"); 1618 } 1619 1620 *addrp = (char*)mapAddress; 1621 *sizep = size; 1622 1623 // File mapping object can be closed at this time without 1624 // invalidating the mapped view of the file 1625 CloseHandle(fmh); 1626 1627 if (PerfTraceMemOps) { 1628 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 1629 INTPTR_FORMAT "\n", size, vmid, mapAddress); 1630 } 1631} 1632 1633// this method unmaps the the mapped view of the the 1634// file mapping object. 1635// 1636static void remove_file_mapping(char* addr) { 1637 1638 // the file mapping object was closed in open_file_mapping() 1639 // after the file map view was created. We only need to 1640 // unmap the file view here. 1641 UnmapViewOfFile(addr); 1642} 1643 1644// create the PerfData memory region in shared memory. 1645static char* create_shared_memory(size_t size) { 1646 1647 return mapping_create_shared(size); 1648} 1649 1650// release a named, shared memory region 1651// 1652void delete_shared_memory(char* addr, size_t size) { 1653 1654 delete_file_mapping(addr, size); 1655} 1656 1657 1658 1659 1660// create the PerfData memory region 1661// 1662// This method creates the memory region used to store performance 1663// data for the JVM. The memory may be created in standard or 1664// shared memory. 1665// 1666void PerfMemory::create_memory_region(size_t size) { 1667 1668 if (PerfDisableSharedMem || !os::win32::is_nt()) { 1669 // do not share the memory for the performance data. 1670 PerfDisableSharedMem = true; 1671 _start = create_standard_memory(size); 1672 } 1673 else { 1674 _start = create_shared_memory(size); 1675 if (_start == NULL) { 1676 1677 // creation of the shared memory region failed, attempt 1678 // to create a contiguous, non-shared memory region instead. 1679 // 1680 if (PrintMiscellaneous && Verbose) { 1681 warning("Reverting to non-shared PerfMemory region.\n"); 1682 } 1683 PerfDisableSharedMem = true; 1684 _start = create_standard_memory(size); 1685 } 1686 } 1687 1688 if (_start != NULL) _capacity = size; 1689 1690} 1691 1692// delete the PerfData memory region 1693// 1694// This method deletes the memory region used to store performance 1695// data for the JVM. The memory region indicated by the <address, size> 1696// tuple will be inaccessible after a call to this method. 1697// 1698void PerfMemory::delete_memory_region() { 1699 1700 assert((start() != NULL && capacity() > 0), "verify proper state"); 1701 1702 // If user specifies PerfDataSaveFile, it will save the performance data 1703 // to the specified file name no matter whether PerfDataSaveToFile is specified 1704 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 1705 // -XX:+PerfDataSaveToFile. 1706 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 1707 save_memory_to_file(start(), capacity()); 1708 } 1709 1710 if (PerfDisableSharedMem) { 1711 delete_standard_memory(start(), capacity()); 1712 } 1713 else { 1714 delete_shared_memory(start(), capacity()); 1715 } 1716} 1717 1718// attach to the PerfData memory region for another JVM 1719// 1720// This method returns an <address, size> tuple that points to 1721// a memory buffer that is kept reasonably synchronized with 1722// the PerfData memory region for the indicated JVM. This 1723// buffer may be kept in synchronization via shared memory 1724// or some other mechanism that keeps the buffer updated. 1725// 1726// If the JVM chooses not to support the attachability feature, 1727// this method should throw an UnsupportedOperation exception. 1728// 1729// This implementation utilizes named shared memory to map 1730// the indicated process's PerfData memory region into this JVMs 1731// address space. 1732// 1733void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, 1734 char** addrp, size_t* sizep, TRAPS) { 1735 1736 if (vmid == 0 || vmid == os::current_process_id()) { 1737 *addrp = start(); 1738 *sizep = capacity(); 1739 return; 1740 } 1741 1742 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK); 1743} 1744 1745// detach from the PerfData memory region of another JVM 1746// 1747// This method detaches the PerfData memory region of another 1748// JVM, specified as an <address, size> tuple of a buffer 1749// in this process's address space. This method may perform 1750// arbitrary actions to accomplish the detachment. The memory 1751// region specified by <address, size> will be inaccessible after 1752// a call to this method. 1753// 1754// If the JVM chooses not to support the attachability feature, 1755// this method should throw an UnsupportedOperation exception. 1756// 1757// This implementation utilizes named shared memory to detach 1758// the indicated process's PerfData memory region from this 1759// process's address space. 1760// 1761void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 1762 1763 assert(addr != 0, "address sanity check"); 1764 assert(bytes > 0, "capacity sanity check"); 1765 1766 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1767 // prevent accidental detachment of this process's PerfMemory region 1768 return; 1769 } 1770 1771 remove_file_mapping(addr); 1772} 1773 1774char* PerfMemory::backing_store_filename() { 1775 return sharedmem_fileName; 1776} 1777