Skip to contentSkip to conversation

Add __counted_by_ptr macro

PATCH Superseded Bill Wendling 8 participants 35 messages Nov 21, 2025 – Feb 10

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

cover Add __counted_by_ptr macro

These patches add the __counted_by_ptr macro and then uses it in mm/memblock.h. The name of the __counted_by_ptr attribute is the same as __counted_by, but two different macros are needed, because of feature skew in GCC and clang. Once the minmum versions of the compilers support 'counted_by' on both flexible array members and pointers in structs, this macro will become obsolete.

Bill Wendling (2):
Compiler Attributes: Add __counted_by_ptr macro
memblock: annotate struct memblock_type with __counted_by_ptr

 include/linux/compiler_types.h | 11 +++++++++++
 include/linux/memblock.h       |  2 +-
 init/Kconfig                   |  5 +++++
 3 files changed, 17 insertions(+), 1 deletion(-)
Signature · 1 line
2.52.0.rc2.455.g230fcf2819-goog
#1 lore raw

PATCH 1/2 Compiler Attributes: Add __counted_by_ptr macro

Clang and GCC are expanding the '__counted_by' attribute to support pointers in structs. Clang has support for it since version 21. This requires defining a separate macro, '__counted_by_ptr', because, while the attribute has the same name for both a pointer and a flexible array member, minimal compiler versions need to catch up.

The effect of this feature is the same as for __counted_by on flexible array members. It provides hardening the ability to perform run-time bounds checking on otherwise unknown-size pointers.

Cc Kees Cook <[email protected]>
Cc "Gustavo A. R. Silva" <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Justin Stitt <[email protected]>
Cc Miguel Ojeda <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Marc Herbert <[email protected]>
Cc Uros Bizjak <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Jeff Xu <[email protected]>
Cc "Michal Koutný" <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc "Thomas Weißschuh" <[email protected]>
Cc John Stultz <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Brian Gerst <[email protected]>
Cc Masahiro Yamada <[email protected]>
---
 include/linux/compiler_types.h | 11 +++++++++++
 init/Kconfig                   |  5 +++++
 2 files changed, 16 insertions(+)
include/linux/compiler_types.h +11 -0
index 0a1b9598940d..2b0251bb951c 100644
@@ -351,6 +351,17 @@ struct ftrace_likely_data {
 # define __assume(expr)
 #endif
 
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: only supported since clang >= 18
init/Kconfig +5 -0
index cab3ad28ca49..298c94c4c1b1 100644
@@ -139,6 +139,11 @@ config CC_HAS_COUNTED_BY
 	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
 	default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_ON_POINTERS
+	bool
+	# Needs clang 21.1.0 or higher.
+	default y if CC_IS_CLANG && CLANG_VERSION >= 210100
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Signature · 1 line
2.52.0.rc2.455.g230fcf2819-goog
#2 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 68 lines · Bill Wendling

Clang and GCC are expanding the '__counted_by' attribute to support pointers in structs. Clang has support for it since version 21. This requires defining a separate macro, '__counted_by_ptr', because, while the attribute has the same name for both a pointer and a flexible array member, minimal compiler versions need to catch up.

The effect of this feature is the same as for __counted_by on flexible array members. It provides hardening the ability to perform run-time bounds checking on otherwise unknown-size pointers.

Cc Kees Cook <[email protected]>
Cc "Gustavo A. R. Silva" <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Justin Stitt <[email protected]>
Cc Miguel Ojeda <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Marc Herbert <[email protected]>
Cc Uros Bizjak <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Jeff Xu <[email protected]>
Cc "Michal Koutný" <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc "Thomas Weißschuh" <[email protected]>
Cc John Stultz <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Brian Gerst <[email protected]>
Cc Masahiro Yamada <[email protected]>
---
 include/linux/compiler_types.h | 11 +++++++++++
 init/Kconfig                   |  5 +++++
 2 files changed, 16 insertions(+)
include/linux/compiler_types.h +11 -0
index 0a1b9598940d..2b0251bb951c 100644
@@ -351,6 +351,17 @@ struct ftrace_likely_data {
 # define __assume(expr)
 #endif
 
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)       __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: only supported since clang >= 18
init/Kconfig +0 -0
index cab3ad28ca49..298c94c4c1b1 100644

init/Kconfig config CC_HAS_COUNTED_BY · line 146

Quoted 8 lines
init/Kconfig +5 -0
@@ -139,6 +139,11 @@ config CC_HAS_COUNTED_BY
        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
        default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_ON_POINTERS
+       bool
+       # Needs clang 21.1.0 or higher.
+       default y if CC_IS_CLANG && CLANG_VERSION >= 210100
+

I mistakenly left out GCC from here. I'll roll that in with v2.

-bw

Quoted 6 lines
init/Kconfig +0 -1
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
        def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
--

2.52.0.rc2.455.g230fcf2819-goog

#3 lore raw

PATCH v2 1/2 Compiler Attributes: Add __counted_by_ptr macro

In reply to Bill Wendling

Clang and GCC are expanding the '__counted_by' attribute to support pointers in structs. Clang has support for it since version 21. This requires defining a separate macro, '__counted_by_ptr', because, while the attribute has the same name for both a pointer and a flexible array member, minimal compiler versions need to catch up.

The effect of this feature is the same as for __counted_by on flexible array members. It provides hardening the ability to perform run-time bounds checking on otherwise unknown-size pointers.

Cc Kees Cook <[email protected]>
Cc Qing Zhao <[email protected]>
Cc "Gustavo A. R. Silva" <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Justin Stitt <[email protected]>
Cc Miguel Ojeda <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Marc Herbert <[email protected]>
Cc Uros Bizjak <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Jeff Xu <[email protected]>
Cc "Michal Koutný" <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc "Thomas Weißschuh" <[email protected]>
Cc John Stultz <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Brian Gerst <[email protected]>
Cc Masahiro Yamada <[email protected]>

---
v2 - Add support for GCC.

---
 include/linux/compiler_types.h | 11 +++++++++++
 init/Kconfig                   |  7 +++++++
 2 files changed, 18 insertions(+)
include/linux/compiler_types.h +11 -0
index 0a1b9598940d..2b0251bb951c 100644
@@ -351,6 +351,17 @@ struct ftrace_likely_data {
 # define __assume(expr)
 #endif
 
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: only supported since clang >= 18
init/Kconfig +7 -0
index cab3ad28ca49..f947f242bca8 100644
@@ -139,6 +139,13 @@ config CC_HAS_COUNTED_BY
 	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
 	default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_ON_POINTERS
+	bool
+	# supported since clang 21.1.0
+	default y if CC_IS_CLANG && CLANG_VERSION >= 210100
+	# supported since gcc 16.0.0
+	default y if CC_IS_GCC && GCC_VERSION >= 160000
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Signature · 1 line
2.52.0.rc2.455.g230fcf2819-goog
#4 lore raw

Re: [PATCH v2 1/2] Compiler Attributes: Add __counted_by_ptr macro

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)       __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

I guess there is a reason for this name, but it sounds to me a bit like the thing between parenthesis is a pointer, i.e. that perhaps it is the pointee that one that counts.

Hmm... what about __ptr_counted_by?

In addition, could we please provide a bit of context in the documentation? i.e. links to the attribute docs in both Clang and GCC.

And perhaps explaining why this cannot use __has_attribute, i.e. what the commit log mentions.

Thanks!

Cheers,
Miguel

#5 lore raw

Re: [PATCH v2 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 17 lines · Miguel Ojeda

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)       __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

I guess there is a reason for this name, but it sounds to me a bit like the thing between parenthesis is a pointer, i.e. that perhaps it is the pointee that one that counts.

Quoted 8 lines

Hmm... what about __ptr_counted_by?

In addition, could we please provide a bit of context in the documentation? i.e. links to the attribute docs in both Clang and GCC.

And perhaps explaining why this cannot use __has_attribute, i.e. what the commit log mentions.

The attribute used to be hidden behind "__has_attribute" (git show c8248faf3ca2), but was converted to a 'CONFIG_' variable due to (I assume) bug fixes that occurred at different compiler versions (git show f06e108a3dc53). Also "__has_attribute" won't work in this situation, because the attribute name, "__counted_by__", is used for both a pointer field (unsupported) and the flexible array member (supported).

The naming of the macro is flexible of course. I have a preference for adding a suffix, because there are other expansions of this and other bounds safety attributes where, during discussions about the attributes' syntaxes, we've been using suffixes. I.e., Clang supports a limited form of context-free expressions as the argument to the attribute. We want to add support for that in the future, but there are issues with adding that support to GCC that haven't been ironed out yet. We've been calling that macro "__counted_by_expr", because again the attribute name is the same. This is not to say that it's the *best* name for the macro, but it does seem natural.

I'll add these explanations to the commit message in a new version after I collect all feedback. :-)

Thanks!
-bw

#6 lore raw

Re: [PATCH v2 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to Miguel Ojeda
Quoted 17 lines · Miguel Ojeda

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)       __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

I guess there is a reason for this name, but it sounds to me a bit like the thing between parenthesis is a pointer, i.e. that perhaps it is the pointee that one that counts.

Quoted 1 line

Hmm... what about __ptr_counted_by?

Kees promised to drop this attribute once GCC-16 releases by basically doing 's/__counted_by_ptr/__counted_by/' and unifying things again.

This split out state will only exist for a very short while until GCC has a release with this feature on.

#7 lore raw

Re: [PATCH v2 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 18 lines · Peter Zijlstra
Quoted 17 lines · Miguel Ojeda

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)       __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

I guess there is a reason for this name, but it sounds to me a bit like the thing between parenthesis is a pointer, i.e. that perhaps it is the pointee that one that counts.

Quoted 4 lines
Quoted 1 line

Hmm... what about __ptr_counted_by?

Kees promised to drop this attribute once GCC-16 releases by basically doing 's/__counted_by_ptr/__counted_by/' and unifying things again.

Yeah, this will effectively raise "counted_by" support to GCC 16 (from
15) and to Clang 22 (from 20). I'd still prefer to keep the earlier support, but we'll see how it goes.

-Kees

Signature · 1 line
Kees Cook
#8 lore raw

Re: [PATCH v2 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to Peter Zijlstra
Quoted 6 lines · Peter Zijlstra

Kees promised to drop this attribute once GCC-16 releases by basically doing 's/__counted_by_ptr/__counted_by/' and unifying things again.

This split out state will only exist for a very short while until GCC has a release with this feature on.

Ah, I see, thanks!

(even if it happens later, that sounds fine)

Cheers,
Miguel

#9 lore raw

PATCH 1/2 Compiler Attributes: Add __counted_by_ptr macro

In reply to Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

Note that Clang's support for "void *" members will be in version 22. So, when using Clang, you'll need to wait until its release before using the feature with "void *". No such restriction applies to GCC's version 16.

This is a reworking of Kees' previous patch [1].

---
Cc: Kees Cook <[email protected]>
Cc: "Gustavo A. R. Silva" <[email protected]>
Cc: Nathan Chancellor <[email protected]>
Cc: Nick Desaulniers <[email protected]>
Cc: Justin Stitt <[email protected]>
Cc: Miguel Ojeda <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Marc Herbert <[email protected]>
Cc: Uros Bizjak <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Jeff Xu <[email protected]>
Cc: "Michal Koutný" <[email protected]>
Cc: Shakeel Butt <[email protected]>
Cc: "Thomas Weißschuh" <[email protected]>
Cc: John Stultz <[email protected]>
Cc: Christian Brauner <[email protected]>
Cc: Randy Dunlap <[email protected]>
Cc: Brian Gerst <[email protected]>
Cc: Masahiro Yamada <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
v3 - Replace the previous code with a modified version of Kees' previous patch

     [1].

- The question about the naming of the macro was considered, but we decided to keep the original naming (__counted_by_ptr), because it mirrors the current macros like "__counted_by_{le,be}".
v2 - Add support for GCC.

---
 Makefile                       |  6 ++++++
 include/linux/compiler_types.h | 18 +++++++++++++++++-
 include/uapi/linux/stddef.h    |  4 ++++
 init/Kconfig                   |  7 +++++++
 4 files changed, 34 insertions(+), 1 deletion(-)
Makefile +6 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
+endif
+endif
+
 # Explicitly clear padding bits during variable initialization
 KBUILD_CFLAGS += $(call cc-option,-fzero-init-padding-bits=all)
 
include/linux/compiler_types.h +17 -1
index d3318a3c2577..e597c814d60b 100644
@@ -369,7 +369,7 @@ struct ftrace_likely_data {
  * Optional: only supported since clang >= 18
  *
  *   gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
- * clang: https://github.com/llvm/llvm-project/pull/76348
+ * clang: https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
  *
  * __bdos on clang < 19.1.2 can erroneously return 0:
  * https://github.com/llvm/llvm-project/pull/110497
@@ -383,6 +383,22 @@ struct ftrace_likely_data {
 # define __counted_by(member)
 #endif
 
+/*
+ * Runtime track number of objects pointed to by a pointer member for use by
+ * CONFIG_FORTIFY_SOURCE and CONFIG_UBSAN_BOUNDS.
+ *
+ * Optional: only supported since gcc >= 16
+ * Optional: only supported since clang >= 21.1
+ *
+ *   gcc: https://gcc.gnu.org/pipermail/gcc-patches/2025-April/681727.html
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: not supported by Clang
include/uapi/linux/stddef.h +4 -0
index 9a28f7d9a334..111b097ec00b 100644
@@ -72,6 +72,10 @@
 #define __counted_by_be(m)
 #endif
 
+#ifndef __counted_by_ptr
+#define __counted_by_ptr(m)
+#endif
+
 #ifdef __KERNEL__
 #define __kernel_nonstring	__nonstring
 #else
init/Kconfig +7 -0
index fa79feb8fe57..dc27b998d111 100644
@@ -143,6 +143,13 @@ config CC_HAS_COUNTED_BY
 	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
 	default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_PTR
+	bool
+	# supported since clang 21.1.0
+	default y if CC_IS_CLANG && CLANG_VERSION >= 210100
+	# supported since gcc 16.0.0
+	default y if CC_IS_GCC && GCC_VERSION >= 160000
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Signature · 1 line
2.52.0.457.g6b5491de43-goog
#10 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 11 lines · Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};
Quoted 8 lines

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

Note that Clang's support for "void *" members will be in version 22. So, when using Clang, you'll need to wait until its release before using the feature with "void *". No such restriction applies to GCC's version 16.

I think to keep operational parity, we should limit counted_ptr on Clang to version 22 then, otherwise we'll have problems using it on void *.

Quoted 1 line

This is a reworking of Kees' previous patch [1].

Thanks for this!

Quoted 3 lines

This needs to be followed by my S-o-b, I think? checkpatch.pl ought to check this.

Quoted 71 lines

---
Cc: Kees Cook <[email protected]>
Cc: "Gustavo A. R. Silva" <[email protected]>
Cc: Nathan Chancellor <[email protected]>
Cc: Nick Desaulniers <[email protected]>
Cc: Justin Stitt <[email protected]>
Cc: Miguel Ojeda <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Marc Herbert <[email protected]>
Cc: Uros Bizjak <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Jeff Xu <[email protected]>
Cc: "Michal Koutný" <[email protected]>
Cc: Shakeel Butt <[email protected]>
Cc: "Thomas Weißschuh" <[email protected]>
Cc: John Stultz <[email protected]>
Cc: Christian Brauner <[email protected]>
Cc: Randy Dunlap <[email protected]>
Cc: Brian Gerst <[email protected]>
Cc: Masahiro Yamada <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
v3 - Replace the previous code with a modified version of Kees' previous patch

     [1].

- The question about the naming of the macro was considered, but we decided to keep the original naming (__counted_by_ptr), because it mirrors the current macros like "__counted_by_{le,be}".
v2 - Add support for GCC.

---
 Makefile                       |  6 ++++++
 include/linux/compiler_types.h | 18 +++++++++++++++++-
 include/uapi/linux/stddef.h    |  4 ++++
 init/Kconfig                   |  7 +++++++
 4 files changed, 34 insertions(+), 1 deletion(-)
Makefile +6 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
+endif
+endif
+
 # Explicitly clear padding bits during variable initialization
 KBUILD_CFLAGS += $(call cc-option,-fzero-init-padding-bits=all)
 
include/linux/compiler_types.h +1 -1
index d3318a3c2577..e597c814d60b 100644
@@ -369,7 +369,7 @@ struct ftrace_likely_data {
  * Optional: only supported since clang >= 18
  *
  *   gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
- * clang: https://github.com/llvm/llvm-project/pull/76348
+ * clang: https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
  *
  * __bdos on clang < 19.1.2 can erroneously return 0:
  * https://github.com/llvm/llvm-project/pull/110497

include/linux/compiler_types.h struct ftrace_likely_data { · line 391

Quoted 9 lines
include/linux/compiler_types.h +6 -0
@@ -383,6 +383,22 @@ struct ftrace_likely_data {
 # define __counted_by(member)
 #endif
 
+/*
+ * Runtime track number of objects pointed to by a pointer member for use by
+ * CONFIG_FORTIFY_SOURCE and CONFIG_UBSAN_BOUNDS.
+ *
+ * Optional: only supported since gcc >= 16
+ * Optional: only supported since clang >= 21.1

As I mention above, let's make this 22

include/linux/compiler_types.h struct ftrace_likely_data { · line 394

Quoted 3 lines
include/linux/compiler_types.h +3 -0
+ *
+ *   gcc: https://gcc.gnu.org/pipermail/gcc-patches/2025-April/681727.html
+ * clang: https://github.com/llvm/llvm-project/pull/137250

Oh, hm, did the docs for
https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
not get updated by the above PR? Docs should get added to LLVM for this so we can link to the same AttributeReference.html as above.

And, actually, same question for GCC, now that I'm looking at this...

Quoted 30 lines
include/linux/compiler_types.h +7 -0
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: not supported by Clang
include/uapi/linux/stddef.h +4 -0
index 9a28f7d9a334..111b097ec00b 100644
@@ -72,6 +72,10 @@
 #define __counted_by_be(m)
 #endif
 
+#ifndef __counted_by_ptr
+#define __counted_by_ptr(m)
+#endif
+
 #ifdef __KERNEL__
 #define __kernel_nonstring	__nonstring
 #else
init/Kconfig +0 -0
index fa79feb8fe57..dc27b998d111 100644

init/Kconfig config CC_HAS_COUNTED_BY · line 149

Quoted 7 lines
init/Kconfig +4 -0
@@ -143,6 +143,13 @@ config CC_HAS_COUNTED_BY
 	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
 	default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_PTR
+	bool
+	# supported since clang 21.1.0
+	default y if CC_IS_CLANG && CLANG_VERSION >= 210100

Let's do 22

Quoted 9 lines
init/Kconfig +3 -0
+	# supported since gcc 16.0.0
+	default y if CC_IS_GCC && GCC_VERSION >= 160000
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Signature · 1 line
2.52.0.457.g6b5491de43-goog

Great! Once this is fixed up, I'll snag the other 2 patches from my original series too.

Thanks!

-Kees

Signature · 1 line
Kees Cook
#11 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 177 lines · Kees Cook
Quoted 11 lines · Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
      int a, b, c;
      char *buffer __counted_by_ptr(bytes);
      short nr_bars;
      struct bar *bars __counted_by_ptr(nr_bars);
      size_t bytes;
};
Quoted 8 lines

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

Note that Clang's support for "void *" members will be in version 22. So, when using Clang, you'll need to wait until its release before using the feature with "void *". No such restriction applies to GCC's version 16.

I think to keep operational parity, we should limit counted_ptr on Clang to version 22 then, otherwise we'll have problems using it on void *.

Quoted 1 line

This is a reworking of Kees' previous patch [1].

Thanks for this!

Quoted 3 lines

This needs to be followed by my S-o-b, I think? checkpatch.pl ought to check this.

Quoted 71 lines

---
Cc: Kees Cook <[email protected]>
Cc: "Gustavo A. R. Silva" <[email protected]>
Cc: Nathan Chancellor <[email protected]>
Cc: Nick Desaulniers <[email protected]>
Cc: Justin Stitt <[email protected]>
Cc: Miguel Ojeda <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Marc Herbert <[email protected]>
Cc: Uros Bizjak <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Jeff Xu <[email protected]>
Cc: "Michal Koutný" <[email protected]>
Cc: Shakeel Butt <[email protected]>
Cc: "Thomas Weißschuh" <[email protected]>
Cc: John Stultz <[email protected]>
Cc: Christian Brauner <[email protected]>
Cc: Randy Dunlap <[email protected]>
Cc: Brian Gerst <[email protected]>
Cc: Masahiro Yamada <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
---
v3 - Replace the previous code with a modified version of Kees' previous patch

     [1].

- The question about the naming of the macro was considered, but we decided to keep the original naming (__counted_by_ptr), because it mirrors the current macros like "__counted_by_{le,be}".
v2 - Add support for GCC.

---
 Makefile                       |  6 ++++++
 include/linux/compiler_types.h | 18 +++++++++++++++++-
 include/uapi/linux/stddef.h    |  4 ++++
 init/Kconfig                   |  7 +++++++
 4 files changed, 34 insertions(+), 1 deletion(-)
Makefile +6 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS    += $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS        += -fexperimental-late-parse-attributes
+endif
+endif
+
 # Explicitly clear padding bits during variable initialization
 KBUILD_CFLAGS += $(call cc-option,-fzero-init-padding-bits=all)
 
include/linux/compiler_types.h +1 -1
index d3318a3c2577..e597c814d60b 100644
@@ -369,7 +369,7 @@ struct ftrace_likely_data {
  * Optional: only supported since clang >= 18
  *
  *   gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
- * clang: https://github.com/llvm/llvm-project/pull/76348
+ * clang: https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
  *
  * __bdos on clang < 19.1.2 can erroneously return 0:
  * https://github.com/llvm/llvm-project/pull/110497

include/linux/compiler_types.h struct ftrace_likely_data { · line 391

Quoted 9 lines
include/linux/compiler_types.h +6 -0
@@ -383,6 +383,22 @@ struct ftrace_likely_data {
 # define __counted_by(member)
 #endif
 
+/*
+ * Runtime track number of objects pointed to by a pointer member for use by
+ * CONFIG_FORTIFY_SOURCE and CONFIG_UBSAN_BOUNDS.
+ *
+ * Optional: only supported since gcc >= 16
+ * Optional: only supported since clang >= 21.1

As I mention above, let's make this 22

include/linux/compiler_types.h struct ftrace_likely_data { · line 394

Quoted 3 lines
include/linux/compiler_types.h +3 -0
+ *
+ *   gcc: https://gcc.gnu.org/pipermail/gcc-patches/2025-April/681727.html
+ * clang: https://github.com/llvm/llvm-project/pull/137250

Oh, hm, did the docs for
https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
not get updated by the above PR? Docs should get added to LLVM for this so we can link to the same AttributeReference.html as above.

And, actually, same question for GCC, now that I'm looking at this...

Quoted 30 lines
include/linux/compiler_types.h +7 -0
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+#define __counted_by_ptr(member)     __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: not supported by Clang
include/uapi/linux/stddef.h +4 -0
index 9a28f7d9a334..111b097ec00b 100644
@@ -72,6 +72,10 @@
 #define __counted_by_be(m)
 #endif
 
+#ifndef __counted_by_ptr
+#define __counted_by_ptr(m)
+#endif
+
 #ifdef __KERNEL__
 #define __kernel_nonstring   __nonstring
 #else
init/Kconfig +0 -0
index fa79feb8fe57..dc27b998d111 100644

init/Kconfig config CC_HAS_COUNTED_BY · line 149

Quoted 7 lines
init/Kconfig +4 -0
@@ -143,6 +143,13 @@ config CC_HAS_COUNTED_BY
      # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
      default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_PTR
+     bool
+     # supported since clang 21.1.0
+     default y if CC_IS_CLANG && CLANG_VERSION >= 210100

Let's do 22

Quoted 6 lines
init/Kconfig +3 -0
+     # supported since gcc 16.0.0
+     default y if CC_IS_GCC && GCC_VERSION >= 160000
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
      def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Quoted 7 lines
Quoted 3 lines

--
2.52.0.457.g6b5491de43-goog

Great! Once this is fixed up, I'll snag the other 2 patches from my original series too.

Should be corrected now. PTAL.

-bw

#12 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to Kees Cook
Quoted 16 lines · Kees Cook
Quoted 15 lines · Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

Quoted 7 lines
Quoted 4 lines

Note that Clang's support for "void *" members will be in version 22. So, when using Clang, you'll need to wait until its release before using the feature with "void *". No such restriction applies to GCC's version 16.

I think to keep operational parity, we should limit counted_ptr on Clang to version 22 then, otherwise we'll have problems using it on void *.

Ooh, you got that fixed! Nice!

#13 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 5 lines · Peter Zijlstra
Quoted 2 lines · Kees Cook

I think to keep operational parity, we should limit counted_ptr on Clang to version 22 then, otherwise we'll have problems using it on void *.

Ooh, you got that fixed! Nice!

Yes, to my great relief, I was able to convince both GCC and Clang.

Signature · 1 line
Kees Cook
#14 lore raw

PATCH v4 1/2 Compiler Attributes: Add __counted_by_ptr macro

In reply to Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

This is a reworking of Kees' previous patch [1].

---
v4 - Default to Clang's version 22, which has support for "void *".
- Add the missing S-o-b notation.
v3 - Replace the previous code with a modified version of Kees'
previous patch [1].
- The question about the naming of the macro was considered, but we decided to keep the original naming (__counted_by_ptr), because it mirrors the current macros like "__counted_by_{le,be}".
v2 - Add support for GCC.
---
Cc: Kees Cook <[email protected]>
Cc: "Gustavo A. R. Silva" <[email protected]>
Cc: Nathan Chancellor <[email protected]>
Cc: Nick Desaulniers <[email protected]>
Cc: Justin Stitt <[email protected]>
Cc: Miguel Ojeda <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Marc Herbert <[email protected]>
Cc: Uros Bizjak <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Jeff Xu <[email protected]>
Cc: "Michal Koutný" <[email protected]>
Cc: Shakeel Butt <[email protected]>
Cc: "Thomas Weißschuh" <[email protected]>
Cc: John Stultz <[email protected]>
Cc: Christian Brauner <[email protected]>
Cc: Randy Dunlap <[email protected]>
Cc: Brian Gerst <[email protected]>
Cc: Masahiro Yamada <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
 Makefile                       |  6 ++++++
 include/linux/compiler_types.h | 18 +++++++++++++++++-
 include/uapi/linux/stddef.h    |  4 ++++
 init/Kconfig                   |  7 +++++++
 4 files changed, 34 insertions(+), 1 deletion(-)
Makefile +6 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
+endif
+endif
+
 # Explicitly clear padding bits during variable initialization
 KBUILD_CFLAGS += $(call cc-option,-fzero-init-padding-bits=all)
 
include/linux/compiler_types.h +17 -1
index d3318a3c2577..d095beb904ea 100644
@@ -369,7 +369,7 @@ struct ftrace_likely_data {
  * Optional: only supported since clang >= 18
  *
  *   gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
- * clang: https://github.com/llvm/llvm-project/pull/76348
+ * clang: https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
  *
  * __bdos on clang < 19.1.2 can erroneously return 0:
  * https://github.com/llvm/llvm-project/pull/110497
@@ -383,6 +383,22 @@ struct ftrace_likely_data {
 # define __counted_by(member)
 #endif
 
+/*
+ * Runtime track number of objects pointed to by a pointer member for use by
+ * CONFIG_FORTIFY_SOURCE and CONFIG_UBSAN_BOUNDS.
+ *
+ * Optional: only supported since gcc >= 16
+ * Optional: only supported since clang >= 22
+ *
+ *   gcc: https://gcc.gnu.org/pipermail/gcc-patches/2025-April/681727.html
+ * clang: https://clang.llvm.org/docs/AttributeReference.html#counted-by-counted-by-or-null-sized-by-sized-by-or-null
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif
+
 /*
  * Optional: only supported since gcc >= 15
  * Optional: not supported by Clang
include/uapi/linux/stddef.h +4 -0
index 9a28f7d9a334..111b097ec00b 100644
@@ -72,6 +72,10 @@
 #define __counted_by_be(m)
 #endif
 
+#ifndef __counted_by_ptr
+#define __counted_by_ptr(m)
+#endif
+
 #ifdef __KERNEL__
 #define __kernel_nonstring	__nonstring
 #else
init/Kconfig +7 -0
index fa79feb8fe57..96b7cd481eaa 100644
@@ -143,6 +143,13 @@ config CC_HAS_COUNTED_BY
 	# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896
 	default y if CC_IS_GCC && GCC_VERSION >= 150100
 
+config CC_HAS_COUNTED_BY_PTR
+	bool
+	# supported since clang 22
+	default y if CC_IS_CLANG && CLANG_VERSION >= 220000
+	# supported since gcc 16.0.0
+	default y if CC_IS_GCC && GCC_VERSION >= 160000
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
Signature · 1 line
2.52.0.457.g6b5491de43-goog
#15 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 14 lines · On Fri, 16 Jan 2026 00:57:57 +0000 Bill Wendling <[email protected]> wrote:

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

...

Makefile KBUILD_CFLAGS += $(CC_AUTO_VAR_INIT_ZERO_ENABLER) · line 959

Quoted 13 lines
Makefile +5 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
+endif
+endif

Will that still be needed for clang 22?
Looks a bit like a temporary flag to avoid regressions. Probably ought to at least have a comment that it won't be needed by some future clang version so that it gets tidied up.

David

#16 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 26 lines · David Laight
Quoted 14 lines · On Fri, 16 Jan 2026 00:57:57 +0000 Bill Wendling <[email protected]> wrote:

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

...

Quoted 8 lines
Makefile +0 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
Quoted 7 lines

Makefile KBUILD_CFLAGS += $(CC_AUTO_VAR_INIT_ZERO_ENABLER) · line 959

Quoted 5 lines
Makefile +5 -0
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
+endif
+endif

Will that still be needed for clang 22?

AFAIK, yes. AIUI, this flag will remain while -fbounds-safety continues to be upstreamed into LLVM.

Quoted 3 lines

Looks a bit like a temporary flag to avoid regressions. Probably ought to at least have a comment that it won't be needed by some future clang version so that it gets tidied up.

Once it's no longer needed, yes, I will want it removed from the Makefile.

Signature · 1 line
Kees Cook
#17 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 39 lines · Kees Cook
Quoted 26 lines · David Laight
Quoted 14 lines · On Fri, 16 Jan 2026 00:57:57 +0000 Bill Wendling <[email protected]> wrote:

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
    int a, b, c;
    char *buffer __counted_by_ptr(bytes);
    short nr_bars;
    struct bar *bars __counted_by_ptr(nr_bars);
    size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

...

Quoted 8 lines
Makefile +0 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS  += $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
Quoted 7 lines

Makefile KBUILD_CFLAGS += $(CC_AUTO_VAR_INIT_ZERO_ENABLER) · line 959

Quoted 5 lines
Makefile +5 -0
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS      += -fexperimental-late-parse-attributes
+endif
+endif

Will that still be needed for clang 22?

AFAIK, yes. AIUI, this flag will remain while -fbounds-safety continues to be upstreamed into LLVM.

Quoted 7 lines
Quoted 3 lines

Looks a bit like a temporary flag to avoid regressions. Probably ought to at least have a comment that it won't be needed by some future clang version so that it gets tidied up.

Once it's no longer needed, yes, I will want it removed from the Makefile.

Would it be good to 'fixup' a comment in the Makefile for that?

-bw

#18 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 40 lines · On Tue, 20 Jan 2026 10:12:34 -0800 Bill Wendling <[email protected]> wrote:
Quoted 39 lines · Kees Cook
Quoted 26 lines · David Laight
Quoted 14 lines · On Fri, 16 Jan 2026 00:57:57 +0000 Bill Wendling <[email protected]> wrote:

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
    int a, b, c;
    char *buffer __counted_by_ptr(bytes);
    short nr_bars;
    struct bar *bars __counted_by_ptr(nr_bars);
    size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

...

Quoted 8 lines
Makefile +0 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS  += $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
Quoted 7 lines

Makefile KBUILD_CFLAGS += $(CC_AUTO_VAR_INIT_ZERO_ENABLER) · line 959

Quoted 5 lines
Makefile +5 -0
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS      += -fexperimental-late-parse-attributes
+endif
+endif  

Will that still be needed for clang 22?

AFAIK, yes. AIUI, this flag will remain while -fbounds-safety continues to be upstreamed into LLVM.

Quoted 8 lines
Quoted 7 lines
Quoted 3 lines

Looks a bit like a temporary flag to avoid regressions. Probably ought to at least have a comment that it won't be needed by some future clang version so that it gets tidied up.

Once it's no longer needed, yes, I will want it removed from the Makefile.

Would it be good to 'fixup' a comment in the Makefile for that?

Wrap with:
# Update version when no longer required
ifneq ($(call clang-min-version, 999999),y)

Although you might one day need the -f option for something entirely different. So perhaps the logic that enables CC_HAS_COUNTER_BY_PTR need to do the extra version check and set something so that -fexperimental-late-parse-attributes is added here (so it only added once if needed by multiple things).

David

#19 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to David Laight
Quoted 27 lines · David Laight
Quoted 14 lines · On Fri, 16 Jan 2026 00:57:57 +0000 Bill Wendling <[email protected]> wrote:

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
      int a, b, c;
      char *buffer __counted_by_ptr(bytes);
      short nr_bars;
      struct bar *bars __counted_by_ptr(nr_bars);
      size_t bytes;
};

Because "counted_by" can only be applied to pointer members in very recent compiler versions, its application ends up needing to be distinct from flexibe array "counted_by" annotations, hence a separate macro.

...

Quoted 8 lines
Makefile +0 -0
index 9d38125263fb..6b029f694bc2 100644
@@ -952,6 +952,12 @@ KBUILD_CFLAGS    += $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
Quoted 10 lines

Makefile KBUILD_CFLAGS += $(CC_AUTO_VAR_INIT_ZERO_ENABLER) · line 959

Quoted 5 lines
Makefile +5 -0
+ifdef CONFIG_CC_IS_CLANG
+ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
+KBUILD_CFLAGS        += -fexperimental-late-parse-attributes
+endif
+endif

Will that still be needed for clang 22?
Looks a bit like a temporary flag to avoid regressions. Probably ought to at least have a comment that it won't be needed by some future clang version so that it gets tidied up.

I don't believe that there's a timeline for removing this flag, but I agree that it should go at some point.

-bw

Applied
#20 lore raw

Re: [PATCH v4 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to Bill Wendling
Quoted 11 lines · Bill Wendling

Introduce __counted_by_ptr(), which works like __counted_by(), but for pointer struct members.

struct foo {
	int a, b, c;
	char *buffer __counted_by_ptr(bytes);
	short nr_bars;
	struct bar *bars __counted_by_ptr(nr_bars);
	size_t bytes;
};
Quoted 1 line

[...]

Applied to for-next/hardening, thanks!

[1/2] Compiler Attributes: Add __counted_by_ptr macro

      https://git.kernel.org/kees/c/150a04d817d8

Take care,

Signature · 1 line
Kees Cook
#21 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

In reply to Bill Wendling

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)	__attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

Something changed in recent gcc versions. I had tested gcc-16.0.1 successfully with CONFIG_CC_HAS_COUNTED_BY_PTR=y, but after upgrading to a recent git snapshot, I get this output:

fs/coredump.c:95:15: error: 'counted_by' attribute is not allowed for a non-array field

   95 |         char *corename __counted_by_ptr(size);
      |               ^~~~~~~~

drivers/misc/lkdtm/bugs.c:518:15: error: 'counted_by' attribute is not allowed for a non-array field
518 | char *buf __counted_by_ptr(len);
| ^~~
drivers/misc/lkdtm/bugs.c:520:29: error: 'counted_by' attribute is not allowed for a non-array field
520 | struct lkdtm_extra *extra __counted_by_ptr(nr_extra);
| ^~~~~

This is every use of __counted_by_ptr() in linux-next at the moment.

Arnd

#22 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 21 lines · Arnd Bergmann

include/linux/compiler_types.h struct ftrace_likely_data { · line 363

Quoted 11 lines · Bill Wendling
include/linux/compiler_types.h +10 -0
+/*
+ * Optional: only supported since clang >= 21
+ *
+ * clang: https://github.com/llvm/llvm-project/pull/137250
+ */
+#ifdef CONFIG_CC_HAS_COUNTED_BY_FOR_POINTER
+#define __counted_by_ptr(member)     __attribute__((__counted_by__(member)))
+#else
+#define __counted_by_ptr(member)
+#endif

Something changed in recent gcc versions. I had tested gcc-16.0.1 successfully with CONFIG_CC_HAS_COUNTED_BY_PTR=y, but after upgrading to a recent git snapshot, I get this output:

fs/coredump.c:95:15: error: 'counted_by' attribute is not allowed for a non-array field

   95 |         char *corename __counted_by_ptr(size);
      |               ^~~~~~~~
Quoted 9 lines

drivers/misc/lkdtm/bugs.c:518:15: error: 'counted_by' attribute is not allowed for a non-array field
518 | char *buf __counted_by_ptr(len);
| ^~~
drivers/misc/lkdtm/bugs.c:520:29: error: 'counted_by' attribute is not allowed for a non-array field
520 | struct lkdtm_extra *extra __counted_by_ptr(nr_extra);
| ^~~~~

This is every use of __counted_by_ptr() in linux-next at the moment.

I assume it's a git snapshot of GCC. :-) What does scripts/cc-version.sh produce for it?

-bw

#23 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 6 lines · Bill Wendling
Quoted 3 lines · Arnd Bergmann

This is every use of __counted_by_ptr() in linux-next at the moment.

I assume it's a git snapshot of GCC. :-) What does scripts/cc-version.sh produce for it?

It shows 'GCC 160000'

I see my mistake now, I tried to build the lastest snapshot but accidentally checked out an older git commit on that branch, which didn't work.

I retested with current HEAD now, and that does work.

Sorry for the confusion.

Arnd

#24 lore raw

Re: [PATCH 1/2] Compiler Attributes: Add __counted_by_ptr macro

Quoted 11 lines · Arnd Bergmann
Quoted 6 lines · Bill Wendling
Quoted 3 lines · Arnd Bergmann

This is every use of __counted_by_ptr() in linux-next at the moment.

I assume it's a git snapshot of GCC. :-) What does scripts/cc-version.sh produce for it?

It shows 'GCC 160000'

Quoted 8 lines

I see my mistake now, I tried to build the lastest snapshot but accidentally checked out an older git commit on that branch, which didn't work.

I retested with current HEAD now, and that does work.

Sorry for the confusion.

*whew* I can go to sleep now. :-D

-bw

#25 lore raw

PATCH 2/2 memblock: annotate struct memblock_type with __counted_by_ptr

In reply to Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

This annotation allows the Kernel Address Sanitizer (KASAN) to detect out-of-bounds accesses to the 'regions' array.

Cc Kees Cook <[email protected]>
Cc "Gustavo A. R. Silva" <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Nick Desaulniers <[email protected]>
Cc Justin Stitt <[email protected]>
Cc Miguel Ojeda <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Marc Herbert <[email protected]>
Cc Uros Bizjak <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Jeff Xu <[email protected]>
Cc "Michal Koutný" <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc "Thomas Weißschuh" <[email protected]>
Cc John Stultz <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Brian Gerst <[email protected]>
Cc Masahiro Yamada <[email protected]>
Cc Mike Rapoport <[email protected]>
---
 include/linux/memblock.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/memblock.h +1 -1
index 221118b5a16e..ba7f7c999a45 100644
@@ -91,7 +91,7 @@ struct memblock_type {
 	unsigned long cnt;
 	unsigned long max;
 	phys_addr_t total_size;
-	struct memblock_region *regions;
+	struct memblock_region *regions __counted_by_ptr(max);
 	char *name;
 };
 
Signature · 1 line
2.52.0.rc2.455.g230fcf2819-goog
#26 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

Here's what I used in the past for flexible arrays, but it was slow due to Coccinelle needing --recursive-includes to see the structs, but should be adaptable for counted_by on pointers:

@flex_match@
identifier STRUCT, COUNTED, ARRAY;
type COUNTED_TYPE, ARRAY_TYPE;
attribute name __counted_by;
@@

        struct STRUCT {
                ...
                COUNTED_TYPE COUNTED;
                ...
                ARRAY_TYPE ARRAY[] __counted_by(COUNTED);
        };

@missed_counted_assignment@
identifier flex_match.STRUCT;
struct STRUCT *P;
identifier flex_match.COUNTED;
identifier flex_match.ARRAY;
identifier ALLOC =~ ".*alloc.*";
@@

        P = ALLOC(...);
        ... when != P->COUNTED

* P->ARRAY

Quoted 2 lines

This annotation allows the Kernel Address Sanitizer (KASAN) to detect out-of-bounds accesses to the 'regions' array.

I think you mean UBSan here (and CONFIG_FORTIFY_SOURCE)?

Quoted 9 lines
---
 include/linux/memblock.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/memblock.h +0 -0
index 221118b5a16e..ba7f7c999a45 100644

include/linux/memblock.h struct memblock_type { · line 96

Quoted 7 lines
include/linux/memblock.h +1 -1
@@ -91,7 +91,7 @@ struct memblock_type {
 	unsigned long cnt;
 	unsigned long max;
 	phys_addr_t total_size;
-	struct memblock_region *regions;
+	struct memblock_region *regions __counted_by_ptr(max);
 	char *name;
 };

For the handful of places I spot checked, yeah, it looks like a nice annotation.

-Kees

Signature · 1 line
Kees Cook
maintainer
#27 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 6 lines · On Fri, 21 Nov 2025 16:30:43 -0800 Kees Cook <[email protected]> wrote:
Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

Quoted 6 lines

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

How is anyone to know these things? I can't find anything about this in include/ or Documentation/ or in the relevant commits.

There should be a comment at the __counted_by() definition site, please.

And possibly write a Documentation/ file then change checkpatch to direct people to that file if they add a counted_by?

#28 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 15 lines · Andrew Morton
Quoted 6 lines · On Fri, 21 Nov 2025 16:30:43 -0800 Kees Cook <[email protected]> wrote:
Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

Quoted 6 lines

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

Quoted 7 lines

How is anyone to know these things? I can't find anything about this in include/ or Documentation/ or in the relevant commits.

There should be a comment at the __counted_by() definition site, please.

And possibly write a Documentation/ file then change checkpatch to direct people to that file if they add a counted_by?

This is a fair point, yes. The documentation and discussions around counted_by are very big in my mind (and for Bill), so it was mostly a consolidation/reminder and some extra detail on prior solutions, but for anyone new to that annotation, we should have collected common guidance. I will write something up.

Signature · 1 line
Kees Cook
#29 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 22 lines · Kees Cook
Quoted 20 lines · Andrew Morton
Quoted 6 lines · On Fri, 21 Nov 2025 16:30:43 -0800 Kees Cook <[email protected]> wrote:
Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

Quoted 6 lines

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

How is anyone to know these things? I can't find anything about this in include/ or Documentation/ or in the relevant commits.

There should be a comment at the __counted_by() definition site, please.

Quoted 9 lines
Quoted 2 lines

And possibly write a Documentation/ file then change checkpatch to direct people to that file if they add a counted_by?

This is a fair point, yes. The documentation and discussions around counted_by are very big in my mind (and for Bill), so it was mostly a consolidation/reminder and some extra detail on prior solutions, but for anyone new to that annotation, we should have collected common guidance. I will write something up.

Good point. I'll add documentation for these attributes both in Documentation/ and at the macro site. The frustrating thing is that we're likely to have at least one other macro flavor (something like "__counted_by_expr"), though that's the only foreseeable one. All of these macros are wrappers around the same attribute because of compiler skew.

-bw

#30 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

In reply to Andrew Morton
Quoted 15 lines · Andrew Morton
Quoted 6 lines · On Fri, 21 Nov 2025 16:30:43 -0800 Kees Cook <[email protected]> wrote:
Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

Quoted 6 lines

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

Quoted 7 lines

How is anyone to know these things? I can't find anything about this in include/ or Documentation/ or in the relevant commits.

There should be a comment at the __counted_by() definition site, please.

And possibly write a Documentation/ file then change checkpatch to direct people to that file if they add a counted_by?

There is:

https://clang.llvm.org/docs/BoundsSafety.html

#31 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 20 lines · Peter Zijlstra
Quoted 18 lines · Andrew Morton
Quoted 6 lines · On Fri, 21 Nov 2025 16:30:43 -0800 Kees Cook <[email protected]> wrote:
Quoted 4 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

Quoted 6 lines

As part of any counted_by annotation patch, there needs to be discussion in the commit log about how it's been shown to be a safe annotation to make. e.g. in this case, if all allocations of "regions" have a corresponding "max" assignment, etc. If just "git grep" can't find them all, using something like Coccinelle or CodeQL to search for struct memblock_type::regions assignments can work.

How is anyone to know these things? I can't find anything about this in include/ or Documentation/ or in the relevant commits.

Quoted 9 lines
Quoted 4 lines

There should be a comment at the __counted_by() definition site, please.

And possibly write a Documentation/ file then change checkpatch to direct people to that file if they add a counted_by?

There is:

https://clang.llvm.org/docs/BoundsSafety.html

After feedback and more consideration, I think this patch was premature. I'm going to shelve it until we can submit an improved version and the compilers can release the feature. :-)

-bw

maintainer
#32 lore raw

Re: [PATCH 2/2] memblock: annotate struct memblock_type with __counted_by_ptr

In reply to Bill Wendling
Quoted 11 lines · Bill Wendling

Add the '__counted_by_ptr' attribute to the 'regions' field of 'struct memblock_type'. The 'regions' field is an array of 'struct memblock_region' and its size is tracked by the 'max' field, which represents the total number of allocated regions.

This annotation allows the Kernel Address Sanitizer (KASAN) to detect out-of-bounds accesses to the 'regions' array.

---
 include/linux/memblock.h | 2 +-

Please also update tools/testing/memblock

Quoted 18 lines
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/memblock.h +1 -1
index 221118b5a16e..ba7f7c999a45 100644
@@ -91,7 +91,7 @@ struct memblock_type {
 	unsigned long cnt;
 	unsigned long max;
 	phys_addr_t total_size;
-	struct memblock_region *regions;
+	struct memblock_region *regions __counted_by_ptr(max);
 	char *name;
 };
 
Signature · 1 line
2.52.0.rc2.455.g230fcf2819-goog
Signature · 2 lines
Sincerely yours,
Mike.
#33 lore raw
In reply to Bill Wendling
Quoted 10 lines · Bill Wendling

These patches add the __counted_by_ptr macro and then uses it in mm/memblock.h. The name of the __counted_by_ptr attribute is the same as __counted_by, but two different macros are needed, because of feature skew in GCC and clang. Once the minmum versions of the compilers support 'counted_by' on both flexible array members and pointers in structs, this macro will become obsolete.

Bill Wendling (2):
Compiler Attributes: Add __counted_by_ptr macro
memblock: annotate struct memblock_type with __counted_by_ptr

Based on this[1] thread, I think we'll need to wait for GCC and Clang to release with the "void *" support first, and then push the counted_by up to that version to cover flexible arrays, pointers, and void *.

-Kees

[1] https://lore.kernel.org/lkml/[email protected]/

-Kees

Signature · 1 line
Kees Cook
#34 lore raw
Quoted 12 lines · Kees Cook
Quoted 10 lines · Bill Wendling

These patches add the __counted_by_ptr macro and then uses it in mm/memblock.h. The name of the __counted_by_ptr attribute is the same as __counted_by, but two different macros are needed, because of feature skew in GCC and clang. Once the minmum versions of the compilers support 'counted_by' on both flexible array members and pointers in structs, this macro will become obsolete.

Bill Wendling (2):
Compiler Attributes: Add __counted_by_ptr macro
memblock: annotate struct memblock_type with __counted_by_ptr

Quoted 6 lines

Based on this[1] thread, I think we'll need to wait for GCC and Clang to release with the "void *" support first, and then push the counted_by up to that version to cover flexible arrays, pointers, and void *.

[1] https://lore.kernel.org/lkml/[email protected]/

Would it make sense to add it with the expected compiler version releases so that (1) we'll be ready when the compilers are released, and (2) people could test the new features with compiler RCs?

-bw