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