From fb590e4eeb1aa897209b853430dc4854ece97802 Mon Sep 17 00:00:00 2001
From: Jakub Jelinek <jakub@redhat.com>
Date: Thu, 12 Oct 2023 16:07:25 +0200
Subject: [PATCH] wide-int: Add simple CHECKING_P stack-protector canary like
 checking

This patch adds hopefully not so expensive --enable-checking=yes
verification that the widest_int upper length bound estimates are really
upper bounds and nothing attempts to write more elements.
It is done only if the estimated upper length bound is smaller than
WIDE_INT_MAX_INL_ELTS, but that should be the most common case unless
large _BitInt is involved.

2023-10-12  Jakub Jelinek  <jakub@redhat.com>

	* wide-int.h (widest_int_storage <N>::write_val): If l is small
	and there is space in u.val array, store a canary value at the
	end when checking.
	(widest_int_storage <N>::set_len): Check the canary hasn't been
	overwritten.
---
 gcc/wide-int.h | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/gcc/wide-int.h b/gcc/wide-int.h
index 1b12472d41e7..07bacc9c9a54 100644
--- a/gcc/wide-int.h
+++ b/gcc/wide-int.h
@@ -1635,6 +1635,8 @@ widest_int_storage <N>::write_val (unsigned int l)
       u.valp = XNEWVEC (HOST_WIDE_INT, l);
       return u.valp;
     }
+  else if (CHECKING_P && l < WIDE_INT_MAX_INL_ELTS)
+    u.val[l] = HOST_WIDE_INT_UC (0xbaaaaaaddeadbeef);
   return u.val;
 }
 
@@ -1650,6 +1652,9 @@ widest_int_storage <N>::set_len (unsigned int l, bool)
       memcpy (u.val, valp, l * sizeof (u.val[0]));
       XDELETEVEC (valp);
     }
+  else if (len && len < WIDE_INT_MAX_INL_ELTS)
+    gcc_checking_assert ((unsigned HOST_WIDE_INT) u.val[len]
+			 == HOST_WIDE_INT_UC (0xbaaaaaaddeadbeef));
   len = l;
   /* There are no excess bits in val[len - 1].  */
   STATIC_ASSERT (N % HOST_BITS_PER_WIDE_INT == 0);
-- 
GitLab