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