|
| 1 | +#include <cstring> |
1 | 2 | #include <memory> |
2 | 3 | #include <string> |
3 | 4 |
|
@@ -118,6 +119,36 @@ TEST(JsonEscapeTest, Escape) { |
118 | 119 | expect_json_escape("\x1f", "\\u001f"); |
119 | 120 | } |
120 | 121 |
|
| 122 | +// Regression test for off-by-one write when control characters appear at the end of input. |
| 123 | +TEST(JsonEscapeTest, NulTerminatorIntegrity) { |
| 124 | + const auto verify_nul_terminator = [](absl::string_view input) { |
| 125 | + std::string escaped = JsonEscaper::escapeString(input, JsonEscaper::extraSpace(input)); |
| 126 | + |
| 127 | + // Verify the null terminator is intact. |
| 128 | + EXPECT_EQ('\0', escaped.c_str()[escaped.size()]) |
| 129 | + << "null terminator corrupted for input ending with control character"; |
| 130 | + |
| 131 | + // Verify strlen matches the size. A corrupted null terminator would cause strlen |
| 132 | + // to read past the string boundary. |
| 133 | + EXPECT_EQ(escaped.size(), std::strlen(escaped.c_str())) |
| 134 | + << "strlen mismatch indicates NUL terminator corruption"; |
| 135 | + }; |
| 136 | + |
| 137 | + // Test control characters at the end of input. These would trigger the buggy code path. |
| 138 | + verify_nul_terminator("\x01"); // Single control char. |
| 139 | + verify_nul_terminator("\x00"); // Single NUL. |
| 140 | + verify_nul_terminator("test\x01"); // Trailing control char. |
| 141 | + verify_nul_terminator(absl::string_view("test\x00", 5)); // Trailing NUL. |
| 142 | + verify_nul_terminator("\x01\x02"); // Multiple control chars. |
| 143 | + verify_nul_terminator("test\x01\x02"); // Multiple trailing control chars. |
| 144 | + verify_nul_terminator(std::string(100, 'A') + "\x1f"); // Large string ending with control char. |
| 145 | + |
| 146 | + // Test control characters not at the end. These should always work. |
| 147 | + verify_nul_terminator("\x01test"); // Leading control char. |
| 148 | + verify_nul_terminator("te\x01st"); // Middle control char. |
| 149 | + verify_nul_terminator("\x01test\x02more"); // Multiple control chars in middle. |
| 150 | +} |
| 151 | + |
121 | 152 | class LoggerCustomFlagsTest : public testing::TestWithParam<spdlog::logger*> { |
122 | 153 | public: |
123 | 154 | LoggerCustomFlagsTest() : logger_(GetParam()) {} |
|
0 commit comments