perfMemory_windows.cpp revision 1875:0b33f0736406
1/* 2 * Copyright (c) 2001, 2007, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25# include "incls/_precompiled.incl" 26# include "incls/_perfMemory_windows.cpp.incl" 27 28#include <windows.h> 29#include <sys/types.h> 30#include <sys/stat.h> 31#include <errno.h> 32#include <lmcons.h> 33 34typedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)( 35 IN PSECURITY_DESCRIPTOR pSecurityDescriptor, 36 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest, 37 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet); 38 39// Standard Memory Implementation Details 40 41// create the PerfData memory region in standard memory. 42// 43static char* create_standard_memory(size_t size) { 44 45 // allocate an aligned chuck of memory 46 char* mapAddress = os::reserve_memory(size); 47 48 if (mapAddress == NULL) { 49 return NULL; 50 } 51 52 // commit memory 53 if (!os::commit_memory(mapAddress, size)) { 54 if (PrintMiscellaneous && Verbose) { 55 warning("Could not commit PerfData memory\n"); 56 } 57 os::release_memory(mapAddress, size); 58 return NULL; 59 } 60 61 return mapAddress; 62} 63 64// delete the PerfData memory region 65// 66static void delete_standard_memory(char* addr, size_t size) { 67 68 // there are no persistent external resources to cleanup for standard 69 // memory. since DestroyJavaVM does not support unloading of the JVM, 70 // cleanup of the memory resource is not performed. The memory will be 71 // reclaimed by the OS upon termination of the process. 72 // 73 return; 74 75} 76 77// save the specified memory region to the given file 78// 79static void save_memory_to_file(char* addr, size_t size) { 80 81 const char* destfile = PerfMemory::get_perfdata_file_path(); 82 assert(destfile[0] != '\0', "invalid Perfdata file path"); 83 84 int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC, 85 _S_IREAD|_S_IWRITE); 86 87 if (fd == OS_ERR) { 88 if (PrintMiscellaneous && Verbose) { 89 warning("Could not create Perfdata save file: %s: %s\n", 90 destfile, strerror(errno)); 91 } 92 } else { 93 for (size_t remaining = size; remaining > 0;) { 94 95 int nbytes = ::_write(fd, addr, (unsigned int)remaining); 96 if (nbytes == OS_ERR) { 97 if (PrintMiscellaneous && Verbose) { 98 warning("Could not write Perfdata save file: %s: %s\n", 99 destfile, strerror(errno)); 100 } 101 break; 102 } 103 104 remaining -= (size_t)nbytes; 105 addr += nbytes; 106 } 107 108 int result = ::_close(fd); 109 if (PrintMiscellaneous && Verbose) { 110 if (result == OS_ERR) { 111 warning("Could not close %s: %s\n", destfile, strerror(errno)); 112 } 113 } 114 } 115 116 FREE_C_HEAP_ARRAY(char, destfile); 117} 118 119// Shared Memory Implementation Details 120 121// Note: the win32 shared memory implementation uses two objects to represent 122// the shared memory: a windows kernel based file mapping object and a backing 123// store file. On windows, the name space for shared memory is a kernel 124// based name space that is disjoint from other win32 name spaces. Since Java 125// is unaware of this name space, a parallel file system based name space is 126// maintained, which provides a common file system based shared memory name 127// space across the supported platforms and one that Java apps can deal with 128// through simple file apis. 129// 130// For performance and resource cleanup reasons, it is recommended that the 131// user specific directory and the backing store file be stored in either a 132// RAM based file system or a local disk based file system. Network based 133// file systems are not recommended for performance reasons. In addition, 134// use of SMB network based file systems may result in unsuccesful cleanup 135// of the disk based resource on exit of the VM. The Windows TMP and TEMP 136// environement variables, as used by the GetTempPath() Win32 API (see 137// os::get_temp_directory() in os_win32.cpp), control the location of the 138// user specific directory and the shared memory backing store file. 139 140static HANDLE sharedmem_fileMapHandle = NULL; 141static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE; 142static char* sharedmem_fileName = NULL; 143 144// return the user specific temporary directory name. 145// 146// the caller is expected to free the allocated memory. 147// 148static char* get_user_tmp_dir(const char* user) { 149 150 const char* tmpdir = os::get_temp_directory(); 151 const char* perfdir = PERFDATA_NAME; 152 size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3; 153 char* dirname = NEW_C_HEAP_ARRAY(char, nbytes); 154 155 // construct the path name to user specific tmp directory 156 _snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user); 157 158 return dirname; 159} 160 161// convert the given file name into a process id. if the file 162// does not meet the file naming constraints, return 0. 163// 164static int filename_to_pid(const char* filename) { 165 166 // a filename that doesn't begin with a digit is not a 167 // candidate for conversion. 168 // 169 if (!isdigit(*filename)) { 170 return 0; 171 } 172 173 // check if file name can be converted to an integer without 174 // any leftover characters. 175 // 176 char* remainder = NULL; 177 errno = 0; 178 int pid = (int)strtol(filename, &remainder, 10); 179 180 if (errno != 0) { 181 return 0; 182 } 183 184 // check for left over characters. If any, then the filename is 185 // not a candidate for conversion. 186 // 187 if (remainder != NULL && *remainder != '\0') { 188 return 0; 189 } 190 191 // successful conversion, return the pid 192 return pid; 193} 194 195// check if the given path is considered a secure directory for 196// the backing store files. Returns true if the directory exists 197// and is considered a secure location. Returns false if the path 198// is a symbolic link or if an error occurred. 199// 200static bool is_directory_secure(const char* path) { 201 202 DWORD fa; 203 204 fa = GetFileAttributes(path); 205 if (fa == 0xFFFFFFFF) { 206 DWORD lasterror = GetLastError(); 207 if (lasterror == ERROR_FILE_NOT_FOUND) { 208 return false; 209 } 210 else { 211 // unexpected error, declare the path insecure 212 if (PrintMiscellaneous && Verbose) { 213 warning("could not get attributes for file %s: ", 214 " lasterror = %d\n", path, lasterror); 215 } 216 return false; 217 } 218 } 219 220 if (fa & FILE_ATTRIBUTE_REPARSE_POINT) { 221 // we don't accept any redirection for the user specific directory 222 // so declare the path insecure. This may be too conservative, 223 // as some types of reparse points might be acceptable, but it 224 // is probably more secure to avoid these conditions. 225 // 226 if (PrintMiscellaneous && Verbose) { 227 warning("%s is a reparse point\n", path); 228 } 229 return false; 230 } 231 232 if (fa & FILE_ATTRIBUTE_DIRECTORY) { 233 // this is the expected case. Since windows supports symbolic 234 // links to directories only, not to files, there is no need 235 // to check for open write permissions on the directory. If the 236 // directory has open write permissions, any files deposited that 237 // are not expected will be removed by the cleanup code. 238 // 239 return true; 240 } 241 else { 242 // this is either a regular file or some other type of file, 243 // any of which are unexpected and therefore insecure. 244 // 245 if (PrintMiscellaneous && Verbose) { 246 warning("%s is not a directory, file attributes = " 247 INTPTR_FORMAT "\n", path, fa); 248 } 249 return false; 250 } 251} 252 253// return the user name for the owner of this process 254// 255// the caller is expected to free the allocated memory. 256// 257static char* get_user_name() { 258 259 /* get the user name. This code is adapted from code found in 260 * the jdk in src/windows/native/java/lang/java_props_md.c 261 * java_props_md.c 1.29 02/02/06. According to the original 262 * source, the call to GetUserName is avoided because of a resulting 263 * increase in footprint of 100K. 264 */ 265 char* user = getenv("USERNAME"); 266 char buf[UNLEN+1]; 267 DWORD buflen = sizeof(buf); 268 if (user == NULL || strlen(user) == 0) { 269 if (GetUserName(buf, &buflen)) { 270 user = buf; 271 } 272 else { 273 return NULL; 274 } 275 } 276 277 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1); 278 strcpy(user_name, user); 279 280 return user_name; 281} 282 283// return the name of the user that owns the process identified by vmid. 284// 285// This method uses a slow directory search algorithm to find the backing 286// store file for the specified vmid and returns the user name, as determined 287// by the user name suffix of the hsperfdata_<username> directory name. 288// 289// the caller is expected to free the allocated memory. 290// 291static char* get_user_name_slow(int vmid) { 292 293 // directory search 294 char* oldest_user = NULL; 295 time_t oldest_ctime = 0; 296 297 const char* tmpdirname = os::get_temp_directory(); 298 299 DIR* tmpdirp = os::opendir(tmpdirname); 300 301 if (tmpdirp == NULL) { 302 return NULL; 303 } 304 305 // for each entry in the directory that matches the pattern hsperfdata_*, 306 // open the directory and check if the file for the given vmid exists. 307 // The file with the expected name and the latest creation date is used 308 // to determine the user name for the process id. 309 // 310 struct dirent* dentry; 311 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname)); 312 errno = 0; 313 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) { 314 315 // check if the directory entry is a hsperfdata file 316 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) { 317 continue; 318 } 319 320 char* usrdir_name = NEW_C_HEAP_ARRAY(char, 321 strlen(tmpdirname) + strlen(dentry->d_name) + 2); 322 strcpy(usrdir_name, tmpdirname); 323 strcat(usrdir_name, "\\"); 324 strcat(usrdir_name, dentry->d_name); 325 326 DIR* subdirp = os::opendir(usrdir_name); 327 328 if (subdirp == NULL) { 329 FREE_C_HEAP_ARRAY(char, usrdir_name); 330 continue; 331 } 332 333 // Since we don't create the backing store files in directories 334 // pointed to by symbolic links, we also don't follow them when 335 // looking for the files. We check for a symbolic link after the 336 // call to opendir in order to eliminate a small window where the 337 // symlink can be exploited. 338 // 339 if (!is_directory_secure(usrdir_name)) { 340 FREE_C_HEAP_ARRAY(char, usrdir_name); 341 os::closedir(subdirp); 342 continue; 343 } 344 345 struct dirent* udentry; 346 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name)); 347 errno = 0; 348 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) { 349 350 if (filename_to_pid(udentry->d_name) == vmid) { 351 struct stat statbuf; 352 353 char* filename = NEW_C_HEAP_ARRAY(char, 354 strlen(usrdir_name) + strlen(udentry->d_name) + 2); 355 356 strcpy(filename, usrdir_name); 357 strcat(filename, "\\"); 358 strcat(filename, udentry->d_name); 359 360 if (::stat(filename, &statbuf) == OS_ERR) { 361 FREE_C_HEAP_ARRAY(char, filename); 362 continue; 363 } 364 365 // skip over files that are not regular files. 366 if ((statbuf.st_mode & S_IFMT) != S_IFREG) { 367 FREE_C_HEAP_ARRAY(char, filename); 368 continue; 369 } 370 371 // compare and save filename with latest creation time 372 if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) { 373 374 if (statbuf.st_ctime > oldest_ctime) { 375 char* user = strchr(dentry->d_name, '_') + 1; 376 377 if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user); 378 oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1); 379 380 strcpy(oldest_user, user); 381 oldest_ctime = statbuf.st_ctime; 382 } 383 } 384 385 FREE_C_HEAP_ARRAY(char, filename); 386 } 387 } 388 os::closedir(subdirp); 389 FREE_C_HEAP_ARRAY(char, udbuf); 390 FREE_C_HEAP_ARRAY(char, usrdir_name); 391 } 392 os::closedir(tmpdirp); 393 FREE_C_HEAP_ARRAY(char, tdbuf); 394 395 return(oldest_user); 396} 397 398// return the name of the user that owns the process identified by vmid. 399// 400// note: this method should only be used via the Perf native methods. 401// There are various costs to this method and limiting its use to the 402// Perf native methods limits the impact to monitoring applications only. 403// 404static char* get_user_name(int vmid) { 405 406 // A fast implementation is not provided at this time. It's possible 407 // to provide a fast process id to user name mapping function using 408 // the win32 apis, but the default ACL for the process object only 409 // allows processes with the same owner SID to acquire the process 410 // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible 411 // to have the JVM change the ACL for the process object to allow arbitrary 412 // users to access the process handle and the process security token. 413 // The security ramifications need to be studied before providing this 414 // mechanism. 415 // 416 return get_user_name_slow(vmid); 417} 418 419// return the name of the shared memory file mapping object for the 420// named shared memory region for the given user name and vmid. 421// 422// The file mapping object's name is not the file name. It is a name 423// in a separate name space. 424// 425// the caller is expected to free the allocated memory. 426// 427static char *get_sharedmem_objectname(const char* user, int vmid) { 428 429 // construct file mapping object's name, add 3 for two '_' and a 430 // null terminator. 431 int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3; 432 433 // the id is converted to an unsigned value here because win32 allows 434 // negative process ids. However, OpenFileMapping API complains 435 // about a name containing a '-' characters. 436 // 437 nbytes += UINT_CHARS; 438 char* name = NEW_C_HEAP_ARRAY(char, nbytes); 439 _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid); 440 441 return name; 442} 443 444// return the file name of the backing store file for the named 445// shared memory region for the given user name and vmid. 446// 447// the caller is expected to free the allocated memory. 448// 449static char* get_sharedmem_filename(const char* dirname, int vmid) { 450 451 // add 2 for the file separator and a null terminator. 452 size_t nbytes = strlen(dirname) + UINT_CHARS + 2; 453 454 char* name = NEW_C_HEAP_ARRAY(char, nbytes); 455 _snprintf(name, nbytes, "%s\\%d", dirname, vmid); 456 457 return name; 458} 459 460// remove file 461// 462// this method removes the file with the given file name. 463// 464// Note: if the indicated file is on an SMB network file system, this 465// method may be unsuccessful in removing the file. 466// 467static void remove_file(const char* dirname, const char* filename) { 468 469 size_t nbytes = strlen(dirname) + strlen(filename) + 2; 470 char* path = NEW_C_HEAP_ARRAY(char, nbytes); 471 472 strcpy(path, dirname); 473 strcat(path, "\\"); 474 strcat(path, filename); 475 476 if (::unlink(path) == OS_ERR) { 477 if (PrintMiscellaneous && Verbose) { 478 if (errno != ENOENT) { 479 warning("Could not unlink shared memory backing" 480 " store file %s : %s\n", path, strerror(errno)); 481 } 482 } 483 } 484 485 FREE_C_HEAP_ARRAY(char, path); 486} 487 488// returns true if the process represented by pid is alive, otherwise 489// returns false. the validity of the result is only accurate if the 490// target process is owned by the same principal that owns this process. 491// this method should not be used if to test the status of an otherwise 492// arbitrary process unless it is know that this process has the appropriate 493// privileges to guarantee a result valid. 494// 495static bool is_alive(int pid) { 496 497 HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); 498 if (ph == NULL) { 499 // the process does not exist. 500 if (PrintMiscellaneous && Verbose) { 501 DWORD lastError = GetLastError(); 502 if (lastError != ERROR_INVALID_PARAMETER) { 503 warning("OpenProcess failed: %d\n", GetLastError()); 504 } 505 } 506 return false; 507 } 508 509 DWORD exit_status; 510 if (!GetExitCodeProcess(ph, &exit_status)) { 511 if (PrintMiscellaneous && Verbose) { 512 warning("GetExitCodeProcess failed: %d\n", GetLastError()); 513 } 514 CloseHandle(ph); 515 return false; 516 } 517 518 CloseHandle(ph); 519 return (exit_status == STILL_ACTIVE) ? true : false; 520} 521 522// check if the file system is considered secure for the backing store files 523// 524static bool is_filesystem_secure(const char* path) { 525 526 char root_path[MAX_PATH]; 527 char fs_type[MAX_PATH]; 528 529 if (PerfBypassFileSystemCheck) { 530 if (PrintMiscellaneous && Verbose) { 531 warning("bypassing file system criteria checks for %s\n", path); 532 } 533 return true; 534 } 535 536 char* first_colon = strchr((char *)path, ':'); 537 if (first_colon == NULL) { 538 if (PrintMiscellaneous && Verbose) { 539 warning("expected device specifier in path: %s\n", path); 540 } 541 return false; 542 } 543 544 size_t len = (size_t)(first_colon - path); 545 assert(len + 2 <= MAX_PATH, "unexpected device specifier length"); 546 strncpy(root_path, path, len + 1); 547 root_path[len + 1] = '\\'; 548 root_path[len + 2] = '\0'; 549 550 // check that we have something like "C:\" or "AA:\" 551 assert(strlen(root_path) >= 3, "device specifier too short"); 552 assert(strchr(root_path, ':') != NULL, "bad device specifier format"); 553 assert(strchr(root_path, '\\') != NULL, "bad device specifier format"); 554 555 DWORD maxpath; 556 DWORD flags; 557 558 if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath, 559 &flags, fs_type, MAX_PATH)) { 560 // we can't get information about the volume, so assume unsafe. 561 if (PrintMiscellaneous && Verbose) { 562 warning("could not get device information for %s: " 563 " path = %s: lasterror = %d\n", 564 root_path, path, GetLastError()); 565 } 566 return false; 567 } 568 569 if ((flags & FS_PERSISTENT_ACLS) == 0) { 570 // file system doesn't support ACLs, declare file system unsafe 571 if (PrintMiscellaneous && Verbose) { 572 warning("file system type %s on device %s does not support" 573 " ACLs\n", fs_type, root_path); 574 } 575 return false; 576 } 577 578 if ((flags & FS_VOL_IS_COMPRESSED) != 0) { 579 // file system is compressed, declare file system unsafe 580 if (PrintMiscellaneous && Verbose) { 581 warning("file system type %s on device %s is compressed\n", 582 fs_type, root_path); 583 } 584 return false; 585 } 586 587 return true; 588} 589 590// cleanup stale shared memory resources 591// 592// This method attempts to remove all stale shared memory files in 593// the named user temporary directory. It scans the named directory 594// for files matching the pattern ^$[0-9]*$. For each file found, the 595// process id is extracted from the file name and a test is run to 596// determine if the process is alive. If the process is not alive, 597// any stale file resources are removed. 598// 599static void cleanup_sharedmem_resources(const char* dirname) { 600 601 // open the user temp directory 602 DIR* dirp = os::opendir(dirname); 603 604 if (dirp == NULL) { 605 // directory doesn't exist, so there is nothing to cleanup 606 return; 607 } 608 609 if (!is_directory_secure(dirname)) { 610 // the directory is not secure, don't attempt any cleanup 611 return; 612 } 613 614 // for each entry in the directory that matches the expected file 615 // name pattern, determine if the file resources are stale and if 616 // so, remove the file resources. Note, instrumented HotSpot processes 617 // for this user may start and/or terminate during this search and 618 // remove or create new files in this directory. The behavior of this 619 // loop under these conditions is dependent upon the implementation of 620 // opendir/readdir. 621 // 622 struct dirent* entry; 623 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname)); 624 errno = 0; 625 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 626 627 int pid = filename_to_pid(entry->d_name); 628 629 if (pid == 0) { 630 631 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 632 633 // attempt to remove all unexpected files, except "." and ".." 634 remove_file(dirname, entry->d_name); 635 } 636 637 errno = 0; 638 continue; 639 } 640 641 // we now have a file name that converts to a valid integer 642 // that could represent a process id . if this process id 643 // matches the current process id or the process is not running, 644 // then remove the stale file resources. 645 // 646 // process liveness is detected by checking the exit status 647 // of the process. if the process id is valid and the exit status 648 // indicates that it is still running, the file file resources 649 // are not removed. If the process id is invalid, or if we don't 650 // have permissions to check the process status, or if the process 651 // id is valid and the process has terminated, the the file resources 652 // are assumed to be stale and are removed. 653 // 654 if (pid == os::current_process_id() || !is_alive(pid)) { 655 656 // we can only remove the file resources. Any mapped views 657 // of the file can only be unmapped by the processes that 658 // opened those views and the file mapping object will not 659 // get removed until all views are unmapped. 660 // 661 remove_file(dirname, entry->d_name); 662 } 663 errno = 0; 664 } 665 os::closedir(dirp); 666 FREE_C_HEAP_ARRAY(char, dbuf); 667} 668 669// create a file mapping object with the requested name, and size 670// from the file represented by the given Handle object 671// 672static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) { 673 674 DWORD lowSize = (DWORD)size; 675 DWORD highSize = 0; 676 HANDLE fmh = NULL; 677 678 // Create a file mapping object with the given name. This function 679 // will grow the file to the specified size. 680 // 681 fmh = CreateFileMapping( 682 fh, /* HANDLE file handle for backing store */ 683 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */ 684 PAGE_READWRITE, /* DWORD protections */ 685 highSize, /* DWORD High word of max size */ 686 lowSize, /* DWORD Low word of max size */ 687 name); /* LPCTSTR name for object */ 688 689 if (fmh == NULL) { 690 if (PrintMiscellaneous && Verbose) { 691 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError()); 692 } 693 return NULL; 694 } 695 696 if (GetLastError() == ERROR_ALREADY_EXISTS) { 697 698 // a stale file mapping object was encountered. This object may be 699 // owned by this or some other user and cannot be removed until 700 // the other processes either exit or close their mapping objects 701 // and/or mapped views of this mapping object. 702 // 703 if (PrintMiscellaneous && Verbose) { 704 warning("file mapping already exists, lasterror = %d\n", GetLastError()); 705 } 706 707 CloseHandle(fmh); 708 return NULL; 709 } 710 711 return fmh; 712} 713 714 715// method to free the given security descriptor and the contained 716// access control list. 717// 718static void free_security_desc(PSECURITY_DESCRIPTOR pSD) { 719 720 BOOL success, exists, isdefault; 721 PACL pACL; 722 723 if (pSD != NULL) { 724 725 // get the access control list from the security descriptor 726 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault); 727 728 // if an ACL existed and it was not a default acl, then it must 729 // be an ACL we enlisted. free the resources. 730 // 731 if (success && exists && pACL != NULL && !isdefault) { 732 FREE_C_HEAP_ARRAY(char, pACL); 733 } 734 735 // free the security descriptor 736 FREE_C_HEAP_ARRAY(char, pSD); 737 } 738} 739 740// method to free up a security attributes structure and any 741// contained security descriptors and ACL 742// 743static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) { 744 745 if (lpSA != NULL) { 746 // free the contained security descriptor and the ACL 747 free_security_desc(lpSA->lpSecurityDescriptor); 748 lpSA->lpSecurityDescriptor = NULL; 749 750 // free the security attributes structure 751 FREE_C_HEAP_ARRAY(char, lpSA); 752 } 753} 754 755// get the user SID for the process indicated by the process handle 756// 757static PSID get_user_sid(HANDLE hProcess) { 758 759 HANDLE hAccessToken; 760 PTOKEN_USER token_buf = NULL; 761 DWORD rsize = 0; 762 763 if (hProcess == NULL) { 764 return NULL; 765 } 766 767 // get the process token 768 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) { 769 if (PrintMiscellaneous && Verbose) { 770 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError()); 771 } 772 return NULL; 773 } 774 775 // determine the size of the token structured needed to retrieve 776 // the user token information from the access token. 777 // 778 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) { 779 DWORD lasterror = GetLastError(); 780 if (lasterror != ERROR_INSUFFICIENT_BUFFER) { 781 if (PrintMiscellaneous && Verbose) { 782 warning("GetTokenInformation failure: lasterror = %d," 783 " rsize = %d\n", lasterror, rsize); 784 } 785 CloseHandle(hAccessToken); 786 return NULL; 787 } 788 } 789 790 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize); 791 792 // get the user token information 793 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) { 794 if (PrintMiscellaneous && Verbose) { 795 warning("GetTokenInformation failure: lasterror = %d," 796 " rsize = %d\n", GetLastError(), rsize); 797 } 798 FREE_C_HEAP_ARRAY(char, token_buf); 799 CloseHandle(hAccessToken); 800 return NULL; 801 } 802 803 DWORD nbytes = GetLengthSid(token_buf->User.Sid); 804 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes); 805 806 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) { 807 if (PrintMiscellaneous && Verbose) { 808 warning("GetTokenInformation failure: lasterror = %d," 809 " rsize = %d\n", GetLastError(), rsize); 810 } 811 FREE_C_HEAP_ARRAY(char, token_buf); 812 FREE_C_HEAP_ARRAY(char, pSID); 813 CloseHandle(hAccessToken); 814 return NULL; 815 } 816 817 // close the access token. 818 CloseHandle(hAccessToken); 819 FREE_C_HEAP_ARRAY(char, token_buf); 820 821 return pSID; 822} 823 824// structure used to consolidate access control entry information 825// 826typedef struct ace_data { 827 PSID pSid; // SID of the ACE 828 DWORD mask; // mask for the ACE 829} ace_data_t; 830 831 832// method to add an allow access control entry with the access rights 833// indicated in mask for the principal indicated in SID to the given 834// security descriptor. Much of the DACL handling was adapted from 835// the example provided here: 836// http://support.microsoft.com/kb/102102/EN-US/ 837// 838 839static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD, 840 ace_data_t aces[], int ace_count) { 841 PACL newACL = NULL; 842 PACL oldACL = NULL; 843 844 if (pSD == NULL) { 845 return false; 846 } 847 848 BOOL exists, isdefault; 849 850 // retrieve any existing access control list. 851 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) { 852 if (PrintMiscellaneous && Verbose) { 853 warning("GetSecurityDescriptor failure: lasterror = %d \n", 854 GetLastError()); 855 } 856 return false; 857 } 858 859 // get the size of the DACL 860 ACL_SIZE_INFORMATION aclinfo; 861 862 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent) 863 // while oldACL is NULL for some case. 864 if (oldACL == NULL) { 865 exists = FALSE; 866 } 867 868 if (exists) { 869 if (!GetAclInformation(oldACL, &aclinfo, 870 sizeof(ACL_SIZE_INFORMATION), 871 AclSizeInformation)) { 872 if (PrintMiscellaneous && Verbose) { 873 warning("GetAclInformation failure: lasterror = %d \n", GetLastError()); 874 return false; 875 } 876 } 877 } else { 878 aclinfo.AceCount = 0; // assume NULL DACL 879 aclinfo.AclBytesFree = 0; 880 aclinfo.AclBytesInUse = sizeof(ACL); 881 } 882 883 // compute the size needed for the new ACL 884 // initial size of ACL is sum of the following: 885 // * size of ACL structure. 886 // * size of each ACE structure that ACL is to contain minus the sid 887 // sidStart member (DWORD) of the ACE. 888 // * length of the SID that each ACE is to contain. 889 DWORD newACLsize = aclinfo.AclBytesInUse + 890 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count; 891 for (int i = 0; i < ace_count; i++) { 892 assert(aces[i].pSid != 0, "pSid should not be 0"); 893 newACLsize += GetLengthSid(aces[i].pSid); 894 } 895 896 // create the new ACL 897 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize); 898 899 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) { 900 if (PrintMiscellaneous && Verbose) { 901 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 902 } 903 FREE_C_HEAP_ARRAY(char, newACL); 904 return false; 905 } 906 907 unsigned int ace_index = 0; 908 // copy any existing ACEs from the old ACL (if any) to the new ACL. 909 if (aclinfo.AceCount != 0) { 910 while (ace_index < aclinfo.AceCount) { 911 LPVOID ace; 912 if (!GetAce(oldACL, ace_index, &ace)) { 913 if (PrintMiscellaneous && Verbose) { 914 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 915 } 916 FREE_C_HEAP_ARRAY(char, newACL); 917 return false; 918 } 919 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) { 920 // this is an inherited, allowed ACE; break from loop so we can 921 // add the new access allowed, non-inherited ACE in the correct 922 // position, immediately following all non-inherited ACEs. 923 break; 924 } 925 926 // determine if the SID of this ACE matches any of the SIDs 927 // for which we plan to set ACEs. 928 int matches = 0; 929 for (int i = 0; i < ace_count; i++) { 930 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) { 931 matches++; 932 break; 933 } 934 } 935 936 // if there are no SID matches, then add this existing ACE to the new ACL 937 if (matches == 0) { 938 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 939 ((PACE_HEADER)ace)->AceSize)) { 940 if (PrintMiscellaneous && Verbose) { 941 warning("AddAce failure: lasterror = %d \n", GetLastError()); 942 } 943 FREE_C_HEAP_ARRAY(char, newACL); 944 return false; 945 } 946 } 947 ace_index++; 948 } 949 } 950 951 // add the passed-in access control entries to the new ACL 952 for (int i = 0; i < ace_count; i++) { 953 if (!AddAccessAllowedAce(newACL, ACL_REVISION, 954 aces[i].mask, aces[i].pSid)) { 955 if (PrintMiscellaneous && Verbose) { 956 warning("AddAccessAllowedAce failure: lasterror = %d \n", 957 GetLastError()); 958 } 959 FREE_C_HEAP_ARRAY(char, newACL); 960 return false; 961 } 962 } 963 964 // now copy the rest of the inherited ACEs from the old ACL 965 if (aclinfo.AceCount != 0) { 966 // picking up at ace_index, where we left off in the 967 // previous ace_index loop 968 while (ace_index < aclinfo.AceCount) { 969 LPVOID ace; 970 if (!GetAce(oldACL, ace_index, &ace)) { 971 if (PrintMiscellaneous && Verbose) { 972 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 973 } 974 FREE_C_HEAP_ARRAY(char, newACL); 975 return false; 976 } 977 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 978 ((PACE_HEADER)ace)->AceSize)) { 979 if (PrintMiscellaneous && Verbose) { 980 warning("AddAce failure: lasterror = %d \n", GetLastError()); 981 } 982 FREE_C_HEAP_ARRAY(char, newACL); 983 return false; 984 } 985 ace_index++; 986 } 987 } 988 989 // add the new ACL to the security descriptor. 990 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) { 991 if (PrintMiscellaneous && Verbose) { 992 warning("SetSecurityDescriptorDacl failure:" 993 " lasterror = %d \n", GetLastError()); 994 } 995 FREE_C_HEAP_ARRAY(char, newACL); 996 return false; 997 } 998 999 // if running on windows 2000 or later, set the automatic inheritance 1000 // control flags. 1001 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl; 1002 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr) 1003 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")), 1004 "SetSecurityDescriptorControl"); 1005 1006 if (_SetSecurityDescriptorControl != NULL) { 1007 // We do not want to further propagate inherited DACLs, so making them 1008 // protected prevents that. 1009 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, 1010 SE_DACL_PROTECTED)) { 1011 if (PrintMiscellaneous && Verbose) { 1012 warning("SetSecurityDescriptorControl failure:" 1013 " lasterror = %d \n", GetLastError()); 1014 } 1015 FREE_C_HEAP_ARRAY(char, newACL); 1016 return false; 1017 } 1018 } 1019 // Note, the security descriptor maintains a reference to the newACL, not 1020 // a copy of it. Therefore, the newACL is not freed here. It is freed when 1021 // the security descriptor containing its reference is freed. 1022 // 1023 return true; 1024} 1025 1026// method to create a security attributes structure, which contains a 1027// security descriptor and an access control list comprised of 0 or more 1028// access control entries. The method take an array of ace_data structures 1029// that indicate the ACE to be added to the security descriptor. 1030// 1031// the caller must free the resources associated with the security 1032// attributes structure created by this method by calling the 1033// free_security_attr() method. 1034// 1035static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) { 1036 1037 // allocate space for a security descriptor 1038 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) 1039 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH); 1040 1041 // initialize the security descriptor 1042 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { 1043 if (PrintMiscellaneous && Verbose) { 1044 warning("InitializeSecurityDescriptor failure: " 1045 "lasterror = %d \n", GetLastError()); 1046 } 1047 free_security_desc(pSD); 1048 return NULL; 1049 } 1050 1051 // add the access control entries 1052 if (!add_allow_aces(pSD, aces, count)) { 1053 free_security_desc(pSD); 1054 return NULL; 1055 } 1056 1057 // allocate and initialize the security attributes structure and 1058 // return it to the caller. 1059 // 1060 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES) 1061 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES)); 1062 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES); 1063 lpSA->lpSecurityDescriptor = pSD; 1064 lpSA->bInheritHandle = FALSE; 1065 1066 return(lpSA); 1067} 1068 1069// method to create a security attributes structure with a restrictive 1070// access control list that creates a set access rights for the user/owner 1071// of the securable object and a separate set access rights for everyone else. 1072// also provides for full access rights for the administrator group. 1073// 1074// the caller must free the resources associated with the security 1075// attributes structure created by this method by calling the 1076// free_security_attr() method. 1077// 1078 1079static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr( 1080 DWORD umask, DWORD emask, DWORD amask) { 1081 1082 ace_data_t aces[3]; 1083 1084 // initialize the user ace data 1085 aces[0].pSid = get_user_sid(GetCurrentProcess()); 1086 aces[0].mask = umask; 1087 1088 if (aces[0].pSid == 0) 1089 return NULL; 1090 1091 // get the well known SID for BUILTIN\Administrators 1092 PSID administratorsSid = NULL; 1093 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY; 1094 1095 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2, 1096 SECURITY_BUILTIN_DOMAIN_RID, 1097 DOMAIN_ALIAS_RID_ADMINS, 1098 0, 0, 0, 0, 0, 0, &administratorsSid)) { 1099 1100 if (PrintMiscellaneous && Verbose) { 1101 warning("AllocateAndInitializeSid failure: " 1102 "lasterror = %d \n", GetLastError()); 1103 } 1104 return NULL; 1105 } 1106 1107 // initialize the ace data for administrator group 1108 aces[1].pSid = administratorsSid; 1109 aces[1].mask = amask; 1110 1111 // get the well known SID for the universal Everybody 1112 PSID everybodySid = NULL; 1113 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY; 1114 1115 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID, 1116 0, 0, 0, 0, 0, 0, 0, &everybodySid)) { 1117 1118 if (PrintMiscellaneous && Verbose) { 1119 warning("AllocateAndInitializeSid failure: " 1120 "lasterror = %d \n", GetLastError()); 1121 } 1122 return NULL; 1123 } 1124 1125 // initialize the ace data for everybody else. 1126 aces[2].pSid = everybodySid; 1127 aces[2].mask = emask; 1128 1129 // create a security attributes structure with access control 1130 // entries as initialized above. 1131 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3); 1132 FREE_C_HEAP_ARRAY(char, aces[0].pSid); 1133 FreeSid(everybodySid); 1134 FreeSid(administratorsSid); 1135 return(lpSA); 1136} 1137 1138 1139// method to create the security attributes structure for restricting 1140// access to the user temporary directory. 1141// 1142// the caller must free the resources associated with the security 1143// attributes structure created by this method by calling the 1144// free_security_attr() method. 1145// 1146static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() { 1147 1148 // create full access rights for the user/owner of the directory 1149 // and read-only access rights for everybody else. This is 1150 // effectively equivalent to UNIX 755 permissions on a directory. 1151 // 1152 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS; 1153 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1154 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1155 1156 return make_user_everybody_admin_security_attr(umask, emask, amask); 1157} 1158 1159// method to create the security attributes structure for restricting 1160// access to the shared memory backing store file. 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_file_security_attr() { 1167 1168 // create extensive access rights for the user/owner of the file 1169 // and attribute read-only access rights for everybody else. This 1170 // is effectively equivalent to UNIX 600 permissions on a file. 1171 // 1172 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1173 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | 1174 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1175 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1176 1177 return make_user_everybody_admin_security_attr(umask, emask, amask); 1178} 1179 1180// method to create the security attributes structure for restricting 1181// access to the name shared memory file mapping object. 1182// 1183// the caller must free the resources associated with the security 1184// attributes structure created by this method by calling the 1185// free_security_attr() method. 1186// 1187static LPSECURITY_ATTRIBUTES make_smo_security_attr() { 1188 1189 // create extensive access rights for the user/owner of the shared 1190 // memory object and attribute read-only access rights for everybody 1191 // else. This is effectively equivalent to UNIX 600 permissions on 1192 // on the shared memory object. 1193 // 1194 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS; 1195 DWORD emask = STANDARD_RIGHTS_READ; // attributes only 1196 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS; 1197 1198 return make_user_everybody_admin_security_attr(umask, emask, amask); 1199} 1200 1201// make the user specific temporary directory 1202// 1203static bool make_user_tmp_dir(const char* dirname) { 1204 1205 1206 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr(); 1207 if (pDirSA == NULL) { 1208 return false; 1209 } 1210 1211 1212 // create the directory with the given security attributes 1213 if (!CreateDirectory(dirname, pDirSA)) { 1214 DWORD lasterror = GetLastError(); 1215 if (lasterror == ERROR_ALREADY_EXISTS) { 1216 // The directory already exists and was probably created by another 1217 // JVM instance. However, this could also be the result of a 1218 // deliberate symlink. Verify that the existing directory is safe. 1219 // 1220 if (!is_directory_secure(dirname)) { 1221 // directory is not secure 1222 if (PrintMiscellaneous && Verbose) { 1223 warning("%s directory is insecure\n", dirname); 1224 } 1225 return false; 1226 } 1227 // The administrator should be able to delete this directory. 1228 // But the directory created by previous version of JVM may not 1229 // have permission for administrators to delete this directory. 1230 // So add full permission to the administrator. Also setting new 1231 // DACLs might fix the corrupted the DACLs. 1232 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1233 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) { 1234 if (PrintMiscellaneous && Verbose) { 1235 lasterror = GetLastError(); 1236 warning("SetFileSecurity failed for %s directory. lasterror %d \n", 1237 dirname, lasterror); 1238 } 1239 } 1240 } 1241 else { 1242 if (PrintMiscellaneous && Verbose) { 1243 warning("CreateDirectory failed: %d\n", GetLastError()); 1244 } 1245 return false; 1246 } 1247 } 1248 1249 // free the security attributes structure 1250 free_security_attr(pDirSA); 1251 1252 return true; 1253} 1254 1255// create the shared memory resources 1256// 1257// This function creates the shared memory resources. This includes 1258// the backing store file and the file mapping shared memory object. 1259// 1260static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) { 1261 1262 HANDLE fh = INVALID_HANDLE_VALUE; 1263 HANDLE fmh = NULL; 1264 1265 1266 // create the security attributes for the backing store file 1267 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr(); 1268 if (lpFileSA == NULL) { 1269 return NULL; 1270 } 1271 1272 // create the security attributes for the shared memory object 1273 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr(); 1274 if (lpSmoSA == NULL) { 1275 free_security_attr(lpFileSA); 1276 return NULL; 1277 } 1278 1279 // create the user temporary directory 1280 if (!make_user_tmp_dir(dirname)) { 1281 // could not make/find the directory or the found directory 1282 // was not secure 1283 return NULL; 1284 } 1285 1286 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the 1287 // file to be deleted by the last process that closes its handle to 1288 // the file. This is important as the apis do not allow a terminating 1289 // JVM being monitored by another process to remove the file name. 1290 // 1291 // the FILE_SHARE_DELETE share mode is valid only in winnt 1292 // 1293 fh = CreateFile( 1294 filename, /* LPCTSTR file name */ 1295 1296 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */ 1297 1298 (os::win32::is_nt() ? FILE_SHARE_DELETE : 0)| 1299 FILE_SHARE_READ, /* DWORD share mode, future READONLY 1300 * open operations allowed 1301 */ 1302 lpFileSA, /* LPSECURITY security attributes */ 1303 CREATE_ALWAYS, /* DWORD creation disposition 1304 * create file, if it already 1305 * exists, overwrite it. 1306 */ 1307 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */ 1308 1309 NULL); /* HANDLE template file access */ 1310 1311 free_security_attr(lpFileSA); 1312 1313 if (fh == INVALID_HANDLE_VALUE) { 1314 DWORD lasterror = GetLastError(); 1315 if (PrintMiscellaneous && Verbose) { 1316 warning("could not create file %s: %d\n", filename, lasterror); 1317 } 1318 return NULL; 1319 } 1320 1321 // try to create the file mapping 1322 fmh = create_file_mapping(objectname, fh, lpSmoSA, size); 1323 1324 free_security_attr(lpSmoSA); 1325 1326 if (fmh == NULL) { 1327 // closing the file handle here will decrement the reference count 1328 // on the file. When all processes accessing the file close their 1329 // handle to it, the reference count will decrement to 0 and the 1330 // OS will delete the file. These semantics are requested by the 1331 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above. 1332 CloseHandle(fh); 1333 fh = NULL; 1334 return NULL; 1335 } 1336 1337 // the file has been successfully created and the file mapping 1338 // object has been created. 1339 sharedmem_fileHandle = fh; 1340 sharedmem_fileName = strdup(filename); 1341 1342 return fmh; 1343} 1344 1345// open the shared memory object for the given vmid. 1346// 1347static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) { 1348 1349 HANDLE fmh; 1350 1351 // open the file mapping with the requested mode 1352 fmh = OpenFileMapping( 1353 ofm_access, /* DWORD access mode */ 1354 FALSE, /* BOOL inherit flag - Do not allow inherit */ 1355 objectname); /* name for object */ 1356 1357 if (fmh == NULL) { 1358 if (PrintMiscellaneous && Verbose) { 1359 warning("OpenFileMapping failed for shared memory object %s:" 1360 " lasterror = %d\n", objectname, GetLastError()); 1361 } 1362 THROW_MSG_(vmSymbols::java_lang_Exception(), 1363 "Could not open PerfMemory", INVALID_HANDLE_VALUE); 1364 } 1365 1366 return fmh;; 1367} 1368 1369// create a named shared memory region 1370// 1371// On Win32, a named shared memory object has a name space that 1372// is independent of the file system name space. Shared memory object, 1373// or more precisely, file mapping objects, provide no mechanism to 1374// inquire the size of the memory region. There is also no api to 1375// enumerate the memory regions for various processes. 1376// 1377// This implementation utilizes the shared memory name space in parallel 1378// with the file system name space. This allows us to determine the 1379// size of the shared memory region from the size of the file and it 1380// allows us to provide a common, file system based name space for 1381// shared memory across platforms. 1382// 1383static char* mapping_create_shared(size_t size) { 1384 1385 void *mapAddress; 1386 int vmid = os::current_process_id(); 1387 1388 // get the name of the user associated with this process 1389 char* user = get_user_name(); 1390 1391 if (user == NULL) { 1392 return NULL; 1393 } 1394 1395 // construct the name of the user specific temporary directory 1396 char* dirname = get_user_tmp_dir(user); 1397 1398 // check that the file system is secure - i.e. it supports ACLs. 1399 if (!is_filesystem_secure(dirname)) { 1400 return NULL; 1401 } 1402 1403 // create the names of the backing store files and for the 1404 // share memory object. 1405 // 1406 char* filename = get_sharedmem_filename(dirname, vmid); 1407 char* objectname = get_sharedmem_objectname(user, vmid); 1408 1409 // cleanup any stale shared memory resources 1410 cleanup_sharedmem_resources(dirname); 1411 1412 assert(((size != 0) && (size % os::vm_page_size() == 0)), 1413 "unexpected PerfMemry region size"); 1414 1415 FREE_C_HEAP_ARRAY(char, user); 1416 1417 // create the shared memory resources 1418 sharedmem_fileMapHandle = 1419 create_sharedmem_resources(dirname, filename, objectname, size); 1420 1421 FREE_C_HEAP_ARRAY(char, filename); 1422 FREE_C_HEAP_ARRAY(char, objectname); 1423 FREE_C_HEAP_ARRAY(char, dirname); 1424 1425 if (sharedmem_fileMapHandle == NULL) { 1426 return NULL; 1427 } 1428 1429 // map the file into the address space 1430 mapAddress = MapViewOfFile( 1431 sharedmem_fileMapHandle, /* HANDLE = file mapping object */ 1432 FILE_MAP_ALL_ACCESS, /* DWORD access flags */ 1433 0, /* DWORD High word of offset */ 1434 0, /* DWORD Low word of offset */ 1435 (DWORD)size); /* DWORD Number of bytes to map */ 1436 1437 if (mapAddress == NULL) { 1438 if (PrintMiscellaneous && Verbose) { 1439 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1440 } 1441 CloseHandle(sharedmem_fileMapHandle); 1442 sharedmem_fileMapHandle = NULL; 1443 return NULL; 1444 } 1445 1446 // clear the shared memory region 1447 (void)memset(mapAddress, '\0', size); 1448 1449 return (char*) mapAddress; 1450} 1451 1452// this method deletes the file mapping object. 1453// 1454static void delete_file_mapping(char* addr, size_t size) { 1455 1456 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1457 // not support unloading of the JVM, unmapping of the memory resource is not 1458 // performed. The memory will be reclaimed by the OS upon termination of all 1459 // processes mapping the resource. The file mapping handle and the file 1460 // handle are closed here to expedite the remove of the file by the OS. The 1461 // file is not removed directly because it was created with 1462 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would 1463 // be unsuccessful. 1464 1465 // close the fileMapHandle. the file mapping will still be retained 1466 // by the OS as long as any other JVM processes has an open file mapping 1467 // handle or a mapped view of the file. 1468 // 1469 if (sharedmem_fileMapHandle != NULL) { 1470 CloseHandle(sharedmem_fileMapHandle); 1471 sharedmem_fileMapHandle = NULL; 1472 } 1473 1474 // close the file handle. This will decrement the reference count on the 1475 // backing store file. When the reference count decrements to 0, the OS 1476 // will delete the file. These semantics apply because the file was 1477 // created with the FILE_FLAG_DELETE_ON_CLOSE flag. 1478 // 1479 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) { 1480 CloseHandle(sharedmem_fileHandle); 1481 sharedmem_fileHandle = INVALID_HANDLE_VALUE; 1482 } 1483} 1484 1485// this method determines the size of the shared memory file 1486// 1487static size_t sharedmem_filesize(const char* filename, TRAPS) { 1488 1489 struct stat statbuf; 1490 1491 // get the file size 1492 // 1493 // on win95/98/me, _stat returns a file size of 0 bytes, but on 1494 // winnt/2k the appropriate file size is returned. support for 1495 // the sharable aspects of performance counters was abandonded 1496 // on the non-nt win32 platforms due to this and other api 1497 // inconsistencies 1498 // 1499 if (::stat(filename, &statbuf) == OS_ERR) { 1500 if (PrintMiscellaneous && Verbose) { 1501 warning("stat %s failed: %s\n", filename, strerror(errno)); 1502 } 1503 THROW_MSG_0(vmSymbols::java_io_IOException(), 1504 "Could not determine PerfMemory size"); 1505 } 1506 1507 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) { 1508 if (PrintMiscellaneous && Verbose) { 1509 warning("unexpected file size: size = " SIZE_FORMAT "\n", 1510 statbuf.st_size); 1511 } 1512 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1513 "Invalid PerfMemory size"); 1514 } 1515 1516 return statbuf.st_size; 1517} 1518 1519// this method opens a file mapping object and maps the object 1520// into the address space of the process 1521// 1522static void open_file_mapping(const char* user, int vmid, 1523 PerfMemory::PerfMemoryMode mode, 1524 char** addrp, size_t* sizep, TRAPS) { 1525 1526 ResourceMark rm; 1527 1528 void *mapAddress = 0; 1529 size_t size; 1530 HANDLE fmh; 1531 DWORD ofm_access; 1532 DWORD mv_access; 1533 const char* luser = NULL; 1534 1535 if (mode == PerfMemory::PERF_MODE_RO) { 1536 ofm_access = FILE_MAP_READ; 1537 mv_access = FILE_MAP_READ; 1538 } 1539 else if (mode == PerfMemory::PERF_MODE_RW) { 1540#ifdef LATER 1541 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE; 1542 mv_access = FILE_MAP_READ | FILE_MAP_WRITE; 1543#else 1544 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1545 "Unsupported access mode"); 1546#endif 1547 } 1548 else { 1549 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1550 "Illegal access mode"); 1551 } 1552 1553 // if a user name wasn't specified, then find the user name for 1554 // the owner of the target vm. 1555 if (user == NULL || strlen(user) == 0) { 1556 luser = get_user_name(vmid); 1557 } 1558 else { 1559 luser = user; 1560 } 1561 1562 if (luser == NULL) { 1563 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1564 "Could not map vmid to user name"); 1565 } 1566 1567 // get the names for the resources for the target vm 1568 char* dirname = get_user_tmp_dir(luser); 1569 1570 // since we don't follow symbolic links when creating the backing 1571 // store file, we also don't following them when attaching 1572 // 1573 if (!is_directory_secure(dirname)) { 1574 FREE_C_HEAP_ARRAY(char, dirname); 1575 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1576 "Process not found"); 1577 } 1578 1579 char* filename = get_sharedmem_filename(dirname, vmid); 1580 char* objectname = get_sharedmem_objectname(luser, vmid); 1581 1582 // copy heap memory to resource memory. the objectname and 1583 // filename are passed to methods that may throw exceptions. 1584 // using resource arrays for these names prevents the leaks 1585 // that would otherwise occur. 1586 // 1587 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 1588 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1); 1589 strcpy(rfilename, filename); 1590 strcpy(robjectname, objectname); 1591 1592 // free the c heap resources that are no longer needed 1593 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 1594 FREE_C_HEAP_ARRAY(char, dirname); 1595 FREE_C_HEAP_ARRAY(char, filename); 1596 FREE_C_HEAP_ARRAY(char, objectname); 1597 1598 if (*sizep == 0) { 1599 size = sharedmem_filesize(rfilename, CHECK); 1600 assert(size != 0, "unexpected size"); 1601 } 1602 1603 // Open the file mapping object with the given name 1604 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK); 1605 1606 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value"); 1607 1608 // map the entire file into the address space 1609 mapAddress = MapViewOfFile( 1610 fmh, /* HANDLE Handle of file mapping object */ 1611 mv_access, /* DWORD access flags */ 1612 0, /* DWORD High word of offset */ 1613 0, /* DWORD Low word of offset */ 1614 size); /* DWORD Number of bytes to map */ 1615 1616 if (mapAddress == NULL) { 1617 if (PrintMiscellaneous && Verbose) { 1618 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1619 } 1620 CloseHandle(fmh); 1621 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 1622 "Could not map PerfMemory"); 1623 } 1624 1625 *addrp = (char*)mapAddress; 1626 *sizep = size; 1627 1628 // File mapping object can be closed at this time without 1629 // invalidating the mapped view of the file 1630 CloseHandle(fmh); 1631 1632 if (PerfTraceMemOps) { 1633 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 1634 INTPTR_FORMAT "\n", size, vmid, mapAddress); 1635 } 1636} 1637 1638// this method unmaps the the mapped view of the the 1639// file mapping object. 1640// 1641static void remove_file_mapping(char* addr) { 1642 1643 // the file mapping object was closed in open_file_mapping() 1644 // after the file map view was created. We only need to 1645 // unmap the file view here. 1646 UnmapViewOfFile(addr); 1647} 1648 1649// create the PerfData memory region in shared memory. 1650static char* create_shared_memory(size_t size) { 1651 1652 return mapping_create_shared(size); 1653} 1654 1655// release a named, shared memory region 1656// 1657void delete_shared_memory(char* addr, size_t size) { 1658 1659 delete_file_mapping(addr, size); 1660} 1661 1662 1663 1664 1665// create the PerfData memory region 1666// 1667// This method creates the memory region used to store performance 1668// data for the JVM. The memory may be created in standard or 1669// shared memory. 1670// 1671void PerfMemory::create_memory_region(size_t size) { 1672 1673 if (PerfDisableSharedMem || !os::win32::is_nt()) { 1674 // do not share the memory for the performance data. 1675 PerfDisableSharedMem = true; 1676 _start = create_standard_memory(size); 1677 } 1678 else { 1679 _start = create_shared_memory(size); 1680 if (_start == NULL) { 1681 1682 // creation of the shared memory region failed, attempt 1683 // to create a contiguous, non-shared memory region instead. 1684 // 1685 if (PrintMiscellaneous && Verbose) { 1686 warning("Reverting to non-shared PerfMemory region.\n"); 1687 } 1688 PerfDisableSharedMem = true; 1689 _start = create_standard_memory(size); 1690 } 1691 } 1692 1693 if (_start != NULL) _capacity = size; 1694 1695} 1696 1697// delete the PerfData memory region 1698// 1699// This method deletes the memory region used to store performance 1700// data for the JVM. The memory region indicated by the <address, size> 1701// tuple will be inaccessible after a call to this method. 1702// 1703void PerfMemory::delete_memory_region() { 1704 1705 assert((start() != NULL && capacity() > 0), "verify proper state"); 1706 1707 // If user specifies PerfDataSaveFile, it will save the performance data 1708 // to the specified file name no matter whether PerfDataSaveToFile is specified 1709 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 1710 // -XX:+PerfDataSaveToFile. 1711 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 1712 save_memory_to_file(start(), capacity()); 1713 } 1714 1715 if (PerfDisableSharedMem) { 1716 delete_standard_memory(start(), capacity()); 1717 } 1718 else { 1719 delete_shared_memory(start(), capacity()); 1720 } 1721} 1722 1723// attach to the PerfData memory region for another JVM 1724// 1725// This method returns an <address, size> tuple that points to 1726// a memory buffer that is kept reasonably synchronized with 1727// the PerfData memory region for the indicated JVM. This 1728// buffer may be kept in synchronization via shared memory 1729// or some other mechanism that keeps the buffer updated. 1730// 1731// If the JVM chooses not to support the attachability feature, 1732// this method should throw an UnsupportedOperation exception. 1733// 1734// This implementation utilizes named shared memory to map 1735// the indicated process's PerfData memory region into this JVMs 1736// address space. 1737// 1738void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, 1739 char** addrp, size_t* sizep, TRAPS) { 1740 1741 if (vmid == 0 || vmid == os::current_process_id()) { 1742 *addrp = start(); 1743 *sizep = capacity(); 1744 return; 1745 } 1746 1747 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK); 1748} 1749 1750// detach from the PerfData memory region of another JVM 1751// 1752// This method detaches the PerfData memory region of another 1753// JVM, specified as an <address, size> tuple of a buffer 1754// in this process's address space. This method may perform 1755// arbitrary actions to accomplish the detachment. The memory 1756// region specified by <address, size> will be inaccessible after 1757// a call to this method. 1758// 1759// If the JVM chooses not to support the attachability feature, 1760// this method should throw an UnsupportedOperation exception. 1761// 1762// This implementation utilizes named shared memory to detach 1763// the indicated process's PerfData memory region from this 1764// process's address space. 1765// 1766void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 1767 1768 assert(addr != 0, "address sanity check"); 1769 assert(bytes > 0, "capacity sanity check"); 1770 1771 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1772 // prevent accidental detachment of this process's PerfMemory region 1773 return; 1774 } 1775 1776 remove_file_mapping(addr); 1777} 1778 1779char* PerfMemory::backing_store_filename() { 1780 return sharedmem_fileName; 1781} 1782