[libc-commits] [libc] [libc] Fix FILE mutex, buffering (PR #238618)

via libc-commits libc-commits at lists.llvm.org
Tue Nov 3 16:55:58 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Michael Jones (michaelrj-google)

<details>
<summary>Changes</summary>

This change fixes some small issues found in FILE while building
programs against LLVM-libc. Specifically:

1) Linux pipes sometimes give less data than was requested, but the FILE
   is expected to retry until it gets a blank read.
2) FILE mutexes are expected to be reentrant.
3) Changing the buffer status of a FILE is expected to flush the buffer
   before it's changed.

This PR fixes these minor issues and adds appropriate tests to catch
this behavior in future.

Assisted-by: Automated tooling, human reviewed.


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


3 Files Affected:

- (modified) libc/src/__support/File/file.cpp (+57-30) 
- (modified) libc/src/__support/File/file.h (+1-1) 
- (modified) libc/test/src/__support/File/file_test.cpp (+147) 


``````````diff
diff --git a/libc/src/__support/File/file.cpp b/libc/src/__support/File/file.cpp
index f8ff4a6e52f2ca..b4d5e9aaa180c8 100644
--- a/libc/src/__support/File/file.cpp
+++ b/libc/src/__support/File/file.cpp
@@ -316,32 +316,44 @@ FileIOResult File::read_unlocked_fbf(uint8_t *data, size_t len) {
                              to_fetch);
 
   if (to_fetch > bufsize) {
-    FileIOResult result = platform_read(this, dataref.data(), to_fetch);
+    while (to_fetch > 0) {
+      FileIOResult result = platform_read(this, dataref.data(), to_fetch);
+      size_t fetched_size = result.value;
+      available_data += fetched_size;
+      if (result.has_error() || fetched_size == 0) {
+        if (!result.has_error())
+          eof = true;
+        else
+          err = true;
+        return {available_data, result.error};
+      }
+      to_fetch -= fetched_size;
+      dataref = dataref.subspan(fetched_size);
+    }
+    return len;
+  }
+
+  // Fetch and buffer another buffer worth of data.
+  while (to_fetch > 0) {
+    FileIOResult result = platform_read(this, buf, bufsize);
     size_t fetched_size = result.value;
-    if (result.has_error() || fetched_size < to_fetch) {
+    read_limit = fetched_size;
+    pos = 0;
+    size_t transfer_size = fetched_size >= to_fetch ? to_fetch : fetched_size;
+    inline_memcpy(dataref.data(), buf, transfer_size);
+    pos += transfer_size;
+    available_data += transfer_size;
+    to_fetch -= transfer_size;
+    dataref = dataref.subspan(transfer_size);
+    if (result.has_error() || fetched_size == 0) {
       if (!result.has_error())
         eof = true;
       else
         err = true;
-      return {available_data + fetched_size, result.error};
+      return {available_data, result.error};
     }
-    return len;
   }
-
-  // Fetch and buffer another buffer worth of data.
-  FileIOResult result = platform_read(this, buf, bufsize);
-  size_t fetched_size = result.value;
-  read_limit += fetched_size;
-  size_t transfer_size = fetched_size >= to_fetch ? to_fetch : fetched_size;
-  inline_memcpy(dataref.data(), buf, transfer_size);
-  pos += transfer_size;
-  if (result.has_error() || fetched_size < to_fetch) {
-    if (!result.has_error())
-      eof = true;
-    else
-      err = true;
-  }
-  return {transfer_size + available_data, result.error};
+  return available_data;
 }
 
 FileIOResult File::read_unlocked_nbf(uint8_t *data, size_t len) {
@@ -351,17 +363,24 @@ FileIOResult File::read_unlocked_nbf(uint8_t *data, size_t len) {
     return available_data;
 
   // Directly copy the data into |data|.
+  size_t to_fetch = len - available_data;
   cpp::span<uint8_t> dataref(static_cast<uint8_t *>(data) + available_data,
-                             len - available_data);
-  FileIOResult result = platform_read(this, dataref.data(), dataref.size());
-
-  if (result.has_error() || result < dataref.size()) {
-    if (!result.has_error())
-      eof = true;
-    else
-      err = true;
+                             to_fetch);
+  while (to_fetch > 0) {
+    FileIOResult result = platform_read(this, dataref.data(), to_fetch);
+    size_t fetched_size = result.value;
+    available_data += fetched_size;
+    if (result.has_error() || fetched_size == 0) {
+      if (!result.has_error())
+        eof = true;
+      else
+        err = true;
+      return {available_data, result.error};
+    }
+    to_fetch -= fetched_size;
+    dataref = dataref.subspan(fetched_size);
   }
-  return {result + available_data, result.error};
+  return available_data;
 }
 
 int File::ungetc_unlocked(int c) {
@@ -532,8 +551,6 @@ int File::close() {
 }
 
 int File::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)
     return EINVAL;
 
@@ -546,6 +563,16 @@ int File::set_buffer(void *buffer, size_t size, int buffer_mode) {
     return EINVAL;
   }
 
+  FileLock lock(this);
+  if (prev_op == FileOp::WRITE && pos > 0)
+    flush_unlocked();
+  pos = 0;
+  read_limit = 0;
+  prev_op = FileOp::NONE;
+
+  if (buffer == nullptr && size == 0 && buffer_mode != _IONBF)
+    size = DEFAULT_BUFFER_SIZE;
+
   if (buffer == nullptr && size != 0 && buffer_mode != _IONBF) {
     // We exclude the case of buffer_mode == _IONBF in this branch
     // because we don't need to allocate buffer in such a case.
diff --git a/libc/src/__support/File/file.h b/libc/src/__support/File/file.h
index d4a16c582a3de9..9532ec3f8d7cf5 100644
--- a/libc/src/__support/File/file.h
+++ b/libc/src/__support/File/file.h
@@ -155,7 +155,7 @@ class File {
                              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), mutex(/*timed=*/false, /*recursive=*/false,
+        platform_close(cf), mutex(/*timed=*/false, /*recursive=*/true,
                                   /*robust=*/false, /*pshared=*/false),
         ungetc_buf{}, buf(buffer), bufsize(buffer_size), bufmode(buffer_mode),
         own_buf(owned), mode(mode), pos(0), prev_op(FileOp::NONE),
diff --git a/libc/test/src/__support/File/file_test.cpp b/libc/test/src/__support/File/file_test.cpp
index 48663a76a8a62a..5d222af9c74f90 100644
--- a/libc/test/src/__support/File/file_test.cpp
+++ b/libc/test/src/__support/File/file_test.cpp
@@ -882,3 +882,150 @@ TEST(LlvmLibcFileTest, FileLockRAII) {
   ASSERT_EQ(f->write("def", 3).value, size_t(3));
   ASSERT_EQ(f->close(), 0);
 }
+
+class ShortReadFile : public File {
+  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) {
+    return 0;
+  }
+
+  static FileIOResult short_read(LIBC_NAMESPACE::File *f, void *data,
+                                 size_t len) {
+    ShortReadFile *sf = static_cast<ShortReadFile *>(f);
+    if (sf->pos >= sf->src_len)
+      return 0;
+    size_t avail = sf->src_len - sf->pos;
+    size_t to_read = len < sf->max_read ? len : sf->max_read;
+    if (to_read > avail)
+      to_read = avail;
+    for (size_t i = 0; i < to_read; ++i)
+      reinterpret_cast<char *>(data)[i] = sf->src[sf->pos + i];
+    sf->pos += to_read;
+    return to_read;
+  }
+
+  static ErrorOr<off_t> short_seek(LIBC_NAMESPACE::File *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) {
+    delete reinterpret_cast<ShortReadFile *>(f);
+    return 0;
+  }
+
+public:
+  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")),
+        src(data), src_len(data_len), pos(0), max_read(max_read_bytes) {}
+};
+
+TEST(LlvmLibcFileTest, ShortReadsUntilLengthOrEOF) {
+  constexpr char DATA[] = "0123456789abcdef";
+  constexpr size_t DATA_LEN = sizeof(DATA) - 1;
+  LIBC_NAMESPACE::AllocChecker ac;
+
+  // Test buffered mode (_IOFBF) with both > bufsize and <= bufsize reads when
+  // platform_read returns at most 3 bytes per call (e.g. reading from a pipe).
+  char file_buf[8];
+  ShortReadFile *f_fbf =
+      new (ac) ShortReadFile(file_buf, sizeof(file_buf), _IOFBF, DATA, DATA_LEN,
+                             /*max_read_bytes=*/3);
+  ASSERT_NE(f_fbf, nullptr);
+
+  char out[32] = {0};
+  // Read 5 bytes (<= bufsize): requires two 3-byte platform_read calls,
+  // leaving 1 byte buffered and eof == false.
+  auto res1 = f_fbf->read(out, 5);
+  EXPECT_EQ(res1.value, size_t(5));
+  EXPECT_FALSE(f_fbf->iseof());
+  EXPECT_FALSE(f_fbf->error());
+
+  // Read remaining 11 bytes + try to read past end (> bufsize): loops until
+  // platform_read returns 0 and sets eof == true.
+  auto res2 = f_fbf->read(out + 5, 20);
+  EXPECT_EQ(res2.value, size_t(11));
+  EXPECT_TRUE(f_fbf->iseof());
+  EXPECT_FALSE(f_fbf->error());
+  EXPECT_STREQ(out, DATA);
+  ASSERT_EQ(f_fbf->close(), 0);
+
+  // Test unbuffered mode (_IONBF) with short reads.
+  ShortReadFile *f_nbf = new (ac)
+      ShortReadFile(nullptr, 0, _IONBF, DATA, DATA_LEN, /*max_read_bytes=*/3);
+  ASSERT_NE(f_nbf, nullptr);
+
+  char out_nbf[32] = {0};
+  auto res3 = f_nbf->read(out_nbf, 10);
+  EXPECT_EQ(res3.value, size_t(10));
+  EXPECT_FALSE(f_nbf->iseof());
+  auto res4 = f_nbf->read(out_nbf + 10, 10);
+  EXPECT_EQ(res4.value, size_t(6));
+  EXPECT_TRUE(f_nbf->iseof());
+  EXPECT_STREQ(out_nbf, DATA);
+  ASSERT_EQ(f_nbf->close(), 0);
+}
+
+TEST(LlvmLibcFileTest, RecursiveFileLock) {
+  char file_buf[16];
+  StringFile *f =
+      new_string_file(file_buf, sizeof(file_buf), _IOFBF, false, "w+");
+  ASSERT_NE(f, nullptr);
+
+  // Simulate flockfile(f) followed by locked operations (write, ungetc, error,
+  // iseof) on the same thread, plus nested lock()/unlock().
+  f->lock();
+  f->lock();
+  ASSERT_EQ(f->write("ab", 2).value, size_t(2));
+  ASSERT_EQ(f->flush(), 0);
+  ASSERT_EQ(f->seek(0, SEEK_SET).value(), 0);
+
+  char c = 0;
+  ASSERT_EQ(f->read_unlocked(&c, 1).value, size_t(1));
+  EXPECT_EQ(c, 'a');
+  EXPECT_EQ(f->ungetc('x'), int('x'));
+  EXPECT_FALSE(f->error());
+  EXPECT_FALSE(f->iseof());
+
+  char out[3] = {0};
+  ASSERT_EQ(f->read(out, 2).value, size_t(2));
+  EXPECT_STREQ(out, "xb");
+  f->unlock();
+  f->unlock();
+
+  ASSERT_EQ(f->close(), 0);
+}
+
+TEST(LlvmLibcFileTest, SetBufferFlushesAndAllocatesDefaultSize) {
+  char file_buf[16];
+  StringFile *f =
+      new_string_file(file_buf, sizeof(file_buf), _IOFBF, false, "w");
+  ASSERT_NE(f, nullptr);
+
+  ASSERT_EQ(f->write("111\n", 4).value, size_t(4));
+  // Buffered in _IOFBF prior to set_buffer.
+  EXPECT_EQ(f->get_pos(), size_t(0));
+
+  // Switching to _IOLBF with (nullptr, 0) should flush pending data and
+  // allocate a default-sized buffer without leaving stale pos.
+  ASSERT_EQ(f->set_buffer(nullptr, 0, _IOLBF), 0);
+  EXPECT_EQ(f->get_pos(), size_t(4));
+
+  ASSERT_EQ(f->write("------\n", 7).value, size_t(7));
+  EXPECT_EQ(f->get_pos(), size_t(11));
+  EXPECT_STREQ(f->get_str(), "111\n------\n");
+
+  ASSERT_EQ(f->close(), 0);
+}

``````````

</details>


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


More information about the libc-commits mailing list