perfMemory_solaris.cpp revision 5883:2c2a99f6cf83
1/*
2 * Copyright (c) 2001, 2014, 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 <pwd.h>
45# include <procfs.h>
46
47
48static char* backing_store_file_name = NULL;  // name of the backing store
49                                              // file, if successfully created.
50
51// Standard Memory Implementation Details
52
53// create the PerfData memory region in standard memory.
54//
55static char* create_standard_memory(size_t size) {
56
57  // allocate an aligned chuck of memory
58  char* mapAddress = os::reserve_memory(size);
59
60  if (mapAddress == NULL) {
61    return NULL;
62  }
63
64  // commit memory
65  if (!os::commit_memory(mapAddress, size, !ExecMem)) {
66    if (PrintMiscellaneous && Verbose) {
67      warning("Could not commit PerfData memory\n");
68    }
69    os::release_memory(mapAddress, size);
70    return NULL;
71  }
72
73  return mapAddress;
74}
75
76// delete the PerfData memory region
77//
78static void delete_standard_memory(char* addr, size_t size) {
79
80  // there are no persistent external resources to cleanup for standard
81  // memory. since DestroyJavaVM does not support unloading of the JVM,
82  // cleanup of the memory resource is not performed. The memory will be
83  // reclaimed by the OS upon termination of the process.
84  //
85  return;
86}
87
88// save the specified memory region to the given file
89//
90// Note: this function might be called from signal handler (by os::abort()),
91// don't allocate heap memory.
92//
93static void save_memory_to_file(char* addr, size_t size) {
94
95  const char* destfile = PerfMemory::get_perfdata_file_path();
96  assert(destfile[0] != '\0', "invalid PerfData file path");
97
98  int result;
99
100  RESTARTABLE(::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE),
101              result);;
102  if (result == OS_ERR) {
103    if (PrintMiscellaneous && Verbose) {
104      warning("Could not create Perfdata save file: %s: %s\n",
105              destfile, strerror(errno));
106    }
107  } else {
108
109    int fd = result;
110
111    for (size_t remaining = size; remaining > 0;) {
112
113      RESTARTABLE(::write(fd, addr, remaining), result);
114      if (result == OS_ERR) {
115        if (PrintMiscellaneous && Verbose) {
116          warning("Could not write Perfdata save file: %s: %s\n",
117                  destfile, strerror(errno));
118        }
119        break;
120      }
121      remaining -= (size_t)result;
122      addr += result;
123    }
124
125    result = ::close(fd);
126    if (PrintMiscellaneous && Verbose) {
127      if (result == OS_ERR) {
128        warning("Could not close %s: %s\n", destfile, strerror(errno));
129      }
130    }
131  }
132  FREE_C_HEAP_ARRAY(char, destfile, mtInternal);
133}
134
135
136// Shared Memory Implementation Details
137
138// Note: the solaris and linux shared memory implementation uses the mmap
139// interface with a backing store file to implement named shared memory.
140// Using the file system as the name space for shared memory allows a
141// common name space to be supported across a variety of platforms. It
142// also provides a name space that Java applications can deal with through
143// simple file apis.
144//
145// The solaris and linux implementations store the backing store file in
146// a user specific temporary directory located in the /tmp file system,
147// which is always a local file system and is sometimes a RAM based file
148// system.
149
150// return the user specific temporary directory name.
151//
152// the caller is expected to free the allocated memory.
153//
154static char* get_user_tmp_dir(const char* user) {
155
156  const char* tmpdir = os::get_temp_directory();
157  const char* perfdir = PERFDATA_NAME;
158  size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;
159  char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
160
161  // construct the path name to user specific tmp directory
162  snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);
163
164  return dirname;
165}
166
167// convert the given file name into a process id. if the file
168// does not meet the file naming constraints, return 0.
169//
170static pid_t filename_to_pid(const char* filename) {
171
172  // a filename that doesn't begin with a digit is not a
173  // candidate for conversion.
174  //
175  if (!isdigit(*filename)) {
176    return 0;
177  }
178
179  // check if file name can be converted to an integer without
180  // any leftover characters.
181  //
182  char* remainder = NULL;
183  errno = 0;
184  pid_t pid = (pid_t)strtol(filename, &remainder, 10);
185
186  if (errno != 0) {
187    return 0;
188  }
189
190  // check for left over characters. If any, then the filename is
191  // not a candidate for conversion.
192  //
193  if (remainder != NULL && *remainder != '\0') {
194    return 0;
195  }
196
197  // successful conversion, return the pid
198  return pid;
199}
200
201
202// check if the given path is considered a secure directory for
203// the backing store files. Returns true if the directory exists
204// and is considered a secure location. Returns false if the path
205// is a symbolic link or if an error occurred.
206//
207static bool is_directory_secure(const char* path) {
208  struct stat statbuf;
209  int result = 0;
210
211  RESTARTABLE(::lstat(path, &statbuf), result);
212  if (result == OS_ERR) {
213    return false;
214  }
215
216  // the path exists, now check it's mode
217  if (S_ISLNK(statbuf.st_mode) || !S_ISDIR(statbuf.st_mode)) {
218    // the path represents a link or some non-directory file type,
219    // which is not what we expected. declare it insecure.
220    //
221    return false;
222  }
223  else {
224    // we have an existing directory, check if the permissions are safe.
225    //
226    if ((statbuf.st_mode & (S_IWGRP|S_IWOTH)) != 0) {
227      // the directory is open for writing and could be subjected
228      // to a symlnk attack. declare it insecure.
229      //
230      return false;
231    }
232  }
233  return true;
234}
235
236
237// return the user name for the given user id
238//
239// the caller is expected to free the allocated memory.
240//
241static char* get_user_name(uid_t uid) {
242
243  struct passwd pwent;
244
245  // determine the max pwbuf size from sysconf, and hardcode
246  // a default if this not available through sysconf.
247  //
248  long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
249  if (bufsize == -1)
250    bufsize = 1024;
251
252  char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
253
254#ifdef _GNU_SOURCE
255  struct passwd* p = NULL;
256  int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);
257#else  // _GNU_SOURCE
258  struct passwd* p = getpwuid_r(uid, &pwent, pwbuf, (int)bufsize);
259#endif // _GNU_SOURCE
260
261  if (p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {
262    if (PrintMiscellaneous && Verbose) {
263      if (p == NULL) {
264        warning("Could not retrieve passwd entry: %s\n",
265                strerror(errno));
266      }
267      else {
268        warning("Could not determine user name: %s\n",
269                p->pw_name == NULL ? "pw_name = NULL" :
270                                     "pw_name zero length");
271      }
272    }
273    FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
274    return NULL;
275  }
276
277  char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);
278  strcpy(user_name, p->pw_name);
279
280  FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
281  return user_name;
282}
283
284// return the name of the user that owns the process identified by vmid.
285//
286// This method uses a slow directory search algorithm to find the backing
287// store file for the specified vmid and returns the user name, as determined
288// by the user name suffix of the hsperfdata_<username> directory name.
289//
290// the caller is expected to free the allocated memory.
291//
292static char* get_user_name_slow(int vmid, TRAPS) {
293
294  // short circuit the directory search if the process doesn't even exist.
295  if (kill(vmid, 0) == OS_ERR) {
296    if (errno == ESRCH) {
297      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
298                  "Process not found");
299    }
300    else /* EPERM */ {
301      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
302    }
303  }
304
305  // directory search
306  char* oldest_user = NULL;
307  time_t oldest_ctime = 0;
308
309  const char* tmpdirname = os::get_temp_directory();
310
311  DIR* tmpdirp = os::opendir(tmpdirname);
312
313  if (tmpdirp == NULL) {
314    return NULL;
315  }
316
317  // for each entry in the directory that matches the pattern hsperfdata_*,
318  // open the directory and check if the file for the given vmid exists.
319  // The file with the expected name and the latest creation date is used
320  // to determine the user name for the process id.
321  //
322  struct dirent* dentry;
323  char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal);
324  errno = 0;
325  while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
326
327    // check if the directory entry is a hsperfdata file
328    if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
329      continue;
330    }
331
332    char* usrdir_name = NEW_C_HEAP_ARRAY(char,
333                  strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);
334    strcpy(usrdir_name, tmpdirname);
335    strcat(usrdir_name, "/");
336    strcat(usrdir_name, dentry->d_name);
337
338    DIR* subdirp = os::opendir(usrdir_name);
339
340    if (subdirp == NULL) {
341      FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
342      continue;
343    }
344
345    // Since we don't create the backing store files in directories
346    // pointed to by symbolic links, we also don't follow them when
347    // looking for the files. We check for a symbolic link after the
348    // call to opendir in order to eliminate a small window where the
349    // symlink can be exploited.
350    //
351    if (!is_directory_secure(usrdir_name)) {
352      FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
353      os::closedir(subdirp);
354      continue;
355    }
356
357    struct dirent* udentry;
358    char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal);
359    errno = 0;
360    while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
361
362      if (filename_to_pid(udentry->d_name) == vmid) {
363        struct stat statbuf;
364        int result;
365
366        char* filename = NEW_C_HEAP_ARRAY(char,
367                 strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
368
369        strcpy(filename, usrdir_name);
370        strcat(filename, "/");
371        strcat(filename, udentry->d_name);
372
373        // don't follow symbolic links for the file
374        RESTARTABLE(::lstat(filename, &statbuf), result);
375        if (result == OS_ERR) {
376           FREE_C_HEAP_ARRAY(char, filename, mtInternal);
377           continue;
378        }
379
380        // skip over files that are not regular files.
381        if (!S_ISREG(statbuf.st_mode)) {
382          FREE_C_HEAP_ARRAY(char, filename, mtInternal);
383          continue;
384        }
385
386        // compare and save filename with latest creation time
387        if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
388
389          if (statbuf.st_ctime > oldest_ctime) {
390            char* user = strchr(dentry->d_name, '_') + 1;
391
392            if (oldest_user != NULL) FREE_C_HEAP_ARRAY(char, oldest_user, mtInternal);
393            oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
394
395            strcpy(oldest_user, user);
396            oldest_ctime = statbuf.st_ctime;
397          }
398        }
399
400        FREE_C_HEAP_ARRAY(char, filename, mtInternal);
401      }
402    }
403    os::closedir(subdirp);
404    FREE_C_HEAP_ARRAY(char, udbuf, mtInternal);
405    FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
406  }
407  os::closedir(tmpdirp);
408  FREE_C_HEAP_ARRAY(char, tdbuf, mtInternal);
409
410  return(oldest_user);
411}
412
413// return the name of the user that owns the JVM indicated by the given vmid.
414//
415static char* get_user_name(int vmid, TRAPS) {
416
417  char psinfo_name[PATH_MAX];
418  int result;
419
420  snprintf(psinfo_name, PATH_MAX, "/proc/%d/psinfo", vmid);
421
422  RESTARTABLE(::open(psinfo_name, O_RDONLY), result);
423
424  if (result != OS_ERR) {
425    int fd = result;
426
427    psinfo_t psinfo;
428    char* addr = (char*)&psinfo;
429
430    for (size_t remaining = sizeof(psinfo_t); remaining > 0;) {
431
432      RESTARTABLE(::read(fd, addr, remaining), result);
433      if (result == OS_ERR) {
434        ::close(fd);
435        THROW_MSG_0(vmSymbols::java_io_IOException(), "Read error");
436      } else {
437        remaining-=result;
438        addr+=result;
439      }
440    }
441
442    ::close(fd);
443
444    // get the user name for the effective user id of the process
445    char* user_name = get_user_name(psinfo.pr_euid);
446
447    return user_name;
448  }
449
450  if (result == OS_ERR && errno == EACCES) {
451
452    // In this case, the psinfo file for the process id existed,
453    // but we didn't have permission to access it.
454    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
455                strerror(errno));
456  }
457
458  // at this point, we don't know if the process id itself doesn't
459  // exist or if the psinfo file doesn't exit. If the psinfo file
460  // doesn't exist, then we are running on Solaris 2.5.1 or earlier.
461  // since the structured procfs and old procfs interfaces can't be
462  // mixed, we attempt to find the file through a directory search.
463
464  return get_user_name_slow(vmid, CHECK_NULL);
465}
466
467// return the file name of the backing store file for the named
468// shared memory region for the given user name and vmid.
469//
470// the caller is expected to free the allocated memory.
471//
472static char* get_sharedmem_filename(const char* dirname, int vmid) {
473
474  // add 2 for the file separator and a NULL terminator.
475  size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
476
477  char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
478  snprintf(name, nbytes, "%s/%d", dirname, vmid);
479
480  return name;
481}
482
483
484// remove file
485//
486// this method removes the file specified by the given path
487//
488static void remove_file(const char* path) {
489
490  int result;
491
492  // if the file is a directory, the following unlink will fail. since
493  // we don't expect to find directories in the user temp directory, we
494  // won't try to handle this situation. even if accidentially or
495  // maliciously planted, the directory's presence won't hurt anything.
496  //
497  RESTARTABLE(::unlink(path), result);
498  if (PrintMiscellaneous && Verbose && result == OS_ERR) {
499    if (errno != ENOENT) {
500      warning("Could not unlink shared memory backing"
501              " store file %s : %s\n", path, strerror(errno));
502    }
503  }
504}
505
506
507// remove file
508//
509// this method removes the file with the given file name in the
510// named directory.
511//
512static void remove_file(const char* dirname, const char* filename) {
513
514  size_t nbytes = strlen(dirname) + strlen(filename) + 2;
515  char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
516
517  strcpy(path, dirname);
518  strcat(path, "/");
519  strcat(path, filename);
520
521  remove_file(path);
522
523  FREE_C_HEAP_ARRAY(char, path, mtInternal);
524}
525
526
527// cleanup stale shared memory resources
528//
529// This method attempts to remove all stale shared memory files in
530// the named user temporary directory. It scans the named directory
531// for files matching the pattern ^$[0-9]*$. For each file found, the
532// process id is extracted from the file name and a test is run to
533// determine if the process is alive. If the process is not alive,
534// any stale file resources are removed.
535//
536static void cleanup_sharedmem_resources(const char* dirname) {
537
538  // open the user temp directory
539  DIR* dirp = os::opendir(dirname);
540
541  if (dirp == NULL) {
542    // directory doesn't exist, so there is nothing to cleanup
543    return;
544  }
545
546  if (!is_directory_secure(dirname)) {
547    // the directory is not a secure directory
548    return;
549  }
550
551  // for each entry in the directory that matches the expected file
552  // name pattern, determine if the file resources are stale and if
553  // so, remove the file resources. Note, instrumented HotSpot processes
554  // for this user may start and/or terminate during this search and
555  // remove or create new files in this directory. The behavior of this
556  // loop under these conditions is dependent upon the implementation of
557  // opendir/readdir.
558  //
559  struct dirent* entry;
560  char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
561  errno = 0;
562  while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
563
564    pid_t pid = filename_to_pid(entry->d_name);
565
566    if (pid == 0) {
567
568      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
569
570        // attempt to remove all unexpected files, except "." and ".."
571        remove_file(dirname, entry->d_name);
572      }
573
574      errno = 0;
575      continue;
576    }
577
578    // we now have a file name that converts to a valid integer
579    // that could represent a process id . if this process id
580    // matches the current process id or the process is not running,
581    // then remove the stale file resources.
582    //
583    // process liveness is detected by sending signal number 0 to
584    // the process id (see kill(2)). if kill determines that the
585    // process does not exist, then the file resources are removed.
586    // if kill determines that that we don't have permission to
587    // signal the process, then the file resources are assumed to
588    // be stale and are removed because the resources for such a
589    // process should be in a different user specific directory.
590    //
591    if ((pid == os::current_process_id()) ||
592        (kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
593
594        remove_file(dirname, entry->d_name);
595    }
596    errno = 0;
597  }
598  os::closedir(dirp);
599  FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
600}
601
602// make the user specific temporary directory. Returns true if
603// the directory exists and is secure upon return. Returns false
604// if the directory exists but is either a symlink, is otherwise
605// insecure, or if an error occurred.
606//
607static bool make_user_tmp_dir(const char* dirname) {
608
609  // create the directory with 0755 permissions. note that the directory
610  // will be owned by euid::egid, which may not be the same as uid::gid.
611  //
612  if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
613    if (errno == EEXIST) {
614      // The directory already exists and was probably created by another
615      // JVM instance. However, this could also be the result of a
616      // deliberate symlink. Verify that the existing directory is safe.
617      //
618      if (!is_directory_secure(dirname)) {
619        // directory is not secure
620        if (PrintMiscellaneous && Verbose) {
621          warning("%s directory is insecure\n", dirname);
622        }
623        return false;
624      }
625    }
626    else {
627      // we encountered some other failure while attempting
628      // to create the directory
629      //
630      if (PrintMiscellaneous && Verbose) {
631        warning("could not create directory %s: %s\n",
632                dirname, strerror(errno));
633      }
634      return false;
635    }
636  }
637  return true;
638}
639
640// create the shared memory file resources
641//
642// This method creates the shared memory file with the given size
643// This method also creates the user specific temporary directory, if
644// it does not yet exist.
645//
646static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
647
648  // make the user temporary directory
649  if (!make_user_tmp_dir(dirname)) {
650    // could not make/find the directory or the found directory
651    // was not secure
652    return -1;
653  }
654
655  int result;
656
657  RESTARTABLE(::open(filename, O_RDWR|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE), result);
658  if (result == OS_ERR) {
659    if (PrintMiscellaneous && Verbose) {
660      warning("could not create file %s: %s\n", filename, strerror(errno));
661    }
662    return -1;
663  }
664
665  // save the file descriptor
666  int fd = result;
667
668  // set the file size
669  RESTARTABLE(::ftruncate(fd, (off_t)size), result);
670  if (result == OS_ERR) {
671    if (PrintMiscellaneous && Verbose) {
672      warning("could not set shared memory file size: %s\n", strerror(errno));
673    }
674    ::close(fd);
675    return -1;
676  }
677
678  return fd;
679}
680
681// open the shared memory file for the given user and vmid. returns
682// the file descriptor for the open file or -1 if the file could not
683// be opened.
684//
685static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
686
687  // open the file
688  int result;
689  RESTARTABLE(::open(filename, oflags), result);
690  if (result == OS_ERR) {
691    if (errno == ENOENT) {
692      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
693                  "Process not found", OS_ERR);
694    }
695    else if (errno == EACCES) {
696      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
697                  "Permission denied", OS_ERR);
698    }
699    else {
700      THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);
701    }
702  }
703
704  return result;
705}
706
707// create a named shared memory region. returns the address of the
708// memory region on success or NULL on failure. A return value of
709// NULL will ultimately disable the shared memory feature.
710//
711// On Solaris and Linux, the name space for shared memory objects
712// is the file system name space.
713//
714// A monitoring application attaching to a JVM does not need to know
715// the file system name of the shared memory object. However, it may
716// be convenient for applications to discover the existence of newly
717// created and terminating JVMs by watching the file system name space
718// for files being created or removed.
719//
720static char* mmap_create_shared(size_t size) {
721
722  int result;
723  int fd;
724  char* mapAddress;
725
726  int vmid = os::current_process_id();
727
728  char* user_name = get_user_name(geteuid());
729
730  if (user_name == NULL)
731    return NULL;
732
733  char* dirname = get_user_tmp_dir(user_name);
734  char* filename = get_sharedmem_filename(dirname, vmid);
735
736  // cleanup any stale shared memory files
737  cleanup_sharedmem_resources(dirname);
738
739  assert(((size > 0) && (size % os::vm_page_size() == 0)),
740         "unexpected PerfMemory region size");
741
742  fd = create_sharedmem_resources(dirname, filename, size);
743
744  FREE_C_HEAP_ARRAY(char, user_name, mtInternal);
745  FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
746
747  if (fd == -1) {
748    FREE_C_HEAP_ARRAY(char, filename, mtInternal);
749    return NULL;
750  }
751
752  mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
753
754  result = ::close(fd);
755  assert(result != OS_ERR, "could not close file");
756
757  if (mapAddress == MAP_FAILED) {
758    if (PrintMiscellaneous && Verbose) {
759      warning("mmap failed -  %s\n", strerror(errno));
760    }
761    remove_file(filename);
762    FREE_C_HEAP_ARRAY(char, filename, mtInternal);
763    return NULL;
764  }
765
766  // save the file name for use in delete_shared_memory()
767  backing_store_file_name = filename;
768
769  // clear the shared memory region
770  (void)::memset((void*) mapAddress, 0, size);
771
772  // it does not go through os api, the operation has to record from here
773  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
774
775  return mapAddress;
776}
777
778// release a named shared memory region
779//
780static void unmap_shared(char* addr, size_t bytes) {
781  os::release_memory(addr, bytes);
782}
783
784// create the PerfData memory region in shared memory.
785//
786static char* create_shared_memory(size_t size) {
787
788  // create the shared memory region.
789  return mmap_create_shared(size);
790}
791
792// delete the shared PerfData memory region
793//
794static void delete_shared_memory(char* addr, size_t size) {
795
796  // cleanup the persistent shared memory resources. since DestroyJavaVM does
797  // not support unloading of the JVM, unmapping of the memory resource is
798  // not performed. The memory will be reclaimed by the OS upon termination of
799  // the process. The backing store file is deleted from the file system.
800
801  assert(!PerfDisableSharedMem, "shouldn't be here");
802
803  if (backing_store_file_name != NULL) {
804    remove_file(backing_store_file_name);
805    // Don't.. Free heap memory could deadlock os::abort() if it is called
806    // from signal handler. OS will reclaim the heap memory.
807    // FREE_C_HEAP_ARRAY(char, backing_store_file_name);
808    backing_store_file_name = NULL;
809  }
810}
811
812// return the size of the file for the given file descriptor
813// or 0 if it is not a valid size for a shared memory file
814//
815static size_t sharedmem_filesize(int fd, TRAPS) {
816
817  struct stat statbuf;
818  int result;
819
820  RESTARTABLE(::fstat(fd, &statbuf), result);
821  if (result == OS_ERR) {
822    if (PrintMiscellaneous && Verbose) {
823      warning("fstat failed: %s\n", strerror(errno));
824    }
825    THROW_MSG_0(vmSymbols::java_io_IOException(),
826                "Could not determine PerfMemory size");
827  }
828
829  if ((statbuf.st_size == 0) ||
830     ((size_t)statbuf.st_size % os::vm_page_size() != 0)) {
831    THROW_MSG_0(vmSymbols::java_lang_Exception(),
832                "Invalid PerfMemory size");
833  }
834
835  return (size_t)statbuf.st_size;
836}
837
838// attach to a named shared memory region.
839//
840static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
841
842  char* mapAddress;
843  int result;
844  int fd;
845  size_t size = 0;
846  const char* luser = NULL;
847
848  int mmap_prot;
849  int file_flags;
850
851  ResourceMark rm;
852
853  // map the high level access mode to the appropriate permission
854  // constructs for the file and the shared memory mapping.
855  if (mode == PerfMemory::PERF_MODE_RO) {
856    mmap_prot = PROT_READ;
857    file_flags = O_RDONLY;
858  }
859  else if (mode == PerfMemory::PERF_MODE_RW) {
860#ifdef LATER
861    mmap_prot = PROT_READ | PROT_WRITE;
862    file_flags = O_RDWR;
863#else
864    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
865              "Unsupported access mode");
866#endif
867  }
868  else {
869    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
870              "Illegal access mode");
871  }
872
873  if (user == NULL || strlen(user) == 0) {
874    luser = get_user_name(vmid, CHECK);
875  }
876  else {
877    luser = user;
878  }
879
880  if (luser == NULL) {
881    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
882              "Could not map vmid to user Name");
883  }
884
885  char* dirname = get_user_tmp_dir(luser);
886
887  // since we don't follow symbolic links when creating the backing
888  // store file, we don't follow them when attaching either.
889  //
890  if (!is_directory_secure(dirname)) {
891    FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
892    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
893              "Process not found");
894  }
895
896  char* filename = get_sharedmem_filename(dirname, vmid);
897
898  // copy heap memory to resource memory. the open_sharedmem_file
899  // method below need to use the filename, but could throw an
900  // exception. using a resource array prevents the leak that
901  // would otherwise occur.
902  char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
903  strcpy(rfilename, filename);
904
905  // free the c heap resources that are no longer needed
906  if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);
907  FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
908  FREE_C_HEAP_ARRAY(char, filename, mtInternal);
909
910  // open the shared memory file for the give vmid
911  fd = open_sharedmem_file(rfilename, file_flags, THREAD);
912
913  if (fd == OS_ERR) {
914    return;
915  }
916
917  if (HAS_PENDING_EXCEPTION) {
918    ::close(fd);
919    return;
920  }
921
922  if (*sizep == 0) {
923    size = sharedmem_filesize(fd, CHECK);
924  } else {
925    size = *sizep;
926  }
927
928  assert(size > 0, "unexpected size <= 0");
929
930  mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
931
932  result = ::close(fd);
933  assert(result != OS_ERR, "could not close file");
934
935  if (mapAddress == MAP_FAILED) {
936    if (PrintMiscellaneous && Verbose) {
937      warning("mmap failed: %s\n", strerror(errno));
938    }
939    THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
940              "Could not map PerfMemory");
941  }
942
943  // it does not go through os api, the operation has to record from here
944  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
945
946  *addr = mapAddress;
947  *sizep = size;
948
949  if (PerfTraceMemOps) {
950    tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
951               INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);
952  }
953}
954
955
956
957
958// create the PerfData memory region
959//
960// This method creates the memory region used to store performance
961// data for the JVM. The memory may be created in standard or
962// shared memory.
963//
964void PerfMemory::create_memory_region(size_t size) {
965
966  if (PerfDisableSharedMem) {
967    // do not share the memory for the performance data.
968    _start = create_standard_memory(size);
969  }
970  else {
971    _start = create_shared_memory(size);
972    if (_start == NULL) {
973
974      // creation of the shared memory region failed, attempt
975      // to create a contiguous, non-shared memory region instead.
976      //
977      if (PrintMiscellaneous && Verbose) {
978        warning("Reverting to non-shared PerfMemory region.\n");
979      }
980      PerfDisableSharedMem = true;
981      _start = create_standard_memory(size);
982    }
983  }
984
985  if (_start != NULL) _capacity = size;
986
987}
988
989// delete the PerfData memory region
990//
991// This method deletes the memory region used to store performance
992// data for the JVM. The memory region indicated by the <address, size>
993// tuple will be inaccessible after a call to this method.
994//
995void PerfMemory::delete_memory_region() {
996
997  assert((start() != NULL && capacity() > 0), "verify proper state");
998
999  // If user specifies PerfDataSaveFile, it will save the performance data
1000  // to the specified file name no matter whether PerfDataSaveToFile is specified
1001  // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1002  // -XX:+PerfDataSaveToFile.
1003  if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1004    save_memory_to_file(start(), capacity());
1005  }
1006
1007  if (PerfDisableSharedMem) {
1008    delete_standard_memory(start(), capacity());
1009  }
1010  else {
1011    delete_shared_memory(start(), capacity());
1012  }
1013}
1014
1015// attach to the PerfData memory region for another JVM
1016//
1017// This method returns an <address, size> tuple that points to
1018// a memory buffer that is kept reasonably synchronized with
1019// the PerfData memory region for the indicated JVM. This
1020// buffer may be kept in synchronization via shared memory
1021// or some other mechanism that keeps the buffer updated.
1022//
1023// If the JVM chooses not to support the attachability feature,
1024// this method should throw an UnsupportedOperation exception.
1025//
1026// This implementation utilizes named shared memory to map
1027// the indicated process's PerfData memory region into this JVMs
1028// address space.
1029//
1030void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
1031
1032  if (vmid == 0 || vmid == os::current_process_id()) {
1033     *addrp = start();
1034     *sizep = capacity();
1035     return;
1036  }
1037
1038  mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
1039}
1040
1041// detach from the PerfData memory region of another JVM
1042//
1043// This method detaches the PerfData memory region of another
1044// JVM, specified as an <address, size> tuple of a buffer
1045// in this process's address space. This method may perform
1046// arbitrary actions to accomplish the detachment. The memory
1047// region specified by <address, size> will be inaccessible after
1048// a call to this method.
1049//
1050// If the JVM chooses not to support the attachability feature,
1051// this method should throw an UnsupportedOperation exception.
1052//
1053// This implementation utilizes named shared memory to detach
1054// the indicated process's PerfData memory region from this
1055// process's address space.
1056//
1057void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
1058
1059  assert(addr != 0, "address sanity check");
1060  assert(bytes > 0, "capacity sanity check");
1061
1062  if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1063    // prevent accidental detachment of this process's PerfMemory region
1064    return;
1065  }
1066
1067  unmap_shared(addr, bytes);
1068}
1069
1070char* PerfMemory::backing_store_filename() {
1071  return backing_store_file_name;
1072}
1073