[clang] [InstallAPI] Fix potential null pointer dereference in file enumeration (PR #97900)

via cfe-commits cfe-commits at lists.llvm.org
Sat Jul 6 08:35:35 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: None (smanna12)

<details>
<summary>Changes</summary>

This patch addresses a static analyser concern about a potential null pointer dereference in the clang::installapi::enumerateFiles function.

The recursive_directory_iterator could become invalid (i.e., i.State set to nullptr) when iterating over files.

We now check the validity of the iterator before dereferencing it and handle possible errors from FS.status. This fix ensures safe iteration over the directory entries and prevents crashes due to undefined behavior.

---
Full diff: https://github.com/llvm/llvm-project/pull/97900.diff


1 Files Affected:

- (modified) clang/lib/InstallAPI/HeaderFile.cpp (+6-1) 


``````````diff
diff --git a/clang/lib/InstallAPI/HeaderFile.cpp b/clang/lib/InstallAPI/HeaderFile.cpp
index 0b7041ec8147e..f25bf3428ee13 100644
--- a/clang/lib/InstallAPI/HeaderFile.cpp
+++ b/clang/lib/InstallAPI/HeaderFile.cpp
@@ -51,8 +51,13 @@ llvm::Expected<PathSeq> enumerateFiles(FileManager &FM, StringRef Directory) {
     if (EC)
       return errorCodeToError(EC);
 
+    Ensure the iterator is valid before dereferencing.
+    if (i == ie || !i->isValid())
+      break;
+
     // Skip files that do not exist. This usually happens for broken symlinks.
-    if (FS.status(i->path()) == std::errc::no_such_file_or_directory)
+    auto StatusOrErr = FS.status(i->path());
+    if (!StatusOrErr || StatusOrErr.getError() == std::errc::no_such_file_or_directory)
       continue;
 
     StringRef Path = i->path();

``````````

</details>


https://github.com/llvm/llvm-project/pull/97900


More information about the cfe-commits mailing list