Skip to content

Commit e035a15

Browse files
committed
Add overflow test for vfprintf
1 parent 63c710b commit e035a15

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

libc/test/src/stdio/vfprintf_test.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
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;
2930
using LIBC_NAMESPACE::ferror;
3031
using LIBC_NAMESPACE::fopen;
3132
using LIBC_NAMESPACE::fread;
33+
using LIBC_NAMESPACE::fopencookie;
3234
#else // defined(LIBC_COPT_STDIO_USE_SYSTEM_FILE)
3335
using ::fclose;
3436
using ::ferror;
3537
using ::fopen;
3638
using ::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

Comments
 (0)