perfMemory_windows.cpp revision 6856:5217fa82f1a4
1274958Sdim/* 2274958Sdim * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. 3353358Sdim * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4353358Sdim * 5353358Sdim * This code is free software; you can redistribute it and/or modify it 6274958Sdim * under the terms of the GNU General Public License version 2 only, as 7274958Sdim * published by the Free Software Foundation. 8274958Sdim * 9274958Sdim * This code is distributed in the hope that it will be useful, but WITHOUT 10274958Sdim * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11274958Sdim * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12274958Sdim * version 2 for more details (a copy is included in the LICENSE file that 13274958Sdim * accompanied this code). 14280031Sdim * 15280031Sdim * You should have received a copy of the GNU General Public License version 16274958Sdim * 2 along with this work; if not, write to the Free Software Foundation, 17288943Sdim * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18274958Sdim * 19309124Sdim * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20274958Sdim * or visit www.oracle.com if you need additional information or have any 21274958Sdim * questions. 22274958Sdim * 23274958Sdim */ 24274958Sdim 25274958Sdim#include "precompiled.hpp" 26274958Sdim#include "classfile/vmSymbols.hpp" 27274958Sdim#include "memory/allocation.inline.hpp" 28274958Sdim#include "memory/resourceArea.hpp" 29274958Sdim#include "oops/oop.inline.hpp" 30288943Sdim#include "os_windows.inline.hpp" 31296417Sdim#include "runtime/handles.inline.hpp" 32274958Sdim#include "runtime/os.hpp" 33274958Sdim#include "runtime/perfMemory.hpp" 34341825Sdim#include "services/memTracker.hpp" 35274958Sdim#include "utilities/exceptions.hpp" 36274958Sdim 37274958Sdim#include <windows.h> 38274958Sdim#include <sys/types.h> 39341825Sdim#include <sys/stat.h> 40274958Sdim#include <errno.h> 41274958Sdim#include <lmcons.h> 42341825Sdim 43296417Sdimtypedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)( 44274958Sdim IN PSECURITY_DESCRIPTOR pSecurityDescriptor, 45341825Sdim IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest, 46296417Sdim IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet); 47274958Sdim 48341825Sdim// Standard Memory Implementation Details 49296417Sdim 50274958Sdim// create the PerfData memory region in standard memory. 51344779Sdim// 52344779Sdimstatic char* create_standard_memory(size_t size) { 53344779Sdim 54360784Sdim // allocate an aligned chuck of memory 55360784Sdim char* mapAddress = os::reserve_memory(size); 56360784Sdim 57341825Sdim if (mapAddress == NULL) { 58296417Sdim return NULL; 59296417Sdim } 60341825Sdim 61296417Sdim // commit memory 62296417Sdim if (!os::commit_memory(mapAddress, size, !ExecMem)) { 63341825Sdim if (PrintMiscellaneous && Verbose) { 64296417Sdim warning("Could not commit PerfData memory\n"); 65309124Sdim } 66344779Sdim os::release_memory(mapAddress, size); 67344779Sdim return NULL; 68344779Sdim } 69341825Sdim 70309124Sdim return mapAddress; 71344779Sdim} 72344779Sdim 73344779Sdim// delete the PerfData memory region 74344779Sdim// 75344779Sdimstatic void delete_standard_memory(char* addr, size_t size) { 76344779Sdim 77274958Sdim // there are no persistent external resources to cleanup for standard 78274958Sdim // memory. since DestroyJavaVM does not support unloading of the JVM, 79341825Sdim // cleanup of the memory resource is not performed. The memory will be 80274958Sdim // reclaimed by the OS upon termination of the process. 81274958Sdim // 82341825Sdim return; 83309124Sdim 84353358Sdim} 85353358Sdim 86274958Sdim// save the specified memory region to the given file 87341825Sdim// 88353358Sdimstatic void save_memory_to_file(char* addr, size_t size) { 89274958Sdim 90341825Sdim const char* destfile = PerfMemory::get_perfdata_file_path(); 91274958Sdim assert(destfile[0] != '\0', "invalid Perfdata file path"); 92274958Sdim 93341825Sdim int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC, 94274958Sdim _S_IREAD|_S_IWRITE); 95274958Sdim 96344779Sdim if (fd == OS_ERR) { 97344779Sdim if (PrintMiscellaneous && Verbose) { 98344779Sdim warning("Could not create Perfdata save file: %s: %s\n", 99353358Sdim destfile, strerror(errno)); 100353358Sdim } 101353358Sdim } else { 102353358Sdim for (size_t remaining = size; remaining > 0;) { 103274958Sdim 104341825Sdim int nbytes = ::_write(fd, addr, (unsigned int)remaining); 105353358Sdim if (nbytes == OS_ERR) { 106341825Sdim if (PrintMiscellaneous && Verbose) { 107274958Sdim warning("Could not write Perfdata save file: %s: %s\n", 108341825Sdim destfile, strerror(errno)); 109274958Sdim } 110344779Sdim break; 111344779Sdim } 112353358Sdim 113353358Sdim remaining -= (size_t)nbytes; 114353358Sdim addr += nbytes; 115353358Sdim } 116353358Sdim 117353358Sdim int result = ::_close(fd); 118353358Sdim if (PrintMiscellaneous && Verbose) { 119353358Sdim if (result == OS_ERR) { 120353358Sdim warning("Could not close %s: %s\n", destfile, strerror(errno)); 121353358Sdim } 122353358Sdim } 123353358Sdim } 124353358Sdim 125353358Sdim FREE_C_HEAP_ARRAY(char, destfile, mtInternal); 126353358Sdim} 127353358Sdim 128353358Sdim// Shared Memory Implementation Details 129353358Sdim 130353358Sdim// Note: the win32 shared memory implementation uses two objects to represent 131353358Sdim// the shared memory: a windows kernel based file mapping object and a backing 132353358Sdim// store file. On windows, the name space for shared memory is a kernel 133353358Sdim// based name space that is disjoint from other win32 name spaces. Since Java 134353358Sdim// is unaware of this name space, a parallel file system based name space is 135353358Sdim// maintained, which provides a common file system based shared memory name 136353358Sdim// space across the supported platforms and one that Java apps can deal with 137353358Sdim// through simple file apis. 138353358Sdim// 139353358Sdim// For performance and resource cleanup reasons, it is recommended that the 140353358Sdim// user specific directory and the backing store file be stored in either a 141353358Sdim// RAM based file system or a local disk based file system. Network based 142353358Sdim// file systems are not recommended for performance reasons. In addition, 143353358Sdim// use of SMB network based file systems may result in unsuccesful cleanup 144353358Sdim// of the disk based resource on exit of the VM. The Windows TMP and TEMP 145353358Sdim// environement variables, as used by the GetTempPath() Win32 API (see 146353358Sdim// os::get_temp_directory() in os_win32.cpp), control the location of the 147353358Sdim// user specific directory and the shared memory backing store file. 148353358Sdim 149353358Sdimstatic HANDLE sharedmem_fileMapHandle = NULL; 150353358Sdimstatic HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE; 151353358Sdimstatic char* sharedmem_fileName = NULL; 152353358Sdim 153353358Sdim// return the user specific temporary directory name. 154353358Sdim// 155353358Sdim// the caller is expected to free the allocated memory. 156353358Sdim// 157353358Sdimstatic char* get_user_tmp_dir(const char* user) { 158353358Sdim 159353358Sdim const char* tmpdir = os::get_temp_directory(); 160353358Sdim const char* perfdir = PERFDATA_NAME; 161353358Sdim size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3; 162353358Sdim char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 163353358Sdim 164353358Sdim // construct the path name to user specific tmp directory 165353358Sdim _snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user); 166353358Sdim 167353358Sdim return dirname; 168353358Sdim} 169353358Sdim 170353358Sdim// convert the given file name into a process id. if the file 171353358Sdim// does not meet the file naming constraints, return 0. 172353358Sdim// 173353358Sdimstatic int filename_to_pid(const char* filename) { 174353358Sdim 175353358Sdim // a filename that doesn't begin with a digit is not a 176353358Sdim // candidate for conversion. 177353358Sdim // 178353358Sdim if (!isdigit(*filename)) { 179353358Sdim return 0; 180353358Sdim } 181353358Sdim 182353358Sdim // check if file name can be converted to an integer without 183353358Sdim // any leftover characters. 184353358Sdim // 185274958Sdim char* remainder = NULL; 186274958Sdim errno = 0; 187341825Sdim int pid = (int)strtol(filename, &remainder, 10); 188274958Sdim 189274958Sdim if (errno != 0) { 190274958Sdim return 0; 191288943Sdim } 192288943Sdim 193274958Sdim // check for left over characters. If any, then the filename is 194274958Sdim // not a candidate for conversion. 195274958Sdim // 196274958Sdim if (remainder != NULL && *remainder != '\0') { 197341825Sdim return 0; 198274958Sdim } 199314564Sdim 200314564Sdim // successful conversion, return the pid 201274958Sdim return pid; 202341825Sdim} 203296417Sdim 204296417Sdim// check if the given path is considered a secure directory for 205314564Sdim// the backing store files. Returns true if the directory exists 206314564Sdim// and is considered a secure location. Returns false if the path 207296417Sdim// is a symbolic link or if an error occurred. 208341825Sdim// 209274958Sdimstatic bool is_directory_secure(const char* path) { 210274958Sdim 211341825Sdim DWORD fa; 212274958Sdim 213274958Sdim fa = GetFileAttributes(path); 214341825Sdim if (fa == 0xFFFFFFFF) { 215274958Sdim DWORD lasterror = GetLastError(); 216274958Sdim if (lasterror == ERROR_FILE_NOT_FOUND) { 217274958Sdim return false; 218274958Sdim } 219341825Sdim else { 220274958Sdim // unexpected error, declare the path insecure 221274958Sdim if (PrintMiscellaneous && Verbose) { 222274958Sdim warning("could not get attributes for file %s: ", 223341825Sdim " lasterror = %d\n", path, lasterror); 224274958Sdim } 225274958Sdim return false; 226341825Sdim } 227296417Sdim } 228296417Sdim 229296417Sdim if (fa & FILE_ATTRIBUTE_REPARSE_POINT) { 230274958Sdim // we don't accept any redirection for the user specific directory 231274958Sdim // so declare the path insecure. This may be too conservative, 232341825Sdim // as some types of reparse points might be acceptable, but it 233309124Sdim // is probably more secure to avoid these conditions. 234309124Sdim // 235309124Sdim if (PrintMiscellaneous && Verbose) { 236309124Sdim warning("%s is a reparse point\n", path); 237309124Sdim } 238341825Sdim return false; 239296417Sdim } 240296417Sdim 241296417Sdim if (fa & FILE_ATTRIBUTE_DIRECTORY) { 242274958Sdim // this is the expected case. Since windows supports symbolic 243360784Sdim // links to directories only, not to files, there is no need 244360784Sdim // to check for open write permissions on the directory. If the 245360784Sdim // directory has open write permissions, any files deposited that 246360784Sdim // are not expected will be removed by the cleanup code. 247360784Sdim // 248344779Sdim return true; 249344779Sdim } 250344779Sdim else { 251344779Sdim // this is either a regular file or some other type of file, 252344779Sdim // any of which are unexpected and therefore insecure. 253341825Sdim // 254296417Sdim if (PrintMiscellaneous && Verbose) { 255274958Sdim warning("%s is not a directory, file attributes = " 256341825Sdim INTPTR_FORMAT "\n", path, fa); 257296417Sdim } 258296417Sdim return false; 259341825Sdim } 260296417Sdim} 261296417Sdim 262344779Sdim// return the user name for the owner of this process 263344779Sdim// 264344779Sdim// the caller is expected to free the allocated memory. 265344779Sdim// 266344779Sdimstatic char* get_user_name() { 267344779Sdim 268344779Sdim /* get the user name. This code is adapted from code found in 269344779Sdim * the jdk in src/windows/native/java/lang/java_props_md.c 270344779Sdim * java_props_md.c 1.29 02/02/06. According to the original 271344779Sdim * source, the call to GetUserName is avoided because of a resulting 272344779Sdim * increase in footprint of 100K. 273274958Sdim */ 274341825Sdim char* user = getenv("USERNAME"); 275274958Sdim char buf[UNLEN+1]; 276341825Sdim DWORD buflen = sizeof(buf); 277274958Sdim if (user == NULL || strlen(user) == 0) { 278360784Sdim if (GetUserName(buf, &buflen)) { 279341825Sdim user = buf; 280274958Sdim } 281341825Sdim else { 282360784Sdim return NULL; 283274958Sdim } 284274958Sdim } 285274958Sdim 286274958Sdim char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal); 287274958Sdim strcpy(user_name, user); 288280031Sdim 289 return user_name; 290} 291 292// return the name of the user that owns the process identified by vmid. 293// 294// This method uses a slow directory search algorithm to find the backing 295// store file for the specified vmid and returns the user name, as determined 296// by the user name suffix of the hsperfdata_<username> directory name. 297// 298// the caller is expected to free the allocated memory. 299// 300static char* get_user_name_slow(int vmid) { 301 302 // directory search 303 char* latest_user = NULL; 304 time_t latest_ctime = 0; 305 306 const char* tmpdirname = os::get_temp_directory(); 307 308 DIR* tmpdirp = os::opendir(tmpdirname); 309 310 if (tmpdirp == NULL) { 311 return NULL; 312 } 313 314 // for each entry in the directory that matches the pattern hsperfdata_*, 315 // open the directory and check if the file for the given vmid exists. 316 // The file with the expected name and the latest creation date is used 317 // to determine the user name for the process id. 318 // 319 struct dirent* dentry; 320 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal); 321 errno = 0; 322 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) { 323 324 // check if the directory entry is a hsperfdata file 325 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) { 326 continue; 327 } 328 329 char* usrdir_name = NEW_C_HEAP_ARRAY(char, 330 strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal); 331 strcpy(usrdir_name, tmpdirname); 332 strcat(usrdir_name, "\\"); 333 strcat(usrdir_name, dentry->d_name); 334 335 DIR* subdirp = os::opendir(usrdir_name); 336 337 if (subdirp == NULL) { 338 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal); 339 continue; 340 } 341 342 // Since we don't create the backing store files in directories 343 // pointed to by symbolic links, we also don't follow them when 344 // looking for the files. We check for a symbolic link after the 345 // call to opendir in order to eliminate a small window where the 346 // symlink can be exploited. 347 // 348 if (!is_directory_secure(usrdir_name)) { 349 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal); 350 os::closedir(subdirp); 351 continue; 352 } 353 354 struct dirent* udentry; 355 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal); 356 errno = 0; 357 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) { 358 359 if (filename_to_pid(udentry->d_name) == vmid) { 360 struct stat statbuf; 361 362 char* filename = NEW_C_HEAP_ARRAY(char, 363 strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal); 364 365 strcpy(filename, usrdir_name); 366 strcat(filename, "\\"); 367 strcat(filename, udentry->d_name); 368 369 if (::stat(filename, &statbuf) == OS_ERR) { 370 FREE_C_HEAP_ARRAY(char, filename, mtInternal); 371 continue; 372 } 373 374 // skip over files that are not regular files. 375 if ((statbuf.st_mode & S_IFMT) != S_IFREG) { 376 FREE_C_HEAP_ARRAY(char, filename, mtInternal); 377 continue; 378 } 379 380 // If we found a matching file with a newer creation time, then 381 // save the user name. The newer creation time indicates that 382 // we found a newer incarnation of the process associated with 383 // vmid. Due to the way that Windows recycles pids and the fact 384 // that we can't delete the file from the file system namespace 385 // until last close, it is possible for there to be more than 386 // one hsperfdata file with a name matching vmid (diff users). 387 // 388 // We no longer ignore hsperfdata files where (st_size == 0). 389 // In this function, all we're trying to do is determine the 390 // name of the user that owns the process associated with vmid 391 // so the size doesn't matter. Very rarely, we have observed 392 // hsperfdata files where (st_size == 0) and the st_size field 393 // later becomes the expected value. 394 // 395 if (statbuf.st_ctime > latest_ctime) { 396 char* user = strchr(dentry->d_name, '_') + 1; 397 398 if (latest_user != NULL) FREE_C_HEAP_ARRAY(char, latest_user, mtInternal); 399 latest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal); 400 401 strcpy(latest_user, user); 402 latest_ctime = statbuf.st_ctime; 403 } 404 405 FREE_C_HEAP_ARRAY(char, filename, mtInternal); 406 } 407 } 408 os::closedir(subdirp); 409 FREE_C_HEAP_ARRAY(char, udbuf, mtInternal); 410 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal); 411 } 412 os::closedir(tmpdirp); 413 FREE_C_HEAP_ARRAY(char, tdbuf, mtInternal); 414 415 return(latest_user); 416} 417 418// return the name of the user that owns the process identified by vmid. 419// 420// note: this method should only be used via the Perf native methods. 421// There are various costs to this method and limiting its use to the 422// Perf native methods limits the impact to monitoring applications only. 423// 424static char* get_user_name(int vmid) { 425 426 // A fast implementation is not provided at this time. It's possible 427 // to provide a fast process id to user name mapping function using 428 // the win32 apis, but the default ACL for the process object only 429 // allows processes with the same owner SID to acquire the process 430 // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible 431 // to have the JVM change the ACL for the process object to allow arbitrary 432 // users to access the process handle and the process security token. 433 // The security ramifications need to be studied before providing this 434 // mechanism. 435 // 436 return get_user_name_slow(vmid); 437} 438 439// return the name of the shared memory file mapping object for the 440// named shared memory region for the given user name and vmid. 441// 442// The file mapping object's name is not the file name. It is a name 443// in a separate name space. 444// 445// the caller is expected to free the allocated memory. 446// 447static char *get_sharedmem_objectname(const char* user, int vmid) { 448 449 // construct file mapping object's name, add 3 for two '_' and a 450 // null terminator. 451 int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3; 452 453 // the id is converted to an unsigned value here because win32 allows 454 // negative process ids. However, OpenFileMapping API complains 455 // about a name containing a '-' characters. 456 // 457 nbytes += UINT_CHARS; 458 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 459 _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid); 460 461 return name; 462} 463 464// return the file name of the backing store file for the named 465// shared memory region for the given user name and vmid. 466// 467// the caller is expected to free the allocated memory. 468// 469static char* get_sharedmem_filename(const char* dirname, int vmid) { 470 471 // add 2 for the file separator and a null terminator. 472 size_t nbytes = strlen(dirname) + UINT_CHARS + 2; 473 474 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 475 _snprintf(name, nbytes, "%s\\%d", dirname, vmid); 476 477 return name; 478} 479 480// remove file 481// 482// this method removes the file with the given file name. 483// 484// Note: if the indicated file is on an SMB network file system, this 485// method may be unsuccessful in removing the file. 486// 487static void remove_file(const char* dirname, const char* filename) { 488 489 size_t nbytes = strlen(dirname) + strlen(filename) + 2; 490 char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 491 492 strcpy(path, dirname); 493 strcat(path, "\\"); 494 strcat(path, filename); 495 496 if (::unlink(path) == OS_ERR) { 497 if (PrintMiscellaneous && Verbose) { 498 if (errno != ENOENT) { 499 warning("Could not unlink shared memory backing" 500 " store file %s : %s\n", path, strerror(errno)); 501 } 502 } 503 } 504 505 FREE_C_HEAP_ARRAY(char, path, mtInternal); 506} 507 508// returns true if the process represented by pid is alive, otherwise 509// returns false. the validity of the result is only accurate if the 510// target process is owned by the same principal that owns this process. 511// this method should not be used if to test the status of an otherwise 512// arbitrary process unless it is know that this process has the appropriate 513// privileges to guarantee a result valid. 514// 515static bool is_alive(int pid) { 516 517 HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); 518 if (ph == NULL) { 519 // the process does not exist. 520 if (PrintMiscellaneous && Verbose) { 521 DWORD lastError = GetLastError(); 522 if (lastError != ERROR_INVALID_PARAMETER) { 523 warning("OpenProcess failed: %d\n", GetLastError()); 524 } 525 } 526 return false; 527 } 528 529 DWORD exit_status; 530 if (!GetExitCodeProcess(ph, &exit_status)) { 531 if (PrintMiscellaneous && Verbose) { 532 warning("GetExitCodeProcess failed: %d\n", GetLastError()); 533 } 534 CloseHandle(ph); 535 return false; 536 } 537 538 CloseHandle(ph); 539 return (exit_status == STILL_ACTIVE) ? true : false; 540} 541 542// check if the file system is considered secure for the backing store files 543// 544static bool is_filesystem_secure(const char* path) { 545 546 char root_path[MAX_PATH]; 547 char fs_type[MAX_PATH]; 548 549 if (PerfBypassFileSystemCheck) { 550 if (PrintMiscellaneous && Verbose) { 551 warning("bypassing file system criteria checks for %s\n", path); 552 } 553 return true; 554 } 555 556 char* first_colon = strchr((char *)path, ':'); 557 if (first_colon == NULL) { 558 if (PrintMiscellaneous && Verbose) { 559 warning("expected device specifier in path: %s\n", path); 560 } 561 return false; 562 } 563 564 size_t len = (size_t)(first_colon - path); 565 assert(len + 2 <= MAX_PATH, "unexpected device specifier length"); 566 strncpy(root_path, path, len + 1); 567 root_path[len + 1] = '\\'; 568 root_path[len + 2] = '\0'; 569 570 // check that we have something like "C:\" or "AA:\" 571 assert(strlen(root_path) >= 3, "device specifier too short"); 572 assert(strchr(root_path, ':') != NULL, "bad device specifier format"); 573 assert(strchr(root_path, '\\') != NULL, "bad device specifier format"); 574 575 DWORD maxpath; 576 DWORD flags; 577 578 if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath, 579 &flags, fs_type, MAX_PATH)) { 580 // we can't get information about the volume, so assume unsafe. 581 if (PrintMiscellaneous && Verbose) { 582 warning("could not get device information for %s: " 583 " path = %s: lasterror = %d\n", 584 root_path, path, GetLastError()); 585 } 586 return false; 587 } 588 589 if ((flags & FS_PERSISTENT_ACLS) == 0) { 590 // file system doesn't support ACLs, declare file system unsafe 591 if (PrintMiscellaneous && Verbose) { 592 warning("file system type %s on device %s does not support" 593 " ACLs\n", fs_type, root_path); 594 } 595 return false; 596 } 597 598 if ((flags & FS_VOL_IS_COMPRESSED) != 0) { 599 // file system is compressed, declare file system unsafe 600 if (PrintMiscellaneous && Verbose) { 601 warning("file system type %s on device %s is compressed\n", 602 fs_type, root_path); 603 } 604 return false; 605 } 606 607 return true; 608} 609 610// cleanup stale shared memory resources 611// 612// This method attempts to remove all stale shared memory files in 613// the named user temporary directory. It scans the named directory 614// for files matching the pattern ^$[0-9]*$. For each file found, the 615// process id is extracted from the file name and a test is run to 616// determine if the process is alive. If the process is not alive, 617// any stale file resources are removed. 618// 619static void cleanup_sharedmem_resources(const char* dirname) { 620 621 // open the user temp directory 622 DIR* dirp = os::opendir(dirname); 623 624 if (dirp == NULL) { 625 // directory doesn't exist, so there is nothing to cleanup 626 return; 627 } 628 629 if (!is_directory_secure(dirname)) { 630 // the directory is not secure, don't attempt any cleanup 631 return; 632 } 633 634 // for each entry in the directory that matches the expected file 635 // name pattern, determine if the file resources are stale and if 636 // so, remove the file resources. Note, instrumented HotSpot processes 637 // for this user may start and/or terminate during this search and 638 // remove or create new files in this directory. The behavior of this 639 // loop under these conditions is dependent upon the implementation of 640 // opendir/readdir. 641 // 642 struct dirent* entry; 643 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal); 644 errno = 0; 645 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 646 647 int pid = filename_to_pid(entry->d_name); 648 649 if (pid == 0) { 650 651 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 652 653 // attempt to remove all unexpected files, except "." and ".." 654 remove_file(dirname, entry->d_name); 655 } 656 657 errno = 0; 658 continue; 659 } 660 661 // we now have a file name that converts to a valid integer 662 // that could represent a process id . if this process id 663 // matches the current process id or the process is not running, 664 // then remove the stale file resources. 665 // 666 // process liveness is detected by checking the exit status 667 // of the process. if the process id is valid and the exit status 668 // indicates that it is still running, the file file resources 669 // are not removed. If the process id is invalid, or if we don't 670 // have permissions to check the process status, or if the process 671 // id is valid and the process has terminated, the the file resources 672 // are assumed to be stale and are removed. 673 // 674 if (pid == os::current_process_id() || !is_alive(pid)) { 675 676 // we can only remove the file resources. Any mapped views 677 // of the file can only be unmapped by the processes that 678 // opened those views and the file mapping object will not 679 // get removed until all views are unmapped. 680 // 681 remove_file(dirname, entry->d_name); 682 } 683 errno = 0; 684 } 685 os::closedir(dirp); 686 FREE_C_HEAP_ARRAY(char, dbuf, mtInternal); 687} 688 689// create a file mapping object with the requested name, and size 690// from the file represented by the given Handle object 691// 692static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) { 693 694 DWORD lowSize = (DWORD)size; 695 DWORD highSize = 0; 696 HANDLE fmh = NULL; 697 698 // Create a file mapping object with the given name. This function 699 // will grow the file to the specified size. 700 // 701 fmh = CreateFileMapping( 702 fh, /* HANDLE file handle for backing store */ 703 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */ 704 PAGE_READWRITE, /* DWORD protections */ 705 highSize, /* DWORD High word of max size */ 706 lowSize, /* DWORD Low word of max size */ 707 name); /* LPCTSTR name for object */ 708 709 if (fmh == NULL) { 710 if (PrintMiscellaneous && Verbose) { 711 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError()); 712 } 713 return NULL; 714 } 715 716 if (GetLastError() == ERROR_ALREADY_EXISTS) { 717 718 // a stale file mapping object was encountered. This object may be 719 // owned by this or some other user and cannot be removed until 720 // the other processes either exit or close their mapping objects 721 // and/or mapped views of this mapping object. 722 // 723 if (PrintMiscellaneous && Verbose) { 724 warning("file mapping already exists, lasterror = %d\n", GetLastError()); 725 } 726 727 CloseHandle(fmh); 728 return NULL; 729 } 730 731 return fmh; 732} 733 734 735// method to free the given security descriptor and the contained 736// access control list. 737// 738static void free_security_desc(PSECURITY_DESCRIPTOR pSD) { 739 740 BOOL success, exists, isdefault; 741 PACL pACL; 742 743 if (pSD != NULL) { 744 745 // get the access control list from the security descriptor 746 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault); 747 748 // if an ACL existed and it was not a default acl, then it must 749 // be an ACL we enlisted. free the resources. 750 // 751 if (success && exists && pACL != NULL && !isdefault) { 752 FREE_C_HEAP_ARRAY(char, pACL, mtInternal); 753 } 754 755 // free the security descriptor 756 FREE_C_HEAP_ARRAY(char, pSD, mtInternal); 757 } 758} 759 760// method to free up a security attributes structure and any 761// contained security descriptors and ACL 762// 763static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) { 764 765 if (lpSA != NULL) { 766 // free the contained security descriptor and the ACL 767 free_security_desc(lpSA->lpSecurityDescriptor); 768 lpSA->lpSecurityDescriptor = NULL; 769 770 // free the security attributes structure 771 FREE_C_HEAP_ARRAY(char, lpSA, mtInternal); 772 } 773} 774 775// get the user SID for the process indicated by the process handle 776// 777static PSID get_user_sid(HANDLE hProcess) { 778 779 HANDLE hAccessToken; 780 PTOKEN_USER token_buf = NULL; 781 DWORD rsize = 0; 782 783 if (hProcess == NULL) { 784 return NULL; 785 } 786 787 // get the process token 788 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) { 789 if (PrintMiscellaneous && Verbose) { 790 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError()); 791 } 792 return NULL; 793 } 794 795 // determine the size of the token structured needed to retrieve 796 // the user token information from the access token. 797 // 798 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) { 799 DWORD lasterror = GetLastError(); 800 if (lasterror != ERROR_INSUFFICIENT_BUFFER) { 801 if (PrintMiscellaneous && Verbose) { 802 warning("GetTokenInformation failure: lasterror = %d," 803 " rsize = %d\n", lasterror, rsize); 804 } 805 CloseHandle(hAccessToken); 806 return NULL; 807 } 808 } 809 810 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal); 811 812 // get the user token information 813 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) { 814 if (PrintMiscellaneous && Verbose) { 815 warning("GetTokenInformation failure: lasterror = %d," 816 " rsize = %d\n", GetLastError(), rsize); 817 } 818 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal); 819 CloseHandle(hAccessToken); 820 return NULL; 821 } 822 823 DWORD nbytes = GetLengthSid(token_buf->User.Sid); 824 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 825 826 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) { 827 if (PrintMiscellaneous && Verbose) { 828 warning("GetTokenInformation failure: lasterror = %d," 829 " rsize = %d\n", GetLastError(), rsize); 830 } 831 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal); 832 FREE_C_HEAP_ARRAY(char, pSID, mtInternal); 833 CloseHandle(hAccessToken); 834 return NULL; 835 } 836 837 // close the access token. 838 CloseHandle(hAccessToken); 839 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal); 840 841 return pSID; 842} 843 844// structure used to consolidate access control entry information 845// 846typedef struct ace_data { 847 PSID pSid; // SID of the ACE 848 DWORD mask; // mask for the ACE 849} ace_data_t; 850 851 852// method to add an allow access control entry with the access rights 853// indicated in mask for the principal indicated in SID to the given 854// security descriptor. Much of the DACL handling was adapted from 855// the example provided here: 856// http://support.microsoft.com/kb/102102/EN-US/ 857// 858 859static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD, 860 ace_data_t aces[], int ace_count) { 861 PACL newACL = NULL; 862 PACL oldACL = NULL; 863 864 if (pSD == NULL) { 865 return false; 866 } 867 868 BOOL exists, isdefault; 869 870 // retrieve any existing access control list. 871 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) { 872 if (PrintMiscellaneous && Verbose) { 873 warning("GetSecurityDescriptor failure: lasterror = %d \n", 874 GetLastError()); 875 } 876 return false; 877 } 878 879 // get the size of the DACL 880 ACL_SIZE_INFORMATION aclinfo; 881 882 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent) 883 // while oldACL is NULL for some case. 884 if (oldACL == NULL) { 885 exists = FALSE; 886 } 887 888 if (exists) { 889 if (!GetAclInformation(oldACL, &aclinfo, 890 sizeof(ACL_SIZE_INFORMATION), 891 AclSizeInformation)) { 892 if (PrintMiscellaneous && Verbose) { 893 warning("GetAclInformation failure: lasterror = %d \n", GetLastError()); 894 return false; 895 } 896 } 897 } else { 898 aclinfo.AceCount = 0; // assume NULL DACL 899 aclinfo.AclBytesFree = 0; 900 aclinfo.AclBytesInUse = sizeof(ACL); 901 } 902 903 // compute the size needed for the new ACL 904 // initial size of ACL is sum of the following: 905 // * size of ACL structure. 906 // * size of each ACE structure that ACL is to contain minus the sid 907 // sidStart member (DWORD) of the ACE. 908 // * length of the SID that each ACE is to contain. 909 DWORD newACLsize = aclinfo.AclBytesInUse + 910 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count; 911 for (int i = 0; i < ace_count; i++) { 912 assert(aces[i].pSid != 0, "pSid should not be 0"); 913 newACLsize += GetLengthSid(aces[i].pSid); 914 } 915 916 // create the new ACL 917 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal); 918 919 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) { 920 if (PrintMiscellaneous && Verbose) { 921 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 922 } 923 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 924 return false; 925 } 926 927 unsigned int ace_index = 0; 928 // copy any existing ACEs from the old ACL (if any) to the new ACL. 929 if (aclinfo.AceCount != 0) { 930 while (ace_index < aclinfo.AceCount) { 931 LPVOID ace; 932 if (!GetAce(oldACL, ace_index, &ace)) { 933 if (PrintMiscellaneous && Verbose) { 934 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 935 } 936 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 937 return false; 938 } 939 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) { 940 // this is an inherited, allowed ACE; break from loop so we can 941 // add the new access allowed, non-inherited ACE in the correct 942 // position, immediately following all non-inherited ACEs. 943 break; 944 } 945 946 // determine if the SID of this ACE matches any of the SIDs 947 // for which we plan to set ACEs. 948 int matches = 0; 949 for (int i = 0; i < ace_count; i++) { 950 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) { 951 matches++; 952 break; 953 } 954 } 955 956 // if there are no SID matches, then add this existing ACE to the new ACL 957 if (matches == 0) { 958 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 959 ((PACE_HEADER)ace)->AceSize)) { 960 if (PrintMiscellaneous && Verbose) { 961 warning("AddAce failure: lasterror = %d \n", GetLastError()); 962 } 963 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 964 return false; 965 } 966 } 967 ace_index++; 968 } 969 } 970 971 // add the passed-in access control entries to the new ACL 972 for (int i = 0; i < ace_count; i++) { 973 if (!AddAccessAllowedAce(newACL, ACL_REVISION, 974 aces[i].mask, aces[i].pSid)) { 975 if (PrintMiscellaneous && Verbose) { 976 warning("AddAccessAllowedAce failure: lasterror = %d \n", 977 GetLastError()); 978 } 979 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 980 return false; 981 } 982 } 983 984 // now copy the rest of the inherited ACEs from the old ACL 985 if (aclinfo.AceCount != 0) { 986 // picking up at ace_index, where we left off in the 987 // previous ace_index loop 988 while (ace_index < aclinfo.AceCount) { 989 LPVOID ace; 990 if (!GetAce(oldACL, ace_index, &ace)) { 991 if (PrintMiscellaneous && Verbose) { 992 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 993 } 994 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 995 return false; 996 } 997 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 998 ((PACE_HEADER)ace)->AceSize)) { 999 if (PrintMiscellaneous && Verbose) { 1000 warning("AddAce failure: lasterror = %d \n", GetLastError()); 1001 } 1002 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 1003 return false; 1004 } 1005 ace_index++; 1006 } 1007 } 1008 1009 // add the new ACL to the security descriptor. 1010 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) { 1011 if (PrintMiscellaneous && Verbose) { 1012 warning("SetSecurityDescriptorDacl failure:" 1013 " lasterror = %d \n", GetLastError()); 1014 } 1015 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 1016 return false; 1017 } 1018 1019 // if running on windows 2000 or later, set the automatic inheritance 1020 // control flags. 1021 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl; 1022 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr) 1023 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")), 1024 "SetSecurityDescriptorControl"); 1025 1026 if (_SetSecurityDescriptorControl != NULL) { 1027 // We do not want to further propagate inherited DACLs, so making them 1028 // protected prevents that. 1029 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, 1030 SE_DACL_PROTECTED)) { 1031 if (PrintMiscellaneous && Verbose) { 1032 warning("SetSecurityDescriptorControl failure:" 1033 " lasterror = %d \n", GetLastError()); 1034 } 1035 FREE_C_HEAP_ARRAY(char, newACL, mtInternal); 1036 return false; 1037 } 1038 } 1039 // Note, the security descriptor maintains a reference to the newACL, not 1040 // a copy of it. Therefore, the newACL is not freed here. It is freed when 1041 // the security descriptor containing its reference is freed. 1042 // 1043 return true; 1044} 1045 1046// method to create a security attributes structure, which contains a 1047// security descriptor and an access control list comprised of 0 or more 1048// access control entries. The method take an array of ace_data structures 1049// that indicate the ACE to be added to the security descriptor. 1050// 1051// the caller must free the resources associated with the security 1052// attributes structure created by this method by calling the 1053// free_security_attr() method. 1054// 1055static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) { 1056 1057 // allocate space for a security descriptor 1058 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) 1059 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal); 1060 1061 // initialize the security descriptor 1062 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { 1063 if (PrintMiscellaneous && Verbose) { 1064 warning("InitializeSecurityDescriptor failure: " 1065 "lasterror = %d \n", GetLastError()); 1066 } 1067 free_security_desc(pSD); 1068 return NULL; 1069 } 1070 1071 // add the access control entries 1072 if (!add_allow_aces(pSD, aces, count)) { 1073 free_security_desc(pSD); 1074 return NULL; 1075 } 1076 1077 // allocate and initialize the security attributes structure and 1078 // return it to the caller. 1079 // 1080 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES) 1081 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES), mtInternal); 1082 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES); 1083 lpSA->lpSecurityDescriptor = pSD; 1084 lpSA->bInheritHandle = FALSE; 1085 1086 return(lpSA); 1087} 1088 1089// method to create a security attributes structure with a restrictive 1090// access control list that creates a set access rights for the user/owner 1091// of the securable object and a separate set access rights for everyone else. 1092// also provides for full access rights for the administrator group. 1093// 1094// the caller must free the resources associated with the security 1095// attributes structure created by this method by calling the 1096// free_security_attr() method. 1097// 1098 1099static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr( 1100 DWORD umask, DWORD emask, DWORD amask) { 1101 1102 ace_data_t aces[3]; 1103 1104 // initialize the user ace data 1105 aces[0].pSid = get_user_sid(GetCurrentProcess()); 1106 aces[0].mask = umask; 1107 1108 if (aces[0].pSid == 0) 1109 return NULL; 1110 1111 // get the well known SID for BUILTIN\Administrators 1112 PSID administratorsSid = NULL; 1113 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY; 1114 1115 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2, 1116 SECURITY_BUILTIN_DOMAIN_RID, 1117 DOMAIN_ALIAS_RID_ADMINS, 1118 0, 0, 0, 0, 0, 0, &administratorsSid)) { 1119 1120 if (PrintMiscellaneous && Verbose) { 1121 warning("AllocateAndInitializeSid failure: " 1122 "lasterror = %d \n", GetLastError()); 1123 } 1124 return NULL; 1125 } 1126 1127 // initialize the ace data for administrator group 1128 aces[1].pSid = administratorsSid; 1129 aces[1].mask = amask; 1130 1131 // get the well known SID for the universal Everybody 1132 PSID everybodySid = NULL; 1133 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY; 1134 1135 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID, 1136 0, 0, 0, 0, 0, 0, 0, &everybodySid)) { 1137 1138 if (PrintMiscellaneous && Verbose) { 1139 warning("AllocateAndInitializeSid failure: " 1140 "lasterror = %d \n", GetLastError()); 1141 } 1142 return NULL; 1143 } 1144 1145 // initialize the ace data for everybody else. 1146 aces[2].pSid = everybodySid; 1147 aces[2].mask = emask; 1148 1149 // create a security attributes structure with access control 1150 // entries as initialized above. 1151 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3); 1152 FREE_C_HEAP_ARRAY(char, aces[0].pSid, mtInternal); 1153 FreeSid(everybodySid); 1154 FreeSid(administratorsSid); 1155 return(lpSA); 1156} 1157 1158 1159// method to create the security attributes structure for restricting 1160// access to the user temporary directory. 1161// 1162// the caller must free the resources associated with the security 1163// attributes structure created by this method by calling the 1164// free_security_attr() method. 1165// 1166static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() { 1167 1168 // create full access rights for the user/owner of the directory 1169 // and read-only access rights for everybody else. This is 1170 // effectively equivalent to UNIX 755 permissions on a directory. 1171 // 1172 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS; 1173 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1174 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1175 1176 return make_user_everybody_admin_security_attr(umask, emask, amask); 1177} 1178 1179// method to create the security attributes structure for restricting 1180// access to the shared memory backing store file. 1181// 1182// the caller must free the resources associated with the security 1183// attributes structure created by this method by calling the 1184// free_security_attr() method. 1185// 1186static LPSECURITY_ATTRIBUTES make_file_security_attr() { 1187 1188 // create extensive access rights for the user/owner of the file 1189 // and attribute read-only access rights for everybody else. This 1190 // is effectively equivalent to UNIX 600 permissions on a file. 1191 // 1192 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1193 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | 1194 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1195 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1196 1197 return make_user_everybody_admin_security_attr(umask, emask, amask); 1198} 1199 1200// method to create the security attributes structure for restricting 1201// access to the name shared memory file mapping object. 1202// 1203// the caller must free the resources associated with the security 1204// attributes structure created by this method by calling the 1205// free_security_attr() method. 1206// 1207static LPSECURITY_ATTRIBUTES make_smo_security_attr() { 1208 1209 // create extensive access rights for the user/owner of the shared 1210 // memory object and attribute read-only access rights for everybody 1211 // else. This is effectively equivalent to UNIX 600 permissions on 1212 // on the shared memory object. 1213 // 1214 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS; 1215 DWORD emask = STANDARD_RIGHTS_READ; // attributes only 1216 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS; 1217 1218 return make_user_everybody_admin_security_attr(umask, emask, amask); 1219} 1220 1221// make the user specific temporary directory 1222// 1223static bool make_user_tmp_dir(const char* dirname) { 1224 1225 1226 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr(); 1227 if (pDirSA == NULL) { 1228 return false; 1229 } 1230 1231 1232 // create the directory with the given security attributes 1233 if (!CreateDirectory(dirname, pDirSA)) { 1234 DWORD lasterror = GetLastError(); 1235 if (lasterror == ERROR_ALREADY_EXISTS) { 1236 // The directory already exists and was probably created by another 1237 // JVM instance. However, this could also be the result of a 1238 // deliberate symlink. Verify that the existing directory is safe. 1239 // 1240 if (!is_directory_secure(dirname)) { 1241 // directory is not secure 1242 if (PrintMiscellaneous && Verbose) { 1243 warning("%s directory is insecure\n", dirname); 1244 } 1245 return false; 1246 } 1247 // The administrator should be able to delete this directory. 1248 // But the directory created by previous version of JVM may not 1249 // have permission for administrators to delete this directory. 1250 // So add full permission to the administrator. Also setting new 1251 // DACLs might fix the corrupted the DACLs. 1252 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1253 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) { 1254 if (PrintMiscellaneous && Verbose) { 1255 lasterror = GetLastError(); 1256 warning("SetFileSecurity failed for %s directory. lasterror %d \n", 1257 dirname, lasterror); 1258 } 1259 } 1260 } 1261 else { 1262 if (PrintMiscellaneous && Verbose) { 1263 warning("CreateDirectory failed: %d\n", GetLastError()); 1264 } 1265 return false; 1266 } 1267 } 1268 1269 // free the security attributes structure 1270 free_security_attr(pDirSA); 1271 1272 return true; 1273} 1274 1275// create the shared memory resources 1276// 1277// This function creates the shared memory resources. This includes 1278// the backing store file and the file mapping shared memory object. 1279// 1280static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) { 1281 1282 HANDLE fh = INVALID_HANDLE_VALUE; 1283 HANDLE fmh = NULL; 1284 1285 1286 // create the security attributes for the backing store file 1287 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr(); 1288 if (lpFileSA == NULL) { 1289 return NULL; 1290 } 1291 1292 // create the security attributes for the shared memory object 1293 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr(); 1294 if (lpSmoSA == NULL) { 1295 free_security_attr(lpFileSA); 1296 return NULL; 1297 } 1298 1299 // create the user temporary directory 1300 if (!make_user_tmp_dir(dirname)) { 1301 // could not make/find the directory or the found directory 1302 // was not secure 1303 return NULL; 1304 } 1305 1306 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the 1307 // file to be deleted by the last process that closes its handle to 1308 // the file. This is important as the apis do not allow a terminating 1309 // JVM being monitored by another process to remove the file name. 1310 // 1311 // the FILE_SHARE_DELETE share mode is valid only in winnt 1312 // 1313 fh = CreateFile( 1314 filename, /* LPCTSTR file name */ 1315 1316 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */ 1317 1318 (os::win32::is_nt() ? FILE_SHARE_DELETE : 0)| 1319 FILE_SHARE_READ, /* DWORD share mode, future READONLY 1320 * open operations allowed 1321 */ 1322 lpFileSA, /* LPSECURITY security attributes */ 1323 CREATE_ALWAYS, /* DWORD creation disposition 1324 * create file, if it already 1325 * exists, overwrite it. 1326 */ 1327 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */ 1328 1329 NULL); /* HANDLE template file access */ 1330 1331 free_security_attr(lpFileSA); 1332 1333 if (fh == INVALID_HANDLE_VALUE) { 1334 DWORD lasterror = GetLastError(); 1335 if (PrintMiscellaneous && Verbose) { 1336 warning("could not create file %s: %d\n", filename, lasterror); 1337 } 1338 return NULL; 1339 } 1340 1341 // try to create the file mapping 1342 fmh = create_file_mapping(objectname, fh, lpSmoSA, size); 1343 1344 free_security_attr(lpSmoSA); 1345 1346 if (fmh == NULL) { 1347 // closing the file handle here will decrement the reference count 1348 // on the file. When all processes accessing the file close their 1349 // handle to it, the reference count will decrement to 0 and the 1350 // OS will delete the file. These semantics are requested by the 1351 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above. 1352 CloseHandle(fh); 1353 fh = NULL; 1354 return NULL; 1355 } else { 1356 // We created the file mapping, but rarely the size of the 1357 // backing store file is reported as zero (0) which can cause 1358 // failures when trying to use the hsperfdata file. 1359 struct stat statbuf; 1360 int ret_code = ::stat(filename, &statbuf); 1361 if (ret_code == OS_ERR) { 1362 if (PrintMiscellaneous && Verbose) { 1363 warning("Could not get status information from file %s: %s\n", 1364 filename, strerror(errno)); 1365 } 1366 CloseHandle(fmh); 1367 CloseHandle(fh); 1368 fh = NULL; 1369 fmh = NULL; 1370 return NULL; 1371 } 1372 1373 // We could always call FlushFileBuffers() but the Microsoft 1374 // docs indicate that it is considered expensive so we only 1375 // call it when we observe the size as zero (0). 1376 if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) { 1377 DWORD lasterror = GetLastError(); 1378 if (PrintMiscellaneous && Verbose) { 1379 warning("could not flush file %s: %d\n", filename, lasterror); 1380 } 1381 CloseHandle(fmh); 1382 CloseHandle(fh); 1383 fh = NULL; 1384 fmh = NULL; 1385 return NULL; 1386 } 1387 } 1388 1389 // the file has been successfully created and the file mapping 1390 // object has been created. 1391 sharedmem_fileHandle = fh; 1392 sharedmem_fileName = os::strdup(filename); 1393 1394 return fmh; 1395} 1396 1397// open the shared memory object for the given vmid. 1398// 1399static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) { 1400 1401 HANDLE fmh; 1402 1403 // open the file mapping with the requested mode 1404 fmh = OpenFileMapping( 1405 ofm_access, /* DWORD access mode */ 1406 FALSE, /* BOOL inherit flag - Do not allow inherit */ 1407 objectname); /* name for object */ 1408 1409 if (fmh == NULL) { 1410 if (PrintMiscellaneous && Verbose) { 1411 warning("OpenFileMapping failed for shared memory object %s:" 1412 " lasterror = %d\n", objectname, GetLastError()); 1413 } 1414 THROW_MSG_(vmSymbols::java_lang_Exception(), 1415 "Could not open PerfMemory", INVALID_HANDLE_VALUE); 1416 } 1417 1418 return fmh;; 1419} 1420 1421// create a named shared memory region 1422// 1423// On Win32, a named shared memory object has a name space that 1424// is independent of the file system name space. Shared memory object, 1425// or more precisely, file mapping objects, provide no mechanism to 1426// inquire the size of the memory region. There is also no api to 1427// enumerate the memory regions for various processes. 1428// 1429// This implementation utilizes the shared memory name space in parallel 1430// with the file system name space. This allows us to determine the 1431// size of the shared memory region from the size of the file and it 1432// allows us to provide a common, file system based name space for 1433// shared memory across platforms. 1434// 1435static char* mapping_create_shared(size_t size) { 1436 1437 void *mapAddress; 1438 int vmid = os::current_process_id(); 1439 1440 // get the name of the user associated with this process 1441 char* user = get_user_name(); 1442 1443 if (user == NULL) { 1444 return NULL; 1445 } 1446 1447 // construct the name of the user specific temporary directory 1448 char* dirname = get_user_tmp_dir(user); 1449 1450 // check that the file system is secure - i.e. it supports ACLs. 1451 if (!is_filesystem_secure(dirname)) { 1452 return NULL; 1453 } 1454 1455 // create the names of the backing store files and for the 1456 // share memory object. 1457 // 1458 char* filename = get_sharedmem_filename(dirname, vmid); 1459 char* objectname = get_sharedmem_objectname(user, vmid); 1460 1461 // cleanup any stale shared memory resources 1462 cleanup_sharedmem_resources(dirname); 1463 1464 assert(((size != 0) && (size % os::vm_page_size() == 0)), 1465 "unexpected PerfMemry region size"); 1466 1467 FREE_C_HEAP_ARRAY(char, user, mtInternal); 1468 1469 // create the shared memory resources 1470 sharedmem_fileMapHandle = 1471 create_sharedmem_resources(dirname, filename, objectname, size); 1472 1473 FREE_C_HEAP_ARRAY(char, filename, mtInternal); 1474 FREE_C_HEAP_ARRAY(char, objectname, mtInternal); 1475 FREE_C_HEAP_ARRAY(char, dirname, mtInternal); 1476 1477 if (sharedmem_fileMapHandle == NULL) { 1478 return NULL; 1479 } 1480 1481 // map the file into the address space 1482 mapAddress = MapViewOfFile( 1483 sharedmem_fileMapHandle, /* HANDLE = file mapping object */ 1484 FILE_MAP_ALL_ACCESS, /* DWORD access flags */ 1485 0, /* DWORD High word of offset */ 1486 0, /* DWORD Low word of offset */ 1487 (DWORD)size); /* DWORD Number of bytes to map */ 1488 1489 if (mapAddress == NULL) { 1490 if (PrintMiscellaneous && Verbose) { 1491 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1492 } 1493 CloseHandle(sharedmem_fileMapHandle); 1494 sharedmem_fileMapHandle = NULL; 1495 return NULL; 1496 } 1497 1498 // clear the shared memory region 1499 (void)memset(mapAddress, '\0', size); 1500 1501 // it does not go through os api, the operation has to record from here 1502 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, 1503 size, CURRENT_PC, mtInternal); 1504 1505 return (char*) mapAddress; 1506} 1507 1508// this method deletes the file mapping object. 1509// 1510static void delete_file_mapping(char* addr, size_t size) { 1511 1512 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1513 // not support unloading of the JVM, unmapping of the memory resource is not 1514 // performed. The memory will be reclaimed by the OS upon termination of all 1515 // processes mapping the resource. The file mapping handle and the file 1516 // handle are closed here to expedite the remove of the file by the OS. The 1517 // file is not removed directly because it was created with 1518 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would 1519 // be unsuccessful. 1520 1521 // close the fileMapHandle. the file mapping will still be retained 1522 // by the OS as long as any other JVM processes has an open file mapping 1523 // handle or a mapped view of the file. 1524 // 1525 if (sharedmem_fileMapHandle != NULL) { 1526 CloseHandle(sharedmem_fileMapHandle); 1527 sharedmem_fileMapHandle = NULL; 1528 } 1529 1530 // close the file handle. This will decrement the reference count on the 1531 // backing store file. When the reference count decrements to 0, the OS 1532 // will delete the file. These semantics apply because the file was 1533 // created with the FILE_FLAG_DELETE_ON_CLOSE flag. 1534 // 1535 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) { 1536 CloseHandle(sharedmem_fileHandle); 1537 sharedmem_fileHandle = INVALID_HANDLE_VALUE; 1538 } 1539} 1540 1541// this method determines the size of the shared memory file 1542// 1543static size_t sharedmem_filesize(const char* filename, TRAPS) { 1544 1545 struct stat statbuf; 1546 1547 // get the file size 1548 // 1549 // on win95/98/me, _stat returns a file size of 0 bytes, but on 1550 // winnt/2k the appropriate file size is returned. support for 1551 // the sharable aspects of performance counters was abandonded 1552 // on the non-nt win32 platforms due to this and other api 1553 // inconsistencies 1554 // 1555 if (::stat(filename, &statbuf) == OS_ERR) { 1556 if (PrintMiscellaneous && Verbose) { 1557 warning("stat %s failed: %s\n", filename, strerror(errno)); 1558 } 1559 THROW_MSG_0(vmSymbols::java_io_IOException(), 1560 "Could not determine PerfMemory size"); 1561 } 1562 1563 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) { 1564 if (PrintMiscellaneous && Verbose) { 1565 warning("unexpected file size: size = " SIZE_FORMAT "\n", 1566 statbuf.st_size); 1567 } 1568 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1569 "Invalid PerfMemory size"); 1570 } 1571 1572 return statbuf.st_size; 1573} 1574 1575// this method opens a file mapping object and maps the object 1576// into the address space of the process 1577// 1578static void open_file_mapping(const char* user, int vmid, 1579 PerfMemory::PerfMemoryMode mode, 1580 char** addrp, size_t* sizep, TRAPS) { 1581 1582 ResourceMark rm; 1583 1584 void *mapAddress = 0; 1585 size_t size = 0; 1586 HANDLE fmh; 1587 DWORD ofm_access; 1588 DWORD mv_access; 1589 const char* luser = NULL; 1590 1591 if (mode == PerfMemory::PERF_MODE_RO) { 1592 ofm_access = FILE_MAP_READ; 1593 mv_access = FILE_MAP_READ; 1594 } 1595 else if (mode == PerfMemory::PERF_MODE_RW) { 1596#ifdef LATER 1597 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE; 1598 mv_access = FILE_MAP_READ | FILE_MAP_WRITE; 1599#else 1600 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1601 "Unsupported access mode"); 1602#endif 1603 } 1604 else { 1605 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1606 "Illegal access mode"); 1607 } 1608 1609 // if a user name wasn't specified, then find the user name for 1610 // the owner of the target vm. 1611 if (user == NULL || strlen(user) == 0) { 1612 luser = get_user_name(vmid); 1613 } 1614 else { 1615 luser = user; 1616 } 1617 1618 if (luser == NULL) { 1619 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1620 "Could not map vmid to user name"); 1621 } 1622 1623 // get the names for the resources for the target vm 1624 char* dirname = get_user_tmp_dir(luser); 1625 1626 // since we don't follow symbolic links when creating the backing 1627 // store file, we also don't following them when attaching 1628 // 1629 if (!is_directory_secure(dirname)) { 1630 FREE_C_HEAP_ARRAY(char, dirname, mtInternal); 1631 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1632 "Process not found"); 1633 } 1634 1635 char* filename = get_sharedmem_filename(dirname, vmid); 1636 char* objectname = get_sharedmem_objectname(luser, vmid); 1637 1638 // copy heap memory to resource memory. the objectname and 1639 // filename are passed to methods that may throw exceptions. 1640 // using resource arrays for these names prevents the leaks 1641 // that would otherwise occur. 1642 // 1643 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 1644 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1); 1645 strcpy(rfilename, filename); 1646 strcpy(robjectname, objectname); 1647 1648 // free the c heap resources that are no longer needed 1649 if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal); 1650 FREE_C_HEAP_ARRAY(char, dirname, mtInternal); 1651 FREE_C_HEAP_ARRAY(char, filename, mtInternal); 1652 FREE_C_HEAP_ARRAY(char, objectname, mtInternal); 1653 1654 if (*sizep == 0) { 1655 size = sharedmem_filesize(rfilename, CHECK); 1656 } else { 1657 size = *sizep; 1658 } 1659 1660 assert(size > 0, "unexpected size <= 0"); 1661 1662 // Open the file mapping object with the given name 1663 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK); 1664 1665 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value"); 1666 1667 // map the entire file into the address space 1668 mapAddress = MapViewOfFile( 1669 fmh, /* HANDLE Handle of file mapping object */ 1670 mv_access, /* DWORD access flags */ 1671 0, /* DWORD High word of offset */ 1672 0, /* DWORD Low word of offset */ 1673 size); /* DWORD Number of bytes to map */ 1674 1675 if (mapAddress == NULL) { 1676 if (PrintMiscellaneous && Verbose) { 1677 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1678 } 1679 CloseHandle(fmh); 1680 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 1681 "Could not map PerfMemory"); 1682 } 1683 1684 // it does not go through os api, the operation has to record from here 1685 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, 1686 CURRENT_PC, mtInternal); 1687 1688 1689 *addrp = (char*)mapAddress; 1690 *sizep = size; 1691 1692 // File mapping object can be closed at this time without 1693 // invalidating the mapped view of the file 1694 CloseHandle(fmh); 1695 1696 if (PerfTraceMemOps) { 1697 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 1698 INTPTR_FORMAT "\n", size, vmid, mapAddress); 1699 } 1700} 1701 1702// this method unmaps the the mapped view of the the 1703// file mapping object. 1704// 1705static void remove_file_mapping(char* addr) { 1706 1707 // the file mapping object was closed in open_file_mapping() 1708 // after the file map view was created. We only need to 1709 // unmap the file view here. 1710 UnmapViewOfFile(addr); 1711} 1712 1713// create the PerfData memory region in shared memory. 1714static char* create_shared_memory(size_t size) { 1715 1716 return mapping_create_shared(size); 1717} 1718 1719// release a named, shared memory region 1720// 1721void delete_shared_memory(char* addr, size_t size) { 1722 1723 delete_file_mapping(addr, size); 1724} 1725 1726 1727 1728 1729// create the PerfData memory region 1730// 1731// This method creates the memory region used to store performance 1732// data for the JVM. The memory may be created in standard or 1733// shared memory. 1734// 1735void PerfMemory::create_memory_region(size_t size) { 1736 1737 if (PerfDisableSharedMem || !os::win32::is_nt()) { 1738 // do not share the memory for the performance data. 1739 PerfDisableSharedMem = true; 1740 _start = create_standard_memory(size); 1741 } 1742 else { 1743 _start = create_shared_memory(size); 1744 if (_start == NULL) { 1745 1746 // creation of the shared memory region failed, attempt 1747 // to create a contiguous, non-shared memory region instead. 1748 // 1749 if (PrintMiscellaneous && Verbose) { 1750 warning("Reverting to non-shared PerfMemory region.\n"); 1751 } 1752 PerfDisableSharedMem = true; 1753 _start = create_standard_memory(size); 1754 } 1755 } 1756 1757 if (_start != NULL) _capacity = size; 1758 1759} 1760 1761// delete the PerfData memory region 1762// 1763// This method deletes the memory region used to store performance 1764// data for the JVM. The memory region indicated by the <address, size> 1765// tuple will be inaccessible after a call to this method. 1766// 1767void PerfMemory::delete_memory_region() { 1768 1769 assert((start() != NULL && capacity() > 0), "verify proper state"); 1770 1771 // If user specifies PerfDataSaveFile, it will save the performance data 1772 // to the specified file name no matter whether PerfDataSaveToFile is specified 1773 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 1774 // -XX:+PerfDataSaveToFile. 1775 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 1776 save_memory_to_file(start(), capacity()); 1777 } 1778 1779 if (PerfDisableSharedMem) { 1780 delete_standard_memory(start(), capacity()); 1781 } 1782 else { 1783 delete_shared_memory(start(), capacity()); 1784 } 1785} 1786 1787// attach to the PerfData memory region for another JVM 1788// 1789// This method returns an <address, size> tuple that points to 1790// a memory buffer that is kept reasonably synchronized with 1791// the PerfData memory region for the indicated JVM. This 1792// buffer may be kept in synchronization via shared memory 1793// or some other mechanism that keeps the buffer updated. 1794// 1795// If the JVM chooses not to support the attachability feature, 1796// this method should throw an UnsupportedOperation exception. 1797// 1798// This implementation utilizes named shared memory to map 1799// the indicated process's PerfData memory region into this JVMs 1800// address space. 1801// 1802void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, 1803 char** addrp, size_t* sizep, TRAPS) { 1804 1805 if (vmid == 0 || vmid == os::current_process_id()) { 1806 *addrp = start(); 1807 *sizep = capacity(); 1808 return; 1809 } 1810 1811 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK); 1812} 1813 1814// detach from the PerfData memory region of another JVM 1815// 1816// This method detaches the PerfData memory region of another 1817// JVM, specified as an <address, size> tuple of a buffer 1818// in this process's address space. This method may perform 1819// arbitrary actions to accomplish the detachment. The memory 1820// region specified by <address, size> will be inaccessible after 1821// a call to this method. 1822// 1823// If the JVM chooses not to support the attachability feature, 1824// this method should throw an UnsupportedOperation exception. 1825// 1826// This implementation utilizes named shared memory to detach 1827// the indicated process's PerfData memory region from this 1828// process's address space. 1829// 1830void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 1831 1832 assert(addr != 0, "address sanity check"); 1833 assert(bytes > 0, "capacity sanity check"); 1834 1835 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1836 // prevent accidental detachment of this process's PerfMemory region 1837 return; 1838 } 1839 1840 if (MemTracker::tracking_level() > NMT_minimal) { 1841 // it does not go through os api, the operation has to record from here 1842 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 1843 remove_file_mapping(addr); 1844 tkr.record((address)addr, bytes); 1845 } else { 1846 remove_file_mapping(addr); 1847 } 1848} 1849 1850char* PerfMemory::backing_store_filename() { 1851 return sharedmem_fileName; 1852} 1853