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_windows.inline.hpp"
31 #include "runtime/handles.inline.hpp"
32 #include "runtime/perfMemory.hpp"
33 #include "services/memTracker.hpp"
34 #include "utilities/exceptions.hpp"
36 #include <windows.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <errno.h>
40 #include <lmcons.h>
42 typedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)(
43 IN PSECURITY_DESCRIPTOR pSecurityDescriptor,
44 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
45 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet);
47 // Standard Memory Implementation Details
49 // create the PerfData memory region in standard memory.
50 //
51 static char* create_standard_memory(size_t size) {
53 // allocate an aligned chuck of memory
54 char* mapAddress = os::reserve_memory(size);
56 if (mapAddress == NULL) {
57 return NULL;
58 }
60 // commit memory
61 if (!os::commit_memory(mapAddress, size, !ExecMem)) {
62 if (PrintMiscellaneous && Verbose) {
63 warning("Could not commit PerfData memory\n");
64 }
65 os::release_memory(mapAddress, size);
66 return NULL;
67 }
69 return mapAddress;
70 }
72 // delete the PerfData memory region
73 //
74 static void delete_standard_memory(char* addr, size_t size) {
76 // there are no persistent external resources to cleanup for standard
77 // memory. since DestroyJavaVM does not support unloading of the JVM,
78 // cleanup of the memory resource is not performed. The memory will be
79 // reclaimed by the OS upon termination of the process.
80 //
81 return;
83 }
85 // save the specified memory region to the given file
86 //
87 static void save_memory_to_file(char* addr, size_t size) {
89 const char* destfile = PerfMemory::get_perfdata_file_path();
90 assert(destfile[0] != '\0', "invalid Perfdata file path");
92 int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC,
93 _S_IREAD|_S_IWRITE);
95 if (fd == OS_ERR) {
96 if (PrintMiscellaneous && Verbose) {
97 warning("Could not create Perfdata save file: %s: %s\n",
98 destfile, strerror(errno));
99 }
100 } else {
101 for (size_t remaining = size; remaining > 0;) {
103 int nbytes = ::_write(fd, addr, (unsigned int)remaining);
104 if (nbytes == OS_ERR) {
105 if (PrintMiscellaneous && Verbose) {
106 warning("Could not write Perfdata save file: %s: %s\n",
107 destfile, strerror(errno));
108 }
109 break;
110 }
112 remaining -= (size_t)nbytes;
113 addr += nbytes;
114 }
116 int result = ::_close(fd);
117 if (PrintMiscellaneous && Verbose) {
118 if (result == OS_ERR) {
119 warning("Could not close %s: %s\n", destfile, strerror(errno));
120 }
121 }
122 }
124 FREE_C_HEAP_ARRAY(char, destfile, mtInternal);
125 }
127 // Shared Memory Implementation Details
129 // Note: the win32 shared memory implementation uses two objects to represent
130 // the shared memory: a windows kernel based file mapping object and a backing
131 // store file. On windows, the name space for shared memory is a kernel
132 // based name space that is disjoint from other win32 name spaces. Since Java
133 // is unaware of this name space, a parallel file system based name space is
134 // maintained, which provides a common file system based shared memory name
135 // space across the supported platforms and one that Java apps can deal with
136 // through simple file apis.
137 //
138 // For performance and resource cleanup reasons, it is recommended that the
139 // user specific directory and the backing store file be stored in either a
140 // RAM based file system or a local disk based file system. Network based
141 // file systems are not recommended for performance reasons. In addition,
142 // use of SMB network based file systems may result in unsuccesful cleanup
143 // of the disk based resource on exit of the VM. The Windows TMP and TEMP
144 // environement variables, as used by the GetTempPath() Win32 API (see
145 // os::get_temp_directory() in os_win32.cpp), control the location of the
146 // user specific directory and the shared memory backing store file.
148 static HANDLE sharedmem_fileMapHandle = NULL;
149 static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE;
150 static char* sharedmem_fileName = NULL;
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) {
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);
163 // construct the path name to user specific tmp directory
164 _snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user);
166 return dirname;
167 }
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 int filename_to_pid(const char* filename) {
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 }
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 int pid = (int)strtol(filename, &remainder, 10);
188 if (errno != 0) {
189 return 0;
190 }
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 }
199 // successful conversion, return the pid
200 return pid;
201 }
203 // check if the given path is considered a secure directory for
204 // the backing store files. Returns true if the directory exists
205 // and is considered a secure location. Returns false if the path
206 // is a symbolic link or if an error occurred.
207 //
208 static bool is_directory_secure(const char* path) {
210 DWORD fa;
212 fa = GetFileAttributes(path);
213 if (fa == 0xFFFFFFFF) {
214 DWORD lasterror = GetLastError();
215 if (lasterror == ERROR_FILE_NOT_FOUND) {
216 return false;
217 }
218 else {
219 // unexpected error, declare the path insecure
220 if (PrintMiscellaneous && Verbose) {
221 warning("could not get attributes for file %s: ",
222 " lasterror = %d\n", path, lasterror);
223 }
224 return false;
225 }
226 }
228 if (fa & FILE_ATTRIBUTE_REPARSE_POINT) {
229 // we don't accept any redirection for the user specific directory
230 // so declare the path insecure. This may be too conservative,
231 // as some types of reparse points might be acceptable, but it
232 // is probably more secure to avoid these conditions.
233 //
234 if (PrintMiscellaneous && Verbose) {
235 warning("%s is a reparse point\n", path);
236 }
237 return false;
238 }
240 if (fa & FILE_ATTRIBUTE_DIRECTORY) {
241 // this is the expected case. Since windows supports symbolic
242 // links to directories only, not to files, there is no need
243 // to check for open write permissions on the directory. If the
244 // directory has open write permissions, any files deposited that
245 // are not expected will be removed by the cleanup code.
246 //
247 return true;
248 }
249 else {
250 // this is either a regular file or some other type of file,
251 // any of which are unexpected and therefore insecure.
252 //
253 if (PrintMiscellaneous && Verbose) {
254 warning("%s is not a directory, file attributes = "
255 INTPTR_FORMAT "\n", path, fa);
256 }
257 return false;
258 }
259 }
261 // return the user name for the owner of this process
262 //
263 // the caller is expected to free the allocated memory.
264 //
265 static char* get_user_name() {
267 /* get the user name. This code is adapted from code found in
268 * the jdk in src/windows/native/java/lang/java_props_md.c
269 * java_props_md.c 1.29 02/02/06. According to the original
270 * source, the call to GetUserName is avoided because of a resulting
271 * increase in footprint of 100K.
272 */
273 char* user = getenv("USERNAME");
274 char buf[UNLEN+1];
275 DWORD buflen = sizeof(buf);
276 if (user == NULL || strlen(user) == 0) {
277 if (GetUserName(buf, &buflen)) {
278 user = buf;
279 }
280 else {
281 return NULL;
282 }
283 }
285 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
286 strcpy(user_name, user);
288 return user_name;
289 }
291 // return the name of the user that owns the process identified by vmid.
292 //
293 // This method uses a slow directory search algorithm to find the backing
294 // store file for the specified vmid and returns the user name, as determined
295 // by the user name suffix of the hsperfdata_<username> directory name.
296 //
297 // the caller is expected to free the allocated memory.
298 //
299 static char* get_user_name_slow(int vmid) {
301 // directory search
302 char* latest_user = NULL;
303 time_t latest_ctime = 0;
305 const char* tmpdirname = os::get_temp_directory();
307 DIR* tmpdirp = os::opendir(tmpdirname);
309 if (tmpdirp == NULL) {
310 return NULL;
311 }
313 // for each entry in the directory that matches the pattern hsperfdata_*,
314 // open the directory and check if the file for the given vmid exists.
315 // The file with the expected name and the latest creation date is used
316 // to determine the user name for the process id.
317 //
318 struct dirent* dentry;
319 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal);
320 errno = 0;
321 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
323 // check if the directory entry is a hsperfdata file
324 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
325 continue;
326 }
328 char* usrdir_name = NEW_C_HEAP_ARRAY(char,
329 strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);
330 strcpy(usrdir_name, tmpdirname);
331 strcat(usrdir_name, "\\");
332 strcat(usrdir_name, dentry->d_name);
334 DIR* subdirp = os::opendir(usrdir_name);
336 if (subdirp == NULL) {
337 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
338 continue;
339 }
341 // Since we don't create the backing store files in directories
342 // pointed to by symbolic links, we also don't follow them when
343 // looking for the files. We check for a symbolic link after the
344 // call to opendir in order to eliminate a small window where the
345 // symlink can be exploited.
346 //
347 if (!is_directory_secure(usrdir_name)) {
348 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
349 os::closedir(subdirp);
350 continue;
351 }
353 struct dirent* udentry;
354 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal);
355 errno = 0;
356 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
358 if (filename_to_pid(udentry->d_name) == vmid) {
359 struct stat statbuf;
361 char* filename = NEW_C_HEAP_ARRAY(char,
362 strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
364 strcpy(filename, usrdir_name);
365 strcat(filename, "\\");
366 strcat(filename, udentry->d_name);
368 if (::stat(filename, &statbuf) == OS_ERR) {
369 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
370 continue;
371 }
373 // skip over files that are not regular files.
374 if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
375 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
376 continue;
377 }
379 // If we found a matching file with a newer creation time, then
380 // save the user name. The newer creation time indicates that
381 // we found a newer incarnation of the process associated with
382 // vmid. Due to the way that Windows recycles pids and the fact
383 // that we can't delete the file from the file system namespace
384 // until last close, it is possible for there to be more than
385 // one hsperfdata file with a name matching vmid (diff users).
386 //
387 // We no longer ignore hsperfdata files where (st_size == 0).
388 // In this function, all we're trying to do is determine the
389 // name of the user that owns the process associated with vmid
390 // so the size doesn't matter. Very rarely, we have observed
391 // hsperfdata files where (st_size == 0) and the st_size field
392 // later becomes the expected value.
393 //
394 if (statbuf.st_ctime > latest_ctime) {
395 char* user = strchr(dentry->d_name, '_') + 1;
397 if (latest_user != NULL) FREE_C_HEAP_ARRAY(char, latest_user, mtInternal);
398 latest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
400 strcpy(latest_user, user);
401 latest_ctime = statbuf.st_ctime;
402 }
404 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
405 }
406 }
407 os::closedir(subdirp);
408 FREE_C_HEAP_ARRAY(char, udbuf, mtInternal);
409 FREE_C_HEAP_ARRAY(char, usrdir_name, mtInternal);
410 }
411 os::closedir(tmpdirp);
412 FREE_C_HEAP_ARRAY(char, tdbuf, mtInternal);
414 return(latest_user);
415 }
417 // return the name of the user that owns the process identified by vmid.
418 //
419 // note: this method should only be used via the Perf native methods.
420 // There are various costs to this method and limiting its use to the
421 // Perf native methods limits the impact to monitoring applications only.
422 //
423 static char* get_user_name(int vmid) {
425 // A fast implementation is not provided at this time. It's possible
426 // to provide a fast process id to user name mapping function using
427 // the win32 apis, but the default ACL for the process object only
428 // allows processes with the same owner SID to acquire the process
429 // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible
430 // to have the JVM change the ACL for the process object to allow arbitrary
431 // users to access the process handle and the process security token.
432 // The security ramifications need to be studied before providing this
433 // mechanism.
434 //
435 return get_user_name_slow(vmid);
436 }
438 // return the name of the shared memory file mapping object for the
439 // named shared memory region for the given user name and vmid.
440 //
441 // The file mapping object's name is not the file name. It is a name
442 // in a separate name space.
443 //
444 // the caller is expected to free the allocated memory.
445 //
446 static char *get_sharedmem_objectname(const char* user, int vmid) {
448 // construct file mapping object's name, add 3 for two '_' and a
449 // null terminator.
450 int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3;
452 // the id is converted to an unsigned value here because win32 allows
453 // negative process ids. However, OpenFileMapping API complains
454 // about a name containing a '-' characters.
455 //
456 nbytes += UINT_CHARS;
457 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
458 _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid);
460 return name;
461 }
463 // return the file name of the backing store file for the named
464 // shared memory region for the given user name and vmid.
465 //
466 // the caller is expected to free the allocated memory.
467 //
468 static char* get_sharedmem_filename(const char* dirname, int vmid) {
470 // add 2 for the file separator and a null terminator.
471 size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
473 char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
474 _snprintf(name, nbytes, "%s\\%d", dirname, vmid);
476 return name;
477 }
479 // remove file
480 //
481 // this method removes the file with the given file name.
482 //
483 // Note: if the indicated file is on an SMB network file system, this
484 // method may be unsuccessful in removing the file.
485 //
486 static void remove_file(const char* dirname, const char* filename) {
488 size_t nbytes = strlen(dirname) + strlen(filename) + 2;
489 char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
491 strcpy(path, dirname);
492 strcat(path, "\\");
493 strcat(path, filename);
495 if (::unlink(path) == OS_ERR) {
496 if (PrintMiscellaneous && Verbose) {
497 if (errno != ENOENT) {
498 warning("Could not unlink shared memory backing"
499 " store file %s : %s\n", path, strerror(errno));
500 }
501 }
502 }
504 FREE_C_HEAP_ARRAY(char, path, mtInternal);
505 }
507 // returns true if the process represented by pid is alive, otherwise
508 // returns false. the validity of the result is only accurate if the
509 // target process is owned by the same principal that owns this process.
510 // this method should not be used if to test the status of an otherwise
511 // arbitrary process unless it is know that this process has the appropriate
512 // privileges to guarantee a result valid.
513 //
514 static bool is_alive(int pid) {
516 HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
517 if (ph == NULL) {
518 // the process does not exist.
519 if (PrintMiscellaneous && Verbose) {
520 DWORD lastError = GetLastError();
521 if (lastError != ERROR_INVALID_PARAMETER) {
522 warning("OpenProcess failed: %d\n", GetLastError());
523 }
524 }
525 return false;
526 }
528 DWORD exit_status;
529 if (!GetExitCodeProcess(ph, &exit_status)) {
530 if (PrintMiscellaneous && Verbose) {
531 warning("GetExitCodeProcess failed: %d\n", GetLastError());
532 }
533 CloseHandle(ph);
534 return false;
535 }
537 CloseHandle(ph);
538 return (exit_status == STILL_ACTIVE) ? true : false;
539 }
541 // check if the file system is considered secure for the backing store files
542 //
543 static bool is_filesystem_secure(const char* path) {
545 char root_path[MAX_PATH];
546 char fs_type[MAX_PATH];
548 if (PerfBypassFileSystemCheck) {
549 if (PrintMiscellaneous && Verbose) {
550 warning("bypassing file system criteria checks for %s\n", path);
551 }
552 return true;
553 }
555 char* first_colon = strchr((char *)path, ':');
556 if (first_colon == NULL) {
557 if (PrintMiscellaneous && Verbose) {
558 warning("expected device specifier in path: %s\n", path);
559 }
560 return false;
561 }
563 size_t len = (size_t)(first_colon - path);
564 assert(len + 2 <= MAX_PATH, "unexpected device specifier length");
565 strncpy(root_path, path, len + 1);
566 root_path[len + 1] = '\\';
567 root_path[len + 2] = '\0';
569 // check that we have something like "C:\" or "AA:\"
570 assert(strlen(root_path) >= 3, "device specifier too short");
571 assert(strchr(root_path, ':') != NULL, "bad device specifier format");
572 assert(strchr(root_path, '\\') != NULL, "bad device specifier format");
574 DWORD maxpath;
575 DWORD flags;
577 if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath,
578 &flags, fs_type, MAX_PATH)) {
579 // we can't get information about the volume, so assume unsafe.
580 if (PrintMiscellaneous && Verbose) {
581 warning("could not get device information for %s: "
582 " path = %s: lasterror = %d\n",
583 root_path, path, GetLastError());
584 }
585 return false;
586 }
588 if ((flags & FS_PERSISTENT_ACLS) == 0) {
589 // file system doesn't support ACLs, declare file system unsafe
590 if (PrintMiscellaneous && Verbose) {
591 warning("file system type %s on device %s does not support"
592 " ACLs\n", fs_type, root_path);
593 }
594 return false;
595 }
597 if ((flags & FS_VOL_IS_COMPRESSED) != 0) {
598 // file system is compressed, declare file system unsafe
599 if (PrintMiscellaneous && Verbose) {
600 warning("file system type %s on device %s is compressed\n",
601 fs_type, root_path);
602 }
603 return false;
604 }
606 return true;
607 }
609 // cleanup stale shared memory resources
610 //
611 // This method attempts to remove all stale shared memory files in
612 // the named user temporary directory. It scans the named directory
613 // for files matching the pattern ^$[0-9]*$. For each file found, the
614 // process id is extracted from the file name and a test is run to
615 // determine if the process is alive. If the process is not alive,
616 // any stale file resources are removed.
617 //
618 static void cleanup_sharedmem_resources(const char* dirname) {
620 // open the user temp directory
621 DIR* dirp = os::opendir(dirname);
623 if (dirp == NULL) {
624 // directory doesn't exist, so there is nothing to cleanup
625 return;
626 }
628 if (!is_directory_secure(dirname)) {
629 // the directory is not secure, don't attempt any cleanup
630 return;
631 }
633 // for each entry in the directory that matches the expected file
634 // name pattern, determine if the file resources are stale and if
635 // so, remove the file resources. Note, instrumented HotSpot processes
636 // for this user may start and/or terminate during this search and
637 // remove or create new files in this directory. The behavior of this
638 // loop under these conditions is dependent upon the implementation of
639 // opendir/readdir.
640 //
641 struct dirent* entry;
642 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
643 errno = 0;
644 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
646 int pid = filename_to_pid(entry->d_name);
648 if (pid == 0) {
650 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
652 // attempt to remove all unexpected files, except "." and ".."
653 remove_file(dirname, entry->d_name);
654 }
656 errno = 0;
657 continue;
658 }
660 // we now have a file name that converts to a valid integer
661 // that could represent a process id . if this process id
662 // matches the current process id or the process is not running,
663 // then remove the stale file resources.
664 //
665 // process liveness is detected by checking the exit status
666 // of the process. if the process id is valid and the exit status
667 // indicates that it is still running, the file file resources
668 // are not removed. If the process id is invalid, or if we don't
669 // have permissions to check the process status, or if the process
670 // id is valid and the process has terminated, the the file resources
671 // are assumed to be stale and are removed.
672 //
673 if (pid == os::current_process_id() || !is_alive(pid)) {
675 // we can only remove the file resources. Any mapped views
676 // of the file can only be unmapped by the processes that
677 // opened those views and the file mapping object will not
678 // get removed until all views are unmapped.
679 //
680 remove_file(dirname, entry->d_name);
681 }
682 errno = 0;
683 }
684 os::closedir(dirp);
685 FREE_C_HEAP_ARRAY(char, dbuf, mtInternal);
686 }
688 // create a file mapping object with the requested name, and size
689 // from the file represented by the given Handle object
690 //
691 static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) {
693 DWORD lowSize = (DWORD)size;
694 DWORD highSize = 0;
695 HANDLE fmh = NULL;
697 // Create a file mapping object with the given name. This function
698 // will grow the file to the specified size.
699 //
700 fmh = CreateFileMapping(
701 fh, /* HANDLE file handle for backing store */
702 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */
703 PAGE_READWRITE, /* DWORD protections */
704 highSize, /* DWORD High word of max size */
705 lowSize, /* DWORD Low word of max size */
706 name); /* LPCTSTR name for object */
708 if (fmh == NULL) {
709 if (PrintMiscellaneous && Verbose) {
710 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError());
711 }
712 return NULL;
713 }
715 if (GetLastError() == ERROR_ALREADY_EXISTS) {
717 // a stale file mapping object was encountered. This object may be
718 // owned by this or some other user and cannot be removed until
719 // the other processes either exit or close their mapping objects
720 // and/or mapped views of this mapping object.
721 //
722 if (PrintMiscellaneous && Verbose) {
723 warning("file mapping already exists, lasterror = %d\n", GetLastError());
724 }
726 CloseHandle(fmh);
727 return NULL;
728 }
730 return fmh;
731 }
734 // method to free the given security descriptor and the contained
735 // access control list.
736 //
737 static void free_security_desc(PSECURITY_DESCRIPTOR pSD) {
739 BOOL success, exists, isdefault;
740 PACL pACL;
742 if (pSD != NULL) {
744 // get the access control list from the security descriptor
745 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault);
747 // if an ACL existed and it was not a default acl, then it must
748 // be an ACL we enlisted. free the resources.
749 //
750 if (success && exists && pACL != NULL && !isdefault) {
751 FREE_C_HEAP_ARRAY(char, pACL, mtInternal);
752 }
754 // free the security descriptor
755 FREE_C_HEAP_ARRAY(char, pSD, mtInternal);
756 }
757 }
759 // method to free up a security attributes structure and any
760 // contained security descriptors and ACL
761 //
762 static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) {
764 if (lpSA != NULL) {
765 // free the contained security descriptor and the ACL
766 free_security_desc(lpSA->lpSecurityDescriptor);
767 lpSA->lpSecurityDescriptor = NULL;
769 // free the security attributes structure
770 FREE_C_HEAP_ARRAY(char, lpSA, mtInternal);
771 }
772 }
774 // get the user SID for the process indicated by the process handle
775 //
776 static PSID get_user_sid(HANDLE hProcess) {
778 HANDLE hAccessToken;
779 PTOKEN_USER token_buf = NULL;
780 DWORD rsize = 0;
782 if (hProcess == NULL) {
783 return NULL;
784 }
786 // get the process token
787 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) {
788 if (PrintMiscellaneous && Verbose) {
789 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError());
790 }
791 return NULL;
792 }
794 // determine the size of the token structured needed to retrieve
795 // the user token information from the access token.
796 //
797 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) {
798 DWORD lasterror = GetLastError();
799 if (lasterror != ERROR_INSUFFICIENT_BUFFER) {
800 if (PrintMiscellaneous && Verbose) {
801 warning("GetTokenInformation failure: lasterror = %d,"
802 " rsize = %d\n", lasterror, rsize);
803 }
804 CloseHandle(hAccessToken);
805 return NULL;
806 }
807 }
809 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal);
811 // get the user token information
812 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) {
813 if (PrintMiscellaneous && Verbose) {
814 warning("GetTokenInformation failure: lasterror = %d,"
815 " rsize = %d\n", GetLastError(), rsize);
816 }
817 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal);
818 CloseHandle(hAccessToken);
819 return NULL;
820 }
822 DWORD nbytes = GetLengthSid(token_buf->User.Sid);
823 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
825 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) {
826 if (PrintMiscellaneous && Verbose) {
827 warning("GetTokenInformation failure: lasterror = %d,"
828 " rsize = %d\n", GetLastError(), rsize);
829 }
830 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal);
831 FREE_C_HEAP_ARRAY(char, pSID, mtInternal);
832 CloseHandle(hAccessToken);
833 return NULL;
834 }
836 // close the access token.
837 CloseHandle(hAccessToken);
838 FREE_C_HEAP_ARRAY(char, token_buf, mtInternal);
840 return pSID;
841 }
843 // structure used to consolidate access control entry information
844 //
845 typedef struct ace_data {
846 PSID pSid; // SID of the ACE
847 DWORD mask; // mask for the ACE
848 } ace_data_t;
851 // method to add an allow access control entry with the access rights
852 // indicated in mask for the principal indicated in SID to the given
853 // security descriptor. Much of the DACL handling was adapted from
854 // the example provided here:
855 // http://support.microsoft.com/kb/102102/EN-US/
856 //
858 static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD,
859 ace_data_t aces[], int ace_count) {
860 PACL newACL = NULL;
861 PACL oldACL = NULL;
863 if (pSD == NULL) {
864 return false;
865 }
867 BOOL exists, isdefault;
869 // retrieve any existing access control list.
870 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) {
871 if (PrintMiscellaneous && Verbose) {
872 warning("GetSecurityDescriptor failure: lasterror = %d \n",
873 GetLastError());
874 }
875 return false;
876 }
878 // get the size of the DACL
879 ACL_SIZE_INFORMATION aclinfo;
881 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent)
882 // while oldACL is NULL for some case.
883 if (oldACL == NULL) {
884 exists = FALSE;
885 }
887 if (exists) {
888 if (!GetAclInformation(oldACL, &aclinfo,
889 sizeof(ACL_SIZE_INFORMATION),
890 AclSizeInformation)) {
891 if (PrintMiscellaneous && Verbose) {
892 warning("GetAclInformation failure: lasterror = %d \n", GetLastError());
893 return false;
894 }
895 }
896 } else {
897 aclinfo.AceCount = 0; // assume NULL DACL
898 aclinfo.AclBytesFree = 0;
899 aclinfo.AclBytesInUse = sizeof(ACL);
900 }
902 // compute the size needed for the new ACL
903 // initial size of ACL is sum of the following:
904 // * size of ACL structure.
905 // * size of each ACE structure that ACL is to contain minus the sid
906 // sidStart member (DWORD) of the ACE.
907 // * length of the SID that each ACE is to contain.
908 DWORD newACLsize = aclinfo.AclBytesInUse +
909 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count;
910 for (int i = 0; i < ace_count; i++) {
911 assert(aces[i].pSid != 0, "pSid should not be 0");
912 newACLsize += GetLengthSid(aces[i].pSid);
913 }
915 // create the new ACL
916 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal);
918 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) {
919 if (PrintMiscellaneous && Verbose) {
920 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
921 }
922 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
923 return false;
924 }
926 unsigned int ace_index = 0;
927 // copy any existing ACEs from the old ACL (if any) to the new ACL.
928 if (aclinfo.AceCount != 0) {
929 while (ace_index < aclinfo.AceCount) {
930 LPVOID ace;
931 if (!GetAce(oldACL, ace_index, &ace)) {
932 if (PrintMiscellaneous && Verbose) {
933 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
934 }
935 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
936 return false;
937 }
938 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) {
939 // this is an inherited, allowed ACE; break from loop so we can
940 // add the new access allowed, non-inherited ACE in the correct
941 // position, immediately following all non-inherited ACEs.
942 break;
943 }
945 // determine if the SID of this ACE matches any of the SIDs
946 // for which we plan to set ACEs.
947 int matches = 0;
948 for (int i = 0; i < ace_count; i++) {
949 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) {
950 matches++;
951 break;
952 }
953 }
955 // if there are no SID matches, then add this existing ACE to the new ACL
956 if (matches == 0) {
957 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
958 ((PACE_HEADER)ace)->AceSize)) {
959 if (PrintMiscellaneous && Verbose) {
960 warning("AddAce failure: lasterror = %d \n", GetLastError());
961 }
962 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
963 return false;
964 }
965 }
966 ace_index++;
967 }
968 }
970 // add the passed-in access control entries to the new ACL
971 for (int i = 0; i < ace_count; i++) {
972 if (!AddAccessAllowedAce(newACL, ACL_REVISION,
973 aces[i].mask, aces[i].pSid)) {
974 if (PrintMiscellaneous && Verbose) {
975 warning("AddAccessAllowedAce failure: lasterror = %d \n",
976 GetLastError());
977 }
978 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
979 return false;
980 }
981 }
983 // now copy the rest of the inherited ACEs from the old ACL
984 if (aclinfo.AceCount != 0) {
985 // picking up at ace_index, where we left off in the
986 // previous ace_index loop
987 while (ace_index < aclinfo.AceCount) {
988 LPVOID ace;
989 if (!GetAce(oldACL, ace_index, &ace)) {
990 if (PrintMiscellaneous && Verbose) {
991 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
992 }
993 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
994 return false;
995 }
996 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
997 ((PACE_HEADER)ace)->AceSize)) {
998 if (PrintMiscellaneous && Verbose) {
999 warning("AddAce failure: lasterror = %d \n", GetLastError());
1000 }
1001 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
1002 return false;
1003 }
1004 ace_index++;
1005 }
1006 }
1008 // add the new ACL to the security descriptor.
1009 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) {
1010 if (PrintMiscellaneous && Verbose) {
1011 warning("SetSecurityDescriptorDacl failure:"
1012 " lasterror = %d \n", GetLastError());
1013 }
1014 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
1015 return false;
1016 }
1018 // if running on windows 2000 or later, set the automatic inheritance
1019 // control flags.
1020 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl;
1021 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr)
1022 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")),
1023 "SetSecurityDescriptorControl");
1025 if (_SetSecurityDescriptorControl != NULL) {
1026 // We do not want to further propagate inherited DACLs, so making them
1027 // protected prevents that.
1028 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED,
1029 SE_DACL_PROTECTED)) {
1030 if (PrintMiscellaneous && Verbose) {
1031 warning("SetSecurityDescriptorControl failure:"
1032 " lasterror = %d \n", GetLastError());
1033 }
1034 FREE_C_HEAP_ARRAY(char, newACL, mtInternal);
1035 return false;
1036 }
1037 }
1038 // Note, the security descriptor maintains a reference to the newACL, not
1039 // a copy of it. Therefore, the newACL is not freed here. It is freed when
1040 // the security descriptor containing its reference is freed.
1041 //
1042 return true;
1043 }
1045 // method to create a security attributes structure, which contains a
1046 // security descriptor and an access control list comprised of 0 or more
1047 // access control entries. The method take an array of ace_data structures
1048 // that indicate the ACE to be added to the security descriptor.
1049 //
1050 // the caller must free the resources associated with the security
1051 // attributes structure created by this method by calling the
1052 // free_security_attr() method.
1053 //
1054 static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) {
1056 // allocate space for a security descriptor
1057 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)
1058 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal);
1060 // initialize the security descriptor
1061 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
1062 if (PrintMiscellaneous && Verbose) {
1063 warning("InitializeSecurityDescriptor failure: "
1064 "lasterror = %d \n", GetLastError());
1065 }
1066 free_security_desc(pSD);
1067 return NULL;
1068 }
1070 // add the access control entries
1071 if (!add_allow_aces(pSD, aces, count)) {
1072 free_security_desc(pSD);
1073 return NULL;
1074 }
1076 // allocate and initialize the security attributes structure and
1077 // return it to the caller.
1078 //
1079 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES)
1080 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES), mtInternal);
1081 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES);
1082 lpSA->lpSecurityDescriptor = pSD;
1083 lpSA->bInheritHandle = FALSE;
1085 return(lpSA);
1086 }
1088 // method to create a security attributes structure with a restrictive
1089 // access control list that creates a set access rights for the user/owner
1090 // of the securable object and a separate set access rights for everyone else.
1091 // also provides for full access rights for the administrator group.
1092 //
1093 // the caller must free the resources associated with the security
1094 // attributes structure created by this method by calling the
1095 // free_security_attr() method.
1096 //
1098 static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr(
1099 DWORD umask, DWORD emask, DWORD amask) {
1101 ace_data_t aces[3];
1103 // initialize the user ace data
1104 aces[0].pSid = get_user_sid(GetCurrentProcess());
1105 aces[0].mask = umask;
1107 if (aces[0].pSid == 0)
1108 return NULL;
1110 // get the well known SID for BUILTIN\Administrators
1111 PSID administratorsSid = NULL;
1112 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY;
1114 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2,
1115 SECURITY_BUILTIN_DOMAIN_RID,
1116 DOMAIN_ALIAS_RID_ADMINS,
1117 0, 0, 0, 0, 0, 0, &administratorsSid)) {
1119 if (PrintMiscellaneous && Verbose) {
1120 warning("AllocateAndInitializeSid failure: "
1121 "lasterror = %d \n", GetLastError());
1122 }
1123 return NULL;
1124 }
1126 // initialize the ace data for administrator group
1127 aces[1].pSid = administratorsSid;
1128 aces[1].mask = amask;
1130 // get the well known SID for the universal Everybody
1131 PSID everybodySid = NULL;
1132 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY;
1134 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID,
1135 0, 0, 0, 0, 0, 0, 0, &everybodySid)) {
1137 if (PrintMiscellaneous && Verbose) {
1138 warning("AllocateAndInitializeSid failure: "
1139 "lasterror = %d \n", GetLastError());
1140 }
1141 return NULL;
1142 }
1144 // initialize the ace data for everybody else.
1145 aces[2].pSid = everybodySid;
1146 aces[2].mask = emask;
1148 // create a security attributes structure with access control
1149 // entries as initialized above.
1150 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3);
1151 FREE_C_HEAP_ARRAY(char, aces[0].pSid, mtInternal);
1152 FreeSid(everybodySid);
1153 FreeSid(administratorsSid);
1154 return(lpSA);
1155 }
1158 // method to create the security attributes structure for restricting
1159 // access to the user temporary directory.
1160 //
1161 // the caller must free the resources associated with the security
1162 // attributes structure created by this method by calling the
1163 // free_security_attr() method.
1164 //
1165 static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() {
1167 // create full access rights for the user/owner of the directory
1168 // and read-only access rights for everybody else. This is
1169 // effectively equivalent to UNIX 755 permissions on a directory.
1170 //
1171 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS;
1172 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1173 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1175 return make_user_everybody_admin_security_attr(umask, emask, amask);
1176 }
1178 // method to create the security attributes structure for restricting
1179 // access to the shared memory backing store file.
1180 //
1181 // the caller must free the resources associated with the security
1182 // attributes structure created by this method by calling the
1183 // free_security_attr() method.
1184 //
1185 static LPSECURITY_ATTRIBUTES make_file_security_attr() {
1187 // create extensive access rights for the user/owner of the file
1188 // and attribute read-only access rights for everybody else. This
1189 // is effectively equivalent to UNIX 600 permissions on a file.
1190 //
1191 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1192 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES |
1193 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1194 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1196 return make_user_everybody_admin_security_attr(umask, emask, amask);
1197 }
1199 // method to create the security attributes structure for restricting
1200 // access to the name shared memory file mapping object.
1201 //
1202 // the caller must free the resources associated with the security
1203 // attributes structure created by this method by calling the
1204 // free_security_attr() method.
1205 //
1206 static LPSECURITY_ATTRIBUTES make_smo_security_attr() {
1208 // create extensive access rights for the user/owner of the shared
1209 // memory object and attribute read-only access rights for everybody
1210 // else. This is effectively equivalent to UNIX 600 permissions on
1211 // on the shared memory object.
1212 //
1213 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS;
1214 DWORD emask = STANDARD_RIGHTS_READ; // attributes only
1215 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS;
1217 return make_user_everybody_admin_security_attr(umask, emask, amask);
1218 }
1220 // make the user specific temporary directory
1221 //
1222 static bool make_user_tmp_dir(const char* dirname) {
1225 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr();
1226 if (pDirSA == NULL) {
1227 return false;
1228 }
1231 // create the directory with the given security attributes
1232 if (!CreateDirectory(dirname, pDirSA)) {
1233 DWORD lasterror = GetLastError();
1234 if (lasterror == ERROR_ALREADY_EXISTS) {
1235 // The directory already exists and was probably created by another
1236 // JVM instance. However, this could also be the result of a
1237 // deliberate symlink. Verify that the existing directory is safe.
1238 //
1239 if (!is_directory_secure(dirname)) {
1240 // directory is not secure
1241 if (PrintMiscellaneous && Verbose) {
1242 warning("%s directory is insecure\n", dirname);
1243 }
1244 return false;
1245 }
1246 // The administrator should be able to delete this directory.
1247 // But the directory created by previous version of JVM may not
1248 // have permission for administrators to delete this directory.
1249 // So add full permission to the administrator. Also setting new
1250 // DACLs might fix the corrupted the DACLs.
1251 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION;
1252 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) {
1253 if (PrintMiscellaneous && Verbose) {
1254 lasterror = GetLastError();
1255 warning("SetFileSecurity failed for %s directory. lasterror %d \n",
1256 dirname, lasterror);
1257 }
1258 }
1259 }
1260 else {
1261 if (PrintMiscellaneous && Verbose) {
1262 warning("CreateDirectory failed: %d\n", GetLastError());
1263 }
1264 return false;
1265 }
1266 }
1268 // free the security attributes structure
1269 free_security_attr(pDirSA);
1271 return true;
1272 }
1274 // create the shared memory resources
1275 //
1276 // This function creates the shared memory resources. This includes
1277 // the backing store file and the file mapping shared memory object.
1278 //
1279 static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) {
1281 HANDLE fh = INVALID_HANDLE_VALUE;
1282 HANDLE fmh = NULL;
1285 // create the security attributes for the backing store file
1286 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr();
1287 if (lpFileSA == NULL) {
1288 return NULL;
1289 }
1291 // create the security attributes for the shared memory object
1292 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr();
1293 if (lpSmoSA == NULL) {
1294 free_security_attr(lpFileSA);
1295 return NULL;
1296 }
1298 // create the user temporary directory
1299 if (!make_user_tmp_dir(dirname)) {
1300 // could not make/find the directory or the found directory
1301 // was not secure
1302 return NULL;
1303 }
1305 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the
1306 // file to be deleted by the last process that closes its handle to
1307 // the file. This is important as the apis do not allow a terminating
1308 // JVM being monitored by another process to remove the file name.
1309 //
1310 // the FILE_SHARE_DELETE share mode is valid only in winnt
1311 //
1312 fh = CreateFile(
1313 filename, /* LPCTSTR file name */
1315 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */
1317 (os::win32::is_nt() ? FILE_SHARE_DELETE : 0)|
1318 FILE_SHARE_READ, /* DWORD share mode, future READONLY
1319 * open operations allowed
1320 */
1321 lpFileSA, /* LPSECURITY security attributes */
1322 CREATE_ALWAYS, /* DWORD creation disposition
1323 * create file, if it already
1324 * exists, overwrite it.
1325 */
1326 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */
1328 NULL); /* HANDLE template file access */
1330 free_security_attr(lpFileSA);
1332 if (fh == INVALID_HANDLE_VALUE) {
1333 DWORD lasterror = GetLastError();
1334 if (PrintMiscellaneous && Verbose) {
1335 warning("could not create file %s: %d\n", filename, lasterror);
1336 }
1337 return NULL;
1338 }
1340 // try to create the file mapping
1341 fmh = create_file_mapping(objectname, fh, lpSmoSA, size);
1343 free_security_attr(lpSmoSA);
1345 if (fmh == NULL) {
1346 // closing the file handle here will decrement the reference count
1347 // on the file. When all processes accessing the file close their
1348 // handle to it, the reference count will decrement to 0 and the
1349 // OS will delete the file. These semantics are requested by the
1350 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above.
1351 CloseHandle(fh);
1352 fh = NULL;
1353 return NULL;
1354 } else {
1355 // We created the file mapping, but rarely the size of the
1356 // backing store file is reported as zero (0) which can cause
1357 // failures when trying to use the hsperfdata file.
1358 struct stat statbuf;
1359 int ret_code = ::stat(filename, &statbuf);
1360 if (ret_code == OS_ERR) {
1361 if (PrintMiscellaneous && Verbose) {
1362 warning("Could not get status information from file %s: %s\n",
1363 filename, strerror(errno));
1364 }
1365 CloseHandle(fmh);
1366 CloseHandle(fh);
1367 fh = NULL;
1368 fmh = NULL;
1369 return NULL;
1370 }
1372 // We could always call FlushFileBuffers() but the Microsoft
1373 // docs indicate that it is considered expensive so we only
1374 // call it when we observe the size as zero (0).
1375 if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) {
1376 DWORD lasterror = GetLastError();
1377 if (PrintMiscellaneous && Verbose) {
1378 warning("could not flush file %s: %d\n", filename, lasterror);
1379 }
1380 CloseHandle(fmh);
1381 CloseHandle(fh);
1382 fh = NULL;
1383 fmh = NULL;
1384 return NULL;
1385 }
1386 }
1388 // the file has been successfully created and the file mapping
1389 // object has been created.
1390 sharedmem_fileHandle = fh;
1391 sharedmem_fileName = strdup(filename);
1393 return fmh;
1394 }
1396 // open the shared memory object for the given vmid.
1397 //
1398 static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) {
1400 HANDLE fmh;
1402 // open the file mapping with the requested mode
1403 fmh = OpenFileMapping(
1404 ofm_access, /* DWORD access mode */
1405 FALSE, /* BOOL inherit flag - Do not allow inherit */
1406 objectname); /* name for object */
1408 if (fmh == NULL) {
1409 if (PrintMiscellaneous && Verbose) {
1410 warning("OpenFileMapping failed for shared memory object %s:"
1411 " lasterror = %d\n", objectname, GetLastError());
1412 }
1413 THROW_MSG_(vmSymbols::java_lang_Exception(),
1414 "Could not open PerfMemory", INVALID_HANDLE_VALUE);
1415 }
1417 return fmh;;
1418 }
1420 // create a named shared memory region
1421 //
1422 // On Win32, a named shared memory object has a name space that
1423 // is independent of the file system name space. Shared memory object,
1424 // or more precisely, file mapping objects, provide no mechanism to
1425 // inquire the size of the memory region. There is also no api to
1426 // enumerate the memory regions for various processes.
1427 //
1428 // This implementation utilizes the shared memory name space in parallel
1429 // with the file system name space. This allows us to determine the
1430 // size of the shared memory region from the size of the file and it
1431 // allows us to provide a common, file system based name space for
1432 // shared memory across platforms.
1433 //
1434 static char* mapping_create_shared(size_t size) {
1436 void *mapAddress;
1437 int vmid = os::current_process_id();
1439 // get the name of the user associated with this process
1440 char* user = get_user_name();
1442 if (user == NULL) {
1443 return NULL;
1444 }
1446 // construct the name of the user specific temporary directory
1447 char* dirname = get_user_tmp_dir(user);
1449 // check that the file system is secure - i.e. it supports ACLs.
1450 if (!is_filesystem_secure(dirname)) {
1451 return NULL;
1452 }
1454 // create the names of the backing store files and for the
1455 // share memory object.
1456 //
1457 char* filename = get_sharedmem_filename(dirname, vmid);
1458 char* objectname = get_sharedmem_objectname(user, vmid);
1460 // cleanup any stale shared memory resources
1461 cleanup_sharedmem_resources(dirname);
1463 assert(((size != 0) && (size % os::vm_page_size() == 0)),
1464 "unexpected PerfMemry region size");
1466 FREE_C_HEAP_ARRAY(char, user, mtInternal);
1468 // create the shared memory resources
1469 sharedmem_fileMapHandle =
1470 create_sharedmem_resources(dirname, filename, objectname, size);
1472 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
1473 FREE_C_HEAP_ARRAY(char, objectname, mtInternal);
1474 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
1476 if (sharedmem_fileMapHandle == NULL) {
1477 return NULL;
1478 }
1480 // map the file into the address space
1481 mapAddress = MapViewOfFile(
1482 sharedmem_fileMapHandle, /* HANDLE = file mapping object */
1483 FILE_MAP_ALL_ACCESS, /* DWORD access flags */
1484 0, /* DWORD High word of offset */
1485 0, /* DWORD Low word of offset */
1486 (DWORD)size); /* DWORD Number of bytes to map */
1488 if (mapAddress == NULL) {
1489 if (PrintMiscellaneous && Verbose) {
1490 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1491 }
1492 CloseHandle(sharedmem_fileMapHandle);
1493 sharedmem_fileMapHandle = NULL;
1494 return NULL;
1495 }
1497 // clear the shared memory region
1498 (void)memset(mapAddress, '\0', size);
1500 // it does not go through os api, the operation has to record from here
1501 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,
1502 size, CURRENT_PC, mtInternal);
1504 return (char*) mapAddress;
1505 }
1507 // this method deletes the file mapping object.
1508 //
1509 static void delete_file_mapping(char* addr, size_t size) {
1511 // cleanup the persistent shared memory resources. since DestroyJavaVM does
1512 // not support unloading of the JVM, unmapping of the memory resource is not
1513 // performed. The memory will be reclaimed by the OS upon termination of all
1514 // processes mapping the resource. The file mapping handle and the file
1515 // handle are closed here to expedite the remove of the file by the OS. The
1516 // file is not removed directly because it was created with
1517 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would
1518 // be unsuccessful.
1520 // close the fileMapHandle. the file mapping will still be retained
1521 // by the OS as long as any other JVM processes has an open file mapping
1522 // handle or a mapped view of the file.
1523 //
1524 if (sharedmem_fileMapHandle != NULL) {
1525 CloseHandle(sharedmem_fileMapHandle);
1526 sharedmem_fileMapHandle = NULL;
1527 }
1529 // close the file handle. This will decrement the reference count on the
1530 // backing store file. When the reference count decrements to 0, the OS
1531 // will delete the file. These semantics apply because the file was
1532 // created with the FILE_FLAG_DELETE_ON_CLOSE flag.
1533 //
1534 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) {
1535 CloseHandle(sharedmem_fileHandle);
1536 sharedmem_fileHandle = INVALID_HANDLE_VALUE;
1537 }
1538 }
1540 // this method determines the size of the shared memory file
1541 //
1542 static size_t sharedmem_filesize(const char* filename, TRAPS) {
1544 struct stat statbuf;
1546 // get the file size
1547 //
1548 // on win95/98/me, _stat returns a file size of 0 bytes, but on
1549 // winnt/2k the appropriate file size is returned. support for
1550 // the sharable aspects of performance counters was abandonded
1551 // on the non-nt win32 platforms due to this and other api
1552 // inconsistencies
1553 //
1554 if (::stat(filename, &statbuf) == OS_ERR) {
1555 if (PrintMiscellaneous && Verbose) {
1556 warning("stat %s failed: %s\n", filename, strerror(errno));
1557 }
1558 THROW_MSG_0(vmSymbols::java_io_IOException(),
1559 "Could not determine PerfMemory size");
1560 }
1562 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) {
1563 if (PrintMiscellaneous && Verbose) {
1564 warning("unexpected file size: size = " SIZE_FORMAT "\n",
1565 statbuf.st_size);
1566 }
1567 THROW_MSG_0(vmSymbols::java_lang_Exception(),
1568 "Invalid PerfMemory size");
1569 }
1571 return statbuf.st_size;
1572 }
1574 // this method opens a file mapping object and maps the object
1575 // into the address space of the process
1576 //
1577 static void open_file_mapping(const char* user, int vmid,
1578 PerfMemory::PerfMemoryMode mode,
1579 char** addrp, size_t* sizep, TRAPS) {
1581 ResourceMark rm;
1583 void *mapAddress = 0;
1584 size_t size = 0;
1585 HANDLE fmh;
1586 DWORD ofm_access;
1587 DWORD mv_access;
1588 const char* luser = NULL;
1590 if (mode == PerfMemory::PERF_MODE_RO) {
1591 ofm_access = FILE_MAP_READ;
1592 mv_access = FILE_MAP_READ;
1593 }
1594 else if (mode == PerfMemory::PERF_MODE_RW) {
1595 #ifdef LATER
1596 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE;
1597 mv_access = FILE_MAP_READ | FILE_MAP_WRITE;
1598 #else
1599 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1600 "Unsupported access mode");
1601 #endif
1602 }
1603 else {
1604 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1605 "Illegal access mode");
1606 }
1608 // if a user name wasn't specified, then find the user name for
1609 // the owner of the target vm.
1610 if (user == NULL || strlen(user) == 0) {
1611 luser = get_user_name(vmid);
1612 }
1613 else {
1614 luser = user;
1615 }
1617 if (luser == NULL) {
1618 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1619 "Could not map vmid to user name");
1620 }
1622 // get the names for the resources for the target vm
1623 char* dirname = get_user_tmp_dir(luser);
1625 // since we don't follow symbolic links when creating the backing
1626 // store file, we also don't following them when attaching
1627 //
1628 if (!is_directory_secure(dirname)) {
1629 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
1630 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1631 "Process not found");
1632 }
1634 char* filename = get_sharedmem_filename(dirname, vmid);
1635 char* objectname = get_sharedmem_objectname(luser, vmid);
1637 // copy heap memory to resource memory. the objectname and
1638 // filename are passed to methods that may throw exceptions.
1639 // using resource arrays for these names prevents the leaks
1640 // that would otherwise occur.
1641 //
1642 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
1643 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1);
1644 strcpy(rfilename, filename);
1645 strcpy(robjectname, objectname);
1647 // free the c heap resources that are no longer needed
1648 if (luser != user) FREE_C_HEAP_ARRAY(char, luser, mtInternal);
1649 FREE_C_HEAP_ARRAY(char, dirname, mtInternal);
1650 FREE_C_HEAP_ARRAY(char, filename, mtInternal);
1651 FREE_C_HEAP_ARRAY(char, objectname, mtInternal);
1653 if (*sizep == 0) {
1654 size = sharedmem_filesize(rfilename, CHECK);
1655 } else {
1656 size = *sizep;
1657 }
1659 assert(size > 0, "unexpected size <= 0");
1661 // Open the file mapping object with the given name
1662 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK);
1664 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value");
1666 // map the entire file into the address space
1667 mapAddress = MapViewOfFile(
1668 fmh, /* HANDLE Handle of file mapping object */
1669 mv_access, /* DWORD access flags */
1670 0, /* DWORD High word of offset */
1671 0, /* DWORD Low word of offset */
1672 size); /* DWORD Number of bytes to map */
1674 if (mapAddress == NULL) {
1675 if (PrintMiscellaneous && Verbose) {
1676 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1677 }
1678 CloseHandle(fmh);
1679 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
1680 "Could not map PerfMemory");
1681 }
1683 // it does not go through os api, the operation has to record from here
1684 MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size,
1685 CURRENT_PC, mtInternal);
1688 *addrp = (char*)mapAddress;
1689 *sizep = size;
1691 // File mapping object can be closed at this time without
1692 // invalidating the mapped view of the file
1693 CloseHandle(fmh);
1695 if (PerfTraceMemOps) {
1696 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
1697 INTPTR_FORMAT "\n", size, vmid, mapAddress);
1698 }
1699 }
1701 // this method unmaps the the mapped view of the the
1702 // file mapping object.
1703 //
1704 static void remove_file_mapping(char* addr) {
1706 // the file mapping object was closed in open_file_mapping()
1707 // after the file map view was created. We only need to
1708 // unmap the file view here.
1709 UnmapViewOfFile(addr);
1710 }
1712 // create the PerfData memory region in shared memory.
1713 static char* create_shared_memory(size_t size) {
1715 return mapping_create_shared(size);
1716 }
1718 // release a named, shared memory region
1719 //
1720 void delete_shared_memory(char* addr, size_t size) {
1722 delete_file_mapping(addr, size);
1723 }
1728 // create the PerfData memory region
1729 //
1730 // This method creates the memory region used to store performance
1731 // data for the JVM. The memory may be created in standard or
1732 // shared memory.
1733 //
1734 void PerfMemory::create_memory_region(size_t size) {
1736 if (PerfDisableSharedMem || !os::win32::is_nt()) {
1737 // do not share the memory for the performance data.
1738 PerfDisableSharedMem = true;
1739 _start = create_standard_memory(size);
1740 }
1741 else {
1742 _start = create_shared_memory(size);
1743 if (_start == NULL) {
1745 // creation of the shared memory region failed, attempt
1746 // to create a contiguous, non-shared memory region instead.
1747 //
1748 if (PrintMiscellaneous && Verbose) {
1749 warning("Reverting to non-shared PerfMemory region.\n");
1750 }
1751 PerfDisableSharedMem = true;
1752 _start = create_standard_memory(size);
1753 }
1754 }
1756 if (_start != NULL) _capacity = size;
1758 }
1760 // delete the PerfData memory region
1761 //
1762 // This method deletes the memory region used to store performance
1763 // data for the JVM. The memory region indicated by the <address, size>
1764 // tuple will be inaccessible after a call to this method.
1765 //
1766 void PerfMemory::delete_memory_region() {
1768 assert((start() != NULL && capacity() > 0), "verify proper state");
1770 // If user specifies PerfDataSaveFile, it will save the performance data
1771 // to the specified file name no matter whether PerfDataSaveToFile is specified
1772 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1773 // -XX:+PerfDataSaveToFile.
1774 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1775 save_memory_to_file(start(), capacity());
1776 }
1778 if (PerfDisableSharedMem) {
1779 delete_standard_memory(start(), capacity());
1780 }
1781 else {
1782 delete_shared_memory(start(), capacity());
1783 }
1784 }
1786 // attach to the PerfData memory region for another JVM
1787 //
1788 // This method returns an <address, size> tuple that points to
1789 // a memory buffer that is kept reasonably synchronized with
1790 // the PerfData memory region for the indicated JVM. This
1791 // buffer may be kept in synchronization via shared memory
1792 // or some other mechanism that keeps the buffer updated.
1793 //
1794 // If the JVM chooses not to support the attachability feature,
1795 // this method should throw an UnsupportedOperation exception.
1796 //
1797 // This implementation utilizes named shared memory to map
1798 // the indicated process's PerfData memory region into this JVMs
1799 // address space.
1800 //
1801 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode,
1802 char** addrp, size_t* sizep, TRAPS) {
1804 if (vmid == 0 || vmid == os::current_process_id()) {
1805 *addrp = start();
1806 *sizep = capacity();
1807 return;
1808 }
1810 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK);
1811 }
1813 // detach from the PerfData memory region of another JVM
1814 //
1815 // This method detaches the PerfData memory region of another
1816 // JVM, specified as an <address, size> tuple of a buffer
1817 // in this process's address space. This method may perform
1818 // arbitrary actions to accomplish the detachment. The memory
1819 // region specified by <address, size> will be inaccessible after
1820 // a call to this method.
1821 //
1822 // If the JVM chooses not to support the attachability feature,
1823 // this method should throw an UnsupportedOperation exception.
1824 //
1825 // This implementation utilizes named shared memory to detach
1826 // the indicated process's PerfData memory region from this
1827 // process's address space.
1828 //
1829 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
1831 assert(addr != 0, "address sanity check");
1832 assert(bytes > 0, "capacity sanity check");
1834 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1835 // prevent accidental detachment of this process's PerfMemory region
1836 return;
1837 }
1839 if (MemTracker::tracking_level() > NMT_minimal) {
1840 // it does not go through os api, the operation has to record from here
1841 Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1842 remove_file_mapping(addr);
1843 tkr.record((address)addr, bytes);
1844 } else {
1845 remove_file_mapping(addr);
1846 }
1847 }
1849 char* PerfMemory::backing_store_filename() {
1850 return sharedmem_fileName;
1851 }