perfMemory_aix.cpp revision 10295:ad7a71500f4a
1/* 2 * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2012, 2016 SAP SE. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26#include "precompiled.hpp" 27#include "classfile/vmSymbols.hpp" 28#include "memory/allocation.inline.hpp" 29#include "memory/resourceArea.hpp" 30#include "oops/oop.inline.hpp" 31#include "os_aix.inline.hpp" 32#include "runtime/handles.inline.hpp" 33#include "runtime/perfMemory.hpp" 34#include "services/memTracker.hpp" 35#include "utilities/exceptions.hpp" 36 37// put OS-includes here 38# include <sys/types.h> 39# include <sys/mman.h> 40# include <errno.h> 41# include <stdio.h> 42# include <unistd.h> 43# include <sys/stat.h> 44# include <signal.h> 45# include <pwd.h> 46 47static char* backing_store_file_name = NULL; // name of the backing store 48 // file, if successfully created. 49 50// Standard Memory Implementation Details 51 52// create the PerfData memory region in standard memory. 53// 54static char* create_standard_memory(size_t size) { 55 56 // allocate an aligned chuck of memory 57 char* mapAddress = os::reserve_memory(size); 58 59 if (mapAddress == NULL) { 60 return NULL; 61 } 62 63 // commit memory 64 if (!os::commit_memory(mapAddress, size, !ExecMem)) { 65 if (PrintMiscellaneous && Verbose) { 66 warning("Could not commit PerfData memory\n"); 67 } 68 os::release_memory(mapAddress, size); 69 return NULL; 70 } 71 72 return mapAddress; 73} 74 75// delete the PerfData memory region 76// 77static void delete_standard_memory(char* addr, size_t size) { 78 79 // there are no persistent external resources to cleanup for standard 80 // memory. since DestroyJavaVM does not support unloading of the JVM, 81 // cleanup of the memory resource is not performed. The memory will be 82 // reclaimed by the OS upon termination of the process. 83 // 84 return; 85} 86 87// save the specified memory region to the given file 88// 89// Note: this function might be called from signal handler (by os::abort()), 90// don't allocate heap memory. 91// 92static void save_memory_to_file(char* addr, size_t size) { 93 94 const char* destfile = PerfMemory::get_perfdata_file_path(); 95 assert(destfile[0] != '\0', "invalid PerfData file path"); 96 97 int result; 98 99 RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE), 100 result);; 101 if (result == OS_ERR) { 102 if (PrintMiscellaneous && Verbose) { 103 warning("Could not create Perfdata save file: %s: %s\n", 104 destfile, strerror(errno)); 105 } 106 } else { 107 int fd = result; 108 109 for (size_t remaining = size; remaining > 0;) { 110 111 RESTARTABLE(::write(fd, addr, remaining), result); 112 if (result == OS_ERR) { 113 if (PrintMiscellaneous && Verbose) { 114 warning("Could not write Perfdata save file: %s: %s\n", 115 destfile, strerror(errno)); 116 } 117 break; 118 } 119 120 remaining -= (size_t)result; 121 addr += result; 122 } 123 124 result = ::close(fd); 125 if (PrintMiscellaneous && Verbose) { 126 if (result == OS_ERR) { 127 warning("Could not close %s: %s\n", destfile, strerror(errno)); 128 } 129 } 130 } 131 FREE_C_HEAP_ARRAY(char, destfile); 132} 133 134 135// Shared Memory Implementation Details 136 137// Note: the solaris and linux shared memory implementation uses the mmap 138// interface with a backing store file to implement named shared memory. 139// Using the file system as the name space for shared memory allows a 140// common name space to be supported across a variety of platforms. It 141// also provides a name space that Java applications can deal with through 142// simple file apis. 143// 144// The solaris and linux implementations store the backing store file in 145// a user specific temporary directory located in the /tmp file system, 146// which is always a local file system and is sometimes a RAM based file 147// system. 148 149// return the user specific temporary directory name. 150// 151// the caller is expected to free the allocated memory. 152// 153static char* get_user_tmp_dir(const char* user) { 154 155 const char* tmpdir = os::get_temp_directory(); 156 const char* perfdir = PERFDATA_NAME; 157 size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3; 158 char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 159 160 // construct the path name to user specific tmp directory 161 snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user); 162 163 return dirname; 164} 165 166// convert the given file name into a process id. if the file 167// does not meet the file naming constraints, return 0. 168// 169static pid_t filename_to_pid(const char* filename) { 170 171 // a filename that doesn't begin with a digit is not a 172 // candidate for conversion. 173 // 174 if (!isdigit(*filename)) { 175 return 0; 176 } 177 178 // check if file name can be converted to an integer without 179 // any leftover characters. 180 // 181 char* remainder = NULL; 182 errno = 0; 183 pid_t pid = (pid_t)strtol(filename, &remainder, 10); 184 185 if (errno != 0) { 186 return 0; 187 } 188 189 // check for left over characters. If any, then the filename is 190 // not a candidate for conversion. 191 // 192 if (remainder != NULL && *remainder != '\0') { 193 return 0; 194 } 195 196 // successful conversion, return the pid 197 return pid; 198} 199 200// Check if the given statbuf is considered a secure directory for 201// the backing store files. Returns true if the directory is considered 202// a secure location. Returns false if the statbuf is a symbolic link or 203// if an error occurred. 204// 205static bool is_statbuf_secure(struct stat *statp) { 206 if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) { 207 // The path represents a link or some non-directory file type, 208 // which is not what we expected. Declare it insecure. 209 // 210 return false; 211 } 212 // We have an existing directory, check if the permissions are safe. 213 // 214 if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) { 215 // The directory is open for writing and could be subjected 216 // to a symlink or a hard link attack. Declare it insecure. 217 // 218 return false; 219 } 220 // If user is not root then see if the uid of the directory matches the effective uid of the process. 221 uid_t euid = geteuid(); 222 if ((euid != 0) && (statp->st_uid != euid)) { 223 // The directory was not created by this user, declare it insecure. 224 // 225 return false; 226 } 227 return true; 228} 229 230 231// Check if the given path is considered a secure directory for 232// the backing store files. Returns true if the directory exists 233// and is considered a secure location. Returns false if the path 234// is a symbolic link or if an error occurred. 235// 236static bool is_directory_secure(const char* path) { 237 struct stat statbuf; 238 int result = 0; 239 240 RESTARTABLE(::lstat(path, &statbuf), result); 241 if (result == OS_ERR) { 242 return false; 243 } 244 245 // The path exists, see if it is secure. 246 return is_statbuf_secure(&statbuf); 247} 248 249// (Taken over from Solaris to support the O_NOFOLLOW case on AIX.) 250// Check if the given directory file descriptor is considered a secure 251// directory for the backing store files. Returns true if the directory 252// exists and is considered a secure location. Returns false if the path 253// is a symbolic link or if an error occurred. 254static bool is_dirfd_secure(int dir_fd) { 255 struct stat statbuf; 256 int result = 0; 257 258 RESTARTABLE(::fstat(dir_fd, &statbuf), result); 259 if (result == OS_ERR) { 260 return false; 261 } 262 263 // The path exists, now check its mode. 264 return is_statbuf_secure(&statbuf); 265} 266 267 268// Check to make sure fd1 and fd2 are referencing the same file system object. 269static bool is_same_fsobject(int fd1, int fd2) { 270 struct stat statbuf1; 271 struct stat statbuf2; 272 int result = 0; 273 274 RESTARTABLE(::fstat(fd1, &statbuf1), result); 275 if (result == OS_ERR) { 276 return false; 277 } 278 RESTARTABLE(::fstat(fd2, &statbuf2), result); 279 if (result == OS_ERR) { 280 return false; 281 } 282 283 if ((statbuf1.st_ino == statbuf2.st_ino) && 284 (statbuf1.st_dev == statbuf2.st_dev)) { 285 return true; 286 } else { 287 return false; 288 } 289} 290 291// Helper functions for open without O_NOFOLLOW which is not present on AIX 5.3/6.1. 292// We use the jdk6 implementation here. 293#ifndef O_NOFOLLOW 294// The O_NOFOLLOW oflag doesn't exist before solaris 5.10, this is to simulate that behaviour 295// was done in jdk 5/6 hotspot by Oracle this way 296static int open_o_nofollow_impl(const char* path, int oflag, mode_t mode, bool use_mode) { 297 struct stat orig_st; 298 struct stat new_st; 299 bool create; 300 int error; 301 int fd; 302 int result; 303 304 create = false; 305 306 RESTARTABLE(::lstat(path, &orig_st), result); 307 308 if (result == OS_ERR) { 309 if (errno == ENOENT && (oflag & O_CREAT) != 0) { 310 // File doesn't exist, but_we want to create it, add O_EXCL flag 311 // to make sure no-one creates it (or a symlink) before us 312 // This works as we expect with symlinks, from posix man page: 313 // 'If O_EXCL and O_CREAT are set, and path names a symbolic 314 // link, open() shall fail and set errno to [EEXIST]'. 315 oflag |= O_EXCL; 316 create = true; 317 } else { 318 // File doesn't exist, and we are not creating it. 319 return OS_ERR; 320 } 321 } else { 322 // lstat success, check if existing file is a link. 323 if ((orig_st.st_mode & S_IFMT) == S_IFLNK) { 324 // File is a symlink. 325 errno = ELOOP; 326 return OS_ERR; 327 } 328 } 329 330 if (use_mode == true) { 331 RESTARTABLE(::open(path, oflag, mode), fd); 332 } else { 333 RESTARTABLE(::open(path, oflag), fd); 334 } 335 336 if (fd == OS_ERR) { 337 return fd; 338 } 339 340 // Can't do inode checks on before/after if we created the file. 341 if (create == false) { 342 RESTARTABLE(::fstat(fd, &new_st), result); 343 if (result == OS_ERR) { 344 // Keep errno from fstat, in case close also fails. 345 error = errno; 346 ::close(fd); 347 errno = error; 348 return OS_ERR; 349 } 350 351 if (orig_st.st_dev != new_st.st_dev || orig_st.st_ino != new_st.st_ino) { 352 // File was tampered with during race window. 353 ::close(fd); 354 errno = EEXIST; 355 if (PrintMiscellaneous && Verbose) { 356 warning("possible file tampering attempt detected when opening %s", path); 357 } 358 return OS_ERR; 359 } 360 } 361 362 return fd; 363} 364 365static int open_o_nofollow(const char* path, int oflag, mode_t mode) { 366 return open_o_nofollow_impl(path, oflag, mode, true); 367} 368 369static int open_o_nofollow(const char* path, int oflag) { 370 return open_o_nofollow_impl(path, oflag, 0, false); 371} 372#endif 373 374// Open the directory of the given path and validate it. 375// Return a DIR * of the open directory. 376static DIR *open_directory_secure(const char* dirname) { 377 // Open the directory using open() so that it can be verified 378 // to be secure by calling is_dirfd_secure(), opendir() and then check 379 // to see if they are the same file system object. This method does not 380 // introduce a window of opportunity for the directory to be attacked that 381 // calling opendir() and is_directory_secure() does. 382 int result; 383 DIR *dirp = NULL; 384 385 // No O_NOFOLLOW defined at buildtime, and it is not documented for open; 386 // so provide a workaround in this case. 387#ifdef O_NOFOLLOW 388 RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result); 389#else 390 // workaround (jdk6 coding) 391 result = open_o_nofollow(dirname, O_RDONLY); 392#endif 393 394 if (result == OS_ERR) { 395 // Directory doesn't exist or is a symlink, so there is nothing to cleanup. 396 if (PrintMiscellaneous && Verbose) { 397 if (errno == ELOOP) { 398 warning("directory %s is a symlink and is not secure\n", dirname); 399 } else { 400 warning("could not open directory %s: %s\n", dirname, strerror(errno)); 401 } 402 } 403 return dirp; 404 } 405 int fd = result; 406 407 // Determine if the open directory is secure. 408 if (!is_dirfd_secure(fd)) { 409 // The directory is not a secure directory. 410 os::close(fd); 411 return dirp; 412 } 413 414 // Open the directory. 415 dirp = ::opendir(dirname); 416 if (dirp == NULL) { 417 // The directory doesn't exist, close fd and return. 418 os::close(fd); 419 return dirp; 420 } 421 422 // Check to make sure fd and dirp are referencing the same file system object. 423 if (!is_same_fsobject(fd, dirp->dd_fd)) { 424 // The directory is not secure. 425 os::close(fd); 426 os::closedir(dirp); 427 dirp = NULL; 428 return dirp; 429 } 430 431 // Close initial open now that we know directory is secure 432 os::close(fd); 433 434 return dirp; 435} 436 437// NOTE: The code below uses fchdir(), open() and unlink() because 438// fdopendir(), openat() and unlinkat() are not supported on all 439// versions. Once the support for fdopendir(), openat() and unlinkat() 440// is available on all supported versions the code can be changed 441// to use these functions. 442 443// Open the directory of the given path, validate it and set the 444// current working directory to it. 445// Return a DIR * of the open directory and the saved cwd fd. 446// 447static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) { 448 449 // Open the directory. 450 DIR* dirp = open_directory_secure(dirname); 451 if (dirp == NULL) { 452 // Directory doesn't exist or is insecure, so there is nothing to cleanup. 453 return dirp; 454 } 455 int fd = dirp->dd_fd; 456 457 // Open a fd to the cwd and save it off. 458 int result; 459 RESTARTABLE(::open(".", O_RDONLY), result); 460 if (result == OS_ERR) { 461 *saved_cwd_fd = -1; 462 } else { 463 *saved_cwd_fd = result; 464 } 465 466 // Set the current directory to dirname by using the fd of the directory and 467 // handle errors, otherwise shared memory files will be created in cwd. 468 result = fchdir(fd); 469 if (result == OS_ERR) { 470 if (PrintMiscellaneous && Verbose) { 471 warning("could not change to directory %s", dirname); 472 } 473 if (*saved_cwd_fd != -1) { 474 ::close(*saved_cwd_fd); 475 *saved_cwd_fd = -1; 476 } 477 // Close the directory. 478 os::closedir(dirp); 479 return NULL; 480 } else { 481 return dirp; 482 } 483} 484 485// Close the directory and restore the current working directory. 486// 487static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) { 488 489 int result; 490 // If we have a saved cwd change back to it and close the fd. 491 if (saved_cwd_fd != -1) { 492 result = fchdir(saved_cwd_fd); 493 ::close(saved_cwd_fd); 494 } 495 496 // Close the directory. 497 os::closedir(dirp); 498} 499 500// Check if the given file descriptor is considered a secure. 501static bool is_file_secure(int fd, const char *filename) { 502 503 int result; 504 struct stat statbuf; 505 506 // Determine if the file is secure. 507 RESTARTABLE(::fstat(fd, &statbuf), result); 508 if (result == OS_ERR) { 509 if (PrintMiscellaneous && Verbose) { 510 warning("fstat failed on %s: %s\n", filename, strerror(errno)); 511 } 512 return false; 513 } 514 if (statbuf.st_nlink > 1) { 515 // A file with multiple links is not expected. 516 if (PrintMiscellaneous && Verbose) { 517 warning("file %s has multiple links\n", filename); 518 } 519 return false; 520 } 521 return true; 522} 523 524// Return the user name for the given user id. 525// 526// The caller is expected to free the allocated memory. 527static char* get_user_name(uid_t uid) { 528 529 struct passwd pwent; 530 531 // Determine the max pwbuf size from sysconf, and hardcode 532 // a default if this not available through sysconf. 533 long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); 534 if (bufsize == -1) 535 bufsize = 1024; 536 537 char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 538 539 struct passwd* p; 540 int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p); 541 542 if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') { 543 if (PrintMiscellaneous && Verbose) { 544 if (result != 0) { 545 warning("Could not retrieve passwd entry: %s\n", 546 strerror(result)); 547 } 548 else if (p == NULL) { 549 // this check is added to protect against an observed problem 550 // with getpwuid_r() on RedHat 9 where getpwuid_r returns 0, 551 // indicating success, but has p == NULL. This was observed when 552 // inserting a file descriptor exhaustion fault prior to the call 553 // getpwuid_r() call. In this case, error is set to the appropriate 554 // error condition, but this is undocumented behavior. This check 555 // is safe under any condition, but the use of errno in the output 556 // message may result in an erroneous message. 557 // Bug Id 89052 was opened with RedHat. 558 // 559 warning("Could not retrieve passwd entry: %s\n", 560 strerror(errno)); 561 } 562 else { 563 warning("Could not determine user name: %s\n", 564 p->pw_name == NULL ? "pw_name = NULL" : 565 "pw_name zero length"); 566 } 567 } 568 FREE_C_HEAP_ARRAY(char, pwbuf); 569 return NULL; 570 } 571 572 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal); 573 strcpy(user_name, p->pw_name); 574 575 FREE_C_HEAP_ARRAY(char, pwbuf); 576 return user_name; 577} 578 579// return the name of the user that owns the process identified by vmid. 580// 581// This method uses a slow directory search algorithm to find the backing 582// store file for the specified vmid and returns the user name, as determined 583// by the user name suffix of the hsperfdata_<username> directory name. 584// 585// the caller is expected to free the allocated memory. 586// 587static char* get_user_name_slow(int vmid, TRAPS) { 588 589 // short circuit the directory search if the process doesn't even exist. 590 if (kill(vmid, 0) == OS_ERR) { 591 if (errno == ESRCH) { 592 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 593 "Process not found"); 594 } 595 else /* EPERM */ { 596 THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno)); 597 } 598 } 599 600 // directory search 601 char* oldest_user = NULL; 602 time_t oldest_ctime = 0; 603 604 const char* tmpdirname = os::get_temp_directory(); 605 606 DIR* tmpdirp = os::opendir(tmpdirname); 607 608 if (tmpdirp == NULL) { 609 return NULL; 610 } 611 612 // for each entry in the directory that matches the pattern hsperfdata_*, 613 // open the directory and check if the file for the given vmid exists. 614 // The file with the expected name and the latest creation date is used 615 // to determine the user name for the process id. 616 // 617 struct dirent* dentry; 618 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal); 619 errno = 0; 620 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) { 621 622 // check if the directory entry is a hsperfdata file 623 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) { 624 continue; 625 } 626 627 char* usrdir_name = NEW_C_HEAP_ARRAY(char, 628 strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal); 629 strcpy(usrdir_name, tmpdirname); 630 strcat(usrdir_name, "/"); 631 strcat(usrdir_name, dentry->d_name); 632 633 // Open the user directory. 634 DIR* subdirp = open_directory_secure(usrdir_name); 635 636 if (subdirp == NULL) { 637 FREE_C_HEAP_ARRAY(char, usrdir_name); 638 continue; 639 } 640 641 // Since we don't create the backing store files in directories 642 // pointed to by symbolic links, we also don't follow them when 643 // looking for the files. We check for a symbolic link after the 644 // call to opendir in order to eliminate a small window where the 645 // symlink can be exploited. 646 // 647 if (!is_directory_secure(usrdir_name)) { 648 FREE_C_HEAP_ARRAY(char, usrdir_name); 649 os::closedir(subdirp); 650 continue; 651 } 652 653 struct dirent* udentry; 654 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal); 655 errno = 0; 656 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) { 657 658 if (filename_to_pid(udentry->d_name) == vmid) { 659 struct stat statbuf; 660 int result; 661 662 char* filename = NEW_C_HEAP_ARRAY(char, 663 strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal); 664 665 strcpy(filename, usrdir_name); 666 strcat(filename, "/"); 667 strcat(filename, udentry->d_name); 668 669 // don't follow symbolic links for the file 670 RESTARTABLE(::lstat(filename, &statbuf), result); 671 if (result == OS_ERR) { 672 FREE_C_HEAP_ARRAY(char, filename); 673 continue; 674 } 675 676 // skip over files that are not regular files. 677 if (!S_ISREG(statbuf.st_mode)) { 678 FREE_C_HEAP_ARRAY(char, filename); 679 continue; 680 } 681 682 // compare and save filename with latest creation time 683 if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) { 684 685 if (statbuf.st_ctime > oldest_ctime) { 686 char* user = strchr(dentry->d_name, '_') + 1; 687 688 if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user); 689 oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal); 690 691 strcpy(oldest_user, user); 692 oldest_ctime = statbuf.st_ctime; 693 } 694 } 695 696 FREE_C_HEAP_ARRAY(char, filename); 697 } 698 } 699 os::closedir(subdirp); 700 FREE_C_HEAP_ARRAY(char, udbuf); 701 FREE_C_HEAP_ARRAY(char, usrdir_name); 702 } 703 os::closedir(tmpdirp); 704 FREE_C_HEAP_ARRAY(char, tdbuf); 705 706 return(oldest_user); 707} 708 709// return the name of the user that owns the JVM indicated by the given vmid. 710// 711static char* get_user_name(int vmid, TRAPS) { 712 return get_user_name_slow(vmid, THREAD); 713} 714 715// return the file name of the backing store file for the named 716// shared memory region for the given user name and vmid. 717// 718// the caller is expected to free the allocated memory. 719// 720static char* get_sharedmem_filename(const char* dirname, int vmid) { 721 722 // add 2 for the file separator and a null terminator. 723 size_t nbytes = strlen(dirname) + UINT_CHARS + 2; 724 725 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal); 726 snprintf(name, nbytes, "%s/%d", dirname, vmid); 727 728 return name; 729} 730 731 732// remove file 733// 734// this method removes the file specified by the given path 735// 736static void remove_file(const char* path) { 737 738 int result; 739 740 // if the file is a directory, the following unlink will fail. since 741 // we don't expect to find directories in the user temp directory, we 742 // won't try to handle this situation. even if accidentially or 743 // maliciously planted, the directory's presence won't hurt anything. 744 // 745 RESTARTABLE(::unlink(path), result); 746 if (PrintMiscellaneous && Verbose && result == OS_ERR) { 747 if (errno != ENOENT) { 748 warning("Could not unlink shared memory backing" 749 " store file %s : %s\n", path, strerror(errno)); 750 } 751 } 752} 753 754// Cleanup stale shared memory resources 755// 756// This method attempts to remove all stale shared memory files in 757// the named user temporary directory. It scans the named directory 758// for files matching the pattern ^$[0-9]*$. For each file found, the 759// process id is extracted from the file name and a test is run to 760// determine if the process is alive. If the process is not alive, 761// any stale file resources are removed. 762static void cleanup_sharedmem_resources(const char* dirname) { 763 764 int saved_cwd_fd; 765 // Open the directory. 766 DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd); 767 if (dirp == NULL) { 768 // Directory doesn't exist or is insecure, so there is nothing to cleanup. 769 return; 770 } 771 772 // For each entry in the directory that matches the expected file 773 // name pattern, determine if the file resources are stale and if 774 // so, remove the file resources. Note, instrumented HotSpot processes 775 // for this user may start and/or terminate during this search and 776 // remove or create new files in this directory. The behavior of this 777 // loop under these conditions is dependent upon the implementation of 778 // opendir/readdir. 779 struct dirent* entry; 780 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal); 781 782 errno = 0; 783 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) { 784 785 pid_t pid = filename_to_pid(entry->d_name); 786 787 if (pid == 0) { 788 789 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { 790 791 // Attempt to remove all unexpected files, except "." and "..". 792 unlink(entry->d_name); 793 } 794 795 errno = 0; 796 continue; 797 } 798 799 // We now have a file name that converts to a valid integer 800 // that could represent a process id . if this process id 801 // matches the current process id or the process is not running, 802 // then remove the stale file resources. 803 // 804 // Process liveness is detected by sending signal number 0 to 805 // the process id (see kill(2)). if kill determines that the 806 // process does not exist, then the file resources are removed. 807 // if kill determines that that we don't have permission to 808 // signal the process, then the file resources are assumed to 809 // be stale and are removed because the resources for such a 810 // process should be in a different user specific directory. 811 if ((pid == os::current_process_id()) || 812 (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) { 813 814 unlink(entry->d_name); 815 } 816 errno = 0; 817 } 818 819 // Close the directory and reset the current working directory. 820 close_directory_secure_cwd(dirp, saved_cwd_fd); 821 822 FREE_C_HEAP_ARRAY(char, dbuf); 823} 824 825// Make the user specific temporary directory. Returns true if 826// the directory exists and is secure upon return. Returns false 827// if the directory exists but is either a symlink, is otherwise 828// insecure, or if an error occurred. 829static bool make_user_tmp_dir(const char* dirname) { 830 831 // Create the directory with 0755 permissions. note that the directory 832 // will be owned by euid::egid, which may not be the same as uid::gid. 833 if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) { 834 if (errno == EEXIST) { 835 // The directory already exists and was probably created by another 836 // JVM instance. However, this could also be the result of a 837 // deliberate symlink. Verify that the existing directory is safe. 838 if (!is_directory_secure(dirname)) { 839 // Directory is not secure. 840 if (PrintMiscellaneous && Verbose) { 841 warning("%s directory is insecure\n", dirname); 842 } 843 return false; 844 } 845 } 846 else { 847 // we encountered some other failure while attempting 848 // to create the directory 849 // 850 if (PrintMiscellaneous && Verbose) { 851 warning("could not create directory %s: %s\n", 852 dirname, strerror(errno)); 853 } 854 return false; 855 } 856 } 857 return true; 858} 859 860// create the shared memory file resources 861// 862// This method creates the shared memory file with the given size 863// This method also creates the user specific temporary directory, if 864// it does not yet exist. 865// 866static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) { 867 868 // make the user temporary directory 869 if (!make_user_tmp_dir(dirname)) { 870 // could not make/find the directory or the found directory 871 // was not secure 872 return -1; 873 } 874 875 int saved_cwd_fd; 876 // Open the directory and set the current working directory to it. 877 DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd); 878 if (dirp == NULL) { 879 // Directory doesn't exist or is insecure, so cannot create shared 880 // memory file. 881 return -1; 882 } 883 884 // Open the filename in the current directory. 885 // Cannot use O_TRUNC here; truncation of an existing file has to happen 886 // after the is_file_secure() check below. 887 int result; 888 889 // No O_NOFOLLOW defined at buildtime, and it is not documented for open; 890 // so provide a workaround in this case. 891#ifdef O_NOFOLLOW 892 RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result); 893#else 894 // workaround function (jdk6 code) 895 result = open_o_nofollow(filename, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); 896#endif 897 898 if (result == OS_ERR) { 899 if (PrintMiscellaneous && Verbose) { 900 if (errno == ELOOP) { 901 warning("file %s is a symlink and is not secure\n", filename); 902 } else { 903 warning("could not create file %s: %s\n", filename, strerror(errno)); 904 } 905 } 906 // Close the directory and reset the current working directory. 907 close_directory_secure_cwd(dirp, saved_cwd_fd); 908 909 return -1; 910 } 911 // Close the directory and reset the current working directory. 912 close_directory_secure_cwd(dirp, saved_cwd_fd); 913 914 // save the file descriptor 915 int fd = result; 916 917 // Check to see if the file is secure. 918 if (!is_file_secure(fd, filename)) { 919 ::close(fd); 920 return -1; 921 } 922 923 // Truncate the file to get rid of any existing data. 924 RESTARTABLE(::ftruncate(fd, (off_t)0), result); 925 if (result == OS_ERR) { 926 if (PrintMiscellaneous && Verbose) { 927 warning("could not truncate shared memory file: %s\n", strerror(errno)); 928 } 929 ::close(fd); 930 return -1; 931 } 932 // set the file size 933 RESTARTABLE(::ftruncate(fd, (off_t)size), result); 934 if (result == OS_ERR) { 935 if (PrintMiscellaneous && Verbose) { 936 warning("could not set shared memory file size: %s\n", strerror(errno)); 937 } 938 ::close(fd); 939 return -1; 940 } 941 942 return fd; 943} 944 945// open the shared memory file for the given user and vmid. returns 946// the file descriptor for the open file or -1 if the file could not 947// be opened. 948// 949static int open_sharedmem_file(const char* filename, int oflags, TRAPS) { 950 951 // open the file 952 int result; 953 // No O_NOFOLLOW defined at buildtime, and it is not documented for open; 954 // so provide a workaround in this case 955#ifdef O_NOFOLLOW 956 RESTARTABLE(::open(filename, oflags), result); 957#else 958 open_o_nofollow(filename, oflags); 959#endif 960 961 if (result == OS_ERR) { 962 if (errno == ENOENT) { 963 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 964 "Process not found"); 965 } 966 else if (errno == EACCES) { 967 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), 968 "Permission denied"); 969 } 970 else { 971 THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno)); 972 } 973 } 974 int fd = result; 975 976 // Check to see if the file is secure. 977 if (!is_file_secure(fd, filename)) { 978 ::close(fd); 979 return -1; 980 } 981 982 return fd; 983} 984 985// create a named shared memory region. returns the address of the 986// memory region on success or NULL on failure. A return value of 987// NULL will ultimately disable the shared memory feature. 988// 989// On AIX, Solaris and Linux, the name space for shared memory objects 990// is the file system name space. 991// 992// A monitoring application attaching to a JVM does not need to know 993// the file system name of the shared memory object. However, it may 994// be convenient for applications to discover the existence of newly 995// created and terminating JVMs by watching the file system name space 996// for files being created or removed. 997// 998static char* mmap_create_shared(size_t size) { 999 1000 int result; 1001 int fd; 1002 char* mapAddress; 1003 1004 int vmid = os::current_process_id(); 1005 1006 char* user_name = get_user_name(geteuid()); 1007 1008 if (user_name == NULL) 1009 return NULL; 1010 1011 char* dirname = get_user_tmp_dir(user_name); 1012 char* filename = get_sharedmem_filename(dirname, vmid); 1013 // get the short filename. 1014 char* short_filename = strrchr(filename, '/'); 1015 if (short_filename == NULL) { 1016 short_filename = filename; 1017 } else { 1018 short_filename++; 1019 } 1020 1021 // cleanup any stale shared memory files 1022 cleanup_sharedmem_resources(dirname); 1023 1024 assert(((size > 0) && (size % os::vm_page_size() == 0)), 1025 "unexpected PerfMemory region size"); 1026 1027 fd = create_sharedmem_resources(dirname, short_filename, size); 1028 1029 FREE_C_HEAP_ARRAY(char, user_name); 1030 FREE_C_HEAP_ARRAY(char, dirname); 1031 1032 if (fd == -1) { 1033 FREE_C_HEAP_ARRAY(char, filename); 1034 return NULL; 1035 } 1036 1037 mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 1038 1039 result = ::close(fd); 1040 assert(result != OS_ERR, "could not close file"); 1041 1042 if (mapAddress == MAP_FAILED) { 1043 if (PrintMiscellaneous && Verbose) { 1044 warning("mmap failed - %s\n", strerror(errno)); 1045 } 1046 remove_file(filename); 1047 FREE_C_HEAP_ARRAY(char, filename); 1048 return NULL; 1049 } 1050 1051 // save the file name for use in delete_shared_memory() 1052 backing_store_file_name = filename; 1053 1054 // clear the shared memory region 1055 (void)::memset((void*) mapAddress, 0, size); 1056 1057 // It does not go through os api, the operation has to record from here. 1058 MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal); 1059 1060 return mapAddress; 1061} 1062 1063// release a named shared memory region 1064// 1065static void unmap_shared(char* addr, size_t bytes) { 1066 // Do not rely on os::reserve_memory/os::release_memory to use mmap. 1067 // Use os::reserve_memory/os::release_memory for PerfDisableSharedMem=1, mmap/munmap for PerfDisableSharedMem=0 1068 if (::munmap(addr, bytes) == -1) { 1069 warning("perfmemory: munmap failed (%d)\n", errno); 1070 } 1071} 1072 1073// create the PerfData memory region in shared memory. 1074// 1075static char* create_shared_memory(size_t size) { 1076 1077 // create the shared memory region. 1078 return mmap_create_shared(size); 1079} 1080 1081// delete the shared PerfData memory region 1082// 1083static void delete_shared_memory(char* addr, size_t size) { 1084 1085 // cleanup the persistent shared memory resources. since DestroyJavaVM does 1086 // not support unloading of the JVM, unmapping of the memory resource is 1087 // not performed. The memory will be reclaimed by the OS upon termination of 1088 // the process. The backing store file is deleted from the file system. 1089 1090 assert(!PerfDisableSharedMem, "shouldn't be here"); 1091 1092 if (backing_store_file_name != NULL) { 1093 remove_file(backing_store_file_name); 1094 // Don't.. Free heap memory could deadlock os::abort() if it is called 1095 // from signal handler. OS will reclaim the heap memory. 1096 // FREE_C_HEAP_ARRAY(char, backing_store_file_name); 1097 backing_store_file_name = NULL; 1098 } 1099} 1100 1101// return the size of the file for the given file descriptor 1102// or 0 if it is not a valid size for a shared memory file 1103// 1104static size_t sharedmem_filesize(int fd, TRAPS) { 1105 1106 struct stat statbuf; 1107 int result; 1108 1109 RESTARTABLE(::fstat(fd, &statbuf), result); 1110 if (result == OS_ERR) { 1111 if (PrintMiscellaneous && Verbose) { 1112 warning("fstat failed: %s\n", strerror(errno)); 1113 } 1114 THROW_MSG_0(vmSymbols::java_io_IOException(), 1115 "Could not determine PerfMemory size"); 1116 } 1117 1118 if ((statbuf.st_size == 0) || 1119 ((size_t)statbuf.st_size % os::vm_page_size() != 0)) { 1120 THROW_MSG_0(vmSymbols::java_lang_Exception(), 1121 "Invalid PerfMemory size"); 1122 } 1123 1124 return (size_t)statbuf.st_size; 1125} 1126 1127// attach to a named shared memory region. 1128// 1129static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) { 1130 1131 char* mapAddress; 1132 int result; 1133 int fd; 1134 size_t size = 0; 1135 const char* luser = NULL; 1136 1137 int mmap_prot; 1138 int file_flags; 1139 1140 ResourceMark rm; 1141 1142 // map the high level access mode to the appropriate permission 1143 // constructs for the file and the shared memory mapping. 1144 if (mode == PerfMemory::PERF_MODE_RO) { 1145 mmap_prot = PROT_READ; 1146 // No O_NOFOLLOW defined at buildtime, and it is not documented for open. 1147#ifdef O_NOFOLLOW 1148 file_flags = O_RDONLY | O_NOFOLLOW; 1149#else 1150 file_flags = O_RDONLY; 1151#endif 1152 } 1153 else if (mode == PerfMemory::PERF_MODE_RW) { 1154#ifdef LATER 1155 mmap_prot = PROT_READ | PROT_WRITE; 1156 file_flags = O_RDWR | O_NOFOLLOW; 1157#else 1158 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1159 "Unsupported access mode"); 1160#endif 1161 } 1162 else { 1163 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1164 "Illegal access mode"); 1165 } 1166 1167 if (user == NULL || strlen(user) == 0) { 1168 luser = get_user_name(vmid, CHECK); 1169 } 1170 else { 1171 luser = user; 1172 } 1173 1174 if (luser == NULL) { 1175 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1176 "Could not map vmid to user Name"); 1177 } 1178 1179 char* dirname = get_user_tmp_dir(luser); 1180 1181 // since we don't follow symbolic links when creating the backing 1182 // store file, we don't follow them when attaching either. 1183 // 1184 if (!is_directory_secure(dirname)) { 1185 FREE_C_HEAP_ARRAY(char, dirname); 1186 if (luser != user) { 1187 FREE_C_HEAP_ARRAY(char, luser); 1188 } 1189 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1190 "Process not found"); 1191 } 1192 1193 char* filename = get_sharedmem_filename(dirname, vmid); 1194 1195 // copy heap memory to resource memory. the open_sharedmem_file 1196 // method below need to use the filename, but could throw an 1197 // exception. using a resource array prevents the leak that 1198 // would otherwise occur. 1199 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1); 1200 strcpy(rfilename, filename); 1201 1202 // free the c heap resources that are no longer needed 1203 if (luser != user) FREE_C_HEAP_ARRAY(char, luser); 1204 FREE_C_HEAP_ARRAY(char, dirname); 1205 FREE_C_HEAP_ARRAY(char, filename); 1206 1207 // open the shared memory file for the give vmid 1208 fd = open_sharedmem_file(rfilename, file_flags, THREAD); 1209 1210 if (fd == OS_ERR) { 1211 return; 1212 } 1213 1214 if (HAS_PENDING_EXCEPTION) { 1215 ::close(fd); 1216 return; 1217 } 1218 1219 if (*sizep == 0) { 1220 size = sharedmem_filesize(fd, CHECK); 1221 } else { 1222 size = *sizep; 1223 } 1224 1225 assert(size > 0, "unexpected size <= 0"); 1226 1227 mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0); 1228 1229 result = ::close(fd); 1230 assert(result != OS_ERR, "could not close file"); 1231 1232 if (mapAddress == MAP_FAILED) { 1233 if (PrintMiscellaneous && Verbose) { 1234 warning("mmap failed: %s\n", strerror(errno)); 1235 } 1236 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), 1237 "Could not map PerfMemory"); 1238 } 1239 1240 // it does not go through os api, the operation has to record from here. 1241 MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal); 1242 1243 *addr = mapAddress; 1244 *sizep = size; 1245 1246 if (PerfTraceMemOps) { 1247 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at " 1248 INTPTR_FORMAT "\n", size, vmid, p2i((void*)mapAddress)); 1249 } 1250} 1251 1252 1253 1254 1255// create the PerfData memory region 1256// 1257// This method creates the memory region used to store performance 1258// data for the JVM. The memory may be created in standard or 1259// shared memory. 1260// 1261void PerfMemory::create_memory_region(size_t size) { 1262 1263 if (PerfDisableSharedMem) { 1264 // do not share the memory for the performance data. 1265 _start = create_standard_memory(size); 1266 } 1267 else { 1268 _start = create_shared_memory(size); 1269 if (_start == NULL) { 1270 1271 // creation of the shared memory region failed, attempt 1272 // to create a contiguous, non-shared memory region instead. 1273 // 1274 if (PrintMiscellaneous && Verbose) { 1275 warning("Reverting to non-shared PerfMemory region.\n"); 1276 } 1277 PerfDisableSharedMem = true; 1278 _start = create_standard_memory(size); 1279 } 1280 } 1281 1282 if (_start != NULL) _capacity = size; 1283 1284} 1285 1286// delete the PerfData memory region 1287// 1288// This method deletes the memory region used to store performance 1289// data for the JVM. The memory region indicated by the <address, size> 1290// tuple will be inaccessible after a call to this method. 1291// 1292void PerfMemory::delete_memory_region() { 1293 1294 assert((start() != NULL && capacity() > 0), "verify proper state"); 1295 1296 // If user specifies PerfDataSaveFile, it will save the performance data 1297 // to the specified file name no matter whether PerfDataSaveToFile is specified 1298 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag 1299 // -XX:+PerfDataSaveToFile. 1300 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) { 1301 save_memory_to_file(start(), capacity()); 1302 } 1303 1304 if (PerfDisableSharedMem) { 1305 delete_standard_memory(start(), capacity()); 1306 } 1307 else { 1308 delete_shared_memory(start(), capacity()); 1309 } 1310} 1311 1312// attach to the PerfData memory region for another JVM 1313// 1314// This method returns an <address, size> tuple that points to 1315// a memory buffer that is kept reasonably synchronized with 1316// the PerfData memory region for the indicated JVM. This 1317// buffer may be kept in synchronization via shared memory 1318// or some other mechanism that keeps the buffer updated. 1319// 1320// If the JVM chooses not to support the attachability feature, 1321// this method should throw an UnsupportedOperation exception. 1322// 1323// This implementation utilizes named shared memory to map 1324// the indicated process's PerfData memory region into this JVMs 1325// address space. 1326// 1327void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) { 1328 1329 if (vmid == 0 || vmid == os::current_process_id()) { 1330 *addrp = start(); 1331 *sizep = capacity(); 1332 return; 1333 } 1334 1335 mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK); 1336} 1337 1338// detach from the PerfData memory region of another JVM 1339// 1340// This method detaches the PerfData memory region of another 1341// JVM, specified as an <address, size> tuple of a buffer 1342// in this process's address space. This method may perform 1343// arbitrary actions to accomplish the detachment. The memory 1344// region specified by <address, size> will be inaccessible after 1345// a call to this method. 1346// 1347// If the JVM chooses not to support the attachability feature, 1348// this method should throw an UnsupportedOperation exception. 1349// 1350// This implementation utilizes named shared memory to detach 1351// the indicated process's PerfData memory region from this 1352// process's address space. 1353// 1354void PerfMemory::detach(char* addr, size_t bytes, TRAPS) { 1355 1356 assert(addr != 0, "address sanity check"); 1357 assert(bytes > 0, "capacity sanity check"); 1358 1359 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) { 1360 // prevent accidental detachment of this process's PerfMemory region 1361 return; 1362 } 1363 1364 unmap_shared(addr, bytes); 1365} 1366