[libc-commits] [libc] [libc] Add POSIX.1-2024 <ftw.h> and Linux nftw implementation (PR #234996)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Wed Nov 18 13:55:51 PST 2026


https://github.com/kaladron updated https://github.com/llvm/llvm-project/pull/234996

>From 991e09a4cd32f3d2448b3c8c0a2f26444b67a6b1 Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Fri, 23 Oct 2026 11:44:59 +0100
Subject: [PATCH] [libc] Add POSIX.1-2024 <ftw.h> and Linux nftw implementation

Implement the POSIX.1-2024 <ftw.h> header, hdrgen metadata, internal
proxy headers, Linux iterative nftw traversal, hermetic unit tests,
and docgen metadata.  Omit ftw(), which was removed in POSIX.1-2024
(Issue 8) and is recorded as removed-in-posix-2024 in docgen.

The traversal is completely non-recursive and uses an explicit heap
frame vector paired with a dynamic path buffer, bounded open directory
descriptors with offset resumption via lseek(SEEK_SET) when fd_limit
is exceeded, *at relative syscalls (statx and openat) against the
active parent directory descriptor with (st_dev, st_ino) verification
to prevent TOCTOU directory replacement races, active ancestor cycle
detection, visited-directory tracking in logical mode so no directory
is reported twice, FTW_CHDIR working directory management and
restoration, and GNU FTW_ACTIONRETVAL support.

Co-authored-by: Raman Tenneti <rtenneti at google.com>
Assisted-by: Automated tooling, human reviewed.
---
 libc/config/linux/aarch64/entrypoints.txt    |   3 +
 libc/config/linux/aarch64/headers.txt        |   1 +
 libc/config/linux/riscv/entrypoints.txt      |   3 +
 libc/config/linux/riscv/headers.txt          |   1 +
 libc/config/linux/x86_64/entrypoints.txt     |   3 +
 libc/config/linux/x86_64/headers.txt         |   1 +
 libc/hdr/CMakeLists.txt                      |   8 +
 libc/hdr/ftw_macros.h                        |  27 +
 libc/hdr/types/CMakeLists.txt                |  16 +
 libc/hdr/types/ino_t.h                       |  27 +
 libc/hdr/types/struct_FTW.h                  |  27 +
 libc/include/CMakeLists.txt                  |  11 +
 libc/include/ftw.yaml                        |  62 ++
 libc/include/llvm-libc-macros/CMakeLists.txt |   6 +
 libc/include/llvm-libc-macros/ftw-macros.h   |  39 +
 libc/include/llvm-libc-types/CMakeLists.txt  |   1 +
 libc/include/llvm-libc-types/struct_FTW.h    |  22 +
 libc/src/CMakeLists.txt                      |   1 +
 libc/src/ftw/CMakeLists.txt                  |  10 +
 libc/src/ftw/linux/CMakeLists.txt            |  37 +
 libc/src/ftw/linux/nftw.cpp                  | 772 +++++++++++++++++++
 libc/src/ftw/nftw.h                          |  29 +
 libc/test/src/CMakeLists.txt                 |   1 +
 libc/test/src/ftw/CMakeLists.txt             |  33 +
 libc/test/src/ftw/nftw_test.cpp              | 709 +++++++++++++++++
 libc/utils/docgen/ftw.yaml                   |  10 +
 26 files changed, 1860 insertions(+)
 create mode 100644 libc/hdr/ftw_macros.h
 create mode 100644 libc/hdr/types/ino_t.h
 create mode 100644 libc/hdr/types/struct_FTW.h
 create mode 100644 libc/include/ftw.yaml
 create mode 100644 libc/include/llvm-libc-macros/ftw-macros.h
 create mode 100644 libc/include/llvm-libc-types/struct_FTW.h
 create mode 100644 libc/src/ftw/CMakeLists.txt
 create mode 100644 libc/src/ftw/linux/CMakeLists.txt
 create mode 100644 libc/src/ftw/linux/nftw.cpp
 create mode 100644 libc/src/ftw/nftw.h
 create mode 100644 libc/test/src/ftw/CMakeLists.txt
 create mode 100644 libc/test/src/ftw/nftw_test.cpp

diff --git a/libc/config/linux/aarch64/entrypoints.txt b/libc/config/linux/aarch64/entrypoints.txt
index b43c7c670db822..0a16329e6385ff 100644
--- a/libc/config/linux/aarch64/entrypoints.txt
+++ b/libc/config/linux/aarch64/entrypoints.txt
@@ -1204,6 +1204,9 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.dirent.scandir
     libc.src.dirent.fdopendir
 
+    # ftw.h entrypoints
+    libc.src.ftw.nftw
+
     # errno.h entrypoints
     libc.src.errno.program_invocation_name
     libc.src.errno.program_invocation_short_name
diff --git a/libc/config/linux/aarch64/headers.txt b/libc/config/linux/aarch64/headers.txt
index 53ced730e8ff8d..44000c12cb4dbb 100644
--- a/libc/config/linux/aarch64/headers.txt
+++ b/libc/config/linux/aarch64/headers.txt
@@ -19,6 +19,7 @@ set(TARGET_PUBLIC_HEADERS
     libc.include.fenv
     libc.include.fnmatch
     libc.include.float
+    libc.include.ftw
     libc.include.grp
     libc.include.inttypes
     libc.include.langinfo
diff --git a/libc/config/linux/riscv/entrypoints.txt b/libc/config/linux/riscv/entrypoints.txt
index 6354889fa0edd5..696dfd30b0c988 100644
--- a/libc/config/linux/riscv/entrypoints.txt
+++ b/libc/config/linux/riscv/entrypoints.txt
@@ -1447,6 +1447,9 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.dirent.scandir
     libc.src.dirent.fdopendir
 
+    # ftw.h entrypoints
+    libc.src.ftw.nftw
+
     # net/if.h entrypoints
     libc.src.net.if.if_freenameindex
     libc.src.net.if.if_nameindex
diff --git a/libc/config/linux/riscv/headers.txt b/libc/config/linux/riscv/headers.txt
index 4fd6f5e591a6bb..897564e51c49fb 100644
--- a/libc/config/linux/riscv/headers.txt
+++ b/libc/config/linux/riscv/headers.txt
@@ -19,6 +19,7 @@ set(TARGET_PUBLIC_HEADERS
     libc.include.fenv
     libc.include.fnmatch
     libc.include.float
+    libc.include.ftw
     libc.include.grp
     libc.include.inttypes
     libc.include.langinfo
diff --git a/libc/config/linux/x86_64/entrypoints.txt b/libc/config/linux/x86_64/entrypoints.txt
index 0e7ae76c11457c..6f043f5df895f1 100644
--- a/libc/config/linux/x86_64/entrypoints.txt
+++ b/libc/config/linux/x86_64/entrypoints.txt
@@ -1447,6 +1447,9 @@ if(LLVM_LIBC_FULL_BUILD)
     libc.src.dirent.scandir
     libc.src.dirent.fdopendir
 
+    # ftw.h entrypoints
+    libc.src.ftw.nftw
+
     # net/if.h entrypoints
     libc.src.net.if.if_freenameindex
     libc.src.net.if.if_nameindex
diff --git a/libc/config/linux/x86_64/headers.txt b/libc/config/linux/x86_64/headers.txt
index cd882ec8e36039..0ec92e6cffedd3 100644
--- a/libc/config/linux/x86_64/headers.txt
+++ b/libc/config/linux/x86_64/headers.txt
@@ -19,6 +19,7 @@ set(TARGET_PUBLIC_HEADERS
     libc.include.fenv
     libc.include.fnmatch
     libc.include.float
+    libc.include.ftw
     libc.include.grp
     libc.include.inttypes
     libc.include.langinfo
diff --git a/libc/hdr/CMakeLists.txt b/libc/hdr/CMakeLists.txt
index 15b03c616fe5bb..ef8888d927a180 100644
--- a/libc/hdr/CMakeLists.txt
+++ b/libc/hdr/CMakeLists.txt
@@ -88,6 +88,14 @@ add_proxy_header_library(
     libc.include.llvm-libc-macros.fnmatch_macros
 )
 
+add_proxy_header_library(
+  ftw_macros
+  HDRS
+    ftw_macros.h
+  FULL_BUILD_DEPENDS
+    libc.include.llvm-libc-macros.ftw_macros
+)
+
 add_proxy_header_library(
   glob_macros
   HDRS
diff --git a/libc/hdr/ftw_macros.h b/libc/hdr/ftw_macros.h
new file mode 100644
index 00000000000000..05b0cbf88cfc5f
--- /dev/null
+++ b/libc/hdr/ftw_macros.h
@@ -0,0 +1,27 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Proxy header for ftw macros.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_HDR_FTW_MACROS_H
+#define LLVM_LIBC_HDR_FTW_MACROS_H
+
+#ifdef LIBC_FULL_BUILD
+
+#include "include/llvm-libc-macros/ftw-macros.h"
+
+#else // Overlay mode
+
+#include <ftw.h>
+
+#endif // LIBC_FULL_BUILD
+
+#endif // LLVM_LIBC_HDR_FTW_MACROS_H
diff --git a/libc/hdr/types/CMakeLists.txt b/libc/hdr/types/CMakeLists.txt
index 61fc9c948a638c..921ecc4cc04c17 100644
--- a/libc/hdr/types/CMakeLists.txt
+++ b/libc/hdr/types/CMakeLists.txt
@@ -1445,3 +1445,19 @@ add_proxy_header_library(
   FULL_BUILD_DEPENDS
     libc.include.llvm-libc-types.eventfd_t
 )
+
+add_proxy_header_library(
+  ino_t
+  HDRS
+    ino_t.h
+  FULL_BUILD_DEPENDS
+    libc.include.llvm-libc-types.ino_t
+)
+
+add_proxy_header_library(
+  struct_FTW
+  HDRS
+    struct_FTW.h
+  FULL_BUILD_DEPENDS
+    libc.include.llvm-libc-types.struct_FTW
+)
diff --git a/libc/hdr/types/ino_t.h b/libc/hdr/types/ino_t.h
new file mode 100644
index 00000000000000..d520f54b33676a
--- /dev/null
+++ b/libc/hdr/types/ino_t.h
@@ -0,0 +1,27 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Proxy header for ino_t.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_HDR_TYPES_INO_T_H
+#define LLVM_LIBC_HDR_TYPES_INO_T_H
+
+#ifdef LIBC_FULL_BUILD
+
+#include "include/llvm-libc-types/ino_t.h"
+
+#else // Overlay mode
+
+#include <sys/types.h>
+
+#endif // LIBC_FULL_BUILD
+
+#endif // LLVM_LIBC_HDR_TYPES_INO_T_H
diff --git a/libc/hdr/types/struct_FTW.h b/libc/hdr/types/struct_FTW.h
new file mode 100644
index 00000000000000..c39a7819ea1990
--- /dev/null
+++ b/libc/hdr/types/struct_FTW.h
@@ -0,0 +1,27 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Proxy header for struct FTW.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_HDR_TYPES_STRUCT_FTW_H
+#define LLVM_LIBC_HDR_TYPES_STRUCT_FTW_H
+
+#ifdef LIBC_FULL_BUILD
+
+#include "include/llvm-libc-types/struct_FTW.h"
+
+#else // Overlay mode
+
+#include <ftw.h>
+
+#endif // LIBC_FULL_BUILD
+
+#endif // LLVM_LIBC_HDR_TYPES_STRUCT_FTW_H
diff --git a/libc/include/CMakeLists.txt b/libc/include/CMakeLists.txt
index 7ca695073e2ab1..c023de1f0d60bb 100644
--- a/libc/include/CMakeLists.txt
+++ b/libc/include/CMakeLists.txt
@@ -927,6 +927,17 @@ add_header_macro(
     .llvm-libc-types.struct_statx
 )
 
+add_header_macro(
+  ftw
+  ../libc/include/ftw.yaml
+  ftw.h
+  DEPENDS
+    .sys_stat
+    .llvm_libc_common_h
+    .llvm-libc-macros.ftw_macros
+    .llvm-libc-types.struct_FTW
+)
+
 add_header_macro(
   sys_select
   ../libc/include/sys/select.yaml
diff --git a/libc/include/ftw.yaml b/libc/include/ftw.yaml
new file mode 100644
index 00000000000000..3713d6ad2af685
--- /dev/null
+++ b/libc/include/ftw.yaml
@@ -0,0 +1,62 @@
+header: ftw.h
+public_includes:
+  - sys/stat.h
+standards:
+  - posix
+macros:
+  - macro_name: FTW_F
+    macro_header: ftw-macros.h
+  - macro_name: FTW_D
+    macro_header: ftw-macros.h
+  - macro_name: FTW_DNR
+    macro_header: ftw-macros.h
+  - macro_name: FTW_NS
+    macro_header: ftw-macros.h
+  - macro_name: FTW_SL
+    macro_header: ftw-macros.h
+  - macro_name: FTW_DP
+    macro_header: ftw-macros.h
+  - macro_name: FTW_SLN
+    macro_header: ftw-macros.h
+  - macro_name: FTW_PHYS
+    macro_header: ftw-macros.h
+  - macro_name: FTW_MOUNT
+    macro_header: ftw-macros.h
+  - macro_name: FTW_CHDIR
+    macro_header: ftw-macros.h
+  - macro_name: FTW_DEPTH
+    macro_header: ftw-macros.h
+  - macro_name: FTW_ACTIONRETVAL
+    standards:
+      - gnu
+    macro_header: ftw-macros.h
+  - macro_name: FTW_CONTINUE
+    standards:
+      - gnu
+    macro_header: ftw-macros.h
+  - macro_name: FTW_STOP
+    standards:
+      - gnu
+    macro_header: ftw-macros.h
+  - macro_name: FTW_SKIP_SUBTREE
+    standards:
+      - gnu
+    macro_header: ftw-macros.h
+  - macro_name: FTW_SKIP_SIBLINGS
+    standards:
+      - gnu
+    macro_header: ftw-macros.h
+types:
+  - type_name: struct_FTW
+enums: []
+objects: []
+functions:
+  - name: nftw
+    standards:
+      - posix
+    return_type: int
+    arguments:
+      - type: const char *
+      - type: int (*)(const char *, const struct stat *, int, struct FTW *)
+      - type: int
+      - type: int
diff --git a/libc/include/llvm-libc-macros/CMakeLists.txt b/libc/include/llvm-libc-macros/CMakeLists.txt
index a71a370dd59ac3..c499f34e7d55fb 100644
--- a/libc/include/llvm-libc-macros/CMakeLists.txt
+++ b/libc/include/llvm-libc-macros/CMakeLists.txt
@@ -129,6 +129,12 @@ add_macro_header(
     fnmatch-macros.h
 )
 
+add_macro_header(
+  ftw_macros
+  HDR
+    ftw-macros.h
+)
+
 add_macro_header(
   glob_macros
   HDR
diff --git a/libc/include/llvm-libc-macros/ftw-macros.h b/libc/include/llvm-libc-macros/ftw-macros.h
new file mode 100644
index 00000000000000..b4c468fd75dddc
--- /dev/null
+++ b/libc/include/llvm-libc-macros/ftw-macros.h
@@ -0,0 +1,39 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Definition of macros from ftw.h.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_MACROS_FTW_MACROS_H
+#define LLVM_LIBC_MACROS_FTW_MACROS_H
+
+// Values for the typeflag argument to the callback function.
+#define FTW_F 0   // Non-directory file.
+#define FTW_D 1   // Directory.
+#define FTW_DNR 2 // Directory without read permission.
+#define FTW_NS 3  // Unknown type; stat() failed.
+#define FTW_SL 4  // Symbolic link.
+#define FTW_DP 5  // Directory with subdirectories visited.
+#define FTW_SLN 6 // Symbolic link naming non-existing file.
+
+// Flags for the flags argument to nftw().
+#define FTW_PHYS 1          // Physical walk, does not follow symbolic links.
+#define FTW_MOUNT 2         // The walk does not cross a mount point.
+#define FTW_CHDIR 4         // Change to each directory before processing.
+#define FTW_DEPTH 8         // All subdirectories visited before the directory.
+#define FTW_ACTIONRETVAL 16 // Use FTW_* action return values (GNU extension).
+
+// Return values from callback functions (when FTW_ACTIONRETVAL is set).
+#define FTW_CONTINUE 0      // Continue with next sibling.
+#define FTW_STOP 1          // Return from nftw with FTW_STOP.
+#define FTW_SKIP_SUBTREE 2  // Do not walk through subtree (FTW_D only).
+#define FTW_SKIP_SIBLINGS 3 // Skip siblings, continue with parent.
+
+#endif // LLVM_LIBC_MACROS_FTW_MACROS_H
diff --git a/libc/include/llvm-libc-types/CMakeLists.txt b/libc/include/llvm-libc-types/CMakeLists.txt
index 485a93d9959f05..df8be6b7218b9c 100644
--- a/libc/include/llvm-libc-types/CMakeLists.txt
+++ b/libc/include/llvm-libc-types/CMakeLists.txt
@@ -189,6 +189,7 @@ add_header(dl_info HDR Dl_info.h)
 add_header(struct_f_owner_ex HDR struct_f_owner_ex.h DEPENDS .pid_t)
 add_header(struct_flock HDR struct_flock.h DEPENDS .off_t .pid_t)
 add_header(struct_flock64 HDR struct_flock64.h DEPENDS .off64_t .pid_t)
+add_header(struct_FTW HDR struct_FTW.h)
 add_header(
   struct_ipc_perm
   HDR struct_ipc_perm.h
diff --git a/libc/include/llvm-libc-types/struct_FTW.h b/libc/include/llvm-libc-types/struct_FTW.h
new file mode 100644
index 00000000000000..46a8d5252322e4
--- /dev/null
+++ b/libc/include/llvm-libc-types/struct_FTW.h
@@ -0,0 +1,22 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Definition of struct FTW.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_TYPES_STRUCT_FTW_H
+#define LLVM_LIBC_TYPES_STRUCT_FTW_H
+
+struct FTW {
+  int base;  // Offset of the filename in the pathname.
+  int level; // Depth of the file in the tree.
+};
+
+#endif // LLVM_LIBC_TYPES_STRUCT_FTW_H
diff --git a/libc/src/CMakeLists.txt b/libc/src/CMakeLists.txt
index e05bb014d20d7b..4515593b7c7369 100644
--- a/libc/src/CMakeLists.txt
+++ b/libc/src/CMakeLists.txt
@@ -31,6 +31,7 @@ if(${LIBC_TARGET_OS} STREQUAL "linux")
   add_subdirectory(dirent)
   add_subdirectory(err)
   add_subdirectory(fcntl)
+  add_subdirectory(ftw)
   add_subdirectory(grp)
   add_subdirectory(poll)
   add_subdirectory(pthread)
diff --git a/libc/src/ftw/CMakeLists.txt b/libc/src/ftw/CMakeLists.txt
new file mode 100644
index 00000000000000..e610ba27fbe336
--- /dev/null
+++ b/libc/src/ftw/CMakeLists.txt
@@ -0,0 +1,10 @@
+if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
+  add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${LIBC_TARGET_OS})
+endif()
+
+add_entrypoint_object(
+  nftw
+  ALIAS
+  DEPENDS
+    .${LIBC_TARGET_OS}.nftw
+)
diff --git a/libc/src/ftw/linux/CMakeLists.txt b/libc/src/ftw/linux/CMakeLists.txt
new file mode 100644
index 00000000000000..db04530838df76
--- /dev/null
+++ b/libc/src/ftw/linux/CMakeLists.txt
@@ -0,0 +1,37 @@
+add_entrypoint_object(
+  nftw
+  SRCS
+    nftw.cpp
+  HDRS
+    ../nftw.h
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.fcntl_macros
+    libc.hdr.ftw_macros
+    libc.hdr.sys_stat_macros
+    libc.hdr.types.dev_t
+    libc.hdr.types.ino_t
+    libc.hdr.types.off_t
+    libc.hdr.types.struct_FTW
+    libc.hdr.types.struct_dirent
+    libc.hdr.types.struct_stat
+    libc.hdr.unistd_macros
+    libc.src.__support.CPP.limits
+    libc.src.__support.CPP.new
+    libc.src.__support.CPP.string_view
+    libc.src.__support.File.dir
+    libc.src.__support.File.platform_dir
+    libc.src.__support.OSUtil.linux.stat.stat_via_statx
+    libc.src.__support.OSUtil.linux.syscall_wrappers.chdir
+    libc.src.__support.OSUtil.linux.syscall_wrappers.close
+    libc.src.__support.OSUtil.linux.syscall_wrappers.fchdir
+    libc.src.__support.OSUtil.linux.syscall_wrappers.lseek
+    libc.src.__support.OSUtil.linux.syscall_wrappers.open
+    libc.src.__support.OSUtil.linux.syscall_wrappers.openat
+    libc.src.__support.error_or
+    libc.src.__support.libc_errno
+    libc.src.__support.macros.null_check
+    libc.src.__support.macros.optimization
+    libc.src.errno.errno
+    libc.src.string.memory_utils.inline_memcpy
+)
diff --git a/libc/src/ftw/linux/nftw.cpp b/libc/src/ftw/linux/nftw.cpp
new file mode 100644
index 00000000000000..68b35cd5ba57f0
--- /dev/null
+++ b/libc/src/ftw/linux/nftw.cpp
@@ -0,0 +1,772 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Linux implementation of the POSIX nftw function.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/ftw/nftw.h"
+
+#include "hdr/errno_macros.h"
+#include "hdr/fcntl_macros.h"
+#include "hdr/ftw_macros.h"
+#include "hdr/sys_stat_macros.h"
+#include "hdr/types/dev_t.h"
+#include "hdr/types/ino_t.h"
+#include "hdr/types/off_t.h"
+#include "hdr/types/struct_FTW.h"
+#include "hdr/types/struct_dirent.h"
+#include "hdr/types/struct_stat.h"
+#include "hdr/unistd_macros.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/File/dir.h"
+#include "src/__support/OSUtil/linux/stat/stat_via_statx.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/chdir.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/close.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/fchdir.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/lseek.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/open.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/openat.h"
+#include "src/__support/alloc-checker.h"
+#include "src/__support/common.h"
+#include "src/__support/error_or.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+#include "src/__support/macros/optimization.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace {
+
+using NftwCallback = int (*)(const char *, const struct stat *, int,
+                             struct FTW *);
+
+constexpr size_t INITIAL_PATH_CAPACITY = 256;
+constexpr size_t INITIAL_FRAME_CAPACITY = 16;
+constexpr size_t INITIAL_VISITED_CAPACITY = 32;
+
+// POSIX allows PATH_MAX to be omitted when pathname limits are indeterminate,
+// and relative *at / FTW_CHDIR traversals on Linux can exceed 4096 bytes.
+// Cap the dynamic path buffer at INT_MAX so offsets always fit in struct FTW's
+// int base field.
+constexpr size_t MAX_PATH_BUF_CAPACITY =
+    static_cast<size_t>(cpp::numeric_limits<int>::max());
+
+constexpr int VALID_FLAGS =
+    FTW_PHYS | FTW_MOUNT | FTW_CHDIR | FTW_DEPTH | FTW_ACTIONRETVAL;
+
+template <typename T, size_t InitialCap> struct CheckedBuffer {
+  T *data = nullptr;
+  size_t size = 0;
+  size_t capacity = 0;
+
+  CheckedBuffer() = default;
+  CheckedBuffer(const CheckedBuffer &) = delete;
+  CheckedBuffer &operator=(const CheckedBuffer &) = delete;
+  LIBC_INLINE ~CheckedBuffer() noexcept { delete[] data; }
+
+  bool reserve(size_t required,
+               size_t max_cap = cpp::numeric_limits<size_t>::max() /
+                                sizeof(T)) {
+    if (required <= capacity)
+      return true;
+    if (LIBC_UNLIKELY(required > max_cap))
+      return false;
+    size_t new_cap = capacity == 0
+                         ? InitialCap
+                         : (capacity > max_cap / 2 ? max_cap : capacity * 2);
+    if (new_cap < required)
+      new_cap = required;
+    AllocChecker ac;
+    T *new_data = new (ac) T[new_cap];
+    if (LIBC_UNLIKELY(!ac))
+      return false;
+    if (size > 0)
+      inline_memcpy(new_data, data, size * sizeof(T));
+    delete[] data;
+    data = new_data;
+    capacity = new_cap;
+    return true;
+  }
+};
+
+struct DirId {
+  dev_t dev;
+  ino_t ino;
+
+  LIBC_INLINE bool operator==(const DirId &other) const {
+    return dev == other.dev && ino == other.ino;
+  }
+};
+
+struct VisitedDirs {
+  CheckedBuffer<DirId, INITIAL_VISITED_CAPACITY> entries;
+
+  bool contains(DirId id) const {
+    for (size_t i = 0; i < entries.size; ++i)
+      if (entries.data[i] == id)
+        return true;
+    return false;
+  }
+
+  bool insert(DirId id) {
+    if (LIBC_UNLIKELY(!entries.reserve(entries.size + 1)))
+      return false;
+    entries.data[entries.size++] = id;
+    return true;
+  }
+};
+
+struct PathBuffer {
+  CheckedBuffer<char, INITIAL_PATH_CAPACITY> buf;
+
+  LIBC_INLINE char *c_str() { return buf.data; }
+  LIBC_INLINE size_t len() const { return buf.size; }
+
+  bool init(cpp::string_view sv) {
+    while (sv.size() > 1 && sv.back() == '/')
+      sv.remove_suffix(1);
+    if (LIBC_UNLIKELY(sv.size() >= MAX_PATH_BUF_CAPACITY ||
+                      !buf.reserve(sv.size() + 1, MAX_PATH_BUF_CAPACITY)))
+      return false;
+    inline_memcpy(buf.data, sv.data(), sv.size());
+    buf.size = sv.size();
+    buf.data[buf.size] = '\0';
+    return true;
+  }
+
+  bool push_child(cpp::string_view child_name) {
+    bool need_slash = (buf.size > 0 && buf.data[buf.size - 1] != '/');
+    size_t slash_len = need_slash ? 1 : 0;
+    if (LIBC_UNLIKELY(child_name.size() >=
+                      MAX_PATH_BUF_CAPACITY - buf.size - slash_len))
+      return false;
+    size_t add_len = slash_len + child_name.size();
+    if (LIBC_UNLIKELY(
+            !buf.reserve(buf.size + add_len + 1, MAX_PATH_BUF_CAPACITY)))
+      return false;
+    if (need_slash)
+      buf.data[buf.size++] = '/';
+    inline_memcpy(buf.data + buf.size, child_name.data(), child_name.size());
+    buf.size += child_name.size();
+    buf.data[buf.size] = '\0';
+    return true;
+  }
+
+  void pop_to(size_t prev_len) {
+    buf.size = prev_len;
+    buf.data[prev_len] = '\0';
+  }
+};
+
+struct ScopedDir {
+  Dir *dir = nullptr;
+  explicit ScopedDir(Dir *d) : dir(d) {}
+  ScopedDir(const ScopedDir &) = delete;
+  ScopedDir &operator=(const ScopedDir &) = delete;
+  LIBC_INLINE ~ScopedDir() noexcept {
+    if (dir != nullptr)
+      static_cast<void>(dir->close());
+  }
+  LIBC_INLINE Dir *operator->() const { return dir; }
+  LIBC_INLINE Dir *release() {
+    Dir *d = dir;
+    dir = nullptr;
+    return d;
+  }
+  int close() {
+    if (dir == nullptr)
+      return 0;
+    Dir *d = dir;
+    dir = nullptr;
+    return d->close();
+  }
+};
+
+struct DirFrame {
+  Dir *dir;
+  off_t resume_offset;
+  bool has_resume_offset;
+  DirId id;
+  size_t path_len;
+  int base;
+  int level;
+  struct stat stat_buf;
+};
+
+struct FrameStack {
+  CheckedBuffer<DirFrame, INITIAL_FRAME_CAPACITY> frames;
+  int open_dirs = 0;
+
+  FrameStack() = default;
+  FrameStack(const FrameStack &) = delete;
+  FrameStack &operator=(const FrameStack &) = delete;
+
+  LIBC_INLINE ~FrameStack() noexcept {
+    for (size_t i = frames.size; i > 0; --i) {
+      if (frames.data[i - 1].dir != nullptr)
+        static_cast<void>(frames.data[i - 1].dir->close());
+    }
+  }
+
+  LIBC_INLINE bool empty() const { return frames.size == 0; }
+  LIBC_INLINE size_t size() const { return frames.size; }
+  LIBC_INLINE DirFrame &back() { return frames.data[frames.size - 1]; }
+  LIBC_INLINE DirFrame &operator[](size_t idx) { return frames.data[idx]; }
+
+  bool has_ancestor(DirId id) const {
+    for (size_t i = 0; i < frames.size; ++i)
+      if (frames.data[i].id == id)
+        return true;
+    return false;
+  }
+
+  bool push(const DirFrame &frame) {
+    if (LIBC_UNLIKELY(!frames.reserve(frames.size + 1)))
+      return false;
+    frames.data[frames.size++] = frame;
+    if (frame.dir != nullptr)
+      ++open_dirs;
+    return true;
+  }
+
+  ErrorOr<int> evict_oldest_open() {
+    for (size_t i = 0; i < frames.size; ++i) {
+      if (frames.data[i].dir != nullptr) {
+        int close_err = frames.data[i].dir->close();
+        if (close_err != 0)
+          return Error(close_err);
+        frames.data[i].dir = nullptr;
+        --open_dirs;
+        return 0;
+      }
+    }
+    return 0;
+  }
+
+  ErrorOr<int> close_and_pop() {
+    DirFrame &top = back();
+    if (top.dir != nullptr) {
+      int close_err = top.dir->close();
+      top.dir = nullptr;
+      --open_dirs;
+      if (close_err != 0) {
+        --frames.size;
+        return Error(close_err);
+      }
+    }
+    --frames.size;
+    return 0;
+  }
+};
+
+struct OriginCwd {
+  int fd = -1;
+  bool dirty = false;
+
+  OriginCwd() = default;
+  OriginCwd(const OriginCwd &) = delete;
+  OriginCwd &operator=(const OriginCwd &) = delete;
+
+  LIBC_INLINE ~OriginCwd() noexcept {
+    if (dirty && fd >= 0)
+      linux_syscalls::fchdir(fd);
+    if (fd >= 0)
+      linux_syscalls::close(fd);
+  }
+
+  LIBC_INLINE int root_dfd() const { return fd >= 0 ? fd : AT_FDCWD; }
+
+  ErrorOr<int> capture(int fd_limit, int &available_fds) {
+    ErrorOr<int> fd_or_err =
+        linux_syscalls::open(".", O_PATH | O_DIRECTORY | O_CLOEXEC, 0);
+    if (!fd_or_err.has_value())
+      return Error(fd_or_err.error());
+    fd = fd_or_err.value();
+    available_fds = (fd_limit > 1) ? (fd_limit - 1) : 1;
+    return 0;
+  }
+
+  ErrorOr<int> restore() {
+    if (fd < 0)
+      return 0;
+    ErrorOr<int> res = linux_syscalls::fchdir(fd);
+    if (res.has_value())
+      dirty = false;
+    return res;
+  }
+
+  ErrorOr<int> chdir_to_walk_path(const char *walk_path) {
+    if (walk_path[0] != '/') {
+      ErrorOr<int> res = restore();
+      if (!res.has_value())
+        return res;
+    }
+    ErrorOr<int> res = linux_syscalls::chdir(walk_path);
+    if (res.has_value())
+      dirty = true;
+    return res;
+  }
+};
+
+struct WalkContext {
+  const char *raw_root_path;
+  PathBuffer path_buf;
+  NftwCallback fn;
+  int flags;
+  int available_fds;
+  dev_t start_device = 0;
+  OriginCwd origin_cwd;
+  VisitedDirs visited_dirs;
+
+  ErrorOr<int> chdir_to_parent_of(int base) {
+    if (base == 0)
+      return origin_cwd.restore();
+    if (base == 1) {
+      ErrorOr<int> res = linux_syscalls::chdir("/");
+      if (res.has_value())
+        origin_cwd.dirty = true;
+      return res;
+    }
+    char saved = path_buf.c_str()[base - 1];
+    path_buf.c_str()[base - 1] = '\0';
+    ErrorOr<int> res = origin_cwd.chdir_to_walk_path(path_buf.c_str());
+    path_buf.c_str()[base - 1] = saved;
+    return res;
+  }
+};
+
+enum class WalkAction { Continue, SkipSubtree, SkipSiblings, Stop };
+
+struct CallbackOutcome {
+  WalkAction action;
+  int stop_value;
+};
+
+CallbackOutcome evaluate_callback(int flags, int res) {
+  if (!(flags & FTW_ACTIONRETVAL))
+    return res == 0 ? CallbackOutcome{WalkAction::Continue, 0}
+                    : CallbackOutcome{WalkAction::Stop, res};
+  switch (res) {
+  case FTW_CONTINUE:
+    return {WalkAction::Continue, 0};
+  case FTW_SKIP_SUBTREE:
+    return {WalkAction::SkipSubtree, 0};
+  case FTW_SKIP_SIBLINGS:
+    return {WalkAction::SkipSiblings, 0};
+  default:
+    return {WalkAction::Stop, res};
+  }
+}
+
+ErrorOr<int> classify_entry(WalkContext &ctx, int lookup_dfd,
+                            const char *lookup_path, int level,
+                            struct stat &stat_buf) {
+  int stat_flags = (ctx.flags & FTW_PHYS) ? AT_SYMLINK_NOFOLLOW : 0;
+  ErrorOr<void> stat_res =
+      internal::stat_via_statx(lookup_dfd, lookup_path, stat_flags, &stat_buf);
+  if (stat_res.has_value()) {
+    if (S_ISDIR(stat_buf.st_mode))
+      return FTW_D;
+    if (S_ISLNK(stat_buf.st_mode))
+      return FTW_SL;
+    return FTW_F;
+  }
+
+  int err = stat_res.error();
+  if (!(ctx.flags & FTW_PHYS) && (err == ENOENT || err == ENOTDIR)) {
+    ErrorOr<void> lstat_res = internal::stat_via_statx(
+        lookup_dfd, lookup_path, AT_SYMLINK_NOFOLLOW, &stat_buf);
+    if (lstat_res.has_value() && S_ISLNK(stat_buf.st_mode))
+      return FTW_SLN;
+    if (level > 0 && err == ENOENT)
+      return FTW_NS;
+    return Error(err);
+  }
+  if (level > 0 && (err == EACCES || err == ENOENT))
+    return FTW_NS;
+  return Error(err);
+}
+
+struct OpenDirResult {
+  Dir *dir;
+  int report_flag;
+};
+
+ErrorOr<OpenDirResult> open_verified_dir(int lookup_dfd,
+                                         const char *lookup_path, int flags,
+                                         int level, DirId expected_id) {
+  int open_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
+  if (flags & FTW_PHYS)
+    open_flags |= O_NOFOLLOW;
+
+  ErrorOr<int> fd_or_err =
+      linux_syscalls::openat(lookup_dfd, lookup_path, open_flags, 0);
+  if (!fd_or_err.has_value()) {
+    int err = fd_or_err.error();
+    if (level > 0 &&
+        (err == EACCES || err == ENOENT || err == ENOTDIR || err == ELOOP))
+      return OpenDirResult{nullptr, (err == EACCES) ? FTW_DNR : FTW_NS};
+    return Error(err);
+  }
+  int fd = fd_or_err.value();
+
+  // Verify the opened directory matches expected_id to prevent TOCTOU
+  // directory-replacement races before reading or fchdir'ing into it.
+  struct stat opened_stat = {};
+  ErrorOr<void> verify_res =
+      internal::stat_via_statx(fd, "", AT_EMPTY_PATH, &opened_stat);
+  if (!verify_res.has_value() ||
+      !(DirId{opened_stat.st_dev, opened_stat.st_ino} == expected_id)) {
+    linux_syscalls::close(fd);
+    if (level == 0)
+      return Error(verify_res.has_value() ? ENOENT : verify_res.error());
+    return OpenDirResult{nullptr, FTW_NS};
+  }
+
+  ErrorOr<Dir *> dir_or_err = Dir::fdopen(fd);
+  if (!dir_or_err.has_value()) {
+    linux_syscalls::close(fd);
+    return Error(dir_or_err.error());
+  }
+  return OpenDirResult{dir_or_err.value(), 0};
+}
+
+ErrorOr<int> reopen_frame_dir(WalkContext &ctx, FrameStack &frames,
+                              size_t frame_idx) {
+  if (frames.open_dirs >= ctx.available_fds) {
+    ErrorOr<int> evict_res = frames.evict_oldest_open();
+    if (!evict_res.has_value())
+      return evict_res;
+  }
+
+  DirFrame &frame = frames[frame_idx];
+  int open_flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC;
+  if (ctx.flags & FTW_PHYS)
+    open_flags |= O_NOFOLLOW;
+
+  ErrorOr<int> fd_or_err(0);
+  if (frame_idx == 0) {
+    fd_or_err = linux_syscalls::openat(ctx.origin_cwd.root_dfd(),
+                                       ctx.raw_root_path, open_flags, 0);
+  } else {
+    char saved = ctx.path_buf.c_str()[frame.path_len];
+    ctx.path_buf.c_str()[frame.path_len] = '\0';
+    fd_or_err = linux_syscalls::openat(ctx.origin_cwd.root_dfd(),
+                                       ctx.path_buf.c_str(), open_flags, 0);
+    ctx.path_buf.c_str()[frame.path_len] = saved;
+  }
+  if (!fd_or_err.has_value())
+    return Error(fd_or_err.error());
+  int fd = fd_or_err.value();
+
+  struct stat reopened_stat = {};
+  ErrorOr<void> verify_res =
+      internal::stat_via_statx(fd, "", AT_EMPTY_PATH, &reopened_stat);
+  if (!verify_res.has_value() ||
+      !(DirId{reopened_stat.st_dev, reopened_stat.st_ino} == frame.id)) {
+    linux_syscalls::close(fd);
+    return Error(verify_res.has_value() ? ENOENT : verify_res.error());
+  }
+
+  if (frame.has_resume_offset) {
+    ErrorOr<off_t> seek_res =
+        linux_syscalls::lseek(fd, frame.resume_offset, SEEK_SET);
+    if (!seek_res.has_value()) {
+      linux_syscalls::close(fd);
+      return Error(seek_res.error());
+    }
+  }
+
+  ErrorOr<Dir *> dir_or_err = Dir::fdopen(fd);
+  if (!dir_or_err.has_value()) {
+    linux_syscalls::close(fd);
+    return Error(dir_or_err.error());
+  }
+  frame.dir = dir_or_err.value();
+  ++frames.open_dirs;
+  return 0;
+}
+
+ErrorOr<CallbackOutcome> visit_entry(WalkContext &ctx, FrameStack &frames,
+                                     int base, int level) {
+  struct FTW ftw_buf = {base, level};
+
+  // Preserve the caller's raw dir_path at level 0 so trailing slashes on files
+  // or symlinks are resolved by the kernel according to POSIX rules; at
+  // level > 0, parent's Dir is guaranteed open here, so resolve the child's
+  // single-component name directly against parent_fd.
+  int lookup_dfd = (level == 0) ? AT_FDCWD : frames.back().dir->getfd();
+  const char *lookup_path =
+      (level == 0) ? ctx.raw_root_path : (ctx.path_buf.c_str() + base);
+
+  struct stat stat_buf = {};
+  ErrorOr<int> type_or_err =
+      classify_entry(ctx, lookup_dfd, lookup_path, level, stat_buf);
+  if (!type_or_err.has_value())
+    return Error(type_or_err.error());
+  int type_flag = type_or_err.value();
+
+  if (type_flag != FTW_NS) {
+    if (level == 0)
+      ctx.start_device = stat_buf.st_dev;
+    else if ((ctx.flags & FTW_MOUNT) && stat_buf.st_dev != ctx.start_device)
+      return CallbackOutcome{WalkAction::Continue, 0};
+  }
+
+  if (type_flag != FTW_D) {
+    if ((ctx.flags & FTW_CHDIR) && level == 0 && base > 0) {
+      ErrorOr<int> cwd_res = ctx.chdir_to_parent_of(base);
+      if (!cwd_res.has_value())
+        return Error(cwd_res.error());
+    }
+    return evaluate_callback(ctx.flags, ctx.fn(ctx.path_buf.c_str(), &stat_buf,
+                                               type_flag, &ftw_buf));
+  }
+
+  // Always check active ancestors (preventing both symlink and bind-mount loops
+  // even under FTW_PHYS), and in logical mode skip any directory already
+  // visited so no directory is reported twice per POSIX.1-2024.
+  DirId dir_id{stat_buf.st_dev, stat_buf.st_ino};
+  if (frames.has_ancestor(dir_id))
+    return CallbackOutcome{WalkAction::Continue, 0};
+  if (!(ctx.flags & FTW_PHYS)) {
+    if (ctx.visited_dirs.contains(dir_id))
+      return CallbackOutcome{WalkAction::Continue, 0};
+    if (LIBC_UNLIKELY(!ctx.visited_dirs.insert(dir_id)))
+      return Error(ENOMEM);
+  }
+  if (LIBC_UNLIKELY(level == cpp::numeric_limits<int>::max()))
+    return Error(EOVERFLOW);
+
+  if (frames.open_dirs >= ctx.available_fds) {
+    ErrorOr<int> evict_res = frames.evict_oldest_open();
+    if (!evict_res.has_value())
+      return Error(evict_res.error());
+  }
+
+  int open_dfd = AT_FDCWD;
+  const char *open_path = ctx.raw_root_path;
+  if (level > 0) {
+    if (frames.back().dir != nullptr) {
+      open_dfd = frames.back().dir->getfd();
+      open_path = ctx.path_buf.c_str() + base;
+    } else if (ctx.flags & FTW_CHDIR) {
+      open_path = ctx.path_buf.c_str() + base;
+    } else {
+      open_path = ctx.path_buf.c_str();
+    }
+  }
+
+  ErrorOr<OpenDirResult> open_res =
+      open_verified_dir(open_dfd, open_path, ctx.flags, level, dir_id);
+  if (!open_res.has_value())
+    return Error(open_res.error());
+  if (open_res->dir == nullptr) {
+    return evaluate_callback(ctx.flags,
+                             ctx.fn(ctx.path_buf.c_str(), &stat_buf,
+                                    open_res->report_flag, &ftw_buf));
+  }
+  ScopedDir open_dir(open_res->dir);
+
+  if (!(ctx.flags & FTW_DEPTH)) {
+    if ((ctx.flags & FTW_CHDIR) && level == 0 && base > 0) {
+      ErrorOr<int> cwd_res = ctx.chdir_to_parent_of(base);
+      if (!cwd_res.has_value())
+        return Error(cwd_res.error());
+    }
+    CallbackOutcome pre_outcome = evaluate_callback(
+        ctx.flags, ctx.fn(ctx.path_buf.c_str(), &stat_buf, FTW_D, &ftw_buf));
+    if (pre_outcome.action != WalkAction::Continue) {
+      int close_err = open_dir.close();
+      if (close_err != 0 && pre_outcome.action != WalkAction::Stop)
+        return Error(close_err);
+      return pre_outcome;
+    }
+  }
+
+  if (ctx.flags & FTW_CHDIR) {
+    ErrorOr<int> chdir_res = linux_syscalls::fchdir(open_dir->getfd());
+    if (!chdir_res.has_value())
+      return Error(chdir_res.error());
+    ctx.origin_cwd.dirty = true;
+  }
+
+  DirFrame frame{open_dir.release(), 0,    false, dir_id,
+                 ctx.path_buf.len(), base, level, stat_buf};
+  if (LIBC_UNLIKELY(!frames.push(frame))) {
+    static_cast<void>(frame.dir->close());
+    return Error(ENOMEM);
+  }
+  return CallbackOutcome{WalkAction::Continue, 0};
+}
+
+ErrorOr<CallbackOutcome> finish_directory(WalkContext &ctx,
+                                          FrameStack &frames) {
+  int base = frames.back().base;
+  int level = frames.back().level;
+  struct stat stat_buf = frames.back().stat_buf;
+
+  ErrorOr<int> pop_res = frames.close_and_pop();
+  if (!pop_res.has_value())
+    return Error(pop_res.error());
+
+  if (ctx.flags & FTW_CHDIR) {
+    if (!frames.empty()) {
+      if (frames.back().dir == nullptr) {
+        ErrorOr<int> reopen_res =
+            reopen_frame_dir(ctx, frames, frames.size() - 1);
+        if (!reopen_res.has_value())
+          return Error(reopen_res.error());
+      }
+      ErrorOr<int> chdir_res =
+          linux_syscalls::fchdir(frames.back().dir->getfd());
+      if (!chdir_res.has_value())
+        return Error(chdir_res.error());
+    } else if (ctx.flags & FTW_DEPTH) {
+      ErrorOr<int> cwd_res = ctx.chdir_to_parent_of(base);
+      if (!cwd_res.has_value())
+        return Error(cwd_res.error());
+    }
+  }
+
+  CallbackOutcome outcome{WalkAction::Continue, 0};
+  if (ctx.flags & FTW_DEPTH) {
+    struct FTW ftw_buf = {base, level};
+    outcome = evaluate_callback(
+        ctx.flags, ctx.fn(ctx.path_buf.c_str(), &stat_buf, FTW_DP, &ftw_buf));
+  }
+
+  if (!frames.empty())
+    ctx.path_buf.pop_to(frames.back().path_len);
+  return outcome;
+}
+
+ErrorOr<int> walk_tree_iterative(WalkContext &ctx, int root_base) {
+  FrameStack frames;
+  ErrorOr<CallbackOutcome> root_res = visit_entry(ctx, frames, root_base, 0);
+  if (!root_res.has_value())
+    return Error(root_res.error());
+  if (root_res->action == WalkAction::Stop)
+    return root_res->stop_value;
+
+  while (!frames.empty()) {
+    if (frames.back().dir == nullptr) {
+      ErrorOr<int> reopen_res =
+          reopen_frame_dir(ctx, frames, frames.size() - 1);
+      if (!reopen_res.has_value())
+        return reopen_res;
+    }
+
+    DirFrame &top = frames.back();
+    ErrorOr<struct dirent *> entry_or_err = top.dir->read();
+    if (!entry_or_err.has_value())
+      return Error(entry_or_err.error());
+    struct dirent *entry = entry_or_err.value();
+
+    bool finish_cur_dir = (entry == nullptr);
+    if (!finish_cur_dir) {
+      top.resume_offset = entry->d_off;
+      top.has_resume_offset = true;
+      cpp::string_view name(entry->d_name);
+      if (name == "." || name == "..")
+        continue;
+
+      size_t parent_len = top.path_len;
+      size_t depth_before = frames.size();
+      int child_level = top.level + 1;
+      if (LIBC_UNLIKELY(!ctx.path_buf.push_child(name)))
+        return Error(ENOMEM);
+      int child_base = static_cast<int>(ctx.path_buf.len() - name.size());
+
+      ErrorOr<CallbackOutcome> child_res =
+          visit_entry(ctx, frames, child_base, child_level);
+      if (!child_res.has_value())
+        return Error(child_res.error());
+
+      if (frames.size() == depth_before)
+        ctx.path_buf.pop_to(parent_len);
+
+      if (child_res->action == WalkAction::Stop)
+        return child_res->stop_value;
+      if (child_res->action == WalkAction::SkipSiblings)
+        finish_cur_dir = true;
+    }
+
+    if (finish_cur_dir) {
+      while (true) {
+        ErrorOr<CallbackOutcome> fin_res = finish_directory(ctx, frames);
+        if (!fin_res.has_value())
+          return Error(fin_res.error());
+        if (fin_res->action == WalkAction::Stop)
+          return fin_res->stop_value;
+        if (fin_res->action == WalkAction::SkipSiblings && !frames.empty())
+          continue;
+        break;
+      }
+    }
+  }
+
+  return 0;
+}
+
+ErrorOr<int> run_nftw(const char *dir_path, NftwCallback fn, int fd_limit,
+                      int flags) {
+  if (fd_limit <= 0 || (flags & ~VALID_FLAGS) != 0)
+    return Error(EINVAL);
+  if (dir_path[0] == '\0')
+    return Error(ENOENT);
+
+  WalkContext ctx{dir_path, {}, fn, flags, fd_limit, 0, {}, {}};
+  if (LIBC_UNLIKELY(!ctx.path_buf.init(dir_path)))
+    return Error(ENOMEM);
+
+  cpp::string_view root_view(ctx.path_buf.c_str(), ctx.path_buf.len());
+  size_t slash_pos = root_view.find_last_of('/');
+  int root_base = 0;
+  if (slash_pos != cpp::string_view::npos && ctx.path_buf.len() > 1)
+    root_base = static_cast<int>(slash_pos + 1);
+
+  if (flags & FTW_CHDIR) {
+    ErrorOr<int> cwd_res = ctx.origin_cwd.capture(fd_limit, ctx.available_fds);
+    if (!cwd_res.has_value())
+      return Error(cwd_res.error());
+  }
+
+  ErrorOr<int> walk_res = walk_tree_iterative(ctx, root_base);
+  if ((flags & FTW_CHDIR) && ctx.origin_cwd.dirty) {
+    ErrorOr<int> restore_res = ctx.origin_cwd.restore();
+    if (!restore_res.has_value() && walk_res.has_value())
+      return Error(restore_res.error());
+  }
+  return walk_res;
+}
+
+} // namespace
+
+LLVM_LIBC_FUNCTION(int, nftw,
+                   (const char *dir_path,
+                    int (*fn)(const char *, const struct stat *, int,
+                              struct FTW *),
+                    int fd_limit, int flags)) {
+  LIBC_CRASH_ON_NULLPTR(dir_path);
+  LIBC_CRASH_ON_NULLPTR(fn);
+  ErrorOr<int> result = run_nftw(dir_path, fn, fd_limit, flags);
+  if (!result.has_value()) {
+    libc_errno = result.error();
+    return -1;
+  }
+  return result.value();
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/ftw/nftw.h b/libc/src/ftw/nftw.h
new file mode 100644
index 00000000000000..3934919e1ef62e
--- /dev/null
+++ b/libc/src/ftw/nftw.h
@@ -0,0 +1,29 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Implementation header for nftw.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_FTW_NFTW_H
+#define LLVM_LIBC_SRC_FTW_NFTW_H
+
+#include "hdr/types/struct_FTW.h"
+#include "hdr/types/struct_stat.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+int nftw(const char *dir_path,
+         int (*fn)(const char *, const struct stat *, int, struct FTW *),
+         int fd_limit, int flags);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_FTW_NFTW_H
diff --git a/libc/test/src/CMakeLists.txt b/libc/test/src/CMakeLists.txt
index 33f94b961188ce..28e673a259d6b4 100644
--- a/libc/test/src/CMakeLists.txt
+++ b/libc/test/src/CMakeLists.txt
@@ -60,6 +60,7 @@ add_subdirectory(spawn)
 add_subdirectory(pwd)
 
 if(${LIBC_TARGET_OS} STREQUAL "linux")
+  add_subdirectory(ftw)
   add_subdirectory(pthread)
   add_subdirectory(semaphore)
 endif()
diff --git a/libc/test/src/ftw/CMakeLists.txt b/libc/test/src/ftw/CMakeLists.txt
new file mode 100644
index 00000000000000..86af79b7c531c2
--- /dev/null
+++ b/libc/test/src/ftw/CMakeLists.txt
@@ -0,0 +1,33 @@
+add_libc_testsuite(libc-ftw-tests)
+
+add_libc_test(
+  nftw_test
+  SUITE
+    libc-ftw-tests
+  SRCS
+    nftw_test.cpp
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.fcntl_macros
+    libc.hdr.ftw_macros
+    libc.hdr.sys_stat_macros
+    libc.hdr.types.mode_t
+    libc.hdr.types.struct_FTW
+    libc.hdr.types.struct_stat
+    libc.src.__support.CPP.scope
+    libc.src.__support.CPP.string_view
+    libc.src.fcntl.open
+    libc.src.ftw.nftw
+    libc.src.string.memory_utils.inline_memcpy
+    libc.src.sys.stat.chmod
+    libc.src.sys.stat.mkdir
+    libc.src.unistd.chdir
+    libc.src.unistd.close
+    libc.src.unistd.getcwd
+    libc.src.unistd.geteuid
+    libc.src.unistd.rmdir
+    libc.src.unistd.symlink
+    libc.src.unistd.unlink
+    libc.test.UnitTest.ErrnoCheckingTest
+    libc.test.UnitTest.ErrnoSetterMatcher
+)
diff --git a/libc/test/src/ftw/nftw_test.cpp b/libc/test/src/ftw/nftw_test.cpp
new file mode 100644
index 00000000000000..07378f69f8ed9b
--- /dev/null
+++ b/libc/test/src/ftw/nftw_test.cpp
@@ -0,0 +1,709 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Unit tests for nftw.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/errno_macros.h"
+#include "hdr/fcntl_macros.h"
+#include "hdr/ftw_macros.h"
+#include "hdr/sys_stat_macros.h"
+#include "hdr/types/mode_t.h"
+#include "hdr/types/struct_FTW.h"
+#include "hdr/types/struct_stat.h"
+#include "src/__support/CPP/scope.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/libc_errno.h"
+#include "src/fcntl/open.h"
+#include "src/ftw/nftw.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+#include "src/sys/stat/chmod.h"
+#include "src/sys/stat/mkdir.h"
+#include "src/unistd/chdir.h"
+#include "src/unistd/close.h"
+#include "src/unistd/getcwd.h"
+#include "src/unistd/geteuid.h"
+#include "src/unistd/rmdir.h"
+#include "src/unistd/symlink.h"
+#include "src/unistd/unlink.h"
+#include "test/UnitTest/ErrnoCheckingTest.h"
+#include "test/UnitTest/ErrnoSetterMatcher.h"
+#include "test/UnitTest/Test.h"
+#include "test/UnitTest/TestLogger.h"
+
+using LIBC_NAMESPACE::cpp::string_view;
+using LIBC_NAMESPACE::testing::tlog;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
+
+namespace {
+
+struct Visit {
+  char path[256];
+  size_t path_len;
+  int typeflag;
+  int level;
+  int base;
+  mode_t fmt;
+};
+
+constexpr size_t MAX_VISITS = 64;
+Visit visits[MAX_VISITS];
+size_t visit_count = 0;
+
+int call_count = 0;
+int dir_count = 0;
+int dp_count = 0;
+int file_count = 0;
+int sl_count = 0;
+int sln_count = 0;
+int dnr_count = 0;
+int ns_count = 0;
+int max_level = -1;
+
+void reset_counts() {
+  visit_count = 0;
+  call_count = 0;
+  dir_count = 0;
+  dp_count = 0;
+  file_count = 0;
+  sl_count = 0;
+  sln_count = 0;
+  dnr_count = 0;
+  ns_count = 0;
+  max_level = -1;
+}
+
+int find_visit(string_view path) {
+  for (size_t i = 0; i < visit_count; ++i)
+    if (string_view(visits[i].path, visits[i].path_len) == path)
+      return static_cast<int>(i);
+  return -1;
+}
+
+int record_callback(const char *fpath, const struct stat *sb, int typeflag,
+                    struct FTW *ftwbuf) {
+  string_view full(fpath);
+  string_view base(fpath + ftwbuf->base);
+  EXPECT_GT(base.size(), size_t(0));
+  EXPECT_EQ(base.find_first_of('/'), string_view::npos);
+  if (ftwbuf->base > 0)
+    EXPECT_EQ(fpath[ftwbuf->base - 1], '/');
+  if (ftwbuf->base > 1)
+    EXPECT_NE(fpath[ftwbuf->base - 2], '/');
+
+  if (visit_count < MAX_VISITS && full.size() < sizeof(visits[0].path)) {
+    Visit &v = visits[visit_count++];
+    LIBC_NAMESPACE::inline_memcpy(v.path, full.data(), full.size());
+    v.path[full.size()] = '\0';
+    v.path_len = full.size();
+    v.typeflag = typeflag;
+    v.level = ftwbuf->level;
+    v.base = ftwbuf->base;
+    v.fmt = sb->st_mode & S_IFMT;
+  }
+
+  if (ftwbuf->level > max_level)
+    max_level = ftwbuf->level;
+
+  ++call_count;
+  if (typeflag == FTW_D) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFDIR));
+    ++dir_count;
+  } else if (typeflag == FTW_DP) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFDIR));
+    ++dp_count;
+  } else if (typeflag == FTW_F) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFREG));
+    ++file_count;
+  } else if (typeflag == FTW_SL) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFLNK));
+    ++sl_count;
+  } else if (typeflag == FTW_SLN) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFLNK));
+    ++sln_count;
+  } else if (typeflag == FTW_DNR) {
+    EXPECT_EQ(sb->st_mode & S_IFMT, static_cast<mode_t>(S_IFDIR));
+    ++dnr_count;
+  } else if (typeflag == FTW_NS) {
+    ++ns_count;
+  }
+  return 0;
+}
+
+int chdir_callback(const char *fpath, const struct stat *sb, int typeflag,
+                   struct FTW *ftwbuf) {
+  record_callback(fpath, sb, typeflag, ftwbuf);
+  if (typeflag != FTW_SL && typeflag != FTW_SLN && typeflag != FTW_NS) {
+    // When FTW_CHDIR is set, every entry (including level 0 when the root path
+    // contains a directory prefix) must resolve via its relative basename in
+    // the current working directory.
+    const char *rel_name = fpath + ftwbuf->base;
+    int fd = LIBC_NAMESPACE::open(rel_name, O_RDONLY);
+    EXPECT_GE(fd, 0);
+    if (fd >= 0)
+      EXPECT_EQ(LIBC_NAMESPACE::close(fd), 0);
+  }
+  return 0;
+}
+
+int unlink_sibling_cb(const char *fpath, const struct stat *sb, int typeflag,
+                      struct FTW *ftwbuf) {
+  (void)sb;
+  ++call_count;
+  if (typeflag == FTW_NS)
+    ++ns_count;
+  string_view base(fpath + ftwbuf->base);
+  if (typeflag == FTW_F && base == "vanish_a.txt")
+    LIBC_NAMESPACE::unlink("nftw_race_root/vanish_b.txt");
+  else if (typeflag == FTW_F && base == "vanish_b.txt")
+    LIBC_NAMESPACE::unlink("nftw_race_root/vanish_a.txt");
+  return 0;
+}
+
+int stop_42_cb(const char *fpath, const struct stat *sb, int typeflag,
+               struct FTW *ftwbuf) {
+  (void)fpath;
+  (void)sb;
+  (void)typeflag;
+  (void)ftwbuf;
+  ++call_count;
+  return 42;
+}
+
+int stop_neg_one_cb(const char *fpath, const struct stat *sb, int typeflag,
+                    struct FTW *ftwbuf) {
+  (void)fpath;
+  (void)sb;
+  (void)typeflag;
+  (void)ftwbuf;
+  ++call_count;
+  LIBC_NAMESPACE::libc_errno = EXDEV;
+  return -1;
+}
+
+int stop_at_level1_cb(const char *fpath, const struct stat *sb, int typeflag,
+                      struct FTW *ftwbuf) {
+  (void)fpath;
+  (void)sb;
+  (void)typeflag;
+  ++call_count;
+  if (ftwbuf->level == 1)
+    return 99;
+  return 0;
+}
+
+int skip_subtree_cb(const char *fpath, const struct stat *sb, int typeflag,
+                    struct FTW *ftwbuf) {
+  (void)sb;
+  (void)typeflag;
+  ++call_count;
+  if (string_view(fpath + ftwbuf->base) == "dir1")
+    return FTW_SKIP_SUBTREE;
+  return FTW_CONTINUE;
+}
+
+int skip_siblings_cb(const char *fpath, const struct stat *sb, int typeflag,
+                     struct FTW *ftwbuf) {
+  (void)fpath;
+  (void)sb;
+  (void)typeflag;
+  ++call_count;
+  if (ftwbuf->level == 1)
+    return FTW_SKIP_SIBLINGS;
+  return FTW_CONTINUE;
+}
+
+int stop_action_cb(const char *fpath, const struct stat *sb, int typeflag,
+                   struct FTW *ftwbuf) {
+  (void)fpath;
+  (void)sb;
+  (void)typeflag;
+  (void)ftwbuf;
+  ++call_count;
+  return FTW_STOP;
+}
+
+int create_empty_file(const char *path) {
+  int fd = LIBC_NAMESPACE::open(path, O_CREAT | O_WRONLY | O_TRUNC, 0644);
+  if (fd < 0)
+    return -1;
+  return LIBC_NAMESPACE::close(fd);
+}
+
+} // namespace
+
+class LlvmLibcNftwTest : public LIBC_NAMESPACE::testing::ErrnoCheckingTest {
+public:
+  void SetUp() override {
+    ErrnoCheckingTest::SetUp();
+    reset_counts();
+  }
+};
+
+TEST_F(LlvmLibcNftwTest, BasicAndSymlinkTraversal) {
+  constexpr const char *ROOT_REL = "nftw_basic_root";
+  constexpr const char *ROOT_SLASH_REL = "nftw_basic_root/";
+  constexpr const char *SUBDIR_REL = "nftw_basic_root/dir1";
+  constexpr const char *FILE1_REL = "nftw_basic_root/file1.txt";
+  constexpr const char *FILE2_REL = "nftw_basic_root/dir1/file2.txt";
+  constexpr const char *SYMLINK_REL = "nftw_basic_root/link_to_file1";
+  constexpr const char *BROKEN_REL = "nftw_basic_root/broken_link";
+  constexpr const char *CYCLE_REL = "nftw_basic_root/dir1/cycle_link";
+  constexpr const char *DUPDIR_REL = "nftw_basic_root/dup_dir1";
+
+  auto root = libc_make_test_file_path(ROOT_REL);
+  auto root_slash = libc_make_test_file_path(ROOT_SLASH_REL);
+  auto subdir = libc_make_test_file_path(SUBDIR_REL);
+  auto file1 = libc_make_test_file_path(FILE1_REL);
+  auto file2 = libc_make_test_file_path(FILE2_REL);
+  auto symlink_path = libc_make_test_file_path(SYMLINK_REL);
+  auto broken_path = libc_make_test_file_path(BROKEN_REL);
+  auto cycle_path = libc_make_test_file_path(CYCLE_REL);
+  auto dupdir_path = libc_make_test_file_path(DUPDIR_REL);
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::unlink(dupdir_path);
+    LIBC_NAMESPACE::unlink(cycle_path);
+    LIBC_NAMESPACE::unlink(broken_path);
+    LIBC_NAMESPACE::unlink(symlink_path);
+    LIBC_NAMESPACE::unlink(file2);
+    LIBC_NAMESPACE::unlink(file1);
+    LIBC_NAMESPACE::rmdir(subdir);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(subdir, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(file1), Succeeds(0));
+  ASSERT_THAT(create_empty_file(file2), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("file1.txt", symlink_path), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("nonexistent_target", broken_path),
+              Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("..", cycle_path), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("dir1", dupdir_path), Succeeds(0));
+
+  // POSIX.1-2024 FTW_PHYS: "If clear, nftw() shall follow links instead of
+  // reporting them, and shall not report the same file twice." Both cycle_link
+  // (pointing to ancestor root) and whichever of dir1 / dup_dir1 is visited
+  // second are omitted, leaving 6 unique visits.
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root_slash, record_callback, 10, 0),
+              Succeeds(0));
+  EXPECT_EQ(call_count, 6);
+  EXPECT_EQ(dir_count, 2);
+  EXPECT_EQ(file_count, 3);
+  EXPECT_EQ(sln_count, 1);
+  EXPECT_EQ(sl_count, 0);
+
+  int root_idx = find_visit(ROOT_REL);
+  int f1_idx = find_visit(FILE1_REL);
+  int broken_idx = find_visit(BROKEN_REL);
+  ASSERT_EQ(root_idx, 0);
+  EXPECT_EQ(visits[root_idx].typeflag, FTW_D);
+  EXPECT_EQ(visits[root_idx].level, 0);
+  ASSERT_GE(f1_idx, 0);
+  EXPECT_EQ(visits[f1_idx].typeflag, FTW_F);
+  EXPECT_EQ(visits[f1_idx].level, 1);
+  ASSERT_GE(broken_idx, 0);
+  EXPECT_EQ(visits[broken_idx].typeflag, FTW_SLN);
+  EXPECT_EQ(visits[broken_idx].level, 1);
+  EXPECT_EQ(find_visit(CYCLE_REL), -1);
+
+  // Logical post-order walk (FTW_DEPTH without FTW_PHYS): omits duplicate
+  // directories and reports directories after their descendants as FTW_DP.
+  reset_counts();
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, 10, FTW_DEPTH),
+              Succeeds(0));
+  EXPECT_EQ(call_count, 6);
+  EXPECT_EQ(dp_count, 2);
+  EXPECT_EQ(file_count, 3);
+  EXPECT_EQ(sln_count, 1);
+  EXPECT_EQ(find_visit(ROOT_REL), 5);
+}
+
+TEST_F(LlvmLibcNftwTest, ConstrainedFdLimitAndChdir) {
+  constexpr const char *ROOT_REL = "nftw_fdlimit_root";
+  constexpr const char *DIR1_REL = "nftw_fdlimit_root/dir1";
+  constexpr const char *DIR2_REL = "nftw_fdlimit_root/dir1/dir2";
+  constexpr const char *FILE3_REL = "nftw_fdlimit_root/dir1/dir2/file3.txt";
+  constexpr const char *DIRB_REL = "nftw_fdlimit_root/dir1/dirb";
+  constexpr const char *FILEB_REL = "nftw_fdlimit_root/dir1/dirb/fileb.txt";
+
+  auto root = libc_make_test_file_path(ROOT_REL);
+  auto dir1 = libc_make_test_file_path(DIR1_REL);
+  auto dir2 = libc_make_test_file_path(DIR2_REL);
+  auto file3 = libc_make_test_file_path(FILE3_REL);
+  auto dirb = libc_make_test_file_path(DIRB_REL);
+  auto fileb = libc_make_test_file_path(FILEB_REL);
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::unlink(fileb);
+    LIBC_NAMESPACE::rmdir(dirb);
+    LIBC_NAMESPACE::unlink(file3);
+    LIBC_NAMESPACE::rmdir(dir2);
+    LIBC_NAMESPACE::rmdir(dir1);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(dir1, 0755), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(dir2, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(file3), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(dirb, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(fileb), Succeeds(0));
+
+  char cwd_before[4096];
+  char cwd_after[4096];
+  ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_before, sizeof(cwd_before)),
+              Succeeds(cwd_before));
+  auto restore_cwd = LIBC_NAMESPACE::cpp::scope_exit(
+      [&]() { LIBC_NAMESPACE::chdir(cwd_before); });
+
+  // Exercise fd_limit across buffered (1), mixed transition (2, 3), and
+  // keep-open (10) modes, walking a root path with a slash (DIR1_REL) so
+  // level-0 FTW_CHDIR must chdir into dirname(DIR1_REL) before calling fn.
+  constexpr int LIMITS[] = {1, 2, 3, 10};
+  for (int limit : LIMITS) {
+    reset_counts();
+    ASSERT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, limit, FTW_PHYS),
+                Succeeds(0));
+    EXPECT_EQ(call_count, 6);
+    EXPECT_EQ(dir_count, 4);
+    EXPECT_EQ(file_count, 2);
+    EXPECT_EQ(max_level, 3);
+
+    reset_counts();
+    ASSERT_THAT(
+        LIBC_NAMESPACE::nftw(dir1, chdir_callback, limit, FTW_CHDIR | FTW_PHYS),
+        Succeeds(0));
+    ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_after, sizeof(cwd_after)),
+                Succeeds(cwd_after));
+    EXPECT_STREQ(cwd_before, cwd_after);
+    EXPECT_EQ(call_count, 5);
+
+    reset_counts();
+    ASSERT_THAT(LIBC_NAMESPACE::nftw(dir1, chdir_callback, limit,
+                                     FTW_CHDIR | FTW_PHYS | FTW_DEPTH),
+                Succeeds(0));
+    ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_after, sizeof(cwd_after)),
+                Succeeds(cwd_after));
+    EXPECT_STREQ(cwd_before, cwd_after);
+    EXPECT_EQ(call_count, 5);
+  }
+
+  // Early callback stop at level == 1 with FTW_CHDIR and fd_limit == 1 must
+  // still restore the caller's working directory.
+  reset_counts();
+  ASSERT_THAT(
+      LIBC_NAMESPACE::nftw(dir1, stop_at_level1_cb, 1, FTW_CHDIR | FTW_PHYS),
+      Succeeds(99));
+  ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_after, sizeof(cwd_after)),
+              Succeeds(cwd_after));
+  EXPECT_STREQ(cwd_before, cwd_after);
+  EXPECT_EQ(call_count, 2);
+}
+
+TEST_F(LlvmLibcNftwTest, BufferGrowthAndVanishedEntry) {
+  // Exercise PathBuffer growth (>256 bytes) under fd_limit == 1, plus
+  // ENOENT->FTW_NS when a sibling vanishes mid-walk.
+  constexpr const char *RACE_ROOT = "nftw_race_root";
+  constexpr const char *VANISH_A = "nftw_race_root/vanish_a.txt";
+  constexpr const char *VANISH_B = "nftw_race_root/vanish_b.txt";
+  constexpr const char *LONG_A =
+      "nftw_race_root/"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+  constexpr const char *LONG_B =
+      "nftw_race_root/"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
+      "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+      "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
+  constexpr const char *LONG_FILE =
+      "nftw_race_root/"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"
+      "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+      "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/"
+      "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+      "cccccccccccccccccccccccccccccccccccccccccccccccccccccccc.txt";
+
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::unlink(LONG_FILE);
+    LIBC_NAMESPACE::rmdir(LONG_B);
+    LIBC_NAMESPACE::rmdir(LONG_A);
+    LIBC_NAMESPACE::unlink(VANISH_A);
+    LIBC_NAMESPACE::unlink(VANISH_B);
+    LIBC_NAMESPACE::rmdir(RACE_ROOT);
+    LIBC_NAMESPACE::libc_errno = 0;
+  });
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(RACE_ROOT, 0755), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(LONG_A, 0755), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(LONG_B, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(LONG_FILE), Succeeds(0));
+
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(RACE_ROOT, record_callback, 1, FTW_PHYS),
+              Succeeds(0));
+  EXPECT_EQ(call_count, 4);
+  EXPECT_EQ(dir_count, 3);
+  EXPECT_EQ(file_count, 1);
+
+  // When one sibling unlinks the other during iteration, the vanished sibling
+  // is reported as FTW_NS and the walk continues rather than aborting.
+  ASSERT_THAT(create_empty_file(VANISH_A), Succeeds(0));
+  ASSERT_THAT(create_empty_file(VANISH_B), Succeeds(0));
+  reset_counts();
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(RACE_ROOT, unlink_sibling_cb, 1, FTW_PHYS),
+              Succeeds(0));
+  EXPECT_EQ(call_count, 6);
+  EXPECT_EQ(ns_count, 1);
+}
+
+TEST_F(LlvmLibcNftwTest, CallbackReturnAndErrorCases) {
+  constexpr const char *ROOT_REL = "nftw_err_root";
+  constexpr const char *FILE_REL = "nftw_err_root/file.txt";
+  constexpr const char *FILE_SLASH_REL = "nftw_err_root/file.txt/";
+  constexpr const char *NOTDIR_REL = "nftw_err_root/file.txt/child";
+  constexpr const char *NONEXISTENT_REL = "nftw_nonexistent_path";
+
+  auto root = libc_make_test_file_path(ROOT_REL);
+  auto file_path = libc_make_test_file_path(FILE_REL);
+  auto file_slash_path = libc_make_test_file_path(FILE_SLASH_REL);
+  auto notdir_path = libc_make_test_file_path(NOTDIR_REL);
+  auto nonexistent = libc_make_test_file_path(NONEXISTENT_REL);
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::unlink(file_path);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+  ASSERT_THAT(create_empty_file(file_path), Succeeds(0));
+
+  // Passing a regular file directly as the root path reports FTW_F at level 0.
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(file_path, record_callback, 10, 0),
+              Succeeds(0));
+  EXPECT_EQ(call_count, 1);
+  EXPECT_EQ(file_count, 1);
+  EXPECT_EQ(max_level, 0);
+
+  reset_counts();
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, stop_42_cb, 10, 0), Succeeds(42));
+  EXPECT_EQ(call_count, 1);
+
+  // Returning -1 from callback must preserve the errno set by the callback.
+  reset_counts();
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, stop_neg_one_cb, 10, 0), Fails(EXDEV));
+  EXPECT_EQ(call_count, 1);
+
+  EXPECT_THAT(LIBC_NAMESPACE::nftw("", record_callback, 10, 0), Fails(ENOENT));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(nonexistent, record_callback, 10, 0),
+              Fails(ENOENT));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(file_slash_path, record_callback, 10, 0),
+              Fails(ENOTDIR));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(notdir_path, record_callback, 10, 0),
+              Fails(ENOTDIR));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, 0, 0), Fails(EINVAL));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, -1, 0),
+              Fails(EINVAL));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, 10, ~0),
+              Fails(EINVAL));
+}
+
+TEST_F(LlvmLibcNftwTest, PermissionErrors) {
+  if (LIBC_NAMESPACE::geteuid() == 0) {
+    tlog << "Skipping PermissionErrors: running as root.\n";
+    return;
+  }
+
+  constexpr const char *ROOT_REL = "nftw_perm_root";
+  constexpr const char *UNREADABLE_REL = "nftw_perm_root/unreadable_dir";
+  constexpr const char *NOSEARCH_REL = "nftw_perm_root/nosearch_dir";
+  constexpr const char *CHILD_REL = "nftw_perm_root/nosearch_dir/child";
+
+  auto root = libc_make_test_file_path(ROOT_REL);
+  auto unreadable = libc_make_test_file_path(UNREADABLE_REL);
+  auto nosearch = libc_make_test_file_path(NOSEARCH_REL);
+  auto child = libc_make_test_file_path(CHILD_REL);
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::chmod(unreadable, 0755);
+    LIBC_NAMESPACE::chmod(nosearch, 0755);
+    LIBC_NAMESPACE::unlink(child);
+    LIBC_NAMESPACE::rmdir(unreadable);
+    LIBC_NAMESPACE::rmdir(nosearch);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(unreadable, 0333), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(nosearch, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(child), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::chmod(nosearch, 0666), Succeeds(0));
+
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, 10, 0), Succeeds(0));
+  EXPECT_EQ(call_count, 4);
+  EXPECT_EQ(dir_count, 2);
+  EXPECT_EQ(dnr_count, 1);
+  EXPECT_EQ(ns_count, 1);
+
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(unreadable, record_callback, 10, 0),
+              Fails(EACCES));
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(child, record_callback, 10, 0),
+              Fails(EACCES));
+}
+
+TEST_F(LlvmLibcNftwTest, FlagsAndActionRetVal) {
+  constexpr const char *ROOT_REL = "nftw_flags_root";
+  constexpr const char *SUBDIR_REL = "nftw_flags_root/dir1";
+  constexpr const char *FILE1_REL = "nftw_flags_root/file1.txt";
+  constexpr const char *FILE2_REL = "nftw_flags_root/dir1/file2.txt";
+  constexpr const char *SYMLINK_REL = "nftw_flags_root/link_to_file1";
+  constexpr const char *BROKEN_REL = "nftw_flags_root/broken_link";
+  constexpr const char *BROKEN_SLASH_REL = "nftw_flags_root/broken_link/";
+
+  auto root = libc_make_test_file_path(ROOT_REL);
+  auto subdir = libc_make_test_file_path(SUBDIR_REL);
+  auto file1 = libc_make_test_file_path(FILE1_REL);
+  auto file2 = libc_make_test_file_path(FILE2_REL);
+  auto symlink_path = libc_make_test_file_path(SYMLINK_REL);
+  auto broken_path = libc_make_test_file_path(BROKEN_REL);
+  auto broken_slash_path = libc_make_test_file_path(BROKEN_SLASH_REL);
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::unlink(broken_path);
+    LIBC_NAMESPACE::unlink(symlink_path);
+    LIBC_NAMESPACE::unlink(file2);
+    LIBC_NAMESPACE::unlink(file1);
+    LIBC_NAMESPACE::rmdir(subdir);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(subdir, 0755), Succeeds(0));
+  ASSERT_THAT(create_empty_file(file1), Succeeds(0));
+  ASSERT_THAT(create_empty_file(file2), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("file1.txt", symlink_path), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::symlink("nonexistent_target", broken_path),
+              Succeeds(0));
+
+  // Trailing slash on a dangling symlink forces target resolution and fails
+  // with ENOENT rather than reporting FTW_SL or FTW_SLN.
+  EXPECT_THAT(LIBC_NAMESPACE::nftw(broken_slash_path, record_callback, 10, 0),
+              Fails(ENOENT));
+  EXPECT_THAT(
+      LIBC_NAMESPACE::nftw(broken_slash_path, record_callback, 10, FTW_PHYS),
+      Fails(ENOENT));
+
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, record_callback, 10, FTW_MOUNT),
+              Succeeds(0));
+  EXPECT_EQ(max_level, 2);
+  EXPECT_EQ(dir_count, 2);
+  EXPECT_EQ(file_count, 3);
+  EXPECT_EQ(sln_count, 1);
+  EXPECT_EQ(sl_count, 0);
+
+  // FTW_PHYS + FTW_DEPTH: both symlinks are FTW_SL, directories are FTW_DP,
+  // and subdir is visited before root.
+  reset_counts();
+  ASSERT_THAT(
+      LIBC_NAMESPACE::nftw(root, record_callback, 10, FTW_PHYS | FTW_DEPTH),
+      Succeeds(0));
+  EXPECT_EQ(dp_count, 2);
+  EXPECT_EQ(sl_count, 2);
+  EXPECT_GT(find_visit(ROOT_REL), find_visit(SUBDIR_REL));
+  EXPECT_GT(find_visit(SUBDIR_REL), find_visit(FILE2_REL));
+
+  constexpr int LIMITS[] = {1, 10};
+  for (int limit : LIMITS) {
+    // FTW_ACTIONRETVAL: FTW_SKIP_SUBTREE skips file2.txt inside dir1 (6 - 1 =
+    // 5).
+    reset_counts();
+    ASSERT_THAT(LIBC_NAMESPACE::nftw(root, skip_subtree_cb, limit,
+                                     FTW_PHYS | FTW_ACTIONRETVAL),
+                Succeeds(0));
+    EXPECT_EQ(call_count, 5);
+
+    // FTW_ACTIONRETVAL: FTW_SKIP_SIBLINGS at level 1 stops after the first
+    // level-1 entry and returns to parent (root + first child = 2).
+    reset_counts();
+    ASSERT_THAT(LIBC_NAMESPACE::nftw(root, skip_siblings_cb, limit,
+                                     FTW_PHYS | FTW_ACTIONRETVAL),
+                Succeeds(0));
+    EXPECT_EQ(call_count, 2);
+
+    // FTW_ACTIONRETVAL: FTW_STOP halts immediately and returns FTW_STOP.
+    reset_counts();
+    ASSERT_THAT(
+        LIBC_NAMESPACE::nftw(root, stop_action_cb, limit, FTW_ACTIONRETVAL),
+        Succeeds<int>(FTW_STOP));
+    EXPECT_EQ(call_count, 1);
+  }
+}
+
+TEST_F(LlvmLibcNftwTest, DeepIterativeTraversal) {
+  // Build a 24-level nested tree (> INITIAL_FRAME_CAPACITY = 16) with a
+  // sibling file at each level to exercise FrameStack growth and lseek-based
+  // directory offset resumption when fd_limit == 1.
+  constexpr int DEPTH = 24;
+  auto root = libc_make_test_file_path("nftw_deep_root");
+
+  char cwd_before[4096];
+  char cwd_after[4096];
+  ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_before, sizeof(cwd_before)),
+              Succeeds(cwd_before));
+
+  ASSERT_THAT(LIBC_NAMESPACE::mkdir(root, 0755), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::chdir(root), Succeeds(0));
+
+  int created_levels = 0;
+  auto cleanup = LIBC_NAMESPACE::cpp::scope_exit([&]() {
+    LIBC_NAMESPACE::chdir(root);
+    for (int i = 0; i < created_levels; ++i)
+      LIBC_NAMESPACE::chdir("d");
+    for (int i = created_levels; i > 0; --i) {
+      LIBC_NAMESPACE::unlink("sib.txt");
+      LIBC_NAMESPACE::chdir("..");
+      LIBC_NAMESPACE::rmdir("d");
+    }
+    LIBC_NAMESPACE::chdir(cwd_before);
+    LIBC_NAMESPACE::rmdir(root);
+  });
+
+  for (int i = 0; i < DEPTH; ++i) {
+    ASSERT_THAT(LIBC_NAMESPACE::mkdir("d", 0755), Succeeds(0));
+    ASSERT_THAT(LIBC_NAMESPACE::chdir("d"), Succeeds(0));
+    ++created_levels;
+    ASSERT_THAT(create_empty_file("sib.txt"), Succeeds(0));
+  }
+  ASSERT_THAT(LIBC_NAMESPACE::chdir(cwd_before), Succeeds(0));
+
+  reset_counts();
+  ASSERT_THAT(LIBC_NAMESPACE::nftw(root, chdir_callback, 1,
+                                   FTW_PHYS | FTW_CHDIR | FTW_DEPTH),
+              Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::getcwd(cwd_after, sizeof(cwd_after)),
+              Succeeds(cwd_after));
+  EXPECT_STREQ(cwd_before, cwd_after);
+  // 1 root dir + 24 nested dirs + 24 sibling files = 49 entries.
+  EXPECT_EQ(call_count, 1 + 2 * DEPTH);
+  EXPECT_EQ(dp_count, 1 + DEPTH);
+  EXPECT_EQ(file_count, DEPTH);
+  EXPECT_EQ(max_level, DEPTH + 1);
+}
+
+#if defined(LIBC_ADD_NULL_CHECKS)
+TEST_F(LlvmLibcNftwTest, NullptrCrash) {
+  ASSERT_DEATH([] { LIBC_NAMESPACE::nftw(nullptr, record_callback, 10, 0); },
+               WITH_SIGNAL(-1));
+  ASSERT_DEATH([] { LIBC_NAMESPACE::nftw(".", nullptr, 10, 0); },
+               WITH_SIGNAL(-1));
+}
+#endif // LIBC_ADD_NULL_CHECKS
diff --git a/libc/utils/docgen/ftw.yaml b/libc/utils/docgen/ftw.yaml
index a1c7721d62e3c6..209a907a8dc739 100644
--- a/libc/utils/docgen/ftw.yaml
+++ b/libc/utils/docgen/ftw.yaml
@@ -1,7 +1,11 @@
 posix: posix-2024
 macros:
+  FTW_ACTIONRETVAL:
+    extension: gnu
   FTW_CHDIR:
     in-latest-posix: ''
+  FTW_CONTINUE:
+    extension: gnu
   FTW_D:
     in-latest-posix: ''
   FTW_DEPTH:
@@ -18,10 +22,16 @@ macros:
     in-latest-posix: ''
   FTW_PHYS:
     in-latest-posix: ''
+  FTW_SKIP_SIBLINGS:
+    extension: gnu
+  FTW_SKIP_SUBTREE:
+    extension: gnu
   FTW_SL:
     in-latest-posix: ''
   FTW_SLN:
     in-latest-posix: ''
+  FTW_STOP:
+    extension: gnu
 functions:
   ftw:
     removed-in-posix-2024: ''



More information about the libc-commits mailing list