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