https://gcc.gnu.org/g:2d296e9f024edbb49cad1f3ebb5ae34c71ea5f7a

commit r17-5970-g2d296e9f024edbb49cad1f3ebb5ae34c71ea5f7a
Author: Jonathan Wakely <[email protected]>
Date:   Wed Oct 28 10:34:17 2026 +0000

    libstdc++: Fix buffer overflows in basic_filebuf::overflow [PR118099]
    
    If we fail to write the content of the buffer after inserting the
    overflow character into the end of it, then remove that overflow
    character before propagating the error back to the caller. Without this,
    the caller is left with pptr set past epptr, and successive calls to
    overflow will write further past the end of the managed buffer with each
    failure.
    
    The new 118099-codecvt.cc tests were assisted by an LLM because I was
    too lazy to remember how to write codecvt facets.
    
    Assisted-by: LLM
    
    libstdc++-v3/ChangeLog:
    
            PR libstdc++/118099
            * include/bits/fstream.tcc (basic_filebuf::overflow): Rewind the
            put position if outputting the put area fails.
            * testsuite/27_io/basic_filebuf/overflow/char/118099-codecvt.cc:
            New test.
            * testsuite/27_io/basic_filebuf/overflow/char/118099.cc: New
            test.
            * testsuite/27_io/basic_filebuf/overflow/wchar_t/118099-codecvt.cc:
            New test.
            * testsuite/27_io/basic_filebuf/overflow/wchar_t/118099.cc:
            New test.
    
    Reviewed-by: Tomasz KamiƄski <[email protected]>

Diff:
---
 libstdc++-v3/include/bits/fstream.tcc              |  8 +++
 .../basic_filebuf/overflow/char/118099-codecvt.cc  | 76 ++++++++++++++++++++++
 .../27_io/basic_filebuf/overflow/char/118099.cc    | 57 ++++++++++++++++
 .../overflow/wchar_t/118099-codecvt.cc             | 76 ++++++++++++++++++++++
 .../27_io/basic_filebuf/overflow/wchar_t/118099.cc | 57 ++++++++++++++++
 5 files changed, 274 insertions(+)

diff --git a/libstdc++-v3/include/bits/fstream.tcc 
b/libstdc++-v3/include/bits/fstream.tcc
index 99aa296b83c4..0d1d9491cb6a 100644
--- a/libstdc++-v3/include/bits/fstream.tcc
+++ b/libstdc++-v3/include/bits/fstream.tcc
@@ -561,11 +561,18 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
             }
          if (this->pbase() < this->pptr())
            {
+             struct _Guard {
+               ~_Guard() { if (_M_p) _M_p->pbump(-1); }
+               basic_filebuf* _M_p;
+             };
+             _Guard __g = { };
+
              // If appropriate, append the overflow char.
              if (!__testeof)
                {
                  *this->pptr() = traits_type::to_char_type(__c);
                  this->pbump(1);
+                 __g._M_p = this;
                }
 
              // Convert pending sequence to external representation,
@@ -573,6 +580,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
              if (_M_convert_to_external(this->pbase(),
                                         this->pptr() - this->pbase()))
                {
+                 __g._M_p = 0;
                  _M_set_buffer(0);
                  __ret = traits_type::not_eof(__c);
                }
diff --git 
a/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099-codecvt.cc 
b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099-codecvt.cc
new file mode 100644
index 000000000000..e4b1106b9b8d
--- /dev/null
+++ b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099-codecvt.cc
@@ -0,0 +1,76 @@
+// { dg-do run }
+// { dg-require-fileio "" }
+
+// PR libstdc++/118099
+// basic_filebuf::overflow leaves streambuf in inconsistent state on I/O error
+//
+// Companion test of 118099.cc testing the throwing failure path in overflow:
+// a codecvt whose do_out always returns error makes _M_convert_to_external
+// throw after the overflow character has been written to the end of put area.
+// If the put pointer is advanced before the throw (and only rewound on the
+// non-throwing error path), a caller that catches the exception and keeps
+// writing will cause overflow(c) to write past the end of the managed buffer,
+// just like the original PR libstdc++/118099 testcase.
+
+#include <fstream>
+#include <locale>
+#include <testsuite_hooks.h>
+
+typedef char C;
+
+struct failing_codecvt : std::codecvt<C, char, std::mbstate_t>
+{
+protected:
+  result
+  do_out(state_type&, const intern_type* from, const intern_type*,
+        const intern_type*& from_next,
+        extern_type* to, extern_type*, extern_type*& to_next) const
+  {
+    from_next = from;
+    to_next = to;
+    return error;
+  }
+
+  bool do_always_noconv() const throw() { return false; }
+};
+
+static void
+test_pr118099_codecvt()
+{
+  const C val = C('x');
+  const C canary = ~val;
+  const int N = 8;
+  C buf[N * 2];
+  for (int i = 0; i < N * 2; ++i)
+    buf[i] = canary;
+
+  std::basic_filebuf<C> fb;
+  fb.pubimbue(std::locale(std::locale::classic(), new failing_codecvt));
+  fb.pubsetbuf(buf, N); // filebuf can use buf[0..N]
+  fb.open("tmp_118099_codecvt", std::ios_base::out | std::ios_base::trunc);
+  VERIFY( fb.is_open() );
+
+  // Libstdc++ filebuf throws ios::failure for the codecvt error,
+  // but the standard allows overflow to return eof instead.
+  // To make this test portable, we check for either kind of error.
+  bool got_error = false;
+  for (int i = 0; i < N * 2; ++i)
+    try {
+      std::char_traits<C>::int_type r = fb.sputc(val);
+      if (std::char_traits<C>::eq_int_type(r, std::char_traits<C>::eof()))
+       got_error = true;
+    } catch (const std::exception&) {
+      got_error = true;
+    }
+  VERIFY( got_error ); // a codecvt error actually happened
+
+  for (int i = 0; i < N; ++i)
+    VERIFY( buf[i] == val );
+  for (int i = N; i < N * 2; ++i)
+    VERIFY( buf[i] == canary ); // nothing was written past buf[0..N]
+}
+
+int main()
+{
+  test_pr118099_codecvt();
+}
diff --git a/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099.cc 
b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099.cc
new file mode 100644
index 000000000000..2407119dcb1b
--- /dev/null
+++ b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/char/118099.cc
@@ -0,0 +1,57 @@
+// { dg-do run }
+// { dg-require-fileio "" }
+
+// PR libstdc++/118099
+// basic_filebuf::overflow leaves streambuf in inconsistent state on I/O error
+
+#include <fstream>
+#include <testsuite_hooks.h>
+
+static void
+test_pr118099()
+{
+  typedef char C;
+
+  // Only run if /dev/full already exists as a device: probe it with a
+  // read-only open first, so we never accidentally create a regular file
+  // named /dev/full on a hypothetical system with a writable /dev.
+  {
+    std::filebuf probe;
+    if (!probe.open("/dev/full", std::ios_base::in))
+      return; // no /dev/full here: nothing to test.
+  }
+
+  const C val = C('x');
+  const C canary = ~val;
+  const int N = 8;
+  C buf[N * 2] = { };
+  for (int i = 0; i < N * 2; ++i)
+    buf[i] = canary;
+
+  std::basic_filebuf<C> fb;
+  fb.pubsetbuf(buf, N); // filebuf can use buf[0..N]
+  fb.open("/dev/full", std::ios_base::out);
+  VERIFY( fb.is_open() );
+
+  int i = 0;
+  // Keep writing until overflow happens (and fails):
+  while (fb.sputc(val) != std::char_traits<C>::eof())
+    ++i;
+  // There should have been N-1 successful calls before overflow failed:
+  VERIFY( i == (N - 1) );
+  // Overflow some more:
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+
+  // Verify that only the first N positions in the buffer were changed:
+  for (i = 0; i < N; ++i)
+    VERIFY( buf[i] == val );
+  for (; i < N * 2; ++i)
+    VERIFY( buf[i] == canary );
+}
+
+int main()
+{
+  test_pr118099();
+}
diff --git 
a/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099-codecvt.cc 
b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099-codecvt.cc
new file mode 100644
index 000000000000..add23cc99500
--- /dev/null
+++ 
b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099-codecvt.cc
@@ -0,0 +1,76 @@
+// { dg-do run }
+// { dg-require-fileio "" }
+
+// PR libstdc++/118099
+// basic_filebuf::overflow leaves streambuf in inconsistent state on I/O error
+//
+// Companion test of 118099.cc testing the throwing failure path in overflow:
+// a codecvt whose do_out always returns error makes _M_convert_to_external
+// throw after the overflow character has been written to the end of put area.
+// If the put pointer is advanced before the throw (and only rewound on the
+// non-throwing error path), a caller that catches the exception and keeps
+// writing will cause overflow(c) to write past the end of the managed buffer,
+// just like the original PR libstdc++/118099 testcase.
+
+#include <fstream>
+#include <locale>
+#include <testsuite_hooks.h>
+
+typedef wchar_t C;
+
+struct failing_codecvt : std::codecvt<C, char, std::mbstate_t>
+{
+protected:
+  result
+  do_out(state_type&, const intern_type* from, const intern_type*,
+        const intern_type*& from_next,
+        extern_type* to, extern_type*, extern_type*& to_next) const
+  {
+    from_next = from;
+    to_next = to;
+    return error;
+  }
+
+  bool do_always_noconv() const throw() { return false; }
+};
+
+static void
+test_pr118099_codecvt()
+{
+  const C val = C('x');
+  const C canary = ~val;
+  const int N = 8;
+  C buf[N * 2];
+  for (int i = 0; i < N * 2; ++i)
+    buf[i] = canary;
+
+  std::basic_filebuf<C> fb;
+  fb.pubimbue(std::locale(std::locale::classic(), new failing_codecvt));
+  fb.pubsetbuf(buf, N); // filebuf can use buf[0..N]
+  fb.open("tmp_118099_codecvt", std::ios_base::out | std::ios_base::trunc);
+  VERIFY( fb.is_open() );
+
+  // Libstdc++ filebuf throws ios::failure for the codecvt error,
+  // but the standard allows overflow to return eof instead.
+  // To make this test portable, we check for either kind of error.
+  bool got_error = false;
+  for (int i = 0; i < N * 2; ++i)
+    try {
+      std::char_traits<C>::int_type r = fb.sputc(val);
+      if (std::char_traits<C>::eq_int_type(r, std::char_traits<C>::eof()))
+       got_error = true;
+    } catch (const std::exception&) {
+      got_error = true;
+    }
+  VERIFY( got_error ); // a codecvt error actually happened
+
+  for (int i = 0; i < N; ++i)
+    VERIFY( buf[i] == val );
+  for (int i = N; i < N * 2; ++i)
+    VERIFY( buf[i] == canary ); // nothing was written past buf[0..N]
+}
+
+int main()
+{
+  test_pr118099_codecvt();
+}
diff --git 
a/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099.cc 
b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099.cc
new file mode 100644
index 000000000000..bcbbd58ee9c1
--- /dev/null
+++ b/libstdc++-v3/testsuite/27_io/basic_filebuf/overflow/wchar_t/118099.cc
@@ -0,0 +1,57 @@
+// { dg-do run }
+// { dg-require-fileio "" }
+
+// PR libstdc++/118099
+// basic_filebuf::overflow leaves streambuf in inconsistent state on I/O error
+
+#include <fstream>
+#include <testsuite_hooks.h>
+
+static void
+test_pr118099()
+{
+  typedef wchar_t C;
+
+  // Only run if /dev/full already exists as a device: probe it with a
+  // read-only open first, so we never accidentally create a regular file
+  // named /dev/full on a hypothetical system with a writable /dev.
+  {
+    std::filebuf probe;
+    if (!probe.open("/dev/full", std::ios_base::in))
+      return; // no /dev/full here: nothing to test.
+  }
+
+  const C val = C('x');
+  const C canary = ~val;
+  const int N = 8;
+  C buf[N * 2] = { };
+  for (int i = 0; i < N * 2; ++i)
+    buf[i] = canary;
+
+  std::basic_filebuf<C> fb;
+  fb.pubsetbuf(buf, N); // filebuf can use buf[0..N]
+  fb.open("/dev/full", std::ios_base::out);
+  VERIFY( fb.is_open() );
+
+  int i = 0;
+  // Keep writing until overflow happens (and fails):
+  while (fb.sputc(val) != std::char_traits<C>::eof())
+    ++i;
+  // There should have been N-1 successful calls before overflow failed:
+  VERIFY( i == (N - 1) );
+  // Cause some more calls to overflow, which should also fail:
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+  VERIFY( fb.sputc(val) == std::char_traits<C>::eof() );
+
+  // Verify that only the first N positions in the buffer were changed:
+  for (i = 0; i < N; ++i)
+    VERIFY( buf[i] == val );
+  for (; i < N * 2; ++i)
+    VERIFY( buf[i] == canary );
+}
+
+int main()
+{
+  test_pr118099();
+}

Reply via email to