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