[PATCH] D36529: Fixed a race condition in PrecompiledPreamble.

Ilya Biryukov via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 9 09:41:11 PDT 2017


ilya-biryukov created this revision.

Two PrecompiledPreambles, used in parallel on separate threads,
could be writing preamble to the same temporary file.


https://reviews.llvm.org/D36529

Files:
  lib/Frontend/PrecompiledPreamble.cpp


Index: lib/Frontend/PrecompiledPreamble.cpp
===================================================================
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -28,6 +28,7 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Mutex.h"
 #include "llvm/Support/MutexGuard.h"
+#include "llvm/Support/Process.h"
 
 using namespace clang;
 
@@ -462,9 +463,16 @@
 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
                                                         StringRef Suffix) {
   llvm::SmallString<64> File;
-  auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, /*ref*/ File);
+  // Using a version of createTemporaryFile with a file descriptor guarantees
+  // that we would never get a race condition in a multi-threaded setting (i.e.,
+  // multiple threads getting the same temporary path).
+  int FD;
+  auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, /*ref*/ FD,
+                                               /*ref*/ File);
   if (EC)
     return EC;
+  // We only needed to make sure the file exists, close the file right away.
+  llvm::sys::Process::SafelyCloseFileDescriptor(FD);
   return TempPCHFile(std::move(File).str());
 }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D36529.110418.patch
Type: text/x-patch
Size: 1248 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20170809/00d6294f/attachment-0001.bin>


More information about the cfe-commits mailing list