From 2d011961c94ac81700c366537f52208a4c55db92 Mon Sep 17 00:00:00 2001 From: Ben Wiederhake Date: Sun, 30 May 2021 13:10:37 +0200 Subject: [PATCH] AK: Fix accidentally-quadratic behavior in StringBuilder Found by OSS Fuzz: #34451 (old bug) Related commit: 3908a49661a00e15621748dcb2b0424f29433571 --- AK/ByteBuffer.h | 3 ++- AK/StringBuilder.cpp | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h index 76dc9c55c8..30785cab71 100644 --- a/AK/ByteBuffer.h +++ b/AK/ByteBuffer.h @@ -187,6 +187,8 @@ public: operator Bytes() { return bytes(); } operator ReadonlyBytes() const { return bytes(); } + ALWAYS_INLINE size_t capacity() const { return is_inline() ? inline_capacity : m_outline_capacity; } + private: ByteBuffer(size_t size) { @@ -236,7 +238,6 @@ private: } ALWAYS_INLINE bool is_inline() const { return m_size <= inline_capacity; } - ALWAYS_INLINE size_t capacity() const { return is_inline() ? inline_capacity : m_outline_capacity; } size_t m_size { 0 }; union { diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp index 53a72f04de..e834f3c944 100644 --- a/AK/StringBuilder.cpp +++ b/AK/StringBuilder.cpp @@ -21,10 +21,11 @@ inline void StringBuilder::will_append(size_t size) Checked needed_capacity = m_length; needed_capacity += size; VERIFY(!needed_capacity.has_overflow()); + if (needed_capacity <= m_buffer.capacity()) + return; + Checked expanded_capacity = needed_capacity; - // Prefer to completely use the inline buffer first - if (needed_capacity > inline_capacity) - expanded_capacity *= 2; + expanded_capacity *= 2; VERIFY(!expanded_capacity.has_overflow()); m_buffer.grow(expanded_capacity.value()); }