Add a debug assertion against in-place Base64 unescaping. Base64 unescaping does not support in-place decoding because it prepares the destination buffer before reading `src`. Document that `src` and `*dest` must not overlap in `absl::Base64Unescape()` and `absl::WebSafeBase64Unescape()`, and assert in debug builds that the input and output pointers differ. PiperOrigin-RevId: 1014789632
diff --git a/absl/strings/escaping.cc b/absl/strings/escaping.cc index efe9041..7338d37 100644 --- a/absl/strings/escaping.cc +++ b/absl/strings/escaping.cc
@@ -973,6 +973,8 @@ bool Base64UnescapeInternal(const char* absl_nullable src, size_t slen, String* absl_nonnull dest, const std::array<signed char, 256>& unbase64) { + ABSL_ASSERT(src != dest->data()); + // Determine the size of the output string. Base64 encodes every 3 bytes into // 4 characters. Any leftover chars are added directly for good measure. const size_t dest_len = 3 * (slen / 4) + (slen % 4);
diff --git a/absl/strings/escaping.h b/absl/strings/escaping.h index fb2de78..ee510b8 100644 --- a/absl/strings/escaping.h +++ b/absl/strings/escaping.h
@@ -154,7 +154,8 @@ // equivalent, writing it to a `dest` buffer, returning `true` on success. If // `src` contains invalid characters, `dest` is cleared and returns `false`. // If padding is included (note that `Base64Escape()` does produce it), it must -// be correct. In the padding, '=' and '.' are treated identically. +// be correct. In the padding, '=' and '.' are treated identically. `src` and +// `*dest` must not overlap. bool Base64Unescape(absl::string_view src, std::string* absl_nonnull dest); // WebSafeBase64Unescape() @@ -164,7 +165,7 @@ // success. If `src` contains invalid characters, `dest` is cleared and returns // `false`. If padding is included (note that `WebSafeBase64Escape()` does not // produce it), it must be correct. In the padding, '=' and '.' are treated -// identically. +// identically. `src` and `*dest` must not overlap. bool WebSafeBase64Unescape(absl::string_view src, std::string* absl_nonnull dest);
diff --git a/absl/strings/escaping_test.cc b/absl/strings/escaping_test.cc index e4a3868..7af9841 100644 --- a/absl/strings/escaping_test.cc +++ b/absl/strings/escaping_test.cc
@@ -706,6 +706,28 @@ EXPECT_EQ(huge, unescaped); } +#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST +TEST(Base64DeathTest, InPlaceUnescape) { + { + std::string s; + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } + + { + std::string s = "YWJj"; + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } + + { + std::string s(64, 'A'); + EXPECT_DEATH(absl::Base64Unescape(s, &s), ""); + EXPECT_DEATH(absl::WebSafeBase64Unescape(s, &s), ""); + } +} +#endif // !defined(NDEBUG) && GTEST_HAS_DEATH_TEST + TEST(Escaping, HexStringToBytesBackToHex) { std::string bytes, hex;