Skip to content

Commit 7427a6b

Browse files
Abseil Teamcopybara-github
authored andcommitted
Use the provided length in ConditionalPrintAsText
While ConditionalPrintAsText gets a char pointer and the string length, it used to only pass the pointer to operator<<. That does not work for strings that are not zero terminated, because operator<< has to resort to strlen, which happily overflows the string buffer. This CL wraps the char pointer and the length in a string_view and passes that to operator<< to fix that issue. PiperOrigin-RevId: 765137769 Change-Id: Ie97067ce9d5b23175a512945fee943a8b95a94ff
1 parent 7da5582 commit 7427a6b

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

googletest/src/gtest-printers.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,7 @@ bool IsValidUTF8(const char* str, size_t length) {
516516
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
517517
if (!ContainsUnprintableControlCodes(str, length) &&
518518
IsValidUTF8(str, length)) {
519-
*os << "\n As Text: \"" << str << "\"";
519+
*os << "\n As Text: \"" << ::std::string_view(str, length) << "\"";
520520
}
521521
}
522522

googletest/test/googletest-printers-test.cc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1929,6 +1929,22 @@ TEST(UniversalPrintTest, SmartPointers) {
19291929
PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
19301930
}
19311931

1932+
TEST(UniversalPrintTest, StringViewNonZeroTerminated) {
1933+
// Craft a non-ASCII UTF-8 input (to trigger a special path in
1934+
// `ConditionalPrintAsText`). Use array notation instead of the string
1935+
// literal syntax, to avoid placing a terminating 0 at the end of the input.
1936+
const char s[] = {'\357', '\243', '\242', 'X'};
1937+
// Only include the first 3 bytes in the `string_view` and leave the last one
1938+
// ('X') outside. This way, if the code tries to use `str.data()` with
1939+
// `strlen` instead of `str.size()`, it will include 'X' and cause a visible
1940+
// difference (in addition to ASAN tests detecting a buffer overflow due to
1941+
// the missing 0 at the end).
1942+
const ::std::string_view str(s, 3);
1943+
::std::stringstream ss;
1944+
UniversalPrint(str, &ss);
1945+
EXPECT_EQ("\"\\xEF\\xA3\\xA2\"\n As Text: \"\xEF\xA3\xA2\"", ss.str());
1946+
}
1947+
19321948
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
19331949
Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
19341950
EXPECT_EQ(0u, result.size());

0 commit comments

Comments
 (0)