8291067: macOS should use O_CLOEXEC instead of FD_CLOEXEC

Reviewed-by: dcubed, dholmes, stuefe
This commit is contained in:
Gerard Ziemski 2022-11-22 16:30:24 +00:00
parent 0ac5b55311
commit ccc6e16918
2 changed files with 28 additions and 27 deletions

View File

@ -2168,28 +2168,6 @@ int os::open(const char *path, int oflag, int mode) {
errno = ENAMETOOLONG;
return -1;
}
int fd;
fd = ::open(path, oflag, mode);
if (fd == -1) return -1;
// If the open succeeded, the file might still be a directory
{
struct stat buf;
int ret = ::fstat(fd, &buf);
int st_mode = buf.st_mode;
if (ret != -1) {
if ((st_mode & S_IFMT) == S_IFDIR) {
errno = EISDIR;
::close(fd);
return -1;
}
} else {
::close(fd);
return -1;
}
}
// All file descriptors that are opened in the JVM and not
// specifically destined for a subprocess should have the
@ -2212,14 +2190,27 @@ int os::open(const char *path, int oflag, int mode) {
// 4843136: (process) pipe file descriptor from Runtime.exec not being closed
// 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
//
#ifdef FD_CLOEXEC
int fd = ::open(path, oflag | O_CLOEXEC, mode);
if (fd == -1) return -1;
// If the open succeeded, the file might still be a directory
{
int flags = ::fcntl(fd, F_GETFD);
if (flags != -1) {
::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
struct stat buf;
int ret = ::fstat(fd, &buf);
int st_mode = buf.st_mode;
if (ret != -1) {
if ((st_mode & S_IFMT) == S_IFDIR) {
errno = EISDIR;
::close(fd);
return -1;
}
} else {
::close(fd);
return -1;
}
}
#endif
return fd;
}

View File

@ -914,3 +914,13 @@ TEST_VM(os, trim_native_heap) {
EXPECT_FALSE(os::can_trim_native_heap());
}
#endif // __GLIBC__
TEST_VM(os, open_O_CLOEXEC) {
#if !defined(_WIN32)
int fd = os::open("test_file.txt", O_RDWR | O_CREAT | O_TRUNC, 0666); // open will use O_CLOEXEC
EXPECT_TRUE(fd > 0);
int flags = ::fcntl(fd, F_GETFD);
EXPECT_TRUE((flags & FD_CLOEXEC) != 0); // if O_CLOEXEC worked, then FD_CLOEXEC should be ON
::close(fd);
#endif
}