AK: Disallow calling String methods that return a view on rvalues

This prevents, for example:

    StringView view = "foo"_string.bytes_as_string_view();

This prevents a class of potential UAF.
This commit is contained in:
Timothy Flynn 2024-04-03 22:00:23 -04:00 committed by Andreas Kling
parent 38ca0f8db9
commit de80f544d8
Notes: sideshowbarker 2024-07-16 23:34:44 +09:00
2 changed files with 6 additions and 4 deletions

View file

@ -77,7 +77,7 @@ ErrorOr<String> String::repeated(u32 code_point, size_t count)
return result; return result;
} }
StringView String::bytes_as_string_view() const StringView String::bytes_as_string_view() const&
{ {
return StringView(bytes()); return StringView(bytes());
} }
@ -197,7 +197,7 @@ u32 String::ascii_case_insensitive_hash() const
return case_insensitive_string_hash(reinterpret_cast<char const*>(bytes().data()), bytes().size()); return case_insensitive_string_hash(reinterpret_cast<char const*>(bytes().data()), bytes().size());
} }
Utf8View String::code_points() const Utf8View String::code_points() const&
{ {
return Utf8View(bytes_as_string_view()); return Utf8View(bytes_as_string_view());
} }

View file

@ -107,13 +107,15 @@ public:
ErrorOr<String> substring_from_byte_offset_with_shared_superstring(size_t start) const; ErrorOr<String> substring_from_byte_offset_with_shared_superstring(size_t start) const;
// Returns an iterable view over the Unicode code points. // Returns an iterable view over the Unicode code points.
[[nodiscard]] Utf8View code_points() const; [[nodiscard]] Utf8View code_points() const&;
[[nodiscard]] Utf8View code_points() const&& = delete;
// Returns true if the String is zero-length. // Returns true if the String is zero-length.
[[nodiscard]] bool is_empty() const; [[nodiscard]] bool is_empty() const;
// Returns a StringView covering the full length of the string. Note that iterating this will go byte-at-a-time, not code-point-at-a-time. // Returns a StringView covering the full length of the string. Note that iterating this will go byte-at-a-time, not code-point-at-a-time.
[[nodiscard]] StringView bytes_as_string_view() const; [[nodiscard]] StringView bytes_as_string_view() const&;
[[nodiscard]] StringView bytes_as_string_view() const&& = delete;
[[nodiscard]] size_t count(StringView needle) const { return StringUtils::count(bytes_as_string_view(), needle); } [[nodiscard]] size_t count(StringView needle) const { return StringUtils::count(bytes_as_string_view(), needle); }