[libc-commits] [libc] [libc] Use RAII and DirScanResult in scandir (PR #240107)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Sun Nov 8 00:44:23 PST 2026


https://github.com/kaladron created https://github.com/llvm/llvm-project/pull/240107

When building LLVM libc in full-build mode, dir_scan_impl_test fails with Scudo due to unaligned buffer casts and raw allocations in the test mock.  In production code, scan_impl relied on manual error jumps to free partially accumulated entries and close the directory descriptor, leaving callers vulnerable to leaks if intermediate failures occurred.

Modernise scan_impl and Dir::scan to manage the directory lifecycle and accumulated entries using RAII (unique_ptr, ScannedEntries, and AllocChecker), eliminating leak hazards on error paths at zero overhead to the happy path.  Return an ErrorOr<DirScanResult> pair rather than mutating an indirect out-pointer, decouple dir.h from the scanning template via dir_scan_result.h, and update unit tests with aligned buffers and span-based loops.

Assisted-by: Automated tooling, human reviewed.

>From e97937e9f091fccec9eedc9d6142511dde93304e Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Sat, 7 Nov 2026 20:54:41 +0000
Subject: [PATCH] [libc] Use RAII and DirScanResult in scandir

When building LLVM libc in full-build mode, dir_scan_impl_test fails
with Scudo due to unaligned buffer casts and raw allocations in the test
mock.  In production code, scan_impl relied on manual error jumps to
free partially accumulated entries and close the directory descriptor,
leaving callers vulnerable to leaks if intermediate failures occurred.

Modernise scan_impl and Dir::scan to manage the directory lifecycle
and accumulated entries using RAII (unique_ptr, ScannedEntries, and
AllocChecker), eliminating leak hazards on error paths at zero overhead
to the happy path.  Return an ErrorOr<DirScanResult> pair rather than
mutating an indirect out-pointer, decouple dir.h from the scanning
template via dir_scan_result.h, and update unit tests with aligned
buffers and span-based loops.

Assisted-by: Automated tooling, human reviewed.
---
 libc/src/__support/File/CMakeLists.txt        |  27 +-
 libc/src/__support/File/dir.cpp               |   9 +-
 libc/src/__support/File/dir.h                 |   8 +-
 libc/src/__support/File/dir_scan_impl.h       | 194 ++++++----
 libc/src/__support/File/dir_scan_result.h     |  38 ++
 libc/src/dirent/CMakeLists.txt                |   5 +-
 libc/src/dirent/scandir.cpp                   |  15 +-
 libc/test/src/__support/File/CMakeLists.txt   |   5 +-
 .../src/__support/File/dir_scan_impl_test.cpp | 351 ++++++++++--------
 libc/test/src/dirent/scandir_test.cpp         |  14 +
 10 files changed, 424 insertions(+), 242 deletions(-)
 create mode 100644 libc/src/__support/File/dir_scan_result.h

diff --git a/libc/src/__support/File/CMakeLists.txt b/libc/src/__support/File/CMakeLists.txt
index ca2670281a92d7..4d44b3befa5a31 100644
--- a/libc/src/__support/File/CMakeLists.txt
+++ b/libc/src/__support/File/CMakeLists.txt
@@ -41,17 +41,35 @@ add_object_library(
     libc.src.string.memory_utils.inline_memcpy
 )
 
+add_header_library(
+  dir_scan_result
+  HDRS
+    dir_scan_result.h
+  DEPENDS
+    libc.hdr.types.struct_dirent
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+)
+
 add_header_library(
   dir_scan_impl
   HDRS
     dir_scan_impl.h
   DEPENDS
-    libc.src.__support.error_or
+    .dir_scan_result
+    libc.hdr.errno_macros
+    libc.hdr.stdint_proxy
+    libc.hdr.types.struct_dirent
     libc.src.__support.CPP.limits
+    libc.src.__support.CPP.new
+    libc.src.__support.CPP.unique_ptr
+    libc.src.__support.alloc_checker
+    libc.src.__support.error_or
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
     libc.src.stdlib.qsort_util
     libc.src.string.memory_utils.inline_memcpy
-    libc.hdr.errno_macros
-    libc.hdr.types.struct_dirent
 )
 
 add_object_library(
@@ -62,16 +80,17 @@ add_object_library(
     dir.h
   DEPENDS
     .dir_scan_impl
+    .dir_scan_result
     libc.src.__support.CPP.mutex
     libc.src.__support.CPP.new
     libc.src.__support.CPP.span
     libc.src.__support.threads.mutex
     libc.src.__support.error_or
-    libc.src.__support.alloc_checker
     libc.hdr.errno_macros
     libc.hdr.types.struct_dirent
 )
 
+
 if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
   return()
 endif()
diff --git a/libc/src/__support/File/dir.cpp b/libc/src/__support/File/dir.cpp
index a7fb56945bd6b3..7d469913955172 100644
--- a/libc/src/__support/File/dir.cpp
+++ b/libc/src/__support/File/dir.cpp
@@ -79,11 +79,10 @@ int Dir::close() {
   return 0;
 }
 
-ErrorOr<int> Dir::scan(const char *name, struct dirent ***namelist,
-                       int (*filter)(const struct dirent *),
-                       int (*compare)(const struct dirent **,
-                                      const struct dirent **)) {
-  return internal::scan_impl<Dir>(name, namelist, filter, compare);
+ErrorOr<DirScanResult>
+Dir::scan(const char *name, int (*filter)(const struct dirent *),
+          int (*compare)(const struct dirent **, const struct dirent **)) {
+  return internal::scan_impl<Dir>(name, filter, compare);
 }
 
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/__support/File/dir.h b/libc/src/__support/File/dir.h
index 58f5276cc9ea16..373eb2aed323c7 100644
--- a/libc/src/__support/File/dir.h
+++ b/libc/src/__support/File/dir.h
@@ -15,6 +15,7 @@
 #define LLVM_LIBC_SRC___SUPPORT_FILE_DIR_H
 
 #include "src/__support/CPP/span.h"
+#include "src/__support/File/dir_scan_result.h"
 #include "src/__support/error_or.h"
 #include "src/__support/macros/config.h"
 #include "src/__support/threads/mutex.h"
@@ -79,10 +80,9 @@ class Dir {
   static ErrorOr<Dir *> open(const char *path);
   static ErrorOr<Dir *> fdopen(int fd);
   ErrorOr<struct dirent *> read();
-  static ErrorOr<int> scan(const char *name, struct dirent ***namelist,
-                           int (*filter)(const struct dirent *),
-                           int (*compare)(const struct dirent **,
-                                          const struct dirent **));
+  static ErrorOr<DirScanResult> scan(
+      const char *name, int (*filter)(const struct dirent *) = nullptr,
+      int (*compare)(const struct dirent **, const struct dirent **) = nullptr);
 
   LIBC_INLINE static size_t reclen(struct dirent *d) {
     return platform_dir_reclen(d);
diff --git a/libc/src/__support/File/dir_scan_impl.h b/libc/src/__support/File/dir_scan_impl.h
index d00a04be3fe07c..e8cd9564c73493 100644
--- a/libc/src/__support/File/dir_scan_impl.h
+++ b/libc/src/__support/File/dir_scan_impl.h
@@ -11,123 +11,171 @@
 ///
 //===----------------------------------------------------------------------===//
 
-#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_SCAN_IMPL_H
-#define LLVM_LIBC_SRC___SUPPORT_FILE_SCAN_IMPL_H
+#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_IMPL_H
+#define LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_IMPL_H
 
 #include "hdr/errno_macros.h"
-#include "hdr/func/free.h"
-#include "hdr/func/malloc.h"
-#include "hdr/func/realloc.h"
+#include "hdr/stdint_proxy.h"
 #include "hdr/types/struct_dirent.h"
 #include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/unique_ptr.h"
+#include "src/__support/File/dir_scan_result.h"
+#include "src/__support/alloc-checker.h"
 #include "src/__support/error_or.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
 #include "src/stdlib/qsort_util.h"
 #include "src/string/memory_utils/inline_memcpy.h"
 
 namespace LIBC_NAMESPACE_DECL {
 namespace internal {
 
-template <typename DirType>
-ErrorOr<int> scan_impl(const char *name, struct dirent ***namelist,
-                       int (*filter)(const struct dirent *),
-                       int (*compare)(const struct dirent **,
-                                      const struct dirent **)) {
-  auto res_open = DirType::open(name);
-  if (!res_open)
-    return LIBC_NAMESPACE::Error(res_open.error());
+template <typename DirType> struct DirCloser {
+  LIBC_INLINE constexpr DirCloser() = default;
 
-  DirType *dir = res_open.value();
+  LIBC_INLINE constexpr void operator()(DirType *d) const {
+    if (d != nullptr)
+      (void)d->close();
+  }
+};
 
-  int error_code = 0;
+// TODO: Replace with a dynamic array container once available.
+class ScannedEntries {
   struct dirent **entries = nullptr;
   size_t count = 0;
-  size_t buffer_capacity = 0;
+  size_t capacity = 0;
 
-  auto free_entries = [&entries, &count]() {
+public:
+  LIBC_INLINE constexpr ScannedEntries() = default;
+  ScannedEntries(const ScannedEntries &) = delete;
+  ScannedEntries &operator=(const ScannedEntries &) = delete;
+  ScannedEntries(ScannedEntries &&) = delete;
+  ScannedEntries &operator=(ScannedEntries &&) = delete;
+
+  LIBC_INLINE ~ScannedEntries() {
     if (entries == nullptr)
       return;
 
+    // Match the uint8_t[] dynamic allocation type when freeing entries.
     for (size_t i = 0; i < count; ++i)
-      ::free(entries[i]);
+      delete[] reinterpret_cast<uint8_t *>(entries[i]);
 
-    ::free(entries);
-  };
+    delete[] entries;
+  }
 
-  while (true) {
-    auto res_read = dir->read();
-    if (!res_read) {
-      error_code = res_read.error();
-      break;
-    }
+  LIBC_INLINE constexpr size_t size() const { return count; }
+  LIBC_INLINE constexpr struct dirent **data() const { return entries; }
 
-    struct dirent *entry = res_read.value();
-    if (entry == nullptr)
-      break;
+  LIBC_INLINE bool ensure_capacity() {
+    if (LIBC_LIKELY(count < capacity))
+      return true;
 
-    if (filter != nullptr && !filter(entry))
-      continue;
+    constexpr size_t INITIAL_CAPACITY = 8;
+    constexpr size_t MAX_CAPACITY =
+        cpp::numeric_limits<size_t>::max() / sizeof(struct dirent *);
+    if (LIBC_UNLIKELY(capacity >= MAX_CAPACITY / 2))
+      return false;
 
-    // Scandir must return the number of entries as int, anything
-    // above that is non-representable.
-    if (count == cpp::numeric_limits<int>::max()) {
-      error_code = EOVERFLOW;
-      break;
-    }
+    size_t new_capacity = (capacity == 0) ? INITIAL_CAPACITY : capacity * 2;
 
-    if (count >= buffer_capacity) {
-      size_t new_capacity = (buffer_capacity == 0) ? 8 : buffer_capacity * 2;
-
-      // Overflow check
-      if (new_capacity >
-          cpp::numeric_limits<size_t>::max() / sizeof(struct dirent *)) {
-        error_code = ENOMEM;
-        break;
-      }
-
-      struct dirent **bigger_buffer = static_cast<struct dirent **>(
-          ::realloc(entries, new_capacity * sizeof(struct dirent *)));
-      if (bigger_buffer == nullptr) {
-        error_code = ENOMEM;
-        break;
-      }
-      buffer_capacity = new_capacity;
-      entries = bigger_buffer;
+    AllocChecker ac;
+    struct dirent **bigger_buffer = new (ac) struct dirent *[new_capacity];
+    if (LIBC_UNLIKELY(!ac))
+      return false;
+
+    if (entries != nullptr) {
+      inline_memcpy(bigger_buffer, entries, count * sizeof(struct dirent *));
+      delete[] entries;
     }
 
-    size_t reclen = DirType::reclen(entry);
+    capacity = new_capacity;
+    entries = bigger_buffer;
+    return true;
+  }
 
-    struct dirent *new_entry = static_cast<struct dirent *>(::malloc(reclen));
-    if (new_entry == nullptr) {
-      error_code = ENOMEM;
-      break;
-    }
-    inline_memcpy(new_entry, entry, reclen);
+  LIBC_INLINE void push_back(struct dirent *entry) { entries[count++] = entry; }
 
-    entries[count] = new_entry;
-    count++;
+  LIBC_INLINE struct dirent **release() {
+    struct dirent **res = entries;
+    entries = nullptr;
+    count = 0;
+    capacity = 0;
+    return res;
   }
+};
+
+template <typename DirType>
+LIBC_INLINE ErrorOr<DirScanResult> scan_impl(
+    const char *name, int (*filter)(const struct dirent *) = nullptr,
+    int (*compare)(const struct dirent **, const struct dirent **) = nullptr) {
+  const auto res_open = DirType::open(name);
+  if (LIBC_UNLIKELY(!res_open))
+    return LIBC_NAMESPACE::Error(res_open.error());
 
-  dir->close();
+  cpp::unique_ptr<DirType, DirCloser<DirType>> dir(res_open.value());
+  ScannedEntries entries;
 
-  if (error_code != 0) {
-    free_entries();
-    return LIBC_NAMESPACE::Error(error_code);
+  constexpr size_t MAX_ENTRIES =
+      static_cast<size_t>(cpp::numeric_limits<int>::max());
+
+  while (true) {
+    const auto res_read = dir->read();
+    if (LIBC_UNLIKELY(!res_read))
+      return LIBC_NAMESPACE::Error(res_read.error());
+
+    struct dirent *const entry = res_read.value();
+    if (entry == nullptr)
+      break;
+
+    if (filter != nullptr && !filter(entry))
+      continue;
+
+    // Scandir must return the number of entries as int, anything
+    // above that is non-representable.
+    if (LIBC_UNLIKELY(entries.size() == MAX_ENTRIES))
+      return LIBC_NAMESPACE::Error(EOVERFLOW);
+
+    if (LIBC_UNLIKELY(!entries.ensure_capacity()))
+      return LIBC_NAMESPACE::Error(ENOMEM);
+
+    const size_t reclen = DirType::reclen(entry);
+    AllocChecker ac;
+    // Allocate only the variable-length record size (reclen) to save memory
+    // whilst heap allocation guarantees max_align_t alignment for struct
+    // dirent.
+    cpp::unique_ptr<uint8_t[]> new_entry_buf(new (ac) uint8_t[reclen]);
+    if (LIBC_UNLIKELY(!ac))
+      return LIBC_NAMESPACE::Error(ENOMEM);
+
+    inline_memcpy(new_entry_buf.get(), entry, reclen);
+    entries.push_back(
+        reinterpret_cast<struct dirent *>(new_entry_buf.release()));
   }
 
-  if (compare != nullptr && count > 1) {
+  dir.reset();
+
+  const size_t NUM_ENTRIES = entries.size();
+  if (compare != nullptr && NUM_ENTRIES > 1) {
+    // POSIX scandir/alphasort specifies 'const struct dirent **' rather than
+    // 'const struct dirent * const *'.  Because the inner pointer is non-const,
+    // converting from the sort engine's read-only 'const void *' requires
+    // const_cast to satisfy C++ qualification rules (see Austin Group #142:
+    // https://austingroupbugs.net/view.php?id=142).
     auto cmp_fn = [compare](const void *a, const void *b) {
       auto left = static_cast<const struct dirent **>(const_cast<void *>(a));
       auto right = static_cast<const struct dirent **>(const_cast<void *>(b));
       return compare(left, right);
     };
-    internal::unstable_sort(entries, count, sizeof(struct dirent *), cmp_fn);
+    internal::unstable_sort(entries.data(), NUM_ENTRIES,
+                            sizeof(struct dirent *), cmp_fn);
   }
 
-  *namelist = entries;
-  return static_cast<int>(count);
+  return DirScanResult{entries.release(), NUM_ENTRIES};
 }
 
 } // namespace internal
 } // namespace LIBC_NAMESPACE_DECL
 
-#endif // LLVM_LIBC_SRC___SUPPORT_FILE_SCAN_IMPL_H
+#endif // LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_IMPL_H
diff --git a/libc/src/__support/File/dir_scan_result.h b/libc/src/__support/File/dir_scan_result.h
new file mode 100644
index 00000000000000..9158b575a669ba
--- /dev/null
+++ b/libc/src/__support/File/dir_scan_result.h
@@ -0,0 +1,38 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Result type for directory scan operations.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_RESULT_H
+#define LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_RESULT_H
+
+#include "hdr/types/struct_dirent.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+
+#include <stddef.h>
+
+namespace LIBC_NAMESPACE_DECL {
+
+/// Holds the dynamically allocated array of directory entries and their count.
+/// Caller assumes ownership of both the entry array and individual dirents.
+struct DirScanResult {
+  struct dirent **entries = nullptr;
+  size_t count = 0;
+
+  LIBC_INLINE constexpr DirScanResult() = default;
+  LIBC_INLINE constexpr DirScanResult(struct dirent **e, size_t c)
+      : entries(e), count(c) {}
+};
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_FILE_DIR_SCAN_RESULT_H
diff --git a/libc/src/dirent/CMakeLists.txt b/libc/src/dirent/CMakeLists.txt
index 455d2b259563e5..c01cf48bf87613 100644
--- a/libc/src/dirent/CMakeLists.txt
+++ b/libc/src/dirent/CMakeLists.txt
@@ -85,9 +85,10 @@ add_entrypoint_object(
     scandir.h
   DEPENDS
     libc.hdr.types.struct_dirent
-    libc.src.__support.common
     libc.src.__support.File.dir
     libc.src.__support.File.platform_dir
-    libc.src.__support.macros.config
+    libc.src.__support.libc_errno
+    libc.src.__support.macros.null_check
+    libc.src.__support.macros.optimization
     libc.src.errno.errno
 )
diff --git a/libc/src/dirent/scandir.cpp b/libc/src/dirent/scandir.cpp
index c1966424f787e5..75f88ccc7295a5 100644
--- a/libc/src/dirent/scandir.cpp
+++ b/libc/src/dirent/scandir.cpp
@@ -17,7 +17,8 @@
 #include "src/__support/File/dir.h"
 #include "src/__support/common.h"
 #include "src/__support/libc_errno.h"
-#include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+#include "src/__support/macros/optimization.h"
 
 namespace LIBC_NAMESPACE_DECL {
 
@@ -26,14 +27,20 @@ LLVM_LIBC_FUNCTION(int, scandir,
                     int (*filter)(const struct dirent *),
                     int (*compare)(const struct dirent **,
                                    const struct dirent **))) {
+  LIBC_CRASH_ON_NULLPTR(dir);
+  LIBC_CRASH_ON_NULLPTR(namelist);
 
-  auto res = Dir::scan(dir, namelist, filter, compare);
-  if (!res) {
+  *namelist = nullptr;
+
+  const auto res = Dir::scan(dir, filter, compare);
+  if (LIBC_UNLIKELY(!res)) {
     libc_errno = res.error();
     return -1;
   }
 
-  return res.value();
+  const DirScanResult &scan_res = res.value();
+  *namelist = scan_res.entries;
+  return static_cast<int>(scan_res.count);
 }
 
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/test/src/__support/File/CMakeLists.txt b/libc/test/src/__support/File/CMakeLists.txt
index c15420188f6644..f880fe0ef2f527 100644
--- a/libc/test/src/__support/File/CMakeLists.txt
+++ b/libc/test/src/__support/File/CMakeLists.txt
@@ -51,13 +51,16 @@ add_libc_test(
   SRCS
     dir_scan_impl_test.cpp
   DEPENDS
+    libc.hdr.errno_macros
     libc.hdr.types.struct_dirent
     libc.src.__support.CPP.limits
+    libc.src.__support.CPP.new
+    libc.src.__support.CPP.span
+    libc.src.__support.CPP.string_view
     libc.src.__support.File.dir_scan_impl
     libc.src.__support.error_or
     libc.src.dirent.alphasort
     libc.src.string.memory_utils.inline_memcpy
-    libc.src.string.strlen
 )
 
 set(platform_stream_targets "platform_stdout;platform_stdin;platform_stderr")
diff --git a/libc/test/src/__support/File/dir_scan_impl_test.cpp b/libc/test/src/__support/File/dir_scan_impl_test.cpp
index 645da3c439cbe9..922874eca43e3c 100644
--- a/libc/test/src/__support/File/dir_scan_impl_test.cpp
+++ b/libc/test/src/__support/File/dir_scan_impl_test.cpp
@@ -7,60 +7,70 @@
 //===----------------------------------------------------------------------===//
 ///
 /// \file
-/// Unittests templated implementation of the scandir logic.
+/// Unit tests for the templated implementation of the scandir logic.
 ///
 //===----------------------------------------------------------------------===//
 
+#include "hdr/errno_macros.h"
 #include "hdr/types/struct_dirent.h"
 #include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
 #include "src/__support/File/dir_scan_impl.h"
 #include "src/__support/error_or.h"
 #include "src/dirent/alphasort.h"
 #include "src/string/memory_utils/inline_memcpy.h"
-#include "src/string/strlen.h"
 #include "test/UnitTest/Test.h"
 
-namespace LIBC_NAMESPACE_DECL {
+namespace {
 
-struct MockDirTestSetup {
+constexpr const char *TEST_FILES[] = {".", "..", "b.txt", "a.md", "c.pdf"};
+constexpr size_t TEST_FILES_COUNT = sizeof(TEST_FILES) / sizeof(TEST_FILES[0]);
+
+struct MockDirTestConfig {
   int read_errno_val = 0;
   int open_errno_val = 0;
-  // how many successful reads until it fails.
-  size_t read_fails_at =
-      cpp::numeric_limits<size_t>::max(); // Don't fail by default
-  const char *test_files[5] = {".", "..", "b.txt", "a.md", "c.pdf"};
-  size_t test_files_count = sizeof(test_files) / sizeof(test_files[0]);
+  size_t read_fails_at = LIBC_NAMESPACE::cpp::numeric_limits<size_t>::max();
+  const char *const *files = TEST_FILES;
+  size_t files_count = TEST_FILES_COUNT;
+  bool was_closed = false;
 };
 
-MockDirTestSetup test_setup;
+MockDirTestConfig g_mock_config;
 
 struct MockDir {
   alignas(struct dirent) char dirent_buffer[sizeof(struct dirent) + 256] = {};
   size_t current_read_index = 0;
-  struct dirent *entry = reinterpret_cast<struct dirent *>(dirent_buffer);
+
+  static MockDir instance;
 
   static LIBC_NAMESPACE::ErrorOr<MockDir *> open(const char *) {
-    if (test_setup.open_errno_val != 0)
-      return LIBC_NAMESPACE::Error(test_setup.open_errno_val);
-    return new MockDir();
+    if (g_mock_config.open_errno_val != 0)
+      return LIBC_NAMESPACE::Error(g_mock_config.open_errno_val);
+    instance.current_read_index = 0;
+    instance.dirent_buffer[0] = '\0';
+    g_mock_config.was_closed = false;
+    return &instance;
   }
 
   LIBC_NAMESPACE::ErrorOr<struct dirent *> read() {
-    if (current_read_index == test_setup.read_fails_at)
-      return LIBC_NAMESPACE::Error(test_setup.read_errno_val);
+    if (current_read_index == g_mock_config.read_fails_at)
+      return LIBC_NAMESPACE::Error(g_mock_config.read_errno_val);
 
-    if (current_read_index >= test_setup.test_files_count)
+    if (current_read_index >= g_mock_config.files_count)
       return nullptr;
 
+    auto *entry = reinterpret_cast<struct dirent *>(dirent_buffer);
     entry->d_ino = current_read_index + 1;
-    const char *name = test_setup.test_files[current_read_index];
-    LIBC_NAMESPACE::inline_memcpy(entry->d_name, name,
-                                  LIBC_NAMESPACE::strlen(name) + 1);
+    const char *name = g_mock_config.files[current_read_index];
+    size_t name_len = LIBC_NAMESPACE::cpp::string_view(name).size();
+    LIBC_NAMESPACE::inline_memcpy(entry->d_name, name, name_len + 1);
     current_read_index++;
     return entry;
   }
 
-  static size_t reclen(struct dirent *entry) {
+  static constexpr size_t reclen(const struct dirent *entry) {
     size_t name_len = 0;
     while (entry->d_name[name_len] != '\0')
       ++name_len;
@@ -68,183 +78,226 @@ struct MockDir {
   }
 
   int close() {
-    delete this;
+    g_mock_config.was_closed = true;
     return 0;
   }
 };
 
-} // namespace LIBC_NAMESPACE_DECL
+MockDir MockDir::instance;
+
+constexpr int partialorder(const struct dirent **a, const struct dirent **b) {
+  char char_a = (*a)->d_name[0];
+  char char_b = (*b)->d_name[0];
+
+  auto get_weight = [](char c) -> int {
+    if (c == 'a')
+      return 1;
+    if (c == 'b')
+      return 2;
+    return 3;
+  };
+
+  return get_weight(char_a) - get_weight(char_b);
+}
+
+constexpr int partialorder_reverse(const struct dirent **a,
+                                   const struct dirent **b) {
+  return -partialorder(a, b);
+}
+
+int omegasort(const struct dirent **a, const struct dirent **b) {
+  return -LIBC_NAMESPACE::alphasort(a, b);
+}
+
+constexpr int skip_hidden(const struct dirent *entry) {
+  return entry->d_name[0] != '.';
+}
+
+constexpr int
+find_entry_index(LIBC_NAMESPACE::cpp::span<struct dirent *const> list,
+                 LIBC_NAMESPACE::cpp::string_view target) {
+  int i = 0;
+  for (const struct dirent *entry : list) {
+    if (entry != nullptr &&
+        LIBC_NAMESPACE::cpp::string_view(entry->d_name) == target)
+      return i;
+    ++i;
+  }
+  return -1;
+}
+
+} // anonymous namespace
 
 class LlvmLibcScanImplTest : public LIBC_NAMESPACE::testing::Test {
 protected:
+  LIBC_NAMESPACE::DirScanResult result{};
+
   void SetUp() override {
     LIBC_NAMESPACE::testing::Test::SetUp();
-    LIBC_NAMESPACE::test_setup = LIBC_NAMESPACE::MockDirTestSetup{};
+    g_mock_config = MockDirTestConfig{};
+    result = LIBC_NAMESPACE::DirScanResult{};
   }
-};
 
-TEST_F(LlvmLibcScanImplTest, SuccessfulRun) {
+  void TearDown() override {
+    if (result.entries != nullptr) {
+      for (struct dirent *entry : entries())
+        delete[] reinterpret_cast<uint8_t *>(entry);
+      delete[] result.entries;
+      result = LIBC_NAMESPACE::DirScanResult{};
+    }
+    LIBC_NAMESPACE::testing::Test::TearDown();
+  }
+
+  LIBC_NAMESPACE::cpp::span<struct dirent *> entries() const {
+    return {result.entries, result.count};
+  }
 
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, nullptr);
-  ASSERT_TRUE(res.has_value());
-  ASSERT_EQ(res.value(),
-            static_cast<int>(LIBC_NAMESPACE::test_setup.test_files_count));
+  LIBC_NAMESPACE::ErrorOr<LIBC_NAMESPACE::DirScanResult>
+  scan(const char *path = "fake/path",
+       int (*filter)(const struct dirent *) = nullptr,
+       int (*compare)(const struct dirent **,
+                      const struct dirent **) = nullptr) {
+    if (result.entries != nullptr)
+      TearDown();
+    auto res =
+        LIBC_NAMESPACE::internal::scan_impl<MockDir>(path, filter, compare);
+    if (res.has_value())
+      result = res.value();
+    else
+      result = LIBC_NAMESPACE::DirScanResult{};
+    return res;
+  }
+};
 
-  for (size_t i = 0; i < LIBC_NAMESPACE::test_setup.test_files_count; ++i) {
-    ASSERT_STREQ(namelist[i]->d_name, LIBC_NAMESPACE::test_setup.test_files[i]);
+TEST_F(LlvmLibcScanImplTest, SuccessfulRun) {
+  auto res = scan();
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  ASSERT_EQ(res.value().count, TEST_FILES_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  size_t i = 0;
+  for (const struct dirent *entry : entries()) {
+    ASSERT_NE(entry, nullptr);
+    EXPECT_STREQ(entry->d_name, TEST_FILES[i++]);
   }
 }
 
 TEST_F(LlvmLibcScanImplTest, OpenFails) {
+  g_mock_config.open_errno_val = EACCES;
 
-  struct dirent **namelist = nullptr;
-  LIBC_NAMESPACE::test_setup.open_errno_val = EACCES;
-
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, nullptr);
-  ASSERT_FALSE(res.has_value());
+  auto res = scan();
+  ASSERT_FALSE(res.has_value())
+      << "Expected failure, but succeeded with count: " << res.value().count;
   EXPECT_EQ(res.error(), EACCES);
+  EXPECT_EQ(result.entries, nullptr);
+  EXPECT_FALSE(g_mock_config.was_closed);
 }
 
 TEST_F(LlvmLibcScanImplTest, ReadFailsAtStart) {
+  g_mock_config.read_errno_val = ENOENT;
+  g_mock_config.read_fails_at = 0;
 
-  struct dirent **namelist = nullptr;
-  LIBC_NAMESPACE::test_setup.read_errno_val = ENOENT;
-  LIBC_NAMESPACE::test_setup.read_fails_at = 0;
-
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, nullptr);
-  ASSERT_FALSE(res.has_value());
+  auto res = scan();
+  ASSERT_FALSE(res.has_value())
+      << "Expected failure, but succeeded with count: " << res.value().count;
   EXPECT_EQ(res.error(), ENOENT);
+  EXPECT_EQ(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
 }
 
 TEST_F(LlvmLibcScanImplTest, ReadFailsMidway) {
+  g_mock_config.read_errno_val = ENOENT;
+  g_mock_config.read_fails_at = 3;
 
-  struct dirent **namelist = nullptr;
-  LIBC_NAMESPACE::test_setup.read_errno_val = ENOENT;
-  LIBC_NAMESPACE::test_setup.read_fails_at = 3;
-
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, nullptr);
-  ASSERT_FALSE(res.has_value());
+  auto res = scan();
+  ASSERT_FALSE(res.has_value())
+      << "Expected failure, but succeeded with count: " << res.value().count;
   EXPECT_EQ(res.error(), ENOENT);
-}
-
-int partialorder(const struct dirent **a, const struct dirent **b) {
-  char char_a = (*a)->d_name[0];
-  char char_b = (*b)->d_name[0];
-
-  auto get_weight = [](char c) {
-    if (c == 'a')
-      return 1;
-    if (c == 'b')
-      return 2;
-    return 3;
-  };
-
-  int weight_a = get_weight(char_a);
-  int weight_b = get_weight(char_b);
-
-  return weight_a - weight_b;
+  EXPECT_EQ(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
 }
 
 TEST_F(LlvmLibcScanImplTest, TestPartialOrdering) {
-
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, partialorder);
-  ASSERT_TRUE(res.has_value());
-  ASSERT_EQ(res.value(),
-            static_cast<int>(LIBC_NAMESPACE::test_setup.test_files_count));
-  int a_index = -1;
-  int b_index = -1;
-  for (int i = 0; i < res.value(); ++i) {
-    if (namelist[i]->d_name[0] == 'a')
-      a_index = i;
-
-    else if (namelist[i]->d_name[0] == 'b') {
-      b_index = i;
-    }
-  }
+  auto res = scan("fake/path", nullptr, partialorder);
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  ASSERT_EQ(res.value().count, TEST_FILES_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  int a_index = find_entry_index(entries(), "a.md");
+  int b_index = find_entry_index(entries(), "b.txt");
   ASSERT_NE(a_index, -1);
   ASSERT_NE(b_index, -1);
-  ASSERT_GT(b_index, a_index);
-}
-
-int partialorder_reverse(const struct dirent **a, const struct dirent **b) {
-  return -partialorder(a, b);
+  EXPECT_LT(a_index, b_index);
 }
 
 TEST_F(LlvmLibcScanImplTest, TestPartialOrderingReverse) {
-
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, partialorder_reverse);
-  ASSERT_TRUE(res.has_value());
-  ASSERT_EQ(res.value(),
-            static_cast<int>(LIBC_NAMESPACE::test_setup.test_files_count));
-  int a_index = -1;
-  int b_index = -1;
-  for (int i = 0; i < res.value(); ++i) {
-    if (namelist[i]->d_name[0] == 'a')
-      a_index = i;
-
-    else if (namelist[i]->d_name[0] == 'b') {
-      b_index = i;
-    }
-  }
+  auto res = scan("fake/path", nullptr, partialorder_reverse);
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  ASSERT_EQ(res.value().count, TEST_FILES_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  int a_index = find_entry_index(entries(), "a.md");
+  int b_index = find_entry_index(entries(), "b.txt");
   ASSERT_NE(a_index, -1);
   ASSERT_NE(b_index, -1);
-  ASSERT_GT(a_index, b_index);
+  EXPECT_GT(a_index, b_index);
 }
 
 TEST_F(LlvmLibcScanImplTest, TestTotalOrderingAZ) {
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, LIBC_NAMESPACE::alphasort);
-  ASSERT_TRUE(res.has_value());
-  ASSERT_EQ(res.value(),
-            static_cast<int>(LIBC_NAMESPACE::test_setup.test_files_count));
-  const char *desired_order[] = {".", "..", "a.md", "b.txt", "c.pdf", nullptr};
-  for (size_t i = 0; i < LIBC_NAMESPACE::test_setup.test_files_count &&
-                     desired_order[i] != nullptr;
-       ++i) {
-    ASSERT_STREQ(namelist[i]->d_name, desired_order[i]);
+  auto res = scan("fake/path", nullptr, LIBC_NAMESPACE::alphasort);
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  ASSERT_EQ(res.value().count, TEST_FILES_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  constexpr const char *DESIRED_ORDER[] = {".", "..", "a.md", "b.txt", "c.pdf"};
+  size_t i = 0;
+  for (const struct dirent *entry : entries()) {
+    ASSERT_NE(entry, nullptr);
+    EXPECT_STREQ(entry->d_name, DESIRED_ORDER[i++]);
   }
 }
 
-int omegasort(const struct dirent **a, const struct dirent **b) {
-  return -LIBC_NAMESPACE::alphasort(a, b);
-}
-
 TEST_F(LlvmLibcScanImplTest, TestTotalOrderingZA) {
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, nullptr, omegasort);
-  ASSERT_TRUE(res.has_value());
-  ASSERT_EQ(res.value(),
-            static_cast<int>(LIBC_NAMESPACE::test_setup.test_files_count));
-  const char *desired_order[] = {"c.pdf", "b.txt", "a.md", "..", ".", nullptr};
-  for (size_t i = 0; i < LIBC_NAMESPACE::test_setup.test_files_count &&
-                     desired_order[i] != nullptr;
-       ++i) {
-    ASSERT_STREQ(namelist[i]->d_name, desired_order[i]);
+  auto res = scan("fake/path", nullptr, omegasort);
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  ASSERT_EQ(res.value().count, TEST_FILES_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  constexpr const char *DESIRED_ORDER[] = {"c.pdf", "b.txt", "a.md", "..", "."};
+  size_t i = 0;
+  for (const struct dirent *entry : entries()) {
+    ASSERT_NE(entry, nullptr);
+    EXPECT_STREQ(entry->d_name, DESIRED_ORDER[i++]);
   }
 }
 
-int skip_hidden(const struct dirent *entry) { return entry->d_name[0] != '.'; }
+TEST_F(LlvmLibcScanImplTest, TestFilter) {
+  auto res = scan("fake/path", skip_hidden, nullptr);
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  constexpr size_t DESIRED_COUNT = TEST_FILES_COUNT - 2;
+  ASSERT_EQ(res.value().count, DESIRED_COUNT);
+  ASSERT_NE(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
+
+  constexpr const char *DESIRED_FILES[] = {"b.txt", "a.md", "c.pdf"};
+  size_t i = 0;
+  for (const struct dirent *entry : entries()) {
+    ASSERT_NE(entry, nullptr);
+    EXPECT_STREQ(entry->d_name, DESIRED_FILES[i++]);
+  }
+}
 
-TEST_F(LlvmLibcScanImplTest, TesetFilter) {
-  struct dirent **namelist = nullptr;
-  auto res = LIBC_NAMESPACE::internal::scan_impl<LIBC_NAMESPACE::MockDir>(
-      "fake/path", &namelist, skip_hidden, nullptr);
-  ASSERT_TRUE(res.has_value());
-  size_t desired_count = LIBC_NAMESPACE::test_setup.test_files_count - 2;
-  ASSERT_EQ(res.value(), static_cast<int>(desired_count));
-  const char *desired_files[] = {"b.txt", "a.md", "c.pdf", nullptr};
+TEST_F(LlvmLibcScanImplTest, EmptyDirectory) {
+  g_mock_config.files_count = 0;
 
-  for (size_t i = 0; i < desired_count && desired_files[i] != nullptr; ++i)
-    ASSERT_STREQ(namelist[i]->d_name, desired_files[i]);
+  auto res = scan();
+  ASSERT_TRUE(res.has_value()) << "scan_impl failed: " << res.error();
+  EXPECT_EQ(res.value().count, 0UL);
+  EXPECT_EQ(result.entries, nullptr);
+  EXPECT_TRUE(g_mock_config.was_closed);
 }
diff --git a/libc/test/src/dirent/scandir_test.cpp b/libc/test/src/dirent/scandir_test.cpp
index 274063836494ea..7736b0386cc6f3 100644
--- a/libc/test/src/dirent/scandir_test.cpp
+++ b/libc/test/src/dirent/scandir_test.cpp
@@ -202,3 +202,17 @@ TEST_F(LlvmLibcScandirTest, TestBadDirname) {
   ASSERT_THAT(LIBC_NAMESPACE::scandir("", &namelist, NULL, NULL),
               Fails(ENOENT, -1));
 }
+
+#if defined(LIBC_ADD_NULL_CHECKS)
+
+TEST_F(LlvmLibcScandirTest, NullPointerCrash) {
+  struct dirent **namelist = nullptr;
+  ASSERT_DEATH(
+      [&]() { LIBC_NAMESPACE::scandir(nullptr, &namelist, nullptr, nullptr); },
+      WITH_SIGNAL(-1));
+  ASSERT_DEATH(
+      [&]() { LIBC_NAMESPACE::scandir("fake_dir", nullptr, nullptr, nullptr); },
+      WITH_SIGNAL(-1));
+}
+
+#endif // defined(LIBC_ADD_NULL_CHECKS)



More information about the libc-commits mailing list