[Support] Use O_CLOEXEC only when declared

Summary:
Use the O_CLOEXEC flag only when it is available. Some old systems (e.g.
SLES10) do not support this flag. POSIX explicitly guarantees that this
flag can be checked for using #if, so there is no need for a CMake
check.

In case O_CLOEXEC is not supported, fall back to fcntl(FD_CLOEXEC)
instead.

Reviewers: rnk, rafael, mgorny

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D28894

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@292912 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Pavel Labath 2017-01-24 10:57:01 +00:00
parent e414b99879
commit c5e1c4de45

View File

@ -587,10 +587,19 @@ std::error_code openFileForRead(const Twine &Name, int &ResultFD,
SmallVectorImpl<char> *RealPath) {
SmallString<128> Storage;
StringRef P = Name.toNullTerminatedStringRef(Storage);
while ((ResultFD = open(P.begin(), O_RDONLY | O_CLOEXEC)) < 0) {
int OpenFlags = O_RDONLY;
#ifdef O_CLOEXEC
OpenFlags |= O_CLOEXEC;
#endif
while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
if (errno != EINTR)
return std::error_code(errno, std::generic_category());
}
#ifndef O_CLOEXEC
int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
(void)r;
assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
#endif
// Attempt to get the real name of the file, if the user asked
if(!RealPath)
return std::error_code();
@ -624,7 +633,11 @@ std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
"Cannot specify both 'excl' and 'append' file creation flags!");
int OpenFlags = O_CREAT | O_CLOEXEC;
int OpenFlags = O_CREAT;
#ifdef O_CLOEXEC
OpenFlags |= O_CLOEXEC;
#endif
if (Flags & F_RW)
OpenFlags |= O_RDWR;
@ -645,6 +658,11 @@ std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
if (errno != EINTR)
return std::error_code(errno, std::generic_category());
}
#ifndef O_CLOEXEC
int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
(void)r;
assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
#endif
return std::error_code();
}