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