Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/os/posix/perfMemory_posix.cpp
40930 views
1
/*
2
* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
3
* Copyright (c) 2012, 2021 SAP SE. All rights reserved.
4
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5
*
6
* This code is free software; you can redistribute it and/or modify it
7
* under the terms of the GNU General Public License version 2 only, as
8
* published by the Free Software Foundation.
9
*
10
* This code is distributed in the hope that it will be useful, but WITHOUT
11
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13
* version 2 for more details (a copy is included in the LICENSE file that
14
* accompanied this code).
15
*
16
* You should have received a copy of the GNU General Public License version
17
* 2 along with this work; if not, write to the Free Software Foundation,
18
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19
*
20
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21
* or visit www.oracle.com if you need additional information or have any
22
* questions.
23
*
24
*/
25
26
#include "precompiled.hpp"
27
#include "jvm_io.h"
28
#include "classfile/vmSymbols.hpp"
29
#include "logging/log.hpp"
30
#include "memory/allocation.inline.hpp"
31
#include "memory/resourceArea.hpp"
32
#include "oops/oop.inline.hpp"
33
#include "os_posix.inline.hpp"
34
#include "runtime/handles.inline.hpp"
35
#include "runtime/os.hpp"
36
#include "runtime/perfMemory.hpp"
37
#include "services/memTracker.hpp"
38
#include "utilities/exceptions.hpp"
39
40
// put OS-includes here
41
# include <sys/types.h>
42
# include <sys/mman.h>
43
# include <errno.h>
44
# include <stdio.h>
45
# include <unistd.h>
46
# include <sys/stat.h>
47
# include <signal.h>
48
# include <pwd.h>
49
50
static char* backing_store_file_name = NULL; // name of the backing store
51
// file, if successfully created.
52
53
// Standard Memory Implementation Details
54
55
// create the PerfData memory region in standard memory.
56
//
57
static char* create_standard_memory(size_t size) {
58
59
// allocate an aligned chuck of memory
60
char* mapAddress = os::reserve_memory(size);
61
62
if (mapAddress == NULL) {
63
return NULL;
64
}
65
66
// commit memory
67
if (!os::commit_memory(mapAddress, size, !ExecMem)) {
68
if (PrintMiscellaneous && Verbose) {
69
warning("Could not commit PerfData memory\n");
70
}
71
os::release_memory(mapAddress, size);
72
return NULL;
73
}
74
75
return mapAddress;
76
}
77
78
// delete the PerfData memory region
79
//
80
static void delete_standard_memory(char* addr, size_t size) {
81
82
// there are no persistent external resources to cleanup for standard
83
// memory. since DestroyJavaVM does not support unloading of the JVM,
84
// cleanup of the memory resource is not performed. The memory will be
85
// reclaimed by the OS upon termination of the process.
86
//
87
return;
88
}
89
90
// save the specified memory region to the given file
91
//
92
// Note: this function might be called from signal handler (by os::abort()),
93
// don't allocate heap memory.
94
//
95
static void save_memory_to_file(char* addr, size_t size) {
96
97
const char* destfile = PerfMemory::get_perfdata_file_path();
98
assert(destfile[0] != '\0', "invalid PerfData file path");
99
100
int result;
101
102
RESTARTABLE(os::open(destfile, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR),
103
result);
104
if (result == OS_ERR) {
105
if (PrintMiscellaneous && Verbose) {
106
warning("Could not create Perfdata save file: %s: %s\n",
107
destfile, os::strerror(errno));
108
}
109
} else {
110
int fd = result;
111
112
for (size_t remaining = size; remaining > 0;) {
113
114
RESTARTABLE(::write(fd, addr, remaining), result);
115
if (result == OS_ERR) {
116
if (PrintMiscellaneous && Verbose) {
117
warning("Could not write Perfdata save file: %s: %s\n",
118
destfile, os::strerror(errno));
119
}
120
break;
121
}
122
123
remaining -= (size_t)result;
124
addr += result;
125
}
126
127
result = ::close(fd);
128
if (PrintMiscellaneous && Verbose) {
129
if (result == OS_ERR) {
130
warning("Could not close %s: %s\n", destfile, os::strerror(errno));
131
}
132
}
133
}
134
FREE_C_HEAP_ARRAY(char, destfile);
135
}
136
137
138
// Shared Memory Implementation Details
139
140
// Note: the Posix shared memory implementation uses the mmap
141
// interface with a backing store file to implement named shared memory.
142
// Using the file system as the name space for shared memory allows a
143
// common name space to be supported across a variety of platforms. It
144
// also provides a name space that Java applications can deal with through
145
// simple file apis.
146
//
147
148
// return the user specific temporary directory name.
149
// the caller is expected to free the allocated memory.
150
//
151
#define TMP_BUFFER_LEN (4+22)
152
static char* get_user_tmp_dir(const char* user, int vmid, int nspid) {
153
char* tmpdir = (char *)os::get_temp_directory();
154
#if defined(LINUX)
155
// On linux, if containerized process, get dirname of
156
// /proc/{vmid}/root/tmp/{PERFDATA_NAME_user}
157
// otherwise /tmp/{PERFDATA_NAME_user}
158
char buffer[TMP_BUFFER_LEN];
159
assert(strlen(tmpdir) == 4, "No longer using /tmp - update buffer size");
160
161
if (nspid != -1) {
162
jio_snprintf(buffer, TMP_BUFFER_LEN, "/proc/%d/root%s", vmid, tmpdir);
163
tmpdir = buffer;
164
}
165
#endif
166
const char* perfdir = PERFDATA_NAME;
167
size_t nbytes = strlen(tmpdir) + strlen(perfdir) + strlen(user) + 3;
168
char* dirname = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
169
170
// construct the path name to user specific tmp directory
171
snprintf(dirname, nbytes, "%s/%s_%s", tmpdir, perfdir, user);
172
173
return dirname;
174
}
175
176
// convert the given file name into a process id. if the file
177
// does not meet the file naming constraints, return 0.
178
//
179
static pid_t filename_to_pid(const char* filename) {
180
181
// a filename that doesn't begin with a digit is not a
182
// candidate for conversion.
183
//
184
if (!isdigit(*filename)) {
185
return 0;
186
}
187
188
// check if file name can be converted to an integer without
189
// any leftover characters.
190
//
191
char* remainder = NULL;
192
errno = 0;
193
pid_t pid = (pid_t)strtol(filename, &remainder, 10);
194
195
if (errno != 0) {
196
return 0;
197
}
198
199
// check for left over characters. If any, then the filename is
200
// not a candidate for conversion.
201
//
202
if (remainder != NULL && *remainder != '\0') {
203
return 0;
204
}
205
206
// successful conversion, return the pid
207
return pid;
208
}
209
210
211
// Check if the given statbuf is considered a secure directory for
212
// the backing store files. Returns true if the directory is considered
213
// a secure location. Returns false if the statbuf is a symbolic link or
214
// if an error occurred.
215
//
216
static bool is_statbuf_secure(struct stat *statp) {
217
if (S_ISLNK(statp->st_mode) || !S_ISDIR(statp->st_mode)) {
218
// The path represents a link or some non-directory file type,
219
// which is not what we expected. Declare it insecure.
220
//
221
return false;
222
}
223
// We have an existing directory, check if the permissions are safe.
224
//
225
if ((statp->st_mode & (S_IWGRP|S_IWOTH)) != 0) {
226
// The directory is open for writing and could be subjected
227
// to a symlink or a hard link attack. Declare it insecure.
228
//
229
return false;
230
}
231
// If user is not root then see if the uid of the directory matches the effective uid of the process.
232
uid_t euid = geteuid();
233
if ((euid != 0) && (statp->st_uid != euid)) {
234
// The directory was not created by this user, declare it insecure.
235
//
236
return false;
237
}
238
return true;
239
}
240
241
242
// Check if the given path is considered a secure directory for
243
// the backing store files. Returns true if the directory exists
244
// and is considered a secure location. Returns false if the path
245
// is a symbolic link or if an error occurred.
246
//
247
static bool is_directory_secure(const char* path) {
248
struct stat statbuf;
249
int result = 0;
250
251
RESTARTABLE(::lstat(path, &statbuf), result);
252
if (result == OS_ERR) {
253
return false;
254
}
255
256
// The path exists, see if it is secure.
257
return is_statbuf_secure(&statbuf);
258
}
259
260
261
// Check if the given directory file descriptor is considered a secure
262
// directory for the backing store files. Returns true if the directory
263
// exists and is considered a secure location. Returns false if the path
264
// is a symbolic link or if an error occurred.
265
//
266
static bool is_dirfd_secure(int dir_fd) {
267
struct stat statbuf;
268
int result = 0;
269
270
RESTARTABLE(::fstat(dir_fd, &statbuf), result);
271
if (result == OS_ERR) {
272
return false;
273
}
274
275
// The path exists, now check its mode.
276
return is_statbuf_secure(&statbuf);
277
}
278
279
280
// Check to make sure fd1 and fd2 are referencing the same file system object.
281
//
282
static bool is_same_fsobject(int fd1, int fd2) {
283
struct stat statbuf1;
284
struct stat statbuf2;
285
int result = 0;
286
287
RESTARTABLE(::fstat(fd1, &statbuf1), result);
288
if (result == OS_ERR) {
289
return false;
290
}
291
RESTARTABLE(::fstat(fd2, &statbuf2), result);
292
if (result == OS_ERR) {
293
return false;
294
}
295
296
if ((statbuf1.st_ino == statbuf2.st_ino) &&
297
(statbuf1.st_dev == statbuf2.st_dev)) {
298
return true;
299
} else {
300
return false;
301
}
302
}
303
304
305
// Open the directory of the given path and validate it.
306
// Return a DIR * of the open directory.
307
//
308
static DIR *open_directory_secure(const char* dirname) {
309
// Open the directory using open() so that it can be verified
310
// to be secure by calling is_dirfd_secure(), opendir() and then check
311
// to see if they are the same file system object. This method does not
312
// introduce a window of opportunity for the directory to be attacked that
313
// calling opendir() and is_directory_secure() does.
314
int result;
315
DIR *dirp = NULL;
316
RESTARTABLE(::open(dirname, O_RDONLY|O_NOFOLLOW), result);
317
if (result == OS_ERR) {
318
// Directory doesn't exist or is a symlink, so there is nothing to cleanup.
319
if (PrintMiscellaneous && Verbose) {
320
if (errno == ELOOP) {
321
warning("directory %s is a symlink and is not secure\n", dirname);
322
} else {
323
warning("could not open directory %s: %s\n", dirname, os::strerror(errno));
324
}
325
}
326
return dirp;
327
}
328
int fd = result;
329
330
// Determine if the open directory is secure.
331
if (!is_dirfd_secure(fd)) {
332
// The directory is not a secure directory.
333
os::close(fd);
334
return dirp;
335
}
336
337
// Open the directory.
338
dirp = ::opendir(dirname);
339
if (dirp == NULL) {
340
// The directory doesn't exist, close fd and return.
341
os::close(fd);
342
return dirp;
343
}
344
345
// Check to make sure fd and dirp are referencing the same file system object.
346
if (!is_same_fsobject(fd, AIX_ONLY(dirp->dd_fd) NOT_AIX(dirfd(dirp)))) {
347
// The directory is not secure.
348
os::close(fd);
349
os::closedir(dirp);
350
dirp = NULL;
351
return dirp;
352
}
353
354
// Close initial open now that we know directory is secure
355
os::close(fd);
356
357
return dirp;
358
}
359
360
// NOTE: The code below uses fchdir(), open() and unlink() because
361
// fdopendir(), openat() and unlinkat() are not supported on all
362
// versions. Once the support for fdopendir(), openat() and unlinkat()
363
// is available on all supported versions the code can be changed
364
// to use these functions.
365
366
// Open the directory of the given path, validate it and set the
367
// current working directory to it.
368
// Return a DIR * of the open directory and the saved cwd fd.
369
//
370
static DIR *open_directory_secure_cwd(const char* dirname, int *saved_cwd_fd) {
371
372
// Open the directory.
373
DIR* dirp = open_directory_secure(dirname);
374
if (dirp == NULL) {
375
// Directory doesn't exist or is insecure, so there is nothing to cleanup.
376
return dirp;
377
}
378
int fd = AIX_ONLY(dirp->dd_fd) NOT_AIX(dirfd(dirp));
379
380
// Open a fd to the cwd and save it off.
381
int result;
382
RESTARTABLE(::open(".", O_RDONLY), result);
383
if (result == OS_ERR) {
384
*saved_cwd_fd = -1;
385
} else {
386
*saved_cwd_fd = result;
387
}
388
389
// Set the current directory to dirname by using the fd of the directory and
390
// handle errors, otherwise shared memory files will be created in cwd.
391
result = fchdir(fd);
392
if (result == OS_ERR) {
393
if (PrintMiscellaneous && Verbose) {
394
warning("could not change to directory %s", dirname);
395
}
396
if (*saved_cwd_fd != -1) {
397
::close(*saved_cwd_fd);
398
*saved_cwd_fd = -1;
399
}
400
// Close the directory.
401
os::closedir(dirp);
402
return NULL;
403
} else {
404
return dirp;
405
}
406
}
407
408
// Close the directory and restore the current working directory.
409
//
410
static void close_directory_secure_cwd(DIR* dirp, int saved_cwd_fd) {
411
412
int result;
413
// If we have a saved cwd change back to it and close the fd.
414
if (saved_cwd_fd != -1) {
415
result = fchdir(saved_cwd_fd);
416
::close(saved_cwd_fd);
417
}
418
419
// Close the directory.
420
os::closedir(dirp);
421
}
422
423
// Check if the given file descriptor is considered a secure.
424
//
425
static bool is_file_secure(int fd, const char *filename) {
426
427
int result;
428
struct stat statbuf;
429
430
// Determine if the file is secure.
431
RESTARTABLE(::fstat(fd, &statbuf), result);
432
if (result == OS_ERR) {
433
if (PrintMiscellaneous && Verbose) {
434
warning("fstat failed on %s: %s\n", filename, os::strerror(errno));
435
}
436
return false;
437
}
438
if (statbuf.st_nlink > 1) {
439
// A file with multiple links is not expected.
440
if (PrintMiscellaneous && Verbose) {
441
warning("file %s has multiple links\n", filename);
442
}
443
return false;
444
}
445
return true;
446
}
447
448
449
// return the user name for the given user id
450
//
451
// the caller is expected to free the allocated memory.
452
//
453
static char* get_user_name(uid_t uid) {
454
455
struct passwd pwent;
456
457
// Determine the max pwbuf size from sysconf, and hardcode
458
// a default if this not available through sysconf.
459
long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
460
if (bufsize == -1)
461
bufsize = 1024;
462
463
char* pwbuf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
464
465
struct passwd* p = NULL;
466
int result = getpwuid_r(uid, &pwent, pwbuf, (size_t)bufsize, &p);
467
468
if (result != 0 || p == NULL || p->pw_name == NULL || *(p->pw_name) == '\0') {
469
if (PrintMiscellaneous && Verbose) {
470
if (result != 0) {
471
warning("Could not retrieve passwd entry: %s\n",
472
os::strerror(result));
473
}
474
else if (p == NULL) {
475
// this check is added to protect against an observed problem
476
// with getpwuid_r() on RedHat 9 where getpwuid_r returns 0,
477
// indicating success, but has p == NULL. This was observed when
478
// inserting a file descriptor exhaustion fault prior to the call
479
// getpwuid_r() call. In this case, error is set to the appropriate
480
// error condition, but this is undocumented behavior. This check
481
// is safe under any condition, but the use of errno in the output
482
// message may result in an erroneous message.
483
// Bug Id 89052 was opened with RedHat.
484
//
485
warning("Could not retrieve passwd entry: %s\n",
486
os::strerror(errno));
487
}
488
else {
489
warning("Could not determine user name: %s\n",
490
p->pw_name == NULL ? "pw_name = NULL" :
491
"pw_name zero length");
492
}
493
}
494
FREE_C_HEAP_ARRAY(char, pwbuf);
495
return NULL;
496
}
497
498
char* user_name = NEW_C_HEAP_ARRAY(char, strlen(p->pw_name) + 1, mtInternal);
499
strcpy(user_name, p->pw_name);
500
501
FREE_C_HEAP_ARRAY(char, pwbuf);
502
return user_name;
503
}
504
505
// return the name of the user that owns the process identified by vmid.
506
//
507
// This method uses a slow directory search algorithm to find the backing
508
// store file for the specified vmid and returns the user name, as determined
509
// by the user name suffix of the hsperfdata_<username> directory name.
510
//
511
// the caller is expected to free the allocated memory.
512
//
513
//
514
static char* get_user_name_slow(int vmid, int nspid, TRAPS) {
515
516
// short circuit the directory search if the process doesn't even exist.
517
if (kill(vmid, 0) == OS_ERR) {
518
if (errno == ESRCH) {
519
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
520
"Process not found");
521
}
522
else /* EPERM */ {
523
THROW_MSG_0(vmSymbols::java_io_IOException(), os::strerror(errno));
524
}
525
}
526
527
// directory search
528
char* oldest_user = NULL;
529
time_t oldest_ctime = 0;
530
int searchpid;
531
char* tmpdirname = (char *)os::get_temp_directory();
532
#if defined(LINUX)
533
char buffer[MAXPATHLEN + 1];
534
assert(strlen(tmpdirname) == 4, "No longer using /tmp - update buffer size");
535
536
// On Linux, if nspid != -1, look in /proc/{vmid}/root/tmp for directories
537
// containing nspid, otherwise just look for vmid in /tmp.
538
if (nspid == -1) {
539
searchpid = vmid;
540
} else {
541
jio_snprintf(buffer, MAXPATHLEN, "/proc/%d/root%s", vmid, tmpdirname);
542
tmpdirname = buffer;
543
searchpid = nspid;
544
}
545
#else
546
searchpid = vmid;
547
#endif
548
549
// open the temp directory
550
DIR* tmpdirp = os::opendir(tmpdirname);
551
552
if (tmpdirp == NULL) {
553
// Cannot open the directory to get the user name, return.
554
return NULL;
555
}
556
557
// for each entry in the directory that matches the pattern hsperfdata_*,
558
// open the directory and check if the file for the given vmid (or nspid) exists.
559
// The file with the expected name and the latest creation date is used
560
// to determine the user name for the process id.
561
//
562
struct dirent* dentry;
563
errno = 0;
564
while ((dentry = os::readdir(tmpdirp)) != NULL) {
565
566
// check if the directory entry is a hsperfdata file
567
if (strncmp(dentry->d_name, PERFDATA_NAME, strlen(PERFDATA_NAME)) != 0) {
568
continue;
569
}
570
571
char* usrdir_name = NEW_C_HEAP_ARRAY(char,
572
strlen(tmpdirname) + strlen(dentry->d_name) + 2,
573
mtInternal);
574
strcpy(usrdir_name, tmpdirname);
575
strcat(usrdir_name, "/");
576
strcat(usrdir_name, dentry->d_name);
577
578
// open the user directory
579
DIR* subdirp = open_directory_secure(usrdir_name);
580
581
if (subdirp == NULL) {
582
FREE_C_HEAP_ARRAY(char, usrdir_name);
583
continue;
584
}
585
586
// Since we don't create the backing store files in directories
587
// pointed to by symbolic links, we also don't follow them when
588
// looking for the files. We check for a symbolic link after the
589
// call to opendir in order to eliminate a small window where the
590
// symlink can be exploited.
591
//
592
if (!is_directory_secure(usrdir_name)) {
593
FREE_C_HEAP_ARRAY(char, usrdir_name);
594
os::closedir(subdirp);
595
continue;
596
}
597
598
struct dirent* udentry;
599
errno = 0;
600
while ((udentry = os::readdir(subdirp)) != NULL) {
601
602
if (filename_to_pid(udentry->d_name) == searchpid) {
603
struct stat statbuf;
604
int result;
605
606
char* filename = NEW_C_HEAP_ARRAY(char,
607
strlen(usrdir_name) + strlen(udentry->d_name) + 2,
608
mtInternal);
609
610
strcpy(filename, usrdir_name);
611
strcat(filename, "/");
612
strcat(filename, udentry->d_name);
613
614
// don't follow symbolic links for the file
615
RESTARTABLE(::lstat(filename, &statbuf), result);
616
if (result == OS_ERR) {
617
FREE_C_HEAP_ARRAY(char, filename);
618
continue;
619
}
620
621
// skip over files that are not regular files.
622
if (!S_ISREG(statbuf.st_mode)) {
623
FREE_C_HEAP_ARRAY(char, filename);
624
continue;
625
}
626
627
// compare and save filename with latest creation time
628
if (statbuf.st_size > 0 && statbuf.st_ctime > oldest_ctime) {
629
630
if (statbuf.st_ctime > oldest_ctime) {
631
char* user = strchr(dentry->d_name, '_') + 1;
632
633
FREE_C_HEAP_ARRAY(char, oldest_user);
634
oldest_user = NEW_C_HEAP_ARRAY(char, strlen(user)+1, mtInternal);
635
636
strcpy(oldest_user, user);
637
oldest_ctime = statbuf.st_ctime;
638
}
639
}
640
641
FREE_C_HEAP_ARRAY(char, filename);
642
}
643
}
644
os::closedir(subdirp);
645
FREE_C_HEAP_ARRAY(char, usrdir_name);
646
}
647
os::closedir(tmpdirp);
648
649
return(oldest_user);
650
}
651
652
// return the name of the user that owns the JVM indicated by the given vmid.
653
//
654
static char* get_user_name(int vmid, int *nspid, TRAPS) {
655
char *result = get_user_name_slow(vmid, *nspid, THREAD);
656
657
#if defined(LINUX)
658
// If we are examining a container process without PID namespaces enabled
659
// we need to use /proc/{pid}/root/tmp to find hsperfdata files.
660
if (result == NULL) {
661
result = get_user_name_slow(vmid, vmid, THREAD);
662
// Enable nspid logic going forward
663
if (result != NULL) *nspid = vmid;
664
}
665
#endif
666
return result;
667
}
668
669
// return the file name of the backing store file for the named
670
// shared memory region for the given user name and vmid.
671
//
672
// the caller is expected to free the allocated memory.
673
//
674
static char* get_sharedmem_filename(const char* dirname, int vmid, int nspid) {
675
676
int pid = LINUX_ONLY((nspid == -1) ? vmid : nspid) NOT_LINUX(vmid);
677
678
// add 2 for the file separator and a null terminator.
679
size_t nbytes = strlen(dirname) + UINT_CHARS + 2;
680
681
char* name = NEW_C_HEAP_ARRAY(char, nbytes, mtInternal);
682
snprintf(name, nbytes, "%s/%d", dirname, pid);
683
684
return name;
685
}
686
687
688
// remove file
689
//
690
// this method removes the file specified by the given path
691
//
692
static void remove_file(const char* path) {
693
694
int result;
695
696
// if the file is a directory, the following unlink will fail. since
697
// we don't expect to find directories in the user temp directory, we
698
// won't try to handle this situation. even if accidentially or
699
// maliciously planted, the directory's presence won't hurt anything.
700
//
701
RESTARTABLE(::unlink(path), result);
702
if (PrintMiscellaneous && Verbose && result == OS_ERR) {
703
if (errno != ENOENT) {
704
warning("Could not unlink shared memory backing"
705
" store file %s : %s\n", path, os::strerror(errno));
706
}
707
}
708
}
709
710
711
// cleanup stale shared memory resources
712
//
713
// This method attempts to remove all stale shared memory files in
714
// the named user temporary directory. It scans the named directory
715
// for files matching the pattern ^$[0-9]*$. For each file found, the
716
// process id is extracted from the file name and a test is run to
717
// determine if the process is alive. If the process is not alive,
718
// any stale file resources are removed.
719
//
720
static void cleanup_sharedmem_resources(const char* dirname) {
721
722
int saved_cwd_fd;
723
// open the directory and set the current working directory to it
724
DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
725
if (dirp == NULL) {
726
// directory doesn't exist or is insecure, so there is nothing to cleanup
727
return;
728
}
729
730
// for each entry in the directory that matches the expected file
731
// name pattern, determine if the file resources are stale and if
732
// so, remove the file resources. Note, instrumented HotSpot processes
733
// for this user may start and/or terminate during this search and
734
// remove or create new files in this directory. The behavior of this
735
// loop under these conditions is dependent upon the implementation of
736
// opendir/readdir.
737
//
738
struct dirent* entry;
739
errno = 0;
740
while ((entry = os::readdir(dirp)) != NULL) {
741
742
pid_t pid = filename_to_pid(entry->d_name);
743
744
if (pid == 0) {
745
746
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
747
// attempt to remove all unexpected files, except "." and ".."
748
unlink(entry->d_name);
749
}
750
751
errno = 0;
752
continue;
753
}
754
755
// we now have a file name that converts to a valid integer
756
// that could represent a process id . if this process id
757
// matches the current process id or the process is not running,
758
// then remove the stale file resources.
759
//
760
// process liveness is detected by sending signal number 0 to
761
// the process id (see kill(2)). if kill determines that the
762
// process does not exist, then the file resources are removed.
763
// if kill determines that that we don't have permission to
764
// signal the process, then the file resources are assumed to
765
// be stale and are removed because the resources for such a
766
// process should be in a different user specific directory.
767
//
768
if ((pid == os::current_process_id()) ||
769
(kill(pid, 0) == OS_ERR && (errno == ESRCH || errno == EPERM))) {
770
unlink(entry->d_name);
771
}
772
errno = 0;
773
}
774
775
// close the directory and reset the current working directory
776
close_directory_secure_cwd(dirp, saved_cwd_fd);
777
}
778
779
// make the user specific temporary directory. Returns true if
780
// the directory exists and is secure upon return. Returns false
781
// if the directory exists but is either a symlink, is otherwise
782
// insecure, or if an error occurred.
783
//
784
static bool make_user_tmp_dir(const char* dirname) {
785
786
// create the directory with 0755 permissions. note that the directory
787
// will be owned by euid::egid, which may not be the same as uid::gid.
788
//
789
if (mkdir(dirname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) == OS_ERR) {
790
if (errno == EEXIST) {
791
// The directory already exists and was probably created by another
792
// JVM instance. However, this could also be the result of a
793
// deliberate symlink. Verify that the existing directory is safe.
794
//
795
if (!is_directory_secure(dirname)) {
796
// directory is not secure
797
if (PrintMiscellaneous && Verbose) {
798
warning("%s directory is insecure\n", dirname);
799
}
800
return false;
801
}
802
}
803
else {
804
// we encountered some other failure while attempting
805
// to create the directory
806
//
807
if (PrintMiscellaneous && Verbose) {
808
warning("could not create directory %s: %s\n",
809
dirname, os::strerror(errno));
810
}
811
return false;
812
}
813
}
814
return true;
815
}
816
817
// create the shared memory file resources
818
//
819
// This method creates the shared memory file with the given size
820
// This method also creates the user specific temporary directory, if
821
// it does not yet exist.
822
//
823
static int create_sharedmem_resources(const char* dirname, const char* filename, size_t size) {
824
825
// make the user temporary directory
826
if (!make_user_tmp_dir(dirname)) {
827
// could not make/find the directory or the found directory
828
// was not secure
829
return -1;
830
}
831
832
int saved_cwd_fd;
833
// open the directory and set the current working directory to it
834
DIR* dirp = open_directory_secure_cwd(dirname, &saved_cwd_fd);
835
if (dirp == NULL) {
836
// Directory doesn't exist or is insecure, so cannot create shared
837
// memory file.
838
return -1;
839
}
840
841
// Open the filename in the current directory.
842
// Cannot use O_TRUNC here; truncation of an existing file has to happen
843
// after the is_file_secure() check below.
844
int result;
845
RESTARTABLE(os::open(filename, O_RDWR|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR), result);
846
if (result == OS_ERR) {
847
if (PrintMiscellaneous && Verbose) {
848
if (errno == ELOOP) {
849
warning("file %s is a symlink and is not secure\n", filename);
850
} else {
851
warning("could not create file %s: %s\n", filename, os::strerror(errno));
852
}
853
}
854
// close the directory and reset the current working directory
855
close_directory_secure_cwd(dirp, saved_cwd_fd);
856
857
return -1;
858
}
859
// close the directory and reset the current working directory
860
close_directory_secure_cwd(dirp, saved_cwd_fd);
861
862
// save the file descriptor
863
int fd = result;
864
865
// check to see if the file is secure
866
if (!is_file_secure(fd, filename)) {
867
::close(fd);
868
return -1;
869
}
870
871
// truncate the file to get rid of any existing data
872
RESTARTABLE(::ftruncate(fd, (off_t)0), result);
873
if (result == OS_ERR) {
874
if (PrintMiscellaneous && Verbose) {
875
warning("could not truncate shared memory file: %s\n", os::strerror(errno));
876
}
877
::close(fd);
878
return -1;
879
}
880
// set the file size
881
RESTARTABLE(::ftruncate(fd, (off_t)size), result);
882
if (result == OS_ERR) {
883
if (PrintMiscellaneous && Verbose) {
884
warning("could not set shared memory file size: %s\n", os::strerror(errno));
885
}
886
::close(fd);
887
return -1;
888
}
889
890
// Verify that we have enough disk space for this file.
891
// We'll get random SIGBUS crashes on memory accesses if
892
// we don't.
893
for (size_t seekpos = 0; seekpos < size; seekpos += os::vm_page_size()) {
894
int zero_int = 0;
895
result = (int)os::seek_to_file_offset(fd, (jlong)(seekpos));
896
if (result == -1 ) break;
897
RESTARTABLE(::write(fd, &zero_int, 1), result);
898
if (result != 1) {
899
if (errno == ENOSPC) {
900
warning("Insufficient space for shared memory file:\n %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename);
901
}
902
break;
903
}
904
}
905
906
if (result != -1) {
907
return fd;
908
} else {
909
::close(fd);
910
return -1;
911
}
912
}
913
914
// open the shared memory file for the given user and vmid. returns
915
// the file descriptor for the open file or -1 if the file could not
916
// be opened.
917
//
918
static int open_sharedmem_file(const char* filename, int oflags, TRAPS) {
919
920
// open the file
921
int result;
922
RESTARTABLE(os::open(filename, oflags, 0), result);
923
if (result == OS_ERR) {
924
if (errno == ENOENT) {
925
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
926
"Process not found", OS_ERR);
927
}
928
else if (errno == EACCES) {
929
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
930
"Permission denied", OS_ERR);
931
}
932
else {
933
THROW_MSG_(vmSymbols::java_io_IOException(),
934
os::strerror(errno), OS_ERR);
935
}
936
}
937
int fd = result;
938
939
// check to see if the file is secure
940
if (!is_file_secure(fd, filename)) {
941
::close(fd);
942
return -1;
943
}
944
945
return fd;
946
}
947
948
// create a named shared memory region. returns the address of the
949
// memory region on success or NULL on failure. A return value of
950
// NULL will ultimately disable the shared memory feature.
951
//
952
// The name space for shared memory objects is the file system name space.
953
//
954
// A monitoring application attaching to a JVM does not need to know
955
// the file system name of the shared memory object. However, it may
956
// be convenient for applications to discover the existence of newly
957
// created and terminating JVMs by watching the file system name space
958
// for files being created or removed.
959
//
960
static char* mmap_create_shared(size_t size) {
961
962
int result;
963
int fd;
964
char* mapAddress;
965
966
int vmid = os::current_process_id();
967
968
char* user_name = get_user_name(geteuid());
969
970
if (user_name == NULL)
971
return NULL;
972
973
char* dirname = get_user_tmp_dir(user_name, vmid, -1);
974
char* filename = get_sharedmem_filename(dirname, vmid, -1);
975
976
// get the short filename
977
char* short_filename = strrchr(filename, '/');
978
if (short_filename == NULL) {
979
short_filename = filename;
980
} else {
981
short_filename++;
982
}
983
984
// cleanup any stale shared memory files
985
cleanup_sharedmem_resources(dirname);
986
987
assert(((size > 0) && (size % os::vm_page_size() == 0)),
988
"unexpected PerfMemory region size");
989
990
fd = create_sharedmem_resources(dirname, short_filename, size);
991
992
FREE_C_HEAP_ARRAY(char, user_name);
993
FREE_C_HEAP_ARRAY(char, dirname);
994
995
if (fd == -1) {
996
FREE_C_HEAP_ARRAY(char, filename);
997
return NULL;
998
}
999
1000
mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
1001
1002
result = ::close(fd);
1003
assert(result != OS_ERR, "could not close file");
1004
1005
if (mapAddress == MAP_FAILED) {
1006
if (PrintMiscellaneous && Verbose) {
1007
warning("mmap failed - %s\n", os::strerror(errno));
1008
}
1009
remove_file(filename);
1010
FREE_C_HEAP_ARRAY(char, filename);
1011
return NULL;
1012
}
1013
1014
// save the file name for use in delete_shared_memory()
1015
backing_store_file_name = filename;
1016
1017
// clear the shared memory region
1018
(void)::memset((void*) mapAddress, 0, size);
1019
1020
// it does not go through os api, the operation has to record from here
1021
MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);
1022
1023
return mapAddress;
1024
}
1025
1026
// release a named shared memory region
1027
//
1028
static void unmap_shared(char* addr, size_t bytes) {
1029
#if defined(_AIX)
1030
// Do not rely on os::reserve_memory/os::release_memory to use mmap.
1031
// Use os::reserve_memory/os::release_memory for PerfDisableSharedMem=1, mmap/munmap for PerfDisableSharedMem=0
1032
if (::munmap(addr, bytes) == -1) {
1033
warning("perfmemory: munmap failed (%d)\n", errno);
1034
}
1035
#else
1036
os::release_memory(addr, bytes);
1037
#endif
1038
}
1039
1040
// create the PerfData memory region in shared memory.
1041
//
1042
static char* create_shared_memory(size_t size) {
1043
1044
// create the shared memory region.
1045
return mmap_create_shared(size);
1046
}
1047
1048
// delete the shared PerfData memory region
1049
//
1050
static void delete_shared_memory(char* addr, size_t size) {
1051
1052
// cleanup the persistent shared memory resources. since DestroyJavaVM does
1053
// not support unloading of the JVM, unmapping of the memory resource is
1054
// not performed. The memory will be reclaimed by the OS upon termination of
1055
// the process. The backing store file is deleted from the file system.
1056
1057
assert(!PerfDisableSharedMem, "shouldn't be here");
1058
1059
if (backing_store_file_name != NULL) {
1060
remove_file(backing_store_file_name);
1061
// Don't.. Free heap memory could deadlock os::abort() if it is called
1062
// from signal handler. OS will reclaim the heap memory.
1063
// FREE_C_HEAP_ARRAY(char, backing_store_file_name);
1064
backing_store_file_name = NULL;
1065
}
1066
}
1067
1068
// return the size of the file for the given file descriptor
1069
// or 0 if it is not a valid size for a shared memory file
1070
//
1071
static size_t sharedmem_filesize(int fd, TRAPS) {
1072
1073
struct stat statbuf;
1074
int result;
1075
1076
RESTARTABLE(::fstat(fd, &statbuf), result);
1077
if (result == OS_ERR) {
1078
if (PrintMiscellaneous && Verbose) {
1079
warning("fstat failed: %s\n", os::strerror(errno));
1080
}
1081
THROW_MSG_0(vmSymbols::java_io_IOException(),
1082
"Could not determine PerfMemory size");
1083
}
1084
1085
if ((statbuf.st_size == 0) ||
1086
((size_t)statbuf.st_size % os::vm_page_size() != 0)) {
1087
THROW_MSG_0(vmSymbols::java_io_IOException(),
1088
"Invalid PerfMemory size");
1089
}
1090
1091
return (size_t)statbuf.st_size;
1092
}
1093
1094
// attach to a named shared memory region.
1095
//
1096
static void mmap_attach_shared(const char* user, int vmid, PerfMemory::PerfMemoryMode mode, char** addr, size_t* sizep, TRAPS) {
1097
1098
char* mapAddress;
1099
int result;
1100
int fd;
1101
size_t size = 0;
1102
const char* luser = NULL;
1103
1104
int mmap_prot;
1105
int file_flags;
1106
1107
ResourceMark rm;
1108
1109
// map the high level access mode to the appropriate permission
1110
// constructs for the file and the shared memory mapping.
1111
if (mode == PerfMemory::PERF_MODE_RO) {
1112
mmap_prot = PROT_READ;
1113
file_flags = O_RDONLY | O_NOFOLLOW;
1114
}
1115
else if (mode == PerfMemory::PERF_MODE_RW) {
1116
#ifdef LATER
1117
mmap_prot = PROT_READ | PROT_WRITE;
1118
file_flags = O_RDWR | O_NOFOLLOW;
1119
#else
1120
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1121
"Unsupported access mode");
1122
#endif
1123
}
1124
else {
1125
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1126
"Illegal access mode");
1127
}
1128
1129
// for linux, determine if vmid is for a containerized process
1130
int nspid = LINUX_ONLY(os::Linux::get_namespace_pid(vmid)) NOT_LINUX(-1);
1131
1132
if (user == NULL || strlen(user) == 0) {
1133
luser = get_user_name(vmid, &nspid, CHECK);
1134
}
1135
else {
1136
luser = user;
1137
}
1138
1139
if (luser == NULL) {
1140
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1141
"Could not map vmid to user Name");
1142
}
1143
1144
char* dirname = get_user_tmp_dir(luser, vmid, nspid);
1145
1146
// since we don't follow symbolic links when creating the backing
1147
// store file, we don't follow them when attaching either.
1148
//
1149
if (!is_directory_secure(dirname)) {
1150
FREE_C_HEAP_ARRAY(char, dirname);
1151
if (luser != user) {
1152
FREE_C_HEAP_ARRAY(char, luser);
1153
}
1154
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1155
"Process not found");
1156
}
1157
1158
char* filename = get_sharedmem_filename(dirname, vmid, nspid);
1159
1160
// copy heap memory to resource memory. the open_sharedmem_file
1161
// method below need to use the filename, but could throw an
1162
// exception. using a resource array prevents the leak that
1163
// would otherwise occur.
1164
char* rfilename = NEW_RESOURCE_ARRAY(char, strlen(filename) + 1);
1165
strcpy(rfilename, filename);
1166
1167
// free the c heap resources that are no longer needed
1168
if (luser != user) FREE_C_HEAP_ARRAY(char, luser);
1169
FREE_C_HEAP_ARRAY(char, dirname);
1170
FREE_C_HEAP_ARRAY(char, filename);
1171
1172
// open the shared memory file for the give vmid
1173
fd = open_sharedmem_file(rfilename, file_flags, THREAD);
1174
1175
if (fd == OS_ERR) {
1176
return;
1177
}
1178
1179
if (HAS_PENDING_EXCEPTION) {
1180
::close(fd);
1181
return;
1182
}
1183
1184
if (*sizep == 0) {
1185
size = sharedmem_filesize(fd, CHECK);
1186
} else {
1187
size = *sizep;
1188
}
1189
1190
assert(size > 0, "unexpected size <= 0");
1191
1192
mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
1193
1194
result = ::close(fd);
1195
assert(result != OS_ERR, "could not close file");
1196
1197
if (mapAddress == MAP_FAILED) {
1198
if (PrintMiscellaneous && Verbose) {
1199
warning("mmap failed: %s\n", os::strerror(errno));
1200
}
1201
THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
1202
"Could not map PerfMemory");
1203
}
1204
1205
// it does not go through os api, the operation has to record from here
1206
MemTracker::record_virtual_memory_reserve_and_commit((address)mapAddress, size, CURRENT_PC, mtInternal);
1207
1208
*addr = mapAddress;
1209
*sizep = size;
1210
1211
log_debug(perf, memops)("mapped " SIZE_FORMAT " bytes for vmid %d at "
1212
INTPTR_FORMAT, size, vmid, p2i((void*)mapAddress));
1213
}
1214
1215
// create the PerfData memory region
1216
//
1217
// This method creates the memory region used to store performance
1218
// data for the JVM. The memory may be created in standard or
1219
// shared memory.
1220
//
1221
void PerfMemory::create_memory_region(size_t size) {
1222
1223
if (PerfDisableSharedMem) {
1224
// do not share the memory for the performance data.
1225
_start = create_standard_memory(size);
1226
}
1227
else {
1228
_start = create_shared_memory(size);
1229
if (_start == NULL) {
1230
1231
// creation of the shared memory region failed, attempt
1232
// to create a contiguous, non-shared memory region instead.
1233
//
1234
if (PrintMiscellaneous && Verbose) {
1235
warning("Reverting to non-shared PerfMemory region.\n");
1236
}
1237
PerfDisableSharedMem = true;
1238
_start = create_standard_memory(size);
1239
}
1240
}
1241
1242
if (_start != NULL) _capacity = size;
1243
1244
}
1245
1246
// delete the PerfData memory region
1247
//
1248
// This method deletes the memory region used to store performance
1249
// data for the JVM. The memory region indicated by the <address, size>
1250
// tuple will be inaccessible after a call to this method.
1251
//
1252
void PerfMemory::delete_memory_region() {
1253
1254
assert((start() != NULL && capacity() > 0), "verify proper state");
1255
1256
// If user specifies PerfDataSaveFile, it will save the performance data
1257
// to the specified file name no matter whether PerfDataSaveToFile is specified
1258
// or not. In other word, -XX:PerfDataSaveFile=.. overrides flag
1259
// -XX:+PerfDataSaveToFile.
1260
if (PerfDataSaveToFile || PerfDataSaveFile != NULL) {
1261
save_memory_to_file(start(), capacity());
1262
}
1263
1264
if (PerfDisableSharedMem) {
1265
delete_standard_memory(start(), capacity());
1266
}
1267
else {
1268
delete_shared_memory(start(), capacity());
1269
}
1270
}
1271
1272
// attach to the PerfData memory region for another JVM
1273
//
1274
// This method returns an <address, size> tuple that points to
1275
// a memory buffer that is kept reasonably synchronized with
1276
// the PerfData memory region for the indicated JVM. This
1277
// buffer may be kept in synchronization via shared memory
1278
// or some other mechanism that keeps the buffer updated.
1279
//
1280
// If the JVM chooses not to support the attachability feature,
1281
// this method should throw an UnsupportedOperation exception.
1282
//
1283
// This implementation utilizes named shared memory to map
1284
// the indicated process's PerfData memory region into this JVMs
1285
// address space.
1286
//
1287
void PerfMemory::attach(const char* user, int vmid, PerfMemoryMode mode, char** addrp, size_t* sizep, TRAPS) {
1288
1289
if (vmid == 0 || vmid == os::current_process_id()) {
1290
*addrp = start();
1291
*sizep = capacity();
1292
return;
1293
}
1294
1295
mmap_attach_shared(user, vmid, mode, addrp, sizep, CHECK);
1296
}
1297
1298
// detach from the PerfData memory region of another JVM
1299
//
1300
// This method detaches the PerfData memory region of another
1301
// JVM, specified as an <address, size> tuple of a buffer
1302
// in this process's address space. This method may perform
1303
// arbitrary actions to accomplish the detachment. The memory
1304
// region specified by <address, size> will be inaccessible after
1305
// a call to this method.
1306
//
1307
// If the JVM chooses not to support the attachability feature,
1308
// this method should throw an UnsupportedOperation exception.
1309
//
1310
// This implementation utilizes named shared memory to detach
1311
// the indicated process's PerfData memory region from this
1312
// process's address space.
1313
//
1314
void PerfMemory::detach(char* addr, size_t bytes) {
1315
1316
assert(addr != 0, "address sanity check");
1317
assert(bytes > 0, "capacity sanity check");
1318
1319
if (PerfMemory::contains(addr) || PerfMemory::contains(addr + bytes - 1)) {
1320
// prevent accidental detachment of this process's PerfMemory region
1321
return;
1322
}
1323
1324
unmap_shared(addr, bytes);
1325
}
1326
1327