src/os/aix/vm/perfMemory_aix.cpp

Tue, 17 Nov 2015 09:39:45 -0800

author
clanger
date
Tue, 17 Nov 2015 09:39:45 -0800
changeset 8177
9f8038f83a6e
parent 7515
b9c06f87e476
child 8210
2d23269a45a0
permissions
-rw-r--r--

8130910: hsperfdata file is created in wrong directory and not cleaned up if /tmp/hsperfdata_<username> has wrong permissions
Summary: Add check for fchir() failure and disable shared PerfMemory in that case.
Reviewed-by: dcubed, simonis, gthornbr

     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 static bool is_statbuf_secure(struct stat *statp) {
   205   if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {
   206     // The path represents a link or some non-directory file type,
   207     // which is not what we expected. Declare it insecure.
   208     //
   209     return false;
   210   }
   211   // We have an existing directory, check if the permissions are safe.
   212   if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {
   213     // The directory is open for writing and could be subjected
   214     // to a symlink or a hard link attack. Declare it insecure.
   215     return false;
   216   }
   217   // See if the uid of the directory matches the effective uid of the process.
   218   //
   219   if (statp->st_uid != geteuid()) {
   220     // The directory was not created by this user, declare it insecure.
   221     return false;
   222   }
   223   return true;
   224 }
   227 // Check if the given path is considered a secure directory for
   228 // the backing store files. Returns true if the directory exists
   229 // and is considered a secure location. Returns false if the path
   230 // is a symbolic link or if an error occurred.
   231 static bool is_directory_secure(const char* path) {
   232   struct stat statbuf;
   233   int result = 0;
   235   RESTARTABLE(::lstat(path, &statbuf), result);
   236   if (result == OS_ERR) {
   237     return false;
   238   }
   240   // The path exists, see if it is secure.
   241   return is_statbuf_secure(&statbuf);
   242 }
   244 // (Taken over from Solaris to support the O_NOFOLLOW case on AIX.)
   245 // Check if the given directory file descriptor is considered a secure
   246 // directory for the backing store files. Returns true if the directory
   247 // exists and is considered a secure location. Returns false if the path
   248 // is a symbolic link or if an error occurred.
   249 static bool is_dirfd_secure(int dir_fd) {
   250   struct stat statbuf;
   251   int result = 0;
   253   RESTARTABLE(::fstat(dir_fd, &statbuf), result);
   254   if (result == OS_ERR) {
   255     return false;
   256   }
   258   // The path exists, now check its mode.
   259   return is_statbuf_secure(&statbuf);
   260 }
   263 // Check to make sure fd1 and fd2 are referencing the same file system object.
   264 static bool is_same_fsobject(int fd1, int fd2) {
   265   struct stat statbuf1;
   266   struct stat statbuf2;
   267   int result = 0;
   269   RESTARTABLE(::fstat(fd1, &statbuf1), result);
   270   if (result == OS_ERR) {
   271     return false;
   272   }
   273   RESTARTABLE(::fstat(fd2, &statbuf2), result);
   274   if (result == OS_ERR) {
   275     return false;
   276   }
   278   if ((statbuf1.st_ino == statbuf2.st_ino) &&
   279       (statbuf1.st_dev == statbuf2.st_dev)) {
   280     return true;
   281   } else {
   282     return false;
   283   }
   284 }
   286 // Helper functions for open without O_NOFOLLOW which is not present on AIX 5.3/6.1.
   287 // We use the jdk6 implementation here.
   288 #ifndef O_NOFOLLOW
   289 // The O_NOFOLLOW oflag doesn't exist before solaris 5.10, this is to simulate that behaviour
   290 // was done in jdk 5/6 hotspot by Oracle this way
   291 static int open_o_nofollow_impl(const char* path, int oflag, mode_t mode, bool use_mode) {
   292   struct stat orig_st;
   293   struct stat new_st;
   294   bool create;
   295   int error;
   296   int fd;
   298   create = false;
   300   if (lstat(path, &orig_st) != 0) {
   301     if (errno == ENOENT && (oflag & O_CREAT) != 0) {
   302       // File doesn't exist, but_we want to create it, add O_EXCL flag
   303       // to make sure no-one creates it (or a symlink) before us
   304       // This works as we expect with symlinks, from posix man page:
   305       // 'If O_EXCL  and  O_CREAT  are set, and path names a symbolic
   306       // link, open() shall fail and set errno to [EEXIST]'.
   307       oflag |= O_EXCL;
   308       create = true;
   309     } else {
   310       // File doesn't exist, and we are not creating it.
   311       return OS_ERR;
   312     }
   313   } else {
   314     // Lstat success, check if existing file is a link.
   315     if ((orig_st.st_mode & S_IFMT) == S_IFLNK)  {
   316       // File is a symlink.
   317       errno = ELOOP;
   318       return OS_ERR;
   319     }
   320   }
   322   if (use_mode == true) {
   323     fd = open(path, oflag, mode);
   324   } else {
   325     fd = open(path, oflag);
   326   }
   328   if (fd == OS_ERR) {
   329     return fd;
   330   }
   332   // Can't do inode checks on before/after if we created the file.
   333   if (create == false) {
   334     if (fstat(fd, &new_st) != 0) {
   335       // Keep errno from fstat, in case close also fails.
   336       error = errno;
   337       ::close(fd);
   338       errno = error;
   339       return OS_ERR;
   340     }
   342     if (orig_st.st_dev != new_st.st_dev || orig_st.st_ino != new_st.st_ino) {
   343       // File was tampered with during race window.
   344       ::close(fd);
   345       errno = EEXIST;
   346       if (PrintMiscellaneous && Verbose) {
   347         warning("possible file tampering attempt detected when opening %s", path);
   348       }
   349       return OS_ERR;
   350     }
   351   }
   353   return fd;
   354 }
   356 static int open_o_nofollow(const char* path, int oflag, mode_t mode) {
   357   return open_o_nofollow_impl(path, oflag, mode, true);
   358 }
   360 static int open_o_nofollow(const char* path, int oflag) {
   361   return open_o_nofollow_impl(path, oflag, 0, false);
   362 }
   363 #endif
   365 // Open the directory of the given path and validate it.
   366 // Return a DIR * of the open directory.
   367 static DIR *open_directory_secure(const char* dirname) {
   368   // Open the directory using open() so that it can be verified
   369   // to be secure by calling is_dirfd_secure(), opendir() and then check
   370   // to see if they are the same file system object.  This method does not
   371   // introduce a window of opportunity for the directory to be attacked that
   372   // calling opendir() and is_directory_secure() does.
   373   int result;
   374   DIR *dirp = NULL;
   376   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   377   // so provide a workaround in this case.
   378 #ifdef O_NOFOLLOW
   379   RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);
   380 #else
   381   // workaround (jdk6 coding)
   382   RESTARTABLE(::open_o_nofollow(dirname, O_RDONLY), result);
   383 #endif
   385   if (result == OS_ERR) {
   386     // Directory doesn't exist or is a symlink, so there is nothing to cleanup.
   387     if (PrintMiscellaneous && Verbose) {
   388       if (errno == ELOOP) {
   389         warning("directory %s is a symlink and is not secure\n", dirname);
   390       } else {
   391         warning("could not open directory %s: %s\n", dirname, strerror(errno));
   392       }
   393     }
   394     return dirp;
   395   }
   396   int fd = result;
   398   // Determine if the open directory is secure.
   399   if (!is_dirfd_secure(fd)) {
   400     // The directory is not a secure directory.
   401     os::close(fd);
   402     return dirp;
   403   }
   405   // Open the directory.
   406   dirp = ::opendir(dirname);
   407   if (dirp == NULL) {
   408     // The directory doesn't exist, close fd and return.
   409     os::close(fd);
   410     return dirp;
   411   }
   413   // Check to make sure fd and dirp are referencing the same file system object.
   414   if (!is_same_fsobject(fd, dirp->dd_fd)) {
   415     // The directory is not secure.
   416     os::close(fd);
   417     os::closedir(dirp);
   418     dirp = NULL;
   419     return dirp;
   420   }
   422   // Close initial open now that we know directory is secure
   423   os::close(fd);
   425   return dirp;
   426 }
   428 // NOTE: The code below uses fchdir(), open() and unlink() because
   429 // fdopendir(), openat() and unlinkat() are not supported on all
   430 // versions.  Once the support for fdopendir(), openat() and unlinkat()
   431 // is available on all supported versions the code can be changed
   432 // to use these functions.
   434 // Open the directory of the given path, validate it and set the
   435 // current working directory to it.
   436 // Return a DIR * of the open directory and the saved cwd fd.
   437 //
   438 static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {
   440   // Open the directory.
   441   DIR* dirp = open_directory_secure(dirname);
   442   if (dirp == NULL) {
   443     // Directory doesn't exist or is insecure, so there is nothing to cleanup.
   444     return dirp;
   445   }
   446   int fd = dirp->dd_fd;
   448   // Open a fd to the cwd and save it off.
   449   int result;
   450   RESTARTABLE(::open(".", O_RDONLY), result);
   451   if (result == OS_ERR) {
   452     *saved_cwd_fd = -1;
   453   } else {
   454     *saved_cwd_fd = result;
   455   }
   457   // Set the current directory to dirname by using the fd of the directory and
   458   // handle errors, otherwise shared memory files will be created in cwd.
   459   result = fchdir(fd);
   460   if (result == OS_ERR) {
   461     if (PrintMiscellaneous && Verbose) {
   462       warning("could not change to directory %s", dirname);
   463     }
   464     if (*saved_cwd_fd != -1) {
   465       ::close(*saved_cwd_fd);
   466       *saved_cwd_fd = -1;
   467     }
   468     // Close the directory.
   469     os::closedir(dirp);
   470     return NULL;
   471   } else {
   472     return dirp;
   473   }
   474 }
   476 // Close the directory and restore the current working directory.
   477 //
   478 static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {
   480   int result;
   481   // If we have a saved cwd change back to it and close the fd.
   482   if (saved_cwd_fd != -1) {
   483     result = fchdir(saved_cwd_fd);
   484     ::close(saved_cwd_fd);
   485   }
   487   // Close the directory.
   488   os::closedir(dirp);
   489 }
   491 // Check if the given file descriptor is considered a secure.
   492 static bool is_file_secure(int fd, const char *filename) {
   494   int result;
   495   struct stat statbuf;
   497   // Determine if the file is secure.
   498   RESTARTABLE(::fstat(fd, &statbuf), result);
   499   if (result == OS_ERR) {
   500     if (PrintMiscellaneous && Verbose) {
   501       warning("fstat failed on %s: %s\n", filename, strerror(errno));
   502     }
   503     return false;
   504   }
   505   if (statbuf.st_nlink > 1) {
   506     // A file with multiple links is not expected.
   507     if (PrintMiscellaneous && Verbose) {
   508       warning("file %s has multiple links\n", filename);
   509     }
   510     return false;
   511   }
   512   return true;
   513 }
   515 // Return the user name for the given user id.
   516 //
   517 // The caller is expected to free the allocated memory.
   518 static char* get_user_name(uid_t uid) {
   520   struct passwd pwent;
   522   // Determine the max pwbuf size from sysconf, and hardcode
   523   // a default if this not available through sysconf.
   524   long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
   525   if (bufsize == -1)
   526     bufsize = 1024;
   528   char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
   530   // POSIX interface to getpwuid_r is used on LINUX
   531   struct passwd* p;
   532   int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);
   534   if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {
   535     if (PrintMiscellaneous && Verbose) {
   536       if (result != 0) {
   537         warning("Could not retrieve passwd entry: %s\n",
   538                 strerror(result));
   539       }
   540       else if (p == NULL) {
   541         // this check is added to protect against an observed problem
   542         // with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,
   543         // indicating success, but has p == NULL. This was observed when
   544         // inserting a file descriptor exhaustion fault prior to the call
   545         // getpwuid_r() call. In this case, error is set to the appropriate
   546         // error condition, but this is undocumented behavior. This check
   547         // is safe under any condition, but the use of errno in the output
   548         // message may result in an erroneous message.
   549         // Bug Id 89052 was opened with RedHat.
   550         //
   551         warning("Could not retrieve passwd entry: %s\n",
   552                 strerror(errno));
   553       }
   554       else {
   555         warning("Could not determine user name: %s\n",
   556                 p->pw_name == NULL ? "pw_name = NULL" :
   557                                      "pw_name zero length");
   558       }
   559     }
   560     FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
   561     return NULL;
   562   }
   564   char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);
   565   strcpy(user_name, p->pw_name);
   567   FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
   568   return user_name;
   569 }
   571 // return the name of the user that owns the process identified by vmid.
   572 //
   573 // This method uses a slow directory search algorithm to find the backing
   574 // store file for the specified vmid and returns the user name, as determined
   575 // by the user name suffix of the hsperfdata_<username> directory name.
   576 //
   577 // the caller is expected to free the allocated memory.
   578 //
   579 static char* get_user_name_slow(int vmid, TRAPS) {
   581   // short circuit the directory search if the process doesn't even exist.
   582   if (kill(vmid, 0) == OS_ERR) {
   583     if (errno == ESRCH) {
   584       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   585                   "Process not found");
   586     }
   587     else /* EPERM */ {
   588       THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   589     }
   590   }
   592   // directory search
   593   char* oldest_user = NULL;
   594   time_t oldest_ctime = 0;
   596   const char* tmpdirname = os::get_temp_directory();
   598   DIR* tmpdirp = os::opendir(tmpdirname);
   600   if (tmpdirp == NULL) {
   601     return NULL;
   602   }
   604   // for each entry in the directory that matches the pattern hsperfdata_*,
   605   // open the directory and check if the file for the given vmid exists.
   606   // The file with the expected name and the latest creation date is used
   607   // to determine the user name for the process id.
   608   //
   609   struct dirent* dentry;
   610   char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal);
   611   errno = 0;
   612   while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
   614     // check if the directory entry is a hsperfdata file
   615     if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
   616       continue;
   617     }
   619     char* usrdir_name = NEW_C_HEAP_ARRAY(char,
   620                               strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);
   621     strcpy(usrdir_name, tmpdirname);
   622     strcat(usrdir_name, "/");
   623     strcat(usrdir_name, dentry->d_name);
   625     // Open the user directory.
   626     DIR* subdirp = open_directory_secure(usrdir_name);
   628     if (subdirp == NULL) {
   629       FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   630       continue;
   631     }
   633     // Since we don't create the backing store files in directories
   634     // pointed to by symbolic links, we also don't follow them when
   635     // looking for the files. We check for a symbolic link after the
   636     // call to opendir in order to eliminate a small window where the
   637     // symlink can be exploited.
   638     //
   639     if (!is_directory_secure(usrdir_name)) {
   640       FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   641       os::closedir(subdirp);
   642       continue;
   643     }
   645     struct dirent* udentry;
   646     char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal);
   647     errno = 0;
   648     while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
   650       if (filename_to_pid(udentry->d_name) == vmid) {
   651         struct stat statbuf;
   652         int result;
   654         char* filename = NEW_C_HEAP_ARRAY(char,
   655                             strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
   657         strcpy(filename, usrdir_name);
   658         strcat(filename, "/");
   659         strcat(filename, udentry->d_name);
   661         // don't follow symbolic links for the file
   662         RESTARTABLE(::lstat(filename, &statbuf), result);
   663         if (result == OS_ERR) {
   664            FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   665            continue;
   666         }
   668         // skip over files that are not regular files.
   669         if (!S_ISREG(statbuf.st_mode)) {
   670           FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   671           continue;
   672         }
   674         // compare and save filename with latest creation time
   675         if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
   677           if (statbuf.st_ctime > oldest_ctime) {
   678             char* user = strchr(dentry->d_name, '_') + 1;
   680             if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);
   681             oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
   683             strcpy(oldest_user, user);
   684             oldest_ctime = statbuf.st_ctime;
   685           }
   686         }
   688         FREE_C_HEAP_ARRAY(char, filename, mtInternal);
   689       }
   690     }
   691     os::closedir(subdirp);
   692     FREE_C_HEAP_ARRAY(char, udbuf, mtInternal);
   693     FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
   694   }
   695   os::closedir(tmpdirp);
   696   FREE_C_HEAP_ARRAY(char, tdbuf, mtInternal);
   698   return(oldest_user);
   699 }
   701 // return the name of the user that owns the JVM indicated by the given vmid.
   702 //
   703 static char* get_user_name(int vmid, TRAPS) {
   704   return get_user_name_slow(vmid, CHECK_NULL);
   705 }
   707 // return the file name of the backing store file for the named
   708 // shared memory region for the given user name and vmid.
   709 //
   710 // the caller is expected to free the allocated memory.
   711 //
   712 static char* get_sharedmem_filename(const char* dirname, int vmid) {
   714   // add 2 for the file separator and a null terminator.
   715   size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
   717   char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
   718   snprintf(name, nbytes, "%s/%d", dirname, vmid);
   720   return name;
   721 }
   724 // remove file
   725 //
   726 // this method removes the file specified by the given path
   727 //
   728 static void remove_file(const char* path) {
   730   int result;
   732   // if the file is a directory, the following unlink will fail. since
   733   // we don't expect to find directories in the user temp directory, we
   734   // won't try to handle this situation. even if accidentially or
   735   // maliciously planted, the directory's presence won't hurt anything.
   736   //
   737   RESTARTABLE(::unlink(path), result);
   738   if (PrintMiscellaneous && Verbose && result == OS_ERR) {
   739     if (errno != ENOENT) {
   740       warning("Could not unlink shared memory backing"
   741               " store file %s : %s\n", path, strerror(errno));
   742     }
   743   }
   744 }
   746 // Cleanup stale shared memory resources
   747 //
   748 // This method attempts to remove all stale shared memory files in
   749 // the named user temporary directory. It scans the named directory
   750 // for files matching the pattern ^$[0-9]*$. For each file found, the
   751 // process id is extracted from the file name and a test is run to
   752 // determine if the process is alive. If the process is not alive,
   753 // any stale file resources are removed.
   754 static void cleanup_sharedmem_resources(const char* dirname) {
   756   int saved_cwd_fd;
   757   // Open the directory.
   758   DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
   759   if (dirp == NULL) {
   760      // Directory doesn't exist or is insecure, so there is nothing to cleanup.
   761     return;
   762   }
   764   // For each entry in the directory that matches the expected file
   765   // name pattern, determine if the file resources are stale and if
   766   // so, remove the file resources. Note, instrumented HotSpot processes
   767   // for this user may start and/or terminate during this search and
   768   // remove or create new files in this directory. The behavior of this
   769   // loop under these conditions is dependent upon the implementation of
   770   // opendir/readdir.
   771   struct dirent* entry;
   772   char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
   774   errno = 0;
   775   while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
   777     pid_t pid = filename_to_pid(entry->d_name);
   779     if (pid == 0) {
   781       if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
   783         // Attempt to remove all unexpected files, except "." and "..".
   784         unlink(entry->d_name);
   785       }
   787       errno = 0;
   788       continue;
   789     }
   791     // We now have a file name that converts to a valid integer
   792     // that could represent a process id . if this process id
   793     // matches the current process id or the process is not running,
   794     // then remove the stale file resources.
   795     //
   796     // Process liveness is detected by sending signal number 0 to
   797     // the process id (see kill(2)). if kill determines that the
   798     // process does not exist, then the file resources are removed.
   799     // if kill determines that that we don't have permission to
   800     // signal the process, then the file resources are assumed to
   801     // be stale and are removed because the resources for such a
   802     // process should be in a different user specific directory.
   803     if ((pid == os::current_process_id()) ||
   804         (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
   806         unlink(entry->d_name);
   807     }
   808     errno = 0;
   809   }
   811   // Close the directory and reset the current working directory.
   812   close_directory_secure_cwd(dirp, saved_cwd_fd);
   814   FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
   815 }
   817 // Make the user specific temporary directory. Returns true if
   818 // the directory exists and is secure upon return. Returns false
   819 // if the directory exists but is either a symlink, is otherwise
   820 // insecure, or if an error occurred.
   821 static bool make_user_tmp_dir(const char* dirname) {
   823   // Create the directory with 0755 permissions. note that the directory
   824   // will be owned by euid::egid, which may not be the same as uid::gid.
   825   if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
   826     if (errno == EEXIST) {
   827       // The directory already exists and was probably created by another
   828       // JVM instance. However, this could also be the result of a
   829       // deliberate symlink. Verify that the existing directory is safe.
   830       if (!is_directory_secure(dirname)) {
   831         // Directory is not secure.
   832         if (PrintMiscellaneous && Verbose) {
   833           warning("%s directory is insecure\n", dirname);
   834         }
   835         return false;
   836       }
   837     }
   838     else {
   839       // we encountered some other failure while attempting
   840       // to create the directory
   841       //
   842       if (PrintMiscellaneous && Verbose) {
   843         warning("could not create directory %s: %s\n",
   844                 dirname, strerror(errno));
   845       }
   846       return false;
   847     }
   848   }
   849   return true;
   850 }
   852 // create the shared memory file resources
   853 //
   854 // This method creates the shared memory file with the given size
   855 // This method also creates the user specific temporary directory, if
   856 // it does not yet exist.
   857 //
   858 static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
   860   // make the user temporary directory
   861   if (!make_user_tmp_dir(dirname)) {
   862     // could not make/find the directory or the found directory
   863     // was not secure
   864     return -1;
   865   }
   867   int saved_cwd_fd;
   868   // Open the directory and set the current working directory to it.
   869   DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
   870   if (dirp == NULL) {
   871     // Directory doesn't exist or is insecure, so cannot create shared
   872     // memory file.
   873     return -1;
   874   }
   876   // Open the filename in the current directory.
   877   // Cannot use O_TRUNC here; truncation of an existing file has to happen
   878   // after the is_file_secure() check below.
   879   int result;
   881   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   882   // so provide a workaround in this case.
   883 #ifdef O_NOFOLLOW
   884   RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IREAD|S_IWRITE), result);
   885 #else
   886   // workaround function (jdk6 code)
   887   RESTARTABLE(::open_o_nofollow(filename, O_RDWR|O_CREAT, S_IREAD|S_IWRITE), result);
   888 #endif
   890   if (result == OS_ERR) {
   891     if (PrintMiscellaneous && Verbose) {
   892       if (errno == ELOOP) {
   893         warning("file %s is a symlink and is not secure\n", filename);
   894       } else {
   895         warning("could not create file %s: %s\n", filename, strerror(errno));
   896       }
   897     }
   898     // Close the directory and reset the current working directory.
   899     close_directory_secure_cwd(dirp, saved_cwd_fd);
   901     return -1;
   902   }
   903   // Close the directory and reset the current working directory.
   904   close_directory_secure_cwd(dirp, saved_cwd_fd);
   906   // save the file descriptor
   907   int fd = result;
   909   // Check to see if the file is secure.
   910   if (!is_file_secure(fd, filename)) {
   911     ::close(fd);
   912     return -1;
   913   }
   915   // Truncate the file to get rid of any existing data.
   916   RESTARTABLE(::ftruncate(fd, (off_t)0), result);
   917   if (result == OS_ERR) {
   918     if (PrintMiscellaneous && Verbose) {
   919       warning("could not truncate shared memory file: %s\n", strerror(errno));
   920     }
   921     ::close(fd);
   922     return -1;
   923   }
   924   // set the file size
   925   RESTARTABLE(::ftruncate(fd, (off_t)size), result);
   926   if (result == OS_ERR) {
   927     if (PrintMiscellaneous && Verbose) {
   928       warning("could not set shared memory file size: %s\n", strerror(errno));
   929     }
   930     RESTARTABLE(::close(fd), result);
   931     return -1;
   932   }
   934   return fd;
   935 }
   937 // open the shared memory file for the given user and vmid. returns
   938 // the file descriptor for the open file or -1 if the file could not
   939 // be opened.
   940 //
   941 static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
   943   // open the file
   944   int result;
   945   // No O_NOFOLLOW defined at buildtime, and it is not documented for open;
   946   // so provide a workaround in this case
   947 #ifdef O_NOFOLLOW
   948   RESTARTABLE(::open(filename, oflags), result);
   949 #else
   950   RESTARTABLE(::open_o_nofollow(filename, oflags), result);
   951 #endif
   953   if (result == OS_ERR) {
   954     if (errno == ENOENT) {
   955       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   956                   "Process not found");
   957     }
   958     else if (errno == EACCES) {
   959       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   960                   "Permission denied");
   961     }
   962     else {
   963       THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   964     }
   965   }
   966   int fd = result;
   968   // Check to see if the file is secure.
   969   if (!is_file_secure(fd, filename)) {
   970     ::close(fd);
   971     return -1;
   972   }
   974   return fd;
   975 }
   977 // create a named shared memory region. returns the address of the
   978 // memory region on success or NULL on failure. A return value of
   979 // NULL will ultimately disable the shared memory feature.
   980 //
   981 // On Solaris and Linux, the name space for shared memory objects
   982 // is the file system name space.
   983 //
   984 // A monitoring application attaching to a JVM does not need to know
   985 // the file system name of the shared memory object. However, it may
   986 // be convenient for applications to discover the existence of newly
   987 // created and terminating JVMs by watching the file system name space
   988 // for files being created or removed.
   989 //
   990 static char* mmap_create_shared(size_t size) {
   992   int result;
   993   int fd;
   994   char* mapAddress;
   996   int vmid = os::current_process_id();
   998   char* user_name = get_user_name(geteuid());
  1000   if (user_name == NULL)
  1001     return NULL;
  1003   char* dirname = get_user_tmp_dir(user_name);
  1004   char* filename = get_sharedmem_filename(dirname, vmid);
  1006   // Get the short filename.
  1007   char* short_filename = strrchr(filename, '/');
  1008   if (short_filename == NULL) {
  1009     short_filename = filename;
  1010   } else {
  1011     short_filename++;
  1014   // cleanup any stale shared memory files
  1015   cleanup_sharedmem_resources(dirname);
  1017   assert(((size > 0) && (size % os::vm_page_size() == 0)),
  1018          "unexpected PerfMemory region size");
  1020   fd = create_sharedmem_resources(dirname, short_filename, size);
  1022   FREE_C_HEAP_ARRAY(char, user_name, mtInternal);
  1023   FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1025   if (fd == -1) {
  1026     FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1027     return NULL;
  1030   mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  1032   // attempt to close the file - restart it if it was interrupted,
  1033   // but ignore other failures
  1034   RESTARTABLE(::close(fd), result);
  1035   assert(result != OS_ERR, "could not close file");
  1037   if (mapAddress == MAP_FAILED) {
  1038     if (PrintMiscellaneous && Verbose) {
  1039       warning("mmap failed -  %s\n", strerror(errno));
  1041     remove_file(filename);
  1042     FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1043     return NULL;
  1046   // save the file name for use in delete_shared_memory()
  1047   backing_store_file_name = filename;
  1049   // clear the shared memory region
  1050   (void)::memset((void*) mapAddress, 0, size);
  1052   // It does not go through os api, the operation has to record from here.
  1053   MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);
  1055   return mapAddress;
  1058 // release a named shared memory region
  1059 //
  1060 static void unmap_shared(char* addr, size_t bytes) {
  1061   // Do not rely on os::reserve_memory/os::release_memory to use mmap.
  1062   // Use os::reserve_memory/os::release_memory for PerfDisableSharedMem=1, mmap/munmap for PerfDisableSharedMem=0
  1063   if (::munmap(addr, bytes) == -1) {
  1064     warning("perfmemory: munmap failed (%d)\n", errno);
  1068 // create the PerfData memory region in shared memory.
  1069 //
  1070 static char* create_shared_memory(size_t size) {
  1072   // create the shared memory region.
  1073   return mmap_create_shared(size);
  1076 // delete the shared PerfData memory region
  1077 //
  1078 static void delete_shared_memory(char* addr, size_t size) {
  1080   // cleanup the persistent shared memory resources. since DestroyJavaVM does
  1081   // not support unloading of the JVM, unmapping of the memory resource is
  1082   // not performed. The memory will be reclaimed by the OS upon termination of
  1083   // the process. The backing store file is deleted from the file system.
  1085   assert(!PerfDisableSharedMem, "shouldn't be here");
  1087   if (backing_store_file_name != NULL) {
  1088     remove_file(backing_store_file_name);
  1089     // Don't.. Free heap memory could deadlock os::abort() if it is called
  1090     // from signal handler. OS will reclaim the heap memory.
  1091     // FREE_C_HEAP_ARRAY(char, backing_store_file_name, mtInternal);
  1092     backing_store_file_name = NULL;
  1096 // return the size of the file for the given file descriptor
  1097 // or 0 if it is not a valid size for a shared memory file
  1098 //
  1099 static size_t sharedmem_filesize(int fd, TRAPS) {
  1101   struct stat statbuf;
  1102   int result;
  1104   RESTARTABLE(::fstat(fd, &statbuf), result);
  1105   if (result == OS_ERR) {
  1106     if (PrintMiscellaneous && Verbose) {
  1107       warning("fstat failed: %s\n", strerror(errno));
  1109     THROW_MSG_0(vmSymbols::java_io_IOException(),
  1110                 "Could not determine PerfMemory size");
  1113   if ((statbuf.st_size == 0) ||
  1114      ((size_t)statbuf.st_size % os::vm_page_size() != 0)) {
  1115     THROW_MSG_0(vmSymbols::java_lang_Exception(),
  1116                 "Invalid PerfMemory size");
  1119   return (size_t)statbuf.st_size;
  1122 // attach to a named shared memory region.
  1123 //
  1124 static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
  1126   char* mapAddress;
  1127   int result;
  1128   int fd;
  1129   size_t size = 0;
  1130   const char* luser = NULL;
  1132   int mmap_prot;
  1133   int file_flags;
  1135   ResourceMark rm;
  1137   // map the high level access mode to the appropriate permission
  1138   // constructs for the file and the shared memory mapping.
  1139   if (mode == PerfMemory::PERF_MODE_RO) {
  1140     mmap_prot = PROT_READ;
  1142   // No O_NOFOLLOW defined at buildtime, and it is not documented for open.
  1143 #ifdef O_NOFOLLOW
  1144     file_flags = O_RDONLY | O_NOFOLLOW;
  1145 #else
  1146     file_flags = O_RDONLY;
  1147 #endif
  1149   else if (mode == PerfMemory::PERF_MODE_RW) {
  1150 #ifdef LATER
  1151     mmap_prot = PROT_READ | PROT_WRITE;
  1152     file_flags = O_RDWR | O_NOFOLLOW;
  1153 #else
  1154     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1155               "Unsupported access mode");
  1156 #endif
  1158   else {
  1159     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1160               "Illegal access mode");
  1163   if (user == NULL || strlen(user) == 0) {
  1164     luser = get_user_name(vmid, CHECK);
  1166   else {
  1167     luser = user;
  1170   if (luser == NULL) {
  1171     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1172               "Could not map vmid to user Name");
  1175   char* dirname = get_user_tmp_dir(luser);
  1177   // since we don't follow symbolic links when creating the backing
  1178   // store file, we don't follow them when attaching either.
  1179   //
  1180   if (!is_directory_secure(dirname)) {
  1181     FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1182     if (luser != user) {
  1183       FREE_C_HEAP_ARRAY(char, luser, mtInternal);
  1185     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
  1186               "Process not found");
  1189   char* filename = get_sharedmem_filename(dirname, vmid);
  1191   // copy heap memory to resource memory. the open_sharedmem_file
  1192   // method below need to use the filename, but could throw an
  1193   // exception. using a resource array prevents the leak that
  1194   // would otherwise occur.
  1195   char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
  1196   strcpy(rfilename, filename);
  1198   // free the c heap resources that are no longer needed
  1199   if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);
  1200   FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
  1201   FREE_C_HEAP_ARRAY(char, filename, mtInternal);
  1203   // open the shared memory file for the give vmid
  1204   fd = open_sharedmem_file(rfilename, file_flags, CHECK);
  1205   assert(fd != OS_ERR, "unexpected value");
  1207   if (*sizep == 0) {
  1208     size = sharedmem_filesize(fd, CHECK);
  1209     assert(size != 0, "unexpected size");
  1210   } else {
  1211     size = *sizep;
  1214   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
  1216   // attempt to close the file - restart if it gets interrupted,
  1217   // but ignore other failures
  1218   RESTARTABLE(::close(fd), result);
  1219   assert(result != OS_ERR, "could not close file");
  1221   if (mapAddress == MAP_FAILED) {
  1222     if (PrintMiscellaneous && Verbose) {
  1223       warning("mmap failed: %s\n", strerror(errno));
  1225     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
  1226               "Could not map PerfMemory");
  1229   // It does not go through os api, the operation has to record from here.
  1230   MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC, mtInternal);
  1232   *addr = mapAddress;
  1233   *sizep = size;
  1235   if (PerfTraceMemOps) {
  1236     tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
  1237                INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);
  1244 // create the PerfData memory region
  1245 //
  1246 // This method creates the memory region used to store performance
  1247 // data for the JVM. The memory may be created in standard or
  1248 // shared memory.
  1249 //
  1250 void PerfMemory::create_memory_region(size_t size) {
  1252   if (PerfDisableSharedMem) {
  1253     // do not share the memory for the performance data.
  1254     _start = create_standard_memory(size);
  1256   else {
  1257     _start = create_shared_memory(size);
  1258     if (_start == NULL) {
  1260       // creation of the shared memory region failed, attempt
  1261       // to create a contiguous, non-shared memory region instead.
  1262       //
  1263       if (PrintMiscellaneous && Verbose) {
  1264         warning("Reverting to non-shared PerfMemory region.\n");
  1266       PerfDisableSharedMem = true;
  1267       _start = create_standard_memory(size);
  1271   if (_start != NULL) _capacity = size;
  1275 // delete the PerfData memory region
  1276 //
  1277 // This method deletes the memory region used to store performance
  1278 // data for the JVM. The memory region indicated by the <address, size>
  1279 // tuple will be inaccessible after a call to this method.
  1280 //
  1281 void PerfMemory::delete_memory_region() {
  1283   assert((start() != NULL && capacity() > 0), "verify proper state");
  1285   // If user specifies PerfDataSaveFile, it will save the performance data
  1286   // to the specified file name no matter whether PerfDataSaveToFile is specified
  1287   // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
  1288   // -XX:+PerfDataSaveToFile.
  1289   if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
  1290     save_memory_to_file(start(), capacity());
  1293   if (PerfDisableSharedMem) {
  1294     delete_standard_memory(start(), capacity());
  1296   else {
  1297     delete_shared_memory(start(), capacity());
  1301 // attach to the PerfData memory region for another JVM
  1302 //
  1303 // This method returns an <address, size> tuple that points to
  1304 // a memory buffer that is kept reasonably synchronized with
  1305 // the PerfData memory region for the indicated JVM. This
  1306 // buffer may be kept in synchronization via shared memory
  1307 // or some other mechanism that keeps the buffer updated.
  1308 //
  1309 // If the JVM chooses not to support the attachability feature,
  1310 // this method should throw an UnsupportedOperation exception.
  1311 //
  1312 // This implementation utilizes named shared memory to map
  1313 // the indicated process's PerfData memory region into this JVMs
  1314 // address space.
  1315 //
  1316 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
  1318   if (vmid == 0 || vmid == os::current_process_id()) {
  1319      *addrp = start();
  1320      *sizep = capacity();
  1321      return;
  1324   mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
  1327 // detach from the PerfData memory region of another JVM
  1328 //
  1329 // This method detaches the PerfData memory region of another
  1330 // JVM, specified as an <address, size> tuple of a buffer
  1331 // in this process's address space. This method may perform
  1332 // arbitrary actions to accomplish the detachment. The memory
  1333 // region specified by <address, size> will be inaccessible after
  1334 // a call to this method.
  1335 //
  1336 // If the JVM chooses not to support the attachability feature,
  1337 // this method should throw an UnsupportedOperation exception.
  1338 //
  1339 // This implementation utilizes named shared memory to detach
  1340 // the indicated process's PerfData memory region from this
  1341 // process's address space.
  1342 //
  1343 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
  1345   assert(addr != 0, "address sanity check");
  1346   assert(bytes > 0, "capacity sanity check");
  1348   if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
  1349     // prevent accidental detachment of this process's PerfMemory region
  1350     return;
  1353   unmap_shared(addr, bytes);
  1356 char* PerfMemory::backing_store_filename() {
  1357   return backing_store_file_name;

mercurial