From 27cc7c57bb211b74bbcf0d2f2bb6618a759b75dc Mon Sep 17 00:00:00 2001
From: Tristan Partin <tristan@partin.io>
Date: Wed, 29 Jul 2026 19:38:39 +0000
Subject: [PATCH v1 1/2] Add pg_attribute_counted_by()

The counted_by attribute allows specifying that an array member (pointer
or flexible array) of a struct is "counted by" another member of the
same struct. Not only does this attribute make arrays a little more
self-documenting, but it is also a hint to the compiler that can improve
detection of object size information and provide better results in
compile time diagnostics and runtime features like the array bound
sanitizer.

Signed-off-by: Tristan Partin <tristan@partin.io>
---
 src/include/c.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 20cfbac54e7..e83c1e391a7 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -297,6 +297,18 @@ extern "C++"
 #define pg_attribute_target(...)
 #endif
 
+/*
+ * pg_attribute_counted_by allows specifying that an array is "counted by"
+ * another struct member. This provides the compiler to improve detection of
+ * object size information and provide better results in compile time
+ * diagnostics and runtime features like the array bound sanitizer.
+ */
+#if __has_attribute (counted_by)
+#define pg_attribute_counted_by(...) __attribute__((counted_by(__VA_ARGS__)))
+#else
+#define pg_attribute_counted_by(...)
+#endif
+
 /*
  * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
  * used in assert-enabled builds, to avoid compiler warnings about unused
-- 
Tristan Partin
https://tristan.partin.io

