Fix a memory leak
Analyzer complaint:
frameworks/compile/slang/slang.cpp:336:12: warning: Potential leak of
memory pointed to by 'OS'
This is a bit tricky: llvm::tool_output_file's ctor might write a
failure value to EC. If so, we'd take the `if (EC) return false;`
branch in Slang::setOutput, and fail to free `OS`.
Using a unique_ptr instead fixes all of our problems.
This also removes a nullptr check; `new` without `std::nothrow` can't
return null, so the null check was unnecessary.
Bug: None
Test: Ran the static analyzer. No complaints about leaky memory.
Change-Id: I22c865ea4ef8caf1d8c3b14939a6d28850f587c4
diff --git a/slang.cpp b/slang.cpp
index 5b6aff7..f942beb 100644
--- a/slang.cpp
+++ b/slang.cpp
@@ -128,7 +128,7 @@
llvm::LLVMContext &getGlobalLLVMContext() { return globalContext; }
-static inline llvm::tool_output_file *
+static inline std::unique_ptr<llvm::tool_output_file>
OpenOutputFile(const char *OutputFile,
llvm::sys::fs::OpenFlags Flags,
std::error_code &EC,
@@ -139,10 +139,7 @@
EC = llvm::sys::fs::create_directories(
llvm::sys::path::parent_path(OutputFile));
if (!EC) {
- llvm::tool_output_file *F =
- new llvm::tool_output_file(OutputFile, EC, Flags);
- if (F != nullptr)
- return F;
+ return llvm::make_unique<llvm::tool_output_file>(OutputFile, EC, Flags);
}
// Report error here.
@@ -310,7 +307,7 @@
bool Slang::setOutput(const char *OutputFile) {
std::error_code EC;
- llvm::tool_output_file *OS = nullptr;
+ std::unique_ptr<llvm::tool_output_file> OS;
switch (mOT) {
case OT_Dependency:
@@ -335,7 +332,7 @@
if (EC)
return false;
- mOS.reset(OS);
+ mOS = std::move(OS);
mOutputFileName = OutputFile;
@@ -345,8 +342,7 @@
bool Slang::setDepOutput(const char *OutputFile) {
std::error_code EC;
- mDOS.reset(
- OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine));
+ mDOS = OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine);
if (EC || (mDOS.get() == nullptr))
return false;