src/os/aix/vm/perfMemory_aix.cpp

Wed, 31 Jan 2018 19:24:57 -0500

author
dbuck
date
Wed, 31 Jan 2018 19:24:57 -0500
changeset 9289
427b2fb1944f
parent 8210
2d23269a45a0
child 9507
7e72702243a4
permissions
-rw-r--r--

8189170: Add option to disable stack overflow checking in primordial thread for use with JNI_CreateJavaJVM
Reviewed-by: dcubed

     1 /*
     2  * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
     3  * Copyright 2012, 2013 SAP AG. 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  */
    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"
    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>
    47 static char* backing_store_file_name = NULL;  // name of the backing store
    48                                               // file, if successfully created.
    50 // Standard Memory Implementation Details
    52 // create the PerfData memory region in standard memory.
    53 //
    54 static char* create_standard_memory(size_t size) {
    56   // allocate an aligned chuck of memory
    57   char* mapAddress = os::reserve_memory(size);
    59   if (mapAddress == NULL) {
    60     return NULL;
    61   }
    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   }
    72   return mapAddress;
    73 }
    75 // delete the PerfData memory region
    76 //
    77 static void delete_standard_memory(char* addr, size_t size) {
    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 }
    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 //
    92 static void save_memory_to_file(char* addr, size_t size) {
    94   const char* destfile = PerfMemory::get_perfdata_file_path();
    95   assert(destfile[0] != '\0', "invalid PerfData file path");
    97   int result;
    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;
   109     for (size_t remaining = size; remaining > 0;) {
   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       }
   120       remaining -= (size_t)result;
   121       addr += result;
   122     }
   124     RESTARTABLE(::close(fd), result);
   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, mtInternal);
   132 }
   135 // Shared Memory Implementation Details
   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.
   149 // return the user specific temporary directory name.
   150 //
   151 // the caller is expected to free the allocated memory.
   152 //
   153 static char* get_user_tmp_dir(const char* user) {
   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);
   160   // construct the path name to user specific tmp directory
   161   snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);
   163   return dirname;
   164 }
   166 // convert the given file name into a process id. if the file
   167 // does not meet the file naming constraints, return 0.
   168 //
   169 static pid_t filename_to_pid(const char* filename) {
   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   }
   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);
   185   if (errno != 0) {
   186     return 0;
   187   }
   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   }
   196   // successful conversion, return the pid
   197   return pid;
   198 }
   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 //
   205 static 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 }
   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 //
   236 static bool is_directory_secure(const char* path) {
   237   struct stat statbuf;
   238   int result = 0;
   240   RESTARTABLE(::lstat(path, &statbuf), result);
   241   if (result == OS_ERR) {
   242     return false;
   243   }
   245   // The path exists, see if it is secure.
   246   return is_statbuf_secure(&statbuf);
   247 }
   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.
   254 static bool is_dirfd_secure(int dir_fd) {
   255   struct stat statbuf;
   256   int result = 0;
   258   RESTARTABLE(::fstat(dir_fd, &statbuf), result);
   259   if (result == OS_ERR) {
   260     return false;
   261   }
   263   // The path exists, now check its mode.
   264   return is_statbuf_secure(&statbuf);
   265 }
   268 // Check to make sure fd1 and fd2 are referencing the same file system object.
   269 static bool is_same_fsobject(int fd1, int fd2) {
   270   struct stat statbuf1;
   271   struct stat statbuf2;
   272   int result = 0;
   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   }
   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 }
   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
   296 static 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;
   303   create = false;
   305   if (lstat(path, &orig_st) != 0) {
   306     if (errno == ENOENT && (oflag & O_CREAT) != 0) {
   307       // File doesn't exist, but_we want to create it, add O_EXCL flag
   308       // to make sure no-one creates it (or a symlink) before us
   309       // This works as we expect with symlinks, from posix man page:
   310       // 'If O_EXCL  and  O_CREAT  are set, and path names a symbolic
   311       // link, open() shall fail and set errno to [EEXIST]'.
   312       oflag |= O_EXCL;
   313       create = true;
   314     } else {
   315       // File doesn't exist, and we are not creating it.
   316       return OS_ERR;
   317     }
   318   } else {
   319     // Lstat success, check if existing file is a link.
   320     if ((orig_st.st_mode & S_IFMT) == S_IFLNK)  {
   321       // File is a symlink.
   322       errno = ELOOP;
   323       return OS_ERR;
   324     }
   325   }
   327   if (use_mode == true) {
   328     fd = open(path, oflag, mode);
   329   } else {
   330     fd = open(path, oflag);
   331   }
   333   if (fd == OS_ERR) {
   334     return fd;
   335   }
   337   // Can't do inode checks on before/after if we created the file.
   338   if (create == false) {
   339     if (fstat(fd, &new_st) != 0) {
   340       // Keep errno from fstat, in case close also fails.
   341       error = errno;
   342       ::close(fd);
   343       errno = error;
   344       return OS_ERR;
   345     }
   347     if (orig_st.st_dev != new_st.st_dev || orig_st.st_ino != new_st.st_ino) {
   348       // File was tampered with during race window.
   349       ::close(fd);
   350       errno = EEXIST;
   351       if (PrintMiscellaneous && Verbose) {
   352         warning("possible file tampering attempt detected when opening %s", path);
   353       }
   354       return OS_ERR;
   355     }
   356   }
   358   return fd;
   359 }
   361 static int open_o_nofollow(const char* path, int oflag, mode_t mode) {
   362   return open_o_nofollow_impl(path, oflag, mode, true);
   363 }
   365 static int open_o_nofollow(const char* path, int oflag) {
   366   return open_o_nofollow_impl(path, oflag, 0, false);
   367 }
   368 #endif
   370 // Open the directory of the given path and validate it.
   371 // Return a DIR * of the open directory.
   372 static DIR *open_directory_secure(const char* dirname) {
   373   // Open the directory using open() so that it can be verified
   374   // to be secure by calling is_dirfd_secure(), opendir() and then check
   375   // to see if they are the same file system object.  This method does not
   376   // introduce a window of opportunity for the directory to be attacked that
   377   // calling opendir() and is_directory_secure() does.
   378   int result;
   379   DIR *dirp = NULL;
   381   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   382   // so provide a workaround in this case.
   383 #ifdef O_NOFOLLOW
   384   RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);
   385 #else
   386   // workaround (jdk6 coding)
   387   RESTARTABLE(::open_o_nofollow(dirname, O_RDONLY), result);
   388 #endif
   390   if (result == OS_ERR) {
   391     // Directory doesn't exist or is a symlink, so there is nothing to cleanup.
   392     if (PrintMiscellaneous && Verbose) {
   393       if (errno == ELOOP) {
   394         warning("directory %s is a symlink and is not secure\n", dirname);
   395       } else {
   396         warning("could not open directory %s: %s\n", dirname, strerror(errno));
   397       }
   398     }
   399     return dirp;
   400   }
   401   int fd = result;
   403   // Determine if the open directory is secure.
   404   if (!is_dirfd_secure(fd)) {
   405     // The directory is not a secure directory.
   406     os::close(fd);
   407     return dirp;
   408   }
   410   // Open the directory.
   411   dirp = ::opendir(dirname);
   412   if (dirp == NULL) {
   413     // The directory doesn't exist, close fd and return.
   414     os::close(fd);
   415     return dirp;
   416   }
   418   // Check to make sure fd and dirp are referencing the same file system object.
   419   if (!is_same_fsobject(fd, dirp->dd_fd)) {
   420     // The directory is not secure.
   421     os::close(fd);
   422     os::closedir(dirp);
   423     dirp = NULL;
   424     return dirp;
   425   }
   427   // Close initial open now that we know directory is secure
   428   os::close(fd);
   430   return dirp;
   431 }
   433 // NOTE: The code below uses fchdir(), open() and unlink() because
   434 // fdopendir(), openat() and unlinkat() are not supported on all
   435 // versions.  Once the support for fdopendir(), openat() and unlinkat()
   436 // is available on all supported versions the code can be changed
   437 // to use these functions.
   439 // Open the directory of the given path, validate it and set the
   440 // current working directory to it.
   441 // Return a DIR * of the open directory and the saved cwd fd.
   442 //
   443 static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {
   445   // Open the directory.
   446   DIR* dirp = open_directory_secure(dirname);
   447   if (dirp == NULL) {
   448     // Directory doesn't exist or is insecure, so there is nothing to cleanup.
   449     return dirp;
   450   }
   451   int fd = dirp->dd_fd;
   453   // Open a fd to the cwd and save it off.
   454   int result;
   455   RESTARTABLE(::open(".", O_RDONLY), result);
   456   if (result == OS_ERR) {
   457     *saved_cwd_fd = -1;
   458   } else {
   459     *saved_cwd_fd = result;
   460   }
   462   // Set the current directory to dirname by using the fd of the directory and
   463   // handle errors, otherwise shared memory files will be created in cwd.
   464   result = fchdir(fd);
   465   if (result == OS_ERR) {
   466     if (PrintMiscellaneous && Verbose) {
   467       warning("could not change to directory %s", dirname);
   468     }
   469     if (*saved_cwd_fd != -1) {
   470       ::close(*saved_cwd_fd);
   471       *saved_cwd_fd = -1;
   472     }
   473     // Close the directory.
   474     os::closedir(dirp);
   475     return NULL;
   476   } else {
   477     return dirp;
   478   }
   479 }
   481 // Close the directory and restore the current working directory.
   482 //
   483 static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {
   485   int result;
   486   // If we have a saved cwd change back to it and close the fd.
   487   if (saved_cwd_fd != -1) {
   488     result = fchdir(saved_cwd_fd);
   489     ::close(saved_cwd_fd);
   490   }
   492   // Close the directory.
   493   os::closedir(dirp);
   494 }
   496 // Check if the given file descriptor is considered a secure.
   497 static bool is_file_secure(int fd, const char *filename) {
   499   int result;
   500   struct stat statbuf;
   502   // Determine if the file is secure.
   503   RESTARTABLE(::fstat(fd, &statbuf), result);
   504   if (result == OS_ERR) {
   505     if (PrintMiscellaneous && Verbose) {
   506       warning("fstat failed on %s: %s\n", filename, strerror(errno));
   507     }
   508     return false;
   509   }
   510   if (statbuf.st_nlink > 1) {
   511     // A file with multiple links is not expected.
   512     if (PrintMiscellaneous && Verbose) {
   513       warning("file %s has multiple links\n", filename);
   514     }
   515     return false;
   516   }
   517   return true;
   518 }
   520 // Return the user name for the given user id.
   521 //
   522 // The caller is expected to free the allocated memory.
   523 static char* get_user_name(uid_t uid) {
   525   struct passwd pwent;
   527   // Determine the max pwbuf size from sysconf, and hardcode
   528   // a default if this not available through sysconf.
   529   long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
   530   if (bufsize == -1)
   531     bufsize = 1024;
   533   char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
   535   // POSIX interface to getpwuid_r is used on LINUX
   536   struct passwd* p;
   537   int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);
   539   if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {
   540     if (PrintMiscellaneous && Verbose) {
   541       if (result != 0) {
   542         warning("Could not retrieve passwd entry: %s\n",
   543                 strerror(result));
   544       }
   545       else if (p == NULL) {
   546         // this check is added to protect against an observed problem
   547         // with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,
   548         // indicating success, but has p == NULL. This was observed when
   549         // inserting a file descriptor exhaustion fault prior to the call
   550         // getpwuid_r() call. In this case, error is set to the appropriate
   551         // error condition, but this is undocumented behavior. This check
   552         // is safe under any condition, but the use of errno in the output
   553         // message may result in an erroneous message.
   554         // Bug Id 89052 was opened with RedHat.
   555         //
   556         warning("Could not retrieve passwd entry: %s\n",
   557                 strerror(errno));
   558       }
   559       else {
   560         warning("Could not determine user name: %s\n",
   561                 p->pw_name == NULL ? "pw_name = NULL" :
   562                                      "pw_name zero length");
   563       }
   564     }
   565     FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
   566     return NULL;
   567   }
   569   char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);
   570   strcpy(user_name, p->pw_name);
   572   FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
   573   return user_name;
   574 }
   576 // return the name of the user that owns the process identified by vmid.
   577 //
   578 // This method uses a slow directory search algorithm to find the backing
   579 // store file for the specified vmid and returns the user name, as determined
   580 // by the user name suffix of the hsperfdata_<username> directory name.
   581 //
   582 // the caller is expected to free the allocated memory.
   583 //
   584 static char* get_user_name_slow(int vmid, TRAPS) {
   586   // short circuit the directory search if the process doesn't even exist.
   587   if (kill(vmid, 0) == OS_ERR) {
   588     if (errno == ESRCH) {
   589       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   590                   "Process not found");
   591     }
   592     else /* EPERM */ {
   593       THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   594     }
   595   }
   597   // directory search
   598   char* oldest_user = NULL;
   599   time_t oldest_ctime = 0;
   601   const char* tmpdirname = os::get_temp_directory();
   603   DIR* tmpdirp = os::opendir(tmpdirname);
   605   if (tmpdirp == NULL) {
   606     return NULL;
   607   }
   609   // for each entry in the directory that matches the pattern hsperfdata_*,
   610   // open the directory and check if the file for the given vmid exists.
   611   // The file with the expected name and the latest creation date is used
   612   // to determine the user name for the process id.
   613   //
   614   struct dirent* dentry;
   615   char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal);
   616   errno = 0;
   617   while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
   619     // check if the directory entry is a hsperfdata file
   620     if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
   621       continue;
   622     }
   624     char* usrdir_name = NEW_C_HEAP_ARRAY(char,
   625                               strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);
   626     strcpy(usrdir_name, tmpdirname);
   627     strcat(usrdir_name, "/");
   628     strcat(usrdir_name, dentry->d_name);
   630     // Open the user directory.
   631     DIR* subdirp = open_directory_secure(usrdir_name);
   633     if (subdirp == NULL) {
   634       FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   635       continue;
   636     }
   638     // Since we don't create the backing store files in directories
   639     // pointed to by symbolic links, we also don't follow them when
   640     // looking for the files. We check for a symbolic link after the
   641     // call to opendir in order to eliminate a small window where the
   642     // symlink can be exploited.
   643     //
   644     if (!is_directory_secure(usrdir_name)) {
   645       FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   646       os::closedir(subdirp);
   647       continue;
   648     }
   650     struct dirent* udentry;
   651     char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal);
   652     errno = 0;
   653     while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
   655       if (filename_to_pid(udentry->d_name) == vmid) {
   656         struct stat statbuf;
   657         int result;
   659         char* filename = NEW_C_HEAP_ARRAY(char,
   660                             strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
   662         strcpy(filename, usrdir_name);
   663         strcat(filename, "/");
   664         strcat(filename, udentry->d_name);
   666         // don't follow symbolic links for the file
   667         RESTARTABLE(::lstat(filename, &statbuf), result);
   668         if (result == OS_ERR) {
   669            FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   670            continue;
   671         }
   673         // skip over files that are not regular files.
   674         if (!S_ISREG(statbuf.st_mode)) {
   675           FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   676           continue;
   677         }
   679         // compare and save filename with latest creation time
   680         if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
   682           if (statbuf.st_ctime > oldest_ctime) {
   683             char* user = strchr(dentry->d_name, '_') + 1;
   685             if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);
   686             oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
   688             strcpy(oldest_user, user);
   689             oldest_ctime = statbuf.st_ctime;
   690           }
   691         }
   693         FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   694       }
   695     }
   696     os::closedir(subdirp);
   697     FREE_C_HEAP_ARRAY(char, udbuf, mtInternal);
   698     FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   699   }
   700   os::closedir(tmpdirp);
   701   FREE_C_HEAP_ARRAY(char, tdbuf, mtInternal);
   703   return(oldest_user);
   704 }
   706 // return the name of the user that owns the JVM indicated by the given vmid.
   707 //
   708 static char* get_user_name(int vmid, TRAPS) {
   709   return get_user_name_slow(vmid, CHECK_NULL);
   710 }
   712 // return the file name of the backing store file for the named
   713 // shared memory region for the given user name and vmid.
   714 //
   715 // the caller is expected to free the allocated memory.
   716 //
   717 static char* get_sharedmem_filename(const char* dirname, int vmid) {
   719   // add 2 for the file separator and a null terminator.
   720   size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
   722   char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
   723   snprintf(name, nbytes, "%s/%d", dirname, vmid);
   725   return name;
   726 }
   729 // remove file
   730 //
   731 // this method removes the file specified by the given path
   732 //
   733 static void remove_file(const char* path) {
   735   int result;
   737   // if the file is a directory, the following unlink will fail. since
   738   // we don't expect to find directories in the user temp directory, we
   739   // won't try to handle this situation. even if accidentially or
   740   // maliciously planted, the directory's presence won't hurt anything.
   741   //
   742   RESTARTABLE(::unlink(path), result);
   743   if (PrintMiscellaneous && Verbose && result == OS_ERR) {
   744     if (errno != ENOENT) {
   745       warning("Could not unlink shared memory backing"
   746               " store file %s : %s\n", path, strerror(errno));
   747     }
   748   }
   749 }
   751 // Cleanup stale shared memory resources
   752 //
   753 // This method attempts to remove all stale shared memory files in
   754 // the named user temporary directory. It scans the named directory
   755 // for files matching the pattern ^$[0-9]*$. For each file found, the
   756 // process id is extracted from the file name and a test is run to
   757 // determine if the process is alive. If the process is not alive,
   758 // any stale file resources are removed.
   759 static void cleanup_sharedmem_resources(const char* dirname) {
   761   int saved_cwd_fd;
   762   // Open the directory.
   763   DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
   764   if (dirp == NULL) {
   765      // Directory doesn't exist or is insecure, so there is nothing to cleanup.
   766     return;
   767   }
   769   // For each entry in the directory that matches the expected file
   770   // name pattern, determine if the file resources are stale and if
   771   // so, remove the file resources. Note, instrumented HotSpot processes
   772   // for this user may start and/or terminate during this search and
   773   // remove or create new files in this directory. The behavior of this
   774   // loop under these conditions is dependent upon the implementation of
   775   // opendir/readdir.
   776   struct dirent* entry;
   777   char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
   779   errno = 0;
   780   while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
   782     pid_t pid = filename_to_pid(entry->d_name);
   784     if (pid == 0) {
   786       if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
   788         // Attempt to remove all unexpected files, except "." and "..".
   789         unlink(entry->d_name);
   790       }
   792       errno = 0;
   793       continue;
   794     }
   796     // We now have a file name that converts to a valid integer
   797     // that could represent a process id . if this process id
   798     // matches the current process id or the process is not running,
   799     // then remove the stale file resources.
   800     //
   801     // Process liveness is detected by sending signal number 0 to
   802     // the process id (see kill(2)). if kill determines that the
   803     // process does not exist, then the file resources are removed.
   804     // if kill determines that that we don't have permission to
   805     // signal the process, then the file resources are assumed to
   806     // be stale and are removed because the resources for such a
   807     // process should be in a different user specific directory.
   808     if ((pid == os::current_process_id()) ||
   809         (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
   811         unlink(entry->d_name);
   812     }
   813     errno = 0;
   814   }
   816   // Close the directory and reset the current working directory.
   817   close_directory_secure_cwd(dirp, saved_cwd_fd);
   819   FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
   820 }
   822 // Make the user specific temporary directory. Returns true if
   823 // the directory exists and is secure upon return. Returns false
   824 // if the directory exists but is either a symlink, is otherwise
   825 // insecure, or if an error occurred.
   826 static bool make_user_tmp_dir(const char* dirname) {
   828   // Create the directory with 0755 permissions. note that the directory
   829   // will be owned by euid::egid, which may not be the same as uid::gid.
   830   if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
   831     if (errno == EEXIST) {
   832       // The directory already exists and was probably created by another
   833       // JVM instance. However, this could also be the result of a
   834       // deliberate symlink. Verify that the existing directory is safe.
   835       if (!is_directory_secure(dirname)) {
   836         // Directory is not secure.
   837         if (PrintMiscellaneous && Verbose) {
   838           warning("%s directory is insecure\n", dirname);
   839         }
   840         return false;
   841       }
   842     }
   843     else {
   844       // we encountered some other failure while attempting
   845       // to create the directory
   846       //
   847       if (PrintMiscellaneous && Verbose) {
   848         warning("could not create directory %s: %s\n",
   849                 dirname, strerror(errno));
   850       }
   851       return false;
   852     }
   853   }
   854   return true;
   855 }
   857 // create the shared memory file resources
   858 //
   859 // This method creates the shared memory file with the given size
   860 // This method also creates the user specific temporary directory, if
   861 // it does not yet exist.
   862 //
   863 static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
   865   // make the user temporary directory
   866   if (!make_user_tmp_dir(dirname)) {
   867     // could not make/find the directory or the found directory
   868     // was not secure
   869     return -1;
   870   }
   872   int saved_cwd_fd;
   873   // Open the directory and set the current working directory to it.
   874   DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
   875   if (dirp == NULL) {
   876     // Directory doesn't exist or is insecure, so cannot create shared
   877     // memory file.
   878     return -1;
   879   }
   881   // Open the filename in the current directory.
   882   // Cannot use O_TRUNC here; truncation of an existing file has to happen
   883   // after the is_file_secure() check below.
   884   int result;
   886   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   887   // so provide a workaround in this case.
   888 #ifdef O_NOFOLLOW
   889   RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);
   890 #else
   891   // workaround function (jdk6 code)
   892   RESTARTABLE(::open_o_nofollow(filename, O_RDWR|O_CREAT, S_IREAD|S_IWRITE), result);
   893 #endif
   895   if (result == OS_ERR) {
   896     if (PrintMiscellaneous && Verbose) {
   897       if (errno == ELOOP) {
   898         warning("file %s is a symlink and is not secure\n", filename);
   899       } else {
   900         warning("could not create file %s: %s\n", filename, strerror(errno));
   901       }
   902     }
   903     // Close the directory and reset the current working directory.
   904     close_directory_secure_cwd(dirp, saved_cwd_fd);
   906     return -1;
   907   }
   908   // Close the directory and reset the current working directory.
   909   close_directory_secure_cwd(dirp, saved_cwd_fd);
   911   // save the file descriptor
   912   int fd = result;
   914   // Check to see if the file is secure.
   915   if (!is_file_secure(fd, filename)) {
   916     ::close(fd);
   917     return -1;
   918   }
   920   // Truncate the file to get rid of any existing data.
   921   RESTARTABLE(::ftruncate(fd, (off_t)0), result);
   922   if (result == OS_ERR) {
   923     if (PrintMiscellaneous && Verbose) {
   924       warning("could not truncate shared memory file: %s\n", strerror(errno));
   925     }
   926     ::close(fd);
   927     return -1;
   928   }
   929   // set the file size
   930   RESTARTABLE(::ftruncate(fd, (off_t)size), result);
   931   if (result == OS_ERR) {
   932     if (PrintMiscellaneous && Verbose) {
   933       warning("could not set shared memory file size: %s\n", strerror(errno));
   934     }
   935     RESTARTABLE(::close(fd), result);
   936     return -1;
   937   }
   939   return fd;
   940 }
   942 // open the shared memory file for the given user and vmid. returns
   943 // the file descriptor for the open file or -1 if the file could not
   944 // be opened.
   945 //
   946 static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
   948   // open the file
   949   int result;
   950   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   951   // so provide a workaround in this case
   952 #ifdef O_NOFOLLOW
   953   RESTARTABLE(::open(filename, oflags), result);
   954 #else
   955   RESTARTABLE(::open_o_nofollow(filename, oflags), result);
   956 #endif
   958   if (result == OS_ERR) {
   959     if (errno == ENOENT) {
   960       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   961                   "Process not found");
   962     }
   963     else if (errno == EACCES) {
   964       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   965                   "Permission denied");
   966     }
   967     else {
   968       THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   969     }
   970   }
   971   int fd = result;
   973   // Check to see if the file is secure.
   974   if (!is_file_secure(fd, filename)) {
   975     ::close(fd);
   976     return -1;
   977   }
   979   return fd;
   980 }
   982 // create a named shared memory region. returns the address of the
   983 // memory region on success or NULL on failure. A return value of
   984 // NULL will ultimately disable the shared memory feature.
   985 //
   986 // On Solaris and Linux, the name space for shared memory objects
   987 // is the file system name space.
   988 //
   989 // A monitoring application attaching to a JVM does not need to know
   990 // the file system name of the shared memory object. However, it may
   991 // be convenient for applications to discover the existence of newly
   992 // created and terminating JVMs by watching the file system name space
   993 // for files being created or removed.
   994 //
   995 static char* mmap_create_shared(size_t size) {
   997   int result;
   998   int fd;
   999   char* mapAddress;
  1001   int vmid = os::current_process_id();
  1003   char* user_name = get_user_name(geteuid());
  1005   if (user_name == NULL)
  1006     return NULL;
  1008   char* dirname = get_user_tmp_dir(user_name);
  1009   char* filename = get_sharedmem_filename(dirname, vmid);
  1011   // Get the short filename.
  1012   char* short_filename = strrchr(filename, '/');
  1013   if (short_filename == NULL) {
  1014     short_filename = filename;
  1015   } else {
  1016     short_filename++;
  1019   // cleanup any stale shared memory files
  1020   cleanup_sharedmem_resources(dirname);
  1022   assert(((size > 0) && (size % os::vm_page_size() == 0)),
  1023          "unexpected PerfMemory region size");
  1025   fd = create_sharedmem_resources(dirname, short_filename, size);
  1027   FREE_C_HEAP_ARRAY(char, user_name, mtInternal);
  1028   FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1030   if (fd == -1) {
  1031     FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1032     return NULL;
  1035   mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  1037   // attempt to close the file - restart it if it was interrupted,
  1038   // but ignore other failures
  1039   RESTARTABLE(::close(fd), result);
  1040   assert(result != OS_ERR, "could not close file");
  1042   if (mapAddress == MAP_FAILED) {
  1043     if (PrintMiscellaneous && Verbose) {
  1044       warning("mmap failed -  %s\n", strerror(errno));
  1046     remove_file(filename);
  1047     FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1048     return NULL;
  1051   // save the file name for use in delete_shared_memory()
  1052   backing_store_file_name = filename;
  1054   // clear the shared memory region
  1055   (void)::memset((void*) mapAddress, 0, size);
  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);
  1060   return mapAddress;
  1063 // release a named shared memory region
  1064 //
  1065 static 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);
  1073 // create the PerfData memory region in shared memory.
  1074 //
  1075 static char* create_shared_memory(size_t size) {
  1077   // create the shared memory region.
  1078   return mmap_create_shared(size);
  1081 // delete the shared PerfData memory region
  1082 //
  1083 static void delete_shared_memory(char* addr, size_t size) {
  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.
  1090   assert(!PerfDisableSharedMem, "shouldn't be here");
  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, mtInternal);
  1097     backing_store_file_name = NULL;
  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 //
  1104 static size_t sharedmem_filesize(int fd, TRAPS) {
  1106   struct stat statbuf;
  1107   int result;
  1109   RESTARTABLE(::fstat(fd, &statbuf), result);
  1110   if (result == OS_ERR) {
  1111     if (PrintMiscellaneous && Verbose) {
  1112       warning("fstat failed: %s\n", strerror(errno));
  1114     THROW_MSG_0(vmSymbols::java_io_IOException(),
  1115                 "Could not determine PerfMemory size");
  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");
  1124   return (size_t)statbuf.st_size;
  1127 // attach to a named shared memory region.
  1128 //
  1129 static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
  1131   char* mapAddress;
  1132   int result;
  1133   int fd;
  1134   size_t size = 0;
  1135   const char* luser = NULL;
  1137   int mmap_prot;
  1138   int file_flags;
  1140   ResourceMark rm;
  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;
  1147   // No O_NOFOLLOW defined at buildtime, and it is not documented for open.
  1148 #ifdef O_NOFOLLOW
  1149     file_flags = O_RDONLY | O_NOFOLLOW;
  1150 #else
  1151     file_flags = O_RDONLY;
  1152 #endif
  1154   else if (mode == PerfMemory::PERF_MODE_RW) {
  1155 #ifdef LATER
  1156     mmap_prot = PROT_READ | PROT_WRITE;
  1157     file_flags = O_RDWR | O_NOFOLLOW;
  1158 #else
  1159     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1160               "Unsupported access mode");
  1161 #endif
  1163   else {
  1164     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1165               "Illegal access mode");
  1168   if (user == NULL || strlen(user) == 0) {
  1169     luser = get_user_name(vmid, CHECK);
  1171   else {
  1172     luser = user;
  1175   if (luser == NULL) {
  1176     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1177               "Could not map vmid to user Name");
  1180   char* dirname = get_user_tmp_dir(luser);
  1182   // since we don't follow symbolic links when creating the backing
  1183   // store file, we don't follow them when attaching either.
  1184   //
  1185   if (!is_directory_secure(dirname)) {
  1186     FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1187     if (luser != user) {
  1188       FREE_C_HEAP_ARRAY(char, luser, mtInternal);
  1190     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1191               "Process not found");
  1194   char* filename = get_sharedmem_filename(dirname, vmid);
  1196   // copy heap memory to resource memory. the open_sharedmem_file
  1197   // method below need to use the filename, but could throw an
  1198   // exception. using a resource array prevents the leak that
  1199   // would otherwise occur.
  1200   char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
  1201   strcpy(rfilename, filename);
  1203   // free the c heap resources that are no longer needed
  1204   if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);
  1205   FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1206   FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1208   // open the shared memory file for the give vmid
  1209   fd = open_sharedmem_file(rfilename, file_flags, CHECK);
  1210   assert(fd != OS_ERR, "unexpected value");
  1212   if (*sizep == 0) {
  1213     size = sharedmem_filesize(fd, CHECK);
  1214     assert(size != 0, "unexpected size");
  1215   } else {
  1216     size = *sizep;
  1219   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
  1221   // attempt to close the file - restart if it gets interrupted,
  1222   // but ignore other failures
  1223   RESTARTABLE(::close(fd), result);
  1224   assert(result != OS_ERR, "could not close file");
  1226   if (mapAddress == MAP_FAILED) {
  1227     if (PrintMiscellaneous && Verbose) {
  1228       warning("mmap failed: %s\n", strerror(errno));
  1230     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
  1231               "Could not map PerfMemory");
  1234   // It does not go through os api, the operation has to record from here.
  1235   MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);
  1237   *addr = mapAddress;
  1238   *sizep = size;
  1240   if (PerfTraceMemOps) {
  1241     tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
  1242                INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);
  1249 // create the PerfData memory region
  1250 //
  1251 // This method creates the memory region used to store performance
  1252 // data for the JVM. The memory may be created in standard or
  1253 // shared memory.
  1254 //
  1255 void PerfMemory::create_memory_region(size_t size) {
  1257   if (PerfDisableSharedMem) {
  1258     // do not share the memory for the performance data.
  1259     _start = create_standard_memory(size);
  1261   else {
  1262     _start = create_shared_memory(size);
  1263     if (_start == NULL) {
  1265       // creation of the shared memory region failed, attempt
  1266       // to create a contiguous, non-shared memory region instead.
  1267       //
  1268       if (PrintMiscellaneous && Verbose) {
  1269         warning("Reverting to non-shared PerfMemory region.\n");
  1271       PerfDisableSharedMem = true;
  1272       _start = create_standard_memory(size);
  1276   if (_start != NULL) _capacity = size;
  1280 // delete the PerfData memory region
  1281 //
  1282 // This method deletes the memory region used to store performance
  1283 // data for the JVM. The memory region indicated by the <address, size>
  1284 // tuple will be inaccessible after a call to this method.
  1285 //
  1286 void PerfMemory::delete_memory_region() {
  1288   assert((start() != NULL && capacity() > 0), "verify proper state");
  1290   // If user specifies PerfDataSaveFile, it will save the performance data
  1291   // to the specified file name no matter whether PerfDataSaveToFile is specified
  1292   // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
  1293   // -XX:+PerfDataSaveToFile.
  1294   if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
  1295     save_memory_to_file(start(), capacity());
  1298   if (PerfDisableSharedMem) {
  1299     delete_standard_memory(start(), capacity());
  1301   else {
  1302     delete_shared_memory(start(), capacity());
  1306 // attach to the PerfData memory region for another JVM
  1307 //
  1308 // This method returns an <address, size> tuple that points to
  1309 // a memory buffer that is kept reasonably synchronized with
  1310 // the PerfData memory region for the indicated JVM. This
  1311 // buffer may be kept in synchronization via shared memory
  1312 // or some other mechanism that keeps the buffer updated.
  1313 //
  1314 // If the JVM chooses not to support the attachability feature,
  1315 // this method should throw an UnsupportedOperation exception.
  1316 //
  1317 // This implementation utilizes named shared memory to map
  1318 // the indicated process's PerfData memory region into this JVMs
  1319 // address space.
  1320 //
  1321 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
  1323   if (vmid == 0 || vmid == os::current_process_id()) {
  1324      *addrp = start();
  1325      *sizep = capacity();
  1326      return;
  1329   mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
  1332 // detach from the PerfData memory region of another JVM
  1333 //
  1334 // This method detaches the PerfData memory region of another
  1335 // JVM, specified as an <address, size> tuple of a buffer
  1336 // in this process's address space. This method may perform
  1337 // arbitrary actions to accomplish the detachment. The memory
  1338 // region specified by <address, size> will be inaccessible after
  1339 // a call to this method.
  1340 //
  1341 // If the JVM chooses not to support the attachability feature,
  1342 // this method should throw an UnsupportedOperation exception.
  1343 //
  1344 // This implementation utilizes named shared memory to detach
  1345 // the indicated process's PerfData memory region from this
  1346 // process's address space.
  1347 //
  1348 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
  1350   assert(addr != 0, "address sanity check");
  1351   assert(bytes > 0, "capacity sanity check");
  1353   if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
  1354     // prevent accidental detachment of this process's PerfMemory region
  1355     return;
  1358   unmap_shared(addr, bytes);
  1361 char* PerfMemory::backing_store_filename() {
  1362   return backing_store_file_name;

mercurial