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