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