]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
gdbsupport: add assertions in array_view
authorSimon Marchi <simon.marchi@efficios.com>
Tue, 19 Oct 2021 19:32:08 +0000 (15:32 -0400)
committerSimon Marchi <simon.marchi@polymtl.ca>
Mon, 25 Oct 2021 18:51:44 +0000 (14:51 -0400)
Add assertions to ensure we don't access an array_view out of bounds.
Enable these assertions only when _GLIBCXX_DEBUG is set, as we did for
gdb::optional.

Change-Id: Iffaee38252405073735ed123c8e57fde6b2c6be3

gdbsupport/array-view.h

index c41fd620f833ee5737bddea0751c484c74490664..ab1d032c60e4b516ea0cff29253aa3f5daec91da 100644 (file)
@@ -162,9 +162,19 @@ public:
   constexpr const T *end () const noexcept { return m_array + m_size; }
 
   /*constexpr14*/ reference operator[] (size_t index) noexcept
-  { return m_array[index]; }
+  {
+#if defined(_GLIBCXX_DEBUG)
+    gdb_assert (index < m_size);
+#endif
+    return m_array[index];
+  }
   constexpr const_reference operator[] (size_t index) const noexcept
-  { return m_array[index]; }
+  {
+#if defined(_GLIBCXX_DEBUG)
+    gdb_assert (index < m_size);
+#endif
+    return m_array[index];
+  }
 
   constexpr size_type size () const noexcept { return m_size; }
   constexpr bool empty () const noexcept { return m_size == 0; }
@@ -173,12 +183,22 @@ public:
 
   /* Return a new array view over SIZE elements starting at START.  */
   constexpr array_view<T> slice (size_type start, size_type size) const noexcept
-  { return {m_array + start, size}; }
+  {
+#if defined(_GLIBCXX_DEBUG)
+    gdb_assert (start + size <= m_size);
+#endif
+    return {m_array + start, size};
+  }
 
   /* Return a new array view over all the elements after START,
      inclusive.  */
   constexpr array_view<T> slice (size_type start) const noexcept
-  { return {m_array + start, size () - start}; }
+  {
+#if defined(_GLIBCXX_DEBUG)
+    gdb_assert (start <= m_size);
+#endif
+    return {m_array + start, size () - start};
+  }
 
 private:
   T *m_array;