浏览代码

AK: Add input bounds checking to String::substring()

This checks for overflow in String::substring(). It also rearranges some
declarations in the header.
Max Wipfli 4 年之前
父节点
当前提交
17eddf3ac4
共有 2 个文件被更改,包括 12 次插入13 次删除
  1. 10 10
      AK/String.cpp
  2. 2 3
      AK/String.h

+ 10 - 10
AK/String.cpp

@@ -91,28 +91,28 @@ String String::isolated_copy() const
     return String(move(*impl));
 }
 
-String String::substring(size_t start) const
-{
-    VERIFY(m_impl);
-    VERIFY(start <= length());
-    return { characters() + start, length() - start };
-}
-
 String String::substring(size_t start, size_t length) const
 {
     if (!length)
-        return "";
+        return String::empty();
     VERIFY(m_impl);
+    VERIFY(!Checked<size_t>::addition_would_overflow(start, length));
     VERIFY(start + length <= m_impl->length());
-    // FIXME: This needs some input bounds checking.
     return { characters() + start, length };
 }
 
+String String::substring(size_t start) const
+{
+    VERIFY(m_impl);
+    VERIFY(start <= length());
+    return { characters() + start, length() - start };
+}
+
 StringView String::substring_view(size_t start, size_t length) const
 {
     VERIFY(m_impl);
+    VERIFY(!Checked<size_t>::addition_would_overflow(start, length));
     VERIFY(start + length <= m_impl->length());
-    // FIXME: This needs some input bounds checking.
     return { characters() + start, length };
 }
 

+ 2 - 3
AK/String.h

@@ -140,6 +140,7 @@ public:
 
     [[nodiscard]] Vector<String> split_limit(char separator, size_t limit, bool keep_empty = false) const;
     [[nodiscard]] Vector<String> split(char separator, bool keep_empty = false) const;
+    [[nodiscard]] Vector<StringView> split_view(char separator, bool keep_empty = false) const;
 
     [[nodiscard]] Optional<size_t> find(char needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); }
     [[nodiscard]] Optional<size_t> find(StringView const& needle, size_t start = 0) const { return StringUtils::find(*this, needle, start); }
@@ -147,10 +148,8 @@ public:
     // FIXME: Implement find_last(StringView const&) for API symmetry.
     [[nodiscard]] Vector<size_t> find_all(StringView const& needle) const { return StringUtils::find_all(*this, needle); }
 
-    [[nodiscard]] String substring(size_t start) const;
     [[nodiscard]] String substring(size_t start, size_t length) const;
-
-    [[nodiscard]] Vector<StringView> split_view(char separator, bool keep_empty = false) const;
+    [[nodiscard]] String substring(size_t start) const;
     [[nodiscard]] StringView substring_view(size_t start, size_t length) const;
     [[nodiscard]] StringView substring_view(size_t start) const;