[libc-commits] [libc] [llvm] [libc] Parametrize File with a platform (PR #245553)

Petr Hosek via libc-commits libc-commits at lists.llvm.org
Tue Nov 24 01:27:47 PST 2026


https://github.com/petrhosek created https://github.com/llvm/llvm-project/pull/245553

This change replaces the File class with a templated class FileImpl which is parameterized by the platform. LinuxFile inherits from File providing concrete implementation for Linux using static dispatch. CustomFileImpl and CookieFileImpl are CRTP classes used to implement PopenFile, MemopenFile and CookieFile atop LinuxFile.

This reduces the size e.g. the LinuxFile is now 96B on x86-64 instead of 128B. When the dynamic backend (i.e. fopencookie or fmemopen) isn't used, we also avoid dynamic dispatch thus improving performance. This change also addresses several latent issues (e.g. leak in fopencookie close).

The parametrized platform also opens the path for reusing the FileImpl implementation for other platforms such as baremetal and GPU. This will be utilized in follow up changes.

Assisted-by: Gemini

>From 6515fad762dd6c21b0f4f2a735687db00dcd4869 Mon Sep 17 00:00:00 2001
From: Petr Hosek <phosek at google.com>
Date: Wed, 18 Nov 2026 09:34:56 -0800
Subject: [PATCH] [libc] Parametrize File with a platform

This change replaces the File class with a templated class FileImpl
which is parameterized by the platform. LinuxFile inherits from File
providing concrete implementation for Linux using static dispatch.
CustomFileImpl and CookieFileImpl are CRTP classes used to implement
PopenFile, MemopenFile and CookieFile atop LinuxFile.

This reduces the size e.g. the LinuxFile is now 96B on x86-64 instead
of 128B. When the dynamic backend (i.e. fopencookie or fmemopen) isn't
used, we also avoid dynamic dispatch thus improving performance. This
change also addresses several latent issues (e.g. leak in fopencookie
close).

The parametrized platform also opens the path for reusing the FileImpl
implementation for other platforms such as baremetal and GPU. This will
be utilized in follow up changes.

Assisted-by: Gemini
---
 libc/src/__support/File/CMakeLists.txt        |  10 +-
 libc/src/__support/File/file.h                | 321 ++++++++--
 .../__support/File/{file.cpp => file_impl.h}  | 187 ++++--
 libc/src/__support/File/linux/CMakeLists.txt  |   4 +-
 libc/src/__support/File/linux/file.cpp        |  59 +-
 libc/src/__support/File/linux/file.h          |  37 +-
 libc/src/__support/File/linux/popen_file.cpp  |  18 +-
 libc/src/__support/File/linux/popen_file.h    |  13 +-
 libc/src/__support/File/platform_file.h       |  23 +
 libc/src/stdio/CMakeLists.txt                 |   7 +-
 libc/src/stdio/fmemopen.cpp                   |  34 +-
 libc/src/stdio/fopencookie.cpp                |  86 +--
 libc/src/stdio/generic/CMakeLists.txt         |   2 +
 libc/src/wchar/CMakeLists.txt                 |  10 +
 libc/test/src/__support/File/CMakeLists.txt   |   4 +
 libc/test/src/__support/File/file_test.cpp    | 593 ++++++++++++++++--
 libc/test/src/stdio/CMakeLists.txt            |  11 +
 libc/test/src/stdio/fmemopen_test.cpp         |   1 +
 libc/test/src/stdio/fopencookie_test.cpp      |  39 +-
 libc/test/src/stdio/freopen_test.cpp          |  66 ++
 libc/test/src/stdio/getdelim_impl_test.cpp    |  12 +-
 libc/test/src/stdio/popen_pclose_test.cpp     |  73 +++
 .../libc/src/__support/File/BUILD.bazel       |   9 +-
 .../libc/src/stdio/BUILD.bazel                |  20 +-
 24 files changed, 1326 insertions(+), 313 deletions(-)
 rename libc/src/__support/File/{file.cpp => file_impl.h} (76%)
 create mode 100644 libc/src/__support/File/platform_file.h

diff --git a/libc/src/__support/File/CMakeLists.txt b/libc/src/__support/File/CMakeLists.txt
index d3fbe37b94839b..c5802e1eeb3670 100644
--- a/libc/src/__support/File/CMakeLists.txt
+++ b/libc/src/__support/File/CMakeLists.txt
@@ -11,12 +11,12 @@ if(NOT (TARGET libc.src.__support.threads.mutex)
   return()
 endif()
 
-add_object_library(
+add_header_library(
   file
-  SRCS
-    file.cpp
   HDRS
     file.h
+    file_impl.h
+    file_mode.h
   DEPENDS
     .file_io_result
     libc.hdr.errno_macros
@@ -26,15 +26,19 @@ add_object_library(
     libc.hdr.types.char32_t
     libc.hdr.types.char8_t
     libc.hdr.types.off_t
+    libc.hdr.types.ssize_t
     libc.hdr.types.wchar_t
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.alloc_checker
     libc.src.__support.CPP.new
     libc.src.__support.CPP.span
+    libc.src.__support.CPP.type_traits
     libc.src.__support.error_or
     libc.src.__support.libc_assert
     libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
     libc.src.__support.threads.mutex
     libc.src.__support.wchar.character_converter
     libc.src.__support.wchar.mbstate
diff --git a/libc/src/__support/File/file.h b/libc/src/__support/File/file.h
index 19b83e0e2fe10c..7134a1e46cd92e 100644
--- a/libc/src/__support/File/file.h
+++ b/libc/src/__support/File/file.h
@@ -14,16 +14,21 @@
 #ifndef LLVM_LIBC_SRC___SUPPORT_FILE_FILE_H
 #define LLVM_LIBC_SRC___SUPPORT_FILE_FILE_H
 
-#include "file_io_result.h"
-#include "file_mode.h"
+#include "hdr/errno_macros.h"
 #include "hdr/stdint_proxy.h"
 #include "hdr/stdio_macros.h"
 #include "hdr/types/off_t.h"
+#include "hdr/types/ssize_t.h"
 #include "hdr/types/wchar_t.h"
 #include "hdr/types/wint_t.h"
+#include "src/__support/CPP/new.h"
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/File/file_io_result.h"
+#include "src/__support/File/file_mode.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/__support/threads/mutex.h"
 #include "src/__support/wchar/mbstate.h"
 
@@ -31,51 +36,109 @@
 
 namespace LIBC_NAMESPACE_DECL {
 
-// This a generic base class to encapsulate a platform independent file data
-// structure. Platform specific specializations should create a subclass as
-// suitable for their platform.
-class File {
+namespace internal {
+
+template <typename FileT>
+LIBC_INLINE FileIOResult default_write(FileT *, const void *, size_t size) {
+  return size;
+}
+
+template <typename FileT>
+LIBC_INLINE FileIOResult default_read(FileT *, void *, size_t) {
+  return 0;
+}
+
+template <typename FileT>
+LIBC_INLINE ErrorOr<off_t> default_seek(FileT *, off_t, int) {
+  return Error(ESPIPE);
+}
+
+template <typename FileT> LIBC_INLINE int default_close(FileT *) { return 0; }
+
+} // namespace internal
+
+template <typename FileT> struct FileOps {
+  using WriteFunc = FileIOResult(FileT *, const void *, size_t);
+  using ReadFunc = FileIOResult(FileT *, void *, size_t);
+  // The SeekFunc is expected to return the current offset of the external
+  // file position indicator.
+  using SeekFunc = ErrorOr<off_t>(FileT *, off_t, int);
+  using CloseFunc = int(FileT *);
+  // Optional hook invoked when reopening a CustomFile onto an OS file
+  // descriptor to tear down subclass-specific state without deleting |FileT|.
+  using DetachFunc = void(FileT *);
+
+  WriteFunc *write;
+  ReadFunc *read;
+  SeekFunc *seek;
+  CloseFunc *close;
+  DetachFunc *detach;
+
+  LIBC_INLINE constexpr FileOps(WriteFunc *w, ReadFunc *r, SeekFunc *s,
+                                CloseFunc *c, DetachFunc *d = nullptr)
+      : write(w != nullptr ? w : &internal::default_write<FileT>),
+        read(r != nullptr ? r : &internal::default_read<FileT>),
+        seek(s != nullptr ? s : &internal::default_seek<FileT>),
+        close(c != nullptr ? c : &internal::default_close<FileT>), detach(d) {}
+};
+
+struct CookieOps {
+  using ReadFunc = ssize_t(void *, char *, size_t);
+  using WriteFunc = ssize_t(void *, const char *, size_t);
+  using SeekFunc = int(void *, off_t *, int);
+  using CloseFunc = int(void *);
+
+  ReadFunc *read = nullptr;
+  WriteFunc *write = nullptr;
+  SeekFunc *seek = nullptr;
+  CloseFunc *close = nullptr;
+};
+
+// This is a generic base class template to encapsulate a platform independent
+// file data structure. Platform specific specializations provide a static
+// Platform policy and optionally subclass FileImpl as suitable for their
+// platform.
+template <typename Platform> class FileImpl {
 public:
-  static void add_file(File *f);
-  static void remove_file(File *f);
-  static File *get_first_file();
+  using PlatformType = Platform;
+  using FileBase = FileImpl;
+  using Ops = FileOps<FileImpl>;
+
+  enum class DispatchKind : uint8_t {
+    STATIC = 0,
+    CUSTOM = 1,
+    COOKIE = 2,
+  };
+
+  static void add_file(FileImpl *f);
+  static void remove_file(FileImpl *f);
+  static FileImpl *get_first_file();
   static void lock_list();
   static void unlock_list();
 
-  static File *list_all;
+  static FileImpl *list_all;
   static Mutex list_lock;
 
-  LIBC_INLINE File *get_next() const { return next; }
+  LIBC_INLINE FileImpl *get_next() const { return next; }
 
   static constexpr size_t DEFAULT_BUFFER_SIZE = 1024;
 
   enum class Orientation : uint8_t { UNORIENTED, BYTE, WIDE };
 
-  using LockFunc = void(File *);
-  using UnlockFunc = void(File *);
+  using LockFunc = void(FileImpl *);
+  using UnlockFunc = void(FileImpl *);
 
-  using WriteFunc = FileIOResult(File *, const void *, size_t);
-  using ReadFunc = FileIOResult(File *, void *, size_t);
-  // The SeekFunc is expected to return the current offset of the external
-  // file position indicator.
-  using SeekFunc = ErrorOr<off_t>(File *, off_t, int);
-  using CloseFunc = int(File *);
-
-  // Exposes the platform I/O callbacks so a platform backend can positively
-  // identify which concrete File subclass an object is (e.g. distinguishing
-  // a LinuxFile from a CookieFile/MemoryFile) without needing RTTI. See
-  // is_linux_file() in the Linux backend for the concrete use.
-  LIBC_INLINE ReadFunc *get_read_func() const { return platform_read; }
-  LIBC_INLINE WriteFunc *get_write_func() const { return platform_write; }
-  LIBC_INLINE SeekFunc *get_seek_func() const { return platform_seek; }
-  LIBC_INLINE CloseFunc *get_close_func() const { return platform_close; }
+  using WriteFunc = typename Ops::WriteFunc;
+  using ReadFunc = typename Ops::ReadFunc;
+  using SeekFunc = typename Ops::SeekFunc;
+  using CloseFunc = typename Ops::CloseFunc;
 
   // This is a convenience RAII class to lock and unlock file objects.
   class FileLock {
-    File *file;
+    FileImpl *file;
 
   public:
-    LIBC_INLINE explicit FileLock(File *f) : file(f) { file->lock(); }
+    LIBC_INLINE explicit FileLock(FileImpl *f) : file(f) { file->lock(); }
 
     LIBC_INLINE ~FileLock() { file->unlock(); }
 
@@ -86,14 +149,6 @@ class File {
 private:
   enum class FileOp : uint8_t { NONE, READ, WRITE, SEEK };
 
-  // Platform specific functions which create new file objects should initialize
-  // these fields suitably via the constructor. Typically, they should be simple
-  // syscall wrappers for the corresponding functionality.
-  WriteFunc *platform_write;
-  ReadFunc *platform_read;
-  SeekFunc *platform_seek;
-  CloseFunc *platform_close;
-
   uint8_t *buf;   // Pointer to the stream buffer for buffered streams
   size_t bufsize; // Size of the buffer pointed to by |buf|.
 
@@ -104,8 +159,8 @@ class File {
   // of the index to which the buffer can be read until.
   size_t read_limit;
 
-  File *prev;
-  File *next;
+  FileImpl *prev;
+  FileImpl *next;
 
   internal::mbstate mbstate;
 
@@ -113,7 +168,7 @@ class File {
   FileMode mode;
 
   // For files which are readable, we should be able to support one ungetc
-  // operation even if |buf| is nullptr. So, in the constructor of File, we
+  // operation even if |buf| is nullptr. So, in the constructor of FileImpl, we
   // set |buf| to point to this buffer character. It needs to be at least 4
   // bytes so we can store a widechar.
   uint8_t ungetc_buf[4];
@@ -132,6 +187,7 @@ class File {
   bool own_buf : 1;
   bool eof : 1;
   bool err : 1;
+  DispatchKind kind : 2;
 
 protected:
   LIBC_INLINE constexpr bool write_allowed() const {
@@ -154,7 +210,19 @@ class File {
     adjust_buf();
   }
 
-public:
+  LIBC_INLINE constexpr FileImpl(DispatchKind dispatch_kind, uint8_t *buffer,
+                                 size_t buffer_size, int buffer_mode,
+                                 bool owned, FileMode mode)
+      : buf(buffer), bufsize(buffer_size), pos(0), read_limit(0), prev(nullptr),
+        next(nullptr), mbstate(), mode(mode), ungetc_buf{},
+        mutex(/*timed=*/false, /*recursive=*/true,
+              /*robust=*/false, /*pshared=*/false),
+        bufmode(static_cast<int8_t>(buffer_mode)), prev_op(FileOp::NONE),
+        orientation(Orientation::UNORIENTED), own_buf(owned), eof(false),
+        err(false), kind(dispatch_kind) {
+    adjust_buf();
+  }
+
   // We want this constructor to be constexpr so that global file objects
   // like stdout do not require invocation of the constructor which can
   // potentially lead to static initialization order fiasco. Consequently,
@@ -162,18 +230,15 @@ class File {
   // meaningful - that is, |buffer| is nullptr if and only if |buffer_size|
   // is zero. This way, we will not have to employ the semantics of
   // the set_buffer method and allocate a buffer.
-  LIBC_INLINE constexpr File(WriteFunc *wf, ReadFunc *rf, SeekFunc *sf,
-                             CloseFunc *cf, uint8_t *buffer, size_t buffer_size,
-                             int buffer_mode, bool owned, FileMode mode)
-      : platform_write(wf), platform_read(rf), platform_seek(sf),
-        platform_close(cf), buf(buffer), bufsize(buffer_size), pos(0),
-        read_limit(0), prev(nullptr), next(nullptr), mbstate(), mode(mode),
-        ungetc_buf{}, mutex(/*timed=*/false, /*recursive=*/true,
-                            /*robust=*/false, /*pshared=*/false),
-        bufmode(static_cast<int8_t>(buffer_mode)), prev_op(FileOp::NONE),
-        orientation(Orientation::UNORIENTED), own_buf(owned), eof(false),
-        err(false) {
-    adjust_buf();
+  LIBC_INLINE constexpr FileImpl(uint8_t *buffer, size_t buffer_size,
+                                 int buffer_mode, bool owned, FileMode mode)
+      : FileImpl(DispatchKind::STATIC, buffer, buffer_size, buffer_mode, owned,
+                 mode) {}
+
+public:
+  LIBC_INLINE constexpr DispatchKind get_dispatch_kind() const { return kind; }
+  LIBC_INLINE constexpr bool is_dynamic() const {
+    return kind != DispatchKind::STATIC;
   }
 
   // Buffered write of |len| bytes from |data| without the file lock.
@@ -338,6 +403,41 @@ class File {
   }
 
 private:
+  LIBC_NOINLINE static FileIOResult
+  platform_write_dynamic(FileImpl *f, const void *data, size_t len);
+  LIBC_NOINLINE static FileIOResult
+  platform_read_dynamic(FileImpl *f, void *data, size_t len);
+  LIBC_NOINLINE static ErrorOr<off_t>
+  platform_seek_dynamic(FileImpl *f, off_t offset, int whence);
+  LIBC_NOINLINE static int platform_close_dynamic(FileImpl *f);
+
+  LIBC_INLINE static FileIOResult platform_write(FileImpl *f, const void *data,
+                                                 size_t len) {
+    if (LIBC_LIKELY(f->kind == DispatchKind::STATIC))
+      return Platform::write(f, data, len);
+    return platform_write_dynamic(f, data, len);
+  }
+
+  LIBC_INLINE static FileIOResult platform_read(FileImpl *f, void *data,
+                                                size_t len) {
+    if (LIBC_LIKELY(f->kind == DispatchKind::STATIC))
+      return Platform::read(f, data, len);
+    return platform_read_dynamic(f, data, len);
+  }
+
+  LIBC_INLINE static ErrorOr<off_t> platform_seek(FileImpl *f, off_t offset,
+                                                  int whence) {
+    if (LIBC_LIKELY(f->kind == DispatchKind::STATIC))
+      return Platform::seek(f, offset, whence);
+    return platform_seek_dynamic(f, offset, whence);
+  }
+
+  LIBC_INLINE static int platform_close(FileImpl *f) {
+    if (LIBC_LIKELY(f->kind == DispatchKind::STATIC))
+      return Platform::close(f);
+    return platform_close_dynamic(f);
+  }
+
   FileIOResult write_unlocked_impl(const void *data, size_t len);
   FileIOResult read_unlocked_impl(void *data, size_t len);
 
@@ -374,6 +474,119 @@ class File {
   }
 };
 
+struct FilePlatform;
+
+template <typename BaseFile> class CustomFileImpl : public BaseFile {
+  static_assert(
+      cpp::is_same_v<BaseFile, typename BaseFile::PlatformType::StreamBase>,
+      "BaseFile must be Platform::StreamBase");
+
+public:
+  using Ops = typename BaseFile::Ops;
+
+private:
+  Ops ops;
+  friend typename BaseFile::FileBase;
+
+  LIBC_INLINE FileIOResult custom_write(const void *data, size_t len) {
+    return ops.write(this, data, len);
+  }
+  LIBC_INLINE FileIOResult custom_read(void *data, size_t len) {
+    return ops.read(this, data, len);
+  }
+  LIBC_INLINE ErrorOr<off_t> custom_seek(off_t offset, int whence) {
+    return ops.seek(this, offset, whence);
+  }
+  LIBC_INLINE int custom_close() { return ops.close(this); }
+
+public:
+  template <typename... Args>
+  LIBC_INLINE constexpr CustomFileImpl(const Ops &fops, uint8_t *buffer,
+                                       size_t buffer_size, int buffer_mode,
+                                       bool owned, FileMode mode,
+                                       Args... base_args)
+      : BaseFile(BaseFile::DispatchKind::CUSTOM, buffer, buffer_size,
+                 buffer_mode, owned, mode, base_args...),
+        ops(fops) {}
+
+  // Tears down subclass-specific backing state (if any) and rebinds the I/O
+  // hooks while preserving |ops.close| so |close()| still deletes the exact
+  // derived dynamic type.
+  LIBC_INLINE void rebind_ops(typename Ops::WriteFunc *w,
+                              typename Ops::ReadFunc *r,
+                              typename Ops::SeekFunc *s) {
+    using FileBaseT = typename BaseFile::FileBase;
+    if (ops.detach != nullptr) {
+      ops.detach(this);
+      ops.detach = nullptr;
+    }
+    ops.write = w != nullptr ? w : &internal::default_write<FileBaseT>;
+    ops.read = r != nullptr ? r : &internal::default_read<FileBaseT>;
+    ops.seek = s != nullptr ? s : &internal::default_seek<FileBaseT>;
+  }
+};
+
+template <typename BaseFile> class CookieFileImpl final : public BaseFile {
+  static_assert(
+      cpp::is_same_v<BaseFile, typename BaseFile::PlatformType::StreamBase>,
+      "BaseFile must be Platform::StreamBase");
+
+  void *cookie;
+  CookieOps ops;
+  friend typename BaseFile::FileBase;
+
+  LIBC_INLINE FileIOResult cookie_write(const void *data, size_t size) {
+    if (ops.write == nullptr)
+      return size;
+    ssize_t result =
+        ops.write(cookie, reinterpret_cast<const char *>(data), size);
+    if (result < 0 || static_cast<size_t>(result) > size)
+      return {0, EIO};
+    size_t written = static_cast<size_t>(result);
+    return {written, written < size ? EIO : 0};
+  }
+
+  LIBC_INLINE FileIOResult cookie_read(void *data, size_t size) {
+    if (ops.read == nullptr)
+      return 0;
+    ssize_t result = ops.read(cookie, reinterpret_cast<char *>(data), size);
+    if (result < 0 || static_cast<size_t>(result) > size)
+      return {0, EIO};
+    return static_cast<size_t>(result);
+  }
+
+  LIBC_INLINE ErrorOr<off_t> cookie_seek(off_t offset, int whence) {
+    if (ops.seek == nullptr)
+      return Error(EINVAL);
+    if (ops.seek(cookie, &offset, whence) == 0)
+      return offset;
+    return Error(EIO);
+  }
+
+  LIBC_INLINE int cookie_close() {
+    BaseFile::FileBase::remove_file(this);
+    int retval = ops.close != nullptr ? ops.close(cookie) : 0;
+    delete this;
+    return retval == 0 ? 0 : EIO;
+  }
+
+public:
+  // CookieFileImpl instances must be heap-allocated because close() deletes
+  // |this| after invoking |ops.close(cookie)|.
+  template <typename... Args>
+  LIBC_INLINE constexpr CookieFileImpl(void *c, CookieOps cops, uint8_t *buffer,
+                                       size_t buffer_size, int buffer_mode,
+                                       bool owned, FileMode mode,
+                                       Args... base_args)
+      : BaseFile(BaseFile::DispatchKind::COOKIE, buffer, buffer_size,
+                 buffer_mode, owned, mode, base_args...),
+        cookie(c), ops(cops) {}
+};
+
+using File = FileImpl<FilePlatform>;
+
+extern template class FileImpl<FilePlatform>;
+
 // The implementation of this function is provided by the platform_file
 // library.
 ErrorOr<File *> openfile(const char *path, const char *mode);
diff --git a/libc/src/__support/File/file.cpp b/libc/src/__support/File/file_impl.h
similarity index 76%
rename from libc/src/__support/File/file.cpp
rename to libc/src/__support/File/file_impl.h
index bfd27e37bcfe52..267317cf5ef4bd 100644
--- a/libc/src/__support/File/file.cpp
+++ b/libc/src/__support/File/file_impl.h
@@ -7,14 +7,13 @@
 //===----------------------------------------------------------------------===//
 ///
 /// \file
-/// Implementation of a platform independent file data structure.
+/// Out-of-line method definitions for FileImpl<Platform>.
 ///
 //===----------------------------------------------------------------------===//
 
-#include "file.h"
+#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_FILE_IMPL_H
+#define LLVM_LIBC_SRC___SUPPORT_FILE_FILE_IMPL_H
 
-#include "file_io_result.h"
-#include "file_mode.h"
 #include "hdr/errno_macros.h"
 #include "hdr/func/realloc.h"
 #include "hdr/stdint_proxy.h"
@@ -27,6 +26,9 @@
 #include "hdr/wchar_macros.h"
 #include "src/__support/CPP/new.h"
 #include "src/__support/CPP/span.h"
+#include "src/__support/File/file.h"
+#include "src/__support/File/file_io_result.h"
+#include "src/__support/File/file_mode.h"
 #include "src/__support/alloc-checker.h"
 #include "src/__support/error_or.h"
 #include "src/__support/libc_assert.h"
@@ -40,40 +42,100 @@
 #include <stddef.h>
 
 namespace LIBC_NAMESPACE_DECL {
-File *File::list_all = nullptr;
-Mutex File::list_lock(/*timed=*/false, /*recursive=*/false, /*robust=*/false,
-                      /*pshared=*/false);
+
+template <typename Platform>
+FileImpl<Platform> *FileImpl<Platform>::list_all = nullptr;
+
+template <typename Platform>
+Mutex FileImpl<Platform>::list_lock(/*timed=*/false,
+                                    /*recursive=*/false,
+                                    /*robust=*/false,
+                                    /*pshared=*/false);
 
 // Adds a file to the global list of all open files.
-void File::add_file(File *f) {
-  File::list_lock.lock();
-  f->next = File::list_all;
+template <typename Platform> void FileImpl<Platform>::add_file(FileImpl *f) {
+  list_lock.lock();
+  f->next = list_all;
   f->prev = nullptr;
-  if (File::list_all != nullptr)
-    File::list_all->prev = f;
-  File::list_all = f;
-  File::list_lock.unlock();
+  if (list_all != nullptr)
+    list_all->prev = f;
+  list_all = f;
+  list_lock.unlock();
 }
 
 // Removes a file from the global list of all open files.
-void File::remove_file(File *f) {
-  File::list_lock.lock();
+template <typename Platform> void FileImpl<Platform>::remove_file(FileImpl *f) {
+  list_lock.lock();
   if (f->prev != nullptr)
     f->prev->next = f->next;
   if (f->next != nullptr)
     f->next->prev = f->prev;
-  if (File::list_all == f)
-    File::list_all = f->next;
+  if (list_all == f)
+    list_all = f->next;
   f->prev = nullptr;
   f->next = nullptr;
-  File::list_lock.unlock();
+  list_lock.unlock();
+}
+
+template <typename Platform>
+FileImpl<Platform> *FileImpl<Platform>::get_first_file() {
+  return list_all;
+}
+
+template <typename Platform> void FileImpl<Platform>::lock_list() {
+  list_lock.lock();
 }
 
-File *File::get_first_file() { return File::list_all; }
-void File::lock_list() { File::list_lock.lock(); }
-void File::unlock_list() { File::list_lock.unlock(); }
+template <typename Platform> void FileImpl<Platform>::unlock_list() {
+  list_lock.unlock();
+}
+
+template <typename Platform>
+FileIOResult FileImpl<Platform>::platform_write_dynamic(FileImpl *f,
+                                                        const void *data,
+                                                        size_t len) {
+  using StreamBase = typename Platform::StreamBase;
+  if (f->kind == DispatchKind::CUSTOM)
+    return static_cast<CustomFileImpl<StreamBase> *>(f)->custom_write(data,
+                                                                      len);
+  LIBC_ASSERT(f->kind == DispatchKind::COOKIE);
+  return static_cast<CookieFileImpl<StreamBase> *>(f)->cookie_write(data, len);
+}
+
+template <typename Platform>
+FileIOResult FileImpl<Platform>::platform_read_dynamic(FileImpl *f, void *data,
+                                                       size_t len) {
+  using StreamBase = typename Platform::StreamBase;
+  if (f->kind == DispatchKind::CUSTOM)
+    return static_cast<CustomFileImpl<StreamBase> *>(f)->custom_read(data, len);
+  LIBC_ASSERT(f->kind == DispatchKind::COOKIE);
+  return static_cast<CookieFileImpl<StreamBase> *>(f)->cookie_read(data, len);
+}
 
-FileIOResult File::write_unlocked(const void *data, size_t len) {
+template <typename Platform>
+ErrorOr<off_t> FileImpl<Platform>::platform_seek_dynamic(FileImpl *f,
+                                                         off_t offset,
+                                                         int whence) {
+  using StreamBase = typename Platform::StreamBase;
+  if (f->kind == DispatchKind::CUSTOM)
+    return static_cast<CustomFileImpl<StreamBase> *>(f)->custom_seek(offset,
+                                                                     whence);
+  LIBC_ASSERT(f->kind == DispatchKind::COOKIE);
+  return static_cast<CookieFileImpl<StreamBase> *>(f)->cookie_seek(offset,
+                                                                   whence);
+}
+
+template <typename Platform>
+int FileImpl<Platform>::platform_close_dynamic(FileImpl *f) {
+  using StreamBase = typename Platform::StreamBase;
+  if (f->kind == DispatchKind::CUSTOM)
+    return static_cast<CustomFileImpl<StreamBase> *>(f)->custom_close();
+  LIBC_ASSERT(f->kind == DispatchKind::COOKIE);
+  return static_cast<CookieFileImpl<StreamBase> *>(f)->cookie_close();
+}
+
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked(const void *data, size_t len) {
   switch (orientation) {
   case Orientation::WIDE:
     err = true;
@@ -87,7 +149,9 @@ FileIOResult File::write_unlocked(const void *data, size_t len) {
   return write_unlocked_impl(data, len);
 }
 
-FileIOResult File::write_unlocked_impl(const void *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked_impl(const void *data,
+                                                     size_t len) {
   if (!write_allowed()) {
     err = true;
     return {0, EBADF};
@@ -100,7 +164,7 @@ FileIOResult File::write_unlocked_impl(const void *data, size_t len) {
   }
 
   if (bufmode == _IONBF) { // unbuffered.
-    size_t ret_val =
+    FileIOResult ret_val =
         write_unlocked_nbf(static_cast<const uint8_t *>(data), len);
     flush_unlocked();
     return ret_val;
@@ -111,7 +175,9 @@ FileIOResult File::write_unlocked_impl(const void *data, size_t len) {
                             len); // line buffered
 }
 
-FileIOResult File::write_unlocked_nbf(const uint8_t *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked_nbf(const uint8_t *data,
+                                                    size_t len) {
   if (pos > 0) { // If the buffer is not empty
     // Flush the buffer
     const size_t write_size = pos;
@@ -131,7 +197,9 @@ FileIOResult File::write_unlocked_nbf(const uint8_t *data, size_t len) {
   return write_result;
 }
 
-FileIOResult File::write_unlocked_fbf(const uint8_t *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked_fbf(const uint8_t *data,
+                                                    size_t len) {
   const size_t init_pos = pos;
   const size_t bufspace = bufsize - pos;
 
@@ -189,7 +257,6 @@ FileIOResult File::write_unlocked_fbf(const uint8_t *data, size_t len) {
     inline_memcpy(bufref.data(), remainder.data(), remainder.size());
     pos = remainder.size();
   } else {
-
     FileIOResult result =
         platform_write(this, remainder.data(), remainder.size());
     bytes_written = result.value;
@@ -205,7 +272,9 @@ FileIOResult File::write_unlocked_fbf(const uint8_t *data, size_t len) {
   return len;
 }
 
-FileIOResult File::write_unlocked_lbf(const uint8_t *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked_lbf(const uint8_t *data,
+                                                    size_t len) {
   constexpr uint8_t NEWLINE_CHAR = '\n';
   size_t last_newline = len;
   for (size_t i = len; i >= 1; --i) {
@@ -252,7 +321,8 @@ FileIOResult File::write_unlocked_lbf(const uint8_t *data, size_t len) {
   return len;
 }
 
-FileIOResult File::read_unlocked(void *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_unlocked(void *data, size_t len) {
   switch (orientation) {
   case Orientation::WIDE:
     err = true;
@@ -266,13 +336,18 @@ FileIOResult File::read_unlocked(void *data, size_t len) {
   return read_unlocked_impl(data, len);
 }
 
-FileIOResult File::read_unlocked_impl(void *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_unlocked_impl(void *data, size_t len) {
   if (!read_allowed()) {
     err = true;
     return {0, EBADF};
   }
 
-  prev_op = FileOp::READ;
+  if (prev_op != FileOp::READ) {
+    pos = 0;
+    read_limit = 0;
+    prev_op = FileOp::READ;
+  }
 
   if (bufmode == _IONBF) { // unbuffered.
     return read_unlocked_nbf(static_cast<uint8_t *>(data), len);
@@ -284,7 +359,8 @@ FileIOResult File::read_unlocked_impl(void *data, size_t len) {
   }
 }
 
-size_t File::copy_data_from_buf(uint8_t *data, size_t len) {
+template <typename Platform>
+size_t FileImpl<Platform>::copy_data_from_buf(uint8_t *data, size_t len) {
   cpp::span<uint8_t> bufref(static_cast<uint8_t *>(buf), bufsize);
   cpp::span<uint8_t> dataref(static_cast<uint8_t *>(data), len);
 
@@ -304,8 +380,10 @@ size_t File::copy_data_from_buf(uint8_t *data, size_t len) {
   return available_data;
 }
 
-FileIOResult File::read_from_platform(uint8_t *dst, size_t min_bytes,
-                                      size_t max_bytes) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_from_platform(uint8_t *dst,
+                                                    size_t min_bytes,
+                                                    size_t max_bytes) {
   LIBC_ASSERT(min_bytes <= max_bytes);
   size_t total_read = 0;
   cpp::span<uint8_t> dstref(dst, max_bytes);
@@ -326,7 +404,8 @@ FileIOResult File::read_from_platform(uint8_t *dst, size_t min_bytes,
   return total_read;
 }
 
-FileIOResult File::read_unlocked_fbf(uint8_t *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_unlocked_fbf(uint8_t *data, size_t len) {
   // Read data from the buffer first.
   size_t available_data = copy_data_from_buf(data, len);
   if (available_data == len)
@@ -351,7 +430,8 @@ FileIOResult File::read_unlocked_fbf(uint8_t *data, size_t len) {
   return {available_data, result.error};
 }
 
-FileIOResult File::read_unlocked_nbf(uint8_t *data, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_unlocked_nbf(uint8_t *data, size_t len) {
   // Check whether there is a character in the ungetc buffer.
   size_t available_data = copy_data_from_buf(data, len);
   if (available_data == len)
@@ -364,7 +444,7 @@ FileIOResult File::read_unlocked_nbf(uint8_t *data, size_t len) {
   return {available_data + result.value, result.error};
 }
 
-int File::ungetc_unlocked(int c) {
+template <typename Platform> int FileImpl<Platform>::ungetc_unlocked(int c) {
   // There is no meaning to unget if:
   // 1. You are trying to push back EOF.
   // 2. Read operations are not allowed on this file.
@@ -414,7 +494,8 @@ int File::ungetc_unlocked(int c) {
   return c;
 }
 
-ErrorOr<int> File::seek_unlocked(off_t offset, int whence) {
+template <typename Platform>
+ErrorOr<int> FileImpl<Platform>::seek_unlocked(off_t offset, int whence) {
   if (prev_op == FileOp::WRITE && pos > 0) {
     FileIOResult buf_result = platform_write(this, buf, pos);
     if (buf_result.has_error() || buf_result.value < pos) {
@@ -444,7 +525,8 @@ ErrorOr<int> File::seek_unlocked(off_t offset, int whence) {
   return 0;
 }
 
-ErrorOr<off_t> File::tell_unlocked() {
+template <typename Platform>
+ErrorOr<off_t> FileImpl<Platform>::tell_unlocked() {
   int seek_target = (eof || (mode.is_append() && prev_op == FileOp::WRITE))
                         ? SEEK_END
                         : SEEK_CUR;
@@ -461,7 +543,9 @@ ErrorOr<off_t> File::tell_unlocked() {
   return platform_offset;
 }
 
-ErrorOr<File::Position> File::get_pos_unlocked() {
+template <typename Platform>
+ErrorOr<typename FileImpl<Platform>::Position>
+FileImpl<Platform>::get_pos_unlocked() {
   auto pos_result = tell_unlocked();
   if (!pos_result.has_value())
     return Error(pos_result.error());
@@ -472,7 +556,8 @@ ErrorOr<File::Position> File::get_pos_unlocked() {
   };
 }
 
-ErrorOr<int> File::set_pos_unlocked(const Position &fpos) {
+template <typename Platform>
+ErrorOr<int> FileImpl<Platform>::set_pos_unlocked(const Position &fpos) {
   auto result = seek_unlocked(fpos.offset, SEEK_SET);
   if (!result.has_value())
     return Error(result.error());
@@ -481,7 +566,7 @@ ErrorOr<int> File::set_pos_unlocked(const Position &fpos) {
   return 0;
 }
 
-int File::flush_unlocked() {
+template <typename Platform> int FileImpl<Platform>::flush_unlocked() {
   if (prev_op == FileOp::WRITE && pos > 0) {
     FileIOResult buf_result = platform_write(this, buf, pos);
     if (buf_result.has_error() || buf_result.value < pos) {
@@ -506,7 +591,7 @@ int File::flush_unlocked() {
 // 1. If in write mode, Write out any data present in the buffer.
 // 2. Call platform_close.
 // platform_close is expected to cleanup the complete file object.
-int File::close() {
+template <typename Platform> int FileImpl<Platform>::close() {
   {
     FileLock lock(this);
     if (prev_op == FileOp::WRITE && pos > 0) {
@@ -531,7 +616,8 @@ int File::close() {
   return platform_close(this);
 }
 
-int File::set_buffer(void *buffer, size_t size, int buffer_mode) {
+template <typename Platform>
+int FileImpl<Platform>::set_buffer(void *buffer, size_t size, int buffer_mode) {
   // We do not need to lock the file as this method should be called before
   // other operations are performed on the file.
   if (buffer != nullptr && size == 0)
@@ -587,7 +673,8 @@ int File::set_buffer(void *buffer, size_t size, int buffer_mode) {
   return 0;
 }
 
-FileIOResult File::write_unlocked(const wchar_t *ws, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::write_unlocked(const wchar_t *ws, size_t len) {
   switch (orientation) {
   case Orientation::BYTE:
     err = true;
@@ -632,7 +719,8 @@ FileIOResult File::write_unlocked(const wchar_t *ws, size_t len) {
   return {written, 0};
 }
 
-FileIOResult File::read_unlocked(wchar_t *ws, size_t len) {
+template <typename Platform>
+FileIOResult FileImpl<Platform>::read_unlocked(wchar_t *ws, size_t len) {
   switch (orientation) {
   case Orientation::BYTE:
     err = true;
@@ -675,7 +763,8 @@ FileIOResult File::read_unlocked(wchar_t *ws, size_t len) {
   return {read_count, 0};
 }
 
-ErrorOr<wint_t> File::ungetwc_unlocked(wint_t wc) {
+template <typename Platform>
+ErrorOr<wint_t> FileImpl<Platform>::ungetwc_unlocked(wint_t wc) {
   // There is no meaning to unget if:
   // 1. You are trying to push back EOF.
   // 2. Read operations are not allowed on this file.
@@ -723,3 +812,5 @@ ErrorOr<wint_t> File::ungetwc_unlocked(wint_t wc) {
 }
 
 } // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_FILE_FILE_IMPL_H
diff --git a/libc/src/__support/File/linux/CMakeLists.txt b/libc/src/__support/File/linux/CMakeLists.txt
index 8ae1757f69d870..b3955ab0873a68 100644
--- a/libc/src/__support/File/linux/CMakeLists.txt
+++ b/libc/src/__support/File/linux/CMakeLists.txt
@@ -5,14 +5,16 @@ add_object_library(
     file.cpp
   HDRS
     file.h
+    ../platform_file.h
   DEPENDS
     libc.hdr.errno_macros
     libc.hdr.fcntl_macros
     libc.hdr.func.free
+    libc.hdr.stdint_proxy
     libc.hdr.stdio_macros
-    libc.hdr.types.mode_t
     libc.hdr.sys_stat_macros
     libc.hdr.types.FILE
+    libc.hdr.types.mode_t
     libc.hdr.types.off_t
     libc.src.__support.alloc_checker
     libc.src.__support.CPP.new
diff --git a/libc/src/__support/File/linux/file.cpp b/libc/src/__support/File/linux/file.cpp
index 8e5f189559c71c..6f73c63f812e65 100644
--- a/libc/src/__support/File/linux/file.cpp
+++ b/libc/src/__support/File/linux/file.cpp
@@ -19,6 +19,7 @@
 #include "hdr/types/off_t.h"
 #include "src/__support/CPP/new.h"
 #include "src/__support/File/file.h"
+#include "src/__support/File/file_impl.h"
 #include "src/__support/File/file_mode.h"
 #include "src/__support/OSUtil/linux/syscall_wrappers/close.h"
 #include "src/__support/OSUtil/linux/syscall_wrappers/dup3.h"
@@ -31,8 +32,8 @@
 
 namespace LIBC_NAMESPACE_DECL {
 
-FileIOResult linux_file_write(File *f, const void *data, size_t size) {
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+FileIOResult FilePlatform::write(File *f, const void *data, size_t size) {
+  auto *lf = static_cast<LinuxFile *>(f);
   auto ret = linux_syscalls::write(lf->get_fd(), data, size);
   if (!ret) {
     return {0, ret.error()};
@@ -40,8 +41,8 @@ FileIOResult linux_file_write(File *f, const void *data, size_t size) {
   return static_cast<size_t>(ret.value());
 }
 
-FileIOResult linux_file_read(File *f, void *buf, size_t size) {
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+FileIOResult FilePlatform::read(File *f, void *buf, size_t size) {
+  auto *lf = static_cast<LinuxFile *>(f);
   auto ret = linux_syscalls::read(lf->get_fd(), buf, size);
   if (!ret) {
     return {0, ret.error()};
@@ -49,8 +50,8 @@ FileIOResult linux_file_read(File *f, void *buf, size_t size) {
   return static_cast<size_t>(ret.value());
 }
 
-ErrorOr<off_t> linux_file_seek(File *f, off_t offset, int whence) {
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+ErrorOr<off_t> FilePlatform::seek(File *f, off_t offset, int whence) {
+  auto *lf = static_cast<LinuxFile *>(f);
   return linux_syscalls::lseek(lf->get_fd(), offset, whence);
 }
 
@@ -66,14 +67,19 @@ int LinuxFile::close_fd() {
   return 0;
 }
 
-int linux_file_close(File *f) {
+int FilePlatform::close(File *f) {
   File::remove_file(f);
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+  auto *lf = static_cast<LinuxFile *>(f);
   int retval = lf->close_fd();
   delete lf;
   return retval;
 }
 
+template class FileImpl<FilePlatform>;
+
+static_assert(sizeof(void *) < 8 || sizeof(LinuxFile) == sizeof(File),
+              "LinuxFile::fd must pack into FileImpl's 64-bit tail padding");
+
 static int map_c_mode_flags_to_linux_open_flags(const FileMode &file_mode) {
   int open_flags = 0;
 
@@ -191,6 +197,19 @@ int LinuxFile::reopen_unlocked(const char *path, const char *mode) {
   const FileMode file_mode(mode);
 
   if (path != nullptr) {
+    // GNU fopencookie streams (DispatchKind::COOKIE) carry CookieOps rather
+    // than FileOps and are not backed by an OS file descriptor.
+    if (get_dispatch_kind() == DispatchKind::COOKIE)
+      return file_mode.is_valid() ? EBADF : EINVAL;
+
+    // Tear down CustomFile-specific state (such as fmemopen's buffer ownership
+    // or popen's pipe list registration) and rebind I/O to FilePlatform
+    // while preserving the derived class's close deleter.
+    if (get_dispatch_kind() == DispatchKind::CUSTOM) {
+      static_cast<CustomFile *>(this)->rebind_ops(
+          &FilePlatform::write, &FilePlatform::read, &FilePlatform::seek);
+    }
+
     int old_fd = get_fd();
 
     if (!file_mode.is_valid()) {
@@ -289,31 +308,19 @@ int LinuxFile::reopen_unlocked(const char *path, const char *mode) {
   reset_stream_state_unlocked(file_mode);
 
   if (do_seek) {
-    auto seek_result = linux_file_seek(this, 0, SEEK_END);
+    auto seek_result = FilePlatform::seek(this, 0, SEEK_END);
     if (!seek_result.has_value())
       return seek_result.error();
   }
   return 0;
 }
 
-bool is_linux_file(const File *f) {
-  // Any LinuxFile (including subtypes like the popen stream, which only swaps
-  // the close callback) registers at least one of these linux_file_* callbacks,
-  // and no non-Linux File (CookieFile/MemoryFile) uses any of them. So a match
-  // on any single callback positively identifies a LinuxFile that has an fd.
-  return f->get_read_func() == &linux_file_read ||
-         f->get_write_func() == &linux_file_write ||
-         f->get_seek_func() == &linux_file_seek ||
-         f->get_close_func() == &linux_file_close;
-}
-
 ErrorOr<int> get_fileno(File *f) {
-  if (!is_linux_file(f))
-    return Error(EBADF);
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+  auto *lf = static_cast<LinuxFile *>(f);
   int fd = lf->get_fd();
-  // freopen can fail and leave an otherwise-normal LinuxFile with fd == -1.
-  if (fd == -1)
+  // Dynamic non-fd streams (MemoryFile, CookieFile) initialize fd to -1, and
+  // freopen can also fail and leave a LinuxFile with fd == -1.
+  if (fd < 0)
     return Error(EBADF);
   return fd;
 }
@@ -324,7 +331,7 @@ int reopenfile(File *f, const char *path, const char *mode) {
 }
 
 int reopenfile_unlocked(File *f, const char *path, const char *mode) {
-  auto *lf = reinterpret_cast<LinuxFile *>(f);
+  auto *lf = static_cast<LinuxFile *>(f);
   return lf->reopen_unlocked(path, mode);
 }
 
diff --git a/libc/src/__support/File/linux/file.h b/libc/src/__support/File/linux/file.h
index 97a675eaf9625b..e3bf83f29889af 100644
--- a/libc/src/__support/File/linux/file.h
+++ b/libc/src/__support/File/linux/file.h
@@ -27,29 +27,27 @@
 
 namespace LIBC_NAMESPACE_DECL {
 
-FileIOResult linux_file_write(File *, const void *, size_t);
-FileIOResult linux_file_read(File *, void *, size_t);
-ErrorOr<off_t> linux_file_seek(File *, off_t, int);
-int linux_file_close(File *);
+class LinuxFile;
 
-// Returns true iff |f| is actually a LinuxFile, as opposed to some other
-// File subclass (e.g. CookieFile, MemoryFile) that doesn't have a real
-// file descriptor. Used because File has no RTTI/type tag: every LinuxFile
-// always registers these exact four callbacks, and no other subclass does.
-bool is_linux_file(const File *f);
+struct FilePlatform {
+  using StreamBase = LinuxFile;
+
+  static FileIOResult write(File *f, const void *data, size_t size);
+  static FileIOResult read(File *f, void *buf, size_t size);
+  static ErrorOr<off_t> seek(File *f, off_t offset, int whence);
+  static int close(File *f);
+};
 
 class LinuxFile : public File {
   int fd;
 
-  friend int linux_file_close(File *);
+  friend struct FilePlatform;
 
 protected:
-  // For subclasses which need to do extra cleanup when the file is closed.
-  constexpr LinuxFile(int file_descriptor, uint8_t *buffer, size_t buffer_size,
-                      int buffer_mode, bool owned, FileMode mode,
-                      CloseFunc *close_func)
-      : File(&linux_file_write, &linux_file_read, &linux_file_seek, close_func,
-             buffer, buffer_size, buffer_mode, owned, mode),
+  constexpr LinuxFile(DispatchKind dispatch_kind, uint8_t *buffer,
+                      size_t buffer_size, int buffer_mode, bool owned,
+                      FileMode mode, int file_descriptor = -1)
+      : File(dispatch_kind, buffer, buffer_size, buffer_mode, owned, mode),
         fd(file_descriptor) {}
 
   // Closes the underlying file descriptor. Returns 0 on success, or an error
@@ -59,8 +57,8 @@ class LinuxFile : public File {
 public:
   constexpr LinuxFile(int file_descriptor, uint8_t *buffer, size_t buffer_size,
                       int buffer_mode, bool owned, FileMode mode)
-      : LinuxFile(file_descriptor, buffer, buffer_size, buffer_mode, owned,
-                  mode, &linux_file_close) {}
+      : File(buffer, buffer_size, buffer_mode, owned, mode),
+        fd(file_descriptor) {}
 
   // Allocates a FileT owning a new default-size buffer. FileT must be
   // LinuxFile or a subclass with LinuxFile's constructor signature.
@@ -92,6 +90,9 @@ class LinuxFile : public File {
   int reopen_unlocked(const char *path, const char *mode);
 };
 
+using CustomFile = CustomFileImpl<LinuxFile>;
+using CookieFile = CookieFileImpl<LinuxFile>;
+
 // Create a File object and associate it with a fd.
 ErrorOr<LinuxFile *> create_file_from_fd(int fd, const char *mode);
 
diff --git a/libc/src/__support/File/linux/popen_file.cpp b/libc/src/__support/File/linux/popen_file.cpp
index 66d1d396724548..85fb932d919f3b 100644
--- a/libc/src/__support/File/linux/popen_file.cpp
+++ b/libc/src/__support/File/linux/popen_file.cpp
@@ -37,10 +37,8 @@ void PopenFile::close_popen_list_fds_unlocked() {
     f->close_fd();
 }
 
-int PopenFile::popen_file_close(File *f) {
-  File::remove_file(f);
-
-  auto *pf = reinterpret_cast<PopenFile *>(f);
+int PopenFile::popen_file_detach_impl(File *f) {
+  auto *pf = static_cast<PopenFile *>(f);
   lock_popen_list();
   if (pf->popen_prev != nullptr)
     pf->popen_prev->popen_next = pf->popen_next;
@@ -48,12 +46,22 @@ int PopenFile::popen_file_close(File *f) {
     pf->popen_next->popen_prev = pf->popen_prev;
   if (popen_list == pf)
     popen_list = pf->popen_next;
+  pf->popen_prev = nullptr;
+  pf->popen_next = nullptr;
   // Close the fd before unlocking so a concurrent popen cannot fork and
   // inherit an fd that has already been removed from popen_list.
   int retval = pf->close_fd();
+  pf->set_fd(-1);
   unlock_popen_list();
+  return retval;
+}
+
+void PopenFile::popen_file_detach(File *f) { (void)popen_file_detach_impl(f); }
 
-  delete pf;
+int PopenFile::popen_file_close(File *f) {
+  File::remove_file(f);
+  int retval = popen_file_detach_impl(f);
+  delete static_cast<PopenFile *>(f);
   return retval;
 }
 
diff --git a/libc/src/__support/File/linux/popen_file.h b/libc/src/__support/File/linux/popen_file.h
index 9c959b069c52dc..8d73cc5e55a2c3 100644
--- a/libc/src/__support/File/linux/popen_file.h
+++ b/libc/src/__support/File/linux/popen_file.h
@@ -26,7 +26,7 @@ namespace LIBC_NAMESPACE_DECL {
 // A LinuxFile connected to a pipe to a child process created by popen. Open
 // popen streams are kept on their own list, so that each new popen child can
 // close the streams of earlier popen calls.
-class PopenFile : public LinuxFile {
+class PopenFile : public CustomFile {
   pid_t pid = -1;
   PopenFile *popen_prev = nullptr;
   PopenFile *popen_next = nullptr;
@@ -34,6 +34,11 @@ class PopenFile : public LinuxFile {
   static PopenFile *popen_list;
   static Mutex popen_list_lock;
 
+  // Detaches |f| from the popen list and closes its pipe descriptor without
+  // freeing |f|.
+  static int popen_file_detach_impl(File *f);
+  static void popen_file_detach(File *f);
+
   // Removes |f| from the popen list, then closes and frees it like a
   // LinuxFile. This does not wait for the child process.
   static int popen_file_close(File *f);
@@ -41,8 +46,10 @@ class PopenFile : public LinuxFile {
 public:
   PopenFile(int file_descriptor, uint8_t *buffer, size_t buffer_size,
             int buffer_mode, bool owned, FileMode mode)
-      : LinuxFile(file_descriptor, buffer, buffer_size, buffer_mode, owned,
-                  mode, &popen_file_close) {}
+      : CustomFile({&FilePlatform::write, &FilePlatform::read,
+                    &FilePlatform::seek, &popen_file_close, &popen_file_detach},
+                   buffer, buffer_size, buffer_mode, owned, mode,
+                   file_descriptor) {}
 
   pid_t get_pid() const { return pid; }
   void set_pid(pid_t new_pid) { pid = new_pid; }
diff --git a/libc/src/__support/File/platform_file.h b/libc/src/__support/File/platform_file.h
new file mode 100644
index 00000000000000..0acb13ee0ddc2c
--- /dev/null
+++ b/libc/src/__support/File/platform_file.h
@@ -0,0 +1,23 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// Platform-specific File specialization dispatch header.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_FILE_PLATFORM_FILE_H
+#define LLVM_LIBC_SRC___SUPPORT_FILE_PLATFORM_FILE_H
+
+#if defined(__linux__)
+#include "src/__support/File/linux/file.h"
+#else
+#error "Platform File specialization is not available on this target."
+#endif
+
+#endif // LLVM_LIBC_SRC___SUPPORT_FILE_PLATFORM_FILE_H
diff --git a/libc/src/stdio/CMakeLists.txt b/libc/src/stdio/CMakeLists.txt
index 4429bcca0338c1..ecff967fbcff41 100644
--- a/libc/src/stdio/CMakeLists.txt
+++ b/libc/src/stdio/CMakeLists.txt
@@ -103,6 +103,7 @@ add_entrypoint_object(
     libc.src.__support.CPP.algorithm
     libc.src.__support.CPP.new
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.alloc_checker
     libc.src.__support.libc_errno
     libc.src.__support.macros.null_check
@@ -116,14 +117,14 @@ add_entrypoint_object(
   HDRS
     fopencookie.h
   DEPENDS
-    libc.hdr.errno_macros
+    libc.hdr.func.free
     libc.hdr.stdio_macros
-    libc.hdr.types.off_t
-    libc.hdr.types.ssize_t
     libc.hdr.types.cookie_io_functions_t
     libc.hdr.types.FILE
     libc.src.__support.CPP.new
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
+    libc.src.__support.alloc_checker
 )
 
 add_entrypoint_object(
diff --git a/libc/src/stdio/fmemopen.cpp b/libc/src/stdio/fmemopen.cpp
index 903c65393a4688..b0be02d70a6034 100644
--- a/libc/src/stdio/fmemopen.cpp
+++ b/libc/src/stdio/fmemopen.cpp
@@ -21,7 +21,9 @@
 #include "src/__support/CPP/new.h"
 #include "src/__support/File/file.h"
 #include "src/__support/File/file_mode.h"
+#include "src/__support/File/platform_file.h"
 #include "src/__support/alloc-checker.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"
@@ -30,7 +32,7 @@
 namespace LIBC_NAMESPACE_DECL {
 namespace {
 
-class MemoryFile : public File {
+class MemoryFile : public CustomFile {
   // The stdio buffer is separate from the memory used as the file's contents.
   // In particular, ungetc and setvbuf must not modify or free that memory.
   uint8_t stream_buffer[DEFAULT_BUFFER_SIZE];
@@ -40,9 +42,10 @@ class MemoryFile : public File {
   size_t end = 0;
   bool owns_storage;
   bool append;
+  bool detached = false;
 
   static FileIOResult memory_read(File *f, void *data, size_t size) {
-    auto *mf = reinterpret_cast<MemoryFile *>(f);
+    auto *mf = static_cast<MemoryFile *>(f);
     if (size == 0 || mf->position >= mf->end)
       return 0;
     size_t available = mf->end - mf->position;
@@ -53,7 +56,7 @@ class MemoryFile : public File {
   }
 
   static FileIOResult memory_write(File *f, const void *data, size_t size) {
-    auto *mf = reinterpret_cast<MemoryFile *>(f);
+    auto *mf = static_cast<MemoryFile *>(f);
     if (size == 0)
       return 0;
     size_t start = mf->append ? mf->end : mf->position;
@@ -75,7 +78,7 @@ class MemoryFile : public File {
   }
 
   static ErrorOr<off_t> memory_seek(File *f, off_t offset, int whence) {
-    auto *mf = reinterpret_cast<MemoryFile *>(f);
+    auto *mf = static_cast<MemoryFile *>(f);
     size_t base;
     switch (whence) {
     case SEEK_SET:
@@ -102,20 +105,31 @@ class MemoryFile : public File {
     return static_cast<off_t>(next);
   }
 
+  static void memory_detach(File *f) {
+    auto *mf = static_cast<MemoryFile *>(f);
+    if (mf->owns_storage) {
+      delete[] mf->storage;
+      mf->storage = nullptr;
+      mf->owns_storage = false;
+    }
+    mf->detached = true;
+  }
+
   static int memory_close(File *f) {
-    auto *mf = reinterpret_cast<MemoryFile *>(f);
+    auto *mf = static_cast<MemoryFile *>(f);
     File::remove_file(mf);
-    if (mf->owns_storage)
-      delete[] mf->storage;
+    int retval = mf->detached ? mf->close_fd() : 0;
+    memory_detach(mf);
     delete mf;
-    return 0;
+    return retval;
   }
 
 public:
   MemoryFile(uint8_t *storage, size_t capacity, bool owns_storage,
              FileMode mode)
-      : File(&memory_write, &memory_read, &memory_seek, &memory_close,
-             stream_buffer, sizeof(stream_buffer), _IOFBF, false, mode),
+      : CustomFile({&memory_write, &memory_read, &memory_seek, &memory_close,
+                    &memory_detach},
+                   stream_buffer, sizeof(stream_buffer), _IOFBF, false, mode),
         storage(storage), capacity(capacity), owns_storage(owns_storage),
         append(mode.is_append()) {
     if (mode.is_read()) {
diff --git a/libc/src/stdio/fopencookie.cpp b/libc/src/stdio/fopencookie.cpp
index c8194c03d67aff..f8fee874de8b47 100644
--- a/libc/src/stdio/fopencookie.cpp
+++ b/libc/src/stdio/fopencookie.cpp
@@ -12,88 +12,21 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/stdio/fopencookie.h"
-#include "hdr/errno_macros.h"
+
+#include "hdr/func/free.h"
 #include "hdr/stdio_macros.h"
 #include "hdr/types/FILE.h"
 #include "hdr/types/cookie_io_functions_t.h"
-#include "hdr/types/off_t.h"
-#include "hdr/types/ssize_t.h"
 #include "src/__support/CPP/new.h"
 #include "src/__support/File/file.h"
 #include "src/__support/File/file_mode.h"
+#include "src/__support/File/platform_file.h"
 #include "src/__support/alloc-checker.h"
-
-#include "hdr/errno_macros.h"
+#include "src/__support/common.h"
 #include "src/__support/macros/config.h"
 
 namespace LIBC_NAMESPACE_DECL {
 
-namespace {
-
-class CookieFile : public LIBC_NAMESPACE::File {
-  void *cookie;
-  cookie_io_functions_t ops;
-
-  static FileIOResult cookie_write(File *f, const void *data, size_t size);
-  static FileIOResult cookie_read(File *f, void *data, size_t size);
-  static ErrorOr<off_t> cookie_seek(File *f, off_t offset, int whence);
-  static int cookie_close(File *f);
-
-public:
-  CookieFile(void *c, cookie_io_functions_t cops, uint8_t *buffer,
-             size_t bufsize, FileMode mode)
-      : File(&cookie_write, &cookie_read, &CookieFile::cookie_seek,
-             &cookie_close, buffer, bufsize, 0 /* default buffering mode */,
-             true /* File owns buffer */, mode),
-        cookie(c), ops(cops) {}
-};
-
-FileIOResult CookieFile::cookie_write(File *f, const void *data, size_t size) {
-  auto cookie_file = reinterpret_cast<CookieFile *>(f);
-  if (cookie_file->ops.write == nullptr)
-    return 0;
-  ssize_t result = cookie_file->ops.write(
-      cookie_file->cookie, reinterpret_cast<const char *>(data), size);
-  if (result < 0)
-    return {0, EIO};
-  return static_cast<size_t>(result);
-}
-
-FileIOResult CookieFile::cookie_read(File *f, void *data, size_t size) {
-  auto cookie_file = reinterpret_cast<CookieFile *>(f);
-  if (cookie_file->ops.read == nullptr)
-    return 0;
-  ssize_t result = cookie_file->ops.read(cookie_file->cookie,
-                                         reinterpret_cast<char *>(data), size);
-  if (result < 0)
-    return {0, EIO};
-  return static_cast<size_t>(result);
-}
-
-ErrorOr<off_t> CookieFile::cookie_seek(File *f, off_t offset, int whence) {
-  auto cookie_file = reinterpret_cast<CookieFile *>(f);
-  if (cookie_file->ops.seek == nullptr) {
-    return Error(EINVAL);
-  }
-  int result = cookie_file->ops.seek(cookie_file->cookie, &offset, whence);
-  if (result == 0)
-    return offset;
-  return Error(EIO);
-}
-
-int CookieFile::cookie_close(File *f) {
-  auto cookie_file = reinterpret_cast<CookieFile *>(f);
-  if (cookie_file->ops.close == nullptr)
-    return 0;
-  int retval = cookie_file->ops.close(cookie_file->cookie);
-  if (retval != 0)
-    return retval;
-  delete cookie_file;
-  return 0;
-}
-
-} // anonymous namespace
-
 LLVM_LIBC_FUNCTION(::FILE *, fopencookie,
                    (void *cookie, const char *mode,
                     cookie_io_functions_t ops)) {
@@ -105,10 +38,15 @@ LLVM_LIBC_FUNCTION(::FILE *, fopencookie,
       return nullptr;
   }
   AllocChecker ac;
-  auto *file = new (ac) CookieFile(cookie, ops, buffer,
-                                   File::DEFAULT_BUFFER_SIZE, FileMode(mode));
-  if (!ac)
+  auto *file =
+      new (ac) CookieFile(cookie, {ops.read, ops.write, ops.seek, ops.close},
+                          buffer, File::DEFAULT_BUFFER_SIZE, _IOFBF,
+                          /*owned=*/true, FileMode(mode));
+  if (!ac) {
+    free(buffer);
     return nullptr;
+  }
+  File::add_file(file);
   return reinterpret_cast<::FILE *>(file);
 }
 
diff --git a/libc/src/stdio/generic/CMakeLists.txt b/libc/src/stdio/generic/CMakeLists.txt
index 78d24e7dd75566..0ec87e81f4c314 100644
--- a/libc/src/stdio/generic/CMakeLists.txt
+++ b/libc/src/stdio/generic/CMakeLists.txt
@@ -143,6 +143,7 @@ add_generic_entrypoint_object(
     libc.hdr.types.mbstate_t
     libc.src.__support.CPP.type_traits
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.error_or
     libc.src.__support.libc_errno
@@ -164,6 +165,7 @@ add_generic_entrypoint_object(
     libc.hdr.types.mbstate_t
     libc.src.__support.CPP.type_traits
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.error_or
     libc.src.__support.libc_errno
diff --git a/libc/src/wchar/CMakeLists.txt b/libc/src/wchar/CMakeLists.txt
index 23698eee25aae2..2a36fd743ed4a8 100644
--- a/libc/src/wchar/CMakeLists.txt
+++ b/libc/src/wchar/CMakeLists.txt
@@ -590,6 +590,7 @@ add_entrypoint_object(
   DEPENDS
     libc.hdr.types.FILE
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.macros.config
     libc.src.__support.macros.null_check
@@ -607,6 +608,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -625,6 +627,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -641,6 +644,7 @@ add_entrypoint_object(
     libc.hdr.types.FILE
     libc.hdr.types.wchar_t
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -658,6 +662,7 @@ add_entrypoint_object(
     libc.hdr.types.FILE
     libc.hdr.types.wchar_t
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -675,6 +680,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -693,6 +699,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -711,6 +718,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -729,6 +737,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
@@ -747,6 +756,7 @@ add_entrypoint_object(
     libc.hdr.types.wint_t
     libc.hdr.wchar_macros
     libc.src.__support.File.file
+    libc.src.__support.File.platform_file
     libc.src.__support.common
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
diff --git a/libc/test/src/__support/File/CMakeLists.txt b/libc/test/src/__support/File/CMakeLists.txt
index f880fe0ef2f527..6cb689e417099f 100644
--- a/libc/test/src/__support/File/CMakeLists.txt
+++ b/libc/test/src/__support/File/CMakeLists.txt
@@ -13,9 +13,13 @@ add_libc_test(
     file_test.cpp
   DEPENDS
     libc.include.stdio
+    libc.hdr.errno_macros
     libc.hdr.wchar_macros
     libc.hdr.types.size_t
+    libc.hdr.types.ssize_t
+    libc.src.__support.alloc_checker
     libc.src.__support.CPP.new
+    libc.src.__support.CPP.scope
     libc.src.__support.File.file
     libc.src.__support.error_or
     libc.test.UnitTest.MemoryMatcher
diff --git a/libc/test/src/__support/File/file_test.cpp b/libc/test/src/__support/File/file_test.cpp
index a02138ff1751d4..395f87de41b62f 100644
--- a/libc/test/src/__support/File/file_test.cpp
+++ b/libc/test/src/__support/File/file_test.cpp
@@ -6,10 +6,14 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "hdr/errno_macros.h"
 #include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
 #include "hdr/wchar_macros.h"
 #include "src/__support/CPP/new.h"
+#include "src/__support/CPP/scope.h"
 #include "src/__support/File/file.h"
+#include "src/__support/File/file_impl.h"
 #include "src/__support/File/file_mode.h"
 #include "src/__support/alloc-checker.h"
 #include "src/__support/error_or.h"
@@ -18,34 +22,142 @@
 #include "test/UnitTest/Test.h"
 
 using MemoryView = LIBC_NAMESPACE::testing::MemoryView;
+using LIBC_NAMESPACE::CookieOps;
+using LIBC_NAMESPACE::Error;
 using LIBC_NAMESPACE::ErrorOr;
-using LIBC_NAMESPACE::File;
 using LIBC_NAMESPACE::FileIOResult;
 using LIBC_NAMESPACE::FileMode;
+using LIBC_NAMESPACE::cpp::scope_exit;
 
-class StringFile : public File {
+struct TestFilePlatform;
+using TestFile = LIBC_NAMESPACE::FileImpl<TestFilePlatform>;
+using TestCustomFile = LIBC_NAMESPACE::CustomFileImpl<TestFile>;
+using TestCookieFile = LIBC_NAMESPACE::CookieFileImpl<TestFile>;
+
+struct TestFilePlatform {
+  using StreamBase = TestFile;
+
+  static FileIOResult write(TestFile *f, const void *data, size_t len);
+  static FileIOResult read(TestFile *f, void *data, size_t len);
+  static ErrorOr<off_t> seek(TestFile *f, off_t offset, int whence);
+  static int close(TestFile *f);
+};
+
+static_assert(sizeof(TestCustomFile) ==
+              sizeof(TestFile) + sizeof(TestFile::Ops));
+static_assert(sizeof(TestCookieFile) ==
+              sizeof(TestFile) + sizeof(void *) + sizeof(CookieOps));
+
+class StaticBufferFile : public TestFile {
+  static constexpr size_t SIZE = 512;
+  size_t pos = 0;
+  char str[SIZE] = {0};
+  size_t eof_marker = 0;
+  bool write_append = false;
+  size_t *write_calls = nullptr;
+  size_t *read_calls = nullptr;
+  size_t *seek_calls = nullptr;
+  size_t *close_calls = nullptr;
+
+  friend struct TestFilePlatform;
+
+public:
+  StaticBufferFile(char *buffer, size_t buflen, int bufmode, bool owned,
+                   FileMode mode, size_t *writes = nullptr,
+                   size_t *reads = nullptr, size_t *seeks = nullptr,
+                   size_t *closes = nullptr)
+      : TestFile(reinterpret_cast<uint8_t *>(buffer), buflen, bufmode, owned,
+                 mode),
+        write_append(mode.is_append()), write_calls(writes), read_calls(reads),
+        seek_calls(seeks), close_calls(closes) {}
+
+  size_t get_pos() const { return pos; }
+  char *get_str() { return str; }
+
+  void reset_and_fill(const char *data, size_t len) {
+    size_t i = 0;
+    for (; i < len && i < SIZE; ++i)
+      str[i] = data[i];
+    pos = 0;
+    eof_marker = i;
+  }
+};
+
+FileIOResult TestFilePlatform::write(TestFile *f, const void *data,
+                                     size_t len) {
+  auto *sf = static_cast<StaticBufferFile *>(f);
+  if (sf->write_calls != nullptr)
+    ++(*sf->write_calls);
+  if (sf->write_append)
+    sf->pos = sf->eof_marker;
+  if (sf->pos >= StaticBufferFile::SIZE)
+    return 0;
+  size_t i = 0;
+  for (; i < len && sf->pos < StaticBufferFile::SIZE; ++i, ++sf->pos)
+    sf->str[sf->pos] = reinterpret_cast<const char *>(data)[i];
+  if (sf->pos > sf->eof_marker)
+    sf->eof_marker = sf->pos;
+  return i;
+}
+
+FileIOResult TestFilePlatform::read(TestFile *f, void *data, size_t len) {
+  auto *sf = static_cast<StaticBufferFile *>(f);
+  if (sf->read_calls != nullptr)
+    ++(*sf->read_calls);
+  if (sf->pos >= sf->eof_marker)
+    return 0;
+  size_t avail = sf->eof_marker - sf->pos;
+  size_t to_copy = len < avail ? len : avail;
+  for (size_t i = 0; i < to_copy; ++i)
+    reinterpret_cast<char *>(data)[i] = sf->str[sf->pos + i];
+  sf->pos += to_copy;
+  return to_copy;
+}
+
+ErrorOr<off_t> TestFilePlatform::seek(TestFile *f, off_t offset, int whence) {
+  auto *sf = static_cast<StaticBufferFile *>(f);
+  if (sf->seek_calls != nullptr)
+    ++(*sf->seek_calls);
+  if (whence == SEEK_SET)
+    sf->pos = static_cast<size_t>(offset);
+  else if (whence == SEEK_CUR)
+    sf->pos = static_cast<size_t>(static_cast<off_t>(sf->pos) + offset);
+  else if (whence == SEEK_END)
+    sf->pos = static_cast<size_t>(sf->eof_marker + offset);
+  else
+    return Error(EINVAL);
+  return static_cast<off_t>(sf->pos);
+}
+
+int TestFilePlatform::close(TestFile *f) {
+  auto *sf = static_cast<StaticBufferFile *>(f);
+  if (sf->close_calls != nullptr)
+    ++(*sf->close_calls);
+  delete sf;
+  return 0;
+}
+
+class StringFile : public TestCustomFile {
   static constexpr size_t SIZE = 512;
   size_t pos;
   char str[SIZE] = {0};
   size_t eof_marker;
   bool write_append;
 
-  static FileIOResult str_read(LIBC_NAMESPACE::File *f, void *data, size_t len);
-  static FileIOResult str_write(LIBC_NAMESPACE::File *f, const void *data,
-                                size_t len);
-  static ErrorOr<off_t> str_seek(LIBC_NAMESPACE::File *f, off_t offset,
-                                 int whence);
-  static int str_close(LIBC_NAMESPACE::File *f) {
-    delete reinterpret_cast<StringFile *>(f);
+  static FileIOResult str_read(TestFile *f, void *data, size_t len);
+  static FileIOResult str_write(TestFile *f, const void *data, size_t len);
+  static ErrorOr<off_t> str_seek(TestFile *f, off_t offset, int whence);
+  static int str_close(TestFile *f) {
+    delete static_cast<StringFile *>(f);
     return 0;
   }
 
 public:
   explicit StringFile(char *buffer, size_t buflen, int bufmode, bool owned,
                       FileMode mode)
-      : LIBC_NAMESPACE::File(&str_write, &str_read, &str_seek, &str_close,
-                             reinterpret_cast<uint8_t *>(buffer), buflen,
-                             bufmode, owned, mode),
+      : TestCustomFile({&str_write, &str_read, &str_seek, &str_close},
+                       reinterpret_cast<uint8_t *>(buffer), buflen, bufmode,
+                       owned, mode),
         pos(0), eof_marker(0), write_append(false) {
     if (mode.is_append())
       write_append = true;
@@ -66,8 +178,7 @@ class StringFile : public File {
   }
 };
 
-FileIOResult StringFile::str_read(LIBC_NAMESPACE::File *f, void *data,
-                                  size_t len) {
+FileIOResult StringFile::str_read(TestFile *f, void *data, size_t len) {
   StringFile *sf = static_cast<StringFile *>(f);
   if (sf->pos >= sf->eof_marker)
     return 0;
@@ -78,8 +189,7 @@ FileIOResult StringFile::str_read(LIBC_NAMESPACE::File *f, void *data,
   return i;
 }
 
-FileIOResult StringFile::str_write(LIBC_NAMESPACE::File *f, const void *data,
-                                   size_t len) {
+FileIOResult StringFile::str_write(TestFile *f, const void *data, size_t len) {
   StringFile *sf = static_cast<StringFile *>(f);
   if (sf->write_append)
     sf->pos = sf->eof_marker;
@@ -94,13 +204,12 @@ FileIOResult StringFile::str_write(LIBC_NAMESPACE::File *f, const void *data,
   return i;
 }
 
-ErrorOr<off_t> StringFile::str_seek(LIBC_NAMESPACE::File *f, off_t offset,
-                                    int whence) {
+ErrorOr<off_t> StringFile::str_seek(TestFile *f, off_t offset, int whence) {
   StringFile *sf = static_cast<StringFile *>(f);
   if (whence == SEEK_SET)
     sf->pos = static_cast<size_t>(offset);
   else if (whence == SEEK_CUR)
-    sf->pos += offset;
+    sf->pos = static_cast<size_t>(static_cast<off_t>(sf->pos) + offset);
   else if (whence == SEEK_END)
     sf->pos = static_cast<size_t>(SIZE + offset);
   return sf->pos;
@@ -610,19 +719,20 @@ TEST(LlvmLibcFileTest, TrySetOrientation) {
   ASSERT_FALSE(f == nullptr);
 
   EXPECT_EQ(static_cast<uint32_t>(f->get_orientation()),
-            static_cast<uint32_t>(File::Orientation::UNORIENTED));
+            static_cast<uint32_t>(TestFile::Orientation::UNORIENTED));
 
-  EXPECT_EQ(
-      static_cast<uint32_t>(f->try_set_orientation(File::Orientation::WIDE)),
-      static_cast<uint32_t>(File::Orientation::WIDE));
+  EXPECT_EQ(static_cast<uint32_t>(
+                f->try_set_orientation(TestFile::Orientation::WIDE)),
+            static_cast<uint32_t>(TestFile::Orientation::WIDE));
   EXPECT_EQ(static_cast<uint32_t>(f->get_orientation()),
-            static_cast<uint32_t>(File::Orientation::WIDE));
+            static_cast<uint32_t>(TestFile::Orientation::WIDE));
 
   EXPECT_EQ(
-      static_cast<uint32_t>(f->try_set_orientation(File::Orientation::BYTE)),
-      static_cast<uint32_t>(File::Orientation::WIDE)); // Cannot change
+      static_cast<uint32_t>(
+          f->try_set_orientation(TestFile::Orientation::BYTE)),
+      static_cast<uint32_t>(TestFile::Orientation::WIDE)); // Cannot change
   EXPECT_EQ(static_cast<uint32_t>(f->get_orientation()),
-            static_cast<uint32_t>(File::Orientation::WIDE));
+            static_cast<uint32_t>(TestFile::Orientation::WIDE));
 
   ASSERT_EQ(f->close(), 0);
 }
@@ -769,7 +879,7 @@ TEST(LlvmLibcFileTest, UngetwcWEOF) {
   ASSERT_FALSE(f == nullptr);
 
   EXPECT_EQ(static_cast<uint32_t>(f->get_orientation()),
-            static_cast<uint32_t>(File::Orientation::UNORIENTED));
+            static_cast<uint32_t>(TestFile::Orientation::UNORIENTED));
 
   auto unget_res = f->ungetwc(WEOF);
   ASSERT_TRUE(unget_res.has_value());
@@ -777,22 +887,21 @@ TEST(LlvmLibcFileTest, UngetwcWEOF) {
             static_cast<uint32_t>(WEOF));
 
   EXPECT_EQ(static_cast<uint32_t>(f->get_orientation()),
-            static_cast<uint32_t>(File::Orientation::UNORIENTED));
+            static_cast<uint32_t>(TestFile::Orientation::UNORIENTED));
 
   ASSERT_EQ(f->close(), 0);
 }
 
-// A File subclass with a platform_write that simulates short writes.
+// A CustomFileImpl subclass with a write callback that simulates short writes.
 // This models the behavior of write(2) on pipes, sockets, or FIFOs where
 // the kernel may write fewer bytes than requested.
-class ShortWriteFile : public File {
+class ShortWriteFile : public TestCustomFile {
   static constexpr size_t SIZE = 512;
   size_t pos;
   char str[SIZE] = {0};
   size_t max_write;
 
-  static FileIOResult short_write(LIBC_NAMESPACE::File *f, const void *data,
-                                  size_t len) {
+  static FileIOResult short_write(TestFile *f, const void *data, size_t len) {
     ShortWriteFile *sf = static_cast<ShortWriteFile *>(f);
     // Simulate a short write: write at most max_write bytes per call.
     size_t to_write = len < sf->max_write ? len : sf->max_write;
@@ -801,8 +910,7 @@ class ShortWriteFile : public File {
     return to_write;
   }
 
-  static FileIOResult short_read(LIBC_NAMESPACE::File *f, void *data,
-                                 size_t len) {
+  static FileIOResult short_read(TestFile *f, void *data, size_t len) {
     ShortWriteFile *sf = static_cast<ShortWriteFile *>(f);
     size_t i = 0;
     for (i = 0; i < len && sf->pos < SIZE; ++i)
@@ -811,8 +919,7 @@ class ShortWriteFile : public File {
     return i;
   }
 
-  static ErrorOr<off_t> short_seek(LIBC_NAMESPACE::File *f, off_t offset,
-                                   int whence) {
+  static ErrorOr<off_t> short_seek(TestFile *f, off_t offset, int whence) {
     ShortWriteFile *sf = static_cast<ShortWriteFile *>(f);
     if (whence == SEEK_SET)
       sf->pos = static_cast<size_t>(offset);
@@ -823,17 +930,17 @@ class ShortWriteFile : public File {
     return sf->pos;
   }
 
-  static int short_close(LIBC_NAMESPACE::File *f) {
-    delete reinterpret_cast<ShortWriteFile *>(f);
+  static int short_close(TestFile *f) {
+    delete static_cast<ShortWriteFile *>(f);
     return 0;
   }
 
 public:
   explicit ShortWriteFile(char *buffer, size_t buflen, int bufmode, bool owned,
                           FileMode mode, size_t max_write_bytes)
-      : LIBC_NAMESPACE::File(&short_write, &short_read, &short_seek,
-                             &short_close, reinterpret_cast<uint8_t *>(buffer),
-                             buflen, bufmode, owned, mode),
+      : TestCustomFile({&short_write, &short_read, &short_seek, &short_close},
+                       reinterpret_cast<uint8_t *>(buffer), buflen, bufmode,
+                       owned, mode),
         pos(0), max_write(max_write_bytes) {}
 
   void reset() { pos = 0; }
@@ -873,7 +980,7 @@ TEST(LlvmLibcFileTest, FileLockRAII) {
   ASSERT_FALSE(f == nullptr);
 
   {
-    File::FileLock lock(f);
+    TestFile::FileLock lock(f);
     ASSERT_EQ(f->write_unlocked("abc", 3).value, size_t(3));
   }
 
@@ -883,19 +990,17 @@ TEST(LlvmLibcFileTest, FileLockRAII) {
   ASSERT_EQ(f->close(), 0);
 }
 
-class ShortReadFile : public File {
+class ShortReadFile : public TestCustomFile {
   const char *src;
   size_t src_len;
   size_t pos;
   size_t max_read;
 
-  static FileIOResult short_write(LIBC_NAMESPACE::File *, const void *,
-                                  size_t) {
+  static FileIOResult short_write(TestFile *, const void *, size_t) {
     return 0;
   }
 
-  static FileIOResult short_read(LIBC_NAMESPACE::File *f, void *data,
-                                 size_t len) {
+  static FileIOResult short_read(TestFile *f, void *data, size_t len) {
     ShortReadFile *sf = static_cast<ShortReadFile *>(f);
     if (sf->pos >= sf->src_len)
       return 0;
@@ -909,15 +1014,14 @@ class ShortReadFile : public File {
     return to_read;
   }
 
-  static ErrorOr<off_t> short_seek(LIBC_NAMESPACE::File *f, off_t offset,
-                                   int whence) {
+  static ErrorOr<off_t> short_seek(TestFile *f, off_t offset, int whence) {
     ShortReadFile *sf = static_cast<ShortReadFile *>(f);
     if (whence == SEEK_SET)
       sf->pos = static_cast<size_t>(offset);
     return sf->pos;
   }
 
-  static int short_close(LIBC_NAMESPACE::File *f) {
+  static int short_close(TestFile *f) {
     delete reinterpret_cast<ShortReadFile *>(f);
     return 0;
   }
@@ -926,9 +1030,9 @@ class ShortReadFile : public File {
   explicit ShortReadFile(char *buffer, size_t buflen, int bufmode,
                          const char *data, size_t data_len,
                          size_t max_read_bytes)
-      : LIBC_NAMESPACE::File(&short_write, &short_read, &short_seek,
-                             &short_close, reinterpret_cast<uint8_t *>(buffer),
-                             buflen, bufmode, false, FileMode("r")),
+      : TestCustomFile({&short_write, &short_read, &short_seek, &short_close},
+                       reinterpret_cast<uint8_t *>(buffer), buflen, bufmode,
+                       false, FileMode("r")),
         src(data), src_len(data_len), pos(0), max_read(max_read_bytes) {}
 };
 
@@ -1007,3 +1111,384 @@ TEST(LlvmLibcFileTest, RecursiveFileLock) {
 
   ASSERT_EQ(f->close(), 0);
 }
+
+TEST(LlvmLibcFileTest, StaticDispatch) {
+  constexpr char PAYLOAD[] = "static dispatch payload";
+  char stream_buf[16];
+  size_t writes = 0;
+  size_t reads = 0;
+  size_t seeks = 0;
+  size_t closes = 0;
+
+  LIBC_NAMESPACE::AllocChecker ac;
+  auto *f = new (ac) StaticBufferFile(stream_buf, sizeof(stream_buf), _IOFBF,
+                                      /*owned=*/false, FileMode("w+"), &writes,
+                                      &reads, &seeks, &closes);
+  ASSERT_NE(f, nullptr);
+  scope_exit close_f([&] { EXPECT_EQ(f->close(), 0); });
+  EXPECT_EQ(static_cast<uint8_t>(f->get_dispatch_kind()),
+            static_cast<uint8_t>(TestFile::DispatchKind::STATIC));
+  EXPECT_FALSE(f->is_dynamic());
+
+  ASSERT_EQ(f->write("hi", 2).value, size_t(2));
+  EXPECT_EQ(writes, size_t(0)); // Buffered before flush.
+  ASSERT_EQ(f->flush(), 0);
+  EXPECT_EQ(writes, size_t(1));
+
+  ASSERT_EQ(f->seek(0, SEEK_SET).value(), 0);
+  ASSERT_EQ(f->write(PAYLOAD, sizeof(PAYLOAD)).value, sizeof(PAYLOAD));
+  ASSERT_EQ(f->flush(), 0);
+  EXPECT_STREQ(f->get_str(), PAYLOAD);
+
+  ASSERT_EQ(f->seek(0, SEEK_SET).value(), 0);
+  EXPECT_EQ(f->tell().value(), off_t(0));
+
+  char out[sizeof(PAYLOAD)] = {0};
+  ASSERT_EQ(f->read(out, sizeof(PAYLOAD)).value, sizeof(PAYLOAD));
+  EXPECT_STREQ(out, PAYLOAD);
+  EXPECT_GT(reads, size_t(0));
+  EXPECT_GT(seeks, size_t(0));
+
+  char extra = 0;
+  EXPECT_EQ(f->read(&extra, 1).value, size_t(0));
+  EXPECT_TRUE(f->iseof());
+  ASSERT_EQ(f->ungetc('!'), static_cast<int>('!'));
+  EXPECT_FALSE(f->iseof());
+  ASSERT_EQ(f->read(&extra, 1).value, size_t(1));
+  EXPECT_EQ(extra, '!');
+
+  close_f.release();
+  ASSERT_EQ(f->close(), 0);
+  EXPECT_EQ(closes, size_t(1));
+}
+
+namespace {
+
+struct TestCookieState {
+  char buf[64] = {0};
+  size_t len = 0;
+  size_t pos = 0;
+  size_t close_calls = 0;
+  int close_ret = 0;
+};
+
+} // namespace
+
+static ssize_t test_cookie_read(void *c, char *out, size_t size) {
+  auto *st = static_cast<TestCookieState *>(c);
+  if (st->pos >= st->len)
+    return 0;
+  size_t avail = st->len - st->pos;
+  size_t n = size < avail ? size : avail;
+  for (size_t i = 0; i < n; ++i)
+    out[i] = st->buf[st->pos + i];
+  st->pos += n;
+  return static_cast<ssize_t>(n);
+}
+
+static ssize_t test_cookie_write(void *c, const char *in, size_t size) {
+  auto *st = static_cast<TestCookieState *>(c);
+  size_t i = 0;
+  for (; i < size && st->pos < sizeof(st->buf); ++i, ++st->pos)
+    st->buf[st->pos] = in[i];
+  if (st->pos > st->len)
+    st->len = st->pos;
+  return static_cast<ssize_t>(i);
+}
+
+static int test_cookie_seek(void *c, off_t *offset, int whence) {
+  auto *st = static_cast<TestCookieState *>(c);
+  off_t base = 0;
+  if (whence == SEEK_SET)
+    base = 0;
+  else if (whence == SEEK_CUR)
+    base = static_cast<off_t>(st->pos);
+  else if (whence == SEEK_END)
+    base = static_cast<off_t>(st->len);
+  else
+    return -1;
+  off_t next = base + *offset;
+  if (next < 0 || static_cast<size_t>(next) > sizeof(st->buf))
+    return -1;
+  st->pos = static_cast<size_t>(next);
+  *offset = next;
+  return 0;
+}
+
+static int test_cookie_close(void *c) {
+  auto *st = static_cast<TestCookieState *>(c);
+  ++st->close_calls;
+  return st->close_ret;
+}
+
+static ssize_t test_cookie_fail_read(void *, char *, size_t) { return -1; }
+static ssize_t test_cookie_fail_write(void *, const char *, size_t) {
+  return -1;
+}
+static ssize_t test_cookie_zero_write(void *, const char *, size_t) {
+  return 0;
+}
+static int test_cookie_fail_seek(void *, off_t *, int) { return -1; }
+static ssize_t test_cookie_oversize_read(void *, char *, size_t size) {
+  return static_cast<ssize_t>(size + 1);
+}
+static ssize_t test_cookie_oversize_write(void *, const char *, size_t size) {
+  return static_cast<ssize_t>(size + 1);
+}
+
+TEST(LlvmLibcFileTest, StaticCustomAndCookieCoexist) {
+  char static_buf[32];
+  size_t static_writes = 0;
+  size_t static_reads = 0;
+  size_t static_seeks = 0;
+  size_t static_closes = 0;
+
+  LIBC_NAMESPACE::AllocChecker ac;
+  auto *static_f = new (ac) StaticBufferFile(
+      static_buf, sizeof(static_buf), _IOFBF, /*owned=*/false, FileMode("w+"),
+      &static_writes, &static_reads, &static_seeks, &static_closes);
+  ASSERT_NE(static_f, nullptr);
+  scope_exit close_static([&] { EXPECT_EQ(static_f->close(), 0); });
+  EXPECT_EQ(static_cast<uint8_t>(static_f->get_dispatch_kind()),
+            static_cast<uint8_t>(TestFile::DispatchKind::STATIC));
+  EXPECT_FALSE(static_f->is_dynamic());
+
+  constexpr char STATIC_MSG[] = "static fast path";
+  ASSERT_EQ(static_f->write(STATIC_MSG, sizeof(STATIC_MSG)).value,
+            sizeof(STATIC_MSG));
+  ASSERT_EQ(static_f->flush(), 0);
+  EXPECT_EQ(static_writes, size_t(1));
+  ASSERT_EQ(static_f->seek(0, SEEK_SET).value(), 0);
+  EXPECT_EQ(static_seeks, size_t(1));
+
+  char read_back[sizeof(STATIC_MSG)] = {0};
+  ASSERT_EQ(static_f->read(read_back, sizeof(STATIC_MSG)).value,
+            sizeof(STATIC_MSG));
+  EXPECT_STREQ(read_back, STATIC_MSG);
+  EXPECT_EQ(static_reads, size_t(1));
+
+  // Simultaneously exercise a CUSTOM stream and a COOKIE stream via TestFile *
+  // and confirm neither invokes TestFilePlatform.
+  char custom_buf[32];
+  StringFile *custom_f =
+      new_string_file(custom_buf, sizeof(custom_buf), _IOFBF, false, "w+");
+  ASSERT_NE(custom_f, nullptr);
+  scope_exit close_custom([&] { EXPECT_EQ(custom_f->close(), 0); });
+  EXPECT_EQ(static_cast<uint8_t>(custom_f->get_dispatch_kind()),
+            static_cast<uint8_t>(TestFile::DispatchKind::CUSTOM));
+  EXPECT_TRUE(custom_f->is_dynamic());
+
+  TestCookieState cookie_state;
+  uint8_t cookie_buf[32];
+  TestFile *cookie_f = new (ac) TestCookieFile(
+      &cookie_state,
+      CookieOps{&test_cookie_read, &test_cookie_write, &test_cookie_seek,
+                &test_cookie_close},
+      cookie_buf, sizeof(cookie_buf), _IOFBF, /*owned=*/false, FileMode("w+"));
+  ASSERT_NE(cookie_f, nullptr);
+  scope_exit close_cookie([&] { EXPECT_EQ(cookie_f->close(), 0); });
+  EXPECT_EQ(static_cast<uint8_t>(cookie_f->get_dispatch_kind()),
+            static_cast<uint8_t>(TestFile::DispatchKind::COOKIE));
+  EXPECT_TRUE(cookie_f->is_dynamic());
+
+  constexpr char CUSTOM_MSG[] = "custom ops path";
+  ASSERT_EQ(custom_f->write(CUSTOM_MSG, sizeof(CUSTOM_MSG)).value,
+            sizeof(CUSTOM_MSG));
+  ASSERT_EQ(custom_f->flush(), 0);
+  EXPECT_STREQ(custom_f->get_str(), CUSTOM_MSG);
+
+  constexpr char COOKIE_MSG[] = "cookie ops path";
+  ASSERT_EQ(cookie_f->write(COOKIE_MSG, sizeof(COOKIE_MSG)).value,
+            sizeof(COOKIE_MSG));
+  ASSERT_EQ(cookie_f->seek(0, SEEK_SET).value(), 0);
+  char cookie_out[sizeof(COOKIE_MSG)] = {0};
+  ASSERT_EQ(cookie_f->read(cookie_out, sizeof(COOKIE_MSG)).value,
+            sizeof(COOKIE_MSG));
+  EXPECT_STREQ(cookie_out, COOKIE_MSG);
+
+  EXPECT_EQ(static_writes, size_t(1));
+  EXPECT_EQ(static_reads, size_t(1));
+  EXPECT_EQ(static_seeks, size_t(1));
+
+  close_custom.release();
+  ASSERT_EQ(custom_f->close(), 0);
+  close_cookie.release();
+  ASSERT_EQ(cookie_f->close(), 0);
+  EXPECT_EQ(cookie_state.close_calls, size_t(1));
+  EXPECT_EQ(static_closes, size_t(0));
+
+  close_static.release();
+  ASSERT_EQ(static_f->close(), 0);
+  EXPECT_EQ(static_closes, size_t(1));
+}
+
+TEST(LlvmLibcFileTest, CustomNullHookFallback) {
+  uint8_t stream_buf[16];
+  TestCustomFile f({nullptr, nullptr, nullptr, nullptr}, stream_buf,
+                   sizeof(stream_buf), _IOFBF, /*owned=*/false, FileMode("r+"));
+  EXPECT_EQ(static_cast<uint8_t>(f.get_dispatch_kind()),
+            static_cast<uint8_t>(TestFile::DispatchKind::CUSTOM));
+  EXPECT_TRUE(f.is_dynamic());
+
+  // default_write accepts and discards bytes without setting the error flag.
+  constexpr char DATA[] = "discarded output exceeding buffer";
+  auto write_res = f.write(DATA, sizeof(DATA));
+  EXPECT_FALSE(write_res.has_error());
+  EXPECT_EQ(write_res.value, sizeof(DATA));
+  EXPECT_EQ(f.flush(), 0);
+  EXPECT_FALSE(f.error());
+
+  // default_seek reports ESPIPE for non-seekable streams.
+  auto seek_res = f.seek(0, SEEK_SET);
+  ASSERT_FALSE(seek_res.has_value());
+  EXPECT_EQ(seek_res.error(), ESPIPE);
+
+  auto tell_res = f.tell();
+  ASSERT_FALSE(tell_res.has_value());
+  EXPECT_EQ(tell_res.error(), ESPIPE);
+
+  // Test default_read returning EOF (0 bytes, no error).
+  TestCustomFile rf({nullptr, nullptr, nullptr, nullptr}, stream_buf,
+                    sizeof(stream_buf), _IOFBF, /*owned=*/false,
+                    FileMode("r+"));
+  char out[8] = {0};
+  auto read_res = rf.read(out, sizeof(out));
+  EXPECT_FALSE(read_res.has_error());
+  EXPECT_EQ(read_res.value, size_t(0));
+  EXPECT_TRUE(rf.iseof());
+  EXPECT_FALSE(rf.error());
+
+  // ungetc still works on top of a stream with null read hook.
+  ASSERT_EQ(rf.ungetc('Q'), static_cast<int>('Q'));
+  EXPECT_FALSE(rf.iseof());
+  ASSERT_EQ(rf.read(out, 1).value, size_t(1));
+  EXPECT_EQ(out[0], 'Q');
+
+  // default_close is a no-op returning 0.
+  EXPECT_EQ(f.close(), 0);
+  EXPECT_EQ(rf.close(), 0);
+}
+
+TEST(LlvmLibcFileTest, CookieNullHooksAndErrorMapping) {
+  LIBC_NAMESPACE::AllocChecker ac;
+  uint8_t stream_buf[16];
+
+  // Null hooks: read -> 0 (EOF), seek -> EINVAL, write -> discards output,
+  // close -> remove_file + 0 + delete this.
+  TestFile *null_f = new (ac) TestCookieFile(
+      nullptr, CookieOps{nullptr, nullptr, nullptr, nullptr}, stream_buf,
+      sizeof(stream_buf), _IOFBF, /*owned=*/false, FileMode("r+"));
+  ASSERT_NE(null_f, nullptr);
+  TestFile::add_file(null_f);
+  scope_exit close_null([&] { EXPECT_EQ(null_f->close(), 0); });
+
+  char out[8] = {0};
+  auto read_res = null_f->read(out, sizeof(out));
+  EXPECT_FALSE(read_res.has_error());
+  EXPECT_EQ(read_res.value, size_t(0));
+  EXPECT_TRUE(null_f->iseof());
+  EXPECT_FALSE(null_f->error());
+
+  auto seek_res = null_f->seek(0, SEEK_SET);
+  ASSERT_FALSE(seek_res.has_value());
+  EXPECT_EQ(seek_res.error(), EINVAL);
+
+  // Per fopencookie(3), a null write hook discards output without error.
+  auto null_write_res = null_f->write("abc", 3);
+  EXPECT_FALSE(null_write_res.has_error());
+  EXPECT_EQ(null_write_res.value, size_t(3));
+  EXPECT_EQ(null_f->flush(), 0);
+  EXPECT_FALSE(null_f->error());
+
+  // close() unlinks from list_all, returns 0, and deletes |null_f|.
+  EXPECT_EQ(TestFile::get_first_file(), null_f);
+  close_null.release();
+  EXPECT_EQ(null_f->close(), 0);
+  EXPECT_EQ(TestFile::get_first_file(), nullptr);
+
+  // Buffered (_IOFBF) stream with a write hook returning 0 (error per
+  // fopencookie(3)): buffered write defers until flush/seek, which must report
+  // EIO instead of silently succeeding.
+  TestFile *zero_write_f = new (ac) TestCookieFile(
+      nullptr, CookieOps{nullptr, &test_cookie_zero_write, nullptr, nullptr},
+      stream_buf, sizeof(stream_buf), _IOFBF, /*owned=*/false, FileMode("r+"));
+  ASSERT_NE(zero_write_f, nullptr);
+  scope_exit close_zero_write([&] {
+    (void)zero_write_f->read(out, 1);
+    EXPECT_EQ(zero_write_f->close(), 0);
+  });
+
+  ASSERT_EQ(zero_write_f->write("abc", 3).value, size_t(3));
+  EXPECT_EQ(zero_write_f->flush(), EIO);
+  EXPECT_TRUE(zero_write_f->error());
+  zero_write_f->clearerr();
+
+  auto buf_seek_res = zero_write_f->seek(0, SEEK_SET);
+  ASSERT_FALSE(buf_seek_res.has_value());
+  EXPECT_EQ(buf_seek_res.error(), EIO);
+  EXPECT_TRUE(zero_write_f->error());
+
+  // Switch out of WRITE mode before closing so close() deletes |zero_write_f|.
+  (void)zero_write_f->read(out, 1);
+  close_zero_write.release();
+  EXPECT_EQ(zero_write_f->close(), 0);
+
+  // Failing callbacks: read/write/seek/close map failures to EIO, and close()
+  // still deletes |fail_f| when ops.close returns non-zero.
+  TestCookieState fail_state;
+  fail_state.close_ret = -42;
+  TestFile *fail_f = new (ac) TestCookieFile(
+      &fail_state,
+      CookieOps{&test_cookie_fail_read, &test_cookie_fail_write,
+                &test_cookie_fail_seek, &test_cookie_close},
+      stream_buf, sizeof(stream_buf), _IOFBF, /*owned=*/false, FileMode("w+"));
+  ASSERT_NE(fail_f, nullptr);
+  scope_exit close_fail([&] { EXPECT_EQ(fail_f->close(), EIO); });
+
+  auto fail_read = fail_f->read(out, sizeof(out));
+  EXPECT_TRUE(fail_read.has_error());
+  EXPECT_EQ(fail_read.error, EIO);
+  EXPECT_TRUE(fail_f->error());
+  fail_f->clearerr();
+
+  constexpr char LARGE_WRITE[36] = "exceeds two 16-byte stream buffers!";
+  auto fail_write = fail_f->write(LARGE_WRITE, sizeof(LARGE_WRITE));
+  EXPECT_TRUE(fail_write.has_error());
+  EXPECT_EQ(fail_write.error, EIO);
+  EXPECT_TRUE(fail_f->error());
+  fail_f->clearerr();
+
+  auto fail_seek = fail_f->seek(0, SEEK_SET);
+  ASSERT_FALSE(fail_seek.has_value());
+  EXPECT_EQ(fail_seek.error(), EIO);
+
+  close_fail.release();
+  EXPECT_EQ(fail_f->close(), EIO);
+  EXPECT_EQ(fail_state.close_calls, size_t(1));
+
+  // Oversize callbacks (> requested size) are rejected as EIO rather than
+  // corrupting stream buffer bounds.
+  TestFile *oversize_f = new (ac) TestCookieFile(
+      nullptr,
+      CookieOps{&test_cookie_oversize_read, &test_cookie_oversize_write,
+                nullptr, nullptr},
+      stream_buf, sizeof(stream_buf), _IOFBF, /*owned=*/false, FileMode("w+"));
+  ASSERT_NE(oversize_f, nullptr);
+  scope_exit close_oversize([&] { EXPECT_EQ(oversize_f->close(), 0); });
+
+  auto oversize_read = oversize_f->read(out, sizeof(out));
+  EXPECT_TRUE(oversize_read.has_error());
+  EXPECT_EQ(oversize_read.error, EIO);
+  EXPECT_EQ(oversize_read.value, size_t(0));
+  EXPECT_TRUE(oversize_f->error());
+  oversize_f->clearerr();
+
+  auto oversize_write = oversize_f->write(LARGE_WRITE, sizeof(LARGE_WRITE));
+  EXPECT_TRUE(oversize_write.has_error());
+  EXPECT_EQ(oversize_write.error, EIO);
+  EXPECT_TRUE(oversize_f->error());
+  oversize_f->clearerr();
+
+  close_oversize.release();
+  EXPECT_EQ(oversize_f->close(), 0);
+}
diff --git a/libc/test/src/stdio/CMakeLists.txt b/libc/test/src/stdio/CMakeLists.txt
index 5852f635904c0c..b7e9ad0271fdca 100644
--- a/libc/test/src/stdio/CMakeLists.txt
+++ b/libc/test/src/stdio/CMakeLists.txt
@@ -19,7 +19,9 @@ add_libc_test(
     libc.src.stdio.ferror
     libc.src.stdio.fflush
     libc.src.stdio.fileno
+    libc.src.stdio.fmemopen
     libc.src.stdio.fopen
+    libc.src.stdio.fopencookie
     libc.src.stdio.fread
     libc.src.stdio.freopen
     libc.src.stdio.fwrite
@@ -149,6 +151,7 @@ add_libc_test(
     fmemopen_test.cpp
   DEPENDS
     libc.include.stdio
+    libc.hdr.errno_macros
     libc.hdr.stdio_macros
     libc.hdr.types.off_t
     libc.src.__support.CPP.limits
@@ -184,6 +187,7 @@ add_libc_test(
     libc.hdr.types.off_t
     libc.hdr.types.size_t
     libc.hdr.types.ssize_t
+    libc.src.__support.CPP.scope
     libc.src.stdio.clearerr
     libc.src.stdio.fclose
     libc.src.stdio.feof
@@ -195,6 +199,7 @@ add_libc_test(
     libc.src.stdio.fseek
     libc.src.stdio.fwrite
     libc.test.UnitTest.ErrnoCheckingTest
+    libc.test.UnitTest.ErrnoSetterMatcher
     libc.test.UnitTest.MemoryMatcher
 )
 
@@ -657,12 +662,17 @@ if(${LIBC_TARGET_OS} STREQUAL "linux")
       libc.hdr.fcntl_macros
       libc.hdr.sys_wait_macros
       libc.hdr.types.FILE
+      libc.src.__support.CPP.scope
       libc.src.fcntl.fcntl
+      libc.src.stdio.fclose
       libc.src.stdio.fgets
       libc.src.stdio.fileno
+      libc.src.stdio.fopen
       libc.src.stdio.fputs
+      libc.src.stdio.freopen
       libc.src.stdio.pclose
       libc.src.stdio.popen
+      libc.src.stdio.remove
       libc.src.stdio.snprintf
       libc.src.sys.wait.wait
       libc.test.UnitTest.ErrnoCheckingTest
@@ -753,6 +763,7 @@ add_libc_test(
     libc.src.__support.CPP.string_view
     libc.src.__support.File.file
     libc.src.__support.File.file_io_result
+    libc.src.__support.File.platform_file
     libc.src.__support.error_or
     libc.src.stdio.generic.getdelim_impl
     libc.src.string.memory_utils.inline_memcpy
diff --git a/libc/test/src/stdio/fmemopen_test.cpp b/libc/test/src/stdio/fmemopen_test.cpp
index 344a1f2d6c7bc4..7f0bb327596fe2 100644
--- a/libc/test/src/stdio/fmemopen_test.cpp
+++ b/libc/test/src/stdio/fmemopen_test.cpp
@@ -11,6 +11,7 @@
 ///
 //===----------------------------------------------------------------------===//
 
+#include "hdr/errno_macros.h"
 #include "hdr/stdio_macros.h"
 #include "hdr/types/off_t.h"
 #include "src/__support/CPP/limits.h"
diff --git a/libc/test/src/stdio/fopencookie_test.cpp b/libc/test/src/stdio/fopencookie_test.cpp
index b4cfd42b07c078..54ed0707bbb2bb 100644
--- a/libc/test/src/stdio/fopencookie_test.cpp
+++ b/libc/test/src/stdio/fopencookie_test.cpp
@@ -22,6 +22,7 @@
 #include "src/stdio/fseek.h"
 #include "src/stdio/fwrite.h"
 #include "test/UnitTest/ErrnoCheckingTest.h"
+#include "test/UnitTest/ErrnoSetterMatcher.h"
 #include "test/UnitTest/MemoryMatcher.h"
 #include "test/UnitTest/Test.h"
 
@@ -30,10 +31,13 @@
 #include "hdr/types/off_t.h"
 #include "hdr/types/size_t.h"
 #include "hdr/types/ssize_t.h"
+#include "src/__support/CPP/scope.h"
 #include "src/__support/libc_errno.h"
 
 using LlvmLibcFOpenCookieTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
 using MemoryView = LIBC_NAMESPACE::testing::MemoryView;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
 
 struct StringStream {
   char *buf;
@@ -148,8 +152,8 @@ TEST_F(LlvmLibcFOpenCookieTest, WriteOnlyCookieTest) {
   constexpr char WRITE_DATA[] = "Hello,writeonly!";
   ASSERT_EQ(sizeof(WRITE_DATA),
             LIBC_NAMESPACE::fwrite(WRITE_DATA, 1, sizeof(WRITE_DATA), f));
-  // Flushing will ensure the data to be written to the string stream.
-  ASSERT_EQ(0, LIBC_NAMESPACE::fflush(f));
+  // fflush(nullptr) flushes all open streams, including fopencookie streams.
+  ASSERT_EQ(0, LIBC_NAMESPACE::fflush(nullptr));
   ASSERT_STREQ(WRITE_DATA, ss->buf);
 
   ASSERT_EQ(0, LIBC_NAMESPACE::fseek(f, 0, SEEK_SET));
@@ -279,6 +283,12 @@ ssize_t failing_write(void *, const char *, size_t) { return -1; }
 
 int failing_seek(void *, off_t *, int) { return -1; }
 
+static int failing_close(void *cookie) {
+  if (cookie != nullptr)
+    ++(*static_cast<int *>(cookie));
+  return -1;
+}
+
 TEST_F(LlvmLibcFOpenCookieTest, FailingCallbacksAreErrors) {
   constexpr cookie_io_functions_t FAILING_FUNCS = {
       &failing_read, &failing_write, &failing_seek, nullptr};
@@ -308,4 +318,29 @@ TEST_F(LlvmLibcFOpenCookieTest, FailingCallbacksAreErrors) {
   ASSERT_ERRNO_EQ(EIO);
   LIBC_NAMESPACE::fclose(f);
   libc_errno = 0;
+
+  constexpr cookie_io_functions_t NULL_FUNCS = {nullptr, nullptr, nullptr,
+                                                nullptr};
+  f = LIBC_NAMESPACE::fopencookie(nullptr, "r+", NULL_FUNCS);
+  ASSERT_NE(f, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_null(
+      [&] { EXPECT_THAT(LIBC_NAMESPACE::fclose(f), Succeeds(0)); });
+  ASSERT_EQ(size_t(0), LIBC_NAMESPACE::fread(data, 1, sizeof(data), f));
+  ASSERT_NE(LIBC_NAMESPACE::feof(f), 0);
+  ASSERT_EQ(0, LIBC_NAMESPACE::ferror(f));
+  ASSERT_THAT(LIBC_NAMESPACE::fseek(f, 0, SEEK_SET), Fails(EINVAL));
+  // Per fopencookie(3), a null write hook discards output without error.
+  ASSERT_EQ(sizeof(data), LIBC_NAMESPACE::fwrite(data, 1, sizeof(data), f));
+  ASSERT_THAT(LIBC_NAMESPACE::fflush(f), Succeeds(0));
+  ASSERT_EQ(0, LIBC_NAMESPACE::ferror(f));
+  close_null.release();
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(f), Succeeds(0));
+
+  int close_calls = 0;
+  constexpr cookie_io_functions_t FAILING_CLOSE_FUNCS = {
+      nullptr, nullptr, nullptr, &failing_close};
+  f = LIBC_NAMESPACE::fopencookie(&close_calls, "r", FAILING_CLOSE_FUNCS);
+  ASSERT_NE(f, nullptr);
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(f), Fails(EIO, EOF));
+  ASSERT_EQ(1, close_calls);
 }
diff --git a/libc/test/src/stdio/freopen_test.cpp b/libc/test/src/stdio/freopen_test.cpp
index 35b9685c3abbde..8f90c2d2ec0fd2 100644
--- a/libc/test/src/stdio/freopen_test.cpp
+++ b/libc/test/src/stdio/freopen_test.cpp
@@ -19,7 +19,9 @@
 #include "src/stdio/ferror.h"
 #include "src/stdio/fflush.h"
 #include "src/stdio/fileno.h"
+#include "src/stdio/fmemopen.h"
 #include "src/stdio/fopen.h"
+#include "src/stdio/fopencookie.h"
 #include "src/stdio/fread.h"
 #include "src/stdio/freopen.h"
 #include "src/stdio/fwrite.h"
@@ -344,6 +346,70 @@ TEST_F(LlvmLibcFreopenTest, StdoutFailureTest) {
 }
 #endif
 
+TEST_F(LlvmLibcFreopenTest, ReopenFmemopenStream) {
+  const auto FILENAME = libc_make_test_file_path("freopen_fmemopen.test");
+  const auto NON_EXISTENT =
+      libc_make_test_file_path("freopen_fmemopen_missing.test");
+  char storage[16] = {0};
+  ::FILE *mem_file = LIBC_NAMESPACE::fmemopen(storage, sizeof(storage), "w+");
+  ASSERT_NE(mem_file, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_mem_file(
+      [&] { EXPECT_THAT(LIBC_NAMESPACE::fclose(mem_file), Succeeds(0)); });
+  ASSERT_THAT(LIBC_NAMESPACE::fwrite("abc", 1, 3, mem_file),
+              Succeeds(static_cast<size_t>(3)));
+
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "invalid", mem_file),
+              Fails(EINVAL, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "r", mem_file),
+              Fails(EBADF, static_cast<void *>(nullptr)));
+
+  constexpr char FILE_CONTENT[] = "Reopened from fmemopen";
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(FILENAME, "w", mem_file),
+              Succeeds(static_cast<void *>(mem_file)));
+  EXPECT_STREQ(storage, "abc");
+  ASSERT_THAT(LIBC_NAMESPACE::fwrite(FILE_CONTENT, 1, sizeof(FILE_CONTENT) - 1,
+                                     mem_file),
+              Succeeds(sizeof(FILE_CONTENT) - 1));
+
+  close_mem_file.release();
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(mem_file), Succeeds(0));
+  verify_file_content(FILENAME, FILE_CONTENT);
+
+  // Also verify an fmemopen stream owning its heap buffer releases it cleanly
+  // even when reopening onto a path fails (matching NonExistentFileFailure,
+  // fclose frees the stream object and reports EBADF).
+  ::FILE *owned_mem = LIBC_NAMESPACE::fmemopen(nullptr, 16, "w+");
+  ASSERT_NE(owned_mem, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_owned_mem(
+      [&] { (void)LIBC_NAMESPACE::fclose(owned_mem); });
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(NON_EXISTENT, "r", owned_mem),
+              Fails(ENOENT, static_cast<void *>(nullptr)));
+  close_owned_mem.release();
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(owned_mem), Fails(EBADF, EOF));
+}
+
+TEST_F(LlvmLibcFreopenTest, CookieStreamFailure) {
+  const auto FILENAME = libc_make_test_file_path("freopen_cookie_stream.test");
+  constexpr cookie_io_functions_t NULL_FUNCS = {nullptr, nullptr, nullptr,
+                                                nullptr};
+  ::FILE *cookie_file = LIBC_NAMESPACE::fopencookie(nullptr, "r+", NULL_FUNCS);
+  ASSERT_NE(cookie_file, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_cookie(
+      [&] { EXPECT_THAT(LIBC_NAMESPACE::fclose(cookie_file), Succeeds(0)); });
+
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(FILENAME, "invalid", cookie_file),
+              Fails(EINVAL, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "invalid", cookie_file),
+              Fails(EINVAL, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(FILENAME, "w", cookie_file),
+              Fails(EBADF, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "r", cookie_file),
+              Fails(EBADF, static_cast<void *>(nullptr)));
+
+  close_cookie.release();
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(cookie_file), Succeeds(0));
+}
+
 TEST_F(LlvmLibcFreopenTest, NullStreamFailure) {
   const auto FILENAME = libc_make_test_file_path("freopen_null_stream.test");
   const char *fn = FILENAME;
diff --git a/libc/test/src/stdio/getdelim_impl_test.cpp b/libc/test/src/stdio/getdelim_impl_test.cpp
index 887dca478439df..b26b0a160986dd 100644
--- a/libc/test/src/stdio/getdelim_impl_test.cpp
+++ b/libc/test/src/stdio/getdelim_impl_test.cpp
@@ -25,6 +25,7 @@
 #include "src/__support/File/file.h"
 #include "src/__support/File/file_io_result.h"
 #include "src/__support/File/file_mode.h"
+#include "src/__support/File/platform_file.h"
 #include "src/__support/error_or.h"
 #include "src/stdio/generic/getdelim_impl.h"
 #include "src/string/memory_utils/inline_memcpy.h"
@@ -32,6 +33,7 @@
 
 namespace {
 
+using LIBC_NAMESPACE::CustomFile;
 using LIBC_NAMESPACE::File;
 using LIBC_NAMESPACE::FileIOResult;
 using LIBC_NAMESPACE::FileMode;
@@ -39,7 +41,7 @@ using LIBC_NAMESPACE::cpp::scope_exit;
 using LIBC_NAMESPACE::cpp::span;
 using LIBC_NAMESPACE::cpp::string_view;
 
-class TestFile : public File {
+class TestFile : public CustomFile {
   span<const char> data;
   size_t pos = 0;
   size_t fail_at_byte = LIBC_NAMESPACE::cpp::numeric_limits<size_t>::max();
@@ -68,10 +70,10 @@ class TestFile : public File {
 
 public:
   explicit TestFile(span<const char> bytes, int bufmode = _IOFBF)
-      : File(/*wf=*/nullptr, &read_func, /*sf=*/nullptr, &close_func,
-             bufmode == _IONBF ? nullptr : stream_buf,
-             bufmode == _IONBF ? 0 : sizeof(stream_buf), bufmode,
-             /*owned=*/false, FileMode("r")),
+      : CustomFile({/*w=*/nullptr, &read_func, /*s=*/nullptr, &close_func},
+                   bufmode == _IONBF ? nullptr : stream_buf,
+                   bufmode == _IONBF ? 0 : sizeof(stream_buf), bufmode,
+                   /*owned=*/false, FileMode("r")),
         data(bytes) {}
 
   explicit TestFile(string_view str, int bufmode = _IOFBF)
diff --git a/libc/test/src/stdio/popen_pclose_test.cpp b/libc/test/src/stdio/popen_pclose_test.cpp
index f901e574fe30a4..e33926f0f8a17e 100644
--- a/libc/test/src/stdio/popen_pclose_test.cpp
+++ b/libc/test/src/stdio/popen_pclose_test.cpp
@@ -17,11 +17,16 @@
 #include "hdr/fcntl_macros.h"
 #include "hdr/sys_wait_macros.h"
 #include "hdr/types/FILE.h"
+#include "src/__support/CPP/scope.h"
 #include "src/fcntl/fcntl.h"
+#include "src/stdio/fclose.h"
 #include "src/stdio/fgets.h"
 #include "src/stdio/fileno.h"
+#include "src/stdio/fopen.h"
 #include "src/stdio/fputs.h"
+#include "src/stdio/freopen.h"
 #include "src/stdio/pclose.h"
+#include "src/stdio/remove.h"
 #include "src/stdio/snprintf.h"
 #include "src/sys/wait/wait.h"
 #include "test/UnitTest/ErrnoCheckingTest.h"
@@ -29,6 +34,7 @@
 #include "test/UnitTest/Test.h"
 
 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
+using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
 using LlvmLibcPopenTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
 
 TEST_F(LlvmLibcPopenTest, ReadMode) {
@@ -156,3 +162,70 @@ TEST_F(LlvmLibcPopenTest, NoCloseOnExecByDefault) {
   ASSERT_TRUE(WIFEXITED(status));
   ASSERT_EQ(WEXITSTATUS(status), 0);
 }
+
+TEST_F(LlvmLibcPopenTest, FreopenNullPath) {
+  ::FILE *stream = LIBC_NAMESPACE::popen("echo reopened", "r");
+  ASSERT_ERRNO_SUCCESS();
+  ASSERT_NE(stream, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_stream(
+      [&] { (void)LIBC_NAMESPACE::pclose(stream); });
+
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "invalid", stream),
+              Fails(EINVAL, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "w", stream),
+              Fails(EBADF, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(nullptr, "rb", stream),
+              Succeeds(static_cast<void *>(stream)));
+
+  char buf[16] = {0};
+  ASSERT_NE(LIBC_NAMESPACE::fgets(buf, sizeof(buf), stream), nullptr);
+  EXPECT_STREQ(buf, "reopened\n");
+
+  close_stream.release();
+  int status = LIBC_NAMESPACE::pclose(stream);
+  ASSERT_ERRNO_SUCCESS();
+  ASSERT_TRUE(WIFEXITED(status));
+  ASSERT_EQ(WEXITSTATUS(status), 0);
+}
+
+TEST_F(LlvmLibcPopenTest, FreopenPath) {
+  const auto FILENAME = libc_make_test_file_path("popen_freopen_path.test");
+  const auto NON_EXISTENT =
+      libc_make_test_file_path("popen_freopen_missing.test");
+
+  ::FILE *stream = LIBC_NAMESPACE::popen("true", "r");
+  ASSERT_ERRNO_SUCCESS();
+  ASSERT_NE(stream, nullptr);
+  LIBC_NAMESPACE::cpp::scope_exit close_stream(
+      [&] { (void)LIBC_NAMESPACE::pclose(stream); });
+
+  // A failed freopen detaches the pipe fd and sets fd = -1, but a subsequent
+  // freopen onto a valid path must still succeed.
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(NON_EXISTENT, "r", stream),
+              Fails(ENOENT, static_cast<void *>(nullptr)));
+  ASSERT_THAT(LIBC_NAMESPACE::freopen(FILENAME, "w+", stream),
+              Succeeds(static_cast<void *>(stream)));
+
+  // Spawning another popen child while |stream| is open must not affect or
+  // inherit the reopened file stream.
+  ::FILE *other = LIBC_NAMESPACE::popen("true", "r");
+  ASSERT_NE(other, nullptr);
+  ASSERT_GE(LIBC_NAMESPACE::pclose(other), 0);
+  ASSERT_ERRNO_SUCCESS();
+
+  ASSERT_GE(LIBC_NAMESPACE::fputs("reopened popen\n", stream), 0);
+
+  close_stream.release();
+  int status = LIBC_NAMESPACE::pclose(stream);
+  ASSERT_ERRNO_SUCCESS();
+  ASSERT_TRUE(WIFEXITED(status));
+  ASSERT_EQ(WEXITSTATUS(status), 0);
+
+  ::FILE *verify = LIBC_NAMESPACE::fopen(FILENAME, "r");
+  ASSERT_NE(verify, nullptr);
+  char buf[32] = {0};
+  ASSERT_NE(LIBC_NAMESPACE::fgets(buf, sizeof(buf), verify), nullptr);
+  EXPECT_STREQ(buf, "reopened popen\n");
+  ASSERT_THAT(LIBC_NAMESPACE::fclose(verify), Succeeds(0));
+  ASSERT_THAT(LIBC_NAMESPACE::remove(FILENAME), Succeeds(0));
+}
diff --git a/utils/bazel/llvm-project-overlay/libc/src/__support/File/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/__support/File/BUILD.bazel
index 71e09d3008e3c1..9cef61abd61ccf 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/__support/File/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/__support/File/BUILD.bazel
@@ -25,11 +25,9 @@ libc_support_library(
 
 libc_support_library(
     name = "file",
-    srcs = [
-        "file.cpp",
-    ],
     hdrs = [
         "file.h",
+        "file_impl.h",
         "file_mode.h",
     ],
     deps = [
@@ -45,6 +43,7 @@ libc_support_library(
         "//libc/hdr/types:char32_t",
         "//libc/hdr/types:char8_t",
         "//libc/hdr/types:off_t",
+        "//libc/hdr/types:ssize_t",
         "//libc/hdr/types:wchar_t",
         "//libc/hdr/types:wint_t",
         "//libc/include:llvm_libc_types_off_t",
@@ -53,8 +52,10 @@ libc_support_library(
         "//libc/src/__support:libc_assert",
         "//libc/src/__support/CPP:new",
         "//libc/src/__support/CPP:span",
+        "//libc/src/__support/CPP:type_traits",
         "//libc/src/__support/macros:attributes",
         "//libc/src/__support/macros:config",
+        "//libc/src/__support/macros:optimization",
         "//libc/src/__support/macros/properties:architectures",
         "//libc/src/__support/threads:mutex",
         "//libc/src/__support/wchar:character_converter",
@@ -72,6 +73,7 @@ libc_support_library(
     hdrs = [
         "linux/file.h",
         "linux/file_flags.h",
+        "platform_file.h",
     ],
     deps = [
         ":file",
@@ -83,6 +85,7 @@ libc_support_library(
         "//libc/hdr/func:free",
         "//libc/hdr/types:mode_t",
         "//libc/hdr/types:off_t",
+        "//libc/include:llvm_libc_types_off_t",
         "//libc/src/__support:alloc_checker",
         "//libc/src/__support:common",
         "//libc/src/__support:error_or",
diff --git a/utils/bazel/llvm-project-overlay/libc/src/stdio/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/stdio/BUILD.bazel
index 1e058dbc8c5074..ab6316b056af59 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/stdio/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/stdio/BUILD.bazel
@@ -245,7 +245,10 @@ libc_function(
         "//libc/src/__support/printf_core:printf_error_mapper",
         "//libc/src/__support/printf_core:vfprintf_internal",
         "//libc/src/errno",
-    ],
+    ] + select({
+        "//libc:full_build": ["//libc/src/__support/File:platform_file"],
+        "//conditions:default": [],
+    }),
 )
 
 libc_function(
@@ -329,7 +332,10 @@ libc_function(
         "//libc/src/__support/printf_core:printf_error_mapper",
         "//libc/src/__support/printf_core:vfprintf_internal",
         "//libc/src/errno",
-    ],
+    ] + select({
+        "//libc:full_build": ["//libc/src/__support/File:platform_file"],
+        "//conditions:default": [],
+    }),
 )
 
 libc_support_library(
@@ -476,7 +482,10 @@ libc_function(
         "//libc/src/__support:arg_list",
         "//libc/src/__support/File:file",
         "//libc/src/__support/macros:config",
-    ],
+    ] + select({
+        "//libc:full_build": ["//libc/src/__support/File:platform_file"],
+        "//conditions:default": [],
+    }),
 )
 
 libc_function(
@@ -489,7 +498,10 @@ libc_function(
         "//libc/src/__support:arg_list",
         "//libc/src/__support/File:file",
         "//libc/src/__support/macros:config",
-    ],
+    ] + select({
+        "//libc:full_build": ["//libc/src/__support/File:platform_file"],
+        "//conditions:default": [],
+    }),
 )
 
 libc_function(



More information about the libc-commits mailing list