[LinkerWrapper] Fix memory issues due to unguarded accesses to global state
authorJoseph Huber <jhuber6@vols.utk.edu>
Tue, 31 Jan 2023 15:50:40 +0000 (09:50 -0600)
committerJoseph Huber <jhuber6@vols.utk.edu>
Wed, 1 Feb 2023 14:12:10 +0000 (08:12 -0600)
There were intemittent errors in the linker wrapper when using the
sanitizers in parallel. First, this is because the `TempFiles` global
was not guarded when creating a new file. Second, even though the `Args`
list is passed as const, the internal state is mutable when adding a
string. So that needs to be guarded too.

Fixes https://github.com/llvm/llvm-project/issues/60437

Reviewed By: tianshilei1992

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

clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

index 3c92d34..6981e12 100644 (file)
@@ -77,6 +77,9 @@ static StringRef ExecutableName;
 /// Binary path for the CUDA installation.
 static std::string CudaBinaryPath;
 
+/// Mutex lock to protect writes to shared TempFiles in parallel.
+static std::mutex TempFilesMutex;
+
 /// Temporary files created by the linker wrapper.
 static std::list<SmallString<128>> TempFiles;
 
@@ -200,6 +203,7 @@ std::string getMainExecutable(const char *Name) {
 
 /// Get a temporary filename suitable for output.
 Expected<StringRef> createOutputFile(const Twine &Prefix, StringRef Extension) {
+  std::scoped_lock<decltype(TempFilesMutex)> Lock(TempFilesMutex);
   SmallString<128> OutputFile;
   if (SaveTemps) {
     (Prefix + "." + Extension).toNullTerminatedStringRef(OutputFile);
@@ -1047,6 +1051,7 @@ linkAndWrapDeviceFiles(SmallVectorImpl<OffloadFile> &LinkerInputFiles,
           return createFileError(*OutputOrErr, EC);
       }
 
+      std::scoped_lock<decltype(ImageMtx)> Guard(ImageMtx);
       OffloadingImage TheImage{};
       TheImage.TheImageKind =
           Args.hasArg(OPT_embed_bitcode) ? IMG_Bitcode : IMG_Object;
@@ -1058,7 +1063,6 @@ linkAndWrapDeviceFiles(SmallVectorImpl<OffloadFile> &LinkerInputFiles,
            Args.MakeArgString(LinkerArgs.getLastArgValue(OPT_arch_EQ))}};
       TheImage.Image = std::move(*FileOrErr);
 
-      std::lock_guard<decltype(ImageMtx)> Guard(ImageMtx);
       Images[Kind].emplace_back(std::move(TheImage));
     }
     return Error::success();