Wed, 27 Aug 2014 08:19:12 -0400
8046598: Scalable Native memory tracking development
Summary: Enhance scalability of native memory tracking
Reviewed-by: coleenp, ctornqvi, gtriantafill
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 */
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"
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>
48 static char* backing_store_file_name = NULL; // name of the backing store
49 // file, if successfully created.
51 // Standard Memory Implementation Details
53 // create the PerfData memory region in standard memory.
54 //
55 static char* create_standard_memory(size_t size) {
57 // allocate an aligned chuck of memory
58 char* mapAddress = os::reserve_memory(size);
60 if (mapAddress == NULL) {
61 return NULL;
62 }
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 }
73 return mapAddress;
74 }
76 // delete the PerfData memory region
77 //
78 static void delete_standard_memory(char* addr, size_t size) {
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 }
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 //
93 static void save_memory_to_file(char* addr, size_t size) {
95 const char* destfile = PerfMemory::get_perfdata_file_path();
96 assert(destfile[0] != '\0', "invalid PerfData file path");
98 int result;
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 {
109 int fd = result;
111 for (size_t remaining = size; remaining > 0;) {
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 }
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 }
136 // Shared Memory Implementation Details
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.
150 // return the user specific temporary directory name.
151 //
152 // the caller is expected to free the allocated memory.
153 //
154 static char* get_user_tmp_dir(const char* user) {
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);
161 // construct the path name to user specific tmp directory
162 snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);
164 return dirname;
165 }
167 // convert the given file name into a process id. if the file
168 // does not meet the file naming constraints, return 0.
169 //
170 static pid_t filename_to_pid(const char* filename) {
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 }
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);
186 if (errno != 0) {
187 return 0;
188 }
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 }
197 // successful conversion, return the pid
198 return pid;
199 }
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 //
207 static bool is_directory_secure(const char* path) {
208 struct stat statbuf;
209 int result = 0;
211 RESTARTABLE(::lstat(path, &statbuf), result);
212 if (result == OS_ERR) {
213 return false;
214 }
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 }
237 // return the user name for the given user id
238 //
239 // the caller is expected to free the allocated memory.
240 //
241 static char* get_user_name(uid_t uid) {
243 struct passwd pwent;
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;
252 char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
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
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 }
277 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);
278 strcpy(user_name, p->pw_name);
280 FREE_C_HEAP_ARRAY(char, pwbuf, mtInternal);
281 return user_name;
282 }
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 //
292 static char* get_user_name_slow(int vmid, TRAPS) {
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 }
305 // directory search
306 char* oldest_user = NULL;
307 time_t oldest_ctime = 0;
309 const char* tmpdirname = os::get_temp_directory();
311 DIR* tmpdirp = os::opendir(tmpdirname);
313 if (tmpdirp == NULL) {
314 return NULL;
315 }
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) {
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 }
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);
338 DIR* subdirp = os::opendir(usrdir_name);
340 if (subdirp == NULL) {
341 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
342 continue;
343 }
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 }
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) {
362 if (filename_to_pid(udentry->d_name) == vmid) {
363 struct stat statbuf;
364 int result;
366 char* filename = NEW_C_HEAP_ARRAY(char,
367 strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
369 strcpy(filename, usrdir_name);
370 strcat(filename, "/");
371 strcat(filename, udentry->d_name);
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 }
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 }
386 // compare and save filename with latest creation time
387 if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
389 if (statbuf.st_ctime > oldest_ctime) {
390 char* user = strchr(dentry->d_name, '_') + 1;
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);
395 strcpy(oldest_user, user);
396 oldest_ctime = statbuf.st_ctime;
397 }
398 }
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);
410 return(oldest_user);
411 }
413 // return the name of the user that owns the JVM indicated by the given vmid.
414 //
415 static char* get_user_name(int vmid, TRAPS) {
417 char psinfo_name[PATH_MAX];
418 int result;
420 snprintf(psinfo_name, PATH_MAX, "/proc/%d/psinfo", vmid);
422 RESTARTABLE(::open(psinfo_name, O_RDONLY), result);
424 if (result != OS_ERR) {
425 int fd = result;
427 psinfo_t psinfo;
428 char* addr = (char*)&psinfo;
430 for (size_t remaining = sizeof(psinfo_t); remaining > 0;) {
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 }
442 ::close(fd);
444 // get the user name for the effective user id of the process
445 char* user_name = get_user_name(psinfo.pr_euid);
447 return user_name;
448 }
450 if (result == OS_ERR && errno == EACCES) {
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 }
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.
464 return get_user_name_slow(vmid, CHECK_NULL);
465 }
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 //
472 static char* get_sharedmem_filename(const char* dirname, int vmid) {
474 // add 2 for the file separator and a NULL terminator.
475 size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
477 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
478 snprintf(name, nbytes, "%s/%d", dirname, vmid);
480 return name;
481 }
484 // remove file
485 //
486 // this method removes the file specified by the given path
487 //
488 static void remove_file(const char* path) {
490 int result;
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 }
507 // remove file
508 //
509 // this method removes the file with the given file name in the
510 // named directory.
511 //
512 static void remove_file(const char* dirname, const char* filename) {
514 size_t nbytes = strlen(dirname) + strlen(filename) + 2;
515 char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
517 strcpy(path, dirname);
518 strcat(path, "/");
519 strcat(path, filename);
521 remove_file(path);
523 FREE_C_HEAP_ARRAY(char, path, mtInternal);
524 }
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 //
536 static void cleanup_sharedmem_resources(const char* dirname) {
538 // open the user temp directory
539 DIR* dirp = os::opendir(dirname);
541 if (dirp == NULL) {
542 // directory doesn't exist, so there is nothing to cleanup
543 return;
544 }
546 if (!is_directory_secure(dirname)) {
547 // the directory is not a secure directory
548 return;
549 }
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) {
564 pid_t pid = filename_to_pid(entry->d_name);
566 if (pid == 0) {
568 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
570 // attempt to remove all unexpected files, except "." and ".."
571 remove_file(dirname, entry->d_name);
572 }
574 errno = 0;
575 continue;
576 }
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))) {
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 }
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 //
607 static bool make_user_tmp_dir(const char* dirname) {
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 }
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 //
646 static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
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 }
655 int result;
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 }
665 // save the file descriptor
666 int fd = result;
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 }
678 return fd;
679 }
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 //
685 static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
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 }
704 return result;
705 }
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 //
720 static char* mmap_create_shared(size_t size) {
722 int result;
723 int fd;
724 char* mapAddress;
726 int vmid = os::current_process_id();
728 char* user_name = get_user_name(geteuid());
730 if (user_name == NULL)
731 return NULL;
733 char* dirname = get_user_tmp_dir(user_name);
734 char* filename = get_sharedmem_filename(dirname, vmid);
736 // cleanup any stale shared memory files
737 cleanup_sharedmem_resources(dirname);
739 assert(((size > 0) && (size % os::vm_page_size() == 0)),
740 "unexpected PerfMemory region size");
742 fd = create_sharedmem_resources(dirname, filename, size);
744 FREE_C_HEAP_ARRAY(char, user_name, mtInternal);
745 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
747 if (fd == -1) {
748 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
749 return NULL;
750 }
752 mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
754 result = ::close(fd);
755 assert(result != OS_ERR, "could not close file");
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 }
766 // save the file name for use in delete_shared_memory()
767 backing_store_file_name = filename;
769 // clear the shared memory region
770 (void)::memset((void*) mapAddress, 0, size);
772 // it does not go through os api, the operation has to record from here
773 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,
774 size, CURRENT_PC, mtInternal);
776 return mapAddress;
777 }
779 // release a named shared memory region
780 //
781 static void unmap_shared(char* addr, size_t bytes) {
782 os::release_memory(addr, bytes);
783 }
785 // create the PerfData memory region in shared memory.
786 //
787 static char* create_shared_memory(size_t size) {
789 // create the shared memory region.
790 return mmap_create_shared(size);
791 }
793 // delete the shared PerfData memory region
794 //
795 static void delete_shared_memory(char* addr, size_t size) {
797 // cleanup the persistent shared memory resources. since DestroyJavaVM does
798 // not support unloading of the JVM, unmapping of the memory resource is
799 // not performed. The memory will be reclaimed by the OS upon termination of
800 // the process. The backing store file is deleted from the file system.
802 assert(!PerfDisableSharedMem, "shouldn't be here");
804 if (backing_store_file_name != NULL) {
805 remove_file(backing_store_file_name);
806 // Don't.. Free heap memory could deadlock os::abort() if it is called
807 // from signal handler. OS will reclaim the heap memory.
808 // FREE_C_HEAP_ARRAY(char, backing_store_file_name);
809 backing_store_file_name = NULL;
810 }
811 }
813 // return the size of the file for the given file descriptor
814 // or 0 if it is not a valid size for a shared memory file
815 //
816 static size_t sharedmem_filesize(int fd, TRAPS) {
818 struct stat statbuf;
819 int result;
821 RESTARTABLE(::fstat(fd, &statbuf), result);
822 if (result == OS_ERR) {
823 if (PrintMiscellaneous && Verbose) {
824 warning("fstat failed: %s\n", strerror(errno));
825 }
826 THROW_MSG_0(vmSymbols::java_io_IOException(),
827 "Could not determine PerfMemory size");
828 }
830 if ((statbuf.st_size == 0) ||
831 ((size_t)statbuf.st_size % os::vm_page_size() != 0)) {
832 THROW_MSG_0(vmSymbols::java_lang_Exception(),
833 "Invalid PerfMemory size");
834 }
836 return (size_t)statbuf.st_size;
837 }
839 // attach to a named shared memory region.
840 //
841 static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
843 char* mapAddress;
844 int result;
845 int fd;
846 size_t size = 0;
847 const char* luser = NULL;
849 int mmap_prot;
850 int file_flags;
852 ResourceMark rm;
854 // map the high level access mode to the appropriate permission
855 // constructs for the file and the shared memory mapping.
856 if (mode == PerfMemory::PERF_MODE_RO) {
857 mmap_prot = PROT_READ;
858 file_flags = O_RDONLY;
859 }
860 else if (mode == PerfMemory::PERF_MODE_RW) {
861 #ifdef LATER
862 mmap_prot = PROT_READ | PROT_WRITE;
863 file_flags = O_RDWR;
864 #else
865 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
866 "Unsupported access mode");
867 #endif
868 }
869 else {
870 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
871 "Illegal access mode");
872 }
874 if (user == NULL || strlen(user) == 0) {
875 luser = get_user_name(vmid, CHECK);
876 }
877 else {
878 luser = user;
879 }
881 if (luser == NULL) {
882 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
883 "Could not map vmid to user Name");
884 }
886 char* dirname = get_user_tmp_dir(luser);
888 // since we don't follow symbolic links when creating the backing
889 // store file, we don't follow them when attaching either.
890 //
891 if (!is_directory_secure(dirname)) {
892 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
893 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
894 "Process not found");
895 }
897 char* filename = get_sharedmem_filename(dirname, vmid);
899 // copy heap memory to resource memory. the open_sharedmem_file
900 // method below need to use the filename, but could throw an
901 // exception. using a resource array prevents the leak that
902 // would otherwise occur.
903 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
904 strcpy(rfilename, filename);
906 // free the c heap resources that are no longer needed
907 if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);
908 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
909 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
911 // open the shared memory file for the give vmid
912 fd = open_sharedmem_file(rfilename, file_flags, THREAD);
914 if (fd == OS_ERR) {
915 return;
916 }
918 if (HAS_PENDING_EXCEPTION) {
919 ::close(fd);
920 return;
921 }
923 if (*sizep == 0) {
924 size = sharedmem_filesize(fd, CHECK);
925 } else {
926 size = *sizep;
927 }
929 assert(size > 0, "unexpected size <= 0");
931 mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
933 result = ::close(fd);
934 assert(result != OS_ERR, "could not close file");
936 if (mapAddress == MAP_FAILED) {
937 if (PrintMiscellaneous && Verbose) {
938 warning("mmap failed: %s\n", strerror(errno));
939 }
940 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
941 "Could not map PerfMemory");
942 }
944 // it does not go through os api, the operation has to record from here
945 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,
946 size, CURRENT_PC, mtInternal);
948 *addr = mapAddress;
949 *sizep = size;
951 if (PerfTraceMemOps) {
952 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
953 INTPTR_FORMAT "\n", size, vmid, (void*)mapAddress);
954 }
955 }
960 // create the PerfData memory region
961 //
962 // This method creates the memory region used to store performance
963 // data for the JVM. The memory may be created in standard or
964 // shared memory.
965 //
966 void PerfMemory::create_memory_region(size_t size) {
968 if (PerfDisableSharedMem) {
969 // do not share the memory for the performance data.
970 _start = create_standard_memory(size);
971 }
972 else {
973 _start = create_shared_memory(size);
974 if (_start == NULL) {
976 // creation of the shared memory region failed, attempt
977 // to create a contiguous, non-shared memory region instead.
978 //
979 if (PrintMiscellaneous && Verbose) {
980 warning("Reverting to non-shared PerfMemory region.\n");
981 }
982 PerfDisableSharedMem = true;
983 _start = create_standard_memory(size);
984 }
985 }
987 if (_start != NULL) _capacity = size;
989 }
991 // delete the PerfData memory region
992 //
993 // This method deletes the memory region used to store performance
994 // data for the JVM. The memory region indicated by the <address, size>
995 // tuple will be inaccessible after a call to this method.
996 //
997 void PerfMemory::delete_memory_region() {
999 assert((start() != NULL && capacity() > 0), "verify proper state");
1001 // If user specifies PerfDataSaveFile, it will save the performance data
1002 // to the specified file name no matter whether PerfDataSaveToFile is specified
1003 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1004 // -XX:+PerfDataSaveToFile.
1005 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1006 save_memory_to_file(start(), capacity());
1007 }
1009 if (PerfDisableSharedMem) {
1010 delete_standard_memory(start(), capacity());
1011 }
1012 else {
1013 delete_shared_memory(start(), capacity());
1014 }
1015 }
1017 // attach to the PerfData memory region for another JVM
1018 //
1019 // This method returns an <address, size> tuple that points to
1020 // a memory buffer that is kept reasonably synchronized with
1021 // the PerfData memory region for the indicated JVM. This
1022 // buffer may be kept in synchronization via shared memory
1023 // or some other mechanism that keeps the buffer updated.
1024 //
1025 // If the JVM chooses not to support the attachability feature,
1026 // this method should throw an UnsupportedOperation exception.
1027 //
1028 // This implementation utilizes named shared memory to map
1029 // the indicated process's PerfData memory region into this JVMs
1030 // address space.
1031 //
1032 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
1034 if (vmid == 0 || vmid == os::current_process_id()) {
1035 *addrp = start();
1036 *sizep = capacity();
1037 return;
1038 }
1040 mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
1041 }
1043 // detach from the PerfData memory region of another JVM
1044 //
1045 // This method detaches the PerfData memory region of another
1046 // JVM, specified as an <address, size> tuple of a buffer
1047 // in this process's address space. This method may perform
1048 // arbitrary actions to accomplish the detachment. The memory
1049 // region specified by <address, size> will be inaccessible after
1050 // a call to this method.
1051 //
1052 // If the JVM chooses not to support the attachability feature,
1053 // this method should throw an UnsupportedOperation exception.
1054 //
1055 // This implementation utilizes named shared memory to detach
1056 // the indicated process's PerfData memory region from this
1057 // process's address space.
1058 //
1059 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
1061 assert(addr != 0, "address sanity check");
1062 assert(bytes > 0, "capacity sanity check");
1064 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1065 // prevent accidental detachment of this process's PerfMemory region
1066 return;
1067 }
1069 unmap_shared(addr, bytes);
1070 }
1072 char* PerfMemory::backing_store_filename() {
1073 return backing_store_file_name;
1074 }