1515#include " src/stdio/ferror.h"
1616#include " src/stdio/fopen.h"
1717#include " src/stdio/fread.h"
18+ #include " src/stdio/fopencookie.h"
1819#endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
1920
2021#include " src/stdio/vfprintf.h"
@@ -29,11 +30,13 @@ using LIBC_NAMESPACE::fclose;
2930using LIBC_NAMESPACE::ferror;
3031using LIBC_NAMESPACE::fopen;
3132using LIBC_NAMESPACE::fread;
33+ using LIBC_NAMESPACE::fopencookie;
3234#else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
3335using ::fclose;
3436using ::ferror;
3537using ::fopen;
3638using ::fread;
39+ using ::fopencookie;
3740#endif // LIBC_COPT_STDIO_USE_SYSTEM_FILE
3841} // namespace printf_test
3942
@@ -98,3 +101,26 @@ TEST(LlvmLibcVFPrintfTest, WriteToFile) {
98101
99102 ASSERT_EQ (printf_test::fclose (file), 0 );
100103}
104+
105+ TEST (LlvmLibcVFPrintfTest, CharsWrittenOverflow) {
106+ struct NoopStream {};
107+ auto noop_write = [](void *cookie, const char *buf, size_t size) -> ssize_t {
108+ return size;
109+ };
110+
111+ NoopStream stream;
112+ cookie_io_functions_t funcs = {nullptr , +noop_write, nullptr , nullptr };
113+ ::FILE *file = printf_test::fopencookie (&stream, " w" , funcs);
114+ ASSERT_NE (file, nullptr );
115+
116+ // Trigger an overflow in the return value of vfprintf by writing more than
117+ // INT_MAX bytes. We do this by printing a string with precision INT_MAX, and
118+ // then one more character.
119+ int max_int = LIBC_NAMESPACE::cpp::numeric_limits<int >::max ();
120+ int result = call_vfprintf (file, " %*sA" , max_int, " " );
121+
122+ EXPECT_LT (result, 0 );
123+ ASSERT_ERRNO_EQ (EOVERFLOW);
124+
125+ EXPECT_EQ (printf_test::fclose (file), 0 );
126+ }
0 commit comments