Tue, 24 Apr 2012 12:15:32 -0700
7157695: Add windows implementation of socket interface
Reviewed-by: kvn, dholmes, twisti
Contributed-by: Nils Eliasson <nils.eliasson@oracle.com>
1 /*
2 * Copyright (c) 2001, 2011, 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 "utilities/exceptions.hpp"
35 #include <windows.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39 #include <lmcons.h>
41 typedef BOOL (WINAPI *SetSecurityDescriptorControlFnPtr)(
42 IN PSECURITY_DESCRIPTOR pSecurityDescriptor,
43 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
44 IN SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet);
46 // Standard Memory Implementation Details
48 // create the PerfData memory region in standard memory.
49 //
50 static char* create_standard_memory(size_t size) {
52 // allocate an aligned chuck of memory
53 char* mapAddress = os::reserve_memory(size);
55 if (mapAddress == NULL) {
56 return NULL;
57 }
59 // commit memory
60 if (!os::commit_memory(mapAddress, size)) {
61 if (PrintMiscellaneous && Verbose) {
62 warning("Could not commit PerfData memory\n");
63 }
64 os::release_memory(mapAddress, size);
65 return NULL;
66 }
68 return mapAddress;
69 }
71 // delete the PerfData memory region
72 //
73 static void delete_standard_memory(char* addr, size_t size) {
75 // there are no persistent external resources to cleanup for standard
76 // memory. since DestroyJavaVM does not support unloading of the JVM,
77 // cleanup of the memory resource is not performed. The memory will be
78 // reclaimed by the OS upon termination of the process.
79 //
80 return;
82 }
84 // save the specified memory region to the given file
85 //
86 static void save_memory_to_file(char* addr, size_t size) {
88 const char* destfile = PerfMemory::get_perfdata_file_path();
89 assert(destfile[0] != '\0', "invalid Perfdata file path");
91 int fd = ::_open(destfile, _O_BINARY|_O_CREAT|_O_WRONLY|_O_TRUNC,
92 _S_IREAD|_S_IWRITE);
94 if (fd == OS_ERR) {
95 if (PrintMiscellaneous && Verbose) {
96 warning("Could not create Perfdata save file: %s: %s\n",
97 destfile, strerror(errno));
98 }
99 } else {
100 for (size_t remaining = size; remaining > 0;) {
102 int nbytes = ::_write(fd, addr, (unsigned int)remaining);
103 if (nbytes == OS_ERR) {
104 if (PrintMiscellaneous && Verbose) {
105 warning("Could not write Perfdata save file: %s: %s\n",
106 destfile, strerror(errno));
107 }
108 break;
109 }
111 remaining -= (size_t)nbytes;
112 addr += nbytes;
113 }
115 int result = ::_close(fd);
116 if (PrintMiscellaneous && Verbose) {
117 if (result == OS_ERR) {
118 warning("Could not close %s: %s\n", destfile, strerror(errno));
119 }
120 }
121 }
123 FREE_C_HEAP_ARRAY(char, destfile);
124 }
126 // Shared Memory Implementation Details
128 // Note: the win32 shared memory implementation uses two objects to represent
129 // the shared memory: a windows kernel based file mapping object and a backing
130 // store file. On windows, the name space for shared memory is a kernel
131 // based name space that is disjoint from other win32 name spaces. Since Java
132 // is unaware of this name space, a parallel file system based name space is
133 // maintained, which provides a common file system based shared memory name
134 // space across the supported platforms and one that Java apps can deal with
135 // through simple file apis.
136 //
137 // For performance and resource cleanup reasons, it is recommended that the
138 // user specific directory and the backing store file be stored in either a
139 // RAM based file system or a local disk based file system. Network based
140 // file systems are not recommended for performance reasons. In addition,
141 // use of SMB network based file systems may result in unsuccesful cleanup
142 // of the disk based resource on exit of the VM. The Windows TMP and TEMP
143 // environement variables, as used by the GetTempPath() Win32 API (see
144 // os::get_temp_directory() in os_win32.cpp), control the location of the
145 // user specific directory and the shared memory backing store file.
147 static HANDLE sharedmem_fileMapHandle = NULL;
148 static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE;
149 static char* sharedmem_fileName = NULL;
151 // return the user specific temporary directory name.
152 //
153 // the caller is expected to free the allocated memory.
154 //
155 static char* get_user_tmp_dir(const char* user) {
157 const char* tmpdir = os::get_temp_directory();
158 const char* perfdir = PERFDATA_NAME;
159 size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;
160 char* dirname = NEW_C_HEAP_ARRAY(char, nbytes);
162 // construct the path name to user specific tmp directory
163 _snprintf(dirname, nbytes, "%s\\%s_%s", tmpdir, perfdir, user);
165 return dirname;
166 }
168 // convert the given file name into a process id. if the file
169 // does not meet the file naming constraints, return 0.
170 //
171 static int filename_to_pid(const char* filename) {
173 // a filename that doesn't begin with a digit is not a
174 // candidate for conversion.
175 //
176 if (!isdigit(*filename)) {
177 return 0;
178 }
180 // check if file name can be converted to an integer without
181 // any leftover characters.
182 //
183 char* remainder = NULL;
184 errno = 0;
185 int pid = (int)strtol(filename, &remainder, 10);
187 if (errno != 0) {
188 return 0;
189 }
191 // check for left over characters. If any, then the filename is
192 // not a candidate for conversion.
193 //
194 if (remainder != NULL && *remainder != '\0') {
195 return 0;
196 }
198 // successful conversion, return the pid
199 return pid;
200 }
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) {
209 DWORD fa;
211 fa = GetFileAttributes(path);
212 if (fa == 0xFFFFFFFF) {
213 DWORD lasterror = GetLastError();
214 if (lasterror == ERROR_FILE_NOT_FOUND) {
215 return false;
216 }
217 else {
218 // unexpected error, declare the path insecure
219 if (PrintMiscellaneous && Verbose) {
220 warning("could not get attributes for file %s: ",
221 " lasterror = %d\n", path, lasterror);
222 }
223 return false;
224 }
225 }
227 if (fa & FILE_ATTRIBUTE_REPARSE_POINT) {
228 // we don't accept any redirection for the user specific directory
229 // so declare the path insecure. This may be too conservative,
230 // as some types of reparse points might be acceptable, but it
231 // is probably more secure to avoid these conditions.
232 //
233 if (PrintMiscellaneous && Verbose) {
234 warning("%s is a reparse point\n", path);
235 }
236 return false;
237 }
239 if (fa & FILE_ATTRIBUTE_DIRECTORY) {
240 // this is the expected case. Since windows supports symbolic
241 // links to directories only, not to files, there is no need
242 // to check for open write permissions on the directory. If the
243 // directory has open write permissions, any files deposited that
244 // are not expected will be removed by the cleanup code.
245 //
246 return true;
247 }
248 else {
249 // this is either a regular file or some other type of file,
250 // any of which are unexpected and therefore insecure.
251 //
252 if (PrintMiscellaneous && Verbose) {
253 warning("%s is not a directory, file attributes = "
254 INTPTR_FORMAT "\n", path, fa);
255 }
256 return false;
257 }
258 }
260 // return the user name for the owner of this process
261 //
262 // the caller is expected to free the allocated memory.
263 //
264 static char* get_user_name() {
266 /* get the user name. This code is adapted from code found in
267 * the jdk in src/windows/native/java/lang/java_props_md.c
268 * java_props_md.c 1.29 02/02/06. According to the original
269 * source, the call to GetUserName is avoided because of a resulting
270 * increase in footprint of 100K.
271 */
272 char* user = getenv("USERNAME");
273 char buf[UNLEN+1];
274 DWORD buflen = sizeof(buf);
275 if (user == NULL || strlen(user) == 0) {
276 if (GetUserName(buf, &buflen)) {
277 user = buf;
278 }
279 else {
280 return NULL;
281 }
282 }
284 char* user_name = NEW_C_HEAP_ARRAY(char, strlen(user)+1);
285 strcpy(user_name, user);
287 return user_name;
288 }
290 // return the name of the user that owns the process identified by vmid.
291 //
292 // This method uses a slow directory search algorithm to find the backing
293 // store file for the specified vmid and returns the user name, as determined
294 // by the user name suffix of the hsperfdata_<username> directory name.
295 //
296 // the caller is expected to free the allocated memory.
297 //
298 static char* get_user_name_slow(int vmid) {
300 // directory search
301 char* latest_user = NULL;
302 time_t latest_ctime = 0;
304 const char* tmpdirname = os::get_temp_directory();
306 DIR* tmpdirp = os::opendir(tmpdirname);
308 if (tmpdirp == NULL) {
309 return NULL;
310 }
312 // for each entry in the directory that matches the pattern hsperfdata_*,
313 // open the directory and check if the file for the given vmid exists.
314 // The file with the expected name and the latest creation date is used
315 // to determine the user name for the process id.
316 //
317 struct dirent* dentry;
318 char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname));
319 errno = 0;
320 while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
322 // check if the directory entry is a hsperfdata file
323 if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
324 continue;
325 }
327 char* usrdir_name = NEW_C_HEAP_ARRAY(char,
328 strlen(tmpdirname) + strlen(dentry->d_name) + 2);
329 strcpy(usrdir_name, tmpdirname);
330 strcat(usrdir_name, "\\");
331 strcat(usrdir_name, dentry->d_name);
333 DIR* subdirp = os::opendir(usrdir_name);
335 if (subdirp == NULL) {
336 FREE_C_HEAP_ARRAY(char, usrdir_name);
337 continue;
338 }
340 // Since we don't create the backing store files in directories
341 // pointed to by symbolic links, we also don't follow them when
342 // looking for the files. We check for a symbolic link after the
343 // call to opendir in order to eliminate a small window where the
344 // symlink can be exploited.
345 //
346 if (!is_directory_secure(usrdir_name)) {
347 FREE_C_HEAP_ARRAY(char, usrdir_name);
348 os::closedir(subdirp);
349 continue;
350 }
352 struct dirent* udentry;
353 char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name));
354 errno = 0;
355 while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
357 if (filename_to_pid(udentry->d_name) == vmid) {
358 struct stat statbuf;
360 char* filename = NEW_C_HEAP_ARRAY(char,
361 strlen(usrdir_name) + strlen(udentry->d_name) + 2);
363 strcpy(filename, usrdir_name);
364 strcat(filename, "\\");
365 strcat(filename, udentry->d_name);
367 if (::stat(filename, &statbuf) == OS_ERR) {
368 FREE_C_HEAP_ARRAY(char, filename);
369 continue;
370 }
372 // skip over files that are not regular files.
373 if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
374 FREE_C_HEAP_ARRAY(char, filename);
375 continue;
376 }
378 // If we found a matching file with a newer creation time, then
379 // save the user name. The newer creation time indicates that
380 // we found a newer incarnation of the process associated with
381 // vmid. Due to the way that Windows recycles pids and the fact
382 // that we can't delete the file from the file system namespace
383 // until last close, it is possible for there to be more than
384 // one hsperfdata file with a name matching vmid (diff users).
385 //
386 // We no longer ignore hsperfdata files where (st_size == 0).
387 // In this function, all we're trying to do is determine the
388 // name of the user that owns the process associated with vmid
389 // so the size doesn't matter. Very rarely, we have observed
390 // hsperfdata files where (st_size == 0) and the st_size field
391 // later becomes the expected value.
392 //
393 if (statbuf.st_ctime > latest_ctime) {
394 char* user = strchr(dentry->d_name, '_') + 1;
396 if (latest_user != NULL) FREE_C_HEAP_ARRAY(char, latest_user);
397 latest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1);
399 strcpy(latest_user, user);
400 latest_ctime = statbuf.st_ctime;
401 }
403 FREE_C_HEAP_ARRAY(char, filename);
404 }
405 }
406 os::closedir(subdirp);
407 FREE_C_HEAP_ARRAY(char, udbuf);
408 FREE_C_HEAP_ARRAY(char, usrdir_name);
409 }
410 os::closedir(tmpdirp);
411 FREE_C_HEAP_ARRAY(char, tdbuf);
413 return(latest_user);
414 }
416 // return the name of the user that owns the process identified by vmid.
417 //
418 // note: this method should only be used via the Perf native methods.
419 // There are various costs to this method and limiting its use to the
420 // Perf native methods limits the impact to monitoring applications only.
421 //
422 static char* get_user_name(int vmid) {
424 // A fast implementation is not provided at this time. It's possible
425 // to provide a fast process id to user name mapping function using
426 // the win32 apis, but the default ACL for the process object only
427 // allows processes with the same owner SID to acquire the process
428 // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible
429 // to have the JVM change the ACL for the process object to allow arbitrary
430 // users to access the process handle and the process security token.
431 // The security ramifications need to be studied before providing this
432 // mechanism.
433 //
434 return get_user_name_slow(vmid);
435 }
437 // return the name of the shared memory file mapping object for the
438 // named shared memory region for the given user name and vmid.
439 //
440 // The file mapping object's name is not the file name. It is a name
441 // in a separate name space.
442 //
443 // the caller is expected to free the allocated memory.
444 //
445 static char *get_sharedmem_objectname(const char* user, int vmid) {
447 // construct file mapping object's name, add 3 for two '_' and a
448 // null terminator.
449 int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3;
451 // the id is converted to an unsigned value here because win32 allows
452 // negative process ids. However, OpenFileMapping API complains
453 // about a name containing a '-' characters.
454 //
455 nbytes += UINT_CHARS;
456 char* name = NEW_C_HEAP_ARRAY(char, nbytes);
457 _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid);
459 return name;
460 }
462 // return the file name of the backing store file for the named
463 // shared memory region for the given user name and vmid.
464 //
465 // the caller is expected to free the allocated memory.
466 //
467 static char* get_sharedmem_filename(const char* dirname, int vmid) {
469 // add 2 for the file separator and a null terminator.
470 size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
472 char* name = NEW_C_HEAP_ARRAY(char, nbytes);
473 _snprintf(name, nbytes, "%s\\%d", dirname, vmid);
475 return name;
476 }
478 // remove file
479 //
480 // this method removes the file with the given file name.
481 //
482 // Note: if the indicated file is on an SMB network file system, this
483 // method may be unsuccessful in removing the file.
484 //
485 static void remove_file(const char* dirname, const char* filename) {
487 size_t nbytes = strlen(dirname) + strlen(filename) + 2;
488 char* path = NEW_C_HEAP_ARRAY(char, nbytes);
490 strcpy(path, dirname);
491 strcat(path, "\\");
492 strcat(path, filename);
494 if (::unlink(path) == OS_ERR) {
495 if (PrintMiscellaneous && Verbose) {
496 if (errno != ENOENT) {
497 warning("Could not unlink shared memory backing"
498 " store file %s : %s\n", path, strerror(errno));
499 }
500 }
501 }
503 FREE_C_HEAP_ARRAY(char, path);
504 }
506 // returns true if the process represented by pid is alive, otherwise
507 // returns false. the validity of the result is only accurate if the
508 // target process is owned by the same principal that owns this process.
509 // this method should not be used if to test the status of an otherwise
510 // arbitrary process unless it is know that this process has the appropriate
511 // privileges to guarantee a result valid.
512 //
513 static bool is_alive(int pid) {
515 HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
516 if (ph == NULL) {
517 // the process does not exist.
518 if (PrintMiscellaneous && Verbose) {
519 DWORD lastError = GetLastError();
520 if (lastError != ERROR_INVALID_PARAMETER) {
521 warning("OpenProcess failed: %d\n", GetLastError());
522 }
523 }
524 return false;
525 }
527 DWORD exit_status;
528 if (!GetExitCodeProcess(ph, &exit_status)) {
529 if (PrintMiscellaneous && Verbose) {
530 warning("GetExitCodeProcess failed: %d\n", GetLastError());
531 }
532 CloseHandle(ph);
533 return false;
534 }
536 CloseHandle(ph);
537 return (exit_status == STILL_ACTIVE) ? true : false;
538 }
540 // check if the file system is considered secure for the backing store files
541 //
542 static bool is_filesystem_secure(const char* path) {
544 char root_path[MAX_PATH];
545 char fs_type[MAX_PATH];
547 if (PerfBypassFileSystemCheck) {
548 if (PrintMiscellaneous && Verbose) {
549 warning("bypassing file system criteria checks for %s\n", path);
550 }
551 return true;
552 }
554 char* first_colon = strchr((char *)path, ':');
555 if (first_colon == NULL) {
556 if (PrintMiscellaneous && Verbose) {
557 warning("expected device specifier in path: %s\n", path);
558 }
559 return false;
560 }
562 size_t len = (size_t)(first_colon - path);
563 assert(len + 2 <= MAX_PATH, "unexpected device specifier length");
564 strncpy(root_path, path, len + 1);
565 root_path[len + 1] = '\\';
566 root_path[len + 2] = '\0';
568 // check that we have something like "C:\" or "AA:\"
569 assert(strlen(root_path) >= 3, "device specifier too short");
570 assert(strchr(root_path, ':') != NULL, "bad device specifier format");
571 assert(strchr(root_path, '\\') != NULL, "bad device specifier format");
573 DWORD maxpath;
574 DWORD flags;
576 if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath,
577 &flags, fs_type, MAX_PATH)) {
578 // we can't get information about the volume, so assume unsafe.
579 if (PrintMiscellaneous && Verbose) {
580 warning("could not get device information for %s: "
581 " path = %s: lasterror = %d\n",
582 root_path, path, GetLastError());
583 }
584 return false;
585 }
587 if ((flags & FS_PERSISTENT_ACLS) == 0) {
588 // file system doesn't support ACLs, declare file system unsafe
589 if (PrintMiscellaneous && Verbose) {
590 warning("file system type %s on device %s does not support"
591 " ACLs\n", fs_type, root_path);
592 }
593 return false;
594 }
596 if ((flags & FS_VOL_IS_COMPRESSED) != 0) {
597 // file system is compressed, declare file system unsafe
598 if (PrintMiscellaneous && Verbose) {
599 warning("file system type %s on device %s is compressed\n",
600 fs_type, root_path);
601 }
602 return false;
603 }
605 return true;
606 }
608 // cleanup stale shared memory resources
609 //
610 // This method attempts to remove all stale shared memory files in
611 // the named user temporary directory. It scans the named directory
612 // for files matching the pattern ^$[0-9]*$. For each file found, the
613 // process id is extracted from the file name and a test is run to
614 // determine if the process is alive. If the process is not alive,
615 // any stale file resources are removed.
616 //
617 static void cleanup_sharedmem_resources(const char* dirname) {
619 // open the user temp directory
620 DIR* dirp = os::opendir(dirname);
622 if (dirp == NULL) {
623 // directory doesn't exist, so there is nothing to cleanup
624 return;
625 }
627 if (!is_directory_secure(dirname)) {
628 // the directory is not secure, don't attempt any cleanup
629 return;
630 }
632 // for each entry in the directory that matches the expected file
633 // name pattern, determine if the file resources are stale and if
634 // so, remove the file resources. Note, instrumented HotSpot processes
635 // for this user may start and/or terminate during this search and
636 // remove or create new files in this directory. The behavior of this
637 // loop under these conditions is dependent upon the implementation of
638 // opendir/readdir.
639 //
640 struct dirent* entry;
641 char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname));
642 errno = 0;
643 while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
645 int pid = filename_to_pid(entry->d_name);
647 if (pid == 0) {
649 if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
651 // attempt to remove all unexpected files, except "." and ".."
652 remove_file(dirname, entry->d_name);
653 }
655 errno = 0;
656 continue;
657 }
659 // we now have a file name that converts to a valid integer
660 // that could represent a process id . if this process id
661 // matches the current process id or the process is not running,
662 // then remove the stale file resources.
663 //
664 // process liveness is detected by checking the exit status
665 // of the process. if the process id is valid and the exit status
666 // indicates that it is still running, the file file resources
667 // are not removed. If the process id is invalid, or if we don't
668 // have permissions to check the process status, or if the process
669 // id is valid and the process has terminated, the the file resources
670 // are assumed to be stale and are removed.
671 //
672 if (pid == os::current_process_id() || !is_alive(pid)) {
674 // we can only remove the file resources. Any mapped views
675 // of the file can only be unmapped by the processes that
676 // opened those views and the file mapping object will not
677 // get removed until all views are unmapped.
678 //
679 remove_file(dirname, entry->d_name);
680 }
681 errno = 0;
682 }
683 os::closedir(dirp);
684 FREE_C_HEAP_ARRAY(char, dbuf);
685 }
687 // create a file mapping object with the requested name, and size
688 // from the file represented by the given Handle object
689 //
690 static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) {
692 DWORD lowSize = (DWORD)size;
693 DWORD highSize = 0;
694 HANDLE fmh = NULL;
696 // Create a file mapping object with the given name. This function
697 // will grow the file to the specified size.
698 //
699 fmh = CreateFileMapping(
700 fh, /* HANDLE file handle for backing store */
701 fsa, /* LPSECURITY_ATTRIBUTES Not inheritable */
702 PAGE_READWRITE, /* DWORD protections */
703 highSize, /* DWORD High word of max size */
704 lowSize, /* DWORD Low word of max size */
705 name); /* LPCTSTR name for object */
707 if (fmh == NULL) {
708 if (PrintMiscellaneous && Verbose) {
709 warning("CreateFileMapping failed, lasterror = %d\n", GetLastError());
710 }
711 return NULL;
712 }
714 if (GetLastError() == ERROR_ALREADY_EXISTS) {
716 // a stale file mapping object was encountered. This object may be
717 // owned by this or some other user and cannot be removed until
718 // the other processes either exit or close their mapping objects
719 // and/or mapped views of this mapping object.
720 //
721 if (PrintMiscellaneous && Verbose) {
722 warning("file mapping already exists, lasterror = %d\n", GetLastError());
723 }
725 CloseHandle(fmh);
726 return NULL;
727 }
729 return fmh;
730 }
733 // method to free the given security descriptor and the contained
734 // access control list.
735 //
736 static void free_security_desc(PSECURITY_DESCRIPTOR pSD) {
738 BOOL success, exists, isdefault;
739 PACL pACL;
741 if (pSD != NULL) {
743 // get the access control list from the security descriptor
744 success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault);
746 // if an ACL existed and it was not a default acl, then it must
747 // be an ACL we enlisted. free the resources.
748 //
749 if (success && exists && pACL != NULL && !isdefault) {
750 FREE_C_HEAP_ARRAY(char, pACL);
751 }
753 // free the security descriptor
754 FREE_C_HEAP_ARRAY(char, pSD);
755 }
756 }
758 // method to free up a security attributes structure and any
759 // contained security descriptors and ACL
760 //
761 static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) {
763 if (lpSA != NULL) {
764 // free the contained security descriptor and the ACL
765 free_security_desc(lpSA->lpSecurityDescriptor);
766 lpSA->lpSecurityDescriptor = NULL;
768 // free the security attributes structure
769 FREE_C_HEAP_ARRAY(char, lpSA);
770 }
771 }
773 // get the user SID for the process indicated by the process handle
774 //
775 static PSID get_user_sid(HANDLE hProcess) {
777 HANDLE hAccessToken;
778 PTOKEN_USER token_buf = NULL;
779 DWORD rsize = 0;
781 if (hProcess == NULL) {
782 return NULL;
783 }
785 // get the process token
786 if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) {
787 if (PrintMiscellaneous && Verbose) {
788 warning("OpenProcessToken failure: lasterror = %d \n", GetLastError());
789 }
790 return NULL;
791 }
793 // determine the size of the token structured needed to retrieve
794 // the user token information from the access token.
795 //
796 if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) {
797 DWORD lasterror = GetLastError();
798 if (lasterror != ERROR_INSUFFICIENT_BUFFER) {
799 if (PrintMiscellaneous && Verbose) {
800 warning("GetTokenInformation failure: lasterror = %d,"
801 " rsize = %d\n", lasterror, rsize);
802 }
803 CloseHandle(hAccessToken);
804 return NULL;
805 }
806 }
808 token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize);
810 // get the user token information
811 if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) {
812 if (PrintMiscellaneous && Verbose) {
813 warning("GetTokenInformation failure: lasterror = %d,"
814 " rsize = %d\n", GetLastError(), rsize);
815 }
816 FREE_C_HEAP_ARRAY(char, token_buf);
817 CloseHandle(hAccessToken);
818 return NULL;
819 }
821 DWORD nbytes = GetLengthSid(token_buf->User.Sid);
822 PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes);
824 if (!CopySid(nbytes, pSID, token_buf->User.Sid)) {
825 if (PrintMiscellaneous && Verbose) {
826 warning("GetTokenInformation failure: lasterror = %d,"
827 " rsize = %d\n", GetLastError(), rsize);
828 }
829 FREE_C_HEAP_ARRAY(char, token_buf);
830 FREE_C_HEAP_ARRAY(char, pSID);
831 CloseHandle(hAccessToken);
832 return NULL;
833 }
835 // close the access token.
836 CloseHandle(hAccessToken);
837 FREE_C_HEAP_ARRAY(char, token_buf);
839 return pSID;
840 }
842 // structure used to consolidate access control entry information
843 //
844 typedef struct ace_data {
845 PSID pSid; // SID of the ACE
846 DWORD mask; // mask for the ACE
847 } ace_data_t;
850 // method to add an allow access control entry with the access rights
851 // indicated in mask for the principal indicated in SID to the given
852 // security descriptor. Much of the DACL handling was adapted from
853 // the example provided here:
854 // http://support.microsoft.com/kb/102102/EN-US/
855 //
857 static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD,
858 ace_data_t aces[], int ace_count) {
859 PACL newACL = NULL;
860 PACL oldACL = NULL;
862 if (pSD == NULL) {
863 return false;
864 }
866 BOOL exists, isdefault;
868 // retrieve any existing access control list.
869 if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) {
870 if (PrintMiscellaneous && Verbose) {
871 warning("GetSecurityDescriptor failure: lasterror = %d \n",
872 GetLastError());
873 }
874 return false;
875 }
877 // get the size of the DACL
878 ACL_SIZE_INFORMATION aclinfo;
880 // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent)
881 // while oldACL is NULL for some case.
882 if (oldACL == NULL) {
883 exists = FALSE;
884 }
886 if (exists) {
887 if (!GetAclInformation(oldACL, &aclinfo,
888 sizeof(ACL_SIZE_INFORMATION),
889 AclSizeInformation)) {
890 if (PrintMiscellaneous && Verbose) {
891 warning("GetAclInformation failure: lasterror = %d \n", GetLastError());
892 return false;
893 }
894 }
895 } else {
896 aclinfo.AceCount = 0; // assume NULL DACL
897 aclinfo.AclBytesFree = 0;
898 aclinfo.AclBytesInUse = sizeof(ACL);
899 }
901 // compute the size needed for the new ACL
902 // initial size of ACL is sum of the following:
903 // * size of ACL structure.
904 // * size of each ACE structure that ACL is to contain minus the sid
905 // sidStart member (DWORD) of the ACE.
906 // * length of the SID that each ACE is to contain.
907 DWORD newACLsize = aclinfo.AclBytesInUse +
908 (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count;
909 for (int i = 0; i < ace_count; i++) {
910 assert(aces[i].pSid != 0, "pSid should not be 0");
911 newACLsize += GetLengthSid(aces[i].pSid);
912 }
914 // create the new ACL
915 newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize);
917 if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) {
918 if (PrintMiscellaneous && Verbose) {
919 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
920 }
921 FREE_C_HEAP_ARRAY(char, newACL);
922 return false;
923 }
925 unsigned int ace_index = 0;
926 // copy any existing ACEs from the old ACL (if any) to the new ACL.
927 if (aclinfo.AceCount != 0) {
928 while (ace_index < aclinfo.AceCount) {
929 LPVOID ace;
930 if (!GetAce(oldACL, ace_index, &ace)) {
931 if (PrintMiscellaneous && Verbose) {
932 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
933 }
934 FREE_C_HEAP_ARRAY(char, newACL);
935 return false;
936 }
937 if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) {
938 // this is an inherited, allowed ACE; break from loop so we can
939 // add the new access allowed, non-inherited ACE in the correct
940 // position, immediately following all non-inherited ACEs.
941 break;
942 }
944 // determine if the SID of this ACE matches any of the SIDs
945 // for which we plan to set ACEs.
946 int matches = 0;
947 for (int i = 0; i < ace_count; i++) {
948 if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) {
949 matches++;
950 break;
951 }
952 }
954 // if there are no SID matches, then add this existing ACE to the new ACL
955 if (matches == 0) {
956 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
957 ((PACE_HEADER)ace)->AceSize)) {
958 if (PrintMiscellaneous && Verbose) {
959 warning("AddAce failure: lasterror = %d \n", GetLastError());
960 }
961 FREE_C_HEAP_ARRAY(char, newACL);
962 return false;
963 }
964 }
965 ace_index++;
966 }
967 }
969 // add the passed-in access control entries to the new ACL
970 for (int i = 0; i < ace_count; i++) {
971 if (!AddAccessAllowedAce(newACL, ACL_REVISION,
972 aces[i].mask, aces[i].pSid)) {
973 if (PrintMiscellaneous && Verbose) {
974 warning("AddAccessAllowedAce failure: lasterror = %d \n",
975 GetLastError());
976 }
977 FREE_C_HEAP_ARRAY(char, newACL);
978 return false;
979 }
980 }
982 // now copy the rest of the inherited ACEs from the old ACL
983 if (aclinfo.AceCount != 0) {
984 // picking up at ace_index, where we left off in the
985 // previous ace_index loop
986 while (ace_index < aclinfo.AceCount) {
987 LPVOID ace;
988 if (!GetAce(oldACL, ace_index, &ace)) {
989 if (PrintMiscellaneous && Verbose) {
990 warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
991 }
992 FREE_C_HEAP_ARRAY(char, newACL);
993 return false;
994 }
995 if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
996 ((PACE_HEADER)ace)->AceSize)) {
997 if (PrintMiscellaneous && Verbose) {
998 warning("AddAce failure: lasterror = %d \n", GetLastError());
999 }
1000 FREE_C_HEAP_ARRAY(char, newACL);
1001 return false;
1002 }
1003 ace_index++;
1004 }
1005 }
1007 // add the new ACL to the security descriptor.
1008 if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) {
1009 if (PrintMiscellaneous && Verbose) {
1010 warning("SetSecurityDescriptorDacl failure:"
1011 " lasterror = %d \n", GetLastError());
1012 }
1013 FREE_C_HEAP_ARRAY(char, newACL);
1014 return false;
1015 }
1017 // if running on windows 2000 or later, set the automatic inheritance
1018 // control flags.
1019 SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl;
1020 _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr)
1021 GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")),
1022 "SetSecurityDescriptorControl");
1024 if (_SetSecurityDescriptorControl != NULL) {
1025 // We do not want to further propagate inherited DACLs, so making them
1026 // protected prevents that.
1027 if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED,
1028 SE_DACL_PROTECTED)) {
1029 if (PrintMiscellaneous && Verbose) {
1030 warning("SetSecurityDescriptorControl failure:"
1031 " lasterror = %d \n", GetLastError());
1032 }
1033 FREE_C_HEAP_ARRAY(char, newACL);
1034 return false;
1035 }
1036 }
1037 // Note, the security descriptor maintains a reference to the newACL, not
1038 // a copy of it. Therefore, the newACL is not freed here. It is freed when
1039 // the security descriptor containing its reference is freed.
1040 //
1041 return true;
1042 }
1044 // method to create a security attributes structure, which contains a
1045 // security descriptor and an access control list comprised of 0 or more
1046 // access control entries. The method take an array of ace_data structures
1047 // that indicate the ACE to be added to the security descriptor.
1048 //
1049 // the caller must free the resources associated with the security
1050 // attributes structure created by this method by calling the
1051 // free_security_attr() method.
1052 //
1053 static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) {
1055 // allocate space for a security descriptor
1056 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)
1057 NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH);
1059 // initialize the security descriptor
1060 if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
1061 if (PrintMiscellaneous && Verbose) {
1062 warning("InitializeSecurityDescriptor failure: "
1063 "lasterror = %d \n", GetLastError());
1064 }
1065 free_security_desc(pSD);
1066 return NULL;
1067 }
1069 // add the access control entries
1070 if (!add_allow_aces(pSD, aces, count)) {
1071 free_security_desc(pSD);
1072 return NULL;
1073 }
1075 // allocate and initialize the security attributes structure and
1076 // return it to the caller.
1077 //
1078 LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES)
1079 NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES));
1080 lpSA->nLength = sizeof(SECURITY_ATTRIBUTES);
1081 lpSA->lpSecurityDescriptor = pSD;
1082 lpSA->bInheritHandle = FALSE;
1084 return(lpSA);
1085 }
1087 // method to create a security attributes structure with a restrictive
1088 // access control list that creates a set access rights for the user/owner
1089 // of the securable object and a separate set access rights for everyone else.
1090 // also provides for full access rights for the administrator group.
1091 //
1092 // the caller must free the resources associated with the security
1093 // attributes structure created by this method by calling the
1094 // free_security_attr() method.
1095 //
1097 static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr(
1098 DWORD umask, DWORD emask, DWORD amask) {
1100 ace_data_t aces[3];
1102 // initialize the user ace data
1103 aces[0].pSid = get_user_sid(GetCurrentProcess());
1104 aces[0].mask = umask;
1106 if (aces[0].pSid == 0)
1107 return NULL;
1109 // get the well known SID for BUILTIN\Administrators
1110 PSID administratorsSid = NULL;
1111 SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY;
1113 if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2,
1114 SECURITY_BUILTIN_DOMAIN_RID,
1115 DOMAIN_ALIAS_RID_ADMINS,
1116 0, 0, 0, 0, 0, 0, &administratorsSid)) {
1118 if (PrintMiscellaneous && Verbose) {
1119 warning("AllocateAndInitializeSid failure: "
1120 "lasterror = %d \n", GetLastError());
1121 }
1122 return NULL;
1123 }
1125 // initialize the ace data for administrator group
1126 aces[1].pSid = administratorsSid;
1127 aces[1].mask = amask;
1129 // get the well known SID for the universal Everybody
1130 PSID everybodySid = NULL;
1131 SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY;
1133 if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID,
1134 0, 0, 0, 0, 0, 0, 0, &everybodySid)) {
1136 if (PrintMiscellaneous && Verbose) {
1137 warning("AllocateAndInitializeSid failure: "
1138 "lasterror = %d \n", GetLastError());
1139 }
1140 return NULL;
1141 }
1143 // initialize the ace data for everybody else.
1144 aces[2].pSid = everybodySid;
1145 aces[2].mask = emask;
1147 // create a security attributes structure with access control
1148 // entries as initialized above.
1149 LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3);
1150 FREE_C_HEAP_ARRAY(char, aces[0].pSid);
1151 FreeSid(everybodySid);
1152 FreeSid(administratorsSid);
1153 return(lpSA);
1154 }
1157 // method to create the security attributes structure for restricting
1158 // access to the user temporary directory.
1159 //
1160 // the caller must free the resources associated with the security
1161 // attributes structure created by this method by calling the
1162 // free_security_attr() method.
1163 //
1164 static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() {
1166 // create full access rights for the user/owner of the directory
1167 // and read-only access rights for everybody else. This is
1168 // effectively equivalent to UNIX 755 permissions on a directory.
1169 //
1170 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS;
1171 DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1172 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1174 return make_user_everybody_admin_security_attr(umask, emask, amask);
1175 }
1177 // method to create the security attributes structure for restricting
1178 // access to the shared memory backing store file.
1179 //
1180 // the caller must free the resources associated with the security
1181 // attributes structure created by this method by calling the
1182 // free_security_attr() method.
1183 //
1184 static LPSECURITY_ATTRIBUTES make_file_security_attr() {
1186 // create extensive access rights for the user/owner of the file
1187 // and attribute read-only access rights for everybody else. This
1188 // is effectively equivalent to UNIX 600 permissions on a file.
1189 //
1190 DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1191 DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES |
1192 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1193 DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1195 return make_user_everybody_admin_security_attr(umask, emask, amask);
1196 }
1198 // method to create the security attributes structure for restricting
1199 // access to the name shared memory file mapping object.
1200 //
1201 // the caller must free the resources associated with the security
1202 // attributes structure created by this method by calling the
1203 // free_security_attr() method.
1204 //
1205 static LPSECURITY_ATTRIBUTES make_smo_security_attr() {
1207 // create extensive access rights for the user/owner of the shared
1208 // memory object and attribute read-only access rights for everybody
1209 // else. This is effectively equivalent to UNIX 600 permissions on
1210 // on the shared memory object.
1211 //
1212 DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS;
1213 DWORD emask = STANDARD_RIGHTS_READ; // attributes only
1214 DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS;
1216 return make_user_everybody_admin_security_attr(umask, emask, amask);
1217 }
1219 // make the user specific temporary directory
1220 //
1221 static bool make_user_tmp_dir(const char* dirname) {
1224 LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr();
1225 if (pDirSA == NULL) {
1226 return false;
1227 }
1230 // create the directory with the given security attributes
1231 if (!CreateDirectory(dirname, pDirSA)) {
1232 DWORD lasterror = GetLastError();
1233 if (lasterror == ERROR_ALREADY_EXISTS) {
1234 // The directory already exists and was probably created by another
1235 // JVM instance. However, this could also be the result of a
1236 // deliberate symlink. Verify that the existing directory is safe.
1237 //
1238 if (!is_directory_secure(dirname)) {
1239 // directory is not secure
1240 if (PrintMiscellaneous && Verbose) {
1241 warning("%s directory is insecure\n", dirname);
1242 }
1243 return false;
1244 }
1245 // The administrator should be able to delete this directory.
1246 // But the directory created by previous version of JVM may not
1247 // have permission for administrators to delete this directory.
1248 // So add full permission to the administrator. Also setting new
1249 // DACLs might fix the corrupted the DACLs.
1250 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION;
1251 if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) {
1252 if (PrintMiscellaneous && Verbose) {
1253 lasterror = GetLastError();
1254 warning("SetFileSecurity failed for %s directory. lasterror %d \n",
1255 dirname, lasterror);
1256 }
1257 }
1258 }
1259 else {
1260 if (PrintMiscellaneous && Verbose) {
1261 warning("CreateDirectory failed: %d\n", GetLastError());
1262 }
1263 return false;
1264 }
1265 }
1267 // free the security attributes structure
1268 free_security_attr(pDirSA);
1270 return true;
1271 }
1273 // create the shared memory resources
1274 //
1275 // This function creates the shared memory resources. This includes
1276 // the backing store file and the file mapping shared memory object.
1277 //
1278 static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) {
1280 HANDLE fh = INVALID_HANDLE_VALUE;
1281 HANDLE fmh = NULL;
1284 // create the security attributes for the backing store file
1285 LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr();
1286 if (lpFileSA == NULL) {
1287 return NULL;
1288 }
1290 // create the security attributes for the shared memory object
1291 LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr();
1292 if (lpSmoSA == NULL) {
1293 free_security_attr(lpFileSA);
1294 return NULL;
1295 }
1297 // create the user temporary directory
1298 if (!make_user_tmp_dir(dirname)) {
1299 // could not make/find the directory or the found directory
1300 // was not secure
1301 return NULL;
1302 }
1304 // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the
1305 // file to be deleted by the last process that closes its handle to
1306 // the file. This is important as the apis do not allow a terminating
1307 // JVM being monitored by another process to remove the file name.
1308 //
1309 // the FILE_SHARE_DELETE share mode is valid only in winnt
1310 //
1311 fh = CreateFile(
1312 filename, /* LPCTSTR file name */
1314 GENERIC_READ|GENERIC_WRITE, /* DWORD desired access */
1316 (os::win32::is_nt() ? FILE_SHARE_DELETE : 0)|
1317 FILE_SHARE_READ, /* DWORD share mode, future READONLY
1318 * open operations allowed
1319 */
1320 lpFileSA, /* LPSECURITY security attributes */
1321 CREATE_ALWAYS, /* DWORD creation disposition
1322 * create file, if it already
1323 * exists, overwrite it.
1324 */
1325 FILE_FLAG_DELETE_ON_CLOSE, /* DWORD flags and attributes */
1327 NULL); /* HANDLE template file access */
1329 free_security_attr(lpFileSA);
1331 if (fh == INVALID_HANDLE_VALUE) {
1332 DWORD lasterror = GetLastError();
1333 if (PrintMiscellaneous && Verbose) {
1334 warning("could not create file %s: %d\n", filename, lasterror);
1335 }
1336 return NULL;
1337 }
1339 // try to create the file mapping
1340 fmh = create_file_mapping(objectname, fh, lpSmoSA, size);
1342 free_security_attr(lpSmoSA);
1344 if (fmh == NULL) {
1345 // closing the file handle here will decrement the reference count
1346 // on the file. When all processes accessing the file close their
1347 // handle to it, the reference count will decrement to 0 and the
1348 // OS will delete the file. These semantics are requested by the
1349 // FILE_FLAG_DELETE_ON_CLOSE flag in CreateFile call above.
1350 CloseHandle(fh);
1351 fh = NULL;
1352 return NULL;
1353 } else {
1354 // We created the file mapping, but rarely the size of the
1355 // backing store file is reported as zero (0) which can cause
1356 // failures when trying to use the hsperfdata file.
1357 struct stat statbuf;
1358 int ret_code = ::stat(filename, &statbuf);
1359 if (ret_code == OS_ERR) {
1360 if (PrintMiscellaneous && Verbose) {
1361 warning("Could not get status information from file %s: %s\n",
1362 filename, strerror(errno));
1363 }
1364 CloseHandle(fmh);
1365 CloseHandle(fh);
1366 fh = NULL;
1367 fmh = NULL;
1368 return NULL;
1369 }
1371 // We could always call FlushFileBuffers() but the Microsoft
1372 // docs indicate that it is considered expensive so we only
1373 // call it when we observe the size as zero (0).
1374 if (statbuf.st_size == 0 && FlushFileBuffers(fh) != TRUE) {
1375 DWORD lasterror = GetLastError();
1376 if (PrintMiscellaneous && Verbose) {
1377 warning("could not flush file %s: %d\n", filename, lasterror);
1378 }
1379 CloseHandle(fmh);
1380 CloseHandle(fh);
1381 fh = NULL;
1382 fmh = NULL;
1383 return NULL;
1384 }
1385 }
1387 // the file has been successfully created and the file mapping
1388 // object has been created.
1389 sharedmem_fileHandle = fh;
1390 sharedmem_fileName = strdup(filename);
1392 return fmh;
1393 }
1395 // open the shared memory object for the given vmid.
1396 //
1397 static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) {
1399 HANDLE fmh;
1401 // open the file mapping with the requested mode
1402 fmh = OpenFileMapping(
1403 ofm_access, /* DWORD access mode */
1404 FALSE, /* BOOL inherit flag - Do not allow inherit */
1405 objectname); /* name for object */
1407 if (fmh == NULL) {
1408 if (PrintMiscellaneous && Verbose) {
1409 warning("OpenFileMapping failed for shared memory object %s:"
1410 " lasterror = %d\n", objectname, GetLastError());
1411 }
1412 THROW_MSG_(vmSymbols::java_lang_Exception(),
1413 "Could not open PerfMemory", INVALID_HANDLE_VALUE);
1414 }
1416 return fmh;;
1417 }
1419 // create a named shared memory region
1420 //
1421 // On Win32, a named shared memory object has a name space that
1422 // is independent of the file system name space. Shared memory object,
1423 // or more precisely, file mapping objects, provide no mechanism to
1424 // inquire the size of the memory region. There is also no api to
1425 // enumerate the memory regions for various processes.
1426 //
1427 // This implementation utilizes the shared memory name space in parallel
1428 // with the file system name space. This allows us to determine the
1429 // size of the shared memory region from the size of the file and it
1430 // allows us to provide a common, file system based name space for
1431 // shared memory across platforms.
1432 //
1433 static char* mapping_create_shared(size_t size) {
1435 void *mapAddress;
1436 int vmid = os::current_process_id();
1438 // get the name of the user associated with this process
1439 char* user = get_user_name();
1441 if (user == NULL) {
1442 return NULL;
1443 }
1445 // construct the name of the user specific temporary directory
1446 char* dirname = get_user_tmp_dir(user);
1448 // check that the file system is secure - i.e. it supports ACLs.
1449 if (!is_filesystem_secure(dirname)) {
1450 return NULL;
1451 }
1453 // create the names of the backing store files and for the
1454 // share memory object.
1455 //
1456 char* filename = get_sharedmem_filename(dirname, vmid);
1457 char* objectname = get_sharedmem_objectname(user, vmid);
1459 // cleanup any stale shared memory resources
1460 cleanup_sharedmem_resources(dirname);
1462 assert(((size != 0) && (size % os::vm_page_size() == 0)),
1463 "unexpected PerfMemry region size");
1465 FREE_C_HEAP_ARRAY(char, user);
1467 // create the shared memory resources
1468 sharedmem_fileMapHandle =
1469 create_sharedmem_resources(dirname, filename, objectname, size);
1471 FREE_C_HEAP_ARRAY(char, filename);
1472 FREE_C_HEAP_ARRAY(char, objectname);
1473 FREE_C_HEAP_ARRAY(char, dirname);
1475 if (sharedmem_fileMapHandle == NULL) {
1476 return NULL;
1477 }
1479 // map the file into the address space
1480 mapAddress = MapViewOfFile(
1481 sharedmem_fileMapHandle, /* HANDLE = file mapping object */
1482 FILE_MAP_ALL_ACCESS, /* DWORD access flags */
1483 0, /* DWORD High word of offset */
1484 0, /* DWORD Low word of offset */
1485 (DWORD)size); /* DWORD Number of bytes to map */
1487 if (mapAddress == NULL) {
1488 if (PrintMiscellaneous && Verbose) {
1489 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1490 }
1491 CloseHandle(sharedmem_fileMapHandle);
1492 sharedmem_fileMapHandle = NULL;
1493 return NULL;
1494 }
1496 // clear the shared memory region
1497 (void)memset(mapAddress, '\0', size);
1499 return (char*) mapAddress;
1500 }
1502 // this method deletes the file mapping object.
1503 //
1504 static void delete_file_mapping(char* addr, size_t size) {
1506 // cleanup the persistent shared memory resources. since DestroyJavaVM does
1507 // not support unloading of the JVM, unmapping of the memory resource is not
1508 // performed. The memory will be reclaimed by the OS upon termination of all
1509 // processes mapping the resource. The file mapping handle and the file
1510 // handle are closed here to expedite the remove of the file by the OS. The
1511 // file is not removed directly because it was created with
1512 // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would
1513 // be unsuccessful.
1515 // close the fileMapHandle. the file mapping will still be retained
1516 // by the OS as long as any other JVM processes has an open file mapping
1517 // handle or a mapped view of the file.
1518 //
1519 if (sharedmem_fileMapHandle != NULL) {
1520 CloseHandle(sharedmem_fileMapHandle);
1521 sharedmem_fileMapHandle = NULL;
1522 }
1524 // close the file handle. This will decrement the reference count on the
1525 // backing store file. When the reference count decrements to 0, the OS
1526 // will delete the file. These semantics apply because the file was
1527 // created with the FILE_FLAG_DELETE_ON_CLOSE flag.
1528 //
1529 if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) {
1530 CloseHandle(sharedmem_fileHandle);
1531 sharedmem_fileHandle = INVALID_HANDLE_VALUE;
1532 }
1533 }
1535 // this method determines the size of the shared memory file
1536 //
1537 static size_t sharedmem_filesize(const char* filename, TRAPS) {
1539 struct stat statbuf;
1541 // get the file size
1542 //
1543 // on win95/98/me, _stat returns a file size of 0 bytes, but on
1544 // winnt/2k the appropriate file size is returned. support for
1545 // the sharable aspects of performance counters was abandonded
1546 // on the non-nt win32 platforms due to this and other api
1547 // inconsistencies
1548 //
1549 if (::stat(filename, &statbuf) == OS_ERR) {
1550 if (PrintMiscellaneous && Verbose) {
1551 warning("stat %s failed: %s\n", filename, strerror(errno));
1552 }
1553 THROW_MSG_0(vmSymbols::java_io_IOException(),
1554 "Could not determine PerfMemory size");
1555 }
1557 if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) {
1558 if (PrintMiscellaneous && Verbose) {
1559 warning("unexpected file size: size = " SIZE_FORMAT "\n",
1560 statbuf.st_size);
1561 }
1562 THROW_MSG_0(vmSymbols::java_lang_Exception(),
1563 "Invalid PerfMemory size");
1564 }
1566 return statbuf.st_size;
1567 }
1569 // this method opens a file mapping object and maps the object
1570 // into the address space of the process
1571 //
1572 static void open_file_mapping(const char* user, int vmid,
1573 PerfMemory::PerfMemoryMode mode,
1574 char** addrp, size_t* sizep, TRAPS) {
1576 ResourceMark rm;
1578 void *mapAddress = 0;
1579 size_t size;
1580 HANDLE fmh;
1581 DWORD ofm_access;
1582 DWORD mv_access;
1583 const char* luser = NULL;
1585 if (mode == PerfMemory::PERF_MODE_RO) {
1586 ofm_access = FILE_MAP_READ;
1587 mv_access = FILE_MAP_READ;
1588 }
1589 else if (mode == PerfMemory::PERF_MODE_RW) {
1590 #ifdef LATER
1591 ofm_access = FILE_MAP_READ | FILE_MAP_WRITE;
1592 mv_access = FILE_MAP_READ | FILE_MAP_WRITE;
1593 #else
1594 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1595 "Unsupported access mode");
1596 #endif
1597 }
1598 else {
1599 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1600 "Illegal access mode");
1601 }
1603 // if a user name wasn't specified, then find the user name for
1604 // the owner of the target vm.
1605 if (user == NULL || strlen(user) == 0) {
1606 luser = get_user_name(vmid);
1607 }
1608 else {
1609 luser = user;
1610 }
1612 if (luser == NULL) {
1613 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1614 "Could not map vmid to user name");
1615 }
1617 // get the names for the resources for the target vm
1618 char* dirname = get_user_tmp_dir(luser);
1620 // since we don't follow symbolic links when creating the backing
1621 // store file, we also don't following them when attaching
1622 //
1623 if (!is_directory_secure(dirname)) {
1624 FREE_C_HEAP_ARRAY(char, dirname);
1625 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1626 "Process not found");
1627 }
1629 char* filename = get_sharedmem_filename(dirname, vmid);
1630 char* objectname = get_sharedmem_objectname(luser, vmid);
1632 // copy heap memory to resource memory. the objectname and
1633 // filename are passed to methods that may throw exceptions.
1634 // using resource arrays for these names prevents the leaks
1635 // that would otherwise occur.
1636 //
1637 char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
1638 char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1);
1639 strcpy(rfilename, filename);
1640 strcpy(robjectname, objectname);
1642 // free the c heap resources that are no longer needed
1643 if (luser != user) FREE_C_HEAP_ARRAY(char, luser);
1644 FREE_C_HEAP_ARRAY(char, dirname);
1645 FREE_C_HEAP_ARRAY(char, filename);
1646 FREE_C_HEAP_ARRAY(char, objectname);
1648 if (*sizep == 0) {
1649 size = sharedmem_filesize(rfilename, CHECK);
1650 assert(size != 0, "unexpected size");
1651 }
1653 // Open the file mapping object with the given name
1654 fmh = open_sharedmem_object(robjectname, ofm_access, CHECK);
1656 assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value");
1658 // map the entire file into the address space
1659 mapAddress = MapViewOfFile(
1660 fmh, /* HANDLE Handle of file mapping object */
1661 mv_access, /* DWORD access flags */
1662 0, /* DWORD High word of offset */
1663 0, /* DWORD Low word of offset */
1664 size); /* DWORD Number of bytes to map */
1666 if (mapAddress == NULL) {
1667 if (PrintMiscellaneous && Verbose) {
1668 warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1669 }
1670 CloseHandle(fmh);
1671 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
1672 "Could not map PerfMemory");
1673 }
1675 *addrp = (char*)mapAddress;
1676 *sizep = size;
1678 // File mapping object can be closed at this time without
1679 // invalidating the mapped view of the file
1680 CloseHandle(fmh);
1682 if (PerfTraceMemOps) {
1683 tty->print("mapped " SIZE_FORMAT " bytes for vmid %d at "
1684 INTPTR_FORMAT "\n", size, vmid, mapAddress);
1685 }
1686 }
1688 // this method unmaps the the mapped view of the the
1689 // file mapping object.
1690 //
1691 static void remove_file_mapping(char* addr) {
1693 // the file mapping object was closed in open_file_mapping()
1694 // after the file map view was created. We only need to
1695 // unmap the file view here.
1696 UnmapViewOfFile(addr);
1697 }
1699 // create the PerfData memory region in shared memory.
1700 static char* create_shared_memory(size_t size) {
1702 return mapping_create_shared(size);
1703 }
1705 // release a named, shared memory region
1706 //
1707 void delete_shared_memory(char* addr, size_t size) {
1709 delete_file_mapping(addr, size);
1710 }
1715 // create the PerfData memory region
1716 //
1717 // This method creates the memory region used to store performance
1718 // data for the JVM. The memory may be created in standard or
1719 // shared memory.
1720 //
1721 void PerfMemory::create_memory_region(size_t size) {
1723 if (PerfDisableSharedMem || !os::win32::is_nt()) {
1724 // do not share the memory for the performance data.
1725 PerfDisableSharedMem = true;
1726 _start = create_standard_memory(size);
1727 }
1728 else {
1729 _start = create_shared_memory(size);
1730 if (_start == NULL) {
1732 // creation of the shared memory region failed, attempt
1733 // to create a contiguous, non-shared memory region instead.
1734 //
1735 if (PrintMiscellaneous && Verbose) {
1736 warning("Reverting to non-shared PerfMemory region.\n");
1737 }
1738 PerfDisableSharedMem = true;
1739 _start = create_standard_memory(size);
1740 }
1741 }
1743 if (_start != NULL) _capacity = size;
1745 }
1747 // delete the PerfData memory region
1748 //
1749 // This method deletes the memory region used to store performance
1750 // data for the JVM. The memory region indicated by the <address, size>
1751 // tuple will be inaccessible after a call to this method.
1752 //
1753 void PerfMemory::delete_memory_region() {
1755 assert((start() != NULL && capacity() > 0), "verify proper state");
1757 // If user specifies PerfDataSaveFile, it will save the performance data
1758 // to the specified file name no matter whether PerfDataSaveToFile is specified
1759 // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1760 // -XX:+PerfDataSaveToFile.
1761 if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1762 save_memory_to_file(start(), capacity());
1763 }
1765 if (PerfDisableSharedMem) {
1766 delete_standard_memory(start(), capacity());
1767 }
1768 else {
1769 delete_shared_memory(start(), capacity());
1770 }
1771 }
1773 // attach to the PerfData memory region for another JVM
1774 //
1775 // This method returns an <address, size> tuple that points to
1776 // a memory buffer that is kept reasonably synchronized with
1777 // the PerfData memory region for the indicated JVM. This
1778 // buffer may be kept in synchronization via shared memory
1779 // or some other mechanism that keeps the buffer updated.
1780 //
1781 // If the JVM chooses not to support the attachability feature,
1782 // this method should throw an UnsupportedOperation exception.
1783 //
1784 // This implementation utilizes named shared memory to map
1785 // the indicated process's PerfData memory region into this JVMs
1786 // address space.
1787 //
1788 void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode,
1789 char** addrp, size_t* sizep, TRAPS) {
1791 if (vmid == 0 || vmid == os::current_process_id()) {
1792 *addrp = start();
1793 *sizep = capacity();
1794 return;
1795 }
1797 open_file_mapping(user, vmid, mode, addrp, sizep, CHECK);
1798 }
1800 // detach from the PerfData memory region of another JVM
1801 //
1802 // This method detaches the PerfData memory region of another
1803 // JVM, specified as an <address, size> tuple of a buffer
1804 // in this process's address space. This method may perform
1805 // arbitrary actions to accomplish the detachment. The memory
1806 // region specified by <address, size> will be inaccessible after
1807 // a call to this method.
1808 //
1809 // If the JVM chooses not to support the attachability feature,
1810 // this method should throw an UnsupportedOperation exception.
1811 //
1812 // This implementation utilizes named shared memory to detach
1813 // the indicated process's PerfData memory region from this
1814 // process's address space.
1815 //
1816 void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
1818 assert(addr != 0, "address sanity check");
1819 assert(bytes > 0, "capacity sanity check");
1821 if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1822 // prevent accidental detachment of this process's PerfMemory region
1823 return;
1824 }
1826 remove_file_mapping(addr);
1827 }
1829 char* PerfMemory::backing_store_filename() {
1830 return sharedmem_fileName;
1831 }