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