perfMemory_windows.cpp revision 10302:046cdd3a4173
1/* 2 * Copyright (c) 2001, 2014, 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 "precompiled.hpp" 26#include "classfile/vmSymbols.hpp" 27#include "memory/allocation.inline.hpp" 28#include "memory/resourceArea.hpp" 29#include "oops/oop.inline.hpp" 30#include "os_windows.inline.hpp" 31#include "runtime/handles.inline.hpp" 32#include "runtime/os.hpp" 33#include "runtime/perfMemory.hpp" 34#include "services/memTracker.hpp" 35#include "utilities/exceptions.hpp" 36 37#include <windows.h> 38#include <sys/types.h> 39#include <sys/stat.h> 40#include <errno.h> 41#include <lmcons.h> 42 43typedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)( 44 IN PSECURITY_DESCRIPTOR pSecurityDescriptor, 45 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest, 46 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet); 47 48// Standard Memory Implementation Details 49 50// create the PerfData memory region in standard memory. 51// 52static char* create_standard_memory(size_t size) { 53 54 // allocate an aligned chuck of memory 55 char* mapAddress = os::reserve_memory(size); 56 57 if (mapAddress == NULL) { 58 return NULL; 59 } 60 61 // commit memory 62 if (!os::commit_memory(mapAddress, size, !ExecMem)) { 63 if (PrintMiscellaneous && Verbose) { 64 warning("Could not commit PerfData memory\n"); 65 } 66 os::release_memory(mapAddress, size); 67 return NULL; 68 } 69 70 return mapAddress; 71} 72 73// delete the PerfData memory region 74// 75static void delete_standard_memory(char* addr, size_t size) { 76 77 // there are no persistent external resources to cleanup for standard 78 // memory. since DestroyJavaVM does not support unloading of the JVM, 79 // cleanup of the memory resource is not performed. The memory will be 80 // reclaimed by the OS upon termination of the process. 81 // 82 return; 83 84} 85 86// save the specified memory region to the given file 87// 88static void save_memory_to_file(char* addr, size_t size) { 89 90 const char* destfile = PerfMemory::get_perfdata_file_path(); 91 assert(destfile[0] != '\0', "invalid Perfdata file path"); 92 93 int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC, 94 _S_IREAD|_S_IWRITE); 95 96 if (fd == OS_ERR) { 97 if (PrintMiscellaneous && Verbose) { 98 warning("Could not create Perfdata save file: %s: %s\n", 99 destfile, strerror(errno)); 100 } 101 } else { 102 for (size_t remaining = size; remaining > 0;) { 103 104 int nbytes = ::_write(fd, addr, (unsigned int)remaining); 105 if (nbytes == OS_ERR) { 106 if (PrintMiscellaneous && Verbose) { 107 warning("Could not write Perfdata save file: %s: %s\n", 108 destfile, strerror(errno)); 109 } 110 break; 111 } 112 113 remaining -= (size_t)nbytes; 114 addr += nbytes; 115 } 116 117 int result = ::_close(fd); 118 if (PrintMiscellaneous && Verbose) { 119 if (result == OS_ERR) { 120 warning("Could not close %s: %s\n", destfile, strerror(errno)); 121 } 122 } 123 } 124 125 FREE_C_HEAP_ARRAY(char, destfile); 126} 127 128// Shared Memory Implementation Details 129 130// Note: the win32 shared memory implementation uses two objects to represent 131// the shared memory: a windows kernel based file mapping object and a backing 132// store file. On windows, the name space for shared memory is a kernel 133// based name space that is disjoint from other win32 name spaces. Since Java 134// is unaware of this name space, a parallel file system based name space is 135// maintained, which provides a common file system based shared memory name 136// space across the supported platforms and one that Java apps can deal with 137// through simple file apis. 138// 139// For performance and resource cleanup reasons, it is recommended that the 140// user specific directory and the backing store file be stored in either a 141// RAM based file system or a local disk based file system. Network based 142// file systems are not recommended for performance reasons. In addition, 143// use of SMB network based file systems may result in unsuccesful cleanup 144// of the disk based resource on exit of the VM. The Windows TMP and TEMP 145// environement variables, as used by the GetTempPath() Win32 API (see 146// os::get_temp_directory() in os_win32.cpp), control the location of the 147// user specific directory and the shared memory backing store file. 148 149static HANDLE sharedmem_fileMapHandle = NULL; 150static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE; 151static char* sharedmem_fileName = NULL; 152 153// return the user specific temporary directory name. 154// 155// the caller is expected to free the allocated memory. 156// 157static char* get_user_tmp_dir(const char* user) { 158 159 const char* tmpdir = os::get_temp_directory(); 160 const char* perfdir = PERFDATA_NAME; 161 size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3; 162 char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 163 164 // construct the path name to user specific tmp directory 165 _snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user); 166 167 return dirname; 168} 169 170// convert the given file name into a process id. if the file 171// does not meet the file naming constraints, return 0. 172// 173static int filename_to_pid(const char* filename) { 174 175 // a filename that doesn't begin with a digit is not a 176 // candidate for conversion. 177 // 178 if (!isdigit(*filename)) { 179 return 0; 180 } 181 182 // check if file name can be converted to an integer without 183 // any leftover characters. 184 // 185 char* remainder = NULL; 186 errno = 0; 187 int pid = (int)strtol(filename, &remainder, 10); 188 189 if (errno != 0) { 190 return 0; 191 } 192 193 // check for left over characters. If any, then the filename is 194 // not a candidate for conversion. 195 // 196 if (remainder != NULL && *remainder != '\0') { 197 return 0; 198 } 199 200 // successful conversion, return the pid 201 return pid; 202} 203 204// check if the given path is considered a secure directory for 205// the backing store files. Returns true if the directory exists 206// and is considered a secure location. Returns false if the path 207// is a symbolic link or if an error occurred. 208// 209static bool is_directory_secure(const char* path) { 210 211 DWORD fa; 212 213 fa = GetFileAttributes(path); 214 if (fa == 0xFFFFFFFF) { 215 DWORD lasterror = GetLastError(); 216 if (lasterror == ERROR_FILE_NOT_FOUND) { 217 return false; 218 } 219 else { 220 // unexpected error, declare the path insecure 221 if (PrintMiscellaneous && Verbose) { 222 warning("could not get attributes for file %s: ", 223 " lasterror = %d\n", path, lasterror); 224 } 225 return false; 226 } 227 } 228 229 if (fa & FILE_ATTRIBUTE_REPARSE_POINT) { 230 // we don't accept any redirection for the user specific directory 231 // so declare the path insecure. This may be too conservative, 232 // as some types of reparse points might be acceptable, but it 233 // is probably more secure to avoid these conditions. 234 // 235 if (PrintMiscellaneous && Verbose) { 236 warning("%s is a reparse point\n", path); 237 } 238 return false; 239 } 240 241 if (fa & FILE_ATTRIBUTE_DIRECTORY) { 242 // this is the expected case. Since windows supports symbolic 243 // links to directories only, not to files, there is no need 244 // to check for open write permissions on the directory. If the 245 // directory has open write permissions, any files deposited that 246 // are not expected will be removed by the cleanup code. 247 // 248 return true; 249 } 250 else { 251 // this is either a regular file or some other type of file, 252 // any of which are unexpected and therefore insecure. 253 // 254 if (PrintMiscellaneous && Verbose) { 255 warning("%s is not a directory, file attributes = " 256 INTPTR_FORMAT "\n", path, fa); 257 } 258 return false; 259 } 260} 261 262// return the user name for the owner of this process 263// 264// the caller is expected to free the allocated memory. 265// 266static char* get_user_name() { 267 268 /* get the user name. This code is adapted from code found in 269 * the jdk in src/windows/native/java/lang/java_props_md.c 270 * java_props_md.c 1.29 02/02/06. According to the original 271 * source, the call to GetUserName is avoided because of a resulting 272 * increase in footprint of 100K. 273 */ 274 char* user = getenv("USERNAME"); 275 char buf[UNLEN+1]; 276 DWORD buflen = sizeof(buf); 277 if (user == NULL || strlen(user) == 0) { 278 if (GetUserName(buf, &buflen)) { 279 user = buf; 280 } 281 else { 282 return NULL; 283 } 284 } 285 286 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal); 287 strcpy(user_name, user); 288 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); 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); 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); 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); 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); 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); 406 } 407 } 408 os::closedir(subdirp); 409 FREE_C_HEAP_ARRAY(char, udbuf); 410 FREE_C_HEAP_ARRAY(char, usrdir_name); 411 } 412 os::closedir(tmpdirp); 413 FREE_C_HEAP_ARRAY(char, tdbuf); 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); 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 os::closedir(dirp); 632 return; 633 } 634 635 // for each entry in the directory that matches the expected file 636 // name pattern, determine if the file resources are stale and if 637 // so, remove the file resources. Note, instrumented HotSpot processes 638 // for this user may start and/or terminate during this search and 639 // remove or create new files in this directory. The behavior of this 640 // loop under these conditions is dependent upon the implementation of 641 // opendir/readdir. 642 // 643 struct dirent* entry; 644 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal); 645 errno = 0; 646 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 647 648 int pid = filename_to_pid(entry->d_name); 649 650 if (pid == 0) { 651 652 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 653 654 // attempt to remove all unexpected files, except "." and ".." 655 remove_file(dirname, entry->d_name); 656 } 657 658 errno = 0; 659 continue; 660 } 661 662 // we now have a file name that converts to a valid integer 663 // that could represent a process id . if this process id 664 // matches the current process id or the process is not running, 665 // then remove the stale file resources. 666 // 667 // process liveness is detected by checking the exit status 668 // of the process. if the process id is valid and the exit status 669 // indicates that it is still running, the file file resources 670 // are not removed. If the process id is invalid, or if we don't 671 // have permissions to check the process status, or if the process 672 // id is valid and the process has terminated, the the file resources 673 // are assumed to be stale and are removed. 674 // 675 if (pid == os::current_process_id() || !is_alive(pid)) { 676 677 // we can only remove the file resources. Any mapped views 678 // of the file can only be unmapped by the processes that 679 // opened those views and the file mapping object will not 680 // get removed until all views are unmapped. 681 // 682 remove_file(dirname, entry->d_name); 683 } 684 errno = 0; 685 } 686 os::closedir(dirp); 687 FREE_C_HEAP_ARRAY(char, dbuf); 688} 689 690// create a file mapping object with the requested name, and size 691// from the file represented by the given Handle object 692// 693static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) { 694 695 DWORD lowSize = (DWORD)size; 696 DWORD highSize = 0; 697 HANDLE fmh = NULL; 698 699 // Create a file mapping object with the given name. This function 700 // will grow the file to the specified size. 701 // 702 fmh = CreateFileMapping( 703 fh, /* HANDLE file handle for backing store */ 704 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */ 705 PAGE_READWRITE, /* DWORD protections */ 706 highSize, /* DWORD High word of max size */ 707 lowSize, /* DWORD Low word of max size */ 708 name); /* LPCTSTR name for object */ 709 710 if (fmh == NULL) { 711 if (PrintMiscellaneous && Verbose) { 712 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError()); 713 } 714 return NULL; 715 } 716 717 if (GetLastError() == ERROR_ALREADY_EXISTS) { 718 719 // a stale file mapping object was encountered. This object may be 720 // owned by this or some other user and cannot be removed until 721 // the other processes either exit or close their mapping objects 722 // and/or mapped views of this mapping object. 723 // 724 if (PrintMiscellaneous && Verbose) { 725 warning("file mapping already exists, lasterror = %d\n", GetLastError()); 726 } 727 728 CloseHandle(fmh); 729 return NULL; 730 } 731 732 return fmh; 733} 734 735 736// method to free the given security descriptor and the contained 737// access control list. 738// 739static void free_security_desc(PSECURITY_DESCRIPTOR pSD) { 740 741 BOOL success, exists, isdefault; 742 PACL pACL; 743 744 if (pSD != NULL) { 745 746 // get the access control list from the security descriptor 747 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault); 748 749 // if an ACL existed and it was not a default acl, then it must 750 // be an ACL we enlisted. free the resources. 751 // 752 if (success && exists && pACL != NULL && !isdefault) { 753 FREE_C_HEAP_ARRAY(char, pACL); 754 } 755 756 // free the security descriptor 757 FREE_C_HEAP_ARRAY(char, pSD); 758 } 759} 760 761// method to free up a security attributes structure and any 762// contained security descriptors and ACL 763// 764static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) { 765 766 if (lpSA != NULL) { 767 // free the contained security descriptor and the ACL 768 free_security_desc(lpSA->lpSecurityDescriptor); 769 lpSA->lpSecurityDescriptor = NULL; 770 771 // free the security attributes structure 772 FREE_C_HEAP_ARRAY(char, lpSA); 773 } 774} 775 776// get the user SID for the process indicated by the process handle 777// 778static PSID get_user_sid(HANDLE hProcess) { 779 780 HANDLE hAccessToken; 781 PTOKEN_USER token_buf = NULL; 782 DWORD rsize = 0; 783 784 if (hProcess == NULL) { 785 return NULL; 786 } 787 788 // get the process token 789 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) { 790 if (PrintMiscellaneous && Verbose) { 791 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError()); 792 } 793 return NULL; 794 } 795 796 // determine the size of the token structured needed to retrieve 797 // the user token information from the access token. 798 // 799 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) { 800 DWORD lasterror = GetLastError(); 801 if (lasterror != ERROR_INSUFFICIENT_BUFFER) { 802 if (PrintMiscellaneous && Verbose) { 803 warning("GetTokenInformation failure: lasterror = %d," 804 " rsize = %d\n", lasterror, rsize); 805 } 806 CloseHandle(hAccessToken); 807 return NULL; 808 } 809 } 810 811 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal); 812 813 // get the user token information 814 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) { 815 if (PrintMiscellaneous && Verbose) { 816 warning("GetTokenInformation failure: lasterror = %d," 817 " rsize = %d\n", GetLastError(), rsize); 818 } 819 FREE_C_HEAP_ARRAY(char, token_buf); 820 CloseHandle(hAccessToken); 821 return NULL; 822 } 823 824 DWORD nbytes = GetLengthSid(token_buf->User.Sid); 825 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 826 827 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) { 828 if (PrintMiscellaneous && Verbose) { 829 warning("GetTokenInformation failure: lasterror = %d," 830 " rsize = %d\n", GetLastError(), rsize); 831 } 832 FREE_C_HEAP_ARRAY(char, token_buf); 833 FREE_C_HEAP_ARRAY(char, pSID); 834 CloseHandle(hAccessToken); 835 return NULL; 836 } 837 838 // close the access token. 839 CloseHandle(hAccessToken); 840 FREE_C_HEAP_ARRAY(char, token_buf); 841 842 return pSID; 843} 844 845// structure used to consolidate access control entry information 846// 847typedef struct ace_data { 848 PSID pSid; // SID of the ACE 849 DWORD mask; // mask for the ACE 850} ace_data_t; 851 852 853// method to add an allow access control entry with the access rights 854// indicated in mask for the principal indicated in SID to the given 855// security descriptor. Much of the DACL handling was adapted from 856// the example provided here: 857// http://support.microsoft.com/kb/102102/EN-US/ 858// 859 860static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD, 861 ace_data_t aces[], int ace_count) { 862 PACL newACL = NULL; 863 PACL oldACL = NULL; 864 865 if (pSD == NULL) { 866 return false; 867 } 868 869 BOOL exists, isdefault; 870 871 // retrieve any existing access control list. 872 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) { 873 if (PrintMiscellaneous && Verbose) { 874 warning("GetSecurityDescriptor failure: lasterror = %d \n", 875 GetLastError()); 876 } 877 return false; 878 } 879 880 // get the size of the DACL 881 ACL_SIZE_INFORMATION aclinfo; 882 883 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent) 884 // while oldACL is NULL for some case. 885 if (oldACL == NULL) { 886 exists = FALSE; 887 } 888 889 if (exists) { 890 if (!GetAclInformation(oldACL, &aclinfo, 891 sizeof(ACL_SIZE_INFORMATION), 892 AclSizeInformation)) { 893 if (PrintMiscellaneous && Verbose) { 894 warning("GetAclInformation failure: lasterror = %d \n", GetLastError()); 895 return false; 896 } 897 } 898 } else { 899 aclinfo.AceCount = 0; // assume NULL DACL 900 aclinfo.AclBytesFree = 0; 901 aclinfo.AclBytesInUse = sizeof(ACL); 902 } 903 904 // compute the size needed for the new ACL 905 // initial size of ACL is sum of the following: 906 // * size of ACL structure. 907 // * size of each ACE structure that ACL is to contain minus the sid 908 // sidStart member (DWORD) of the ACE. 909 // * length of the SID that each ACE is to contain. 910 DWORD newACLsize = aclinfo.AclBytesInUse + 911 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count; 912 for (int i = 0; i < ace_count; i++) { 913 assert(aces[i].pSid != 0, "pSid should not be 0"); 914 newACLsize += GetLengthSid(aces[i].pSid); 915 } 916 917 // create the new ACL 918 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal); 919 920 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) { 921 if (PrintMiscellaneous && Verbose) { 922 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 923 } 924 FREE_C_HEAP_ARRAY(char, newACL); 925 return false; 926 } 927 928 unsigned int ace_index = 0; 929 // copy any existing ACEs from the old ACL (if any) to the new ACL. 930 if (aclinfo.AceCount != 0) { 931 while (ace_index < aclinfo.AceCount) { 932 LPVOID ace; 933 if (!GetAce(oldACL, ace_index, &ace)) { 934 if (PrintMiscellaneous && Verbose) { 935 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 936 } 937 FREE_C_HEAP_ARRAY(char, newACL); 938 return false; 939 } 940 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) { 941 // this is an inherited, allowed ACE; break from loop so we can 942 // add the new access allowed, non-inherited ACE in the correct 943 // position, immediately following all non-inherited ACEs. 944 break; 945 } 946 947 // determine if the SID of this ACE matches any of the SIDs 948 // for which we plan to set ACEs. 949 int matches = 0; 950 for (int i = 0; i < ace_count; i++) { 951 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) { 952 matches++; 953 break; 954 } 955 } 956 957 // if there are no SID matches, then add this existing ACE to the new ACL 958 if (matches == 0) { 959 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 960 ((PACE_HEADER)ace)->AceSize)) { 961 if (PrintMiscellaneous && Verbose) { 962 warning("AddAce failure: lasterror = %d \n", GetLastError()); 963 } 964 FREE_C_HEAP_ARRAY(char, newACL); 965 return false; 966 } 967 } 968 ace_index++; 969 } 970 } 971 972 // add the passed-in access control entries to the new ACL 973 for (int i = 0; i < ace_count; i++) { 974 if (!AddAccessAllowedAce(newACL, ACL_REVISION, 975 aces[i].mask, aces[i].pSid)) { 976 if (PrintMiscellaneous && Verbose) { 977 warning("AddAccessAllowedAce failure: lasterror = %d \n", 978 GetLastError()); 979 } 980 FREE_C_HEAP_ARRAY(char, newACL); 981 return false; 982 } 983 } 984 985 // now copy the rest of the inherited ACEs from the old ACL 986 if (aclinfo.AceCount != 0) { 987 // picking up at ace_index, where we left off in the 988 // previous ace_index loop 989 while (ace_index < aclinfo.AceCount) { 990 LPVOID ace; 991 if (!GetAce(oldACL, ace_index, &ace)) { 992 if (PrintMiscellaneous && Verbose) { 993 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 994 } 995 FREE_C_HEAP_ARRAY(char, newACL); 996 return false; 997 } 998 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 999 ((PACE_HEADER)ace)->AceSize)) { 1000 if (PrintMiscellaneous && Verbose) { 1001 warning("AddAce failure: lasterror = %d \n", GetLastError()); 1002 } 1003 FREE_C_HEAP_ARRAY(char, newACL); 1004 return false; 1005 } 1006 ace_index++; 1007 } 1008 } 1009 1010 // add the new ACL to the security descriptor. 1011 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) { 1012 if (PrintMiscellaneous && Verbose) { 1013 warning("SetSecurityDescriptorDacl failure:" 1014 " lasterror = %d \n", GetLastError()); 1015 } 1016 FREE_C_HEAP_ARRAY(char, newACL); 1017 return false; 1018 } 1019 1020 // if running on windows 2000 or later, set the automatic inheritance 1021 // control flags. 1022 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl; 1023 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr) 1024 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")), 1025 "SetSecurityDescriptorControl"); 1026 1027 if (_SetSecurityDescriptorControl != NULL) { 1028 // We do not want to further propagate inherited DACLs, so making them 1029 // protected prevents that. 1030 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, 1031 SE_DACL_PROTECTED)) { 1032 if (PrintMiscellaneous && Verbose) { 1033 warning("SetSecurityDescriptorControl failure:" 1034 " lasterror = %d \n", GetLastError()); 1035 } 1036 FREE_C_HEAP_ARRAY(char, newACL); 1037 return false; 1038 } 1039 } 1040 // Note, the security descriptor maintains a reference to the newACL, not 1041 // a copy of it. Therefore, the newACL is not freed here. It is freed when 1042 // the security descriptor containing its reference is freed. 1043 // 1044 return true; 1045} 1046 1047// method to create a security attributes structure, which contains a 1048// security descriptor and an access control list comprised of 0 or more 1049// access control entries. The method take an array of ace_data structures 1050// that indicate the ACE to be added to the security descriptor. 1051// 1052// the caller must free the resources associated with the security 1053// attributes structure created by this method by calling the 1054// free_security_attr() method. 1055// 1056static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) { 1057 1058 // allocate space for a security descriptor 1059 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) 1060 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal); 1061 1062 // initialize the security descriptor 1063 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { 1064 if (PrintMiscellaneous && Verbose) { 1065 warning("InitializeSecurityDescriptor failure: " 1066 "lasterror = %d \n", GetLastError()); 1067 } 1068 free_security_desc(pSD); 1069 return NULL; 1070 } 1071 1072 // add the access control entries 1073 if (!add_allow_aces(pSD, aces, count)) { 1074 free_security_desc(pSD); 1075 return NULL; 1076 } 1077 1078 // allocate and initialize the security attributes structure and 1079 // return it to the caller. 1080 // 1081 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES) 1082 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES), mtInternal); 1083 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES); 1084 lpSA->lpSecurityDescriptor = pSD; 1085 lpSA->bInheritHandle = FALSE; 1086 1087 return(lpSA); 1088} 1089 1090// method to create a security attributes structure with a restrictive 1091// access control list that creates a set access rights for the user/owner 1092// of the securable object and a separate set access rights for everyone else. 1093// also provides for full access rights for the administrator group. 1094// 1095// the caller must free the resources associated with the security 1096// attributes structure created by this method by calling the 1097// free_security_attr() method. 1098// 1099 1100static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr( 1101 DWORD umask, DWORD emask, DWORD amask) { 1102 1103 ace_data_t aces[3]; 1104 1105 // initialize the user ace data 1106 aces[0].pSid = get_user_sid(GetCurrentProcess()); 1107 aces[0].mask = umask; 1108 1109 if (aces[0].pSid == 0) 1110 return NULL; 1111 1112 // get the well known SID for BUILTIN\Administrators 1113 PSID administratorsSid = NULL; 1114 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY; 1115 1116 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2, 1117 SECURITY_BUILTIN_DOMAIN_RID, 1118 DOMAIN_ALIAS_RID_ADMINS, 1119 0, 0, 0, 0, 0, 0, &administratorsSid)) { 1120 1121 if (PrintMiscellaneous && Verbose) { 1122 warning("AllocateAndInitializeSid failure: " 1123 "lasterror = %d \n", GetLastError()); 1124 } 1125 return NULL; 1126 } 1127 1128 // initialize the ace data for administrator group 1129 aces[1].pSid = administratorsSid; 1130 aces[1].mask = amask; 1131 1132 // get the well known SID for the universal Everybody 1133 PSID everybodySid = NULL; 1134 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY; 1135 1136 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID, 1137 0, 0, 0, 0, 0, 0, 0, &everybodySid)) { 1138 1139 if (PrintMiscellaneous && Verbose) { 1140 warning("AllocateAndInitializeSid failure: " 1141 "lasterror = %d \n", GetLastError()); 1142 } 1143 return NULL; 1144 } 1145 1146 // initialize the ace data for everybody else. 1147 aces[2].pSid = everybodySid; 1148 aces[2].mask = emask; 1149 1150 // create a security attributes structure with access control 1151 // entries as initialized above. 1152 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3); 1153 FREE_C_HEAP_ARRAY(char, aces[0].pSid); 1154 FreeSid(everybodySid); 1155 FreeSid(administratorsSid); 1156 return(lpSA); 1157} 1158 1159 1160// method to create the security attributes structure for restricting 1161// access to the user temporary directory. 1162// 1163// the caller must free the resources associated with the security 1164// attributes structure created by this method by calling the 1165// free_security_attr() method. 1166// 1167static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() { 1168 1169 // create full access rights for the user/owner of the directory 1170 // and read-only access rights for everybody else. This is 1171 // effectively equivalent to UNIX 755 permissions on a directory. 1172 // 1173 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS; 1174 DWORD emask = GENERIC_READ | 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 shared memory backing store file. 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_file_security_attr() { 1188 1189 // create extensive access rights for the user/owner of the file 1190 // and attribute read-only access rights for everybody else. This 1191 // is effectively equivalent to UNIX 600 permissions on a file. 1192 // 1193 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1194 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | 1195 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1196 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1197 1198 return make_user_everybody_admin_security_attr(umask, emask, amask); 1199} 1200 1201// method to create the security attributes structure for restricting 1202// access to the name shared memory file mapping object. 1203// 1204// the caller must free the resources associated with the security 1205// attributes structure created by this method by calling the 1206// free_security_attr() method. 1207// 1208static LPSECURITY_ATTRIBUTES make_smo_security_attr() { 1209 1210 // create extensive access rights for the user/owner of the shared 1211 // memory object and attribute read-only access rights for everybody 1212 // else. This is effectively equivalent to UNIX 600 permissions on 1213 // on the shared memory object. 1214 // 1215 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS; 1216 DWORD emask = STANDARD_RIGHTS_READ; // attributes only 1217 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS; 1218 1219 return make_user_everybody_admin_security_attr(umask, emask, amask); 1220} 1221 1222// make the user specific temporary directory 1223// 1224static bool make_user_tmp_dir(const char* dirname) { 1225 1226 1227 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr(); 1228 if (pDirSA == NULL) { 1229 return false; 1230 } 1231 1232 1233 // create the directory with the given security attributes 1234 if (!CreateDirectory(dirname, pDirSA)) { 1235 DWORD lasterror = GetLastError(); 1236 if (lasterror == ERROR_ALREADY_EXISTS) { 1237 // The directory already exists and was probably created by another 1238 // JVM instance. However, this could also be the result of a 1239 // deliberate symlink. Verify that the existing directory is safe. 1240 // 1241 if (!is_directory_secure(dirname)) { 1242 // directory is not secure 1243 if (PrintMiscellaneous && Verbose) { 1244 warning("%s directory is insecure\n", dirname); 1245 } 1246 return false; 1247 } 1248 // The administrator should be able to delete this directory. 1249 // But the directory created by previous version of JVM may not 1250 // have permission for administrators to delete this directory. 1251 // So add full permission to the administrator. Also setting new 1252 // DACLs might fix the corrupted the DACLs. 1253 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1254 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) { 1255 if (PrintMiscellaneous && Verbose) { 1256 lasterror = GetLastError(); 1257 warning("SetFileSecurity failed for %s directory. lasterror %d \n", 1258 dirname, lasterror); 1259 } 1260 } 1261 } 1262 else { 1263 if (PrintMiscellaneous && Verbose) { 1264 warning("CreateDirectory failed: %d\n", GetLastError()); 1265 } 1266 return false; 1267 } 1268 } 1269 1270 // free the security attributes structure 1271 free_security_attr(pDirSA); 1272 1273 return true; 1274} 1275 1276// create the shared memory resources 1277// 1278// This function creates the shared memory resources. This includes 1279// the backing store file and the file mapping shared memory object. 1280// 1281static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) { 1282 1283 HANDLE fh = INVALID_HANDLE_VALUE; 1284 HANDLE fmh = NULL; 1285 1286 1287 // create the security attributes for the backing store file 1288 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr(); 1289 if (lpFileSA == NULL) { 1290 return NULL; 1291 } 1292 1293 // create the security attributes for the shared memory object 1294 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr(); 1295 if (lpSmoSA == NULL) { 1296 free_security_attr(lpFileSA); 1297 return NULL; 1298 } 1299 1300 // create the user temporary directory 1301 if (!make_user_tmp_dir(dirname)) { 1302 // could not make/find the directory or the found directory 1303 // was not secure 1304 return NULL; 1305 } 1306 1307 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the 1308 // file to be deleted by the last process that closes its handle to 1309 // the file. This is important as the apis do not allow a terminating 1310 // JVM being monitored by another process to remove the file name. 1311 // 1312 fh = CreateFile( 1313 filename, /* LPCTSTR file name */ 1314 1315 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */ 1316 FILE_SHARE_DELETE|FILE_SHARE_READ, /* DWORD share mode, future READONLY 1317 * open operations allowed 1318 */ 1319 lpFileSA, /* LPSECURITY security attributes */ 1320 CREATE_ALWAYS, /* DWORD creation disposition 1321 * create file, if it already 1322 * exists, overwrite it. 1323 */ 1324 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */ 1325 1326 NULL); /* HANDLE template file access */ 1327 1328 free_security_attr(lpFileSA); 1329 1330 if (fh == INVALID_HANDLE_VALUE) { 1331 DWORD lasterror = GetLastError(); 1332 if (PrintMiscellaneous && Verbose) { 1333 warning("could not create file %s: %d\n", filename, lasterror); 1334 } 1335 return NULL; 1336 } 1337 1338 // try to create the file mapping 1339 fmh = create_file_mapping(objectname, fh, lpSmoSA, size); 1340 1341 free_security_attr(lpSmoSA); 1342 1343 if (fmh == NULL) { 1344 // closing the file handle here will decrement the reference count 1345 // on the file. When all processes accessing the file close their 1346 // handle to it, the reference count will decrement to 0 and the 1347 // OS will delete the file. These semantics are requested by the 1348 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above. 1349 CloseHandle(fh); 1350 fh = NULL; 1351 return NULL; 1352 } else { 1353 // We created the file mapping, but rarely the size of the 1354 // backing store file is reported as zero (0) which can cause 1355 // failures when trying to use the hsperfdata file. 1356 struct stat statbuf; 1357 int ret_code = ::stat(filename, &statbuf); 1358 if (ret_code == OS_ERR) { 1359 if (PrintMiscellaneous && Verbose) { 1360 warning("Could not get status information from file %s: %s\n", 1361 filename, strerror(errno)); 1362 } 1363 CloseHandle(fmh); 1364 CloseHandle(fh); 1365 fh = NULL; 1366 fmh = NULL; 1367 return NULL; 1368 } 1369 1370 // We could always call FlushFileBuffers() but the Microsoft 1371 // docs indicate that it is considered expensive so we only 1372 // call it when we observe the size as zero (0). 1373 if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) { 1374 DWORD lasterror = GetLastError(); 1375 if (PrintMiscellaneous && Verbose) { 1376 warning("could not flush file %s: %d\n", filename, lasterror); 1377 } 1378 CloseHandle(fmh); 1379 CloseHandle(fh); 1380 fh = NULL; 1381 fmh = NULL; 1382 return NULL; 1383 } 1384 } 1385 1386 // the file has been successfully created and the file mapping 1387 // object has been created. 1388 sharedmem_fileHandle = fh; 1389 sharedmem_fileName = os::strdup(filename); 1390 1391 return fmh; 1392} 1393 1394// open the shared memory object for the given vmid. 1395// 1396static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) { 1397 1398 HANDLE fmh; 1399 1400 // open the file mapping with the requested mode 1401 fmh = OpenFileMapping( 1402 ofm_access, /* DWORD access mode */ 1403 FALSE, /* BOOL inherit flag - Do not allow inherit */ 1404 objectname); /* name for object */ 1405 1406 if (fmh == NULL) { 1407 if (PrintMiscellaneous && Verbose) { 1408 warning("OpenFileMapping failed for shared memory object %s:" 1409 " lasterror = %d\n", objectname, GetLastError()); 1410 } 1411 THROW_MSG_(vmSymbols::java_lang_Exception(), 1412 "Could not open PerfMemory", INVALID_HANDLE_VALUE); 1413 } 1414 1415 return fmh;; 1416} 1417 1418// create a named shared memory region 1419// 1420// On Win32, a named shared memory object has a name space that 1421// is independent of the file system name space. Shared memory object, 1422// or more precisely, file mapping objects, provide no mechanism to 1423// inquire the size of the memory region. There is also no api to 1424// enumerate the memory regions for various processes. 1425// 1426// This implementation utilizes the shared memory name space in parallel 1427// with the file system name space. This allows us to determine the 1428// size of the shared memory region from the size of the file and it 1429// allows us to provide a common, file system based name space for 1430// shared memory across platforms. 1431// 1432static char* mapping_create_shared(size_t size) { 1433 1434 void *mapAddress; 1435 int vmid = os::current_process_id(); 1436 1437 // get the name of the user associated with this process 1438 char* user = get_user_name(); 1439 1440 if (user == NULL) { 1441 return NULL; 1442 } 1443 1444 // construct the name of the user specific temporary directory 1445 char* dirname = get_user_tmp_dir(user); 1446 1447 // check that the file system is secure - i.e. it supports ACLs. 1448 if (!is_filesystem_secure(dirname)) { 1449 FREE_C_HEAP_ARRAY(char, dirname); 1450 FREE_C_HEAP_ARRAY(char, user); 1451 return NULL; 1452 } 1453 1454 // create the names of the backing store files and for the 1455 // share memory object. 1456 // 1457 char* filename = get_sharedmem_filename(dirname, vmid); 1458 char* objectname = get_sharedmem_objectname(user, vmid); 1459 1460 // cleanup any stale shared memory resources 1461 cleanup_sharedmem_resources(dirname); 1462 1463 assert(((size != 0) && (size % os::vm_page_size() == 0)), 1464 "unexpected PerfMemry region size"); 1465 1466 FREE_C_HEAP_ARRAY(char, user); 1467 1468 // create the shared memory resources 1469 sharedmem_fileMapHandle = 1470 create_sharedmem_resources(dirname, filename, objectname, size); 1471 1472 FREE_C_HEAP_ARRAY(char, filename); 1473 FREE_C_HEAP_ARRAY(char, objectname); 1474 FREE_C_HEAP_ARRAY(char, dirname); 1475 1476 if (sharedmem_fileMapHandle == NULL) { 1477 return NULL; 1478 } 1479 1480 // map the file into the address space 1481 mapAddress = MapViewOfFile( 1482 sharedmem_fileMapHandle, /* HANDLE = file mapping object */ 1483 FILE_MAP_ALL_ACCESS, /* DWORD access flags */ 1484 0, /* DWORD High word of offset */ 1485 0, /* DWORD Low word of offset */ 1486 (DWORD)size); /* DWORD Number of bytes to map */ 1487 1488 if (mapAddress == NULL) { 1489 if (PrintMiscellaneous && Verbose) { 1490 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1491 } 1492 CloseHandle(sharedmem_fileMapHandle); 1493 sharedmem_fileMapHandle = NULL; 1494 return NULL; 1495 } 1496 1497 // clear the shared memory region 1498 (void)memset(mapAddress, '\0', size); 1499 1500 // it does not go through os api, the operation has to record from here 1501 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, 1502 size, CURRENT_PC, mtInternal); 1503 1504 return (char*) mapAddress; 1505} 1506 1507// this method deletes the file mapping object. 1508// 1509static void delete_file_mapping(char* addr, size_t size) { 1510 1511 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1512 // not support unloading of the JVM, unmapping of the memory resource is not 1513 // performed. The memory will be reclaimed by the OS upon termination of all 1514 // processes mapping the resource. The file mapping handle and the file 1515 // handle are closed here to expedite the remove of the file by the OS. The 1516 // file is not removed directly because it was created with 1517 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would 1518 // be unsuccessful. 1519 1520 // close the fileMapHandle. the file mapping will still be retained 1521 // by the OS as long as any other JVM processes has an open file mapping 1522 // handle or a mapped view of the file. 1523 // 1524 if (sharedmem_fileMapHandle != NULL) { 1525 CloseHandle(sharedmem_fileMapHandle); 1526 sharedmem_fileMapHandle = NULL; 1527 } 1528 1529 // close the file handle. This will decrement the reference count on the 1530 // backing store file. When the reference count decrements to 0, the OS 1531 // will delete the file. These semantics apply because the file was 1532 // created with the FILE_FLAG_DELETE_ON_CLOSE flag. 1533 // 1534 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) { 1535 CloseHandle(sharedmem_fileHandle); 1536 sharedmem_fileHandle = INVALID_HANDLE_VALUE; 1537 } 1538} 1539 1540// this method determines the size of the shared memory file 1541// 1542static size_t sharedmem_filesize(const char* filename, TRAPS) { 1543 1544 struct stat statbuf; 1545 1546 // get the file size 1547 // 1548 // on win95/98/me, _stat returns a file size of 0 bytes, but on 1549 // winnt/2k the appropriate file size is returned. support for 1550 // the sharable aspects of performance counters was abandonded 1551 // on the non-nt win32 platforms due to this and other api 1552 // inconsistencies 1553 // 1554 if (::stat(filename, &statbuf) == OS_ERR) { 1555 if (PrintMiscellaneous && Verbose) { 1556 warning("stat %s failed: %s\n", filename, strerror(errno)); 1557 } 1558 THROW_MSG_0(vmSymbols::java_io_IOException(), 1559 "Could not determine PerfMemory size"); 1560 } 1561 1562 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) { 1563 if (PrintMiscellaneous && Verbose) { 1564 warning("unexpected file size: size = " SIZE_FORMAT "\n", 1565 statbuf.st_size); 1566 } 1567 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1568 "Invalid PerfMemory size"); 1569 } 1570 1571 return statbuf.st_size; 1572} 1573 1574// this method opens a file mapping object and maps the object 1575// into the address space of the process 1576// 1577static void open_file_mapping(const char* user, int vmid, 1578 PerfMemory::PerfMemoryMode mode, 1579 char** addrp, size_t* sizep, TRAPS) { 1580 1581 ResourceMark rm; 1582 1583 void *mapAddress = 0; 1584 size_t size = 0; 1585 HANDLE fmh; 1586 DWORD ofm_access; 1587 DWORD mv_access; 1588 const char* luser = NULL; 1589 1590 if (mode == PerfMemory::PERF_MODE_RO) { 1591 ofm_access = FILE_MAP_READ; 1592 mv_access = FILE_MAP_READ; 1593 } 1594 else if (mode == PerfMemory::PERF_MODE_RW) { 1595#ifdef LATER 1596 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE; 1597 mv_access = FILE_MAP_READ | FILE_MAP_WRITE; 1598#else 1599 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1600 "Unsupported access mode"); 1601#endif 1602 } 1603 else { 1604 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1605 "Illegal access mode"); 1606 } 1607 1608 // if a user name wasn't specified, then find the user name for 1609 // the owner of the target vm. 1610 if (user == NULL || strlen(user) == 0) { 1611 luser = get_user_name(vmid); 1612 } 1613 else { 1614 luser = user; 1615 } 1616 1617 if (luser == NULL) { 1618 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1619 "Could not map vmid to user name"); 1620 } 1621 1622 // get the names for the resources for the target vm 1623 char* dirname = get_user_tmp_dir(luser); 1624 1625 // since we don't follow symbolic links when creating the backing 1626 // store file, we also don't following them when attaching 1627 // 1628 if (!is_directory_secure(dirname)) { 1629 FREE_C_HEAP_ARRAY(char, dirname); 1630 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 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); 1650 FREE_C_HEAP_ARRAY(char, dirname); 1651 FREE_C_HEAP_ARRAY(char, filename); 1652 FREE_C_HEAP_ARRAY(char, objectname); 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) { 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