From faebcf725c5a7b278cecc8eac2e4f4f46bfa050b Mon Sep 17 00:00:00 2001 From: Mahad Ibrahim Date: Wed, 22 Jul 2026 23:02:46 +0000 Subject: [PATCH 01/29] lkdtm: use kmalloc() instead of __get_free_page lkdtm_debugfs_entry and direct_entry use __get_free_page to allocate a temporary buffer, perform copy_from_user to get the crashtype name, strim() to strip whitespace and find_crashtype to find the corresponding crashtype that is being requested. The lkdtm_debugfs_read uses __get_free_page to allocate a temporary buffer to store all the available crashtypes, and then copy it to userspace. The buffers that are allocated can be allocated with kmalloc as there is nothing special that requires a struct page, or the page allocator. kmalloc() additionally provides a better API that doesn't require ugly casts which obfuscate the code and kfree does not need to know the size of the freed object. Replace use of __get_free_page() with kmalloc(). Signed-off-by: Mahad Ibrahim Acked-by: Mike Rapoport (Microsoft) Link: https://patch.msgid.link/20260722230246.2869-1-mahad.ibrahim.dev@gmail.com Signed-off-by: Kees Cook --- drivers/misc/lkdtm/core.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/drivers/misc/lkdtm/core.c b/drivers/misc/lkdtm/core.c index ededa32d6744..01bebcb33bd4 100644 --- a/drivers/misc/lkdtm/core.c +++ b/drivers/misc/lkdtm/core.c @@ -236,11 +236,11 @@ static ssize_t lkdtm_debugfs_entry(struct file *f, if (count >= PAGE_SIZE) return -EINVAL; - buf = (char *)__get_free_page(GFP_KERNEL); + buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!buf) return -ENOMEM; if (copy_from_user(buf, user_buf, count)) { - free_page((unsigned long) buf); + kfree(buf); return -EFAULT; } /* NULL-terminate and remove enter */ @@ -248,7 +248,7 @@ static ssize_t lkdtm_debugfs_entry(struct file *f, strim(buf); crashtype = find_crashtype(buf); - free_page((unsigned long)buf); + kfree(buf); if (!crashtype) return -EINVAL; @@ -271,7 +271,7 @@ static ssize_t lkdtm_debugfs_read(struct file *f, char __user *user_buf, ssize_t out; char *buf; - buf = (char *)__get_free_page(GFP_KERNEL); + buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (buf == NULL) return -ENOMEM; @@ -290,7 +290,7 @@ static ssize_t lkdtm_debugfs_read(struct file *f, char __user *user_buf, out = simple_read_from_buffer(user_buf, count, off, buf, n); - free_page((unsigned long) buf); + kfree(buf); return out; } @@ -313,11 +313,11 @@ static ssize_t direct_entry(struct file *f, const char __user *user_buf, if (count < 1) return -EINVAL; - buf = (char *)__get_free_page(GFP_KERNEL); + buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!buf) return -ENOMEM; if (copy_from_user(buf, user_buf, count)) { - free_page((unsigned long) buf); + kfree(buf); return -EFAULT; } /* NULL-terminate and remove enter */ @@ -325,7 +325,7 @@ static ssize_t direct_entry(struct file *f, const char __user *user_buf, strim(buf); crashtype = find_crashtype(buf); - free_page((unsigned long) buf); + kfree(buf); if (!crashtype) return -EINVAL; From 3555409e524a0279845f91273ba714998658c163 Mon Sep 17 00:00:00 2001 From: Arnd Bergmann Date: Thu, 18 Jun 2026 16:29:43 +0200 Subject: [PATCH 02/29] KMSAN: fix memset() when using fortify-source, again Both kmsan and fortify-source replace the memset function. When both are enabled at the same time, the kmsan version gets used, which triggers a warning about fortify-source being nonfunctional: warning: unsafe memset() usage lacked '__write_overflow' symbol in /home/arnd/arm-soc/lib/test_fortify/write_overflow-memset.c warning: unsafe memset() usage lacked '__write_overflow_field' symbol in /home/arnd/arm-soc/lib/test_fortify/write_overflow_field-memset.c Commit 78a498c3a227 already tried to address this, but this seems to only have worked for memcpy() and memmove() but not memset(), which is still lacking the macro definition when KMSAN is enabled. Remove the incorrect #ifndef check around the memset() macro. Fixes: ff901d80fff6 ("x86: kmsan: use __msan_ string functions where possible.") Fixes: 78a498c3a227 ("x86: fortify: kmsan: fix KMSAN fortify builds") Signed-off-by: Arnd Bergmann Link: https://patch.msgid.link/20260618142951.1739694-1-arnd@kernel.org Signed-off-by: Kees Cook --- include/linux/fortify-string.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/include/linux/fortify-string.h b/include/linux/fortify-string.h index cf841dc71fef..7e7c369e0a6c 100644 --- a/include/linux/fortify-string.h +++ b/include/linux/fortify-string.h @@ -458,10 +458,8 @@ __FORTIFY_INLINE bool fortify_memset_chk(__kernel_size_t size, * __struct_size() vs __member_size() must be captured here to avoid * evaluating argument side-effects further into the macro layers. */ -#ifndef CONFIG_KMSAN #define memset(p, c, s) __fortify_memset_chk(p, c, s, \ __struct_size(p), __member_size(p)) -#endif /* * To make sure the compiler can enforce protection against buffer overflows, From d72e0fb3b00c6a1146bcfd7186ad9f6f609ba236 Mon Sep 17 00:00:00 2001 From: Oleg Nesterov Date: Mon, 6 Apr 2026 15:37:32 +0200 Subject: [PATCH 03/29] signalfd: don't dequeue the forced fatal signals These signals should act like SIGKILL, in that userspace must never dequeue them. But as Kusaram explains, io_uring-driven signalfd_read_iter() called from get_signal() -> task_work_run() paths can do this before get_signal() has a chance to dequeue such a signal and notice SA_IMMUTABLE. Change signalfd_poll() and signalfd_dequeue() to add pending SA_IMMUTABLE signals to ctx->sigmask. TODO: we should probably change force_sig_info_to_task(HANDLER_EXIT) to make fatal_signal_pending() true, or add a fatal_or_forced_signal_pending() helper. Then signalfd_dequeue() could just return -EINTR in this case. This also makes sense for get_signal(), which could prioritize a fatal signal sent by (say) force_sig_seccomp(force_coredump => true), just like it already prioritizes SIGKILL. Cc: stable@kernel.org Reported-by: syzbot+0a4c46806941297fecb9@syzkaller.appspotmail.com Closes: https://syzkaller.appspot.com/bug?extid=0a4c46806941297fecb9 Tested-by: syzbot+0a4c46806941297fecb9@syzkaller.appspotmail.com Link: https://lore.kernel.org/all/69d122fd.050a0220.2dbe29.001c.GAE@google.com/ Suggested-by: Kusaram Devineni Signed-off-by: Oleg Nesterov Reviewed-by: Kees Cook Link: https://patch.msgid.link/adO3HG8bvwRPcmte@redhat.com Signed-off-by: Kees Cook --- fs/signalfd.c | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/fs/signalfd.c b/fs/signalfd.c index dff53745e352..22bc0870a824 100644 --- a/fs/signalfd.c +++ b/fs/signalfd.c @@ -48,17 +48,30 @@ static int signalfd_release(struct inode *inode, struct file *file) return 0; } +static void refine_sigmask(struct signalfd_ctx *ctx, sigset_t *sigmask) +{ + struct k_sigaction *k = current->sighand->action; + int n; + + *sigmask = ctx->sigmask; + for (n = 1; n <= _NSIG; ++n, ++k) { + if (k->sa.sa_flags & SA_IMMUTABLE) + sigaddset(sigmask, n); + } +} + static __poll_t signalfd_poll(struct file *file, poll_table *wait) { struct signalfd_ctx *ctx = file->private_data; __poll_t events = 0; + sigset_t sigmask; poll_wait(file, ¤t->sighand->signalfd_wqh, wait); spin_lock_irq(¤t->sighand->siglock); - if (next_signal(¤t->pending, &ctx->sigmask) || - next_signal(¤t->signal->shared_pending, - &ctx->sigmask)) + refine_sigmask(ctx, &sigmask); + if (next_signal(¤t->pending, &sigmask) || + next_signal(¤t->signal->shared_pending, &sigmask)) events |= EPOLLIN; spin_unlock_irq(¤t->sighand->siglock); @@ -155,11 +168,13 @@ static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, kernel_siginfo_t *info int nonblock) { enum pid_type type; - ssize_t ret; DECLARE_WAITQUEUE(wait, current); + sigset_t sigmask; + ssize_t ret; spin_lock_irq(¤t->sighand->siglock); - ret = dequeue_signal(&ctx->sigmask, info, &type); + refine_sigmask(ctx, &sigmask); + ret = dequeue_signal(&sigmask, info, &type); switch (ret) { case 0: if (!nonblock) @@ -174,7 +189,7 @@ static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, kernel_siginfo_t *info add_wait_queue(¤t->sighand->signalfd_wqh, &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); - ret = dequeue_signal(&ctx->sigmask, info, &type); + ret = dequeue_signal(&sigmask, info, &type); if (ret != 0) break; if (signal_pending(current)) { @@ -184,6 +199,7 @@ static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, kernel_siginfo_t *info spin_unlock_irq(¤t->sighand->siglock); schedule(); spin_lock_irq(¤t->sighand->siglock); + refine_sigmask(ctx, &sigmask); } spin_unlock_irq(¤t->sighand->siglock); From 67beeb5621051eda74ca2171ea576c9602bb6cce Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Thu, 3 Sep 2026 16:24:35 -0700 Subject: [PATCH 04/29] randstruct: fix container_of() false positives after __mptr removal Commit f9e7a7564834 ("container_of: remove local __mptr variable") dropped the "void *__mptr" temporary from container_of(). The randstruct GCC plugin's find_bad_casts pass recognized the casts container_of() generates by that variable's name: const_tree ssa_name_var = SSA_NAME_VAR(rhs1); /* skip bogus type casts introduced by container_of */ if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) && !strcmp(DECL_NAME_POINTER(ssa_name_var), "__mptr")) continue; With the variable gone the suppression never fires, so every container_of() whose container type is randomized now emits a note: include/linux/container_of.h:23:9: note: randstruct: casting between randomized structure pointer types (ssa): 'struct ocfs2_triggers' and 'struct jbd2_buffer_trigger_type' fs/ocfs2/journal.c:524:16: note: in expansion of macro 'container_of' The pass runs on GIMPLE, after folding, and for a member at offset 0 the whole expression collapses to a bare copy that is indistinguishable from an unsafe cast: to_ocfs2_trigger (struct jbd2_buffer_trigger_type * triggers) { _2 = triggers_1(D); /* void * cast and subtraction gone */ return _2; } Match the type relationship instead. A cast from A * to B * is a container_of() if B reaches a field of type A at offset 0 through a chain of by-value members. The chain matters: container_of()'s member argument may be a dotted path, as in ceph_inode(), which is container_of(inode, struct ceph_inode_info, netfs.inode) and needs two levels. The search is depth-bounded to 4 just in case, since real paths are generally one or two members deep. Requiring the cast happens at offset 0 is done because any other member offset the subtraction survives folding and the cast's rhs is still void *, which the pass already skips a few lines above. A cast between two randomized types with no containment relationship is still reported. Verified with: struct cred *f(struct file *f) { return (struct cred *)f; } which is still flagged with the patch applied. Clang's implementation is unaffected. It checks the cast as written, and both the old and new macros cast from void *, which is always permitted; a genuinely bad cast is rejected there as a hard error rather than a note. Build tested ARCH=x86_64 defconfig with CONFIG_RANDSTRUCT_FULL=y and GCC 14.2.0: randstruct notes 52 before, 0 after. Fixes: f9e7a7564834 ("container_of: remove local __mptr variable") Assisted-by: Claude:claude-opus-5[1m] Link: https://patch.msgid.link/20260903232438.60394-1-kees@kernel.org Signed-off-by: Kees Cook --- scripts/gcc-plugins/randomize_layout_plugin.c | 61 ++++++++++++++++++- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/scripts/gcc-plugins/randomize_layout_plugin.c b/scripts/gcc-plugins/randomize_layout_plugin.c index ff65a4f87f24..e2bd9ba08089 100644 --- a/scripts/gcc-plugins/randomize_layout_plugin.c +++ b/scripts/gcc-plugins/randomize_layout_plugin.c @@ -698,6 +698,63 @@ static void handle_local_var_initializers(void) } } +/* + * Does @container reach a field of type @member_type by a chain of + * by-value members? That is the relationship container_of() expresses -- + * its @member argument may be a dotted path, e.g. + * container_of(inode, struct ceph_inode_info, netfs.inode) -- so a cast + * from @member_type * to @container * is legitimate rather than a + * layout-confusing one. + * + * container_of() used to leave a "void *__mptr" temporary behind, and this + * pass recognised such casts by that name. Commit f9e7a7564834 + * ("container_of: remove local __mptr variable") removed it to stop nested + * container_of() shadowing itself, and the cast now folds to a bare SSA + * copy when the member sits at offset 0, leaving nothing syntactic to key + * on. Match the type relationship instead. + * + * The depth bound keeps this cheap; container_of() paths are one or two + * members deep in practice. + */ +#define CONTAINER_OF_MAX_DEPTH 4 + +static bool is_container_of_cast(const_tree container, const_tree member_type, + int depth) +{ + const_tree field; + + if (container == NULL_TREE || depth > CONTAINER_OF_MAX_DEPTH) + return false; + + if (TREE_CODE(container) != RECORD_TYPE && + TREE_CODE(container) != UNION_TYPE) + return false; + + for (field = TYPE_FIELDS(container); field; field = DECL_CHAIN(field)) { + const_tree field_type; + + if (TREE_CODE(field) != FIELD_DECL) + continue; + + /* + * Only a member at offset 0 can reach here: for any other + * offset container_of()'s subtraction survives folding, the + * cast's rhs stays void *, and the caller skipped it above. + */ + if (!integer_zerop(byte_position(field))) + continue; + + field_type = TYPE_MAIN_VARIANT(TREE_TYPE(field)); + if (field_type == member_type) + return true; + + if (is_container_of_cast(field_type, member_type, depth + 1)) + return true; + } + + return false; +} + /* * iterate over all statements to find "bad" casts: * those where the address of the start of a structure is cast @@ -799,10 +856,8 @@ static unsigned int find_bad_casts_execute(void) #endif MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type); } else { - const_tree ssa_name_var = SSA_NAME_VAR(rhs1); /* skip bogus type casts introduced by container_of */ - if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) && - !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr")) + if (is_container_of_cast(ptr_lhs_type, ptr_rhs_type, 0)) continue; #ifndef __DEBUG_PLUGIN if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type))) From b9f13e51ad1262dd77b1178c8011153894765c7b Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Thu, 3 Sep 2026 16:24:36 -0700 Subject: [PATCH 05/29] randstruct: report bad casts as warnings rather than notes find_bad_casts() reports a cast between two randomized structure pointer types with inform(), which renders as a "note:". It has done so since the plugin was originally added, while using error() freely for attribute misuse, UAPI structs, and version mismatches. Clang's implementation of the same check has always been stricter: it rejects such a cast as a full error. There is no reason for the GCC side to be effectively silent about the same problem. Build tested ARCH=x86_64 with CONFIG_RANDSTRUCT_FULL=y and GCC 14.2.0: allmodconfig clean, and defconfig clean under three different random seeds. A deliberate bad cast is still reported, now as a warning, at the correct line and column. Link: https://patch.msgid.link/20260903232438.60394-2-kees@kernel.org Signed-off-by: Kees Cook --- scripts/gcc-plugins/randomize_layout_plugin.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/gcc-plugins/randomize_layout_plugin.c b/scripts/gcc-plugins/randomize_layout_plugin.c index e2bd9ba08089..1e66f45fe29b 100644 --- a/scripts/gcc-plugins/randomize_layout_plugin.c +++ b/scripts/gcc-plugins/randomize_layout_plugin.c @@ -22,7 +22,7 @@ #define ORIG_TYPE_NAME(node) \ (TYPE_NAME(TYPE_MAIN_VARIANT(node)) != NULL_TREE ? ((const unsigned char *)IDENTIFIER_POINTER(TYPE_NAME(TYPE_MAIN_VARIANT(node)))) : (const unsigned char *)"anonymous") -#define INFORM(loc, msg, ...) inform(loc, "randstruct: " msg, ##__VA_ARGS__) +#define INFORM(loc, msg, ...) warning_at(loc, 0, "randstruct: " msg, ##__VA_ARGS__) #define MISMATCH(loc, how, ...) INFORM(loc, "casting between randomized structure pointer types (" how "): %qT and %qT\n", __VA_ARGS__) __visible int plugin_is_GPL_compatible; From 6e72cefa7a47f33fac62a69b22e02b379b7a754b Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 14 Sep 2026 15:37:49 -0700 Subject: [PATCH 06/29] coccinelle: kmalloc_obj: Convert multi-byte integral allocations Currently the kmalloc_obj conversion rules leave alone every allocation sized to an integral type, or assigned to a pointer to one, so that byte buffers keep being allocated with a byte count. That also leaves alone arrays of multi-byte integers, such as vals = kcalloc(n, sizeof(u32), GFP_KERNEL); which count objects like any other array. At the same time the signed types (s8 through s64 and their variants) were not in the list at all. But these multi-byte types are better handled through the full kmalloc_obj-style allocation, as they are, in fact, typed and aren't just a byte string, so they would benefit from type checking. Split INTEGRAL into BYTE_TYPES and MULTIBYTE_TYPES: - Allocations sized by a byte type or a string literal, or assigned to a pointer to a byte type, are still left alone. - Allocations sized by a multi-byte type are converted when they are assigned to a pointer, or a pointer to const, of that same type. Other allocations sized by a multi-byte type are left alone, as their target may be a pointer to an array. - Allocations of other types assigned to a pointer to a multi-byte type are still left alone. - Arrays of pointers to integral types sized by type, such as sizeof(char *), are still left alone, now including the signed types, as their target may be a pointer to an array of pointers, like "const char *(*fmts)[]". Sized as sizeof(*target), they are converted like any other array. List the signed types and the other spellings of the standard integer types (short int, unsigned, long long int, and so on), so that a declaration and a sizeof() that spell the same type differently still match. Assisted-by: LLM coccinelle Link: https://patch.msgid.link/20260914223748.i.971-kees@kernel.org Signed-off-by: Kees Cook --- scripts/coccinelle/api/kmalloc_objs.cocci | 161 +++++++++++++++++----- 1 file changed, 129 insertions(+), 32 deletions(-) diff --git a/scripts/coccinelle/api/kmalloc_objs.cocci b/scripts/coccinelle/api/kmalloc_objs.cocci index e9a415b7b6f4..0a98ddf03eca 100644 --- a/scripts/coccinelle/api/kmalloc_objs.cocci +++ b/scripts/coccinelle/api/kmalloc_objs.cocci @@ -24,27 +24,57 @@ def alloc_array(name): print(f"Unknown transform for {name}", file=sys.stderr) return func -// This excludes anything that is assigning to or from integral types or -// string literals. Everything else gets the sizeof() extracted for the -// kmalloc_obj() type/var argument. sizeof(void *) is also excluded because -// it will need case-by-case double-checking to make sure the right type is +// Allocations sized by a byte-sized type (BYTE_TYPES) or a string literal, +// and allocations assigned to a pointer to a byte-sized type, are byte +// buffers and are left alone. sizeof(void *) is also excluded because it +// will need case-by-case double-checking to make sure the right type is // being assigned. +// +// Allocations sized by a multi-byte integral type (MULTIBYTE_TYPES) are +// converted when they are assigned to a pointer to that same type. +// Otherwise they are left alone: the target may be a pointer to an array +// of that type, such as "s16 (*pairs)[2]", for which the converted +// allocation would have the wrong pointer type. For the same reason, +// arrays of pointers to integral types sized as sizeof(char *) and the +// like are left alone. Allocations of other types assigned to a pointer to +// a multi-byte integral type are left alone too. +// +// Everything else gets the sizeof() extracted for the kmalloc_obj() +// type/var argument. +// +// The first matching alternative below wins, so the exclusions must come +// before the more general conversions. @direct depends on patch && !(file in "tools") && !(file in "samples")@ typedef u8, u16, u32, u64; typedef __u8, __u16, __u32, __u64; typedef uint8_t, uint16_t, uint32_t, uint64_t; +typedef s8, s16, s32, s64; +typedef __s8, __s16, __s32, __s64; +typedef int8_t, int16_t, int32_t, int64_t; typedef uchar, ushort, uint, ulong; typedef __le16, __le32, __le64; typedef __be16, __be32, __be64; typedef wchar_t; -type INTEGRAL = {u8,__u8,uint8_t,char,unsigned char,uchar,wchar_t, - u16,__u16,uint16_t,unsigned short,ushort, - u32,__u32,uint32_t,unsigned int,uint, - u64,__u64,uint64_t,unsigned long,ulong, - __le16,__le32,__le64,__be16,__be32,__be64}; +type BYTE_TYPES = {char,signed char,unsigned char,uchar, + u8,__u8,uint8_t,s8,__s8,int8_t}; +type MULTIBYTE_TYPES = {short,short int,signed short,signed short int, + unsigned short,unsigned short int,ushort, + int,signed,signed int,unsigned,unsigned int,uint, + long,long int,signed long,signed long int, + unsigned long,unsigned long int,ulong, + long long,long long int, + signed long long,signed long long int, + unsigned long long,unsigned long long int, + u16,__u16,uint16_t,s16,__s16,int16_t, + u32,__u32,uint32_t,s32,__s32,int32_t, + u64,__u64,uint64_t,s64,__s64,int64_t, + __le16,__le32,__le64,__be16,__be32,__be64, + wchar_t}; char [] STRING; -INTEGRAL *BYTES; -INTEGRAL **BYTES_PTRS; +BYTE_TYPES *BYTES; +MULTIBYTE_TYPES *MULTIBYTES; +const MULTIBYTE_TYPES *CONST_MULTIBYTES; +MULTIBYTE_TYPES MULTIBYTE; type TYPE; expression VAR; expression GFP; @@ -59,66 +89,133 @@ fresh identifier ALLOC_OBJS = script:python(ALLOC_ARRAY) { alloc_array(ALLOC_ARR @@ ( +// Convert a single object sized by its target: p = kmalloc(sizeof(*p), gfp) - VAR = ALLOC((sizeof(*VAR)), GFP) + VAR = ALLOC_OBJ(*VAR, GFP) | - ALLOC((\(sizeof(STRING)\|sizeof(INTEGRAL)\|sizeof(INTEGRAL *)\)), GFP) +// Exclude byte buffers and integral pointers: kmalloc(sizeof(u8), gfp), +// kmalloc(sizeof("str"), gfp), kmalloc(sizeof(char *), gfp) + ALLOC((\(sizeof(STRING)\|sizeof(BYTE_TYPES)\| + sizeof(BYTE_TYPES *)\|sizeof(MULTIBYTE_TYPES *)\)), GFP) | - BYTES = ALLOC((sizeof(E)), GFP) +// Exclude anything assigned to a byte pointer: +// u8 *buf = kmalloc(sizeof(*hdr), gfp) + BYTES = ALLOC((\(sizeof(E)\|sizeof(TYPE)\)), GFP) | - BYTES = ALLOC((sizeof(TYPE)), GFP) +// Convert a multi-byte type to a pointer to it: +// u32 *p = kmalloc(sizeof(u32), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC((sizeof(MULTIBYTE_TYPES)), GFP) ++ ALLOC_OBJ(MULTIBYTE_TYPES, GFP) | - BYTES_PTRS = ALLOC((sizeof(E)), GFP) +// Same by expression: u32 *p = kmalloc(sizeof(p[0]), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC((sizeof(MULTIBYTE)), GFP) ++ ALLOC_OBJ(MULTIBYTE, GFP) | - BYTES_PTRS = ALLOC((sizeof(TYPE)), GFP) +// Exclude other multi-byte sizes, e.g. to pointers to arrays: s16 (*p)[2] = ... + ALLOC((\(sizeof(MULTIBYTE_TYPES)\|sizeof(MULTIBYTE)\)), GFP) | +// Exclude anything else assigned to a multi-byte pointer: +// u32 *p = kmalloc(sizeof(*hdr), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = ALLOC((\(sizeof(E)\|sizeof(TYPE)\)), GFP) +| +// Exclude void pointers, to be checked by hand: kmalloc(sizeof(void *), gfp) ALLOC((sizeof(void *)), GFP) | +// Convert any other expression: p = kmalloc(sizeof(s->item), gfp) - ALLOC((sizeof(E)), GFP) + ALLOC_OBJ(E, GFP) | +// Convert any other type: p = kmalloc(sizeof(struct item), gfp) - ALLOC((sizeof(TYPE)), GFP) + ALLOC_OBJ(TYPE, GFP) | - ALLOC_ARRAY(COUNT, (\(sizeof(STRING)\|sizeof(INTEGRAL)\|sizeof(INTEGRAL *)\)), GFP) +// The same, for arrays allocated as (count, size): +// Exclude byte buffers and integral pointers: kcalloc(n, sizeof(u8), gfp), +// kcalloc(n, sizeof(char *), gfp) + ALLOC_ARRAY(COUNT, (\(sizeof(STRING)\|sizeof(BYTE_TYPES)\| + sizeof(BYTE_TYPES *)\|sizeof(MULTIBYTE_TYPES *)\)), GFP) | - BYTES = ALLOC_ARRAY(COUNT, (sizeof(E)), GFP) +// Exclude arrays assigned to a byte pointer: +// u8 *buf = kcalloc(n, sizeof(*hdr), gfp) + BYTES = ALLOC_ARRAY(COUNT, (\(sizeof(E)\|sizeof(TYPE)\)), GFP) | - BYTES = ALLOC_ARRAY(COUNT, (sizeof(TYPE)), GFP) +// Convert a multi-byte array to a pointer to it: +// u32 *p = kcalloc(n, sizeof(u32), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC_ARRAY(COUNT, (sizeof(MULTIBYTE_TYPES)), GFP) ++ ALLOC_OBJS(MULTIBYTE_TYPES, COUNT, GFP) | - BYTES_PTRS = ALLOC_ARRAY(COUNT, (sizeof(E)), GFP) +// Same by expression: u32 *p = kcalloc(n, sizeof(*p), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC_ARRAY(COUNT, (sizeof(MULTIBYTE)), GFP) ++ ALLOC_OBJS(MULTIBYTE, COUNT, GFP) | - BYTES_PTRS = ALLOC_ARRAY(COUNT, (sizeof(TYPE)), GFP) +// Exclude other multi-byte arrays: +// s16 (*pairs)[2] = kcalloc(n, sizeof(s16), gfp) + ALLOC_ARRAY(COUNT, (\(sizeof(MULTIBYTE_TYPES)\|sizeof(MULTIBYTE)\)), GFP) | - ALLOC_ARRAY((\(sizeof(STRING)\|sizeof(INTEGRAL)\|sizeof(INTEGRAL *)\)), COUNT, GFP) -| - BYTES = ALLOC_ARRAY((sizeof(E)), COUNT, GFP) -| - BYTES = ALLOC_ARRAY((sizeof(TYPE)), COUNT, GFP) -| - BYTES_PTRS = ALLOC_ARRAY((sizeof(E)), COUNT, GFP) -| - BYTES_PTRS = ALLOC_ARRAY((sizeof(TYPE)), COUNT, GFP) +// Exclude other arrays assigned to a multi-byte pointer: +// u32 *p = kcalloc(n, sizeof(*hdr), gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = ALLOC_ARRAY(COUNT, (\(sizeof(E)\|sizeof(TYPE)\)), GFP) | +// Exclude arrays of void pointers: kcalloc(n, sizeof(void *), gfp) ALLOC_ARRAY(COUNT, (sizeof(void *)), GFP) | - ALLOC_ARRAY((sizeof(void *)), COUNT, GFP) -| +// Convert any other expression: p = kcalloc(n, sizeof(*p), gfp) - ALLOC_ARRAY(COUNT, (sizeof(E)), GFP) + ALLOC_OBJS(E, COUNT, GFP) | +// Convert any other type: p = kcalloc(n, sizeof(struct item), gfp) - ALLOC_ARRAY(COUNT, (sizeof(TYPE)), GFP) + ALLOC_OBJS(TYPE, COUNT, GFP) | +// The same, for arrays allocated as (size, count): +// Exclude byte buffers and integral pointers: kcalloc(sizeof(u8), n, gfp), +// kcalloc(sizeof(char *), n, gfp) + ALLOC_ARRAY((\(sizeof(STRING)\|sizeof(BYTE_TYPES)\| + sizeof(BYTE_TYPES *)\|sizeof(MULTIBYTE_TYPES *)\)), COUNT, GFP) +| +// Exclude arrays assigned to a byte pointer: +// u8 *buf = kcalloc(sizeof(*hdr), n, gfp) + BYTES = ALLOC_ARRAY((\(sizeof(E)\|sizeof(TYPE)\)), COUNT, GFP) +| +// Convert a multi-byte array to a pointer to it: +// u32 *p = kcalloc(sizeof(u32), n, gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC_ARRAY((sizeof(MULTIBYTE_TYPES)), COUNT, GFP) ++ ALLOC_OBJS(MULTIBYTE_TYPES, COUNT, GFP) +| +// Same by expression: u32 *p = kcalloc(sizeof(*p), n, gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = +- ALLOC_ARRAY((sizeof(MULTIBYTE)), COUNT, GFP) ++ ALLOC_OBJS(MULTIBYTE, COUNT, GFP) +| +// Exclude other multi-byte arrays: +// s16 (*pairs)[2] = kcalloc(sizeof(s16), n, gfp) + ALLOC_ARRAY((\(sizeof(MULTIBYTE_TYPES)\|sizeof(MULTIBYTE)\)), COUNT, GFP) +| +// Exclude other arrays assigned to a multi-byte pointer: +// u32 *p = kcalloc(sizeof(*hdr), n, gfp) + \(MULTIBYTES\|CONST_MULTIBYTES\) = ALLOC_ARRAY((\(sizeof(E)\|sizeof(TYPE)\)), COUNT, GFP) +| +// Exclude arrays of void pointers: kcalloc(sizeof(void *), n, gfp) + ALLOC_ARRAY((sizeof(void *)), COUNT, GFP) +| +// Convert any other expression: p = kcalloc(sizeof(*p), n, gfp) - ALLOC_ARRAY((sizeof(E)), COUNT, GFP) + ALLOC_OBJS(E, COUNT, GFP) | +// Convert any other type: p = kcalloc(sizeof(struct item), n, gfp) - ALLOC_ARRAY((sizeof(TYPE)), COUNT, GFP) + ALLOC_OBJS(TYPE, COUNT, GFP) | +// Convert flexible array structures: p = kmalloc(struct_size(p, data, n), gfp) - ALLOC(struct_size(VAR, FLEX, COUNT), GFP) + ALLOC_FLEX(*VAR, FLEX, COUNT, GFP) | +// Same by type: kmalloc(struct_size_t(struct item, data, n), gfp) - ALLOC(struct_size_t(TYPE, FLEX, COUNT), GFP) + ALLOC_FLEX(TYPE, FLEX, COUNT, GFP) ) From 760f96b7f54beb8dc6f85d97ac7854fddba86835 Mon Sep 17 00:00:00 2001 From: Johannes Berg Date: Mon, 27 Jul 2026 13:55:15 -0600 Subject: [PATCH 07/29] um: fix CONFIG_GCOV for built-in code With contemporary toolchains, CONFIG_GCOV doesn't work because gcov now relies on both init and exit handlers, but those are discarded from the binary. Fix the linker scripts to keep them instead, so that CONFIG_GCOV can work again. Note that this does not make it work in modules yet, since we don't call their exit handlers. Note: the .init_array.* wildcard and the RUNTIME_DISCARD_EXIT define are already present in this tree; only the matching .fini_array.* wildcard remained to be added. Signed-off-by: Johannes Berg Signed-off-by: Alex Hung Tested-by: Mariia Nikitash Link: https://patch.msgid.link/20260727195515.2306731-1-alex.hung@amd.com Signed-off-by: Kees Cook --- arch/um/include/asm/common.lds.S | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/um/include/asm/common.lds.S b/arch/um/include/asm/common.lds.S index fd481ac371de..2ed213913afe 100644 --- a/arch/um/include/asm/common.lds.S +++ b/arch/um/include/asm/common.lds.S @@ -91,6 +91,7 @@ .fini_array : { __fini_array_start = .; *(.fini_array) + *(.fini_array.*) __fini_array_end = .; } From 633c60a2e87345bd70ced5a28561991fa5b0b1f3 Mon Sep 17 00:00:00 2001 From: Justin Stitt Date: Fri, 2 Oct 2026 12:27:17 -0700 Subject: [PATCH 08/29] MAINTAINERS: Add stackinit KUnit test to HARDENING Noticed while preparing a patch to lib/tests/stackinit_kunit.c: the file is not listed in MAINTAINERS, so get_maintainer.pl does not suggest Kees or linux-hardening for changes to it, only the catch-all list. before: $ ./scripts/get_maintainer.pl -f lib/tests/stackinit_kunit.c linux-kernel@vger.kernel.org (open list) after: $ ./scripts/get_maintainer.pl -f lib/tests/stackinit_kunit.c Kees Cook (maintainer:KERNEL HARDENING "Gustavo A. R. Silva" (reviewer:KERNEL HARDENING linux-hardening@vger.kernel.org (open list:KERNEL HARDENING linux-kernel@vger.kernel.org (open list) Signed-off-by: Justin Stitt Reviewed-by: Nick Desaulniers Link: https://patch.msgid.link/20261002-maintainers-stackinit-v1-1-27112a221527@google.com Signed-off-by: Kees Cook --- MAINTAINERS | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS b/MAINTAINERS index 6215fcb07770..2baa51d44a4c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14161,6 +14161,7 @@ F: include/linux/ucopysize.h F: kernel/configs/hardening.config F: kernel/kstack_erase.c F: lib/tests/randstruct_kunit.c +F: lib/tests/stackinit_kunit.c F: lib/tests/usercopy_kunit.c F: mm/usercopy.c F: scripts/Makefile.kstack_erase From 6bf37b9c59dc8e7a765a5c7c4ff01ccf8106b122 Mon Sep 17 00:00:00 2001 From: Justin Stitt Date: Fri, 2 Oct 2026 12:12:53 -0700 Subject: [PATCH 09/29] kunit/stackinit: Cover declarations bypassed by goto and switch Under -ftrivial-auto-var-init= the initialization is emitted where a variable is declared. A switch dispatch that reaches a case label below the declaration, or a goto that jumps past it, never reaches that point, so the variable was left uninitialized. Commit 9cf016e6b49b ("lib: test_stackinit.c: XFAIL switch variable init tests") marked test_switch_1_none and test_switch_2_none as expected failures, noting the test should be retained "so that we can evaluate compiler fixes". Clang 24 emits the initialization on the jumps that bypass the declaration, so make the expectation depend on the compiler version instead of failing unconditionally. Add test_goto_none as well. The existing cases only cover a declaration sitting between a switch and its first case label, while the compiler change covers plain goto too. GCC continues to initialize only at the declaration, and reports as much with -Wtrivial-auto-var-init, so it keeps the expected-failure path. Link: https://github.com/llvm/llvm-project/pull/181937 Link: https://github.com/KSPP/linux/issues/125 Link: https://llvm.org/pr44916 Assisted-by: LLM Signed-off-by: Justin Stitt Link: https://patch.msgid.link/20261002-kspp-125-v1-1-91286a454fda@google.com Signed-off-by: Kees Cook --- lib/tests/stackinit_kunit.c | 55 +++++++++++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/lib/tests/stackinit_kunit.c b/lib/tests/stackinit_kunit.c index ff2784769772..4788f6c10c04 100644 --- a/lib/tests/stackinit_kunit.c +++ b/lib/tests/stackinit_kunit.c @@ -382,6 +382,17 @@ union test_small_end { # define STRONG_PASS WANT_SUCCESS #endif +/* + * Clang 24 and later emit initialization on the jumps that bypass the + * declaration. GCC still initializes only at the declaration. Track + * test expectation based on CONFIG_INIT_STACK_NONE above. + */ +#if defined(CONFIG_CC_IS_CLANG) && CONFIG_CLANG_VERSION >= 240000 +# define BYPASS_PASS STRONG_PASS +#else +# define BYPASS_PASS XFAIL +#endif + #define DEFINE_SCALAR_TEST(name, init, xfail) \ DEFINE_TEST(name ## _ ## init, name, SCALAR, \ init, xfail) @@ -493,6 +504,36 @@ static int noinline __leaf_switch_none(int path, bool fill) return 0; } +static noinline int __leaf_goto_none(bool fill) +{ + goto bypass; + /* + * This declaration is jumped over by the goto above, so it is + * never reached. Compilers that initialize only at the point of + * declaration leave this variable untouched. + */ + uint64_t var[10]; + +bypass: + target_start = &var; + target_size = sizeof(var); + if (fill) { + fill_start = &var; + fill_size = sizeof(var); + + memset(fill_start, (forced_mask | 0x55) & FILL_BYTE, fill_size); + } + memcpy(check_buf, target_start, target_size); + + return 0; +} + +static noinline int leaf_goto_none(unsigned long sp, bool fill, + uint64_t *arg) +{ + return __leaf_goto_none(fill); +} + static noinline int leaf_switch_1_none(unsigned long sp, bool fill, uint64_t *arg) { @@ -506,13 +547,14 @@ static noinline int leaf_switch_2_none(unsigned long sp, bool fill, } /* - * These are expected to fail for most configurations because neither - * GCC nor Clang have a way to perform initialization of variables in - * non-code areas (i.e. in a switch statement before the first "case"). - * https://llvm.org/pr44916 + * A declaration whose definition point is jumped over, either by a switch + * dispatch reaching a "case" label below it or by a goto, used to be left + * uninitialized: the initialization is emitted where the variable is + * declared, and that point is never reached. */ -DEFINE_TEST_DRIVER(switch_1_none, uint64_t, SCALAR, ALWAYS_FAIL); -DEFINE_TEST_DRIVER(switch_2_none, uint64_t, SCALAR, ALWAYS_FAIL); +DEFINE_TEST_DRIVER(switch_1_none, uint64_t, SCALAR, BYPASS_PASS); +DEFINE_TEST_DRIVER(switch_2_none, uint64_t, SCALAR, BYPASS_PASS); +DEFINE_TEST_DRIVER(goto_none, uint64_t, SCALAR, BYPASS_PASS); #define KUNIT_test_scalars(init) \ KUNIT_CASE(test_u8_ ## init), \ @@ -568,6 +610,7 @@ static struct kunit_case stackinit_test_cases[] = { KUNIT_test_scalars(none), KUNIT_CASE(test_switch_1_none), KUNIT_CASE(test_switch_2_none), + KUNIT_CASE(test_goto_none), /* STRUCTLEAK_BYREF should cover from here down. */ KUNIT_test_structs(none), /* STRUCTLEAK will only cover this. */ From 0f82b48209e85a1f049df20455703a2767f65cfd Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 02:15:36 -0700 Subject: [PATCH 10/29] kunit/stackinit: Clean up XFAIL under instrumentation Commit 8530ea3c9b97 ("Kbuild: remove structleak gcc plugin") dropped the stackinit GCC plugins, so there is no longer a gradient of test coverage. Collapse the now identical USER_PASS, BYREF_PASS, STRONG_PASS into a single INSTRUMENTED_PASS definition. Signed-off-by: Kees Cook --- lib/tests/stackinit_kunit.c | 40 +++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/lib/tests/stackinit_kunit.c b/lib/tests/stackinit_kunit.c index 4788f6c10c04..d589536afa20 100644 --- a/lib/tests/stackinit_kunit.c +++ b/lib/tests/stackinit_kunit.c @@ -369,17 +369,13 @@ union test_small_end { char four; }; -#define ALWAYS_PASS WANT_SUCCESS -#define ALWAYS_FAIL XFAIL +#define ALWAYS_PASS WANT_SUCCESS +#define ALWAYS_FAIL XFAIL #ifdef CONFIG_INIT_STACK_NONE -# define USER_PASS XFAIL -# define BYREF_PASS XFAIL -# define STRONG_PASS XFAIL +# define INSTRUMENTED_PASS XFAIL #else -# define USER_PASS WANT_SUCCESS -# define BYREF_PASS WANT_SUCCESS -# define STRONG_PASS WANT_SUCCESS +# define INSTRUMENTED_PASS WANT_SUCCESS #endif /* @@ -388,7 +384,7 @@ union test_small_end { * test expectation based on CONFIG_INIT_STACK_NONE above. */ #if defined(CONFIG_CC_IS_CLANG) && CONFIG_CLANG_VERSION >= 240000 -# define BYPASS_PASS STRONG_PASS +# define BYPASS_PASS INSTRUMENTED_PASS #else # define BYPASS_PASS XFAIL #endif @@ -443,23 +439,23 @@ DEFINE_STRUCT_TESTS(old_zero, ALWAYS_PASS); DEFINE_UNION_TESTS(zero, ALWAYS_PASS); DEFINE_UNION_TESTS(old_zero, ALWAYS_PASS); /* Struct initializers: padding may be left uninitialized. */ -DEFINE_STRUCT_INITIALIZER_TESTS(static, STRONG_PASS); -DEFINE_STRUCT_INITIALIZER_TESTS(dynamic, STRONG_PASS); -DEFINE_STRUCT_INITIALIZER_TESTS(runtime, STRONG_PASS); -DEFINE_STRUCT_INITIALIZER_TESTS(assigned_static, STRONG_PASS); -DEFINE_STRUCT_INITIALIZER_TESTS(assigned_dynamic, STRONG_PASS); +DEFINE_STRUCT_INITIALIZER_TESTS(static, INSTRUMENTED_PASS); +DEFINE_STRUCT_INITIALIZER_TESTS(dynamic, INSTRUMENTED_PASS); +DEFINE_STRUCT_INITIALIZER_TESTS(runtime, INSTRUMENTED_PASS); +DEFINE_STRUCT_INITIALIZER_TESTS(assigned_static, INSTRUMENTED_PASS); +DEFINE_STRUCT_INITIALIZER_TESTS(assigned_dynamic, INSTRUMENTED_PASS); DEFINE_STRUCT_TESTS(assigned_copy, ALWAYS_FAIL); -DEFINE_UNION_INITIALIZER_TESTS(static, STRONG_PASS); -DEFINE_UNION_INITIALIZER_TESTS(dynamic, STRONG_PASS); -DEFINE_UNION_INITIALIZER_TESTS(runtime, STRONG_PASS); -DEFINE_UNION_INITIALIZER_TESTS(assigned_static, STRONG_PASS); -DEFINE_UNION_INITIALIZER_TESTS(assigned_dynamic, STRONG_PASS); +DEFINE_UNION_INITIALIZER_TESTS(static, INSTRUMENTED_PASS); +DEFINE_UNION_INITIALIZER_TESTS(dynamic, INSTRUMENTED_PASS); +DEFINE_UNION_INITIALIZER_TESTS(runtime, INSTRUMENTED_PASS); +DEFINE_UNION_INITIALIZER_TESTS(assigned_static, INSTRUMENTED_PASS); +DEFINE_UNION_INITIALIZER_TESTS(assigned_dynamic, INSTRUMENTED_PASS); DEFINE_UNION_TESTS(assigned_copy, ALWAYS_FAIL); /* No initialization without compiler instrumentation. */ -DEFINE_SCALAR_TESTS(none, STRONG_PASS); -DEFINE_STRUCT_TESTS(none, BYREF_PASS); +DEFINE_SCALAR_TESTS(none, INSTRUMENTED_PASS); +DEFINE_STRUCT_TESTS(none, INSTRUMENTED_PASS); /* Initialization of members with __user attribute. */ -DEFINE_TEST(user, struct test_user, STRUCT, none, USER_PASS); +DEFINE_TEST(user, struct test_user, STRUCT, none, INSTRUMENTED_PASS); /* * Check two uses through a variable declaration outside either path, From ff566742e9cf59b0518ecf29f0572f0d9b114d3a Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 14 Sep 2026 15:32:16 -0700 Subject: [PATCH 11/29] mm: Move default_gfp() into gfp_types.h Using default_gfp() only depends on the GFP_KERNEL value. Move default_gfp() into gfp_types.h so that future use in devres.h doesn't require pulling in all of gfp.h. Reviewed-by: Vlastimil Babka (SUSE) Reviewed-by: Zi Yan Link: https://patch.msgid.link/20260914223219.901347-1-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/gfp.h | 4 ---- include/linux/gfp_types.h | 4 ++++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/linux/gfp.h b/include/linux/gfp.h index 872bc53f32ec..b62e2fd53cb4 100644 --- a/include/linux/gfp.h +++ b/include/linux/gfp.h @@ -13,10 +13,6 @@ struct vm_area_struct; struct mempolicy; -/* Helper macro to avoid gfp flags if they are the default one */ -#define __default_gfp(a,b,...) b -#define default_gfp(...) __default_gfp(,##__VA_ARGS__,GFP_KERNEL) - static inline bool gfpflags_allow_blocking(const gfp_t gfp_flags) { return !!(gfp_flags & __GFP_DIRECT_RECLAIM); diff --git a/include/linux/gfp_types.h b/include/linux/gfp_types.h index 190191411009..b1cd143f3c42 100644 --- a/include/linux/gfp_types.h +++ b/include/linux/gfp_types.h @@ -382,4 +382,8 @@ enum { __GFP_NOMEMALLOC | __GFP_NOWARN) & ~__GFP_RECLAIM) #define GFP_TRANSHUGE (GFP_TRANSHUGE_LIGHT | __GFP_DIRECT_RECLAIM) +/* Helper macro to avoid gfp flags if they are the default one */ +#define __default_gfp(a,b,...) b +#define default_gfp(...) __default_gfp(,##__VA_ARGS__,GFP_KERNEL) + #endif /* __LINUX_GFP_TYPES_H */ From 29a86e8818a8b7043643b85b0603eb9f4c225b55 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 14 Sep 2026 15:32:17 -0700 Subject: [PATCH 12/29] devres: Provide kmalloc_obj*-style API for devm_kmalloc Mirroring the type-based allocation now in use for the kmalloc family of APIs, provide the same for the devm_kmalloc family of APIs. This will allow for future plumbing of type information (e.g. alignment) into the underlying allocations. This immediately gains type check on return values (instead of the prior "void *" return type). Reviewed-by: Greg Kroah-Hartman Link: https://patch.msgid.link/20260914223219.901347-2-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/device/devres.h | 102 ++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/include/linux/device/devres.h b/include/linux/device/devres.h index 14ab9159bdda..7656c9ecd4da 100644 --- a/include/linux/device/devres.h +++ b/include/linux/device/devres.h @@ -62,6 +62,108 @@ static inline void *devm_kcalloc(struct device *dev, size_t n, size_t size, gfp_ { return devm_kmalloc_array(dev, n, size, flags | __GFP_ZERO); } + +/** + * __devm_alloc_objs - Device-managed allocation of objects of a given type + * @DEVM_ALLOC: which device-managed size-based allocator to use. + * @DEV: device to scope the allocation lifetime to. + * @GFP: GFP flags for the allocation. + * @TYPE: type to allocate space for. + * @COUNT: how many @TYPE objects to allocate. + * + * Device-managed counterpart of __alloc_objs(). + * @DEVM_ALLOC takes (@DEV, size, gfp). + * + * Returns: Newly allocated pointer to (first) @TYPE of @COUNT-many allocated + * @TYPE objects, or NULL on failure. + */ +#define __devm_alloc_objs(DEVM_ALLOC, DEV, GFP, TYPE, COUNT) \ +({ \ + const size_t __obj_size = size_mul(sizeof(TYPE), COUNT); \ + (TYPE *)DEVM_ALLOC(DEV, __obj_size, GFP); \ +}) + +/** + * devm_kmalloc_obj - Device-managed allocation of a single typed object + * @DEV: Device to scope the allocation lifetime to. + * @VAR_OR_TYPE: Variable or type to allocate. + * @GFP: Optional GFP flags (defaults to %GFP_KERNEL). + * + * Device-managed counterpart of kmalloc_obj(): the allocation is sized from + * @VAR_OR_TYPE and returned as a pointer to that type, not void *. + * + * Returns: newly allocated pointer to a @VAR_OR_TYPE on success, or NULL on + * failure. + */ +#define devm_kmalloc_obj(DEV, VAR_OR_TYPE, ...) \ + __devm_alloc_objs(devm_kmalloc, DEV, default_gfp(__VA_ARGS__), \ + typeof(VAR_OR_TYPE), 1) + +/** + * devm_kmalloc_objs - Device-managed allocation of an array of a typed object + * @DEV: Device to scope the allocation lifetime to. + * @VAR_OR_TYPE: Variable or type to allocate an array of. + * @COUNT: How many elements in the array. + * @GFP: Optional GFP flags (defaults to %GFP_KERNEL). + * + * Returns: newly allocated pointer to an array of @VAR_OR_TYPE on success, or + * NULL on failure (including when the total size overflows). + */ +#define devm_kmalloc_objs(DEV, VAR_OR_TYPE, COUNT, ...) \ + __devm_alloc_objs(devm_kmalloc, DEV, default_gfp(__VA_ARGS__), \ + typeof(VAR_OR_TYPE), COUNT) + +/** + * __devm_alloc_flex - Device-managed allocation of a trailing-flex-array object + * @DEVM_ALLOC: which device-managed allocator to use. + * @DEV: device to scope the allocation lifetime to. + * @GFP: GFP flags for the allocation. + * @TYPE: type of structure to allocate space for. + * @FAM: name of the flexible array member of @TYPE. + * @COUNT: how many @FAM elements to allocate space for. + * + * Device-managed counterpart of __alloc_flex(). + * @DEVM_ALLOC takes (@DEV, size, gfp). + * + * Returns: Newly allocated pointer to @TYPE with @COUNT-many trailing @FAM + * elements, or NULL on failure. + */ +#define __devm_alloc_flex(DEVM_ALLOC, DEV, GFP, TYPE, FAM, COUNT) \ +({ \ + const size_t __count = (COUNT); \ + const size_t __obj_size = struct_size_t(TYPE, FAM, __count); \ + TYPE *__obj_ptr = DEVM_ALLOC(DEV, __obj_size, GFP); \ + if (__obj_ptr) \ + __set_flex_counter(__obj_ptr->FAM, __count); \ + __obj_ptr; \ +}) + +/** + * devm_kmalloc_flex - Device-managed allocation of a flexible-array structure + * @DEV: Device to scope the allocation lifetime to. + * @VAR_OR_TYPE: Variable or type to allocate (with its flexible array). + * @FAM: The name of the flexible array member of the structure. + * @COUNT: How many flexible array member elements to allocate. + * @GFP: Optional GFP flags (defaults to %GFP_KERNEL). + * + * Returns: newly allocated pointer to @VAR_OR_TYPE on success, or NULL on + * failure. If @FAM has been annotated with __counted_by(), its counter is set + * to @COUNT. + */ +#define devm_kmalloc_flex(DEV, VAR_OR_TYPE, FAM, COUNT, ...) \ + __devm_alloc_flex(devm_kmalloc, DEV, default_gfp(__VA_ARGS__), \ + typeof(VAR_OR_TYPE), FAM, COUNT) + +/* All devm_kzalloc aliases for devm_kmalloc_(obj|objs|flex). */ +#define devm_kzalloc_obj(DEV, P, ...) \ + __devm_alloc_objs(devm_kzalloc, DEV, default_gfp(__VA_ARGS__), typeof(P), 1) +#define devm_kzalloc_objs(DEV, P, COUNT, ...) \ + __devm_alloc_objs(devm_kzalloc, DEV, default_gfp(__VA_ARGS__), \ + typeof(P), COUNT) +#define devm_kzalloc_flex(DEV, P, FAM, COUNT, ...) \ + __devm_alloc_flex(devm_kzalloc, DEV, default_gfp(__VA_ARGS__), \ + typeof(P), FAM, COUNT) + static inline __realloc_size(3, 4) void * __must_check devm_krealloc_array(struct device *dev, void *p, size_t new_n, size_t new_size, gfp_t flags) { From e160c4481f60a032e0af813ea7925dbb78ad8a08 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Thu, 8 Oct 2026 23:40:04 -0700 Subject: [PATCH 13/29] .get_maintainer.ignore: Add Kees Cook After the kmalloc conversion my inbox is mostly unusable. Attempt to stem the tide and drop myself from get_maintainer git history CC list generation. Signed-off-by: Kees Cook --- .get_maintainer.ignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.get_maintainer.ignore b/.get_maintainer.ignore index 5ad082b4dd03..5c8b295d647f 100644 --- a/.get_maintainer.ignore +++ b/.get_maintainer.ignore @@ -4,6 +4,7 @@ Alyssa Rosenzweig Askar Safin Christoph Hellwig Jeff Kirsher +Kees Cook Marc Gonzalez Nathan Chancellor Ralf Baechle From a09fb764832dd7dbb9ccc38a9830f7294889c8ae Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:51 -0700 Subject: [PATCH 14/29] seq_buf: Do not print an empty line from an overflowed seq_buf_do_printk() seq_buf_do_printk() prints a buffer line by line, then prints whatever follows the last newline. When a string has overflowed at exactly a newline, an empty line is printed since the pointer hasn't reached the overflow mark of the seq_buf. Switch to just check if the string is already empty and only print if not. The only caller is the memory cgroup OOM report, so this could only ever add a blank line to a report whose statistics already did not fit. Add a test that registers a console to count the records that seq_buf_do_printk() emits. It counts the records carrying the test's marker, and the records holding nothing but a line feed that arrive after one, so that unrelated kernel messages do not disturb it. Both states that reach the flaw are covered: exactly full, and overflowed. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0. Fixes: 96928d9032a7c ("seq_buf: Add seq_buf_do_printk() helper") Assisted-by: LLM Link: https://patch.msgid.link/20261005155708.1471260-1-kees@kernel.org Signed-off-by: Kees Cook --- lib/seq_buf.c | 2 +- lib/tests/seq_buf_kunit.c | 132 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) diff --git a/lib/seq_buf.c b/lib/seq_buf.c index a92093f346da..35a5964370b4 100644 --- a/lib/seq_buf.c +++ b/lib/seq_buf.c @@ -128,7 +128,7 @@ void seq_buf_do_printk(struct seq_buf *s, const char *lvl) } /* No trailing LF */ - if (start < s->buffer + s->len) + if (*start) printk("%s%s\n", lvl, start); } EXPORT_SYMBOL_GPL(seq_buf_do_printk); diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index eb466386bbef..0934dfb602ff 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -6,7 +6,9 @@ */ #include +#include #include +#include static void seq_buf_init_test(struct kunit *test) { @@ -216,6 +218,135 @@ static void seq_buf_putmem_hex_overflow_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); } +/* + * Counters for the console that seq_buf_do_printk_test() registers while it + * runs. Only records carrying the marker are counted, so unrelated kernel + * messages do not disturb them. + * + * An empty record carries nothing to recognize it by, so count one only + * where the flaw puts it: directly after a record of ours, with nothing in + * between. That still misreads a bare line feed printed by another CPU in + * exactly that gap, but no longer counts one printed at any point while the + * console happens to be registered. + */ +#define SEQ_BUF_PRINTK_MARKER "sbdpkx" + +static unsigned int seq_buf_printk_marked; +static unsigned int seq_buf_printk_empty; +static bool seq_buf_printk_last_was_ours; + +static void seq_buf_printk_capture(struct console *con, + const char *s, unsigned int count) +{ + const char *text = s; + const char *prefix; + + /* + * Skip what printk() puts in front of the message: a timestamp, + * and the caller id as well under CONFIG_PRINTK_CALLER, so strip + * every bracketed group rather than just the first. + */ + while (count && text[0] == '[') { + prefix = memchr(text, ']', count); + if (!prefix) + break; + count -= prefix + 1 - text; + text = prefix + 1; + if (count && text[0] == ' ') { + text++; + count--; + } + } + + if (strnstr(text, SEQ_BUF_PRINTK_MARKER, count)) { + seq_buf_printk_marked++; + seq_buf_printk_last_was_ours = true; + return; + } + + if (seq_buf_printk_last_was_ours && + (count == 0 || (count == 1 && text[0] == '\n'))) + seq_buf_printk_empty++; + + seq_buf_printk_last_was_ours = false; +} + +static void seq_buf_printk_run(struct console *capture, struct seq_buf *s) +{ + seq_buf_printk_marked = 0; + seq_buf_printk_empty = 0; + seq_buf_printk_last_was_ours = false; + + /* + * register_console() will not take an unmatched console without + * CON_ENABLED, and unregister_console() clears it, so set it on + * every run to keep the test repeatable. + */ + capture->flags = CON_ENABLED; + register_console(capture); + seq_buf_do_printk(s, KERN_INFO); + unregister_console(capture); +} + +static void seq_buf_do_printk_test(struct kunit *test) +{ + /* + * A registered console is a global object: printk() reaches it + * through the console list from any CPU, and the console code writes + * back into it, so keep it out of this function's stack frame the + * way every other console in the tree does. + */ + static struct console capture = { + .name = "sbufcap", + .write = seq_buf_printk_capture, + .index = -1, + }; + DECLARE_SEQ_BUF(s, 8); + DECLARE_SEQ_BUF(t, 16); + DECLARE_SEQ_BUF(u, 8); + + /* + * Fill the buffer exactly, so that the NUL takes the place of the + * last byte and the string ends with the line feed before it. + */ + seq_buf_puts(&s, SEQ_BUF_PRINTK_MARKER); + seq_buf_putc(&s, '\n'); + seq_buf_putc(&s, '!'); + KUNIT_ASSERT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_ASSERT_EQ(test, seq_buf_used(&s), 8); + KUNIT_ASSERT_EQ(test, strlen(seq_buf_str(&s)), 7); + + seq_buf_printk_run(&capture, &s); + + /* The one line that was written, and nothing after it. */ + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 1); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); + + /* Check that lines without a trailing newline are shown. */ + seq_buf_puts(&t, SEQ_BUF_PRINTK_MARKER "\n" SEQ_BUF_PRINTK_MARKER); + KUNIT_ASSERT_FALSE(test, seq_buf_has_overflowed(&t)); + + seq_buf_printk_run(&capture, &t); + + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 2); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); + + /* + * The buffer above was exactly full, where "len" equals the size. A + * buffer that actually overflowed reaches the same bug by the other + * route the old test had, with "len" one past the size. + */ + seq_buf_puts(&u, SEQ_BUF_PRINTK_MARKER "\n"); + KUNIT_EXPECT_EQ(test, seq_buf_puts(&u, "yy"), -1); + KUNIT_ASSERT_TRUE(test, seq_buf_has_overflowed(&u)); + KUNIT_ASSERT_EQ(test, u.len, u.size + 1); + + seq_buf_printk_run(&capture, &u); + + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 1); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); +} + static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), KUNIT_CASE(seq_buf_declare_test), @@ -228,6 +359,7 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_get_buf_commit_test), KUNIT_CASE(seq_buf_putmem_hex_test), KUNIT_CASE(seq_buf_putmem_hex_overflow_test), + KUNIT_CASE(seq_buf_do_printk_test), {} }; From b7e688b5635a0888613f4d620eeb7440e2f23a7e Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:52 -0700 Subject: [PATCH 15/29] seq_buf: Do not pop from an overflowed seq_buf When a seq_buf has overflowed, its len is size + 1, so seq_buf_pop() decrements len to size and reads buffer[size], one byte past the end of the buffer. It also leaves len equal to size, which no longer counts as overflowed, so a truncated seq_buf then looks like a complete, full one. An overflowed seq_buf logically has no last character to pop: the length of what was written has been lost, and the last byte of the buffer may be the NUL written by vsnprintf() or bytes that were never committed. Return -1 for an overflowed seq_buf, as for an empty one, and leave it overflowed, as the rest of the seq_buf API does until seq_buf_clear() or seq_buf_init(). The current callers do not reach this, e.g. trace_syscalls only calls trace_seq_pop() when the trace_seq it pops from has not overflowed, and kernel/bpf/diagnostics.c sets the length from strnlen() before popping. Add tests for the pop corner cases. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.1.0. Fixes: 32e0f607ac6a2 ("tracing: Add trace_seq_pop() and seq_buf_pop()") Assisted-by: LLM Reviewed-by: Andy Shevchenko Link: https://patch.msgid.link/20261005155708.1471260-2-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 4 ++-- include/linux/trace_seq.h | 5 ++++- lib/tests/seq_buf_kunit.c | 42 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 9f2839e73f8a..f5a350347bc5 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -155,11 +155,11 @@ static inline void seq_buf_commit(struct seq_buf *s, int num) * * Removes the last written character to the seq_buf @s. * - * Returns the last character or -1 if it is empty. + * Returns the last character, or -1 if @s is empty or has overflowed. */ static inline int seq_buf_pop(struct seq_buf *s) { - if (!s->len) + if (!s->len || seq_buf_has_overflowed(s)) return -1; s->len--; diff --git a/include/linux/trace_seq.h b/include/linux/trace_seq.h index 697d619aafdc..7174ebf3f015 100644 --- a/include/linux/trace_seq.h +++ b/include/linux/trace_seq.h @@ -86,7 +86,10 @@ static inline bool trace_seq_has_overflowed(struct trace_seq *s) * * Removes the last written character to the trace_seq @s. * - * Returns the last character or -1 if it is empty. + * Returns the last character, or -1 if the underlying seq_buf is empty or + * has overflowed. Note that only that buffer is consulted: a @s marked + * full by a write that did not fit, which trace_seq_has_overflowed() + * reports as overflowed, still pops the last character written. */ static inline int trace_seq_pop(struct trace_seq *s) { diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index 0934dfb602ff..de491f96c1ac 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -115,6 +115,47 @@ static void seq_buf_putc_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); } +static void seq_buf_pop_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 8); + struct seq_buf t; + char *buf; + + /* Nothing to pop. */ + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), -1); + KUNIT_EXPECT_EQ(test, s.len, 0); + + seq_buf_puts(&s, "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 'o'); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 4); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hell"); + + /* A 0xff byte must not be mistaken for an empty buffer. */ + seq_buf_putc(&s, 0xff); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 0xff); + + /* A full buffer pops its last byte. */ + seq_buf_puts(&s, "abc"); + seq_buf_putc(&s, 'd'); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 8); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 'd'); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 7); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hellabc"); + + /* + * An overflowed buffer has nothing to pop, and stays overflowed. Use + * a buffer allocated at its exact size, so that KASAN reports any + * read past its end. + */ + buf = kunit_kmalloc(test, 16, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq_buf_init(&t, buf, 16); + KUNIT_EXPECT_EQ(test, seq_buf_printf(&t, "%s", "longer than sixteen"), -1); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&t), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&t)); +} + static void seq_buf_printf_test(struct kunit *test) { DECLARE_SEQ_BUF(s, 32); @@ -354,6 +395,7 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_puts_test), KUNIT_CASE(seq_buf_puts_overflow_test), KUNIT_CASE(seq_buf_putc_test), + KUNIT_CASE(seq_buf_pop_test), KUNIT_CASE(seq_buf_printf_test), KUNIT_CASE(seq_buf_printf_overflow_test), KUNIT_CASE(seq_buf_get_buf_commit_test), From cc9d25b451196e1cdbea5891902cb65b03da1226 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:53 -0700 Subject: [PATCH 16/29] scsi: lpfc: Print rx monitor records straight into the seq_buf lpfc_rx_monitor_report() formats each record into a stack buffer, then appends it with seq_buf_puts(), relying on seq_buf_puts() appending nothing when a string does not fit: the debugfs output then ends at the last whole record, and the record left out is read in full next time. The next patch makes seq_buf_puts() copy as much as fits instead, as seq_buf_printf() and strlcat() do. Print each record with seq_buf_printf(), and when it does not fit, end the string where the record began, since the reader takes the buffer up to its NUL. This also takes the DBG_LOG_STR_SZ buffer off the stack. Build tested ARCH=x86_64 with GCC 16.2.0, CONFIG_SCSI_LPFC=m and W=1. Assisted-by: LLM Link: https://patch.msgid.link/20261005155708.1471260-3-kees@kernel.org Signed-off-by: Kees Cook --- drivers/scsi/lpfc/lpfc_sli.c | 45 +++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/drivers/scsi/lpfc/lpfc_sli.c b/drivers/scsi/lpfc/lpfc_sli.c index cfa4371169f1..a7b1ea67ed98 100644 --- a/drivers/scsi/lpfc/lpfc_sli.c +++ b/drivers/scsi/lpfc/lpfc_sli.c @@ -8108,7 +8108,6 @@ u32 lpfc_rx_monitor_report(struct lpfc_hba *phba, spinlock_t *ring_lock = &rx_monitor->lock; u32 ring_size = rx_monitor->entries; u32 cnt = 0; - char tmp[DBG_LOG_STR_SZ] = {0}; bool log_to_kmsg = (!buf || !buf_len) ? true : false; struct seq_buf s; @@ -8133,27 +8132,37 @@ u32 lpfc_rx_monitor_report(struct lpfc_hba *phba, /* Read out this entry's data. */ if (!log_to_kmsg) { + unsigned int len; + + /* A header that did not fit leaves no room. */ + if (seq_buf_has_overflowed(&s)) + break; + len = seq_buf_used(&s); + + seq_buf_printf(&s, + "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n", + *head_idx, + entry->max_bytes_per_interval, + entry->cmf_bytes, + entry->total_bytes, + entry->rcv_bytes, + entry->avg_io_latency, + entry->avg_io_size, + entry->max_read_cnt, + entry->cmf_busy, entry->io_cnt, + entry->cmf_info, + entry->timer_utilization, + entry->timer_interval); + /* * Drop a record whole if it does not fit, without - * consuming its ring entry. + * consuming its ring entry: the reader takes the + * string up to its NUL. */ - scnprintf(tmp, sizeof(tmp), - "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n", - *head_idx, - entry->max_bytes_per_interval, - entry->cmf_bytes, - entry->total_bytes, - entry->rcv_bytes, - entry->avg_io_latency, - entry->avg_io_size, - entry->max_read_cnt, - entry->cmf_busy, entry->io_cnt, - entry->cmf_info, - entry->timer_utilization, - entry->timer_interval); - - if (seq_buf_puts(&s, tmp) < 0) + if (seq_buf_has_overflowed(&s)) { + buf[len] = '\0'; break; + } } else { lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT, "4410 %02u: MBPI %llu Xmit %llu " From 505a4aeea2c98ab9b09bc157e81e19cc0d4bf9cb Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:54 -0700 Subject: [PATCH 17/29] seq_buf: Copy what fits when seq_buf_puts() and seq_buf_putmem() overflow When seq_buf_puts() or seq_buf_putmem() is given more than fits, it copies nothing and only marks the seq_buf as overflowed. If seq_buf_str() is used, it will terminate the buffer in its last byte, so every byte between the end of the data and the end of the buffer becomes part of the string, though the seq_buf never wrote them. seq_buf_printf() does not have this problem, because vsnprintf() writes as much of the output as fits, followed by a NUL. Repeat this behavior in seq_buf_puts(), using strscpy(), and in seq_buf_putmem(), which also covers seq_buf_putmem_hex(). seq_buf_putc() needs no change, as it can only overflow when the buffer is already full. Each writer now records the buffer as full once it has copied what fits, so that what it wrote can be told apart from bytes nothing touched. Of the callers that check the return value or test for overflow afterward, only lpfc_rx_monitor_report() relied on a string that did not fit being left out, and the previous patch has it drop such a record itself. The others treat overflow as an error or report it. The callers that ignore overflow use whatever the buffer holds, which now ends with the part of the string that fit. Update seq_buf_putmem_hex_overflow_test, which expected a hex group that did not fit whole to be left out entirely, and add tests that overflow seq_buf_puts(), seq_buf_putmem() and seq_buf_putmem_hex() with stale bytes in the buffer. The three partial-overflow tests check the buffer itself rather than seq_buf_str(). Neither writer leaves the last byte of the buffer alone: seq_buf_putmem() copies raw bytes and writes no NUL, and seq_buf_puts() relies on strscpy() to write one. That byte is exactly where seq_buf_str() writes its terminator, so asserting only on the string would pass whether the copy stopped a byte early or dropped the NUL entirely. seq_buf_putmem() was not exported, so the test failed to link as a module. Export it. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0, and the test builds as a module (CONFIG_SEQ_BUF_KUNIT_TEST=m). Assisted-by: LLM Reviewed-by: Andy Shevchenko Link: https://patch.msgid.link/20261005155708.1471260-4-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 6 +++ lib/seq_buf.c | 17 +++++++- lib/tests/seq_buf_kunit.c | 85 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 104 insertions(+), 4 deletions(-) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index f5a350347bc5..77e76e283370 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -55,6 +55,12 @@ seq_buf_has_overflowed(struct seq_buf *s) return s->len > s->size; } +/* + * Mark @s as overflowed, which discards the length of what it holds. The + * bytes up to its last one are the string from then on, as that is where + * seq_buf_str() terminates it, so a caller that could not fill the buffer + * has to NUL them itself before calling this. + */ static inline void seq_buf_set_overflow(struct seq_buf *s) { diff --git a/lib/seq_buf.c b/lib/seq_buf.c index 35a5964370b4..60e9eadb3ef7 100644 --- a/lib/seq_buf.c +++ b/lib/seq_buf.c @@ -175,7 +175,9 @@ int seq_buf_bprintf(struct seq_buf *s, const char *fmt, const u32 *binary) * @s: seq_buf descriptor * @str: simple string to record * - * Copy a simple string into the sequence buffer. + * Copy a simple string into the sequence buffer. If @str does not fit, + * as much of it as fits is copied, followed by a null byte, as + * seq_buf_printf() does. * * Returns: zero on success, -1 on overflow. */ @@ -194,6 +196,11 @@ int seq_buf_puts(struct seq_buf *s, const char *str) s->len += len - 1; return 0; } + /* Copy what fits, so the buffer never holds stale bytes */ + if (s->len < s->size) { + strscpy(s->buffer + s->len, str, s->size - s->len); + s->len = s->size; + } seq_buf_set_overflow(s); return -1; } @@ -229,7 +236,7 @@ EXPORT_SYMBOL_GPL(seq_buf_putc); * * There may be cases where raw memory needs to be written into the * buffer and a strcpy() would not work. Using this function allows - * for such cases. + * for such cases. If @mem does not fit, as much of it as fits is copied. * * Returns: zero on success, -1 on overflow. */ @@ -242,9 +249,15 @@ int seq_buf_putmem(struct seq_buf *s, const void *mem, unsigned int len) s->len += len; return 0; } + /* Copy what fits, so the buffer never holds stale bytes */ + if (s->len < s->size) { + memcpy(s->buffer + s->len, mem, s->size - s->len); + s->len = s->size; + } seq_buf_set_overflow(s); return -1; } +EXPORT_SYMBOL_GPL(seq_buf_putmem); #define MAX_MEMHEX_BYTES 8U #define HEX_CHARS (MAX_MEMHEX_BYTES*2 + 1) diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index de491f96c1ac..046614100c77 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -248,9 +248,9 @@ static void seq_buf_putmem_hex_overflow_test(struct kunit *test) DECLARE_SEQ_BUF(s, 20); const u8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; #ifdef __BIG_ENDIAN - const char *expected = "0001020304050607 "; + const char *expected = "0001020304050607 08"; #else - const char *expected = "0706050403020100 "; + const char *expected = "0706050403020100 09"; #endif KUNIT_EXPECT_EQ(test, seq_buf_putmem_hex(&s, data, sizeof(data)), -1); @@ -259,6 +259,84 @@ static void seq_buf_putmem_hex_overflow_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); } +static void seq_buf_puts_partial_overflow_test(struct kunit *test) +{ + static const char expected[] = "abcdefg"; + DECLARE_SEQ_BUF(s, 16); + struct seq_buf t; + char buf[8]; + + /* As much of the string as fits is written, like seq_buf_printf(). */ + seq_buf_puts(&s, "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_puts(&s, " world, again"), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 16); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello world, ag"); + + /* Stale bytes after the data must not show up in the string. */ + memset(buf, 'X', sizeof(buf)); + seq_buf_init(&t, buf, sizeof(buf)); + seq_buf_putc(&t, 'a'); + KUNIT_EXPECT_EQ(test, seq_buf_puts(&t, "bcdefghij"), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&t)); + + /* + * Check the buffer before seq_buf_str() does: it would write the + * terminator over the last byte itself, hiding whether the copy + * placed one there. The literal's own NUL is the eighth byte. + */ + KUNIT_EXPECT_MEMEQ(test, buf, expected, sizeof(buf)); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&t), "abcdefg"); +} + +static void seq_buf_putmem_partial_overflow_test(struct kunit *test) +{ + const u8 data[] = { 1, 2, 3, 4, 5, 6, 7 }; + const char expected[] = { 'a', 'b', 1, 2, 3, 4, 5, 6 }; + struct seq_buf s; + char buf[8]; + + memset(buf, 'X', sizeof(buf)); + seq_buf_init(&s, buf, sizeof(buf)); + seq_buf_putmem(&s, "ab", 2); + + /* One byte too many, so the last byte of @data is dropped. */ + KUNIT_EXPECT_EQ(test, seq_buf_putmem(&s, data, sizeof(data)), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + + /* + * Check the buffer rather than seq_buf_str(): seq_buf_putmem() writes + * no NUL of its own, so a short copy leaves a stale byte at the end, + * exactly where seq_buf_str() would then write the terminator and + * hide it. + */ + KUNIT_EXPECT_MEMEQ(test, buf, expected, sizeof(buf)); +} + +static void seq_buf_putmem_hex_partial_overflow_test(struct kunit *test) +{ + const u8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; +#ifdef __BIG_ENDIAN + const char *expected = "0001020304050607 08"; + static const char expected_raw[] = "0001020304050607 080"; +#else + const char *expected = "0706050403020100 09"; + static const char expected_raw[] = "0706050403020100 090"; +#endif + struct seq_buf s; + char buf[20]; + + /* Stale bytes after the data must not show up in the string. */ + memset(buf, 'X', sizeof(buf)); + seq_buf_init(&s, buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, seq_buf_putmem_hex(&s, data, sizeof(data)), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + + /* Before seq_buf_str() writes the terminator over the last byte. */ + KUNIT_EXPECT_MEMEQ(test, buf, expected_raw, sizeof(buf)); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); +} + /* * Counters for the console that seq_buf_do_printk_test() registers while it * runs. Only records carrying the marker are counted, so unrelated kernel @@ -401,6 +479,9 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_get_buf_commit_test), KUNIT_CASE(seq_buf_putmem_hex_test), KUNIT_CASE(seq_buf_putmem_hex_overflow_test), + KUNIT_CASE(seq_buf_puts_partial_overflow_test), + KUNIT_CASE(seq_buf_putmem_partial_overflow_test), + KUNIT_CASE(seq_buf_putmem_hex_partial_overflow_test), KUNIT_CASE(seq_buf_do_printk_test), {} }; From ea5666e56723e9ac7094ff9849cf154dcb0e436e Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:55 -0700 Subject: [PATCH 18/29] seq_buf: Clear what a writer did not claim when a seq_buf overflows Using seq_buf_set_overflow() would leave the bytes between "len" and "size" untouched, so if seq_buf_str() is used on an overflowed seq_buf, those bytes may be exposed. For any paths that don't claim partially written bytes, by setting "len = size" before calling seq_buf_set_overflow(), wipe the unclaimed bytes. The seq_buf_puts() and related APIs already claim those bytes now, so only the unclaimed cases remain. A specific example of this was seq_buf_path() which uses d_path() and would write to the tail before discovering it was out of space, and would correctly mark a seq_buf as overflowed, but the path fragment would be left over. Clear from len to the end of the buffer in seq_buf_set_overflow(), which every overflow goes through, including seq_buf_commit() with a negative count. Add a test that fills a seq_buf, leaves it too little room for a path, and checks that nothing of the path is left in the buffer. The tests run before anything writable is mounted, so it takes its file from shmem. seq_buf_path() was not exported, so the test failed to link as a module. Export it. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0, and the test builds as a module (CONFIG_SEQ_BUF_KUNIT_TEST=m). Assisted-by: LLM Reviewed-by: Andy Shevchenko Link: https://patch.msgid.link/20261005155708.1471260-5-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 8 +++++-- lib/seq_buf.c | 5 +++++ lib/tests/seq_buf_kunit.c | 44 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 77e76e283370..0c0a0db04b09 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -5,6 +5,7 @@ #include #include #include +#include #include /* @@ -58,12 +59,15 @@ seq_buf_has_overflowed(struct seq_buf *s) /* * Mark @s as overflowed, which discards the length of what it holds. The * bytes up to its last one are the string from then on, as that is where - * seq_buf_str() terminates it, so a caller that could not fill the buffer - * has to NUL them itself before calling this. + * seq_buf_str() terminates it, so clear whatever was not written: a writer + * sets len to how much it filled, and anything past that was never adopted. */ static inline void seq_buf_set_overflow(struct seq_buf *s) { + if (s->len < s->size) + memset(s->buffer + s->len, 0, s->size - s->len); + s->len = s->size + 1; } diff --git a/lib/seq_buf.c b/lib/seq_buf.c index 60e9eadb3ef7..8da2e9447adf 100644 --- a/lib/seq_buf.c +++ b/lib/seq_buf.c @@ -76,6 +76,8 @@ int seq_buf_vprintf(struct seq_buf *s, const char *fmt, va_list args) s->len += len; return 0; } + /* vsnprintf() wrote as much as fits, so none of it is stale */ + s->len = s->size; } seq_buf_set_overflow(s); return -1; @@ -164,6 +166,8 @@ int seq_buf_bprintf(struct seq_buf *s, const char *fmt, const u32 *binary) s->len += ret; return 0; } + /* bstr_printf() wrote as much as fits, so none of it is stale */ + s->len = s->size; } seq_buf_set_overflow(s); return -1; @@ -343,6 +347,7 @@ int seq_buf_path(struct seq_buf *s, const struct path *path, const char *esc) return res; } +EXPORT_SYMBOL_GPL(seq_buf_path); /** * seq_buf_to_user - copy the sequence buffer to user space diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index 046614100c77..5eaf024fa3a5 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -7,7 +7,9 @@ #include #include +#include #include +#include #include static void seq_buf_init_test(struct kunit *test) @@ -466,6 +468,47 @@ static void seq_buf_do_printk_test(struct kunit *test) KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); } +/* Long enough that it cannot fit in the room the test leaves for it. */ +#define SEQ_BUF_TEST_PATH "/seq_buf_kunit_path_name" + +static void seq_buf_path_overflow_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 32); + const char *expected = "keep:xxxxxxxxxxxxxxxxxxxxxxx"; + struct file *file; + size_t len; + int i; + + /* + * The tests run before anything writable is mounted, so take the file + * whose path gets printed from shmem, which needs no mount of its own. + */ + file = shmem_file_setup(SEQ_BUF_TEST_PATH, 0, EMPTY_VMA_FLAGS); + if (IS_ERR(file)) + kunit_skip(test, "cannot create a file to print the path of"); + + /* Leave less room than the path needs, so d_path() cannot fit it. */ + seq_buf_puts(&s, "keep:"); + len = seq_buf_used(&s); + for (i = len; i < 28; i++) + seq_buf_putc(&s, 'x'); + + KUNIT_EXPECT_EQ(test, seq_buf_path(&s, &file->f_path, "\n"), -1); + fput(file); + + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + + /* + * d_path() keeps as much of the path as fits when it does not fit + * whole, and seq_buf_str() would hand out that fragment, as it ends + * the string at the last byte of an overflowed buffer. + */ + for (i = 28; i < 32; i++) + KUNIT_EXPECT_EQ_MSG(test, s.buffer[i], '\0', + "byte %d past the data is not cleared", i); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); +} + static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), KUNIT_CASE(seq_buf_declare_test), @@ -482,6 +525,7 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_puts_partial_overflow_test), KUNIT_CASE(seq_buf_putmem_partial_overflow_test), KUNIT_CASE(seq_buf_putmem_hex_partial_overflow_test), + KUNIT_CASE(seq_buf_path_overflow_test), KUNIT_CASE(seq_buf_do_printk_test), {} }; From 8d1478bfd63be0f065defd1066d2fa294f419ae2 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:56 -0700 Subject: [PATCH 19/29] seq_buf: Add seq_buf_strlen() Several strlcat() call sites being converted to seq_buf need behavior seq_buf doesn't currently provide. The return from seq_buf_used() is not the length of the string in a seq_buf. Once the buffer is full or has overflowed it returns the buffer size, which counts the byte that seq_buf_str() replaces with the NUL, so a caller that needs the string and its length has to call seq_buf_str() and then walk the string with strlen(). Move the termination out of seq_buf_str() into a helper that returns where it put the NUL, and add seq_buf_strlen(), which terminates the buffer in the same way and returns that offset. As discussed in review, don't add WARN_ON() for seq_buf_strlen() and drop it from seq_buf_str(). Add tests comparing seq_buf_strlen() against strlen() of seq_buf_str() for empty, appended, truncated, exactly full, and overflowed buffers, checking that seq_buf_strlen() alone terminates a full buffer, and checking that a zero-sized seq_buf reports an empty string from both accessors without touching the buffer. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0. Assisted-by: LLM Reviewed-by: Andy Shevchenko Link: https://patch.msgid.link/20261005155708.1471260-6-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 67 ++++++++++++++++++-- lib/tests/seq_buf_kunit.c | 129 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 6 deletions(-) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 0c0a0db04b09..7abeca1c166b 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -89,6 +89,27 @@ static inline unsigned int seq_buf_used(struct seq_buf *s) return min(s->len, s->size); } +/* + * NUL-terminate the buffer in @s: directly after the data when there is + * room for it, otherwise in the last byte of the buffer. @s->size must not + * be zero. + * + * Returns: the offset of the NUL. + */ +static inline size_t __seq_buf_terminate(struct seq_buf *s) +{ + size_t end; + + if (seq_buf_buffer_left(s)) + end = s->len; + else + end = s->size - 1; + + s->buffer[end] = 0; + + return end; +} + /** * seq_buf_str - get NUL-terminated C string from seq_buf * @s: the seq_buf handle @@ -98,7 +119,14 @@ static inline unsigned int seq_buf_used(struct seq_buf *s) * * Note, if this is called when the buffer has overflowed, then * the last byte of the buffer is zeroed, and the len will still - * point passed it. + * point passed it. The same happens when the buffer is exactly + * full: the NUL takes the place of the last byte written, which is + * lost, though seq_buf_used() still counts it. + * + * A zero-sized seq_buf has nowhere to put a NUL, so the empty string + * is returned instead of writing to @s->buffer. Any other seq_buf + * returns @s->buffer, even when it holds an empty string, so callers + * always get their own buffer back. * * After this function is called, s->buffer is safe to use * in string operations. @@ -107,17 +135,44 @@ static inline unsigned int seq_buf_used(struct seq_buf *s) */ static inline const char *seq_buf_str(struct seq_buf *s) { - if (WARN_ON(s->size == 0)) + if (s->size == 0) return ""; - if (seq_buf_buffer_left(s)) - s->buffer[s->len] = 0; - else - s->buffer[s->size - 1] = 0; + __seq_buf_terminate(s); return s->buffer; } +/** + * seq_buf_strlen - get the length of the NUL-terminated C string in seq_buf + * @s: the seq_buf handle + * + * This makes sure that the buffer in @s is NUL-terminated, exactly as + * seq_buf_str() does, and returns the length of the resulting string + * without walking it. Unlike seq_buf_used(), this does not count the byte + * given up to the NUL when the buffer is full or has overflowed. When the + * buffer is exactly full, that byte is the last one written, and calling + * either function loses it. + * + * A zero-sized seq_buf holds no string, so 0 is returned without writing + * to @s->buffer, matching what seq_buf_str() returns for one. + * + * After this function is called, s->buffer is safe to use + * in string operations. + * + * Returns: the offset of the NUL that terminates @s->buffer. That is the + * length of the string unless an earlier NUL is in the way, either one the + * data written to @s carried itself, or one seq_buf_set_overflow() left + * behind when it cleared what no writer had claimed. + */ +static inline size_t seq_buf_strlen(struct seq_buf *s) +{ + if (s->size == 0) + return 0; + + return __seq_buf_terminate(s); +} + /** * seq_buf_get_buf - get buffer to write arbitrary data to * @s: the seq_buf handle diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index 5eaf024fa3a5..c6d941a4502f 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -25,6 +25,7 @@ static void seq_buf_init_test(struct kunit *test) KUNIT_EXPECT_EQ(test, seq_buf_buffer_left(&s), 32); KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 0); KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 0); } static void seq_buf_declare_test(struct kunit *test) @@ -509,6 +510,128 @@ static void seq_buf_path_overflow_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); } +static void seq_buf_strlen_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 16); + + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 0); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); + + seq_buf_puts(&s, "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 5); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); + + seq_buf_printf(&s, " %s", "world"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 11); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); +} + +static void seq_buf_strlen_printf_overflow_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 16); + DECLARE_SEQ_BUF(t, 8); + + seq_buf_printf(&s, "%s", "1234567890abcdefghij"); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 16); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 15); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "1234567890abcde"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); + + /* Output one byte too long for the NUL. */ + seq_buf_printf(&t, "%s", "12345678"); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&t)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&t), 8); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&t), 7); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&t), "1234567"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&t), strlen(seq_buf_str(&t))); +} + +static void seq_buf_strlen_full_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 4); + DECLARE_SEQ_BUF(t, 8); + char *buf; + size_t len; + + /* Filled exactly, with no room left for a NUL, but not overflowed. */ + seq_buf_putc(&s, 'a'); + seq_buf_putc(&s, 'b'); + seq_buf_putc(&s, 'c'); + seq_buf_putc(&s, 'd'); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 4); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 3); + /* seq_buf_strlen() terminates the buffer by itself. */ + KUNIT_EXPECT_EQ(test, s.buffer[3], '\0'); + KUNIT_EXPECT_EQ(test, strnlen(s.buffer, s.size), 3); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "abc"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); + + /* A printf into a full buffer writes nothing. */ + KUNIT_EXPECT_EQ(test, seq_buf_printf(&s, "%s", "x"), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 3); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "abc"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); + + len = seq_buf_get_buf(&t, &buf); + KUNIT_ASSERT_EQ(test, len, 8); + memset(buf, 'z', len); + seq_buf_commit(&t, len); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&t)); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&t), 7); + KUNIT_EXPECT_EQ(test, t.buffer[7], '\0'); + KUNIT_EXPECT_EQ(test, strnlen(t.buffer, t.size), 7); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&t), "zzzzzzz"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&t), strlen(seq_buf_str(&t))); +} + +static void seq_buf_strlen_puts_overflow_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 16); + + /* A puts that does not fit copies as much as fits. */ + seq_buf_puts(&s, "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_puts(&s, " this does not fit"), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 15); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello this does"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), strlen(seq_buf_str(&s))); +} + +static void seq_buf_strlen_embedded_nul_test(struct kunit *test) +{ + static const char data[] = "ab\0cd"; + DECLARE_SEQ_BUF(s, 16); + + /* + * seq_buf_strlen() reports where it put the terminator, not where + * the first NUL is, so data carrying a NUL of its own makes the two + * disagree. That is expected, and is what the documented caveat is + * about. + */ + seq_buf_putmem(&s, data, sizeof(data) - 1); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 5); + KUNIT_EXPECT_EQ(test, strlen(seq_buf_str(&s)), 2); +} + +static void seq_buf_strlen_zero_size_test(struct kunit *test) +{ + char buf[] = "untouched"; + struct seq_buf s; + + /* + * A zero-sized seq_buf has nowhere to put a terminator. Both + * accessors report an empty string and leave the buffer alone + * rather than writing outside it. + */ + seq_buf_init(&s, buf, 0); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 0); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); + KUNIT_EXPECT_STREQ(test, buf, "untouched"); +} + static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), KUNIT_CASE(seq_buf_declare_test), @@ -526,6 +649,12 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_putmem_partial_overflow_test), KUNIT_CASE(seq_buf_putmem_hex_partial_overflow_test), KUNIT_CASE(seq_buf_path_overflow_test), + KUNIT_CASE(seq_buf_strlen_test), + KUNIT_CASE(seq_buf_strlen_printf_overflow_test), + KUNIT_CASE(seq_buf_strlen_full_test), + KUNIT_CASE(seq_buf_strlen_puts_overflow_test), + KUNIT_CASE(seq_buf_strlen_embedded_nul_test), + KUNIT_CASE(seq_buf_strlen_zero_size_test), KUNIT_CASE(seq_buf_do_printk_test), {} }; From 88c652df02ccf9e7644c012f8375fec24d848be3 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:57 -0700 Subject: [PATCH 20/29] seq_buf: Add seq_buf_terminate() Seven callers call seq_buf_str() only to NUL-terminate the buffer, discarding the returned pointer. Two of them need a comment to say so. Add seq_buf_terminate(), wrapping the __seq_buf_terminate() helper that seq_buf_str() and seq_buf_strlen() already use, and convert those callers. It returns void: returning the offset would just be seq_buf_strlen() under another name. A zero-sized seq_buf is left untouched, as in the other accessors. Add tests for the three cases: room for the NUL after the data, an overflowed buffer where it lands in the last byte, and a zero-sized buffer that must not be written to. Build tested ARCH=x86_64 defconfig with GCC 16.2.0, plus CONFIG_HIST_TRIGGERS=y and CONFIG_BPF_SYSCALL=y to reach the converted call sites in kernel/trace/trace_events_hist.c and kernel/bpf/diagnostics.c. Tests run 24/24 passing on ARCH=um. Assisted-by: LLM Acked-by: Alexei Starovoitov Link: https://patch.msgid.link/20261005155708.1471260-7-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 23 ++++++++++++++++++++ kernel/bpf/diagnostics.c | 6 +++--- kernel/trace/trace_events.c | 4 ++-- kernel/trace/trace_events_hist.c | 6 ++---- lib/tests/seq_buf_kunit.c | 36 ++++++++++++++++++++++++++++++++ 5 files changed, 66 insertions(+), 9 deletions(-) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 7abeca1c166b..9830f905f0ee 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -173,6 +173,29 @@ static inline size_t seq_buf_strlen(struct seq_buf *s) return __seq_buf_terminate(s); } +/** + * seq_buf_terminate - NUL-terminate the string in a seq_buf + * @s: the seq_buf handle + * + * Terminate @s->buffer exactly as seq_buf_str() and seq_buf_strlen() do, + * for callers that want neither the pointer nor the length and only need + * the buffer to be safe to read as a C string. A zero-sized seq_buf has + * nowhere to put a NUL and is left untouched. + * + * Nothing is returned on purpose: a caller that wants the length should + * use seq_buf_strlen(), which says so. + * + * After this function is called, s->buffer is safe to use + * in string operations. + */ +static inline void seq_buf_terminate(struct seq_buf *s) +{ + if (s->size == 0) + return; + + __seq_buf_terminate(s); +} + /** * seq_buf_get_buf - get buffer to write arbitrary data to * @s: the seq_buf handle diff --git a/kernel/bpf/diagnostics.c b/kernel/bpf/diagnostics.c index 0abbbe177e31..594cf3c8b74c 100644 --- a/kernel/bpf/diagnostics.c +++ b/kernel/bpf/diagnostics.c @@ -351,7 +351,7 @@ static void diag_fmt_restore(struct bpf_verifier_env *env, struct diag_fmt_mark if (mark.chunk) { mark.chunk->seq.len = mark.len; - seq_buf_str(&mark.chunk->seq); + seq_buf_terminate(&mark.chunk->seq); } } @@ -631,11 +631,11 @@ static void format_disasm_line(struct bpf_verifier_env *env, int insn_idx, return; print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); - seq_buf_str(&ctx.seq); + seq_buf_terminate(&ctx.seq); ctx.seq.len = strnlen(line->text, sizeof(line->text)); while (ctx.seq.len && line->text[ctx.seq.len - 1] == '\n') seq_buf_pop(&ctx.seq); - seq_buf_str(&ctx.seq); + seq_buf_terminate(&ctx.seq); line->valid = true; } diff --git a/kernel/trace/trace_events.c b/kernel/trace/trace_events.c index 9dbc2441763b..39bb391546de 100644 --- a/kernel/trace/trace_events.c +++ b/kernel/trace/trace_events.c @@ -4906,7 +4906,7 @@ static __init int event_trace_enable(void) */ __trace_early_add_events(tr); - seq_buf_str(&bootup_event_seq); + seq_buf_terminate(&bootup_event_seq); early_enable_events(tr, bootup_event_buf, false); trace_printk_start_comm(); @@ -4935,7 +4935,7 @@ static __init int event_trace_enable_again(void) if (!tr) return -ENODEV; - seq_buf_str(&bootup_event_seq); + seq_buf_terminate(&bootup_event_seq); early_enable_events(tr, bootup_event_buf, true); return 0; diff --git a/kernel/trace/trace_events_hist.c b/kernel/trace/trace_events_hist.c index 963e0d6b61fd..57bd1cd5c657 100644 --- a/kernel/trace/trace_events_hist.c +++ b/kernel/trace/trace_events_hist.c @@ -2988,8 +2988,7 @@ find_synthetic_field_var(struct hist_trigger_data *target_hist_data, seq_buf_init(&s, synthetic_name, MAX_FILTER_STR_VAL); seq_buf_printf(&s, "synthetic_%s", field_name); - /* Terminate synthetic_name with a NUL. */ - seq_buf_str(&s); + seq_buf_terminate(&s); if (seq_buf_has_overflowed(&s)) { kfree(synthetic_name); @@ -3106,8 +3105,7 @@ create_field_var_hist(struct hist_trigger_data *target_hist_data, if (saved_filter) seq_buf_printf(&s, " if %s", saved_filter); - /* Terminate cmd with a NUL. */ - seq_buf_str(&s); + seq_buf_terminate(&s); if (seq_buf_has_overflowed(&s)) { kfree(cmd); diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index c6d941a4502f..33d351d0be64 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -632,6 +632,41 @@ static void seq_buf_strlen_zero_size_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, buf, "untouched"); } +static void seq_buf_terminate_test(struct kunit *test) +{ + char buf[16]; + struct seq_buf s; + + /* + * seq_buf_putmem() writes no NUL, so only seq_buf_terminate() can + * end these strings early. The NUL in the last byte of buf keeps + * the comparisons in bounds if it does not. + */ + + /* Terminates directly after the data when there is room. */ + memset(buf, 'z', sizeof(buf) - 1); + buf[sizeof(buf) - 1] = '\0'; + seq_buf_init(&s, buf, sizeof(buf)); + seq_buf_putmem(&s, "ab", 2); + seq_buf_terminate(&s); + KUNIT_EXPECT_STREQ(test, buf, "ab"); + + /* Terminates in the last byte once the buffer has overflowed. */ + memset(buf, 'z', sizeof(buf) - 1); + buf[sizeof(buf) - 1] = '\0'; + seq_buf_init(&s, buf, 4); + seq_buf_putmem(&s, "abcdef", 6); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + seq_buf_terminate(&s); + KUNIT_EXPECT_STREQ(test, buf, "abc"); + + /* A zero-sized seq_buf is left alone. */ + strscpy(buf, "untouched", sizeof(buf)); + seq_buf_init(&s, buf, 0); + seq_buf_terminate(&s); + KUNIT_EXPECT_STREQ(test, buf, "untouched"); +} + static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), KUNIT_CASE(seq_buf_declare_test), @@ -655,6 +690,7 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_strlen_puts_overflow_test), KUNIT_CASE(seq_buf_strlen_embedded_nul_test), KUNIT_CASE(seq_buf_strlen_zero_size_test), + KUNIT_CASE(seq_buf_terminate_test), KUNIT_CASE(seq_buf_do_printk_test), {} }; From c8cd1725d259b31b5bfa362696985deb8c9a8039 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:56:58 -0700 Subject: [PATCH 21/29] bpf: Remove dead newline stripping from format_disasm_line() format_disasm_line() strips trailing newlines from the disassembly it stores, as diag_print_insn_context() adds its own. Since commit 483a1bb0b6cf8 ("bpf: Do not print a newline after disassembly in bpf_verbose_insn()"), print_bpf_insn() does not emit one, so there is nothing left to strip. The strnlen() resync of the seq_buf length only existed so the loop could index the buffer safely after an overflow, and the second termination only restored the NUL that seq_buf_pop() does not write. Remove all of it, keeping a single seq_buf_terminate(). Build tested ARCH=x86_64 defconfig with GCC 16.2.0 and CONFIG_BPF_SYSCALL=y. Assisted-by: LLM Acked-by: Alexei Starovoitov Link: https://patch.msgid.link/20261005155708.1471260-8-kees@kernel.org Signed-off-by: Kees Cook --- kernel/bpf/diagnostics.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/kernel/bpf/diagnostics.c b/kernel/bpf/diagnostics.c index 594cf3c8b74c..8f64bfd9afee 100644 --- a/kernel/bpf/diagnostics.c +++ b/kernel/bpf/diagnostics.c @@ -632,10 +632,6 @@ static void format_disasm_line(struct bpf_verifier_env *env, int insn_idx, print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); seq_buf_terminate(&ctx.seq); - ctx.seq.len = strnlen(line->text, sizeof(line->text)); - while (ctx.seq.len && line->text[ctx.seq.len - 1] == '\n') - seq_buf_pop(&ctx.seq); - seq_buf_terminate(&ctx.seq); line->valid = true; } From 61ef3f1490f879ddffe39a8f1a1bf1ae1e60fc23 Mon Sep 17 00:00:00 2001 From: Bill Wendling Date: Mon, 5 Oct 2026 08:56:59 -0700 Subject: [PATCH 22/29] seq_buf: Add seq_buf_init_append() Several strlcat() call sites being converted to seq_buf need behavior seq_buf doesn't currently provide. The normal seq_buf_init() always empties the buffer (sets its "len" to 0) via seq_buf_clear(). Code migrating from strlcat(buf, ...), which appends to whatever buf already contains, can't use seq_buf_init() without discarding that existing content. Add seq_buf_init_append(), which preserves the existing contents and positions the seq_buf to append after it. A buffer with no NUL within its size starts out overflowed, as strlcat() treats it as already truncated. Add KUnit tests for behavior coverage. Tests passed under qemu on ARCH=x86_64 with GCC 16.2.0 and CONFIG_KASAN=y, and on big-endian ARCH=s390 with GCC s390x-linux-gnu 16.2.0. Assisted-by: LLM Signed-off-by: Bill Wendling Reviewed-by: Andy Shevchenko Co-developed-by: Kees Cook Link: https://patch.msgid.link/20261005155708.1471260-9-kees@kernel.org Signed-off-by: Kees Cook --- include/linux/seq_buf.h | 25 ++++++++++++++ lib/tests/seq_buf_kunit.c | 69 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 9830f905f0ee..be979089228f 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -71,6 +71,31 @@ seq_buf_set_overflow(struct seq_buf *s) s->len = s->size + 1; } +/** + * seq_buf_init_append - initialize a seq_buf over a buffer that may + * already hold NUL-terminated content + * @s: the seq_buf handle + * @buf: pointer to the (possibly non-empty) buffer + * @size: total size of @buf + * + * Unlike seq_buf_init(), which always starts @buf at len=0, this + * preserves whatever NUL-terminated content @buf already holds and + * positions @s to append after it. Useful for converting code that used + * to append to an existing buffer with strlcat()/scnprintf() and friends. + * + * If @buf holds no NUL within @size, @s starts out overflowed, as + * strlcat() treats such a buffer as already truncated. + */ +static inline void +seq_buf_init_append(struct seq_buf *s, char *buf, unsigned int size) +{ + s->buffer = buf; + s->size = size; + s->len = strnlen(buf, size); + if (s->len == size) + seq_buf_set_overflow(s); +} + /* * How much buffer is left on the seq_buf? */ diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index 33d351d0be64..fc53e9ef844c 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -28,6 +28,74 @@ static void seq_buf_init_test(struct kunit *test) KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 0); } +static void seq_buf_init_append_test(struct kunit *test) +{ + char buf[32] = "hello"; + struct seq_buf s; + + /* Initial string contents match. */ + seq_buf_init_append(&s, buf, sizeof(buf)); + KUNIT_EXPECT_EQ(test, s.size, 32); + KUNIT_EXPECT_EQ(test, s.len, 5); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_buffer_left(&s), 32 - 5); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 5); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 5); + + /* Appending with space works. */ + seq_buf_puts(&s, " world"); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 11); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello world"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 11); + + /* No truncation when space for NUL is present. */ + seq_buf_init_append(&s, buf, 12); + KUNIT_EXPECT_EQ(test, s.size, 12); + KUNIT_EXPECT_EQ(test, s.len, 11); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 11); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello world"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 11); + + /* + * No NUL within the size: the content is already truncated, as + * strlcat() would see it, so @s starts out overflowed. The content + * stays, and appending adds nothing. + */ + seq_buf_init_append(&s, buf, 11); + KUNIT_EXPECT_EQ(test, s.size, 11); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_buffer_left(&s), 0); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 11); + KUNIT_EXPECT_MEMEQ(test, buf, "hello world", 11); + seq_buf_puts(&s, "!"); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_MEMEQ(test, buf, "hello world", 11); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hello worl"); + KUNIT_EXPECT_EQ(test, seq_buf_strlen(&s), 10); + + /* + * The size bounds the scan: the string runs past it, so there is + * no NUL within the size either. + */ + seq_buf_init_append(&s, buf, 5); + KUNIT_EXPECT_EQ(test, s.size, 5); + /* Overflowed at the size; an unbounded scan would find more. */ + KUNIT_EXPECT_EQ(test, s.len, 5 + 1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_buffer_left(&s), 0); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hell"); + + /* With no room even for a NUL, @s is overflowed and @buf untouched. */ + seq_buf_init_append(&s, buf, 0); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 0); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); + KUNIT_EXPECT_EQ(test, buf[0], 'h'); +} + static void seq_buf_declare_test(struct kunit *test) { DECLARE_SEQ_BUF(s, 24); @@ -669,6 +737,7 @@ static void seq_buf_terminate_test(struct kunit *test) static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), + KUNIT_CASE(seq_buf_init_append_test), KUNIT_CASE(seq_buf_declare_test), KUNIT_CASE(seq_buf_clear_test), KUNIT_CASE(seq_buf_puts_test), From 63ae65caa98a20191c182b5c9c5d8505c9800584 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:57:00 -0700 Subject: [PATCH 23/29] powerpc/papr_scm: Return the string length from the sysfs show functions perf_stats_show() and flags_show() build their output with a seq_buf and return seq_buf_used(), which may include the trailing NUL byte when the seq_buf has overflowed. Use seq_buf_strlen() instead. As suggested in review, use it as well for flags_show()'s check whether any flag was printed. Build tested ARCH=powerpc ppc64_defconfig with GCC powerpc64-linux-gnu 16.2.0: arch/powerpc/platforms/pseries/papr_scm.o Assisted-by: LLM Reviewed-by: Andy Shevchenko Link: https://patch.msgid.link/20261005155708.1471260-10-kees@kernel.org Signed-off-by: Kees Cook --- arch/powerpc/platforms/pseries/papr_scm.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/powerpc/platforms/pseries/papr_scm.c b/arch/powerpc/platforms/pseries/papr_scm.c index 75da96c08cdd..5c3bf06bb59b 100644 --- a/arch/powerpc/platforms/pseries/papr_scm.c +++ b/arch/powerpc/platforms/pseries/papr_scm.c @@ -1108,7 +1108,7 @@ static ssize_t perf_stats_show(struct device *dev, free_stats: kfree(stats); - return rc ? rc : (ssize_t)seq_buf_used(&s); + return rc ?: (ssize_t)seq_buf_strlen(&s); } static DEVICE_ATTR_ADMIN_RO(perf_stats); @@ -1147,10 +1147,10 @@ static ssize_t flags_show(struct device *dev, if (health & PAPR_PMEM_SCRUBBED_AND_LOCKED) seq_buf_printf(&s, "scrubbed locked "); - if (seq_buf_used(&s)) + if (seq_buf_strlen(&s)) seq_buf_printf(&s, "\n"); - return seq_buf_used(&s); + return seq_buf_strlen(&s); } DEVICE_ATTR_RO(flags); From 9ac219976ecfd0ad9c54050ed14f1da5d197cb69 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:57:01 -0700 Subject: [PATCH 24/29] nvdimm: ndtest: Return the string length from flags_show() flags_show() build their output with a seq_buf and return seq_buf_used(), which may include the trailing NUL byte when the seq_buf has overflowed. Use seq_buf_strlen() instead. The flag names are far shorter than the PAGE_SIZE buffer sysfs provides, so this cannot overflow today. Build tested ARCH=x86_64 with GCC 16.2.0, built out of tree with make M=tools/testing/nvdimm: tools/testing/nvdimm/test/ndtest.o Assisted-by: LLM Reviewed-by: Andy Shevchenko Reviewed-by: Dave Jiang Reviewed-by: Alison Schofield Link: https://patch.msgid.link/20261005155708.1471260-11-kees@kernel.org Signed-off-by: Kees Cook --- tools/testing/nvdimm/test/ndtest.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/testing/nvdimm/test/ndtest.c b/tools/testing/nvdimm/test/ndtest.c index 2051ad5d4882..f097f2992966 100644 --- a/tools/testing/nvdimm/test/ndtest.c +++ b/tools/testing/nvdimm/test/ndtest.c @@ -693,7 +693,7 @@ static ssize_t flags_show(struct device *dev, if (seq_buf_used(&s)) seq_buf_printf(&s, "\n"); - return seq_buf_used(&s); + return seq_buf_strlen(&s); } static DEVICE_ATTR_RO(flags); From e3f8dfafd7d6ef905afd6603b0b57984abd0677b Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Mon, 5 Oct 2026 08:57:02 -0700 Subject: [PATCH 25/29] docs: core-api: Document the seq_buf API The kernel-doc in include/linux/seq_buf.h and lib/seq_buf.c documents the seq_buf interface, but no .rst file pulls either of them in, so none of it reaches the generated documentation. Add the missing kernel-doc for seq_buf_clear() and seq_buf_init(), and a Sequence Buffers section to the kernel API documentation. The static internal helper seq_buf_can_fit() is left out. Additionally fix seq_buf_hex_dump() indentation to avoid the reported Sphinx error: ERROR: Unexpected indentation. WARNING: Block quote ends without a blank line; unexpected unindent. Verified with "make SPHINXDIRS=core-api htmldocs", which rendered happily into core-api/kernel-api.html. Assisted-by: LLM Co-developed-by: Bill Wendling Signed-off-by: Bill Wendling Tested-by: Randy Dunlap Reviewed-by: Randy Dunlap Link: https://patch.msgid.link/20261005155708.1471260-12-kees@kernel.org Signed-off-by: Kees Cook --- Documentation/core-api/kernel-api.rst | 9 +++++++++ include/linux/seq_buf.h | 12 ++++++++++++ lib/seq_buf.c | 13 +++++++------ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/Documentation/core-api/kernel-api.rst b/Documentation/core-api/kernel-api.rst index 4c4a57c1c094..f5a0aedbbb48 100644 --- a/Documentation/core-api/kernel-api.rst +++ b/Documentation/core-api/kernel-api.rst @@ -96,6 +96,15 @@ Error Pointers .. kernel-doc:: include/linux/err.h :internal: +Sequence Buffers +---------------- + +.. kernel-doc:: include/linux/seq_buf.h + :internal: + +.. kernel-doc:: lib/seq_buf.c + :no-identifiers: seq_buf_can_fit + Sorting ------- diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index be979089228f..f006f2654e4c 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -31,6 +31,10 @@ struct seq_buf { .size = SIZE, \ } +/** + * seq_buf_clear - reset the seq_buf to be read / appended from the beginning + * @s: the seq_buf handle + */ static inline void seq_buf_clear(struct seq_buf *s) { s->len = 0; @@ -38,6 +42,14 @@ static inline void seq_buf_clear(struct seq_buf *s) s->buffer[0] = '\0'; } +/** + * seq_buf_init - initialize a seq_buf + * @s: the seq_buf handle + * @buf: pointer to the buffer + * @size: total size of @buf + * + * The contents of the buffer are ignored. + */ static inline void seq_buf_init(struct seq_buf *s, char *buf, unsigned int size) { diff --git a/lib/seq_buf.c b/lib/seq_buf.c index 8da2e9447adf..54b76044e4ba 100644 --- a/lib/seq_buf.c +++ b/lib/seq_buf.c @@ -409,12 +409,13 @@ int seq_buf_to_user(struct seq_buf *s, char __user *ubuf, size_t start, int cnt) * * Function is an analogue of print_hex_dump() and thus has similar interface. * - * linebuf size is maximal length for one line. - * 32 * 3 - maximum bytes per line, each printed into 2 chars + 1 for - * separating space - * 2 - spaces separating hex dump and ASCII representation - * 32 - ASCII representation - * 1 - terminating '\0' + * linebuf size is maximal length for one line:: + * + * 32 * 3 - maximum bytes per line, each printed into 2 chars + 1 for + * separating space + * 2 - spaces separating hex dump and ASCII representation + * 32 - ASCII representation + * 1 - terminating '\0' * * Returns: zero on success, -1 on overflow. */ From 752ae52dcc598a310a35d5c87bb7b10ad5f0c767 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Thu, 17 Sep 2026 14:14:29 -0700 Subject: [PATCH 26/29] coresight: cti: Add const to con_groups allocation type In preparation for making the devm_kmalloc family of allocators type aware, we need to make sure that the returned type from the allocation matches the type of the variable being assigned. (Before, the allocator would always return "void *", which can be implicitly cast to any pointer type.) The assigned type is "const struct attribute_group **", but the converted allocation type would be "struct attribute_group **", which is the same type without the const qualifier. As there is no general way to safely add const qualifiers, take the size from the assignment target instead. No change in allocation size results. Build tested ARCH=arm64 allmodconfig with GCC aarch64-linux-gnu 16.1.0: drivers/hwtracing/coresight/coresight-cti-sysfs.o Assisted-by: LLM coccinelle Reviewed-by: Mike Leach Reviewed-by: Leo Yan Link: https://patch.msgid.link/20260917211428.i.947-kees@kernel.org Signed-off-by: Kees Cook --- drivers/hwtracing/coresight/coresight-cti-sysfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/hwtracing/coresight/coresight-cti-sysfs.c b/drivers/hwtracing/coresight/coresight-cti-sysfs.c index 3fe2c916d228..2ed5d8eb1dda 100644 --- a/drivers/hwtracing/coresight/coresight-cti-sysfs.c +++ b/drivers/hwtracing/coresight/coresight-cti-sysfs.c @@ -1132,7 +1132,7 @@ static int cti_create_cons_groups(struct device *dev, struct cti_device *ctidev) /* nr groups = dynamic + static + NULL terminator */ nr_groups = ctidev->nr_trig_con + CORESIGHT_CTI_STATIC_GROUPS_MAX; ctidev->con_groups = devm_kcalloc(dev, nr_groups, - sizeof(struct attribute_group *), + sizeof(*ctidev->con_groups), GFP_KERNEL); if (!ctidev->con_groups) return -ENOMEM; From ef16259088f99c5997e198561bdcbb89ab70fd0f Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Thu, 17 Sep 2026 14:12:47 -0700 Subject: [PATCH 27/29] extcon: realtek: Remove const from type_c_cfg allocation type In preparation for making the devm_kmalloc family of allocators type aware, we need to make sure that the returned type from the allocation matches the type of the variable being assigned. (Before, the allocator would always return "void *", which can be implicitly cast to any pointer type.) The assigned type is "struct type_c_cfg *", but the converted allocation type would be "const struct type_c_cfg *", as the size was taken from the local "type_c_cfg", which points to const as it comes from of_device_get_match_data(). As there is no general way to remove const qualifiers, take the size from the assignment target instead. No change in allocation size results. Build tested ARCH=x86_64 allmodconfig with GCC 16.2.0: drivers/extcon/extcon-rtk-type-c.o Assisted-by: LLM coccinelle Link: https://patch.msgid.link/20260917211246.i.196-kees@kernel.org Signed-off-by: Kees Cook --- drivers/extcon/extcon-rtk-type-c.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/extcon/extcon-rtk-type-c.c b/drivers/extcon/extcon-rtk-type-c.c index 82b60b927e41..da0b3fd3676e 100644 --- a/drivers/extcon/extcon-rtk-type-c.c +++ b/drivers/extcon/extcon-rtk-type-c.c @@ -1368,7 +1368,8 @@ static int extcon_rtk_type_c_probe(struct platform_device *pdev) goto err; } - type_c->type_c_cfg = devm_kzalloc(dev, sizeof(*type_c_cfg), GFP_KERNEL); + type_c->type_c_cfg = devm_kzalloc(dev, sizeof(*type_c->type_c_cfg), + GFP_KERNEL); if (!type_c->type_c_cfg) return -ENOMEM; From e2cd253cb31bb0da4bcc512e20bfeebf76880891 Mon Sep 17 00:00:00 2001 From: Dennis Chen Date: Wed, 14 Oct 2026 13:58:59 -0400 Subject: [PATCH 28/29] lkdtm: Make UNSET_SMEP built-in-only and unexport native_write_cr4() native_write_cr4 should not be exported to modules. Commit 21953ee5013d ("x86/cpu: Export native_write_cr4() only when CONFIG_LKTDM=m") restricted the export somewhat, but native_write_cr4() is still exposed to all GPL-compatible modules when CONFIG_LKDTM=m. UNSET_SMEP is the only module user of native_write_cr4(). Restrict the test to CONFIG_LKDTM=y and remove the export. When LKDTM is built as a module, report XFAIL for UNSET_SMEP. Suggested-by: Christoph Hellwig Link: https://lore.kernel.org/all/20200420090102.GB24518@infradead.org/ Signed-off-by: Dennis Chen Link: https://patch.msgid.link/20261014175859.30863-1-dechen@redhat.com Signed-off-by: Kees Cook --- arch/x86/kernel/cpu/common.c | 3 --- drivers/misc/lkdtm/bugs.c | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/arch/x86/kernel/cpu/common.c b/arch/x86/kernel/cpu/common.c index c7352827f491..7c1b9e045d5f 100644 --- a/arch/x86/kernel/cpu/common.c +++ b/arch/x86/kernel/cpu/common.c @@ -490,9 +490,6 @@ void __no_profile native_write_cr4(unsigned long val) bits_changed); } } -#if IS_MODULE(CONFIG_LKDTM) -EXPORT_SYMBOL_GPL(native_write_cr4); -#endif void cr4_update_irqsoff(unsigned long set, unsigned long clear) { diff --git a/drivers/misc/lkdtm/bugs.c b/drivers/misc/lkdtm/bugs.c index 3eca2ef64aff..d82c47fb9f03 100644 --- a/drivers/misc/lkdtm/bugs.c +++ b/drivers/misc/lkdtm/bugs.c @@ -676,7 +676,7 @@ static void lkdtm_STACK_GUARD_PAGE_TRAILING(void) static void lkdtm_UNSET_SMEP(void) { -#if IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_UML) +#if IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_UML) && IS_BUILTIN(CONFIG_LKDTM) #define MOV_CR4_DEPTH 64 void (*direct_write_cr4)(unsigned long val); unsigned char *insn; @@ -737,7 +737,7 @@ static void lkdtm_UNSET_SMEP(void) native_write_cr4(cr4); } #else - pr_err("XFAIL: this test is x86_64-only\n"); + pr_err("XFAIL: this test is x86_64-only and requires CONFIG_LKDTM=y\n"); #endif } From 2f70a9b7e9c74b92a85a2584090f0f5c4cbaa4be Mon Sep 17 00:00:00 2001 From: Bill Wendling Date: Tue, 13 Oct 2026 20:31:46 +0000 Subject: [PATCH 29/29] overflow: Match arithmetic in both parts of __builtin_choose_expr The two parts of '__builtin_choose_expr()' had different arithmetic expressions. This patch corrects it so that both parts calculate: COUNT * sizeof(*MEMBER) + __must_be_array(MEMBER) In practice, '__must_be_array' is meant to assert if 'MEMBER' isn't an array and return '0' otherwise. However, symmetry is less prone to subtle errors (and far more satisfying). Signed-off-by: Bill Wendling Link: https://patch.msgid.link/20261013203146.387344-1-morbo@google.com Signed-off-by: Kees Cook --- include/linux/overflow.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/overflow.h b/include/linux/overflow.h index a8cb6319b4fb..d0f04436343e 100644 --- a/include/linux/overflow.h +++ b/include/linux/overflow.h @@ -418,7 +418,7 @@ static __always_inline size_t __must_check size_sub(size_t minuend, size_t subtr #define flex_array_size(p, member, count) \ __builtin_choose_expr(__is_constexpr(count), \ (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \ - size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member))) + size_mul(count, sizeof(*(p)->member)) + __must_be_array((p)->member)) /** * struct_size() - Calculate size of structure with trailing flexible array.