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 43 typedef 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 // 52 static 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 // 75 static 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 // 88 static 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 149 static HANDLE sharedmem_fileMapHandle = NULL; 150 static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE; 151 static 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 // 157 static 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 // 173 static 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 // 209 static 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 // 266 static 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 // 300 static 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 // 424 static 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 // 447 static 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 // 469 static 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 // 487 static 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 // 515 static 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 // 544 static 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 // 619 static void cleanup_sharedmem_resources(const char* dirname) { 620 621 // open the user temp directory 622 DIR* dirp = os::opendir(dirname); 623 624 if (dirp == NULL) { 625 // directory doesn't exist, so there is nothing to cleanup 626 return; 627 } 628 629 if (!is_directory_secure(dirname)) { 630 // the directory is not secure, don't attempt any cleanup 631 return; 632 } 633 634 // for each entry in the directory that matches the expected file 635 // name pattern, determine if the file resources are stale and if 636 // so, remove the file resources. Note, instrumented HotSpot processes 637 // for this user may start and/or terminate during this search and 638 // remove or create new files in this directory. The behavior of this 639 // loop under these conditions is dependent upon the implementation of 640 // opendir/readdir. 641 // 642 struct dirent* entry; 643 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal); 644 errno = 0; 645 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 646 647 int pid = filename_to_pid(entry->d_name); 648 649 if (pid == 0) { 650 651 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 652 653 // attempt to remove all unexpected files, except "." and ".." 654 remove_file(dirname, entry->d_name); 655 } 656 657 errno = 0; 658 continue; 659 } 660 661 // we now have a file name that converts to a valid integer 662 // that could represent a process id . if this process id 663 // matches the current process id or the process is not running, 664 // then remove the stale file resources. 665 // 666 // process liveness is detected by checking the exit status 667 // of the process. if the process id is valid and the exit status 668 // indicates that it is still running, the file file resources 669 // are not removed. If the process id is invalid, or if we don't 670 // have permissions to check the process status, or if the process 671 // id is valid and the process has terminated, the the file resources 672 // are assumed to be stale and are removed. 673 // 674 if (pid == os::current_process_id() || !is_alive(pid)) { 675 676 // we can only remove the file resources. Any mapped views 677 // of the file can only be unmapped by the processes that 678 // opened those views and the file mapping object will not 679 // get removed until all views are unmapped. 680 // 681 remove_file(dirname, entry->d_name); 682 } 683 errno = 0; 684 } 685 os::closedir(dirp); 686 FREE_C_HEAP_ARRAY(char, dbuf); 687 } 688 689 // create a file mapping object with the requested name, and size 690 // from the file represented by the given Handle object 691 // 692 static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) { 693 694 DWORD lowSize = (DWORD)size; 695 DWORD highSize = 0; 696 HANDLE fmh = NULL; 697 698 // Create a file mapping object with the given name. This function 699 // will grow the file to the specified size. 700 // 701 fmh = CreateFileMapping( 702 fh, /* HANDLE file handle for backing store */ 703 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */ 704 PAGE_READWRITE, /* DWORD protections */ 705 highSize, /* DWORD High word of max size */ 706 lowSize, /* DWORD Low word of max size */ 707 name); /* LPCTSTR name for object */ 708 709 if (fmh == NULL) { 710 if (PrintMiscellaneous && Verbose) { 711 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError()); 712 } 713 return NULL; 714 } 715 716 if (GetLastError() == ERROR_ALREADY_EXISTS) { 717 718 // a stale file mapping object was encountered. This object may be 719 // owned by this or some other user and cannot be removed until 720 // the other processes either exit or close their mapping objects 721 // and/or mapped views of this mapping object. 722 // 723 if (PrintMiscellaneous && Verbose) { 724 warning("file mapping already exists, lasterror = %d\n", GetLastError()); 725 } 726 727 CloseHandle(fmh); 728 return NULL; 729 } 730 731 return fmh; 732 } 733 734 735 // method to free the given security descriptor and the contained 736 // access control list. 737 // 738 static void free_security_desc(PSECURITY_DESCRIPTOR pSD) { 739 740 BOOL success, exists, isdefault; 741 PACL pACL; 742 743 if (pSD != NULL) { 744 745 // get the access control list from the security descriptor 746 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault); 747 748 // if an ACL existed and it was not a default acl, then it must 749 // be an ACL we enlisted. free the resources. 750 // 751 if (success && exists && pACL != NULL && !isdefault) { 752 FREE_C_HEAP_ARRAY(char, pACL); 753 } 754 755 // free the security descriptor 756 FREE_C_HEAP_ARRAY(char, pSD); 757 } 758 } 759 760 // method to free up a security attributes structure and any 761 // contained security descriptors and ACL 762 // 763 static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) { 764 765 if (lpSA != NULL) { 766 // free the contained security descriptor and the ACL 767 free_security_desc(lpSA->lpSecurityDescriptor); 768 lpSA->lpSecurityDescriptor = NULL; 769 770 // free the security attributes structure 771 FREE_C_HEAP_ARRAY(char, lpSA); 772 } 773 } 774 775 // get the user SID for the process indicated by the process handle 776 // 777 static PSID get_user_sid(HANDLE hProcess) { 778 779 HANDLE hAccessToken; 780 PTOKEN_USER token_buf = NULL; 781 DWORD rsize = 0; 782 783 if (hProcess == NULL) { 784 return NULL; 785 } 786 787 // get the process token 788 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) { 789 if (PrintMiscellaneous && Verbose) { 790 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError()); 791 } 792 return NULL; 793 } 794 795 // determine the size of the token structured needed to retrieve 796 // the user token information from the access token. 797 // 798 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) { 799 DWORD lasterror = GetLastError(); 800 if (lasterror != ERROR_INSUFFICIENT_BUFFER) { 801 if (PrintMiscellaneous && Verbose) { 802 warning("GetTokenInformation failure: lasterror = %d," 803 " rsize = %d\n", lasterror, rsize); 804 } 805 CloseHandle(hAccessToken); 806 return NULL; 807 } 808 } 809 810 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal); 811 812 // get the user token information 813 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) { 814 if (PrintMiscellaneous && Verbose) { 815 warning("GetTokenInformation failure: lasterror = %d," 816 " rsize = %d\n", GetLastError(), rsize); 817 } 818 FREE_C_HEAP_ARRAY(char, token_buf); 819 CloseHandle(hAccessToken); 820 return NULL; 821 } 822 823 DWORD nbytes = GetLengthSid(token_buf->User.Sid); 824 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 825 826 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) { 827 if (PrintMiscellaneous && Verbose) { 828 warning("GetTokenInformation failure: lasterror = %d," 829 " rsize = %d\n", GetLastError(), rsize); 830 } 831 FREE_C_HEAP_ARRAY(char, token_buf); 832 FREE_C_HEAP_ARRAY(char, pSID); 833 CloseHandle(hAccessToken); 834 return NULL; 835 } 836 837 // close the access token. 838 CloseHandle(hAccessToken); 839 FREE_C_HEAP_ARRAY(char, token_buf); 840 841 return pSID; 842 } 843 844 // structure used to consolidate access control entry information 845 // 846 typedef struct ace_data { 847 PSID pSid; // SID of the ACE 848 DWORD mask; // mask for the ACE 849 } ace_data_t; 850 851 852 // method to add an allow access control entry with the access rights 853 // indicated in mask for the principal indicated in SID to the given 854 // security descriptor. Much of the DACL handling was adapted from 855 // the example provided here: 856 // http://support.microsoft.com/kb/102102/EN-US/ 857 // 858 859 static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD, 860 ace_data_t aces[], int ace_count) { 861 PACL newACL = NULL; 862 PACL oldACL = NULL; 863 864 if (pSD == NULL) { 865 return false; 866 } 867 868 BOOL exists, isdefault; 869 870 // retrieve any existing access control list. 871 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) { 872 if (PrintMiscellaneous && Verbose) { 873 warning("GetSecurityDescriptor failure: lasterror = %d \n", 874 GetLastError()); 875 } 876 return false; 877 } 878 879 // get the size of the DACL 880 ACL_SIZE_INFORMATION aclinfo; 881 882 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent) 883 // while oldACL is NULL for some case. 884 if (oldACL == NULL) { 885 exists = FALSE; 886 } 887 888 if (exists) { 889 if (!GetAclInformation(oldACL, &aclinfo, 890 sizeof(ACL_SIZE_INFORMATION), 891 AclSizeInformation)) { 892 if (PrintMiscellaneous && Verbose) { 893 warning("GetAclInformation failure: lasterror = %d \n", GetLastError()); 894 return false; 895 } 896 } 897 } else { 898 aclinfo.AceCount = 0; // assume NULL DACL 899 aclinfo.AclBytesFree = 0; 900 aclinfo.AclBytesInUse = sizeof(ACL); 901 } 902 903 // compute the size needed for the new ACL 904 // initial size of ACL is sum of the following: 905 // * size of ACL structure. 906 // * size of each ACE structure that ACL is to contain minus the sid 907 // sidStart member (DWORD) of the ACE. 908 // * length of the SID that each ACE is to contain. 909 DWORD newACLsize = aclinfo.AclBytesInUse + 910 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count; 911 for (int i = 0; i < ace_count; i++) { 912 assert(aces[i].pSid != 0, "pSid should not be 0"); 913 newACLsize += GetLengthSid(aces[i].pSid); 914 } 915 916 // create the new ACL 917 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal); 918 919 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) { 920 if (PrintMiscellaneous && Verbose) { 921 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 922 } 923 FREE_C_HEAP_ARRAY(char, newACL); 924 return false; 925 } 926 927 unsigned int ace_index = 0; 928 // copy any existing ACEs from the old ACL (if any) to the new ACL. 929 if (aclinfo.AceCount != 0) { 930 while (ace_index < aclinfo.AceCount) { 931 LPVOID ace; 932 if (!GetAce(oldACL, ace_index, &ace)) { 933 if (PrintMiscellaneous && Verbose) { 934 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 935 } 936 FREE_C_HEAP_ARRAY(char, newACL); 937 return false; 938 } 939 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) { 940 // this is an inherited, allowed ACE; break from loop so we can 941 // add the new access allowed, non-inherited ACE in the correct 942 // position, immediately following all non-inherited ACEs. 943 break; 944 } 945 946 // determine if the SID of this ACE matches any of the SIDs 947 // for which we plan to set ACEs. 948 int matches = 0; 949 for (int i = 0; i < ace_count; i++) { 950 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) { 951 matches++; 952 break; 953 } 954 } 955 956 // if there are no SID matches, then add this existing ACE to the new ACL 957 if (matches == 0) { 958 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 959 ((PACE_HEADER)ace)->AceSize)) { 960 if (PrintMiscellaneous && Verbose) { 961 warning("AddAce failure: lasterror = %d \n", GetLastError()); 962 } 963 FREE_C_HEAP_ARRAY(char, newACL); 964 return false; 965 } 966 } 967 ace_index++; 968 } 969 } 970 971 // add the passed-in access control entries to the new ACL 972 for (int i = 0; i < ace_count; i++) { 973 if (!AddAccessAllowedAce(newACL, ACL_REVISION, 974 aces[i].mask, aces[i].pSid)) { 975 if (PrintMiscellaneous && Verbose) { 976 warning("AddAccessAllowedAce failure: lasterror = %d \n", 977 GetLastError()); 978 } 979 FREE_C_HEAP_ARRAY(char, newACL); 980 return false; 981 } 982 } 983 984 // now copy the rest of the inherited ACEs from the old ACL 985 if (aclinfo.AceCount != 0) { 986 // picking up at ace_index, where we left off in the 987 // previous ace_index loop 988 while (ace_index < aclinfo.AceCount) { 989 LPVOID ace; 990 if (!GetAce(oldACL, ace_index, &ace)) { 991 if (PrintMiscellaneous && Verbose) { 992 warning("InitializeAcl failure: lasterror = %d \n", GetLastError()); 993 } 994 FREE_C_HEAP_ARRAY(char, newACL); 995 return false; 996 } 997 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace, 998 ((PACE_HEADER)ace)->AceSize)) { 999 if (PrintMiscellaneous && Verbose) { 1000 warning("AddAce failure: lasterror = %d \n", GetLastError()); 1001 } 1002 FREE_C_HEAP_ARRAY(char, newACL); 1003 return false; 1004 } 1005 ace_index++; 1006 } 1007 } 1008 1009 // add the new ACL to the security descriptor. 1010 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) { 1011 if (PrintMiscellaneous && Verbose) { 1012 warning("SetSecurityDescriptorDacl failure:" 1013 " lasterror = %d \n", GetLastError()); 1014 } 1015 FREE_C_HEAP_ARRAY(char, newACL); 1016 return false; 1017 } 1018 1019 // if running on windows 2000 or later, set the automatic inheritance 1020 // control flags. 1021 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl; 1022 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr) 1023 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")), 1024 "SetSecurityDescriptorControl"); 1025 1026 if (_SetSecurityDescriptorControl != NULL) { 1027 // We do not want to further propagate inherited DACLs, so making them 1028 // protected prevents that. 1029 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, 1030 SE_DACL_PROTECTED)) { 1031 if (PrintMiscellaneous && Verbose) { 1032 warning("SetSecurityDescriptorControl failure:" 1033 " lasterror = %d \n", GetLastError()); 1034 } 1035 FREE_C_HEAP_ARRAY(char, newACL); 1036 return false; 1037 } 1038 } 1039 // Note, the security descriptor maintains a reference to the newACL, not 1040 // a copy of it. Therefore, the newACL is not freed here. It is freed when 1041 // the security descriptor containing its reference is freed. 1042 // 1043 return true; 1044 } 1045 1046 // method to create a security attributes structure, which contains a 1047 // security descriptor and an access control list comprised of 0 or more 1048 // access control entries. The method take an array of ace_data structures 1049 // that indicate the ACE to be added to the security descriptor. 1050 // 1051 // the caller must free the resources associated with the security 1052 // attributes structure created by this method by calling the 1053 // free_security_attr() method. 1054 // 1055 static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) { 1056 1057 // allocate space for a security descriptor 1058 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) 1059 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal); 1060 1061 // initialize the security descriptor 1062 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { 1063 if (PrintMiscellaneous && Verbose) { 1064 warning("InitializeSecurityDescriptor failure: " 1065 "lasterror = %d \n", GetLastError()); 1066 } 1067 free_security_desc(pSD); 1068 return NULL; 1069 } 1070 1071 // add the access control entries 1072 if (!add_allow_aces(pSD, aces, count)) { 1073 free_security_desc(pSD); 1074 return NULL; 1075 } 1076 1077 // allocate and initialize the security attributes structure and 1078 // return it to the caller. 1079 // 1080 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES) 1081 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES), mtInternal); 1082 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES); 1083 lpSA->lpSecurityDescriptor = pSD; 1084 lpSA->bInheritHandle = FALSE; 1085 1086 return(lpSA); 1087 } 1088 1089 // method to create a security attributes structure with a restrictive 1090 // access control list that creates a set access rights for the user/owner 1091 // of the securable object and a separate set access rights for everyone else. 1092 // also provides for full access rights for the administrator group. 1093 // 1094 // the caller must free the resources associated with the security 1095 // attributes structure created by this method by calling the 1096 // free_security_attr() method. 1097 // 1098 1099 static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr( 1100 DWORD umask, DWORD emask, DWORD amask) { 1101 1102 ace_data_t aces[3]; 1103 1104 // initialize the user ace data 1105 aces[0].pSid = get_user_sid(GetCurrentProcess()); 1106 aces[0].mask = umask; 1107 1108 if (aces[0].pSid == 0) 1109 return NULL; 1110 1111 // get the well known SID for BUILTIN\Administrators 1112 PSID administratorsSid = NULL; 1113 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY; 1114 1115 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2, 1116 SECURITY_BUILTIN_DOMAIN_RID, 1117 DOMAIN_ALIAS_RID_ADMINS, 1118 0, 0, 0, 0, 0, 0, &administratorsSid)) { 1119 1120 if (PrintMiscellaneous && Verbose) { 1121 warning("AllocateAndInitializeSid failure: " 1122 "lasterror = %d \n", GetLastError()); 1123 } 1124 return NULL; 1125 } 1126 1127 // initialize the ace data for administrator group 1128 aces[1].pSid = administratorsSid; 1129 aces[1].mask = amask; 1130 1131 // get the well known SID for the universal Everybody 1132 PSID everybodySid = NULL; 1133 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY; 1134 1135 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID, 1136 0, 0, 0, 0, 0, 0, 0, &everybodySid)) { 1137 1138 if (PrintMiscellaneous && Verbose) { 1139 warning("AllocateAndInitializeSid failure: " 1140 "lasterror = %d \n", GetLastError()); 1141 } 1142 return NULL; 1143 } 1144 1145 // initialize the ace data for everybody else. 1146 aces[2].pSid = everybodySid; 1147 aces[2].mask = emask; 1148 1149 // create a security attributes structure with access control 1150 // entries as initialized above. 1151 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3); 1152 FREE_C_HEAP_ARRAY(char, aces[0].pSid); 1153 FreeSid(everybodySid); 1154 FreeSid(administratorsSid); 1155 return(lpSA); 1156 } 1157 1158 1159 // method to create the security attributes structure for restricting 1160 // access to the user temporary directory. 1161 // 1162 // the caller must free the resources associated with the security 1163 // attributes structure created by this method by calling the 1164 // free_security_attr() method. 1165 // 1166 static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() { 1167 1168 // create full access rights for the user/owner of the directory 1169 // and read-only access rights for everybody else. This is 1170 // effectively equivalent to UNIX 755 permissions on a directory. 1171 // 1172 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS; 1173 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1174 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1175 1176 return make_user_everybody_admin_security_attr(umask, emask, amask); 1177 } 1178 1179 // method to create the security attributes structure for restricting 1180 // access to the shared memory backing store file. 1181 // 1182 // the caller must free the resources associated with the security 1183 // attributes structure created by this method by calling the 1184 // free_security_attr() method. 1185 // 1186 static LPSECURITY_ATTRIBUTES make_file_security_attr() { 1187 1188 // create extensive access rights for the user/owner of the file 1189 // and attribute read-only access rights for everybody else. This 1190 // is effectively equivalent to UNIX 600 permissions on a file. 1191 // 1192 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1193 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | 1194 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE; 1195 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS; 1196 1197 return make_user_everybody_admin_security_attr(umask, emask, amask); 1198 } 1199 1200 // method to create the security attributes structure for restricting 1201 // access to the name shared memory file mapping object. 1202 // 1203 // the caller must free the resources associated with the security 1204 // attributes structure created by this method by calling the 1205 // free_security_attr() method. 1206 // 1207 static LPSECURITY_ATTRIBUTES make_smo_security_attr() { 1208 1209 // create extensive access rights for the user/owner of the shared 1210 // memory object and attribute read-only access rights for everybody 1211 // else. This is effectively equivalent to UNIX 600 permissions on 1212 // on the shared memory object. 1213 // 1214 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS; 1215 DWORD emask = STANDARD_RIGHTS_READ; // attributes only 1216 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS; 1217 1218 return make_user_everybody_admin_security_attr(umask, emask, amask); 1219 } 1220 1221 // make the user specific temporary directory 1222 // 1223 static bool make_user_tmp_dir(const char* dirname) { 1224 1225 1226 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr(); 1227 if (pDirSA == NULL) { 1228 return false; 1229 } 1230 1231 1232 // create the directory with the given security attributes 1233 if (!CreateDirectory(dirname, pDirSA)) { 1234 DWORD lasterror = GetLastError(); 1235 if (lasterror == ERROR_ALREADY_EXISTS) { 1236 // The directory already exists and was probably created by another 1237 // JVM instance. However, this could also be the result of a 1238 // deliberate symlink. Verify that the existing directory is safe. 1239 // 1240 if (!is_directory_secure(dirname)) { 1241 // directory is not secure 1242 if (PrintMiscellaneous && Verbose) { 1243 warning("%s directory is insecure\n", dirname); 1244 } 1245 return false; 1246 } 1247 // The administrator should be able to delete this directory. 1248 // But the directory created by previous version of JVM may not 1249 // have permission for administrators to delete this directory. 1250 // So add full permission to the administrator. Also setting new 1251 // DACLs might fix the corrupted the DACLs. 1252 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1253 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) { 1254 if (PrintMiscellaneous && Verbose) { 1255 lasterror = GetLastError(); 1256 warning("SetFileSecurity failed for %s directory. lasterror %d \n", 1257 dirname, lasterror); 1258 } 1259 } 1260 } 1261 else { 1262 if (PrintMiscellaneous && Verbose) { 1263 warning("CreateDirectory failed: %d\n", GetLastError()); 1264 } 1265 return false; 1266 } 1267 } 1268 1269 // free the security attributes structure 1270 free_security_attr(pDirSA); 1271 1272 return true; 1273 } 1274 1275 // create the shared memory resources 1276 // 1277 // This function creates the shared memory resources. This includes 1278 // the backing store file and the file mapping shared memory object. 1279 // 1280 static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) { 1281 1282 HANDLE fh = INVALID_HANDLE_VALUE; 1283 HANDLE fmh = NULL; 1284 1285 1286 // create the security attributes for the backing store file 1287 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr(); 1288 if (lpFileSA == NULL) { 1289 return NULL; 1290 } 1291 1292 // create the security attributes for the shared memory object 1293 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr(); 1294 if (lpSmoSA == NULL) { 1295 free_security_attr(lpFileSA); 1296 return NULL; 1297 } 1298 1299 // create the user temporary directory 1300 if (!make_user_tmp_dir(dirname)) { 1301 // could not make/find the directory or the found directory 1302 // was not secure 1303 return NULL; 1304 } 1305 1306 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the 1307 // file to be deleted by the last process that closes its handle to 1308 // the file. This is important as the apis do not allow a terminating 1309 // JVM being monitored by another process to remove the file name. 1310 // 1311 fh = CreateFile( 1312 filename, /* LPCTSTR file name */ 1313 1314 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */ 1315 FILE_SHARE_DELETE|FILE_SHARE_READ, /* DWORD share mode, future READONLY 1316 * open operations allowed 1317 */ 1318 lpFileSA, /* LPSECURITY security attributes */ 1319 CREATE_ALWAYS, /* DWORD creation disposition 1320 * create file, if it already 1321 * exists, overwrite it. 1322 */ 1323 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */ 1324 1325 NULL); /* HANDLE template file access */ 1326 1327 free_security_attr(lpFileSA); 1328 1329 if (fh == INVALID_HANDLE_VALUE) { 1330 DWORD lasterror = GetLastError(); 1331 if (PrintMiscellaneous && Verbose) { 1332 warning("could not create file %s: %d\n", filename, lasterror); 1333 } 1334 return NULL; 1335 } 1336 1337 // try to create the file mapping 1338 fmh = create_file_mapping(objectname, fh, lpSmoSA, size); 1339 1340 free_security_attr(lpSmoSA); 1341 1342 if (fmh == NULL) { 1343 // closing the file handle here will decrement the reference count 1344 // on the file. When all processes accessing the file close their 1345 // handle to it, the reference count will decrement to 0 and the 1346 // OS will delete the file. These semantics are requested by the 1347 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above. 1348 CloseHandle(fh); 1349 fh = NULL; 1350 return NULL; 1351 } else { 1352 // We created the file mapping, but rarely the size of the 1353 // backing store file is reported as zero (0) which can cause 1354 // failures when trying to use the hsperfdata file. 1355 struct stat statbuf; 1356 int ret_code = ::stat(filename, &statbuf); 1357 if (ret_code == OS_ERR) { 1358 if (PrintMiscellaneous && Verbose) { 1359 warning("Could not get status information from file %s: %s\n", 1360 filename, strerror(errno)); 1361 } 1362 CloseHandle(fmh); 1363 CloseHandle(fh); 1364 fh = NULL; 1365 fmh = NULL; 1366 return NULL; 1367 } 1368 1369 // We could always call FlushFileBuffers() but the Microsoft 1370 // docs indicate that it is considered expensive so we only 1371 // call it when we observe the size as zero (0). 1372 if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) { 1373 DWORD lasterror = GetLastError(); 1374 if (PrintMiscellaneous && Verbose) { 1375 warning("could not flush file %s: %d\n", filename, lasterror); 1376 } 1377 CloseHandle(fmh); 1378 CloseHandle(fh); 1379 fh = NULL; 1380 fmh = NULL; 1381 return NULL; 1382 } 1383 } 1384 1385 // the file has been successfully created and the file mapping 1386 // object has been created. 1387 sharedmem_fileHandle = fh; 1388 sharedmem_fileName = os::strdup(filename); 1389 1390 return fmh; 1391 } 1392 1393 // open the shared memory object for the given vmid. 1394 // 1395 static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) { 1396 1397 HANDLE fmh; 1398 1399 // open the file mapping with the requested mode 1400 fmh = OpenFileMapping( 1401 ofm_access, /* DWORD access mode */ 1402 FALSE, /* BOOL inherit flag - Do not allow inherit */ 1403 objectname); /* name for object */ 1404 1405 if (fmh == NULL) { 1406 if (PrintMiscellaneous && Verbose) { 1407 warning("OpenFileMapping failed for shared memory object %s:" 1408 " lasterror = %d\n", objectname, GetLastError()); 1409 } 1410 THROW_MSG_(vmSymbols::java_lang_Exception(), 1411 "Could not open PerfMemory", INVALID_HANDLE_VALUE); 1412 } 1413 1414 return fmh;; 1415 } 1416 1417 // create a named shared memory region 1418 // 1419 // On Win32, a named shared memory object has a name space that 1420 // is independent of the file system name space. Shared memory object, 1421 // or more precisely, file mapping objects, provide no mechanism to 1422 // inquire the size of the memory region. There is also no api to 1423 // enumerate the memory regions for various processes. 1424 // 1425 // This implementation utilizes the shared memory name space in parallel 1426 // with the file system name space. This allows us to determine the 1427 // size of the shared memory region from the size of the file and it 1428 // allows us to provide a common, file system based name space for 1429 // shared memory across platforms. 1430 // 1431 static char* mapping_create_shared(size_t size) { 1432 1433 void *mapAddress; 1434 int vmid = os::current_process_id(); 1435 1436 // get the name of the user associated with this process 1437 char* user = get_user_name(); 1438 1439 if (user == NULL) { 1440 return NULL; 1441 } 1442 1443 // construct the name of the user specific temporary directory 1444 char* dirname = get_user_tmp_dir(user); 1445 1446 // check that the file system is secure - i.e. it supports ACLs. 1447 if (!is_filesystem_secure(dirname)) { 1448 return NULL; 1449 } 1450 1451 // create the names of the backing store files and for the 1452 // share memory object. 1453 // 1454 char* filename = get_sharedmem_filename(dirname, vmid); 1455 char* objectname = get_sharedmem_objectname(user, vmid); 1456 1457 // cleanup any stale shared memory resources 1458 cleanup_sharedmem_resources(dirname); 1459 1460 assert(((size != 0) && (size % os::vm_page_size() == 0)), 1461 "unexpected PerfMemry region size"); 1462 1463 FREE_C_HEAP_ARRAY(char, user); 1464 1465 // create the shared memory resources 1466 sharedmem_fileMapHandle = 1467 create_sharedmem_resources(dirname, filename, objectname, size); 1468 1469 FREE_C_HEAP_ARRAY(char, filename); 1470 FREE_C_HEAP_ARRAY(char, objectname); 1471 FREE_C_HEAP_ARRAY(char, dirname); 1472 1473 if (sharedmem_fileMapHandle == NULL) { 1474 return NULL; 1475 } 1476 1477 // map the file into the address space 1478 mapAddress = MapViewOfFile( 1479 sharedmem_fileMapHandle, /* HANDLE = file mapping object */ 1480 FILE_MAP_ALL_ACCESS, /* DWORD access flags */ 1481 0, /* DWORD High word of offset */ 1482 0, /* DWORD Low word of offset */ 1483 (DWORD)size); /* DWORD Number of bytes to map */ 1484 1485 if (mapAddress == NULL) { 1486 if (PrintMiscellaneous && Verbose) { 1487 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1488 } 1489 CloseHandle(sharedmem_fileMapHandle); 1490 sharedmem_fileMapHandle = NULL; 1491 return NULL; 1492 } 1493 1494 // clear the shared memory region 1495 (void)memset(mapAddress, '\0', size); 1496 1497 // it does not go through os api, the operation has to record from here 1498 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, 1499 size, CURRENT_PC, mtInternal); 1500 1501 return (char*) mapAddress; 1502 } 1503 1504 // this method deletes the file mapping object. 1505 // 1506 static void delete_file_mapping(char* addr, size_t size) { 1507 1508 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1509 // not support unloading of the JVM, unmapping of the memory resource is not 1510 // performed. The memory will be reclaimed by the OS upon termination of all 1511 // processes mapping the resource. The file mapping handle and the file 1512 // handle are closed here to expedite the remove of the file by the OS. The 1513 // file is not removed directly because it was created with 1514 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would 1515 // be unsuccessful. 1516 1517 // close the fileMapHandle. the file mapping will still be retained 1518 // by the OS as long as any other JVM processes has an open file mapping 1519 // handle or a mapped view of the file. 1520 // 1521 if (sharedmem_fileMapHandle != NULL) { 1522 CloseHandle(sharedmem_fileMapHandle); 1523 sharedmem_fileMapHandle = NULL; 1524 } 1525 1526 // close the file handle. This will decrement the reference count on the 1527 // backing store file. When the reference count decrements to 0, the OS 1528 // will delete the file. These semantics apply because the file was 1529 // created with the FILE_FLAG_DELETE_ON_CLOSE flag. 1530 // 1531 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) { 1532 CloseHandle(sharedmem_fileHandle); 1533 sharedmem_fileHandle = INVALID_HANDLE_VALUE; 1534 } 1535 } 1536 1537 // this method determines the size of the shared memory file 1538 // 1539 static size_t sharedmem_filesize(const char* filename, TRAPS) { 1540 1541 struct stat statbuf; 1542 1543 // get the file size 1544 // 1545 // on win95/98/me, _stat returns a file size of 0 bytes, but on 1546 // winnt/2k the appropriate file size is returned. support for 1547 // the sharable aspects of performance counters was abandonded 1548 // on the non-nt win32 platforms due to this and other api 1549 // inconsistencies 1550 // 1551 if (::stat(filename, &statbuf) == OS_ERR) { 1552 if (PrintMiscellaneous && Verbose) { 1553 warning("stat %s failed: %s\n", filename, strerror(errno)); 1554 } 1555 THROW_MSG_0(vmSymbols::java_io_IOException(), 1556 "Could not determine PerfMemory size"); 1557 } 1558 1559 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) { 1560 if (PrintMiscellaneous && Verbose) { 1561 warning("unexpected file size: size = " SIZE_FORMAT "\n", 1562 statbuf.st_size); 1563 } 1564 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1565 "Invalid PerfMemory size"); 1566 } 1567 1568 return statbuf.st_size; 1569 } 1570 1571 // this method opens a file mapping object and maps the object 1572 // into the address space of the process 1573 // 1574 static void open_file_mapping(const char* user, int vmid, 1575 PerfMemory::PerfMemoryMode mode, 1576 char** addrp, size_t* sizep, TRAPS) { 1577 1578 ResourceMark rm; 1579 1580 void *mapAddress = 0; 1581 size_t size = 0; 1582 HANDLE fmh; 1583 DWORD ofm_access; 1584 DWORD mv_access; 1585 const char* luser = NULL; 1586 1587 if (mode == PerfMemory::PERF_MODE_RO) { 1588 ofm_access = FILE_MAP_READ; 1589 mv_access = FILE_MAP_READ; 1590 } 1591 else if (mode == PerfMemory::PERF_MODE_RW) { 1592 #ifdef LATER 1593 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE; 1594 mv_access = FILE_MAP_READ | FILE_MAP_WRITE; 1595 #else 1596 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1597 "Unsupported access mode"); 1598 #endif 1599 } 1600 else { 1601 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1602 "Illegal access mode"); 1603 } 1604 1605 // if a user name wasn't specified, then find the user name for 1606 // the owner of the target vm. 1607 if (user == NULL || strlen(user) == 0) { 1608 luser = get_user_name(vmid); 1609 } 1610 else { 1611 luser = user; 1612 } 1613 1614 if (luser == NULL) { 1615 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1616 "Could not map vmid to user name"); 1617 } 1618 1619 // get the names for the resources for the target vm 1620 char* dirname = get_user_tmp_dir(luser); 1621 1622 // since we don't follow symbolic links when creating the backing 1623 // store file, we also don't following them when attaching 1624 // 1625 if (!is_directory_secure(dirname)) { 1626 FREE_C_HEAP_ARRAY(char, dirname); 1627 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1628 "Process not found"); 1629 } 1630 1631 char* filename = get_sharedmem_filename(dirname, vmid); 1632 char* objectname = get_sharedmem_objectname(luser, vmid); 1633 1634 // copy heap memory to resource memory. the objectname and 1635 // filename are passed to methods that may throw exceptions. 1636 // using resource arrays for these names prevents the leaks 1637 // that would otherwise occur. 1638 // 1639 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 1640 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1); 1641 strcpy(rfilename, filename); 1642 strcpy(robjectname, objectname); 1643 1644 // free the c heap resources that are no longer needed 1645 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 1646 FREE_C_HEAP_ARRAY(char, dirname); 1647 FREE_C_HEAP_ARRAY(char, filename); 1648 FREE_C_HEAP_ARRAY(char, objectname); 1649 1650 if (*sizep == 0) { 1651 size = sharedmem_filesize(rfilename, CHECK); 1652 } else { 1653 size = *sizep; 1654 } 1655 1656 assert(size > 0, "unexpected size <= 0"); 1657 1658 // Open the file mapping object with the given name 1659 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK); 1660 1661 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value"); 1662 1663 // map the entire file into the address space 1664 mapAddress = MapViewOfFile( 1665 fmh, /* HANDLE Handle of file mapping object */ 1666 mv_access, /* DWORD access flags */ 1667 0, /* DWORD High word of offset */ 1668 0, /* DWORD Low word of offset */ 1669 size); /* DWORD Number of bytes to map */ 1670 1671 if (mapAddress == NULL) { 1672 if (PrintMiscellaneous && Verbose) { 1673 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError()); 1674 } 1675 CloseHandle(fmh); 1676 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 1677 "Could not map PerfMemory"); 1678 } 1679 1680 // it does not go through os api, the operation has to record from here 1681 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, 1682 CURRENT_PC, mtInternal); 1683 1684 1685 *addrp = (char*)mapAddress; 1686 *sizep = size; 1687 1688 // File mapping object can be closed at this time without 1689 // invalidating the mapped view of the file 1690 CloseHandle(fmh); 1691 1692 if (PerfTraceMemOps) { 1693 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 1694 INTPTR_FORMAT "\n", size, vmid, mapAddress); 1695 } 1696 } 1697 1698 // this method unmaps the the mapped view of the the 1699 // file mapping object. 1700 // 1701 static void remove_file_mapping(char* addr) { 1702 1703 // the file mapping object was closed in open_file_mapping() 1704 // after the file map view was created. We only need to 1705 // unmap the file view here. 1706 UnmapViewOfFile(addr); 1707 } 1708 1709 // create the PerfData memory region in shared memory. 1710 static char* create_shared_memory(size_t size) { 1711 1712 return mapping_create_shared(size); 1713 } 1714 1715 // release a named, shared memory region 1716 // 1717 void delete_shared_memory(char* addr, size_t size) { 1718 1719 delete_file_mapping(addr, size); 1720 } 1721 1722 1723 1724 1725 // create the PerfData memory region 1726 // 1727 // This method creates the memory region used to store performance 1728 // data for the JVM. The memory may be created in standard or 1729 // shared memory. 1730 // 1731 void PerfMemory::create_memory_region(size_t size) { 1732 1733 if (PerfDisableSharedMem) { 1734 // do not share the memory for the performance data. 1735 PerfDisableSharedMem = true; 1736 _start = create_standard_memory(size); 1737 } 1738 else { 1739 _start = create_shared_memory(size); 1740 if (_start == NULL) { 1741 1742 // creation of the shared memory region failed, attempt 1743 // to create a contiguous, non-shared memory region instead. 1744 // 1745 if (PrintMiscellaneous && Verbose) { 1746 warning("Reverting to non-shared PerfMemory region.\n"); 1747 } 1748 PerfDisableSharedMem = true; 1749 _start = create_standard_memory(size); 1750 } 1751 } 1752 1753 if (_start != NULL) _capacity = size; 1754 1755 } 1756 1757 // delete the PerfData memory region 1758 // 1759 // This method deletes the memory region used to store performance 1760 // data for the JVM. The memory region indicated by the <address, size> 1761 // tuple will be inaccessible after a call to this method. 1762 // 1763 void PerfMemory::delete_memory_region() { 1764 1765 assert((start() != NULL && capacity() > 0), "verify proper state"); 1766 1767 // If user specifies PerfDataSaveFile, it will save the performance data 1768 // to the specified file name no matter whether PerfDataSaveToFile is specified 1769 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 1770 // -XX:+PerfDataSaveToFile. 1771 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 1772 save_memory_to_file(start(), capacity()); 1773 } 1774 1775 if (PerfDisableSharedMem) { 1776 delete_standard_memory(start(), capacity()); 1777 } 1778 else { 1779 delete_shared_memory(start(), capacity()); 1780 } 1781 } 1782 1783 // attach to the PerfData memory region for another JVM 1784 // 1785 // This method returns an <address, size> tuple that points to 1786 // a memory buffer that is kept reasonably synchronized with 1787 // the PerfData memory region for the indicated JVM. This 1788 // buffer may be kept in synchronization via shared memory 1789 // or some other mechanism that keeps the buffer updated. 1790 // 1791 // If the JVM chooses not to support the attachability feature, 1792 // this method should throw an UnsupportedOperation exception. 1793 // 1794 // This implementation utilizes named shared memory to map 1795 // the indicated process's PerfData memory region into this JVMs 1796 // address space. 1797 // 1798 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, 1799 char** addrp, size_t* sizep, TRAPS) { 1800 1801 if (vmid == 0 || vmid == os::current_process_id()) { 1802 *addrp = start(); 1803 *sizep = capacity(); 1804 return; 1805 } 1806 1807 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK); 1808 } 1809 1810 // detach from the PerfData memory region of another JVM 1811 // 1812 // This method detaches the PerfData memory region of another 1813 // JVM, specified as an <address, size> tuple of a buffer 1814 // in this process's address space. This method may perform 1815 // arbitrary actions to accomplish the detachment. The memory 1816 // region specified by <address, size> will be inaccessible after 1817 // a call to this method. 1818 // 1819 // If the JVM chooses not to support the attachability feature, 1820 // this method should throw an UnsupportedOperation exception. 1821 // 1822 // This implementation utilizes named shared memory to detach 1823 // the indicated process's PerfData memory region from this 1824 // process's address space. 1825 // 1826 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 1827 1828 assert(addr != 0, "address sanity check"); 1829 assert(bytes > 0, "capacity sanity check"); 1830 1831 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1832 // prevent accidental detachment of this process's PerfMemory region 1833 return; 1834 } 1835 1836 if (MemTracker::tracking_level() > NMT_minimal) { 1837 // it does not go through os api, the operation has to record from here 1838 Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); 1839 remove_file_mapping(addr); 1840 tkr.record((address)addr, bytes); 1841 } else { 1842 remove_file_mapping(addr); 1843 } 1844 }