Skip to content

Commit

Permalink
[LinkerWrapper] Fix memory issues due to unguarded accesses to global…
Browse files Browse the repository at this point in the history
… state

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 #60437

Reviewed By: tianshilei1992

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

(cherry picked from commit 9c4591d)
  • Loading branch information
jhuber6 authored and tstellar committed Feb 6, 2023
1 parent 66c1717 commit e757c4d
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -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();
Expand Down

0 comments on commit e757c4d

Please sign in to comment.