1 /* 2 * Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 # include "incls/_precompiled.incl" 26 # include "incls/_perfMemory_linux.cpp.incl" 27 28 // put OS-includes here 29 # include <sys/types.h> 30 # include <sys/mman.h> 31 # include <errno.h> 32 # include <stdio.h> 33 # include <unistd.h> 34 # include <sys/stat.h> 35 # include <signal.h> 36 # include <pwd.h> 37 38 static char* backing_store_file_name = NULL; // name of the backing store 39 // file, if successfully created. 40 41 // Standard Memory Implementation Details 42 43 // create the PerfData memory region in standard memory. 44 // 45 static char* create_standard_memory(size_t size) { 46 47 // allocate an aligned chuck of memory 48 char* mapAddress = os::reserve_memory(size); 49 50 if (mapAddress == NULL) { 51 return NULL; 52 } 53 54 // commit memory 55 if (!os::commit_memory(mapAddress, size)) { 56 if (PrintMiscellaneous && Verbose) { 57 warning("Could not commit PerfData memory\n"); 58 } 59 os::release_memory(mapAddress, size); 60 return NULL; 61 } 62 63 return mapAddress; 64 } 65 66 // delete the PerfData memory region 67 // 68 static void delete_standard_memory(char* addr, size_t size) { 69 70 // there are no persistent external resources to cleanup for standard 71 // memory. since DestroyJavaVM does not support unloading of the JVM, 72 // cleanup of the memory resource is not performed. The memory will be 73 // reclaimed by the OS upon termination of the process. 74 // 75 return; 76 } 77 78 // save the specified memory region to the given file 79 // 80 // Note: this function might be called from signal handler (by os::abort()), 81 // don't allocate heap memory. 82 // 83 static void save_memory_to_file(char* addr, size_t size) { 84 85 const char* destfile = PerfMemory::get_perfdata_file_path(); 86 assert(destfile[0] != '\0', "invalid PerfData file path"); 87 88 int result; 89 90 RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE), 91 result);; 92 if (result == OS_ERR) { 93 if (PrintMiscellaneous && Verbose) { 94 warning("Could not create Perfdata save file: %s: %s\n", 95 destfile, strerror(errno)); 96 } 97 } else { 98 int fd = result; 99 100 for (size_t remaining = size; remaining > 0;) { 101 102 RESTARTABLE(::write(fd, addr, remaining), result); 103 if (result == 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)result; 112 addr += result; 113 } 114 115 RESTARTABLE(::close(fd), result); 116 if (PrintMiscellaneous && Verbose) { 117 if (result == OS_ERR) { 118 warning("Could not close %s: %s\n", destfile, strerror(errno)); 119 } 120 } 121 } 122 FREE_C_HEAP_ARRAY(char, destfile); 123 } 124 125 126 // Shared Memory Implementation Details 127 128 // Note: the solaris and linux shared memory implementation uses the mmap 129 // interface with a backing store file to implement named shared memory. 130 // Using the file system as the name space for shared memory allows a 131 // common name space to be supported across a variety of platforms. It 132 // also provides a name space that Java applications can deal with through 133 // simple file apis. 134 // 135 // The solaris and linux implementations store the backing store file in 136 // a user specific temporary directory located in the /tmp file system, 137 // which is always a local file system and is sometimes a RAM based file 138 // system. 139 140 // return the user specific temporary directory name. 141 // 142 // the caller is expected to free the allocated memory. 143 // 144 static char* get_user_tmp_dir(const char* user) { 145 146 const char* tmpdir = os::get_temp_directory(); 147 const char* perfdir = PERFDATA_NAME; 148 size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3; 149 char* dirname = NEW_C_HEAP_ARRAY(char, nbytes); 150 151 // construct the path name to user specific tmp directory 152 snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user); 153 154 return dirname; 155 } 156 157 // convert the given file name into a process id. if the file 158 // does not meet the file naming constraints, return 0. 159 // 160 static pid_t filename_to_pid(const char* filename) { 161 162 // a filename that doesn't begin with a digit is not a 163 // candidate for conversion. 164 // 165 if (!isdigit(*filename)) { 166 return 0; 167 } 168 169 // check if file name can be converted to an integer without 170 // any leftover characters. 171 // 172 char* remainder = NULL; 173 errno = 0; 174 pid_t pid = (pid_t)strtol(filename, &remainder, 10); 175 176 if (errno != 0) { 177 return 0; 178 } 179 180 // check for left over characters. If any, then the filename is 181 // not a candidate for conversion. 182 // 183 if (remainder != NULL && *remainder != '\0') { 184 return 0; 185 } 186 187 // successful conversion, return the pid 188 return pid; 189 } 190 191 192 // check if the given path is considered a secure directory for 193 // the backing store files. Returns true if the directory exists 194 // and is considered a secure location. Returns false if the path 195 // is a symbolic link or if an error occurred. 196 // 197 static bool is_directory_secure(const char* path) { 198 struct stat statbuf; 199 int result = 0; 200 201 RESTARTABLE(::lstat(path, &statbuf), result); 202 if (result == OS_ERR) { 203 return false; 204 } 205 206 // the path exists, now check it's mode 207 if (S_ISLNK(statbuf.st_mode) || !S_ISDIR(statbuf.st_mode)) { 208 // the path represents a link or some non-directory file type, 209 // which is not what we expected. declare it insecure. 210 // 211 return false; 212 } 213 else { 214 // we have an existing directory, check if the permissions are safe. 215 // 216 if ((statbuf.st_mode & (S_IWGRP|S_IWOTH)) != 0) { 217 // the directory is open for writing and could be subjected 218 // to a symlnk attack. declare it insecure. 219 // 220 return false; 221 } 222 } 223 return true; 224 } 225 226 227 // return the user name for the given user id 228 // 229 // the caller is expected to free the allocated memory. 230 // 231 static char* get_user_name(uid_t uid) { 232 233 struct passwd pwent; 234 235 // determine the max pwbuf size from sysconf, and hardcode 236 // a default if this not available through sysconf. 237 // 238 long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); 239 if (bufsize == -1) 240 bufsize = 1024; 241 242 char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize); 243 244 // POSIX interface to getpwuid_r is used on LINUX 245 struct passwd* p; 246 int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p); 247 248 if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') { 249 if (PrintMiscellaneous && Verbose) { 250 if (result != 0) { 251 warning("Could not retrieve passwd entry: %s\n", 252 strerror(result)); 253 } 254 else if (p == NULL) { 255 // this check is added to protect against an observed problem 256 // with getpwuid_r() on RedHat 9 where getpwuid_r returns 0, 257 // indicating success, but has p == NULL. This was observed when 258 // inserting a file descriptor exhaustion fault prior to the call 259 // getpwuid_r() call. In this case, error is set to the appropriate 260 // error condition, but this is undocumented behavior. This check 261 // is safe under any condition, but the use of errno in the output 262 // message may result in an erroneous message. 263 // Bug Id 89052 was opened with RedHat. 264 // 265 warning("Could not retrieve passwd entry: %s\n", 266 strerror(errno)); 267 } 268 else { 269 warning("Could not determine user name: %s\n", 270 p->pw_name == NULL ? "pw_name = NULL" : 271 "pw_name zero length"); 272 } 273 } 274 FREE_C_HEAP_ARRAY(char, pwbuf); 275 return NULL; 276 } 277 278 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1); 279 strcpy(user_name, p->pw_name); 280 281 FREE_C_HEAP_ARRAY(char, pwbuf); 282 return user_name; 283 } 284 285 // return the name of the user that owns the process identified by vmid. 286 // 287 // This method uses a slow directory search algorithm to find the backing 288 // store file for the specified vmid and returns the user name, as determined 289 // by the user name suffix of the hsperfdata_<username> directory name. 290 // 291 // the caller is expected to free the allocated memory. 292 // 293 static char* get_user_name_slow(int vmid, TRAPS) { 294 295 // short circuit the directory search if the process doesn't even exist. 296 if (kill(vmid, 0) == OS_ERR) { 297 if (errno == ESRCH) { 298 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 299 "Process not found"); 300 } 301 else /* EPERM */ { 302 THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno)); 303 } 304 } 305 306 // directory search 307 char* oldest_user = NULL; 308 time_t oldest_ctime = 0; 309 310 const char* tmpdirname = os::get_temp_directory(); 311 312 DIR* tmpdirp = os::opendir(tmpdirname); 313 314 if (tmpdirp == NULL) { 315 return NULL; 316 } 317 318 // for each entry in the directory that matches the pattern hsperfdata_*, 319 // open the directory and check if the file for the given vmid exists. 320 // The file with the expected name and the latest creation date is used 321 // to determine the user name for the process id. 322 // 323 struct dirent* dentry; 324 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname)); 325 errno = 0; 326 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) { 327 328 // check if the directory entry is a hsperfdata file 329 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) { 330 continue; 331 } 332 333 char* usrdir_name = NEW_C_HEAP_ARRAY(char, 334 strlen(tmpdirname) + strlen(dentry->d_name) + 2); 335 strcpy(usrdir_name, tmpdirname); 336 strcat(usrdir_name, "/"); 337 strcat(usrdir_name, dentry->d_name); 338 339 DIR* subdirp = os::opendir(usrdir_name); 340 341 if (subdirp == NULL) { 342 FREE_C_HEAP_ARRAY(char, usrdir_name); 343 continue; 344 } 345 346 // Since we don't create the backing store files in directories 347 // pointed to by symbolic links, we also don't follow them when 348 // looking for the files. We check for a symbolic link after the 349 // call to opendir in order to eliminate a small window where the 350 // symlink can be exploited. 351 // 352 if (!is_directory_secure(usrdir_name)) { 353 FREE_C_HEAP_ARRAY(char, usrdir_name); 354 os::closedir(subdirp); 355 continue; 356 } 357 358 struct dirent* udentry; 359 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name)); 360 errno = 0; 361 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) { 362 363 if (filename_to_pid(udentry->d_name) == vmid) { 364 struct stat statbuf; 365 int result; 366 367 char* filename = NEW_C_HEAP_ARRAY(char, 368 strlen(usrdir_name) + strlen(udentry->d_name) + 2); 369 370 strcpy(filename, usrdir_name); 371 strcat(filename, "/"); 372 strcat(filename, udentry->d_name); 373 374 // don't follow symbolic links for the file 375 RESTARTABLE(::lstat(filename, &statbuf), result); 376 if (result == OS_ERR) { 377 FREE_C_HEAP_ARRAY(char, filename); 378 continue; 379 } 380 381 // skip over files that are not regular files. 382 if (!S_ISREG(statbuf.st_mode)) { 383 FREE_C_HEAP_ARRAY(char, filename); 384 continue; 385 } 386 387 // compare and save filename with latest creation time 388 if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) { 389 390 if (statbuf.st_ctime > oldest_ctime) { 391 char* user = strchr(dentry->d_name, '_') + 1; 392 393 if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user); 394 oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1); 395 396 strcpy(oldest_user, user); 397 oldest_ctime = statbuf.st_ctime; 398 } 399 } 400 401 FREE_C_HEAP_ARRAY(char, filename); 402 } 403 } 404 os::closedir(subdirp); 405 FREE_C_HEAP_ARRAY(char, udbuf); 406 FREE_C_HEAP_ARRAY(char, usrdir_name); 407 } 408 os::closedir(tmpdirp); 409 FREE_C_HEAP_ARRAY(char, tdbuf); 410 411 return(oldest_user); 412 } 413 414 // return the name of the user that owns the JVM indicated by the given vmid. 415 // 416 static char* get_user_name(int vmid, TRAPS) { 417 return get_user_name_slow(vmid, CHECK_NULL); 418 } 419 420 // return the file name of the backing store file for the named 421 // shared memory region for the given user name and vmid. 422 // 423 // the caller is expected to free the allocated memory. 424 // 425 static char* get_sharedmem_filename(const char* dirname, int vmid) { 426 427 // add 2 for the file separator and a null terminator. 428 size_t nbytes = strlen(dirname) + UINT_CHARS + 2; 429 430 char* name = NEW_C_HEAP_ARRAY(char, nbytes); 431 snprintf(name, nbytes, "%s/%d", dirname, vmid); 432 433 return name; 434 } 435 436 437 // remove file 438 // 439 // this method removes the file specified by the given path 440 // 441 static void remove_file(const char* path) { 442 443 int result; 444 445 // if the file is a directory, the following unlink will fail. since 446 // we don't expect to find directories in the user temp directory, we 447 // won't try to handle this situation. even if accidentially or 448 // maliciously planted, the directory's presence won't hurt anything. 449 // 450 RESTARTABLE(::unlink(path), result); 451 if (PrintMiscellaneous && Verbose && result == OS_ERR) { 452 if (errno != ENOENT) { 453 warning("Could not unlink shared memory backing" 454 " store file %s : %s\n", path, strerror(errno)); 455 } 456 } 457 } 458 459 460 // remove file 461 // 462 // this method removes the file with the given file name in the 463 // named directory. 464 // 465 static void remove_file(const char* dirname, const char* filename) { 466 467 size_t nbytes = strlen(dirname) + strlen(filename) + 2; 468 char* path = NEW_C_HEAP_ARRAY(char, nbytes); 469 470 strcpy(path, dirname); 471 strcat(path, "/"); 472 strcat(path, filename); 473 474 remove_file(path); 475 476 FREE_C_HEAP_ARRAY(char, path); 477 } 478 479 480 // cleanup stale shared memory resources 481 // 482 // This method attempts to remove all stale shared memory files in 483 // the named user temporary directory. It scans the named directory 484 // for files matching the pattern ^$[0-9]*$. For each file found, the 485 // process id is extracted from the file name and a test is run to 486 // determine if the process is alive. If the process is not alive, 487 // any stale file resources are removed. 488 // 489 static void cleanup_sharedmem_resources(const char* dirname) { 490 491 // open the user temp directory 492 DIR* dirp = os::opendir(dirname); 493 494 if (dirp == NULL) { 495 // directory doesn't exist, so there is nothing to cleanup 496 return; 497 } 498 499 if (!is_directory_secure(dirname)) { 500 // the directory is not a secure directory 501 return; 502 } 503 504 // for each entry in the directory that matches the expected file 505 // name pattern, determine if the file resources are stale and if 506 // so, remove the file resources. Note, instrumented HotSpot processes 507 // for this user may start and/or terminate during this search and 508 // remove or create new files in this directory. The behavior of this 509 // loop under these conditions is dependent upon the implementation of 510 // opendir/readdir. 511 // 512 struct dirent* entry; 513 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname)); 514 errno = 0; 515 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 516 517 pid_t pid = filename_to_pid(entry->d_name); 518 519 if (pid == 0) { 520 521 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 522 523 // attempt to remove all unexpected files, except "." and ".." 524 remove_file(dirname, entry->d_name); 525 } 526 527 errno = 0; 528 continue; 529 } 530 531 // we now have a file name that converts to a valid integer 532 // that could represent a process id . if this process id 533 // matches the current process id or the process is not running, 534 // then remove the stale file resources. 535 // 536 // process liveness is detected by sending signal number 0 to 537 // the process id (see kill(2)). if kill determines that the 538 // process does not exist, then the file resources are removed. 539 // if kill determines that that we don't have permission to 540 // signal the process, then the file resources are assumed to 541 // be stale and are removed because the resources for such a 542 // process should be in a different user specific directory. 543 // 544 if ((pid == os::current_process_id()) || 545 (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) { 546 547 remove_file(dirname, entry->d_name); 548 } 549 errno = 0; 550 } 551 os::closedir(dirp); 552 FREE_C_HEAP_ARRAY(char, dbuf); 553 } 554 555 // make the user specific temporary directory. Returns true if 556 // the directory exists and is secure upon return. Returns false 557 // if the directory exists but is either a symlink, is otherwise 558 // insecure, or if an error occurred. 559 // 560 static bool make_user_tmp_dir(const char* dirname) { 561 562 // create the directory with 0755 permissions. note that the directory 563 // will be owned by euid::egid, which may not be the same as uid::gid. 564 // 565 if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) { 566 if (errno == EEXIST) { 567 // The directory already exists and was probably created by another 568 // JVM instance. However, this could also be the result of a 569 // deliberate symlink. Verify that the existing directory is safe. 570 // 571 if (!is_directory_secure(dirname)) { 572 // directory is not secure 573 if (PrintMiscellaneous && Verbose) { 574 warning("%s directory is insecure\n", dirname); 575 } 576 return false; 577 } 578 } 579 else { 580 // we encountered some other failure while attempting 581 // to create the directory 582 // 583 if (PrintMiscellaneous && Verbose) { 584 warning("could not create directory %s: %s\n", 585 dirname, strerror(errno)); 586 } 587 return false; 588 } 589 } 590 return true; 591 } 592 593 // create the shared memory file resources 594 // 595 // This method creates the shared memory file with the given size 596 // This method also creates the user specific temporary directory, if 597 // it does not yet exist. 598 // 599 static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) { 600 601 // make the user temporary directory 602 if (!make_user_tmp_dir(dirname)) { 603 // could not make/find the directory or the found directory 604 // was not secure 605 return -1; 606 } 607 608 int result; 609 610 RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE), result); 611 if (result == OS_ERR) { 612 if (PrintMiscellaneous && Verbose) { 613 warning("could not create file %s: %s\n", filename, strerror(errno)); 614 } 615 return -1; 616 } 617 618 // save the file descriptor 619 int fd = result; 620 621 // set the file size 622 RESTARTABLE(::ftruncate(fd, (off_t)size), result); 623 if (result == OS_ERR) { 624 if (PrintMiscellaneous && Verbose) { 625 warning("could not set shared memory file size: %s\n", strerror(errno)); 626 } 627 RESTARTABLE(::close(fd), result); 628 return -1; 629 } 630 631 return fd; 632 } 633 634 // open the shared memory file for the given user and vmid. returns 635 // the file descriptor for the open file or -1 if the file could not 636 // be opened. 637 // 638 static int open_sharedmem_file(const char* filename, int oflags, TRAPS) { 639 640 // open the file 641 int result; 642 RESTARTABLE(::open(filename, oflags), result); 643 if (result == OS_ERR) { 644 if (errno == ENOENT) { 645 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 646 "Process not found"); 647 } 648 else if (errno == EACCES) { 649 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 650 "Permission denied"); 651 } 652 else { 653 THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno)); 654 } 655 } 656 657 return result; 658 } 659 660 // create a named shared memory region. returns the address of the 661 // memory region on success or NULL on failure. A return value of 662 // NULL will ultimately disable the shared memory feature. 663 // 664 // On Solaris and Linux, the name space for shared memory objects 665 // is the file system name space. 666 // 667 // A monitoring application attaching to a JVM does not need to know 668 // the file system name of the shared memory object. However, it may 669 // be convenient for applications to discover the existence of newly 670 // created and terminating JVMs by watching the file system name space 671 // for files being created or removed. 672 // 673 static char* mmap_create_shared(size_t size) { 674 675 int result; 676 int fd; 677 char* mapAddress; 678 679 int vmid = os::current_process_id(); 680 681 char* user_name = get_user_name(geteuid()); 682 683 if (user_name == NULL) 684 return NULL; 685 686 char* dirname = get_user_tmp_dir(user_name); 687 char* filename = get_sharedmem_filename(dirname, vmid); 688 689 // cleanup any stale shared memory files 690 cleanup_sharedmem_resources(dirname); 691 692 assert(((size > 0) && (size % os::vm_page_size() == 0)), 693 "unexpected PerfMemory region size"); 694 695 fd = create_sharedmem_resources(dirname, filename, size); 696 697 FREE_C_HEAP_ARRAY(char, user_name); 698 FREE_C_HEAP_ARRAY(char, dirname); 699 700 if (fd == -1) { 701 FREE_C_HEAP_ARRAY(char, filename); 702 return NULL; 703 } 704 705 mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 706 707 // attempt to close the file - restart it if it was interrupted, 708 // but ignore other failures 709 RESTARTABLE(::close(fd), result); 710 assert(result != OS_ERR, "could not close file"); 711 712 if (mapAddress == MAP_FAILED) { 713 if (PrintMiscellaneous && Verbose) { 714 warning("mmap failed - %s\n", strerror(errno)); 715 } 716 remove_file(filename); 717 FREE_C_HEAP_ARRAY(char, filename); 718 return NULL; 719 } 720 721 // save the file name for use in delete_shared_memory() 722 backing_store_file_name = filename; 723 724 // clear the shared memory region 725 (void)::memset((void*) mapAddress, 0, size); 726 727 return mapAddress; 728 } 729 730 // release a named shared memory region 731 // 732 static void unmap_shared(char* addr, size_t bytes) { 733 os::release_memory(addr, bytes); 734 } 735 736 // create the PerfData memory region in shared memory. 737 // 738 static char* create_shared_memory(size_t size) { 739 740 // create the shared memory region. 741 return mmap_create_shared(size); 742 } 743 744 // delete the shared PerfData memory region 745 // 746 static void delete_shared_memory(char* addr, size_t size) { 747 748 // cleanup the persistent shared memory resources. since DestroyJavaVM does 749 // not support unloading of the JVM, unmapping of the memory resource is 750 // not performed. The memory will be reclaimed by the OS upon termination of 751 // the process. The backing store file is deleted from the file system. 752 753 assert(!PerfDisableSharedMem, "shouldn't be here"); 754 755 if (backing_store_file_name != NULL) { 756 remove_file(backing_store_file_name); 757 // Don't.. Free heap memory could deadlock os::abort() if it is called 758 // from signal handler. OS will reclaim the heap memory. 759 // FREE_C_HEAP_ARRAY(char, backing_store_file_name); 760 backing_store_file_name = NULL; 761 } 762 } 763 764 // return the size of the file for the given file descriptor 765 // or 0 if it is not a valid size for a shared memory file 766 // 767 static size_t sharedmem_filesize(int fd, TRAPS) { 768 769 struct stat statbuf; 770 int result; 771 772 RESTARTABLE(::fstat(fd, &statbuf), result); 773 if (result == OS_ERR) { 774 if (PrintMiscellaneous && Verbose) { 775 warning("fstat failed: %s\n", strerror(errno)); 776 } 777 THROW_MSG_0(vmSymbols::java_io_IOException(), 778 "Could not determine PerfMemory size"); 779 } 780 781 if ((statbuf.st_size == 0) || 782 ((size_t)statbuf.st_size % os::vm_page_size() != 0)) { 783 THROW_MSG_0(vmSymbols::java_lang_Exception(), 784 "Invalid PerfMemory size"); 785 } 786 787 return (size_t)statbuf.st_size; 788 } 789 790 // attach to a named shared memory region. 791 // 792 static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) { 793 794 char* mapAddress; 795 int result; 796 int fd; 797 size_t size; 798 const char* luser = NULL; 799 800 int mmap_prot; 801 int file_flags; 802 803 ResourceMark rm; 804 805 // map the high level access mode to the appropriate permission 806 // constructs for the file and the shared memory mapping. 807 if (mode == PerfMemory::PERF_MODE_RO) { 808 mmap_prot = PROT_READ; 809 file_flags = O_RDONLY; 810 } 811 else if (mode == PerfMemory::PERF_MODE_RW) { 812 #ifdef LATER 813 mmap_prot = PROT_READ | PROT_WRITE; 814 file_flags = O_RDWR; 815 #else 816 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 817 "Unsupported access mode"); 818 #endif 819 } 820 else { 821 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 822 "Illegal access mode"); 823 } 824 825 if (user == NULL || strlen(user) == 0) { 826 luser = get_user_name(vmid, CHECK); 827 } 828 else { 829 luser = user; 830 } 831 832 if (luser == NULL) { 833 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 834 "Could not map vmid to user Name"); 835 } 836 837 char* dirname = get_user_tmp_dir(luser); 838 839 // since we don't follow symbolic links when creating the backing 840 // store file, we don't follow them when attaching either. 841 // 842 if (!is_directory_secure(dirname)) { 843 FREE_C_HEAP_ARRAY(char, dirname); 844 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 845 "Process not found"); 846 } 847 848 char* filename = get_sharedmem_filename(dirname, vmid); 849 850 // copy heap memory to resource memory. the open_sharedmem_file 851 // method below need to use the filename, but could throw an 852 // exception. using a resource array prevents the leak that 853 // would otherwise occur. 854 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 855 strcpy(rfilename, filename); 856 857 // free the c heap resources that are no longer needed 858 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 859 FREE_C_HEAP_ARRAY(char, dirname); 860 FREE_C_HEAP_ARRAY(char, filename); 861 862 // open the shared memory file for the give vmid 863 fd = open_sharedmem_file(rfilename, file_flags, CHECK); 864 assert(fd != OS_ERR, "unexpected value"); 865 866 if (*sizep == 0) { 867 size = sharedmem_filesize(fd, CHECK); 868 assert(size != 0, "unexpected size"); 869 } 870 871 mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0); 872 873 // attempt to close the file - restart if it gets interrupted, 874 // but ignore other failures 875 RESTARTABLE(::close(fd), result); 876 assert(result != OS_ERR, "could not close file"); 877 878 if (mapAddress == MAP_FAILED) { 879 if (PrintMiscellaneous && Verbose) { 880 warning("mmap failed: %s\n", strerror(errno)); 881 } 882 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 883 "Could not map PerfMemory"); 884 } 885 886 *addr = mapAddress; 887 *sizep = size; 888 889 if (PerfTraceMemOps) { 890 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 891 INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress); 892 } 893 } 894 895 896 897 898 // create the PerfData memory region 899 // 900 // This method creates the memory region used to store performance 901 // data for the JVM. The memory may be created in standard or 902 // shared memory. 903 // 904 void PerfMemory::create_memory_region(size_t size) { 905 906 if (PerfDisableSharedMem) { 907 // do not share the memory for the performance data. 908 _start = create_standard_memory(size); 909 } 910 else { 911 _start = create_shared_memory(size); 912 if (_start == NULL) { 913 914 // creation of the shared memory region failed, attempt 915 // to create a contiguous, non-shared memory region instead. 916 // 917 if (PrintMiscellaneous && Verbose) { 918 warning("Reverting to non-shared PerfMemory region.\n"); 919 } 920 PerfDisableSharedMem = true; 921 _start = create_standard_memory(size); 922 } 923 } 924 925 if (_start != NULL) _capacity = size; 926 927 } 928 929 // delete the PerfData memory region 930 // 931 // This method deletes the memory region used to store performance 932 // data for the JVM. The memory region indicated by the <address, size> 933 // tuple will be inaccessible after a call to this method. 934 // 935 void PerfMemory::delete_memory_region() { 936 937 assert((start() != NULL && capacity() > 0), "verify proper state"); 938 939 // If user specifies PerfDataSaveFile, it will save the performance data 940 // to the specified file name no matter whether PerfDataSaveToFile is specified 941 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 942 // -XX:+PerfDataSaveToFile. 943 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 944 save_memory_to_file(start(), capacity()); 945 } 946 947 if (PerfDisableSharedMem) { 948 delete_standard_memory(start(), capacity()); 949 } 950 else { 951 delete_shared_memory(start(), capacity()); 952 } 953 } 954 955 // attach to the PerfData memory region for another JVM 956 // 957 // This method returns an <address, size> tuple that points to 958 // a memory buffer that is kept reasonably synchronized with 959 // the PerfData memory region for the indicated JVM. This 960 // buffer may be kept in synchronization via shared memory 961 // or some other mechanism that keeps the buffer updated. 962 // 963 // If the JVM chooses not to support the attachability feature, 964 // this method should throw an UnsupportedOperation exception. 965 // 966 // This implementation utilizes named shared memory to map 967 // the indicated process's PerfData memory region into this JVMs 968 // address space. 969 // 970 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) { 971 972 if (vmid == 0 || vmid == os::current_process_id()) { 973 *addrp = start(); 974 *sizep = capacity(); 975 return; 976 } 977 978 mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK); 979 } 980 981 // detach from the PerfData memory region of another JVM 982 // 983 // This method detaches the PerfData memory region of another 984 // JVM, specified as an <address, size> tuple of a buffer 985 // in this process's address space. This method may perform 986 // arbitrary actions to accomplish the detachment. The memory 987 // region specified by <address, size> will be inaccessible after 988 // a call to this method. 989 // 990 // If the JVM chooses not to support the attachability feature, 991 // this method should throw an UnsupportedOperation exception. 992 // 993 // This implementation utilizes named shared memory to detach 994 // the indicated process's PerfData memory region from this 995 // process's address space. 996 // 997 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 998 999 assert(addr != 0, "address sanity check"); 1000 assert(bytes > 0, "capacity sanity check"); 1001 1002 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1003 // prevent accidental detachment of this process's PerfMemory region 1004 return; 1005 } 1006 1007 unmap_shared(addr, bytes); 1008 } 1009 1010 char* PerfMemory::backing_store_filename() { 1011 return backing_store_file_name; 1012 }