src/os/bsd/vm/perfMemory_bsd.cpp

changeset 3156
f08d439fab8c
child 3900
d2a62e0f25eb
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/os/bsd/vm/perfMemory_bsd.cpp	Sun Sep 25 16:03:29 2011 -0700
     1.3 @@ -0,0 +1,1041 @@
     1.4 +/*
     1.5 + * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.
    1.11 + *
    1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.15 + * version 2 for more details (a copy is included in the LICENSE file that
    1.16 + * accompanied this code).
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License version
    1.19 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.21 + *
    1.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.23 + * or visit www.oracle.com if you need additional information or have any
    1.24 + * questions.
    1.25 + *
    1.26 + */
    1.27 +
    1.28 +#include "precompiled.hpp"
    1.29 +#include "classfile/vmSymbols.hpp"
    1.30 +#include "memory/allocation.inline.hpp"
    1.31 +#include "memory/resourceArea.hpp"
    1.32 +#include "oops/oop.inline.hpp"
    1.33 +#include "os_bsd.inline.hpp"
    1.34 +#include "runtime/handles.inline.hpp"
    1.35 +#include "runtime/perfMemory.hpp"
    1.36 +#include "utilities/exceptions.hpp"
    1.37 +
    1.38 +// put OS-includes here
    1.39 +# include <sys/types.h>
    1.40 +# include <sys/mman.h>
    1.41 +# include <errno.h>
    1.42 +# include <stdio.h>
    1.43 +# include <unistd.h>
    1.44 +# include <sys/stat.h>
    1.45 +# include <signal.h>
    1.46 +# include <pwd.h>
    1.47 +
    1.48 +static char* backing_store_file_name = NULL;  // name of the backing store
    1.49 +                                              // file, if successfully created.
    1.50 +
    1.51 +// Standard Memory Implementation Details
    1.52 +
    1.53 +// create the PerfData memory region in standard memory.
    1.54 +//
    1.55 +static char* create_standard_memory(size_t size) {
    1.56 +
    1.57 +  // allocate an aligned chuck of memory
    1.58 +  char* mapAddress = os::reserve_memory(size);
    1.59 +
    1.60 +  if (mapAddress == NULL) {
    1.61 +    return NULL;
    1.62 +  }
    1.63 +
    1.64 +  // commit memory
    1.65 +  if (!os::commit_memory(mapAddress, size)) {
    1.66 +    if (PrintMiscellaneous && Verbose) {
    1.67 +      warning("Could not commit PerfData memory\n");
    1.68 +    }
    1.69 +    os::release_memory(mapAddress, size);
    1.70 +    return NULL;
    1.71 +  }
    1.72 +
    1.73 +  return mapAddress;
    1.74 +}
    1.75 +
    1.76 +// delete the PerfData memory region
    1.77 +//
    1.78 +static void delete_standard_memory(char* addr, size_t size) {
    1.79 +
    1.80 +  // there are no persistent external resources to cleanup for standard
    1.81 +  // memory. since DestroyJavaVM does not support unloading of the JVM,
    1.82 +  // cleanup of the memory resource is not performed. The memory will be
    1.83 +  // reclaimed by the OS upon termination of the process.
    1.84 +  //
    1.85 +  return;
    1.86 +}
    1.87 +
    1.88 +// save the specified memory region to the given file
    1.89 +//
    1.90 +// Note: this function might be called from signal handler (by os::abort()),
    1.91 +// don't allocate heap memory.
    1.92 +//
    1.93 +static void save_memory_to_file(char* addr, size_t size) {
    1.94 +
    1.95 + const char* destfile = PerfMemory::get_perfdata_file_path();
    1.96 + assert(destfile[0] != '\0', "invalid PerfData file path");
    1.97 +
    1.98 +  int result;
    1.99 +
   1.100 +  RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),
   1.101 +              result);;
   1.102 +  if (result == OS_ERR) {
   1.103 +    if (PrintMiscellaneous && Verbose) {
   1.104 +      warning("Could not create Perfdata save file: %s: %s\n",
   1.105 +              destfile, strerror(errno));
   1.106 +    }
   1.107 +  } else {
   1.108 +    int fd = result;
   1.109 +
   1.110 +    for (size_t remaining = size; remaining > 0;) {
   1.111 +
   1.112 +      RESTARTABLE(::write(fd, addr, remaining), result);
   1.113 +      if (result == OS_ERR) {
   1.114 +        if (PrintMiscellaneous && Verbose) {
   1.115 +          warning("Could not write Perfdata save file: %s: %s\n",
   1.116 +                  destfile, strerror(errno));
   1.117 +        }
   1.118 +        break;
   1.119 +      }
   1.120 +
   1.121 +      remaining -= (size_t)result;
   1.122 +      addr += result;
   1.123 +    }
   1.124 +
   1.125 +    RESTARTABLE(::close(fd), result);
   1.126 +    if (PrintMiscellaneous && Verbose) {
   1.127 +      if (result == OS_ERR) {
   1.128 +        warning("Could not close %s: %s\n", destfile, strerror(errno));
   1.129 +      }
   1.130 +    }
   1.131 +  }
   1.132 +  FREE_C_HEAP_ARRAY(char, destfile);
   1.133 +}
   1.134 +
   1.135 +
   1.136 +// Shared Memory Implementation Details
   1.137 +
   1.138 +// Note: the solaris and bsd shared memory implementation uses the mmap
   1.139 +// interface with a backing store file to implement named shared memory.
   1.140 +// Using the file system as the name space for shared memory allows a
   1.141 +// common name space to be supported across a variety of platforms. It
   1.142 +// also provides a name space that Java applications can deal with through
   1.143 +// simple file apis.
   1.144 +//
   1.145 +// The solaris and bsd implementations store the backing store file in
   1.146 +// a user specific temporary directory located in the /tmp file system,
   1.147 +// which is always a local file system and is sometimes a RAM based file
   1.148 +// system.
   1.149 +
   1.150 +// return the user specific temporary directory name.
   1.151 +//
   1.152 +// the caller is expected to free the allocated memory.
   1.153 +//
   1.154 +static char* get_user_tmp_dir(const char* user) {
   1.155 +
   1.156 +  const char* tmpdir = os::get_temp_directory();
   1.157 +  const char* perfdir = PERFDATA_NAME;
   1.158 +  size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;
   1.159 +  char* dirname = NEW_C_HEAP_ARRAY(char, nbytes);
   1.160 +
   1.161 +  // construct the path name to user specific tmp directory
   1.162 +  snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);
   1.163 +
   1.164 +  return dirname;
   1.165 +}
   1.166 +
   1.167 +// convert the given file name into a process id. if the file
   1.168 +// does not meet the file naming constraints, return 0.
   1.169 +//
   1.170 +static pid_t filename_to_pid(const char* filename) {
   1.171 +
   1.172 +  // a filename that doesn't begin with a digit is not a
   1.173 +  // candidate for conversion.
   1.174 +  //
   1.175 +  if (!isdigit(*filename)) {
   1.176 +    return 0;
   1.177 +  }
   1.178 +
   1.179 +  // check if file name can be converted to an integer without
   1.180 +  // any leftover characters.
   1.181 +  //
   1.182 +  char* remainder = NULL;
   1.183 +  errno = 0;
   1.184 +  pid_t pid = (pid_t)strtol(filename, &remainder, 10);
   1.185 +
   1.186 +  if (errno != 0) {
   1.187 +    return 0;
   1.188 +  }
   1.189 +
   1.190 +  // check for left over characters. If any, then the filename is
   1.191 +  // not a candidate for conversion.
   1.192 +  //
   1.193 +  if (remainder != NULL && *remainder != '\0') {
   1.194 +    return 0;
   1.195 +  }
   1.196 +
   1.197 +  // successful conversion, return the pid
   1.198 +  return pid;
   1.199 +}
   1.200 +
   1.201 +
   1.202 +// check if the given path is considered a secure directory for
   1.203 +// the backing store files. Returns true if the directory exists
   1.204 +// and is considered a secure location. Returns false if the path
   1.205 +// is a symbolic link or if an error occurred.
   1.206 +//
   1.207 +static bool is_directory_secure(const char* path) {
   1.208 +  struct stat statbuf;
   1.209 +  int result = 0;
   1.210 +
   1.211 +  RESTARTABLE(::lstat(path, &statbuf), result);
   1.212 +  if (result == OS_ERR) {
   1.213 +    return false;
   1.214 +  }
   1.215 +
   1.216 +  // the path exists, now check it's mode
   1.217 +  if (S_ISLNK(statbuf.st_mode) || !S_ISDIR(statbuf.st_mode)) {
   1.218 +    // the path represents a link or some non-directory file type,
   1.219 +    // which is not what we expected. declare it insecure.
   1.220 +    //
   1.221 +    return false;
   1.222 +  }
   1.223 +  else {
   1.224 +    // we have an existing directory, check if the permissions are safe.
   1.225 +    //
   1.226 +    if ((statbuf.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
   1.227 +      // the directory is open for writing and could be subjected
   1.228 +      // to a symlnk attack. declare it insecure.
   1.229 +      //
   1.230 +      return false;
   1.231 +    }
   1.232 +  }
   1.233 +  return true;
   1.234 +}
   1.235 +
   1.236 +
   1.237 +// return the user name for the given user id
   1.238 +//
   1.239 +// the caller is expected to free the allocated memory.
   1.240 +//
   1.241 +static char* get_user_name(uid_t uid) {
   1.242 +
   1.243 +  struct passwd pwent;
   1.244 +
   1.245 +  // determine the max pwbuf size from sysconf, and hardcode
   1.246 +  // a default if this not available through sysconf.
   1.247 +  //
   1.248 +  long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
   1.249 +  if (bufsize == -1)
   1.250 +    bufsize = 1024;
   1.251 +
   1.252 +  char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize);
   1.253 +
   1.254 +  // POSIX interface to getpwuid_r is used on LINUX
   1.255 +  struct passwd* p;
   1.256 +  int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);
   1.257 +
   1.258 +  if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {
   1.259 +    if (PrintMiscellaneous && Verbose) {
   1.260 +      if (result != 0) {
   1.261 +        warning("Could not retrieve passwd entry: %s\n",
   1.262 +                strerror(result));
   1.263 +      }
   1.264 +      else if (p == NULL) {
   1.265 +        // this check is added to protect against an observed problem
   1.266 +        // with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,
   1.267 +        // indicating success, but has p == NULL. This was observed when
   1.268 +        // inserting a file descriptor exhaustion fault prior to the call
   1.269 +        // getpwuid_r() call. In this case, error is set to the appropriate
   1.270 +        // error condition, but this is undocumented behavior. This check
   1.271 +        // is safe under any condition, but the use of errno in the output
   1.272 +        // message may result in an erroneous message.
   1.273 +        // Bug Id 89052 was opened with RedHat.
   1.274 +        //
   1.275 +        warning("Could not retrieve passwd entry: %s\n",
   1.276 +                strerror(errno));
   1.277 +      }
   1.278 +      else {
   1.279 +        warning("Could not determine user name: %s\n",
   1.280 +                p->pw_name == NULL ? "pw_name = NULL" :
   1.281 +                                     "pw_name zero length");
   1.282 +      }
   1.283 +    }
   1.284 +    FREE_C_HEAP_ARRAY(char, pwbuf);
   1.285 +    return NULL;
   1.286 +  }
   1.287 +
   1.288 +  char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1);
   1.289 +  strcpy(user_name, p->pw_name);
   1.290 +
   1.291 +  FREE_C_HEAP_ARRAY(char, pwbuf);
   1.292 +  return user_name;
   1.293 +}
   1.294 +
   1.295 +// return the name of the user that owns the process identified by vmid.
   1.296 +//
   1.297 +// This method uses a slow directory search algorithm to find the backing
   1.298 +// store file for the specified vmid and returns the user name, as determined
   1.299 +// by the user name suffix of the hsperfdata_<username> directory name.
   1.300 +//
   1.301 +// the caller is expected to free the allocated memory.
   1.302 +//
   1.303 +static char* get_user_name_slow(int vmid, TRAPS) {
   1.304 +
   1.305 +  // short circuit the directory search if the process doesn't even exist.
   1.306 +  if (kill(vmid, 0) == OS_ERR) {
   1.307 +    if (errno == ESRCH) {
   1.308 +      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   1.309 +                  "Process not found");
   1.310 +    }
   1.311 +    else /* EPERM */ {
   1.312 +      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   1.313 +    }
   1.314 +  }
   1.315 +
   1.316 +  // directory search
   1.317 +  char* oldest_user = NULL;
   1.318 +  time_t oldest_ctime = 0;
   1.319 +
   1.320 +  const char* tmpdirname = os::get_temp_directory();
   1.321 +
   1.322 +  DIR* tmpdirp = os::opendir(tmpdirname);
   1.323 +
   1.324 +  if (tmpdirp == NULL) {
   1.325 +    return NULL;
   1.326 +  }
   1.327 +
   1.328 +  // for each entry in the directory that matches the pattern hsperfdata_*,
   1.329 +  // open the directory and check if the file for the given vmid exists.
   1.330 +  // The file with the expected name and the latest creation date is used
   1.331 +  // to determine the user name for the process id.
   1.332 +  //
   1.333 +  struct dirent* dentry;
   1.334 +  char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname));
   1.335 +  errno = 0;
   1.336 +  while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
   1.337 +
   1.338 +    // check if the directory entry is a hsperfdata file
   1.339 +    if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
   1.340 +      continue;
   1.341 +    }
   1.342 +
   1.343 +    char* usrdir_name = NEW_C_HEAP_ARRAY(char,
   1.344 +                              strlen(tmpdirname) + strlen(dentry->d_name) + 2);
   1.345 +    strcpy(usrdir_name, tmpdirname);
   1.346 +    strcat(usrdir_name, "/");
   1.347 +    strcat(usrdir_name, dentry->d_name);
   1.348 +
   1.349 +    DIR* subdirp = os::opendir(usrdir_name);
   1.350 +
   1.351 +    if (subdirp == NULL) {
   1.352 +      FREE_C_HEAP_ARRAY(char, usrdir_name);
   1.353 +      continue;
   1.354 +    }
   1.355 +
   1.356 +    // Since we don't create the backing store files in directories
   1.357 +    // pointed to by symbolic links, we also don't follow them when
   1.358 +    // looking for the files. We check for a symbolic link after the
   1.359 +    // call to opendir in order to eliminate a small window where the
   1.360 +    // symlink can be exploited.
   1.361 +    //
   1.362 +    if (!is_directory_secure(usrdir_name)) {
   1.363 +      FREE_C_HEAP_ARRAY(char, usrdir_name);
   1.364 +      os::closedir(subdirp);
   1.365 +      continue;
   1.366 +    }
   1.367 +
   1.368 +    struct dirent* udentry;
   1.369 +    char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name));
   1.370 +    errno = 0;
   1.371 +    while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
   1.372 +
   1.373 +      if (filename_to_pid(udentry->d_name) == vmid) {
   1.374 +        struct stat statbuf;
   1.375 +        int result;
   1.376 +
   1.377 +        char* filename = NEW_C_HEAP_ARRAY(char,
   1.378 +                            strlen(usrdir_name) + strlen(udentry->d_name) + 2);
   1.379 +
   1.380 +        strcpy(filename, usrdir_name);
   1.381 +        strcat(filename, "/");
   1.382 +        strcat(filename, udentry->d_name);
   1.383 +
   1.384 +        // don't follow symbolic links for the file
   1.385 +        RESTARTABLE(::lstat(filename, &statbuf), result);
   1.386 +        if (result == OS_ERR) {
   1.387 +           FREE_C_HEAP_ARRAY(char, filename);
   1.388 +           continue;
   1.389 +        }
   1.390 +
   1.391 +        // skip over files that are not regular files.
   1.392 +        if (!S_ISREG(statbuf.st_mode)) {
   1.393 +          FREE_C_HEAP_ARRAY(char, filename);
   1.394 +          continue;
   1.395 +        }
   1.396 +
   1.397 +        // compare and save filename with latest creation time
   1.398 +        if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
   1.399 +
   1.400 +          if (statbuf.st_ctime > oldest_ctime) {
   1.401 +            char* user = strchr(dentry->d_name, '_') + 1;
   1.402 +
   1.403 +            if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user);
   1.404 +            oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1);
   1.405 +
   1.406 +            strcpy(oldest_user, user);
   1.407 +            oldest_ctime = statbuf.st_ctime;
   1.408 +          }
   1.409 +        }
   1.410 +
   1.411 +        FREE_C_HEAP_ARRAY(char, filename);
   1.412 +      }
   1.413 +    }
   1.414 +    os::closedir(subdirp);
   1.415 +    FREE_C_HEAP_ARRAY(char, udbuf);
   1.416 +    FREE_C_HEAP_ARRAY(char, usrdir_name);
   1.417 +  }
   1.418 +  os::closedir(tmpdirp);
   1.419 +  FREE_C_HEAP_ARRAY(char, tdbuf);
   1.420 +
   1.421 +  return(oldest_user);
   1.422 +}
   1.423 +
   1.424 +// return the name of the user that owns the JVM indicated by the given vmid.
   1.425 +//
   1.426 +static char* get_user_name(int vmid, TRAPS) {
   1.427 +  return get_user_name_slow(vmid, CHECK_NULL);
   1.428 +}
   1.429 +
   1.430 +// return the file name of the backing store file for the named
   1.431 +// shared memory region for the given user name and vmid.
   1.432 +//
   1.433 +// the caller is expected to free the allocated memory.
   1.434 +//
   1.435 +static char* get_sharedmem_filename(const char* dirname, int vmid) {
   1.436 +
   1.437 +  // add 2 for the file separator and a null terminator.
   1.438 +  size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
   1.439 +
   1.440 +  char* name = NEW_C_HEAP_ARRAY(char, nbytes);
   1.441 +  snprintf(name, nbytes, "%s/%d", dirname, vmid);
   1.442 +
   1.443 +  return name;
   1.444 +}
   1.445 +
   1.446 +
   1.447 +// remove file
   1.448 +//
   1.449 +// this method removes the file specified by the given path
   1.450 +//
   1.451 +static void remove_file(const char* path) {
   1.452 +
   1.453 +  int result;
   1.454 +
   1.455 +  // if the file is a directory, the following unlink will fail. since
   1.456 +  // we don't expect to find directories in the user temp directory, we
   1.457 +  // won't try to handle this situation. even if accidentially or
   1.458 +  // maliciously planted, the directory's presence won't hurt anything.
   1.459 +  //
   1.460 +  RESTARTABLE(::unlink(path), result);
   1.461 +  if (PrintMiscellaneous && Verbose && result == OS_ERR) {
   1.462 +    if (errno != ENOENT) {
   1.463 +      warning("Could not unlink shared memory backing"
   1.464 +              " store file %s : %s\n", path, strerror(errno));
   1.465 +    }
   1.466 +  }
   1.467 +}
   1.468 +
   1.469 +
   1.470 +// remove file
   1.471 +//
   1.472 +// this method removes the file with the given file name in the
   1.473 +// named directory.
   1.474 +//
   1.475 +static void remove_file(const char* dirname, const char* filename) {
   1.476 +
   1.477 +  size_t nbytes = strlen(dirname) + strlen(filename) + 2;
   1.478 +  char* path = NEW_C_HEAP_ARRAY(char, nbytes);
   1.479 +
   1.480 +  strcpy(path, dirname);
   1.481 +  strcat(path, "/");
   1.482 +  strcat(path, filename);
   1.483 +
   1.484 +  remove_file(path);
   1.485 +
   1.486 +  FREE_C_HEAP_ARRAY(char, path);
   1.487 +}
   1.488 +
   1.489 +
   1.490 +// cleanup stale shared memory resources
   1.491 +//
   1.492 +// This method attempts to remove all stale shared memory files in
   1.493 +// the named user temporary directory. It scans the named directory
   1.494 +// for files matching the pattern ^$[0-9]*$. For each file found, the
   1.495 +// process id is extracted from the file name and a test is run to
   1.496 +// determine if the process is alive. If the process is not alive,
   1.497 +// any stale file resources are removed.
   1.498 +//
   1.499 +static void cleanup_sharedmem_resources(const char* dirname) {
   1.500 +
   1.501 +  // open the user temp directory
   1.502 +  DIR* dirp = os::opendir(dirname);
   1.503 +
   1.504 +  if (dirp == NULL) {
   1.505 +    // directory doesn't exist, so there is nothing to cleanup
   1.506 +    return;
   1.507 +  }
   1.508 +
   1.509 +  if (!is_directory_secure(dirname)) {
   1.510 +    // the directory is not a secure directory
   1.511 +    return;
   1.512 +  }
   1.513 +
   1.514 +  // for each entry in the directory that matches the expected file
   1.515 +  // name pattern, determine if the file resources are stale and if
   1.516 +  // so, remove the file resources. Note, instrumented HotSpot processes
   1.517 +  // for this user may start and/or terminate during this search and
   1.518 +  // remove or create new files in this directory. The behavior of this
   1.519 +  // loop under these conditions is dependent upon the implementation of
   1.520 +  // opendir/readdir.
   1.521 +  //
   1.522 +  struct dirent* entry;
   1.523 +  char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname));
   1.524 +  errno = 0;
   1.525 +  while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
   1.526 +
   1.527 +    pid_t pid = filename_to_pid(entry->d_name);
   1.528 +
   1.529 +    if (pid == 0) {
   1.530 +
   1.531 +      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
   1.532 +
   1.533 +        // attempt to remove all unexpected files, except "." and ".."
   1.534 +        remove_file(dirname, entry->d_name);
   1.535 +      }
   1.536 +
   1.537 +      errno = 0;
   1.538 +      continue;
   1.539 +    }
   1.540 +
   1.541 +    // we now have a file name that converts to a valid integer
   1.542 +    // that could represent a process id . if this process id
   1.543 +    // matches the current process id or the process is not running,
   1.544 +    // then remove the stale file resources.
   1.545 +    //
   1.546 +    // process liveness is detected by sending signal number 0 to
   1.547 +    // the process id (see kill(2)). if kill determines that the
   1.548 +    // process does not exist, then the file resources are removed.
   1.549 +    // if kill determines that that we don't have permission to
   1.550 +    // signal the process, then the file resources are assumed to
   1.551 +    // be stale and are removed because the resources for such a
   1.552 +    // process should be in a different user specific directory.
   1.553 +    //
   1.554 +    if ((pid == os::current_process_id()) ||
   1.555 +        (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
   1.556 +
   1.557 +        remove_file(dirname, entry->d_name);
   1.558 +    }
   1.559 +    errno = 0;
   1.560 +  }
   1.561 +  os::closedir(dirp);
   1.562 +  FREE_C_HEAP_ARRAY(char, dbuf);
   1.563 +}
   1.564 +
   1.565 +// make the user specific temporary directory. Returns true if
   1.566 +// the directory exists and is secure upon return. Returns false
   1.567 +// if the directory exists but is either a symlink, is otherwise
   1.568 +// insecure, or if an error occurred.
   1.569 +//
   1.570 +static bool make_user_tmp_dir(const char* dirname) {
   1.571 +
   1.572 +  // create the directory with 0755 permissions. note that the directory
   1.573 +  // will be owned by euid::egid, which may not be the same as uid::gid.
   1.574 +  //
   1.575 +  if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
   1.576 +    if (errno == EEXIST) {
   1.577 +      // The directory already exists and was probably created by another
   1.578 +      // JVM instance. However, this could also be the result of a
   1.579 +      // deliberate symlink. Verify that the existing directory is safe.
   1.580 +      //
   1.581 +      if (!is_directory_secure(dirname)) {
   1.582 +        // directory is not secure
   1.583 +        if (PrintMiscellaneous && Verbose) {
   1.584 +          warning("%s directory is insecure\n", dirname);
   1.585 +        }
   1.586 +        return false;
   1.587 +      }
   1.588 +    }
   1.589 +    else {
   1.590 +      // we encountered some other failure while attempting
   1.591 +      // to create the directory
   1.592 +      //
   1.593 +      if (PrintMiscellaneous && Verbose) {
   1.594 +        warning("could not create directory %s: %s\n",
   1.595 +                dirname, strerror(errno));
   1.596 +      }
   1.597 +      return false;
   1.598 +    }
   1.599 +  }
   1.600 +  return true;
   1.601 +}
   1.602 +
   1.603 +// create the shared memory file resources
   1.604 +//
   1.605 +// This method creates the shared memory file with the given size
   1.606 +// This method also creates the user specific temporary directory, if
   1.607 +// it does not yet exist.
   1.608 +//
   1.609 +static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
   1.610 +
   1.611 +  // make the user temporary directory
   1.612 +  if (!make_user_tmp_dir(dirname)) {
   1.613 +    // could not make/find the directory or the found directory
   1.614 +    // was not secure
   1.615 +    return -1;
   1.616 +  }
   1.617 +
   1.618 +  int result;
   1.619 +
   1.620 +  RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE), result);
   1.621 +  if (result == OS_ERR) {
   1.622 +    if (PrintMiscellaneous && Verbose) {
   1.623 +      warning("could not create file %s: %s\n", filename, strerror(errno));
   1.624 +    }
   1.625 +    return -1;
   1.626 +  }
   1.627 +
   1.628 +  // save the file descriptor
   1.629 +  int fd = result;
   1.630 +
   1.631 +  // set the file size
   1.632 +  RESTARTABLE(::ftruncate(fd, (off_t)size), result);
   1.633 +  if (result == OS_ERR) {
   1.634 +    if (PrintMiscellaneous && Verbose) {
   1.635 +      warning("could not set shared memory file size: %s\n", strerror(errno));
   1.636 +    }
   1.637 +    RESTARTABLE(::close(fd), result);
   1.638 +    return -1;
   1.639 +  }
   1.640 +
   1.641 +  // Verify that we have enough disk space for this file.
   1.642 +  // We'll get random SIGBUS crashes on memory accesses if
   1.643 +  // we don't.
   1.644 +
   1.645 +  for (size_t seekpos = 0; seekpos < size; seekpos += os::vm_page_size()) {
   1.646 +    int zero_int = 0;
   1.647 +    result = (int)os::seek_to_file_offset(fd, (jlong)(seekpos));
   1.648 +    if (result == -1 ) break;
   1.649 +    RESTARTABLE(::write(fd, &zero_int, 1), result);
   1.650 +    if (result != 1) {
   1.651 +      if (errno == ENOSPC) {
   1.652 +        warning("Insufficient space for shared memory file:\n   %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename);
   1.653 +      }
   1.654 +      break;
   1.655 +    }
   1.656 +  }
   1.657 +
   1.658 +  if (result != -1) {
   1.659 +    return fd;
   1.660 +  } else {
   1.661 +    RESTARTABLE(::close(fd), result);
   1.662 +    return -1;
   1.663 +  }
   1.664 +}
   1.665 +
   1.666 +// open the shared memory file for the given user and vmid. returns
   1.667 +// the file descriptor for the open file or -1 if the file could not
   1.668 +// be opened.
   1.669 +//
   1.670 +static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
   1.671 +
   1.672 +  // open the file
   1.673 +  int result;
   1.674 +  RESTARTABLE(::open(filename, oflags), result);
   1.675 +  if (result == OS_ERR) {
   1.676 +    if (errno == ENOENT) {
   1.677 +      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   1.678 +                  "Process not found");
   1.679 +    }
   1.680 +    else if (errno == EACCES) {
   1.681 +      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
   1.682 +                  "Permission denied");
   1.683 +    }
   1.684 +    else {
   1.685 +      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
   1.686 +    }
   1.687 +  }
   1.688 +
   1.689 +  return result;
   1.690 +}
   1.691 +
   1.692 +// create a named shared memory region. returns the address of the
   1.693 +// memory region on success or NULL on failure. A return value of
   1.694 +// NULL will ultimately disable the shared memory feature.
   1.695 +//
   1.696 +// On Solaris and Bsd, the name space for shared memory objects
   1.697 +// is the file system name space.
   1.698 +//
   1.699 +// A monitoring application attaching to a JVM does not need to know
   1.700 +// the file system name of the shared memory object. However, it may
   1.701 +// be convenient for applications to discover the existence of newly
   1.702 +// created and terminating JVMs by watching the file system name space
   1.703 +// for files being created or removed.
   1.704 +//
   1.705 +static char* mmap_create_shared(size_t size) {
   1.706 +
   1.707 +  int result;
   1.708 +  int fd;
   1.709 +  char* mapAddress;
   1.710 +
   1.711 +  int vmid = os::current_process_id();
   1.712 +
   1.713 +  char* user_name = get_user_name(geteuid());
   1.714 +
   1.715 +  if (user_name == NULL)
   1.716 +    return NULL;
   1.717 +
   1.718 +  char* dirname = get_user_tmp_dir(user_name);
   1.719 +  char* filename = get_sharedmem_filename(dirname, vmid);
   1.720 +
   1.721 +  // cleanup any stale shared memory files
   1.722 +  cleanup_sharedmem_resources(dirname);
   1.723 +
   1.724 +  assert(((size > 0) && (size % os::vm_page_size() == 0)),
   1.725 +         "unexpected PerfMemory region size");
   1.726 +
   1.727 +  fd = create_sharedmem_resources(dirname, filename, size);
   1.728 +
   1.729 +  FREE_C_HEAP_ARRAY(char, user_name);
   1.730 +  FREE_C_HEAP_ARRAY(char, dirname);
   1.731 +
   1.732 +  if (fd == -1) {
   1.733 +    FREE_C_HEAP_ARRAY(char, filename);
   1.734 +    return NULL;
   1.735 +  }
   1.736 +
   1.737 +  mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
   1.738 +
   1.739 +  // attempt to close the file - restart it if it was interrupted,
   1.740 +  // but ignore other failures
   1.741 +  RESTARTABLE(::close(fd), result);
   1.742 +  assert(result != OS_ERR, "could not close file");
   1.743 +
   1.744 +  if (mapAddress == MAP_FAILED) {
   1.745 +    if (PrintMiscellaneous && Verbose) {
   1.746 +      warning("mmap failed -  %s\n", strerror(errno));
   1.747 +    }
   1.748 +    remove_file(filename);
   1.749 +    FREE_C_HEAP_ARRAY(char, filename);
   1.750 +    return NULL;
   1.751 +  }
   1.752 +
   1.753 +  // save the file name for use in delete_shared_memory()
   1.754 +  backing_store_file_name = filename;
   1.755 +
   1.756 +  // clear the shared memory region
   1.757 +  (void)::memset((void*) mapAddress, 0, size);
   1.758 +
   1.759 +  return mapAddress;
   1.760 +}
   1.761 +
   1.762 +// release a named shared memory region
   1.763 +//
   1.764 +static void unmap_shared(char* addr, size_t bytes) {
   1.765 +  os::release_memory(addr, bytes);
   1.766 +}
   1.767 +
   1.768 +// create the PerfData memory region in shared memory.
   1.769 +//
   1.770 +static char* create_shared_memory(size_t size) {
   1.771 +
   1.772 +  // create the shared memory region.
   1.773 +  return mmap_create_shared(size);
   1.774 +}
   1.775 +
   1.776 +// delete the shared PerfData memory region
   1.777 +//
   1.778 +static void delete_shared_memory(char* addr, size_t size) {
   1.779 +
   1.780 +  // cleanup the persistent shared memory resources. since DestroyJavaVM does
   1.781 +  // not support unloading of the JVM, unmapping of the memory resource is
   1.782 +  // not performed. The memory will be reclaimed by the OS upon termination of
   1.783 +  // the process. The backing store file is deleted from the file system.
   1.784 +
   1.785 +  assert(!PerfDisableSharedMem, "shouldn't be here");
   1.786 +
   1.787 +  if (backing_store_file_name != NULL) {
   1.788 +    remove_file(backing_store_file_name);
   1.789 +    // Don't.. Free heap memory could deadlock os::abort() if it is called
   1.790 +    // from signal handler. OS will reclaim the heap memory.
   1.791 +    // FREE_C_HEAP_ARRAY(char, backing_store_file_name);
   1.792 +    backing_store_file_name = NULL;
   1.793 +  }
   1.794 +}
   1.795 +
   1.796 +// return the size of the file for the given file descriptor
   1.797 +// or 0 if it is not a valid size for a shared memory file
   1.798 +//
   1.799 +static size_t sharedmem_filesize(int fd, TRAPS) {
   1.800 +
   1.801 +  struct stat statbuf;
   1.802 +  int result;
   1.803 +
   1.804 +  RESTARTABLE(::fstat(fd, &statbuf), result);
   1.805 +  if (result == OS_ERR) {
   1.806 +    if (PrintMiscellaneous && Verbose) {
   1.807 +      warning("fstat failed: %s\n", strerror(errno));
   1.808 +    }
   1.809 +    THROW_MSG_0(vmSymbols::java_io_IOException(),
   1.810 +                "Could not determine PerfMemory size");
   1.811 +  }
   1.812 +
   1.813 +  if ((statbuf.st_size == 0) ||
   1.814 +     ((size_t)statbuf.st_size % os::vm_page_size() != 0)) {
   1.815 +    THROW_MSG_0(vmSymbols::java_lang_Exception(),
   1.816 +                "Invalid PerfMemory size");
   1.817 +  }
   1.818 +
   1.819 +  return (size_t)statbuf.st_size;
   1.820 +}
   1.821 +
   1.822 +// attach to a named shared memory region.
   1.823 +//
   1.824 +static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
   1.825 +
   1.826 +  char* mapAddress;
   1.827 +  int result;
   1.828 +  int fd;
   1.829 +  size_t size;
   1.830 +  const char* luser = NULL;
   1.831 +
   1.832 +  int mmap_prot;
   1.833 +  int file_flags;
   1.834 +
   1.835 +  ResourceMark rm;
   1.836 +
   1.837 +  // map the high level access mode to the appropriate permission
   1.838 +  // constructs for the file and the shared memory mapping.
   1.839 +  if (mode == PerfMemory::PERF_MODE_RO) {
   1.840 +    mmap_prot = PROT_READ;
   1.841 +    file_flags = O_RDONLY;
   1.842 +  }
   1.843 +  else if (mode == PerfMemory::PERF_MODE_RW) {
   1.844 +#ifdef LATER
   1.845 +    mmap_prot = PROT_READ | PROT_WRITE;
   1.846 +    file_flags = O_RDWR;
   1.847 +#else
   1.848 +    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
   1.849 +              "Unsupported access mode");
   1.850 +#endif
   1.851 +  }
   1.852 +  else {
   1.853 +    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
   1.854 +              "Illegal access mode");
   1.855 +  }
   1.856 +
   1.857 +  if (user == NULL || strlen(user) == 0) {
   1.858 +    luser = get_user_name(vmid, CHECK);
   1.859 +  }
   1.860 +  else {
   1.861 +    luser = user;
   1.862 +  }
   1.863 +
   1.864 +  if (luser == NULL) {
   1.865 +    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
   1.866 +              "Could not map vmid to user Name");
   1.867 +  }
   1.868 +
   1.869 +  char* dirname = get_user_tmp_dir(luser);
   1.870 +
   1.871 +  // since we don't follow symbolic links when creating the backing
   1.872 +  // store file, we don't follow them when attaching either.
   1.873 +  //
   1.874 +  if (!is_directory_secure(dirname)) {
   1.875 +    FREE_C_HEAP_ARRAY(char, dirname);
   1.876 +    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
   1.877 +              "Process not found");
   1.878 +  }
   1.879 +
   1.880 +  char* filename = get_sharedmem_filename(dirname, vmid);
   1.881 +
   1.882 +  // copy heap memory to resource memory. the open_sharedmem_file
   1.883 +  // method below need to use the filename, but could throw an
   1.884 +  // exception. using a resource array prevents the leak that
   1.885 +  // would otherwise occur.
   1.886 +  char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
   1.887 +  strcpy(rfilename, filename);
   1.888 +
   1.889 +  // free the c heap resources that are no longer needed
   1.890 +  if (luser != user) FREE_C_HEAP_ARRAY(char, luser);
   1.891 +  FREE_C_HEAP_ARRAY(char, dirname);
   1.892 +  FREE_C_HEAP_ARRAY(char, filename);
   1.893 +
   1.894 +  // open the shared memory file for the give vmid
   1.895 +  fd = open_sharedmem_file(rfilename, file_flags, CHECK);
   1.896 +  assert(fd != OS_ERR, "unexpected value");
   1.897 +
   1.898 +  if (*sizep == 0) {
   1.899 +    size = sharedmem_filesize(fd, CHECK);
   1.900 +    assert(size != 0, "unexpected size");
   1.901 +  }
   1.902 +
   1.903 +  mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
   1.904 +
   1.905 +  // attempt to close the file - restart if it gets interrupted,
   1.906 +  // but ignore other failures
   1.907 +  RESTARTABLE(::close(fd), result);
   1.908 +  assert(result != OS_ERR, "could not close file");
   1.909 +
   1.910 +  if (mapAddress == MAP_FAILED) {
   1.911 +    if (PrintMiscellaneous && Verbose) {
   1.912 +      warning("mmap failed: %s\n", strerror(errno));
   1.913 +    }
   1.914 +    THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
   1.915 +              "Could not map PerfMemory");
   1.916 +  }
   1.917 +
   1.918 +  *addr = mapAddress;
   1.919 +  *sizep = size;
   1.920 +
   1.921 +  if (PerfTraceMemOps) {
   1.922 +    tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
   1.923 +               INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);
   1.924 +  }
   1.925 +}
   1.926 +
   1.927 +
   1.928 +
   1.929 +
   1.930 +// create the PerfData memory region
   1.931 +//
   1.932 +// This method creates the memory region used to store performance
   1.933 +// data for the JVM. The memory may be created in standard or
   1.934 +// shared memory.
   1.935 +//
   1.936 +void PerfMemory::create_memory_region(size_t size) {
   1.937 +
   1.938 +  if (PerfDisableSharedMem) {
   1.939 +    // do not share the memory for the performance data.
   1.940 +    _start = create_standard_memory(size);
   1.941 +  }
   1.942 +  else {
   1.943 +    _start = create_shared_memory(size);
   1.944 +    if (_start == NULL) {
   1.945 +
   1.946 +      // creation of the shared memory region failed, attempt
   1.947 +      // to create a contiguous, non-shared memory region instead.
   1.948 +      //
   1.949 +      if (PrintMiscellaneous && Verbose) {
   1.950 +        warning("Reverting to non-shared PerfMemory region.\n");
   1.951 +      }
   1.952 +      PerfDisableSharedMem = true;
   1.953 +      _start = create_standard_memory(size);
   1.954 +    }
   1.955 +  }
   1.956 +
   1.957 +  if (_start != NULL) _capacity = size;
   1.958 +
   1.959 +}
   1.960 +
   1.961 +// delete the PerfData memory region
   1.962 +//
   1.963 +// This method deletes the memory region used to store performance
   1.964 +// data for the JVM. The memory region indicated by the <address, size>
   1.965 +// tuple will be inaccessible after a call to this method.
   1.966 +//
   1.967 +void PerfMemory::delete_memory_region() {
   1.968 +
   1.969 +  assert((start() != NULL && capacity() > 0), "verify proper state");
   1.970 +
   1.971 +  // If user specifies PerfDataSaveFile, it will save the performance data
   1.972 +  // to the specified file name no matter whether PerfDataSaveToFile is specified
   1.973 +  // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
   1.974 +  // -XX:+PerfDataSaveToFile.
   1.975 +  if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
   1.976 +    save_memory_to_file(start(), capacity());
   1.977 +  }
   1.978 +
   1.979 +  if (PerfDisableSharedMem) {
   1.980 +    delete_standard_memory(start(), capacity());
   1.981 +  }
   1.982 +  else {
   1.983 +    delete_shared_memory(start(), capacity());
   1.984 +  }
   1.985 +}
   1.986 +
   1.987 +// attach to the PerfData memory region for another JVM
   1.988 +//
   1.989 +// This method returns an <address, size> tuple that points to
   1.990 +// a memory buffer that is kept reasonably synchronized with
   1.991 +// the PerfData memory region for the indicated JVM. This
   1.992 +// buffer may be kept in synchronization via shared memory
   1.993 +// or some other mechanism that keeps the buffer updated.
   1.994 +//
   1.995 +// If the JVM chooses not to support the attachability feature,
   1.996 +// this method should throw an UnsupportedOperation exception.
   1.997 +//
   1.998 +// This implementation utilizes named shared memory to map
   1.999 +// the indicated process's PerfData memory region into this JVMs
  1.1000 +// address space.
  1.1001 +//
  1.1002 +void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
  1.1003 +
  1.1004 +  if (vmid == 0 || vmid == os::current_process_id()) {
  1.1005 +     *addrp = start();
  1.1006 +     *sizep = capacity();
  1.1007 +     return;
  1.1008 +  }
  1.1009 +
  1.1010 +  mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
  1.1011 +}
  1.1012 +
  1.1013 +// detach from the PerfData memory region of another JVM
  1.1014 +//
  1.1015 +// This method detaches the PerfData memory region of another
  1.1016 +// JVM, specified as an <address, size> tuple of a buffer
  1.1017 +// in this process's address space. This method may perform
  1.1018 +// arbitrary actions to accomplish the detachment. The memory
  1.1019 +// region specified by <address, size> will be inaccessible after
  1.1020 +// a call to this method.
  1.1021 +//
  1.1022 +// If the JVM chooses not to support the attachability feature,
  1.1023 +// this method should throw an UnsupportedOperation exception.
  1.1024 +//
  1.1025 +// This implementation utilizes named shared memory to detach
  1.1026 +// the indicated process's PerfData memory region from this
  1.1027 +// process's address space.
  1.1028 +//
  1.1029 +void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
  1.1030 +
  1.1031 +  assert(addr != 0, "address sanity check");
  1.1032 +  assert(bytes > 0, "capacity sanity check");
  1.1033 +
  1.1034 +  if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
  1.1035 +    // prevent accidental detachment of this process's PerfMemory region
  1.1036 +    return;
  1.1037 +  }
  1.1038 +
  1.1039 +  unmap_shared(addr, bytes);
  1.1040 +}
  1.1041 +
  1.1042 +char* PerfMemory::backing_store_filename() {
  1.1043 +  return backing_store_file_name;
  1.1044 +}

mercurial