Support: Don't call close again if we get EINTR

Most Unix-like operating systems guarantee that the file descriptor is
closed after a call to close(2), even if close comes back with EINTR.
For these systems, calling close _again_ will either do nothing or close
some other file descriptor open(2)'d by another thread. (Linux)

However, some operating systems do not have this behavior.  They require
at least another call to close(2) before guaranteeing that the
descriptor is closed. (HP-UX)

And some operating systems have an unpredictable blend of the two
behaviors! (xnu)

Avoid this disaster by blocking all signals before we call close(2).
This ensures that a signal will not be delivered to the thread and
close(2) will not give us back EINTR.  We restore the signal mask once
the operation is done.

N.B. This isn't a problem on Windows, it doesn't have a notion of EINTR
because signals always get delivered to dedicated signal handling
threads.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@219189 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
David Majnemer
2014-10-07 05:48:40 +00:00
parent 61c4e41480
commit 220c5ca8f4
4 changed files with 43 additions and 11 deletions
+24
View File
@@ -258,6 +258,30 @@ std::error_code Process::FixupStandardFileDescriptors() {
return std::error_code();
}
std::error_code Process::SafelyCloseFileDescriptor(int FD) {
// Create a signal set filled with *all* signals.
sigset_t FullSet;
if (sigfillset(&FullSet) < 0)
return std::error_code(errno, std::generic_category());
// Atomically swap our current signal mask with a full mask.
sigset_t SavedSet;
if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
return std::error_code(EC, std::generic_category());
// Attempt to close the file descriptor.
// We need to save the error, if one occurs, because our subsequent call to
// pthread_sigmask might tamper with errno.
int ErrnoFromClose = 0;
if (::close(FD) < 0)
ErrnoFromClose = errno;
// Restore the signal mask back to what we saved earlier.
int EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
// The error code from close takes precedence over the one from
// pthread_sigmask.
if (ErrnoFromClose)
return std::error_code(ErrnoFromClose, std::generic_category());
return std::error_code(EC, std::generic_category());
}
bool Process::StandardInIsUserInput() {
return FileDescriptorIsDisplayed(STDIN_FILENO);
}