]> granicus.if.org Git - llvm/commitdiff
[Support] Use O_CLOEXEC only when declared
authorPavel Labath <labath@google.com>
Tue, 24 Jan 2017 10:57:01 +0000 (10:57 +0000)
committerPavel Labath <labath@google.com>
Tue, 24 Jan 2017 10:57:01 +0000 (10:57 +0000)
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

lib/Support/Unix/Path.inc

index f7334245a002684b5eae9e6060ac2878260e6525..ecc9a2ea8e2156f38f87d55e05e610417520cc04 100644 (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();
 }