1/*
2 * Copyright (c) 2001, 2017, 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
44typedef 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//
53static 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//
76static 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//
89static 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
150static HANDLE sharedmem_fileMapHandle = NULL;
151static HANDLE sharedmem_fileHandle = INVALID_HANDLE_VALUE;
152static 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//
158static 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//
174static 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//
210static 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//
267static 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//
301static 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  char* tdbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(tmpdirname), mtInternal);
322  errno = 0;
323  while ((dentry = os::readdir(tmpdirp, (struct dirent *)tdbuf)) != NULL) {
324
325    // check if the directory entry is a hsperfdata file
326    if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
327      continue;
328    }
329
330    char* usrdir_name = NEW_C_HEAP_ARRAY(char,
331        strlen(tmpdirname) + strlen(dentry->d_name) + 2, mtInternal);
332    strcpy(usrdir_name, tmpdirname);
333    strcat(usrdir_name, "\\");
334    strcat(usrdir_name, dentry->d_name);
335
336    DIR* subdirp = os::opendir(usrdir_name);
337
338    if (subdirp == NULL) {
339      FREE_C_HEAP_ARRAY(char, usrdir_name);
340      continue;
341    }
342
343    // Since we don't create the backing store files in directories
344    // pointed to by symbolic links, we also don't follow them when
345    // looking for the files. We check for a symbolic link after the
346    // call to opendir in order to eliminate a small window where the
347    // symlink can be exploited.
348    //
349    if (!is_directory_secure(usrdir_name)) {
350      FREE_C_HEAP_ARRAY(char, usrdir_name);
351      os::closedir(subdirp);
352      continue;
353    }
354
355    struct dirent* udentry;
356    char* udbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(usrdir_name), mtInternal);
357    errno = 0;
358    while ((udentry = os::readdir(subdirp, (struct dirent *)udbuf)) != NULL) {
359
360      if (filename_to_pid(udentry->d_name) == vmid) {
361        struct stat statbuf;
362
363        char* filename = NEW_C_HEAP_ARRAY(char,
364           strlen(usrdir_name) + strlen(udentry->d_name) + 2, mtInternal);
365
366        strcpy(filename, usrdir_name);
367        strcat(filename, "\\");
368        strcat(filename, udentry->d_name);
369
370        if (::stat(filename, &statbuf) == OS_ERR) {
371           FREE_C_HEAP_ARRAY(char, filename);
372           continue;
373        }
374
375        // skip over files that are not regular files.
376        if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
377          FREE_C_HEAP_ARRAY(char, filename);
378          continue;
379        }
380
381        // If we found a matching file with a newer creation time, then
382        // save the user name. The newer creation time indicates that
383        // we found a newer incarnation of the process associated with
384        // vmid. Due to the way that Windows recycles pids and the fact
385        // that we can't delete the file from the file system namespace
386        // until last close, it is possible for there to be more than
387        // one hsperfdata file with a name matching vmid (diff users).
388        //
389        // We no longer ignore hsperfdata files where (st_size == 0).
390        // In this function, all we're trying to do is determine the
391        // name of the user that owns the process associated with vmid
392        // so the size doesn't matter. Very rarely, we have observed
393        // hsperfdata files where (st_size == 0) and the st_size field
394        // later becomes the expected value.
395        //
396        if (statbuf.st_ctime > latest_ctime) {
397          char* user = strchr(dentry->d_name, '_') + 1;
398
399          if (latest_user != NULL) FREE_C_HEAP_ARRAY(char, latest_user);
400          latest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
401
402          strcpy(latest_user, user);
403          latest_ctime = statbuf.st_ctime;
404        }
405
406        FREE_C_HEAP_ARRAY(char, filename);
407      }
408    }
409    os::closedir(subdirp);
410    FREE_C_HEAP_ARRAY(char, udbuf);
411    FREE_C_HEAP_ARRAY(char, usrdir_name);
412  }
413  os::closedir(tmpdirp);
414  FREE_C_HEAP_ARRAY(char, tdbuf);
415
416  return(latest_user);
417}
418
419// return the name of the user that owns the process identified by vmid.
420//
421// note: this method should only be used via the Perf native methods.
422// There are various costs to this method and limiting its use to the
423// Perf native methods limits the impact to monitoring applications only.
424//
425static char* get_user_name(int vmid) {
426
427  // A fast implementation is not provided at this time. It's possible
428  // to provide a fast process id to user name mapping function using
429  // the win32 apis, but the default ACL for the process object only
430  // allows processes with the same owner SID to acquire the process
431  // handle (via OpenProcess(PROCESS_QUERY_INFORMATION)). It's possible
432  // to have the JVM change the ACL for the process object to allow arbitrary
433  // users to access the process handle and the process security token.
434  // The security ramifications need to be studied before providing this
435  // mechanism.
436  //
437  return get_user_name_slow(vmid);
438}
439
440// return the name of the shared memory file mapping object for the
441// named shared memory region for the given user name and vmid.
442//
443// The file mapping object's name is not the file name. It is a name
444// in a separate name space.
445//
446// the caller is expected to free the allocated memory.
447//
448static char *get_sharedmem_objectname(const char* user, int vmid) {
449
450  // construct file mapping object's name, add 3 for two '_' and a
451  // null terminator.
452  int nbytes = (int)strlen(PERFDATA_NAME) + (int)strlen(user) + 3;
453
454  // the id is converted to an unsigned value here because win32 allows
455  // negative process ids. However, OpenFileMapping API complains
456  // about a name containing a '-' characters.
457  //
458  nbytes += UINT_CHARS;
459  char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
460  _snprintf(name, nbytes, "%s_%s_%u", PERFDATA_NAME, user, vmid);
461
462  return name;
463}
464
465// return the file name of the backing store file for the named
466// shared memory region for the given user name and vmid.
467//
468// the caller is expected to free the allocated memory.
469//
470static char* get_sharedmem_filename(const char* dirname, int vmid) {
471
472  // add 2 for the file separator and a null terminator.
473  size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
474
475  char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
476  _snprintf(name, nbytes, "%s\\%d", dirname, vmid);
477
478  return name;
479}
480
481// remove file
482//
483// this method removes the file with the given file name.
484//
485// Note: if the indicated file is on an SMB network file system, this
486// method may be unsuccessful in removing the file.
487//
488static void remove_file(const char* dirname, const char* filename) {
489
490  size_t nbytes = strlen(dirname) + strlen(filename) + 2;
491  char* path = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
492
493  strcpy(path, dirname);
494  strcat(path, "\\");
495  strcat(path, filename);
496
497  if (::unlink(path) == OS_ERR) {
498    if (PrintMiscellaneous && Verbose) {
499      if (errno != ENOENT) {
500        warning("Could not unlink shared memory backing"
501                " store file %s : %s\n", path, os::strerror(errno));
502      }
503    }
504  }
505
506  FREE_C_HEAP_ARRAY(char, path);
507}
508
509// returns true if the process represented by pid is alive, otherwise
510// returns false. the validity of the result is only accurate if the
511// target process is owned by the same principal that owns this process.
512// this method should not be used if to test the status of an otherwise
513// arbitrary process unless it is know that this process has the appropriate
514// privileges to guarantee a result valid.
515//
516static bool is_alive(int pid) {
517
518  HANDLE ph = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
519  if (ph == NULL) {
520    // the process does not exist.
521    if (PrintMiscellaneous && Verbose) {
522      DWORD lastError = GetLastError();
523      if (lastError != ERROR_INVALID_PARAMETER) {
524        warning("OpenProcess failed: %d\n", GetLastError());
525      }
526    }
527    return false;
528  }
529
530  DWORD exit_status;
531  if (!GetExitCodeProcess(ph, &exit_status)) {
532    if (PrintMiscellaneous && Verbose) {
533      warning("GetExitCodeProcess failed: %d\n", GetLastError());
534    }
535    CloseHandle(ph);
536    return false;
537  }
538
539  CloseHandle(ph);
540  return (exit_status == STILL_ACTIVE) ? true : false;
541}
542
543// check if the file system is considered secure for the backing store files
544//
545static bool is_filesystem_secure(const char* path) {
546
547  char root_path[MAX_PATH];
548  char fs_type[MAX_PATH];
549
550  if (PerfBypassFileSystemCheck) {
551    if (PrintMiscellaneous && Verbose) {
552      warning("bypassing file system criteria checks for %s\n", path);
553    }
554    return true;
555  }
556
557  char* first_colon = strchr((char *)path, ':');
558  if (first_colon == NULL) {
559    if (PrintMiscellaneous && Verbose) {
560      warning("expected device specifier in path: %s\n", path);
561    }
562    return false;
563  }
564
565  size_t len = (size_t)(first_colon - path);
566  assert(len + 2 <= MAX_PATH, "unexpected device specifier length");
567  strncpy(root_path, path, len + 1);
568  root_path[len + 1] = '\\';
569  root_path[len + 2] = '\0';
570
571  // check that we have something like "C:\" or "AA:\"
572  assert(strlen(root_path) >= 3, "device specifier too short");
573  assert(strchr(root_path, ':') != NULL, "bad device specifier format");
574  assert(strchr(root_path, '\\') != NULL, "bad device specifier format");
575
576  DWORD maxpath;
577  DWORD flags;
578
579  if (!GetVolumeInformation(root_path, NULL, 0, NULL, &maxpath,
580                            &flags, fs_type, MAX_PATH)) {
581    // we can't get information about the volume, so assume unsafe.
582    if (PrintMiscellaneous && Verbose) {
583      warning("could not get device information for %s: "
584              " path = %s: lasterror = %d\n",
585              root_path, path, GetLastError());
586    }
587    return false;
588  }
589
590  if ((flags & FS_PERSISTENT_ACLS) == 0) {
591    // file system doesn't support ACLs, declare file system unsafe
592    if (PrintMiscellaneous && Verbose) {
593      warning("file system type %s on device %s does not support"
594              " ACLs\n", fs_type, root_path);
595    }
596    return false;
597  }
598
599  if ((flags & FS_VOL_IS_COMPRESSED) != 0) {
600    // file system is compressed, declare file system unsafe
601    if (PrintMiscellaneous && Verbose) {
602      warning("file system type %s on device %s is compressed\n",
603              fs_type, root_path);
604    }
605    return false;
606  }
607
608  return true;
609}
610
611// cleanup stale shared memory resources
612//
613// This method attempts to remove all stale shared memory files in
614// the named user temporary directory. It scans the named directory
615// for files matching the pattern ^$[0-9]*$. For each file found, the
616// process id is extracted from the file name and a test is run to
617// determine if the process is alive. If the process is not alive,
618// any stale file resources are removed.
619//
620static void cleanup_sharedmem_resources(const char* dirname) {
621
622  // open the user temp directory
623  DIR* dirp = os::opendir(dirname);
624
625  if (dirp == NULL) {
626    // directory doesn't exist, so there is nothing to cleanup
627    return;
628  }
629
630  if (!is_directory_secure(dirname)) {
631    // the directory is not secure, don't attempt any cleanup
632    os::closedir(dirp);
633    return;
634  }
635
636  // for each entry in the directory that matches the expected file
637  // name pattern, determine if the file resources are stale and if
638  // so, remove the file resources. Note, instrumented HotSpot processes
639  // for this user may start and/or terminate during this search and
640  // remove or create new files in this directory. The behavior of this
641  // loop under these conditions is dependent upon the implementation of
642  // opendir/readdir.
643  //
644  struct dirent* entry;
645  char* dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(dirname), mtInternal);
646  errno = 0;
647  while ((entry = os::readdir(dirp, (struct dirent *)dbuf)) != NULL) {
648
649    int pid = filename_to_pid(entry->d_name);
650
651    if (pid == 0) {
652
653      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
654
655        // attempt to remove all unexpected files, except "." and ".."
656        remove_file(dirname, entry->d_name);
657      }
658
659      errno = 0;
660      continue;
661    }
662
663    // we now have a file name that converts to a valid integer
664    // that could represent a process id . if this process id
665    // matches the current process id or the process is not running,
666    // then remove the stale file resources.
667    //
668    // process liveness is detected by checking the exit status
669    // of the process. if the process id is valid and the exit status
670    // indicates that it is still running, the file file resources
671    // are not removed. If the process id is invalid, or if we don't
672    // have permissions to check the process status, or if the process
673    // id is valid and the process has terminated, the the file resources
674    // are assumed to be stale and are removed.
675    //
676    if (pid == os::current_process_id() || !is_alive(pid)) {
677
678      // we can only remove the file resources. Any mapped views
679      // of the file can only be unmapped by the processes that
680      // opened those views and the file mapping object will not
681      // get removed until all views are unmapped.
682      //
683      remove_file(dirname, entry->d_name);
684    }
685    errno = 0;
686  }
687  os::closedir(dirp);
688  FREE_C_HEAP_ARRAY(char, dbuf);
689}
690
691// create a file mapping object with the requested name, and size
692// from the file represented by the given Handle object
693//
694static HANDLE create_file_mapping(const char* name, HANDLE fh, LPSECURITY_ATTRIBUTES fsa, size_t size) {
695
696  DWORD lowSize = (DWORD)size;
697  DWORD highSize = 0;
698  HANDLE fmh = NULL;
699
700  // Create a file mapping object with the given name. This function
701  // will grow the file to the specified size.
702  //
703  fmh = CreateFileMapping(
704               fh,                 /* HANDLE file handle for backing store */
705               fsa,                /* LPSECURITY_ATTRIBUTES Not inheritable */
706               PAGE_READWRITE,     /* DWORD protections */
707               highSize,           /* DWORD High word of max size */
708               lowSize,            /* DWORD Low word of max size */
709               name);              /* LPCTSTR name for object */
710
711  if (fmh == NULL) {
712    if (PrintMiscellaneous && Verbose) {
713      warning("CreateFileMapping failed, lasterror = %d\n", GetLastError());
714    }
715    return NULL;
716  }
717
718  if (GetLastError() == ERROR_ALREADY_EXISTS) {
719
720    // a stale file mapping object was encountered. This object may be
721    // owned by this or some other user and cannot be removed until
722    // the other processes either exit or close their mapping objects
723    // and/or mapped views of this mapping object.
724    //
725    if (PrintMiscellaneous && Verbose) {
726      warning("file mapping already exists, lasterror = %d\n", GetLastError());
727    }
728
729    CloseHandle(fmh);
730    return NULL;
731  }
732
733  return fmh;
734}
735
736
737// method to free the given security descriptor and the contained
738// access control list.
739//
740static void free_security_desc(PSECURITY_DESCRIPTOR pSD) {
741
742  BOOL success, exists, isdefault;
743  PACL pACL;
744
745  if (pSD != NULL) {
746
747    // get the access control list from the security descriptor
748    success = GetSecurityDescriptorDacl(pSD, &exists, &pACL, &isdefault);
749
750    // if an ACL existed and it was not a default acl, then it must
751    // be an ACL we enlisted. free the resources.
752    //
753    if (success && exists && pACL != NULL && !isdefault) {
754      FREE_C_HEAP_ARRAY(char, pACL);
755    }
756
757    // free the security descriptor
758    FREE_C_HEAP_ARRAY(char, pSD);
759  }
760}
761
762// method to free up a security attributes structure and any
763// contained security descriptors and ACL
764//
765static void free_security_attr(LPSECURITY_ATTRIBUTES lpSA) {
766
767  if (lpSA != NULL) {
768    // free the contained security descriptor and the ACL
769    free_security_desc(lpSA->lpSecurityDescriptor);
770    lpSA->lpSecurityDescriptor = NULL;
771
772    // free the security attributes structure
773    FREE_C_HEAP_ARRAY(char, lpSA);
774  }
775}
776
777// get the user SID for the process indicated by the process handle
778//
779static PSID get_user_sid(HANDLE hProcess) {
780
781  HANDLE hAccessToken;
782  PTOKEN_USER token_buf = NULL;
783  DWORD rsize = 0;
784
785  if (hProcess == NULL) {
786    return NULL;
787  }
788
789  // get the process token
790  if (!OpenProcessToken(hProcess, TOKEN_READ, &hAccessToken)) {
791    if (PrintMiscellaneous && Verbose) {
792      warning("OpenProcessToken failure: lasterror = %d \n", GetLastError());
793    }
794    return NULL;
795  }
796
797  // determine the size of the token structured needed to retrieve
798  // the user token information from the access token.
799  //
800  if (!GetTokenInformation(hAccessToken, TokenUser, NULL, rsize, &rsize)) {
801    DWORD lasterror = GetLastError();
802    if (lasterror != ERROR_INSUFFICIENT_BUFFER) {
803      if (PrintMiscellaneous && Verbose) {
804        warning("GetTokenInformation failure: lasterror = %d,"
805                " rsize = %d\n", lasterror, rsize);
806      }
807      CloseHandle(hAccessToken);
808      return NULL;
809    }
810  }
811
812  token_buf = (PTOKEN_USER) NEW_C_HEAP_ARRAY(char, rsize, mtInternal);
813
814  // get the user token information
815  if (!GetTokenInformation(hAccessToken, TokenUser, token_buf, rsize, &rsize)) {
816    if (PrintMiscellaneous && Verbose) {
817      warning("GetTokenInformation failure: lasterror = %d,"
818              " rsize = %d\n", GetLastError(), rsize);
819    }
820    FREE_C_HEAP_ARRAY(char, token_buf);
821    CloseHandle(hAccessToken);
822    return NULL;
823  }
824
825  DWORD nbytes = GetLengthSid(token_buf->User.Sid);
826  PSID pSID = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
827
828  if (!CopySid(nbytes, pSID, token_buf->User.Sid)) {
829    if (PrintMiscellaneous && Verbose) {
830      warning("GetTokenInformation failure: lasterror = %d,"
831              " rsize = %d\n", GetLastError(), rsize);
832    }
833    FREE_C_HEAP_ARRAY(char, token_buf);
834    FREE_C_HEAP_ARRAY(char, pSID);
835    CloseHandle(hAccessToken);
836    return NULL;
837  }
838
839  // close the access token.
840  CloseHandle(hAccessToken);
841  FREE_C_HEAP_ARRAY(char, token_buf);
842
843  return pSID;
844}
845
846// structure used to consolidate access control entry information
847//
848typedef struct ace_data {
849  PSID pSid;      // SID of the ACE
850  DWORD mask;     // mask for the ACE
851} ace_data_t;
852
853
854// method to add an allow access control entry with the access rights
855// indicated in mask for the principal indicated in SID to the given
856// security descriptor. Much of the DACL handling was adapted from
857// the example provided here:
858//      http://support.microsoft.com/kb/102102/EN-US/
859//
860
861static bool add_allow_aces(PSECURITY_DESCRIPTOR pSD,
862                           ace_data_t aces[], int ace_count) {
863  PACL newACL = NULL;
864  PACL oldACL = NULL;
865
866  if (pSD == NULL) {
867    return false;
868  }
869
870  BOOL exists, isdefault;
871
872  // retrieve any existing access control list.
873  if (!GetSecurityDescriptorDacl(pSD, &exists, &oldACL, &isdefault)) {
874    if (PrintMiscellaneous && Verbose) {
875      warning("GetSecurityDescriptor failure: lasterror = %d \n",
876              GetLastError());
877    }
878    return false;
879  }
880
881  // get the size of the DACL
882  ACL_SIZE_INFORMATION aclinfo;
883
884  // GetSecurityDescriptorDacl may return true value for exists (lpbDaclPresent)
885  // while oldACL is NULL for some case.
886  if (oldACL == NULL) {
887    exists = FALSE;
888  }
889
890  if (exists) {
891    if (!GetAclInformation(oldACL, &aclinfo,
892                           sizeof(ACL_SIZE_INFORMATION),
893                           AclSizeInformation)) {
894      if (PrintMiscellaneous && Verbose) {
895        warning("GetAclInformation failure: lasterror = %d \n", GetLastError());
896        return false;
897      }
898    }
899  } else {
900    aclinfo.AceCount = 0; // assume NULL DACL
901    aclinfo.AclBytesFree = 0;
902    aclinfo.AclBytesInUse = sizeof(ACL);
903  }
904
905  // compute the size needed for the new ACL
906  // initial size of ACL is sum of the following:
907  //   * size of ACL structure.
908  //   * size of each ACE structure that ACL is to contain minus the sid
909  //     sidStart member (DWORD) of the ACE.
910  //   * length of the SID that each ACE is to contain.
911  DWORD newACLsize = aclinfo.AclBytesInUse +
912                        (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) * ace_count;
913  for (int i = 0; i < ace_count; i++) {
914     assert(aces[i].pSid != 0, "pSid should not be 0");
915     newACLsize += GetLengthSid(aces[i].pSid);
916  }
917
918  // create the new ACL
919  newACL = (PACL) NEW_C_HEAP_ARRAY(char, newACLsize, mtInternal);
920
921  if (!InitializeAcl(newACL, newACLsize, ACL_REVISION)) {
922    if (PrintMiscellaneous && Verbose) {
923      warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
924    }
925    FREE_C_HEAP_ARRAY(char, newACL);
926    return false;
927  }
928
929  unsigned int ace_index = 0;
930  // copy any existing ACEs from the old ACL (if any) to the new ACL.
931  if (aclinfo.AceCount != 0) {
932    while (ace_index < aclinfo.AceCount) {
933      LPVOID ace;
934      if (!GetAce(oldACL, ace_index, &ace)) {
935        if (PrintMiscellaneous && Verbose) {
936          warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
937        }
938        FREE_C_HEAP_ARRAY(char, newACL);
939        return false;
940      }
941      if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceFlags && INHERITED_ACE) {
942        // this is an inherited, allowed ACE; break from loop so we can
943        // add the new access allowed, non-inherited ACE in the correct
944        // position, immediately following all non-inherited ACEs.
945        break;
946      }
947
948      // determine if the SID of this ACE matches any of the SIDs
949      // for which we plan to set ACEs.
950      int matches = 0;
951      for (int i = 0; i < ace_count; i++) {
952        if (EqualSid(aces[i].pSid, &(((ACCESS_ALLOWED_ACE *)ace)->SidStart))) {
953          matches++;
954          break;
955        }
956      }
957
958      // if there are no SID matches, then add this existing ACE to the new ACL
959      if (matches == 0) {
960        if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
961                    ((PACE_HEADER)ace)->AceSize)) {
962          if (PrintMiscellaneous && Verbose) {
963            warning("AddAce failure: lasterror = %d \n", GetLastError());
964          }
965          FREE_C_HEAP_ARRAY(char, newACL);
966          return false;
967        }
968      }
969      ace_index++;
970    }
971  }
972
973  // add the passed-in access control entries to the new ACL
974  for (int i = 0; i < ace_count; i++) {
975    if (!AddAccessAllowedAce(newACL, ACL_REVISION,
976                             aces[i].mask, aces[i].pSid)) {
977      if (PrintMiscellaneous && Verbose) {
978        warning("AddAccessAllowedAce failure: lasterror = %d \n",
979                GetLastError());
980      }
981      FREE_C_HEAP_ARRAY(char, newACL);
982      return false;
983    }
984  }
985
986  // now copy the rest of the inherited ACEs from the old ACL
987  if (aclinfo.AceCount != 0) {
988    // picking up at ace_index, where we left off in the
989    // previous ace_index loop
990    while (ace_index < aclinfo.AceCount) {
991      LPVOID ace;
992      if (!GetAce(oldACL, ace_index, &ace)) {
993        if (PrintMiscellaneous && Verbose) {
994          warning("InitializeAcl failure: lasterror = %d \n", GetLastError());
995        }
996        FREE_C_HEAP_ARRAY(char, newACL);
997        return false;
998      }
999      if (!AddAce(newACL, ACL_REVISION, MAXDWORD, ace,
1000                  ((PACE_HEADER)ace)->AceSize)) {
1001        if (PrintMiscellaneous && Verbose) {
1002          warning("AddAce failure: lasterror = %d \n", GetLastError());
1003        }
1004        FREE_C_HEAP_ARRAY(char, newACL);
1005        return false;
1006      }
1007      ace_index++;
1008    }
1009  }
1010
1011  // add the new ACL to the security descriptor.
1012  if (!SetSecurityDescriptorDacl(pSD, TRUE, newACL, FALSE)) {
1013    if (PrintMiscellaneous && Verbose) {
1014      warning("SetSecurityDescriptorDacl failure:"
1015              " lasterror = %d \n", GetLastError());
1016    }
1017    FREE_C_HEAP_ARRAY(char, newACL);
1018    return false;
1019  }
1020
1021  // if running on windows 2000 or later, set the automatic inheritance
1022  // control flags.
1023  SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl;
1024  _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr)
1025       GetProcAddress(GetModuleHandle(TEXT("advapi32.dll")),
1026                      "SetSecurityDescriptorControl");
1027
1028  if (_SetSecurityDescriptorControl != NULL) {
1029    // We do not want to further propagate inherited DACLs, so making them
1030    // protected prevents that.
1031    if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED,
1032                                            SE_DACL_PROTECTED)) {
1033      if (PrintMiscellaneous && Verbose) {
1034        warning("SetSecurityDescriptorControl failure:"
1035                " lasterror = %d \n", GetLastError());
1036      }
1037      FREE_C_HEAP_ARRAY(char, newACL);
1038      return false;
1039    }
1040  }
1041   // Note, the security descriptor maintains a reference to the newACL, not
1042   // a copy of it. Therefore, the newACL is not freed here. It is freed when
1043   // the security descriptor containing its reference is freed.
1044   //
1045   return true;
1046}
1047
1048// method to create a security attributes structure, which contains a
1049// security descriptor and an access control list comprised of 0 or more
1050// access control entries. The method take an array of ace_data structures
1051// that indicate the ACE to be added to the security descriptor.
1052//
1053// the caller must free the resources associated with the security
1054// attributes structure created by this method by calling the
1055// free_security_attr() method.
1056//
1057static LPSECURITY_ATTRIBUTES make_security_attr(ace_data_t aces[], int count) {
1058
1059  // allocate space for a security descriptor
1060  PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)
1061     NEW_C_HEAP_ARRAY(char, SECURITY_DESCRIPTOR_MIN_LENGTH, mtInternal);
1062
1063  // initialize the security descriptor
1064  if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) {
1065    if (PrintMiscellaneous && Verbose) {
1066      warning("InitializeSecurityDescriptor failure: "
1067              "lasterror = %d \n", GetLastError());
1068    }
1069    free_security_desc(pSD);
1070    return NULL;
1071  }
1072
1073  // add the access control entries
1074  if (!add_allow_aces(pSD, aces, count)) {
1075    free_security_desc(pSD);
1076    return NULL;
1077  }
1078
1079  // allocate and initialize the security attributes structure and
1080  // return it to the caller.
1081  //
1082  LPSECURITY_ATTRIBUTES lpSA = (LPSECURITY_ATTRIBUTES)
1083    NEW_C_HEAP_ARRAY(char, sizeof(SECURITY_ATTRIBUTES), mtInternal);
1084  lpSA->nLength = sizeof(SECURITY_ATTRIBUTES);
1085  lpSA->lpSecurityDescriptor = pSD;
1086  lpSA->bInheritHandle = FALSE;
1087
1088  return(lpSA);
1089}
1090
1091// method to create a security attributes structure with a restrictive
1092// access control list that creates a set access rights for the user/owner
1093// of the securable object and a separate set access rights for everyone else.
1094// also provides for full access rights for the administrator group.
1095//
1096// the caller must free the resources associated with the security
1097// attributes structure created by this method by calling the
1098// free_security_attr() method.
1099//
1100
1101static LPSECURITY_ATTRIBUTES make_user_everybody_admin_security_attr(
1102                                DWORD umask, DWORD emask, DWORD amask) {
1103
1104  ace_data_t aces[3];
1105
1106  // initialize the user ace data
1107  aces[0].pSid = get_user_sid(GetCurrentProcess());
1108  aces[0].mask = umask;
1109
1110  if (aces[0].pSid == 0)
1111    return NULL;
1112
1113  // get the well known SID for BUILTIN\Administrators
1114  PSID administratorsSid = NULL;
1115  SID_IDENTIFIER_AUTHORITY SIDAuthAdministrators = SECURITY_NT_AUTHORITY;
1116
1117  if (!AllocateAndInitializeSid( &SIDAuthAdministrators, 2,
1118           SECURITY_BUILTIN_DOMAIN_RID,
1119           DOMAIN_ALIAS_RID_ADMINS,
1120           0, 0, 0, 0, 0, 0, &administratorsSid)) {
1121
1122    if (PrintMiscellaneous && Verbose) {
1123      warning("AllocateAndInitializeSid failure: "
1124              "lasterror = %d \n", GetLastError());
1125    }
1126    return NULL;
1127  }
1128
1129  // initialize the ace data for administrator group
1130  aces[1].pSid = administratorsSid;
1131  aces[1].mask = amask;
1132
1133  // get the well known SID for the universal Everybody
1134  PSID everybodySid = NULL;
1135  SID_IDENTIFIER_AUTHORITY SIDAuthEverybody = SECURITY_WORLD_SID_AUTHORITY;
1136
1137  if (!AllocateAndInitializeSid( &SIDAuthEverybody, 1, SECURITY_WORLD_RID,
1138           0, 0, 0, 0, 0, 0, 0, &everybodySid)) {
1139
1140    if (PrintMiscellaneous && Verbose) {
1141      warning("AllocateAndInitializeSid failure: "
1142              "lasterror = %d \n", GetLastError());
1143    }
1144    return NULL;
1145  }
1146
1147  // initialize the ace data for everybody else.
1148  aces[2].pSid = everybodySid;
1149  aces[2].mask = emask;
1150
1151  // create a security attributes structure with access control
1152  // entries as initialized above.
1153  LPSECURITY_ATTRIBUTES lpSA = make_security_attr(aces, 3);
1154  FREE_C_HEAP_ARRAY(char, aces[0].pSid);
1155  FreeSid(everybodySid);
1156  FreeSid(administratorsSid);
1157  return(lpSA);
1158}
1159
1160
1161// method to create the security attributes structure for restricting
1162// access to the user temporary directory.
1163//
1164// the caller must free the resources associated with the security
1165// attributes structure created by this method by calling the
1166// free_security_attr() method.
1167//
1168static LPSECURITY_ATTRIBUTES make_tmpdir_security_attr() {
1169
1170  // create full access rights for the user/owner of the directory
1171  // and read-only access rights for everybody else. This is
1172  // effectively equivalent to UNIX 755 permissions on a directory.
1173  //
1174  DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_ALL_ACCESS;
1175  DWORD emask = GENERIC_READ | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1176  DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1177
1178  return make_user_everybody_admin_security_attr(umask, emask, amask);
1179}
1180
1181// method to create the security attributes structure for restricting
1182// access to the shared memory backing store file.
1183//
1184// the caller must free the resources associated with the security
1185// attributes structure created by this method by calling the
1186// free_security_attr() method.
1187//
1188static LPSECURITY_ATTRIBUTES make_file_security_attr() {
1189
1190  // create extensive access rights for the user/owner of the file
1191  // and attribute read-only access rights for everybody else. This
1192  // is effectively equivalent to UNIX 600 permissions on a file.
1193  //
1194  DWORD umask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1195  DWORD emask = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES |
1196                 FILE_READ_EA | FILE_LIST_DIRECTORY | FILE_TRAVERSE;
1197  DWORD amask = STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS;
1198
1199  return make_user_everybody_admin_security_attr(umask, emask, amask);
1200}
1201
1202// method to create the security attributes structure for restricting
1203// access to the name shared memory file mapping object.
1204//
1205// the caller must free the resources associated with the security
1206// attributes structure created by this method by calling the
1207// free_security_attr() method.
1208//
1209static LPSECURITY_ATTRIBUTES make_smo_security_attr() {
1210
1211  // create extensive access rights for the user/owner of the shared
1212  // memory object and attribute read-only access rights for everybody
1213  // else. This is effectively equivalent to UNIX 600 permissions on
1214  // on the shared memory object.
1215  //
1216  DWORD umask = STANDARD_RIGHTS_REQUIRED | FILE_MAP_ALL_ACCESS;
1217  DWORD emask = STANDARD_RIGHTS_READ; // attributes only
1218  DWORD amask = STANDARD_RIGHTS_ALL | FILE_MAP_ALL_ACCESS;
1219
1220  return make_user_everybody_admin_security_attr(umask, emask, amask);
1221}
1222
1223// make the user specific temporary directory
1224//
1225static bool make_user_tmp_dir(const char* dirname) {
1226
1227
1228  LPSECURITY_ATTRIBUTES pDirSA = make_tmpdir_security_attr();
1229  if (pDirSA == NULL) {
1230    return false;
1231  }
1232
1233
1234  // create the directory with the given security attributes
1235  if (!CreateDirectory(dirname, pDirSA)) {
1236    DWORD lasterror = GetLastError();
1237    if (lasterror == ERROR_ALREADY_EXISTS) {
1238      // The directory already exists and was probably created by another
1239      // JVM instance. However, this could also be the result of a
1240      // deliberate symlink. Verify that the existing directory is safe.
1241      //
1242      if (!is_directory_secure(dirname)) {
1243        // directory is not secure
1244        if (PrintMiscellaneous && Verbose) {
1245          warning("%s directory is insecure\n", dirname);
1246        }
1247        return false;
1248      }
1249      // The administrator should be able to delete this directory.
1250      // But the directory created by previous version of JVM may not
1251      // have permission for administrators to delete this directory.
1252      // So add full permission to the administrator. Also setting new
1253      // DACLs might fix the corrupted the DACLs.
1254      SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION;
1255      if (!SetFileSecurity(dirname, secInfo, pDirSA->lpSecurityDescriptor)) {
1256        if (PrintMiscellaneous && Verbose) {
1257          lasterror = GetLastError();
1258          warning("SetFileSecurity failed for %s directory.  lasterror %d \n",
1259                                                        dirname, lasterror);
1260        }
1261      }
1262    }
1263    else {
1264      if (PrintMiscellaneous && Verbose) {
1265        warning("CreateDirectory failed: %d\n", GetLastError());
1266      }
1267      return false;
1268    }
1269  }
1270
1271  // free the security attributes structure
1272  free_security_attr(pDirSA);
1273
1274  return true;
1275}
1276
1277// create the shared memory resources
1278//
1279// This function creates the shared memory resources. This includes
1280// the backing store file and the file mapping shared memory object.
1281//
1282static HANDLE create_sharedmem_resources(const char* dirname, const char* filename, const char* objectname, size_t size) {
1283
1284  HANDLE fh = INVALID_HANDLE_VALUE;
1285  HANDLE fmh = NULL;
1286
1287
1288  // create the security attributes for the backing store file
1289  LPSECURITY_ATTRIBUTES lpFileSA = make_file_security_attr();
1290  if (lpFileSA == NULL) {
1291    return NULL;
1292  }
1293
1294  // create the security attributes for the shared memory object
1295  LPSECURITY_ATTRIBUTES lpSmoSA = make_smo_security_attr();
1296  if (lpSmoSA == NULL) {
1297    free_security_attr(lpFileSA);
1298    return NULL;
1299  }
1300
1301  // create the user temporary directory
1302  if (!make_user_tmp_dir(dirname)) {
1303    // could not make/find the directory or the found directory
1304    // was not secure
1305    return NULL;
1306  }
1307
1308  // Create the file - the FILE_FLAG_DELETE_ON_CLOSE flag allows the
1309  // file to be deleted by the last process that closes its handle to
1310  // the file. This is important as the apis do not allow a terminating
1311  // JVM being monitored by another process to remove the file name.
1312  //
1313  fh = CreateFile(
1314             filename,                          /* LPCTSTR file name */
1315
1316             GENERIC_READ|GENERIC_WRITE,        /* DWORD desired access */
1317             FILE_SHARE_DELETE|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 */
1326
1327             NULL);                             /* HANDLE template file access */
1328
1329  free_security_attr(lpFileSA);
1330
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  }
1338
1339  // try to create the file mapping
1340  fmh = create_file_mapping(objectname, fh, lpSmoSA, size);
1341
1342  free_security_attr(lpSmoSA);
1343
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, os::strerror(errno));
1363      }
1364      CloseHandle(fmh);
1365      CloseHandle(fh);
1366      fh = NULL;
1367      fmh = NULL;
1368      return NULL;
1369    }
1370
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  }
1386
1387  // the file has been successfully created and the file mapping
1388  // object has been created.
1389  sharedmem_fileHandle = fh;
1390  sharedmem_fileName = os::strdup(filename);
1391
1392  return fmh;
1393}
1394
1395// open the shared memory object for the given vmid.
1396//
1397static HANDLE open_sharedmem_object(const char* objectname, DWORD ofm_access, TRAPS) {
1398
1399  HANDLE fmh;
1400
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 */
1406
1407  if (fmh == NULL) {
1408    DWORD lasterror = GetLastError();
1409    if (PrintMiscellaneous && Verbose) {
1410      warning("OpenFileMapping failed for shared memory object %s:"
1411              " lasterror = %d\n", objectname, lasterror);
1412    }
1413    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1414               err_msg("Could not open PerfMemory, error %d", lasterror),
1415               INVALID_HANDLE_VALUE);
1416  }
1417
1418  return fmh;;
1419}
1420
1421// create a named shared memory region
1422//
1423// On Win32, a named shared memory object has a name space that
1424// is independent of the file system name space. Shared memory object,
1425// or more precisely, file mapping objects, provide no mechanism to
1426// inquire the size of the memory region. There is also no api to
1427// enumerate the memory regions for various processes.
1428//
1429// This implementation utilizes the shared memory name space in parallel
1430// with the file system name space. This allows us to determine the
1431// size of the shared memory region from the size of the file and it
1432// allows us to provide a common, file system based name space for
1433// shared memory across platforms.
1434//
1435static char* mapping_create_shared(size_t size) {
1436
1437  void *mapAddress;
1438  int vmid = os::current_process_id();
1439
1440  // get the name of the user associated with this process
1441  char* user = get_user_name();
1442
1443  if (user == NULL) {
1444    return NULL;
1445  }
1446
1447  // construct the name of the user specific temporary directory
1448  char* dirname = get_user_tmp_dir(user);
1449
1450  // check that the file system is secure - i.e. it supports ACLs.
1451  if (!is_filesystem_secure(dirname)) {
1452    FREE_C_HEAP_ARRAY(char, dirname);
1453    FREE_C_HEAP_ARRAY(char, user);
1454    return NULL;
1455  }
1456
1457  // create the names of the backing store files and for the
1458  // share memory object.
1459  //
1460  char* filename = get_sharedmem_filename(dirname, vmid);
1461  char* objectname = get_sharedmem_objectname(user, vmid);
1462
1463  // cleanup any stale shared memory resources
1464  cleanup_sharedmem_resources(dirname);
1465
1466  assert(((size != 0) && (size % os::vm_page_size() == 0)),
1467         "unexpected PerfMemry region size");
1468
1469  FREE_C_HEAP_ARRAY(char, user);
1470
1471  // create the shared memory resources
1472  sharedmem_fileMapHandle =
1473               create_sharedmem_resources(dirname, filename, objectname, size);
1474
1475  FREE_C_HEAP_ARRAY(char, filename);
1476  FREE_C_HEAP_ARRAY(char, objectname);
1477  FREE_C_HEAP_ARRAY(char, dirname);
1478
1479  if (sharedmem_fileMapHandle == NULL) {
1480    return NULL;
1481  }
1482
1483  // map the file into the address space
1484  mapAddress = MapViewOfFile(
1485                   sharedmem_fileMapHandle, /* HANDLE = file mapping object */
1486                   FILE_MAP_ALL_ACCESS,     /* DWORD access flags */
1487                   0,                       /* DWORD High word of offset */
1488                   0,                       /* DWORD Low word of offset */
1489                   (DWORD)size);            /* DWORD Number of bytes to map */
1490
1491  if (mapAddress == NULL) {
1492    if (PrintMiscellaneous && Verbose) {
1493      warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1494    }
1495    CloseHandle(sharedmem_fileMapHandle);
1496    sharedmem_fileMapHandle = NULL;
1497    return NULL;
1498  }
1499
1500  // clear the shared memory region
1501  (void)memset(mapAddress, '\0', size);
1502
1503  // it does not go through os api, the operation has to record from here
1504  MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress,
1505    size, CURRENT_PC, mtInternal);
1506
1507  return (char*) mapAddress;
1508}
1509
1510// this method deletes the file mapping object.
1511//
1512static void delete_file_mapping(char* addr, size_t size) {
1513
1514  // cleanup the persistent shared memory resources. since DestroyJavaVM does
1515  // not support unloading of the JVM, unmapping of the memory resource is not
1516  // performed. The memory will be reclaimed by the OS upon termination of all
1517  // processes mapping the resource. The file mapping handle and the file
1518  // handle are closed here to expedite the remove of the file by the OS. The
1519  // file is not removed directly because it was created with
1520  // FILE_FLAG_DELETE_ON_CLOSE semantics and any attempt to remove it would
1521  // be unsuccessful.
1522
1523  // close the fileMapHandle. the file mapping will still be retained
1524  // by the OS as long as any other JVM processes has an open file mapping
1525  // handle or a mapped view of the file.
1526  //
1527  if (sharedmem_fileMapHandle != NULL) {
1528    CloseHandle(sharedmem_fileMapHandle);
1529    sharedmem_fileMapHandle = NULL;
1530  }
1531
1532  // close the file handle. This will decrement the reference count on the
1533  // backing store file. When the reference count decrements to 0, the OS
1534  // will delete the file. These semantics apply because the file was
1535  // created with the FILE_FLAG_DELETE_ON_CLOSE flag.
1536  //
1537  if (sharedmem_fileHandle != INVALID_HANDLE_VALUE) {
1538    CloseHandle(sharedmem_fileHandle);
1539    sharedmem_fileHandle = INVALID_HANDLE_VALUE;
1540  }
1541}
1542
1543// this method determines the size of the shared memory file
1544//
1545static size_t sharedmem_filesize(const char* filename, TRAPS) {
1546
1547  struct stat statbuf;
1548
1549  // get the file size
1550  //
1551  // on win95/98/me, _stat returns a file size of 0 bytes, but on
1552  // winnt/2k the appropriate file size is returned. support for
1553  // the sharable aspects of performance counters was abandonded
1554  // on the non-nt win32 platforms due to this and other api
1555  // inconsistencies
1556  //
1557  if (::stat(filename, &statbuf) == OS_ERR) {
1558    if (PrintMiscellaneous && Verbose) {
1559      warning("stat %s failed: %s\n", filename, os::strerror(errno));
1560    }
1561    THROW_MSG_0(vmSymbols::java_io_IOException(),
1562                "Could not determine PerfMemory size");
1563  }
1564
1565  if ((statbuf.st_size == 0) || (statbuf.st_size % os::vm_page_size() != 0)) {
1566    if (PrintMiscellaneous && Verbose) {
1567      warning("unexpected file size: size = " SIZE_FORMAT "\n",
1568              statbuf.st_size);
1569    }
1570    THROW_MSG_0(vmSymbols::java_lang_Exception(),
1571                "Invalid PerfMemory size");
1572  }
1573
1574  return statbuf.st_size;
1575}
1576
1577// this method opens a file mapping object and maps the object
1578// into the address space of the process
1579//
1580static void open_file_mapping(const char* user, int vmid,
1581                              PerfMemory::PerfMemoryMode mode,
1582                              char** addrp, size_t* sizep, TRAPS) {
1583
1584  ResourceMark rm;
1585
1586  void *mapAddress = 0;
1587  size_t size = 0;
1588  HANDLE fmh;
1589  DWORD ofm_access;
1590  DWORD mv_access;
1591  const char* luser = NULL;
1592
1593  if (mode == PerfMemory::PERF_MODE_RO) {
1594    ofm_access = FILE_MAP_READ;
1595    mv_access = FILE_MAP_READ;
1596  }
1597  else if (mode == PerfMemory::PERF_MODE_RW) {
1598#ifdef LATER
1599    ofm_access = FILE_MAP_READ | FILE_MAP_WRITE;
1600    mv_access = FILE_MAP_READ | FILE_MAP_WRITE;
1601#else
1602    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1603              "Unsupported access mode");
1604#endif
1605  }
1606  else {
1607    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1608              "Illegal access mode");
1609  }
1610
1611  // if a user name wasn't specified, then find the user name for
1612  // the owner of the target vm.
1613  if (user == NULL || strlen(user) == 0) {
1614    luser = get_user_name(vmid);
1615  }
1616  else {
1617    luser = user;
1618  }
1619
1620  if (luser == NULL) {
1621    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1622              "Could not map vmid to user name");
1623  }
1624
1625  // get the names for the resources for the target vm
1626  char* dirname = get_user_tmp_dir(luser);
1627
1628  // since we don't follow symbolic links when creating the backing
1629  // store file, we also don't following them when attaching
1630  //
1631  if (!is_directory_secure(dirname)) {
1632    FREE_C_HEAP_ARRAY(char, dirname);
1633    if (luser != user) FREE_C_HEAP_ARRAY(char, luser);
1634    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1635              "Process not found");
1636  }
1637
1638  char* filename = get_sharedmem_filename(dirname, vmid);
1639  char* objectname = get_sharedmem_objectname(luser, vmid);
1640
1641  // copy heap memory to resource memory. the objectname and
1642  // filename are passed to methods that may throw exceptions.
1643  // using resource arrays for these names prevents the leaks
1644  // that would otherwise occur.
1645  //
1646  char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
1647  char* robjectname = NEW_RESOURCE_ARRAY(char, strlen(objectname) + 1);
1648  strcpy(rfilename, filename);
1649  strcpy(robjectname, objectname);
1650
1651  // free the c heap resources that are no longer needed
1652  if (luser != user) FREE_C_HEAP_ARRAY(char, luser);
1653  FREE_C_HEAP_ARRAY(char, dirname);
1654  FREE_C_HEAP_ARRAY(char, filename);
1655  FREE_C_HEAP_ARRAY(char, objectname);
1656
1657  if (*sizep == 0) {
1658    size = sharedmem_filesize(rfilename, CHECK);
1659  } else {
1660    size = *sizep;
1661  }
1662
1663  assert(size > 0, "unexpected size <= 0");
1664
1665  // Open the file mapping object with the given name
1666  fmh = open_sharedmem_object(robjectname, ofm_access, CHECK);
1667
1668  assert(fmh != INVALID_HANDLE_VALUE, "unexpected handle value");
1669
1670  // map the entire file into the address space
1671  mapAddress = MapViewOfFile(
1672                 fmh,             /* HANDLE Handle of file mapping object */
1673                 mv_access,       /* DWORD access flags */
1674                 0,               /* DWORD High word of offset */
1675                 0,               /* DWORD Low word of offset */
1676                 size);           /* DWORD Number of bytes to map */
1677
1678  if (mapAddress == NULL) {
1679    if (PrintMiscellaneous && Verbose) {
1680      warning("MapViewOfFile failed, lasterror = %d\n", GetLastError());
1681    }
1682    CloseHandle(fmh);
1683    THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
1684              "Could not map PerfMemory");
1685  }
1686
1687  // it does not go through os api, the operation has to record from here
1688  MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size,
1689    CURRENT_PC, mtInternal);
1690
1691
1692  *addrp = (char*)mapAddress;
1693  *sizep = size;
1694
1695  // File mapping object can be closed at this time without
1696  // invalidating the mapped view of the file
1697  CloseHandle(fmh);
1698
1699  log_debug(perf, memops)("mapped " SIZE_FORMAT " bytes for vmid %d at "
1700                          INTPTR_FORMAT "\n", size, vmid, mapAddress);
1701}
1702
1703// this method unmaps the the mapped view of the the
1704// file mapping object.
1705//
1706static void remove_file_mapping(char* addr) {
1707
1708  // the file mapping object was closed in open_file_mapping()
1709  // after the file map view was created. We only need to
1710  // unmap the file view here.
1711  UnmapViewOfFile(addr);
1712}
1713
1714// create the PerfData memory region in shared memory.
1715static char* create_shared_memory(size_t size) {
1716
1717  return mapping_create_shared(size);
1718}
1719
1720// release a named, shared memory region
1721//
1722void delete_shared_memory(char* addr, size_t size) {
1723
1724  delete_file_mapping(addr, size);
1725}
1726
1727
1728
1729
1730// create the PerfData memory region
1731//
1732// This method creates the memory region used to store performance
1733// data for the JVM. The memory may be created in standard or
1734// shared memory.
1735//
1736void PerfMemory::create_memory_region(size_t size) {
1737
1738  if (PerfDisableSharedMem) {
1739    // do not share the memory for the performance data.
1740    PerfDisableSharedMem = true;
1741    _start = create_standard_memory(size);
1742  }
1743  else {
1744    _start = create_shared_memory(size);
1745    if (_start == NULL) {
1746
1747      // creation of the shared memory region failed, attempt
1748      // to create a contiguous, non-shared memory region instead.
1749      //
1750      if (PrintMiscellaneous && Verbose) {
1751        warning("Reverting to non-shared PerfMemory region.\n");
1752      }
1753      PerfDisableSharedMem = true;
1754      _start = create_standard_memory(size);
1755    }
1756  }
1757
1758  if (_start != NULL) _capacity = size;
1759
1760}
1761
1762// delete the PerfData memory region
1763//
1764// This method deletes the memory region used to store performance
1765// data for the JVM. The memory region indicated by the <address, size>
1766// tuple will be inaccessible after a call to this method.
1767//
1768void PerfMemory::delete_memory_region() {
1769
1770  assert((start() != NULL && capacity() > 0), "verify proper state");
1771
1772  // If user specifies PerfDataSaveFile, it will save the performance data
1773  // to the specified file name no matter whether PerfDataSaveToFile is specified
1774  // or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1775  // -XX:+PerfDataSaveToFile.
1776  if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1777    save_memory_to_file(start(), capacity());
1778  }
1779
1780  if (PerfDisableSharedMem) {
1781    delete_standard_memory(start(), capacity());
1782  }
1783  else {
1784    delete_shared_memory(start(), capacity());
1785  }
1786}
1787
1788// attach to the PerfData memory region for another JVM
1789//
1790// This method returns an <address, size> tuple that points to
1791// a memory buffer that is kept reasonably synchronized with
1792// the PerfData memory region for the indicated JVM. This
1793// buffer may be kept in synchronization via shared memory
1794// or some other mechanism that keeps the buffer updated.
1795//
1796// If the JVM chooses not to support the attachability feature,
1797// this method should throw an UnsupportedOperation exception.
1798//
1799// This implementation utilizes named shared memory to map
1800// the indicated process's PerfData memory region into this JVMs
1801// address space.
1802//
1803void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode,
1804                        char** addrp, size_t* sizep, TRAPS) {
1805
1806  if (vmid == 0 || vmid == os::current_process_id()) {
1807     *addrp = start();
1808     *sizep = capacity();
1809     return;
1810  }
1811
1812  open_file_mapping(user, vmid, mode, addrp, sizep, CHECK);
1813}
1814
1815// detach from the PerfData memory region of another JVM
1816//
1817// This method detaches the PerfData memory region of another
1818// JVM, specified as an <address, size> tuple of a buffer
1819// in this process's address space. This method may perform
1820// arbitrary actions to accomplish the detachment. The memory
1821// region specified by <address, size> will be inaccessible after
1822// a call to this method.
1823//
1824// If the JVM chooses not to support the attachability feature,
1825// this method should throw an UnsupportedOperation exception.
1826//
1827// This implementation utilizes named shared memory to detach
1828// the indicated process's PerfData memory region from this
1829// process's address space.
1830//
1831void PerfMemory::detach(char* addr, size_t bytes, TRAPS) {
1832
1833  assert(addr != 0, "address sanity check");
1834  assert(bytes > 0, "capacity sanity check");
1835
1836  if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1837    // prevent accidental detachment of this process's PerfMemory region
1838    return;
1839  }
1840
1841  if (MemTracker::tracking_level() > NMT_minimal) {
1842    // it does not go through os api, the operation has to record from here
1843    Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1844    remove_file_mapping(addr);
1845    tkr.record((address)addr, bytes);
1846  } else {
1847    remove_file_mapping(addr);
1848  }
1849}
1850