Commit Graph
100 Commits
Author SHA1 Message Date
Kees Cook bcd347f31e coccinelle: kmalloc_obj: Include devm_kmalloc_obj conversion rules
Mirroring the kmalloc -> kmalloc_obj conversion rules, do the same for
devm_kmalloc. The device-managed allocators differ only by taking the
managing "struct device *" as a leading argument, so capture the leading
arguments in an "expression list" metavariable rather than repeating
every pattern.

Signed-off-by: Kees Cook <[email protected]>
Cc: Julia Lawall <[email protected]>
Cc: Nicolas Palix <[email protected]>
Cc: <[email protected]>
2026-11-05 21:55:49 -08:00
Kees Cook 56f8d91973 netdev: Hide the netdev_priv() origin from GCC in netdev_from_priv()
GCC 15.1 and later can compute an object size of 0 for a pointer that
container_of() derives from a pointer into a __counted_by flexible array
member[1]; Clang gets it right. netdev_from_priv() does this with struct
net_device's "priv" array, so when GCC can see that its argument came
from netdev_priv(), FORTIFY_SOURCE sees a zero-sized net_device. Since
commit 9027497a25 ("team: use netdev_from_priv()"), adding a port of
another type to a team device can then fail the memcpy() to
"dev->broadcast" in team_setup_by_port(), which GCC sees through after
inlining team_port_add() into team_add_slave():

  memcpy: detected buffer overflow: 4 byte write of buffer size 0
  ...
  kernel BUG at lib/string_helpers.c:1044!
  ...
  Call Trace:
   <TASK>
   team_add_slave.cold+0x88/0x201
   do_set_master+0x11c/0x180
   do_setlink.isra.0+0x3a4/0x1410

Whether GCC inlines that far depends on the architecture and the
configuration. It does on ppc64le, where this was reported, and on
x86_64 with defconfig plus hardening.config or with Debian's
configuration, but not with allmodconfig.

Hide where "priv" came from with OPTIMIZER_HIDE_VAR(), so GCC sees a
net_device of unknown size whose members have their declared sizes. (An
"unknown" size is considered uncheckable by FORTIFY.)  FORTIFY still
bounds writes to members; only the whole-object size becomes unknown,
as it already is for any net_device pointer GCC can't trace to its
allocation. In an extracted PoC, the __builtin_dynamic_object_size()
of "dev->broadcast" for the two types FORTIFY sees, before and after
this patch:

                                   GCC 16.2.0      Clang 22 and 24
                                 before   after
  plain pointer, whole object   unknown  unknown        44
  container_of(), whole object        0  unknown        44
  container_of(), member              0       32        32

In addition to getting the bogus "0" fixed in GCC, I'll be following up
to solve the whole-object visiblity disparity as well.

Build tested with GCC 16.2.0: ARCH=x86_64 defconfig with hardening.config,
CONFIG_NET_TEAM=y, and CONFIG_NET_IPGRE=y; ARCH=arm64 defconfig with
hardening.config, CONFIG_NET_TEAM=y, CONFIG_PPP=y, and CONFIG_NET_AIROHA=m;
and drivers/net/team/, drivers/net/ppp/, and drivers/net/ethernet/airoha/
in ARCH=x86_64 allmodconfig. Under QEMU, the x86_64 kernel hits the BUG
above when adding the GRE fallback device "gre0" as a port of a new team
device without this patch, and adds it with the patch.

Reported-by: Yeswanth Krishna Tellakula <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Fixes: 9027497a25 ("team: use netdev_from_priv()")
Cc: [email protected]
Link: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127875 [1]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2026-10-20 12:19:33 -07:00
Kees Cook c57fbbe42e ipc, msg: Account msg_msg allocations with GFP_KERNEL_ACCOUNT again
Since commit 734bbc1c97 ("ipc, msg: Use dedicated slab buckets for
alloc_msg()"), alloc_msg() allocates with GFP_KERNEL, and a msg_msg is
accounted only through SLAB_ACCOUNT on its bucket caches. With
CONFIG_SLAB_BUCKETS=n, kmem_buckets_create() creates no caches and
kmem_buckets_alloc() is a GFP_KERNEL kmalloc() from the general caches,
which do not account it; the same happens when kmem_buckets_create()
fails. Either way, the allocation is not charged to the sender's memory
cgroup.

Allocate with GFP_KERNEL_ACCOUNT again, as before that commit, so the
allocation is charged whichever cache serves it.

Build tested ARCH=x86_64 defconfig with GCC 16.2.0, with
CONFIG_SLAB_BUCKETS as y and n.

Fixes: 734bbc1c97 ("ipc, msg: Use dedicated slab buckets for alloc_msg()")
Cc: [email protected]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Vlastimil Babka (SUSE) <[email protected]>
Reviewed-by: Harry Yoo (Meta) <[email protected]>
Reviewed-by: Pedro Falcato <[email protected]>
Signed-off-by: Harry Yoo (Meta) <[email protected]>
2026-10-16 15:52:26 +01:00
Kees Cook 7762562c92 efi/libstub: Disable kernel stack erasing in the common flags
Every architecture that builds the stub now adds $(DISABLE_KSTACK_ERASE)
to its own flags, so add it once to the flags they share instead.

Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Nathan Chancellor <[email protected]>
Signed-off-by: Ard Biesheuvel <[email protected]>
2026-10-15 13:53:04 +02:00
Kees Cook 7aea1470a4 efi/libstub: Build the x86 stub from KBUILD_CFLAGS
The x86 stub replaces KBUILD_CFLAGS with a short list of its own, so new
kernel-wide compiler options go missing, unless explicitly remembered
or when lacking them breaks the build, e.g. commit 5ff8ad3909
("kbuild: Add '-fms-extensions' to areas with dedicated CFLAGS")
did. Today, several still go missing that are provided to non-x86
stub builds, e.g. -ftrivial-auto-var-init, -fzero-call-used-regs,
-fstrict-flex-arrays=3, and the various kernel's warnings.

Flip the x86 option logic to match the other architectures. Since the
x86 stub is linked into the decompressor rather than the kernel proper,
remove the kernel code model, the i386 register calling convention,
and the kernel's reduced stack alignment, along with the retpoline and
return thunks and the call padding, which only the kernel provides,
and disable kernel stack erasing as the other architectures do. The
existing -mcmodel=small, -march=i386, and -fPIC still get overrides.
Build with -fcf-protection=none, since nothing enables IBT while the
stub runs: the firmware applies forward-edge CFI only to images that
advertise it, which bzImage does not.

New flags that change code generation or semantics in a plain x86_64
defconfig hardening.config stub:

Hardening:
	-ftrivial-auto-var-init=zero
	-fzero-init-padding-bits=all
	-fstrict-flex-arrays=3
	-fno-strict-overflow
	-fno-delete-null-pointer-checks
	-fno-allow-store-data-races
	-fno-jump-tables (from the default IBT config)

C semantics:
	-funsigned-char
	-fno-common

x86 code generation:
	-mno-sse2 -mno-3dnow -mno-avx -mno-sse4a
	 (stub already added -mno-mmx -mno-sse)
	-mno-80387 -mno-fp-ret-in-387 -mskip-rax-setup
	-falign-jumps=1 -falign-loops=1 -fmin-function-alignment=16
	-fomit-frame-pointer -fconserve-stack
	-fno-stack-clash-protection -fno-stack-check -fno-builtin-wcslen

Warnings (lots and lots, but notably):
	-Wall -Wextra -Wundef -Wmissing-prototypes
	-Wvla-larger-than=1 -Wimplicit-fallthrough=5

Present but with no effect, because the stub's later flags override them:
	-O2, overridden by -Os
	-fstack-protector-* flags, overridden by -fno-stack-protector
	-fno-PIE, overridden by -fPIC
	-fcf-protection=branch, overridden by -fcf-protection=none
	the stack-erase plugin, loaded and then disabled

Build tested ARCH=x86_64 defconfig hardening.config, plus retpolines,
return thunks, call depth tracking, IBT, GCC plugins, and EFI mixed
mode, with GCC 16.2.0 and Clang 24.0.0git, and ARCH=i386 defconfig
hardening.config with GCC 16.2.0. Each booted through the EFI stub to
userspace under QEMU with x64 and IA32 OVMF, the latter in mixed mode
for x86_64.

Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Nathan Chancellor <[email protected]>
Signed-off-by: Ard Biesheuvel <[email protected]>
2026-10-15 13:52:59 +02:00
Kees Cook d4d1127329 efi/libstub: Declare the x86 stub's assembly entry points
efi_stub_entry() and efi_handover_entry() are entered from efi-mixed.S
and, through the efi32_stub_entry() and efi64_stub_entry() aliases, by
boot loaders using the EFI handover protocol, but have no prototypes.
Declare them in x86-stub.h, as asmlinkage, so that the stub can be built
with the kernel's -Wmissing-prototypes.

Signed-off-by: Kees Cook <[email protected]>
[ardb: fix i386 GCC build by scoping to CONFIG_EFI_MIXED=y]
Signed-off-by: Ard Biesheuvel <[email protected]>
2026-10-15 13:52:56 +02:00
Kees Cook 655668f0ca mm/slab: Mark the kmem_buckets_create() context as a Context: section
kmem_buckets_create() had the same sentence about calling context as
kmem_cache_create(), but lacked the "Context:" prefix, so kernel-doc
rendered in the body instead of as a "context" section.

Give it the missing prefix. Additionally fix the "a interrupt" typo
__kmem_cache_create_args() had.

Fixes: b32801d125 ("mm/slab: Introduce kmem_buckets_create() and family")
Reviewed-by: Harry Yoo (Meta) <[email protected]>
Acked-by: Pedro Falcato <[email protected]>
Reviewed-by: Hao Li <[email protected]>
Acked-by: Vlastimil Babka (SUSE) <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Vlastimil Babka (SUSE) <[email protected]>
2026-10-14 10:11:18 +02:00
Kees Cook 41d1119e2f x86/kcfi: Emit the FineIBT paranoid "cs" prefix as a byte
The "cs" prefix on the LEA in the FineIBT paranoid caller template is
padding: it places the LEA's 0xf0 immediate byte where it doubles as the
LOCK prefix that makes the failing Jcc raise #UD. GNU as warns about it
in every CONFIG_FINEIBT=y build:

  Warning: segment override on `lea' is ineffectual

Clang's integrated assembler does not warn, and both assemble the same
bytes. Emit the prefix with ".byte 0x2e" to silence GNU as.

Build tested ARCH=x86_64 defconfig with CONFIG_CFI=y, with GCC 17.0.0
(experimental, with the kCFI series) and GNU as 2.47, and with Clang
24.0.0git: GNU as no longer warns, and the template assembles to the
same bytes as before with both. Under QEMU with cfi=fineibt,paranoid,
the paranoid caller check catches LKDTM's CFI_FORWARD_PROTO with both.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Link: https://patch.msgid.link/[email protected]
2026-10-12 11:47:35 +02:00
Kees Cook 4505a262de x86/kcfi: Decode the kCFI check from the trap address
Since commit b2250d63e6 ("x86/kcfi: Optimize call sequence"), a
CONFIG_FINEIBT=y kernel running in kCFI mode rewrites each kCFI call
site at boot so that a failed check traps on the 0xd6 byte of
"test $0xd6, %al", one byte past where the compiler's "ud2" was.
handle_cfi_failure() steps "addr" back one byte to find the trap in
.kcfi_traps, but decode_cfi_insn() still decodes from regs->ip, so it
reads each instruction starting at its second byte.
"movl $-<id>, %r10d" then decodes as "movl $-<id>, %edx", so the
reported type is right by accident, but "addl -15(%r11), %r10d" decodes
as "addl -15(%rbx), %edx", so the reported target is whatever %rbx holds:

  CFI failure at lkdtm_indirect_call+0x16/0x20 (target: 0x12; expected type: 0xc79a2d1b)

Pass the adjusted address to decode_cfi_insn() and decode from it.

Tested ARCH=x86_64 defconfig with CONFIG_CFI=y and CONFIG_LKDTM=y under
QEMU, with LKDTM's CFI_FORWARD_PROTO and both Clang 24.0.0git and GCC
17.0.0 (experimental, with the kCFI series). With CONFIG_FINEIBT=y in
kCFI mode, the report gives %rbx as the target without this change, and
the expected lkdtm_increment_int() with it. With cfi=fineibt, with
cfi=fineibt,paranoid, and with CONFIG_FINEIBT=n, it gives
lkdtm_increment_int() both with and without this change.

Fixes: b2250d63e6 ("x86/kcfi: Optimize call sequence")
Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Link: https://patch.msgid.link/[email protected]
2026-10-12 11:47:32 +02:00
Kees Cook e3f8dfafd7 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 <[email protected]>
Signed-off-by: Bill Wendling <[email protected]>
Tested-by: Randy Dunlap <[email protected]>
Reviewed-by: Randy Dunlap <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:30 -07:00
Kees Cook 9ac219976e 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 <[email protected]>
Reviewed-by: Dave Jiang <[email protected]>
Reviewed-by: Alison Schofield <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:30 -07:00
Kees Cook 63ae65caa9 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:30 -07:00
Kees Cook c8cd1725d2 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 483a1bb0b6 ("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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook 88c652df02 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook 8d1478bfd6 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook ea5666e567 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook 505a4aeea2 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook cc9d25b451 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/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook b7e688b563 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: 32e0f607ac ("tracing: Add trace_seq_pop() and seq_buf_pop()")
Assisted-by: LLM
Reviewed-by: Andy Shevchenko <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook a09fb76483 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: 96928d9032 ("seq_buf: Add seq_buf_do_printk() helper")
Assisted-by: LLM
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-11 21:57:29 -07:00
Kees Cook e160c4481f .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 <[email protected]>
2026-10-11 21:57:26 -07:00
Kees Cook ae5f6044c4 kbuild: Mark the initcall ordering recipe as recursive
generate_initcall_order.pl, which orders initcalls for Clang LTO, forks
a child per input file, up to the job count scripts/jobserver-exec
passes it in PARALLELISM. It used to run from link-vmlinux.sh, which
the top-level Makefile invokes as a recursive recipe, but
commit 5d45950dfb ("kbuild: move vmlinux.o link to
scripts/Makefile.vmlinux_o") moved it into a recipe without "+".

GNU Make passes the jobserver pipe only to recipes it treats as
recursive, and the make 4.3 in CentOS Stream 9 also hides it in
sub-makes (a backport of the fix for GNU Make bug 58232), so
jobserver-exec cannot open it and prints:

  WARNING: Unable to reopen jobserver read-side pipe: FileNotFoundError(2, 'No such file or directory')

PARALLELISM is then left unset, and the script caps its children at the
number of online CPUs instead of the free job slots.

Mark the recipe as recursive again (this makes "make -n" runs the script
again too, as it did from link-vmlinux.sh). Masahiro posted the same
change and withdrew it because the script was given only vmlinux.a, and
so never ran more than one child [1]. But on arm64, LoongArch, and RISC-V
with CONFIG_EFI_STUB, KBUILD_VMLINUX_LIBS also gives it the EFI stub's
lib.a. Either way, the warning is silenced.

Tested ARCH=x86_64 defconfig with CONFIG_LTO_CLANG_THIN=y, LLVM=1
(Clang 24.0.0git), and GNU Make 4.3 plus CentOS Stream 9's
make-4.3-cloexec.patch.

Fixes: 5d45950dfb ("kbuild: move vmlinux.o link to scripts/Makefile.vmlinux_o")
Link: https://lore.kernel.org/all/CAK7LNARCM=rUm8mA8GRQ7ufeyfneGf4OEvHmESKt=zuxs2KrHw@mail.gmail.com/ [1]
Assisted-by: LLM
Reviewed-by: Nicolas Schier <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Paul E. McKenney <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Nathan Chancellor <[email protected]>
2026-10-11 01:20:05 +01:00
Kees Cook 0d4d70da34 kbuild: Mark the gzip recipes as recursive
Since commit 48ebe1cbbe ("kbuild: compress the kernel with pigz if
available"), cmd_gzip runs pigz through scripts/jobserver-exec, which
takes the job slots make has free. GNU Make passes the jobserver pipe
only to recipes it treats as recursive, but leaves --jobserver-auth in
MAKEFLAGS for all of them. The make 4.3 in CentOS Stream 9 also hides
the pipe in sub-makes (a backport of the fix for GNU Make bug 58232), so
jobserver-exec cannot open it, runs pigz on one thread, and prints:

  WARNING: Unable to reopen jobserver read-side pipe: FileNotFoundError(2, 'No such file or directory')

Mark every recipe that can run cmd_gzip as recursive with "+", as
commit ecab4115c4 ("kbuild: mark `rustc` (and others) invocations as
recursive") did for rustc. Besides the $(call if_changed,gzip) rules,
this covers those that choose gzip through a variable: the built-in
initramfs in usr/Makefile (which rcutorture's kvm.sh builds), the EFI
zboot image, and the arm, csky, and mips compressed images. As with
rustc, "make -n" now runs these recipes, including those that choose
through a variable when they select another compressor. Also update the
gzip entry in Documentation/kbuild/makefiles.rst, as suggested in
review.

Tested with GNU Make 4.3 plus CentOS Stream 9's make-4.3-cloexec.patch,
GCC 16.2.0, and -j64, on ARCH=x86_64, arm64, and arm defconfig, and
ARCH=x86_64 defconfig with a built-in initramfs: none of them prints the
warning, and pigz gets the free job slots (-p 54, 64, and 50 for the
kernel image). Without this change, the x86_64 builds print it for the
kernel image and for the initramfs.

Reported-by: Paul E. McKenney <[email protected]>
Closes: https://lore.kernel.org/all/0ddb5e5e-f801-444c-aa98-0cfe814a3026@paulmck-laptop/
Fixes: 48ebe1cbbe ("kbuild: compress the kernel with pigz if available")
Assisted-by: LLM
Reviewed-by: Nicolas Schier <[email protected]>
Acked-by: Lorenzo Stoakes (ARM) <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Paul E. McKenney <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Nathan Chancellor <[email protected]>
2026-10-11 01:20:04 +01:00
Kees Cook e320083405 selftests/seccomp: Split fork_and_close into clone and close tests
fork_and_close checked three things against one listener: that a
restarted clone3() creates exactly one child, that a restarted close()
releases its descriptor, and that a supervisor error reaches the caller
after a restart. A three-pass loop chose what each pass did for each
variant, and a failure in the first check kept the others from running.

Split it into notification_restart.clone and notification_restart.close,
each with one mediated syscall, one signal, and one expected result per
variant. They share helpers that fork the filtered child, receive its
listener, and interrupt its notification. notification_restart_child()
now uses the same fork and report helpers, and the filter flags are
computed in one place. Drop the supervisor error check, which
failed_receive already covers.

Tests run on ARCH=x86_64 defconfig with CONFIG_PROVE_LOCKING=y,
CONFIG_DEBUG_ATOMIC_SLEEP=y, and CONFIG_DEBUG_LIST=y under QEMU, built
with GCC 16.2.0: seccomp_bpf passes 137/137 with 5 skips, and the 28
notification_restart tests pass in 25 of 25 runs at -smp 2 and -smp 4.
On v7.3-rc2 the restart and both variants fail and the others pass.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
2026-10-06 02:02:49 -07:00
Kees Cook 9e9bd8f8ac seccomp: Document RESTART_BEFORE_RECV and O_PATH addfd
Describe SECCOMP_FILTER_FLAG_RESTART_BEFORE_RECV in the UAPI header, as
SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV is described above it, and say in
the documentation that supervisors must tolerate ENOENT from
SECCOMP_IOCTL_NOTIF_RECV, which the flag makes routine. Note at the
fget_raw() call that O_PATH files are allowed on purpose.

Build tested ARCH=x86_64 defconfig (kernel/seccomp.o and headers) with
GCC 16.2.0, and SPHINXDIRS=userspace-api htmldocs.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
2026-10-06 01:58:47 -07:00
Kees Cook 29a86e8818 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 <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-05 17:50:53 -07:00
Kees Cook ff566742e9 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) <[email protected]>
Reviewed-by: Zi Yan <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-10-05 17:50:52 -07:00
Kees Cook 0f82b48209 kunit/stackinit: Clean up XFAIL under instrumentation
Commit 8530ea3c9b ("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 <[email protected]>
2026-10-05 02:41:07 -07:00
Kees Cook f59db7fb11 docs: Makefile: Add a testdocs target for the documentation unit tests
tools/unittests/run.py discovers and runs the unit tests there (which
are primarily documentation tools), but nothing in the build calls it,
so the tests are only run by whoever remembers that the script is there.

Give it a target, next to the other checks that need no Sphinx. The name
ends in "docs", so it matches the "%docs" pattern already in
no-dot-config-targets and runs without a configured tree, and it sets
PYTHONPYCACHEPREFIX as the other Python targets here do, to keep
__pycache__ directories out of the source tree.

  $ make testdocs
  ...
  Ran 121 tests

with "make dochelp" listing it between refcheckdocs and cleandocs.

Tested with GNU Make 4.4.1 and Python 3.14.7, on a tree with no .config,
where it ran 121 tests and left no __pycache__ behind.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Randy Dunlap <[email protected]>
Acked-by: Randy Dunlap <[email protected]>
Tested-by: Nicolas Schier <[email protected]>
Reviewed-by: Nicolas Schier <[email protected]>
Reviewed-by: Breno Leitao <[email protected]>
Signed-off-by: Jonathan Corbet <[email protected]>
Message-ID: <[email protected]>
2026-09-26 09:27:05 -06:00
Kees Cook cfcc465018 kconfig: Add "ld-option-str"
Add the linker counterpart to $(cc-option-str), sharing a $(ld-probe)
with $(ld-option) the way the compiler macros share $(cc-probe). Like
$(cc-option-str), it can now be used as:

	config LD_OPT_FOO
		def_string "$(ld-option-str,--new-option,--old-option)"

An omitted fallback expands to the empty string.

Build tested ARCH=x86_64 defconfig with GCC 16.2.0, and checked against
GNU ld 2.47.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Julian Braha <[email protected]>
Reviewed-by: Julian Braha <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Nathan Chancellor <[email protected]>
2026-09-24 11:37:05 -04:00
Kees Cook 889a621272 kconfig: Replace "cc-option-bit" with "cc-option-str"
$(cc-option-bit) returns the flag it was given when the compiler accepts
it, and an empty string otherwise. It was originally only used
internally for machine bit flags, but it is generally useful[1].

Rename it to $(cc-option-str), which says what it returns rather than
what it was first used for, and extract the probe logic from the existing
$(cc-option) macro to reuse it. Additionally add support for an optional
fallback, much like the Kbuild cc-option macro. This can be used as:

	config CC_OPT_FOO
		def_string "$(cc-option-str,-fnew-option,-fold-option)"

If the fallback is omitted, it is just an empty string.

Build tested ARCH=x86_64 defconfig with GCC 16.2.0.

Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Julian Braha <[email protected]>
Reviewed-by: Julian Braha <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Nathan Chancellor <[email protected]>
2026-09-24 11:37:05 -04:00
Kees Cook 651fb291c4 kconfig: Add "def_string", "def_int" and "def_hex"
Kconfig has offered "def_bool" and "def_tristate" as a shorthand for a
type definition plus a default since before the git era, but has never
offered the equivalent for the other three types. Conor Dooley ran into
this gap[1] when fixing a symbol that had been given the wrong type:

  Unfortunately, there is no such thing as "def_string", but in this
  case we can use "default" to propagate the value of ...

Nothing in the grammar requires the restriction. The rule that consumes
a default is already type agnostic. Add the three missing types. No
changes are needed to existing diagnostics. E.g. declaring a symbol
"bool" and then assigning it with "def_string" still reports

  warning: ignoring type redefinition of 'CONFLICT' from 'bool' to 'string'

Added tests for the types.

Build tested ARCH=x86_64 with GCC 16.2.0. Tests pass with "make testconfig".

Link: https://lore.kernel.org/all/[email protected]/ [1]
Assisted-by: LLM
Signed-off-by: Kees Cook <[email protected]>
Tested-by: Julian Braha <[email protected]>
Reviewed-by: Julian Braha <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Nathan Chancellor <[email protected]>
2026-09-24 11:37:05 -04:00
Kees Cook 6e72cefa7a 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/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-09-21 21:26:11 -07:00
Kees Cook b9f13e51ad 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/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-09-21 21:26:11 -07:00
Kees Cook 67beeb5621 randstruct: fix container_of() false positives after __mptr removal
Commit f9e7a75648 ("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: f9e7a75648 ("container_of: remove local __mptr variable")
Assisted-by: Claude:claude-opus-5[1m]
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-09-21 21:26:11 -07:00
Kees Cook 90feea391c drm/amd/display: Fix harmless type mismatch in allocation
While converting to kmalloc_obj() API, a type assignment mismatch was
found between the desired struct dcn42_resource_pool and the allocated
struct dcn401_resource_pool. Fix the type (it is harmless: the objects
have the same contents and size).

Signed-off-by: Kees Cook <[email protected]>
---
Cc: Harry Wentland <[email protected]>
Cc: Leo Li <[email protected]>
Cc: Rodrigo Siqueira <[email protected]>
Cc: Alex Deucher <[email protected]>
Cc: "Christian König" <[email protected]>
Cc: David Airlie <[email protected]>
Cc: Simona Vetter <[email protected]>
Cc: Dan Wheeler <[email protected]>
Cc: Roman Li <[email protected]>
Cc: Ovidiu Bunea <[email protected]>
Cc: Charlene Liu <[email protected]>
Cc: Leo Chen <[email protected]>
Cc: Ivan Lipski <[email protected]>
Cc: Gaghik Khachatrian <[email protected]>
Cc: <[email protected]>
Cc: <[email protected]>
2026-09-04 09:44:34 -07:00
Kees Cook 079a028d63 string: Remove strncpy() from the kernel
strncpy() has been a persistent source of bugs due to its ambiguous
intended usage and frequently counter-intuitive semantics: it may not
NUL-terminate the destination, and it unconditionally zero-pads to the
full length, which isn't always needed. All former callers have been
migrated[1] to:

  - strscpy()        for NUL-terminated destinations
  - strscpy_pad()    for NUL-terminated destinations needing zero-padding
  - strtomem_pad()   for non-NUL-terminated fixed-width fields
  - memcpy_and_pad() for bounded copies with explicit padding
  - memcpy()         for known-length copies

Remove the generic implementation, its declaration, the FORTIFY_SOURCE
wrapper, and associated tests.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:39:31 -07:00
Kees Cook 58c4ce8cd6 xtensa: Remove arch-specific strncpy() implementation
strncpy() has no remaining callers in the kernel[1]. Remove the
xtensa-specific inline assembly implementation and __HAVE_ARCH_STRNCPY
define, falling back to the generic version in lib/string.c.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:37:13 -07:00
Kees Cook dfe05fcca8 x86: Remove arch-specific strncpy() implementation
strncpy() has no remaining callers in the kernel[1]. Remove the
x86-32-specific inline assembly implementation and __HAVE_ARCH_STRNCPY
define, falling back to the generic version in lib/string.c.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:37:13 -07:00
Kees Cook 7eda356658 powerpc: Remove arch-specific strncpy() implementation
strncpy() has no remaining callers in the kernel[1]. Remove the
powerpc-specific assembly implementation from both the kernel
(arch/powerpc/lib/string.S) and the boot wrapper
(arch/powerpc/boot/string.S), along with the __HAVE_ARCH_STRNCPY
define and declaration, falling back to the generic version in
lib/string.c.

The boot wrapper's strncpy had no callers in arch/powerpc/boot/.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:37:13 -07:00
Kees Cook ad3242a9ac m68k: Remove arch-specific strncpy() implementation
strncpy() has no remaining callers in the kernel[1]. Remove the
m68k-specific inline assembly implementation and __HAVE_ARCH_STRNCPY
define, falling back to the generic version in lib/string.c.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:37:12 -07:00
Kees Cook 4cb5e246e6 alpha: Remove arch-specific strncpy() implementation
strncpy() has no remaining callers in the kernel[1]. Remove the
alpha-specific assembly implementation and __HAVE_ARCH_STRNCPY define,
falling back to the generic version in lib/string.c.

The __stxncpy helper (stxncpy.S/ev6-stxncpy.S) is retained as it is
still used by strncat.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-06-18 16:37:12 -07:00
Kees Cook 905c559e51 gcc-plugins: Always define CONST_CAST_GIMPLE and CONST_CAST_TREE
For gcc-16, the CONST_CAST macro family was removed. Add back what
we were using in gcc-common.h, as they are simple wrappers.

See GCC commits:
  c3d96ff9e916c02584aa081f03ab999292efbb50
  458c7926d48959abcb2c1adaa22458e27459a551

Suggested-by: Ingo Saitz <[email protected]>
Link: https://lore.kernel.org/lkml/[email protected]
Fixes: 6b90bd4ba4 ("GCC plugin infrastructure")
Tested-by: Ivan Bulatovic <[email protected]>
Tested-by: Christopher Cradock <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
2026-05-14 09:24:32 -07:00
Kees Cook 74a9bb761a libbpf: Use strscpy() in kernel code for skel_map_create()
Linux has deprecated[1] strncpy(), and the use in skel_map_create()
is best replaced with strscpy(). Since we still need to build this
file in userspace, leave the strncpy() in place in that case. This
is the last use of strncpy() in the kernel.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Alexei Starovoitov <[email protected]>
2026-05-13 10:52:32 -07:00
Kees Cook 6522fe5c1b um: Disable GCOV_PROFILE_ALL on 32-bit UML with Clang 20/21
Clang 20 and 21 miscompute __builtin_object_size() when -fprofile-arcs
is active on 32-bit UML targets, which passes incorrect object size
calculations for local variables through always_inline copy_to_user()
and check_copy_size(), causing spurious compile-time errors:

  include/linux/ucopysize.h:52:4: error: call to '__bad_copy_from' declared with 'error' attribute: copy source size is too small

The regression was introduced in LLVM commit 02b8ee281947 ("[llvm]
Improve llvm.objectsize computation by computing GEP, alloca and malloc
parameters bound"), which shipped in Clang 20. It was fixed in LLVM
by commit 45b697e610fd ("[MemoryBuiltins] Consider index type size
when aggregating gep offsets"), which was backported to the LLVM 22.x
release branch.

The bug requires 32-bit UML + GCOV_PROFILE_ALL (which uses -fprofile-arcs),
though the exact trigger depends on optimizer decisions influenced by other
enabled configs.

Prevent the bad combination by disabling UML's ARCH_HAS_GCOV_PROFILE_ALL
on 32-bit when using Clang 20.x or 21.x.

Reported-by: kernel test robot <[email protected]>
Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
Suggested-by: Nathan Chancellor <[email protected]>
Assisted-by: Claude:claude-opus-4-6[1m]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Johannes Berg <[email protected]>
2026-04-10 09:28:59 +02:00
Kees Cook cf2f06f715 lkdtm/fortify: Drop unneeded FORTIFY_STR_OBJECT test
The str* family of fortified functions all use member-sized limits
for a while now, so the FORTIFY_STR_OBJECT test is redundant to
FORTIFY_STR_MEMBER. While here, replace the strncpy() use with strscpy(),
as strncpy() is being removed.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-03-31 16:53:47 -07:00
Kees Cook 00247cbf17 refcount: Remove unused __signed_wrap function annotations
With CONFIG_UBSAN_INTEGER_WRAP being replaced by Overflow Behavior
Types, remove the __signed_wrap function annotation as it is already
unused, and any future work here will use OBT annotations instead.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-03-31 14:41:56 -07:00
Kees Cook 665fb6a643 scsi: target: Replace strncpy() with strscpy() in VPD dump functions
Replace the deprecated[1] strncpy() with strscpy() in
transport_dump_vpd_proto_id(), transport_dump_vpd_assoc(),
transport_dump_vpd_ident_type(), and transport_dump_vpd_ident().

All four functions follow the same pattern: a local
buf[VPD_TMP_BUF_SIZE] (254 bytes) is zeroed with memset(), populated
via sprintf()/snprintf() (always NUL-terminated), then conditionally
copied to p_buf with strncpy(). The p_buf destination is used as a
C string by all callers in target_core_configfs.c: strlen(buf) and
sprintf(page+len, "%s", buf) to build sysfs output.

NUL-padding is not required: callers in target_core_configfs.c
pre-zero p_buf with memset() or initializer before calling these
functions, and consume p_buf only as a NUL-terminated C string via
strlen() and "%s", never exposing trailing bytes.

No behavioral change: the source buf is always NUL-terminated and
shorter than VPD_TMP_BUF_SIZE, so strscpy() produces identical output.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Martin K. Petersen <[email protected]>
2026-03-27 16:32:44 -04:00
Kees Cook 8aae2da610 um: Replace strncpy() with strnlen()+memcpy_and_pad() in strncpy_chunk_from_user()
Replace the deprecated[1] strncpy() with strnlen() on the source
followed by memcpy_and_pad().

This function is a chunk callback for UML's strncpy_from_user()
implementation, called by buffer_op() to process userspace memory one
page at a time. The source is a kernel-mapped userspace address that
is not guaranteed to be NUL-terminated; "len" bounds how many bytes
to read from it.

By measuring the source string length first with strnlen(), we avoid
reading past the NUL terminator in the source. memcpy_and_pad() then
copies the string content and zero-fills the remainder of the chunk,
preserving the original strncpy() behavior exactly: copy up to the
first NUL, then pad with zeros to the full length.

strtomem_pad() would be the idiomatic helper for this strnlen() +
memcpy_and_pad() pattern, but it requires a compile-time-determinable
destination size (via ARRAY_SIZE()). Here the destination is a char *
into a caller-provided buffer and the chunk length is a runtime value,
so the explicit two-step is necessary.

No behavioral change: the same bytes are written to the destination
(string content followed by zero padding), the pointer advances by
the same amount, and the NUL-found return condition is unchanged.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Johannes Berg <[email protected]>
2026-03-27 08:21:09 +01:00
Kees Cook 3f21614c20 wifi: mac80211: Replace strncpy() with strscpy_pad() in drv_switch_vif_chanctx tracepoint
Replace the deprecated[1] strncpy() with strscpy_pad() for copying the
interface name into a tracepoint entry.

The source "sdata->name" is a NUL-terminated char[IFNAMSIZ] buffer
populated via NUL-guaranteeing paths: strscpy() in ieee80211_if_add(),
snprintf() in ieee80211_add_virtual_monitor(), or memcpy() from
ndev->name in ieee80211_if_add() and netdev_notify()
(net/mac80211/iface.c). In the memcpy() cases, the source ndev->name
is itself always NUL-terminated (populated via snprintf() or strscpy()
in __dev_alloc_name() and dev_prep_valid_name() in net/core/dev.c).

The destination "local_vifs[i].vif.vif_name" is a char[IFNAMSIZ] field
in struct trace_vif_entry, stored in a __dynamic_array within the trace
ring buffer. Since ring buffer entries are not zeroed on allocation,
strscpy_pad() is used to zero-fill trailing bytes and prevent exposing
stale ring buffer contents to userspace readers of tracefs.

No behavioral change: since interface names are always at most 15
characters plus a NUL terminator, strscpy_pad() with size IFNAMSIZ (16)
produces identical output to the original strncpy().

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Johannes Berg <[email protected]>
2026-03-24 16:29:32 +01:00
Kees Cook 97f7d3f9c9 ACPICA: Replace strncpy() with strscpy_pad() in acpi_ut_safe_strncpy()
Replace the deprecated[1] strncpy() with strscpy_pad() in
acpi_ut_safe_strncpy().

The function is a "safe strncpy" wrapper that does
strncpy(dest, source, dest_size) followed by manual NUL-termination
at dest[dest_size - 1]. strscpy_pad() is a direct replacement: it
NUL-terminates, zero-pads the remainder, and the manual termination
is no longer needed.

All callers pass NUL-terminated source strings (C string literals,
__FILE__ via ACPI_MODULE_NAME, or user-provided filenames that have
already been validated). The destinations are fixed-size char arrays
in ACPICA internal structures (allocation->module, aml_op_name,
acpi_gbl_db_debug_filename), all consumed as C strings.

No behavioral change: strscpy_pad() produces identical output to
strncpy() + manual NUL-termination for NUL-terminated sources that
are shorter than dest_size. For sources longer than dest_size,
strncpy() wrote dest_size non-NUL bytes then the manual termination
overwrote the last byte with NUL; strscpy_pad() writes dest_size-1
bytes plus NUL: same result.

Link: https://github.com/KSPP/linux/issues/90 [1]
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Rafael J. Wysocki <[email protected]>
2026-03-23 18:32:34 +01:00
Kees Cook c2d466b9fe block: partitions: Replace pp_buf with struct seq_buf
In preparation for removing the strlcat API[1], replace the char *pp_buf
with a struct seq_buf, which tracks the current write position and
remaining space internally. This allows for:

- Direct use of seq_buf_printf() in place of snprintf()+strlcat()
  pairs, eliminating local tmp buffers throughout.
- Adjacent strlcat() calls that build strings piece-by-piece
  (e.g., strlcat("["); strlcat(name); strlcat("]")) to be collapsed
  into single seq_buf_printf() calls.
- Simpler call sites: seq_buf_puts() takes only the buffer and string,
  with no need to pass PAGE_SIZE at every call.

The backing buffer allocation is unchanged (__get_free_page), and the
output path uses seq_buf_str() to NUL-terminate before passing to
printk().

Link: https://github.com/KSPP/linux/issues/370 [1]
Cc: Andy Shevchenko <[email protected]>
Cc: Josh Law <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Josh Law <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jens Axboe <[email protected]>
2026-03-21 08:27:08 -06:00
Kees Cook 1c7bbaeed1 coccinelle: kmalloc_obj: Remove default GFP_KERNEL arg
Remove any GFP_KERNEL arguments found in the new kmalloc_obj-family
helpers. This captures the script used in commit 189f164e57 ("Convert
remaining multi-line kmalloc_obj/flex GFP_KERNEL uses").

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-03-20 10:52:52 -07:00
Kees Cook c4192754e8 fs/tests: exec: Remove bad test vector
Drop an unusable test in the bprm stack limits.

Reported-by: Guenter Roeck <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]
Fixes: 60371f43e5 ("exec: Add KUnit test for bprm_stack_limits()")
Signed-off-by: Kees Cook <[email protected]>
2026-03-18 11:41:53 -07:00
Kees Cook 9f3d543a9f drm/amd/ras: Fix type size of remainder argument
Forcing an int to be dereferenced at uint64_t for div64_u64_rem() runs
the risk of endian confusion and stack overflowing writes. Seen while
preparing to enable -Warray-bounds globally:

In file included from ../arch/x86/include/asm/processor.h:35,
                 from ../include/linux/sched.h:13,
                 from ../include/linux/ratelimit.h:6,
                 from ../include/linux/dev_printk.h:16,
                 from ../drivers/gpu/drm/amd/amdgpu/../ras/ras_mgr/ras_sys.h:29,
                 from ../drivers/gpu/drm/amd/amdgpu/../ras/rascore/ras.h:27,
                 from ../drivers/gpu/drm/amd/amdgpu/../ras/rascore/ras_core.c:24:
In function 'div64_u64_rem',
    inlined from 'ras_core_convert_timestamp_to_time' at ../drivers/gpu/drm/amd/amdgpu/../ras/rascore/ras_core.c:72:9:
../include/linux/math64.h:56:20: error: array subscript 'u64 {aka long long unsigned int}[0]' is partly outside array bounds of 'int[1]' [-Werror=array-bounds=]
   56 |         *remainder = dividend % divisor;
      |         ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
../drivers/gpu/drm/amd/amdgpu/../ras/rascore/ras_core.c: In function 'ras_core_convert_timestamp_to_time':
../drivers/gpu/drm/amd/amdgpu/../ras/rascore/ras_core.c:70:19: note: object 'remaining_seconds' of size 4
   70 |         int days, remaining_seconds;
      |                   ^~~~~~~~~~~~~~~~~

Use a 64-bit type for the remainder calculation, but leave
remaining_seconds as 32-bit to avoid 64-bit division later. The value of
remainder will always be less than seconds_per_day, so there's no
truncation risk.

Fixes: ace232eff5 ("drm/amdgpu: Add ras module files into amdgpu")
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Alex Deucher <[email protected]>
2026-03-02 16:35:30 -05:00
Kees Cook 795469820c kcsan: test: Adjust "expect" allocation type for kmalloc_obj
The call to kmalloc_obj(observed.lines) returns "char (*)[3][512]",
a pointer to the whole 2D array. But "expect" wants to be "char (*)[512]",
the decayed pointer type, as if it were observed.lines itself (though
without the "3" bounds). This produces the following build error:

../kernel/kcsan/kcsan_test.c: In function '__report_matches':
../kernel/kcsan/kcsan_test.c:171:16: error: assignment to 'char (*)[512]' from incompatible pointer type 'char (*)[3][512]'
[-Wincompatible-pointer-types]
  171 |         expect = kmalloc_obj(observed.lines);
      |                ^

Instead of changing the "expect" type to "char (*)[3][512]" and
requiring a dereference at each use (e.g. "(expect*)[0]"), just
explicitly cast the return to the desired type.

Note that I'm intentionally not switching back to byte-based "kmalloc"
here because I cannot find a way for the Coccinelle script (which will
be used going forward to catch future conversions) to exclude this case.

Tested with:

$ ./tools/testing/kunit/kunit.py run \
	--kconfig_add CONFIG_DEBUG_KERNEL=y \
	--kconfig_add CONFIG_KCSAN=y \
	--kconfig_add CONFIG_KCSAN_KUNIT_TEST=y \
	--arch=x86_64 --qemu_args '-smp 2' kcsan

Reported-by: Nathan Chancellor <[email protected]>
Fixes: 69050f8d6d ("treewide: Replace kmalloc with kmalloc_obj for non-scalar types")
Signed-off-by: Kees Cook <[email protected]>
2026-02-26 09:54:08 -08:00
Kees Cook 4b44cbb264 overflow: Make sure size helpers are always inlined
With kmalloc_obj() performing implicit size calculations, the embedded
size_mul() calls, while marked inline, were not always being inlined.
I noticed a couple places where allocations were making a call out for
things that would otherwise be compile-time calculated. Force the
compilers to always inline these calculations.

Reviewed-by: Gustavo A. R. Silva <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-24 15:46:31 -08:00
Kees Cook 6f6f353519 drm/msm: Adjust msm_iommu_pagetable_prealloc_allocate() allocation type
In preparation for making the 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 "void **" but the returned type will be "void ***".
These are the same allocation size (pointer size), but the types do not
match. Adjust the allocation type to match the assignment.

Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Dmitry Baryshkov <[email protected]>
Patchwork: https://patchwork.freedesktop.org/patch/703588/
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Dmitry Baryshkov <[email protected]>
2026-02-24 01:28:18 +02:00
Kees Cook 96a7b71c44 ubd: Use pointer-to-pointers for io_thread_req arrays
Having an unbounded array for irq_req_buffer and io_req_buffer doesn't
provide any bounds safety, and confuses the needed allocation type,
which is returning a pointer to pointers. Instead of the implicit cast,
switch the variable types.

Reported-by: Nathan Chancellor <[email protected]>
Reported-by: Guenter Roeck <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]
Fixes: 69050f8d6d ("treewide: Replace kmalloc with kmalloc_obj for non-scalar types")
Acked-by: Richard Weinberger <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-23 14:35:16 -08:00
Kees Cook 189f164e57 Convert remaining multi-line kmalloc_obj/flex GFP_KERNEL uses
Conversion performed via this Coccinelle script:

  // SPDX-License-Identifier: GPL-2.0-only
  // Options: --include-headers-for-types --all-includes --include-headers --keep-comments
  virtual patch

  @gfp depends on patch && !(file in "tools") && !(file in "samples")@
  identifier ALLOC = {kmalloc_obj,kmalloc_objs,kmalloc_flex,
 		    kzalloc_obj,kzalloc_objs,kzalloc_flex,
		    kvmalloc_obj,kvmalloc_objs,kvmalloc_flex,
		    kvzalloc_obj,kvzalloc_objs,kvzalloc_flex};
  @@

  	ALLOC(...
  -		, GFP_KERNEL
  	)

  $ make coccicheck MODE=patch COCCI=gfp.cocci

Build and boot tested x86_64 with Fedora 42's GCC and Clang:

Linux version 6.19.0+ (user@host) (gcc (GCC) 15.2.1 20260123 (Red Hat 15.2.1-7), GNU ld version 2.44-12.fc42) #1 SMP PREEMPT_DYNAMIC 1970-01-01
Linux version 6.19.0+ (user@host) (clang version 20.1.8 (Fedora 20.1.8-4.fc42), LLD 20.1.8) #1 SMP PREEMPT_DYNAMIC 1970-01-01

Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
2026-02-22 08:26:33 -08:00
Kees Cook 7a70c15bd1 kmalloc_obj: Clean up after treewide replacements
Coccinelle doesn't handle re-indenting line escapes. Fix the 2 places
where these got misaligned.

Remove 2 now-redundant type casts, found with:
$ git grep -P 'struct (\S+).*\)\s*k\S+alloc_(objs?|flex)\(struct \1'

Signed-off-by: Kees Cook <[email protected]>
2026-02-21 01:02:52 -08:00
Kees Cook 69050f8d6d treewide: Replace kmalloc with kmalloc_obj for non-scalar types
This is the result of running the Coccinelle script from
scripts/coccinelle/api/kmalloc_objs.cocci. The script is designed to
avoid scalar types (which need careful case-by-case checking), and
instead replace kmalloc-family calls that allocate struct or union
object instances:

Single allocations:	kmalloc(sizeof(TYPE), ...)
are replaced with:	kmalloc_obj(TYPE, ...)

Array allocations:	kmalloc_array(COUNT, sizeof(TYPE), ...)
are replaced with:	kmalloc_objs(TYPE, COUNT, ...)

Flex array allocations:	kmalloc(struct_size(PTR, FAM, COUNT), ...)
are replaced with:	kmalloc_flex(*PTR, FAM, COUNT, ...)

(where TYPE may also be *VAR)

The resulting allocations no longer return "void *", instead returning
"TYPE *".

Signed-off-by: Kees Cook <[email protected]>
2026-02-21 01:02:28 -08:00
Kees Cook d39a1d7486 compiler_types: Disable __builtin_counted_by_ref for Clang
Unfortunately, there is a corner case of __builtin_counted_by_ref()
usage that crashes[1] Clang since support was introduced in Clang 19.
Disable it prior to Clang 22. Found while tested kmalloc_obj treewide
refactoring (via kmalloc_flex() usage).

Link: https://github.com/llvm/llvm-project/issues/182575 [1]
Signed-off-by: Kees Cook <[email protected]>
2026-02-21 01:01:14 -08:00
Kees Cook c732084c89 KVM: arm64: vgic: Handle const qualifier from gic_kvm_info allocation type
In preparation for making the 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 gic_kvm_info", but the returned type,
while matching, is const qualified. To get them exactly matching, just
use the dereferenced pointer for the sizeof().

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-19 10:14:02 -08:00
Kees Cook 48634a9ea0 drm/msm: Adjust msm_iommu_pagetable_prealloc_allocate() allocation type
In preparation for making the 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 "void **" but the returned type will be "void ***".
These are the same allocation size (pointer size), but the types do not
match. Adjust the allocation type to match the assignment.

Reviewed-by: Dmitry Baryshkov <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-19 10:07:01 -08:00
Kees Cook a3fab95440 dm: dm-zoned: Adjust dmz_load_mapping() allocation type
In preparation for making the 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 dmz_mblock **" but the returned type will
be "struct dmz_mblk **". These are the same allocation size (pointer
size), but the types do not match. Adjust the allocation type to match
the assignment.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-19 10:05:20 -08:00
Kees Cook c6fcccd539 dm-crypt: Adjust crypt_alloc_tfms_aead() allocation type
In preparation for making the 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 crypto_skcipher **" but the returned type
will be "struct crypto_aead **". These are the same allocation size
(pointer size), but the types don't match. Adjust the allocation type
to match the assignment.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-19 10:05:20 -08:00
Kees Cook ee5c38a8d3 KVM: arm64: vgic: Handle const qualifier from gic_kvm_info allocation type
In preparation for making the 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 gic_kvm_info", but the returned type,
while matching, is const qualified. To get them exactly matching, just
use the dereferenced pointer for the sizeof().

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Marc Zyngier <[email protected]>
2026-02-13 14:59:04 +00:00
Kees Cook 90627a1e08 lib/group_cpus: handle const qualifier from clusters allocation type
In preparation for making the 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 cpumask **", but the returned type,
while matching, is not const qualified.  To get them exactly matching,
just use the dereferenced pointer for the sizeof().

Link: https://lkml.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
Cc: Wangyang Guo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
2026-02-12 15:45:58 -08:00
Kees Cook 1562b1fb7e crypto: omap - Allocate OMAP_CRYPTO_FORCE_COPY scatterlists correctly
The existing allocation of scatterlists in omap_crypto_copy_sg_lists()
was allocating an array of scatterlist pointers, not scatterlist objects,
resulting in a 4x too small allocation.

Use sizeof(*new_sg) to get the correct object size.

Fixes: 74ed87e7e7 ("crypto: omap - add base support library for common routines")
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Herbert Xu <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
2026-02-10 08:43:21 -08:00
Kees Cook bdc5071d7f coccinelle: Add kmalloc_objs conversion script
Finds and converts sized kmalloc-family of allocations into the
typed kmalloc_obj-family of allocations.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-02-09 10:48:20 -08:00
Kees Cook 44dd7cfbd1 MAINTAINERS: pstore: Remove L: entry
A lot of SoC series end up getting CCed to the hardening list due to
their mention of "pstore" in device tree or similar, and this noise isn't
worth making sure I don't lose pstore patches by having them show up in
the hardening patchwork. ;) I can use better email filters instead!

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-17 11:00:37 -08:00
Kees Cook fac4ab5cd0 coredump: Use __counted_by_ptr for struct core_name::corename
Use the __counted_by annotation now available for struct pointer
members, __counted_by_ptr(). Move assignments to immediately
after allocation.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-17 11:00:37 -08:00
Kees Cook a120a832e3 lkdtm/bugs: Add __counted_by_ptr() test PTR_BOUNDS
Provide run-time validation of the __counted_by_ptr() annotation via
newly added PTR_BOUNDS LKDTM test.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-17 11:00:37 -08:00
Kees Cook e4c8b46b92 slab: Introduce kmalloc_flex() and family
As done for kmalloc_obj*(), introduce a type-aware allocator for flexible
arrays, which may also have "counted_by" annotations:

	ptr = kmalloc(struct_size(ptr, flex_member, count), gfp);

becomes:

	ptr = kmalloc_flex(*ptr, flex_member, count, gfp);

The internal use of __flex_counter() allows for automatically setting
the counter member of a struct's flexible array member when it has
been annotated with __counted_by(), avoiding any missed early size
initializations while __counted_by() annotations are added to the
kernel. Additionally, this also checks for "too large" allocations based
on the type size of the counter variable. For example:

	if (count > type_max(ptr->flex_counter))
		fail...;
	size = struct_size(ptr, flex_member, count);
	ptr = kmalloc(size, gfp);
	if (!ptr)
		fail...;
	ptr->flex_counter = count;

becomes (n.b. unchanged from earlier example):

	ptr = kmalloc_flex(*ptr, flex_member, count, gfp);
	if (!ptr)
		fail...;
	ptr->flex_counter = count;

Note that manual initialization of the flexible array counter is still
required (at some point) after allocation as not all compiler versions
support the __counted_by annotation yet. But doing it internally makes
sure they cannot be missed when __counted_by _is_ available, meaning
that the bounds checker will not trip due to the lack of "early enough"
initializations that used to work before enabling the stricter bounds
checking. For example:

	ptr = kmalloc_flex(*ptr, flex_member, count, gfp);
	fill(ptr->flex, count);
	ptr->flex_count = count;

This works correctly before adding a __counted_by annotation (since
nothing is checking ptr->flex accesses against ptr->flex_count). After
adding the annotation, the bounds sanitizer would trip during fill()
because ptr->flex_count wasn't set yet. But with kmalloc_flex() setting
ptr->flex_count internally at allocation time, the existing code works
without needing to move the ptr->flex_count assignment before the call
to fill(). (This has been a stumbling block for __counted_by adoption.)

Link: https://patch.msgid.link/[email protected]
Acked-by: Vlastimil Babka <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
2026-01-14 14:43:01 -08:00
Kees Cook 81cee9166a compiler_types: Introduce __flex_counter() and family
Introduce __flex_counter() which wraps __builtin_counted_by_ref(),
as newly introduced by GCC[1] and Clang[2]. Use of __flex_counter()
allows access to the counter member of a struct's flexible array member
when it has been annotated with __counted_by().

Introduce typeof_flex_counter(), overflows_flex_counter_type(), and
__set_flex_counter() to provide the needed _Generic() wrappers to get
sane results out of __flex_counter().

For example, with:

	struct foo {
		int counter;
		short array[] __counted_by(counter);
	} *p;

__flex_counter(p->array) will resolve to: &p->counter

typeof_flex_counter(p->array) will resolve to "int". (If p->array was not
annotated, it would resolve to "size_t".)

overflows_flex_counter_type(typeof(*p), array, COUNT) is the same as:

	COUNT <= type_max(p->counter) && COUNT >= type_min(p->counter)

(If p->array was not annotated it would return true since everything
fits in size_t.)

__set_flex_counter(p->array, COUNT) is the same as:

	p->counter = COUNT;

(It is a no-op if p->array is not annotated with __counted_by().)

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-14 14:43:01 -08:00
Kees Cook 070580b0b1 checkpatch: Suggest kmalloc_obj family for sizeof allocations
To support shifting away from sized allocation towards typed
allocations, suggest the kmalloc_obj family of macros when a sizeof() is
present in the argument lists.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-14 14:43:01 -08:00
Kees Cook 2932ba8d9c slab: Introduce kmalloc_obj() and family
Introduce type-aware kmalloc-family helpers to replace the common
idioms for single object and arrays of objects allocation:

	ptr = kmalloc(sizeof(*ptr), gfp);
	ptr = kmalloc(sizeof(struct some_obj_name), gfp);
	ptr = kzalloc(sizeof(*ptr), gfp);
	ptr = kmalloc_array(count, sizeof(*ptr), gfp);
	ptr = kcalloc(count, sizeof(*ptr), gfp);

These become, respectively:

	ptr = kmalloc_obj(*ptr, gfp);
	ptr = kmalloc_obj(*ptr, gfp);
	ptr = kzalloc_obj(*ptr, gfp);
	ptr = kmalloc_objs(*ptr, count, gfp);
	ptr = kzalloc_objs(*ptr, count, gfp);

Beyond the other benefits outlined below, the primary ergonomic benefit
is the elimination of needing "sizeof" nor the type name, and the
enforcement of assignment types (they do not return "void *", but rather
a pointer to the type of the first argument). The type name _can_ be
used, though, in the case where an assignment is indirect (e.g. via
"return"). This additionally allows[1] variables to be declared via
__auto_type:

	__auto_type ptr = kmalloc_obj(struct foo, gfp);

Internal introspection of the allocated type now becomes possible,
allowing for future alignment-aware choices to be made by the allocator
and future hardening work that can be type sensitive. For example,
adding __alignof(*ptr) as an argument to the internal allocators so that
appropriate/efficient alignment choices can be made, or being able to
correctly choose per-allocation offset randomization within a bucket
that does not break alignment requirements.

Link: https://lore.kernel.org/all/CAHk-=wiCOTW5UftUrAnvJkr6769D29tF7Of79gUjdQHS_TkF5A@mail.gmail.com/ [1]
Acked-by: Vlastimil Babka <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2026-01-14 14:43:01 -08:00
Kees Cook 0fdf6323c3 media: solo6x10: Check for out of bounds chip_id
Clang with CONFIG_UBSAN_SHIFT=y noticed a condition where a signed type
(literal "1" is an "int") could end up being shifted beyond 32 bits,
so instrumentation was added (and due to the double is_tw286x() call
seen via inlining), Clang decides the second one must now be undefined
behavior and elides the rest of the function[1]. This is a known problem
with Clang (that is still being worked on), but we can avoid the entire
problem by actually checking the existing max chip ID, and now there is
no runtime instrumentation added at all since everything is known to be
within bounds.

Additionally use an unsigned value for the shift to remove the
instrumentation even without the explicit bounds checking.

Link: https://github.com/ClangBuiltLinux/linux/issues/2144 [1]
Suggested-by: Nathan Chancellor <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
[hverkuil: fix checkpatch warning for is_tw286x]
2026-01-13 13:21:03 +01:00
Kees Cook 68e8555858 module/decompress: Avoid open-coded kvrealloc()
Replace open-coded allocate/copy with kvrealloc().

Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Petr Pavlu <[email protected]>
Signed-off-by: Sami Tolvanen <[email protected]>
2025-12-22 16:35:54 +00:00
Kees Cook 7454048db2 kbuild: Enable GCC diagnostic context for value-tracking warnings
Enable GCC 16's coming "-fdiagnostics-show-context=N" option[1] to
provide enhanced diagnostic information for value-tracking warnings,
which displays the control flow chain leading to the diagnostic. This
covers our existing use of -Wrestrict and -Wstringop-overread, and
gets us closer to enabling -Warray-bounds, -Wstringop-overflow, and
-Wstringop-truncation, so we can track the rationale for the warning,
letting us more quickly identify actual issues vs what have looked in
the past like false positives. Fixes based on this work have already
been landing, e.g.:

  4a6f18f286 ("net/mlx4_core: Avoid impossible mlx4_db_alloc() order value")
  8a39f1c870 ("ovl: Check for NULL d_inode() in ovl_dentry_upper()")
  e5f7e4e0a4 ("drm/amdgpu/atom: Work around vbios NULL offset false positive")

The context depth ("=N") provides the immediate decision path that led
to the problematic code location, showing conditional checks and branch
decisions that caused the warning. This will help us understand why
GCC's value-tracking analysis triggered the warning and makes it easier
to determine whether warnings are legitimate issues or false positives.

For example, an array bounds warning will now show the conditional
statements (like "if (i >= 4)") that established the out-of-bounds access
range, directly connecting the control flow to the warning location.
This is particularly valuable when GCC's interprocedural analysis can
generate warnings that are difficult to understand without seeing the
inferred control flow.

While my testing has shown that "=1" reports enough for finding
the origin of most bounds issues, I have used "=2" here just to be
conservative. Build time measurements with this option off, =1, and =2
are all with noise of each other, so there seems to be no harm in "turning
it up". If we need to, we can make this value configurable in the future.

Link: https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=6faa3cfe60ff9769d1bebfffdd2c7325217d7389 [1]
Reviewed-by: Miguel Ojeda <[email protected]>
Reviewed-by: Nathan Chancellor <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-11-24 12:44:05 -08:00
Kees Cook fbcc2150aa media: iris: Cast iris_hfi_gen2_get_instance() allocation type
In preparation for making the 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 iris_inst *", but the returned type is
"struct iris_inst_hfi_gen2 *". The allocation is intentionally larger as
the first member of struct iris_inst_hfi_gen2 is struct iris_inst, so
this is by design. Cast the allocation type to match the assignment.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-11-24 12:44:05 -08:00
Kees Cook 961c989c5f drm/plane: Remove const qualifier from plane->modifiers allocation type
In preparation for making the 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 "uint64_t *", but the returned type, while matching,
will be const qualified. As there is no general way to remove const
qualifiers, adjust the allocation type to match the assignment.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-11-24 12:43:52 -08:00
Kees Cook 5146f56dee comedi: Adjust range_table_list allocation type
In preparation for making the 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 returned type is "struct comedi_lrange **", but the assigned type,
while technically matching, is const qualified. Since there is no general
way to remove const qualifiers, switch the returned type to match the
assign type. No change in allocation size results.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-11-24 12:43:28 -08:00
Kees Cook ae83f3b726 module: Add compile-time check for embedded NUL characters
Long ago, the kernel module license checks were bypassed by embedding a
NUL character in the MODULE_LICENSE() string[1]. By using a string like
"GPL\0proprietary text", the kernel would only read "GPL" due to C string
termination at the NUL byte, allowing proprietary modules to avoid kernel
tainting and access GPL-only symbols.

The MODULE_INFO() macro stores these strings in the .modinfo ELF
section, and get_next_modinfo() uses strcmp()-family functions
which stop at the first NUL. This split the embedded string into two
separate .modinfo entries, with only the first part being processed by
license_is_gpl_compatible().

Add a compile-time check using static_assert that compares the full
string length (sizeof - 1) against __builtin_strlen(), which stops at
the first NUL. If they differ, compilation fails with a clear error
message.

While this check can still be circumvented by modifying the ELF binary
post-compilation, it prevents accidental embedded NULs and forces
intentional abuse to require deliberate binary manipulation rather than
simple source-level tricks.

Build tested with test modules containing both valid and invalid license
strings. The check correctly rejects:

    MODULE_LICENSE("GPL\0proprietary")

while accepting normal declarations:

    MODULE_LICENSE("GPL")

Link: https://lwn.net/Articles/82305/ [1]
Suggested-by: Rusty Russell <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Daniel Gomez <[email protected]>
Reviewed-by: Aaron Tomlin <[email protected]>
Reviewed-by: Petr Pavlu <[email protected]>
Tested-by: Daniel Gomez <[email protected]>
Signed-off-by: Daniel Gomez <[email protected]>
2025-11-05 14:08:58 +01:00
Kees Cook 57e9853737 media: radio: si470x: Fix DRIVER_AUTHOR macro definition
The DRIVER_AUTHOR macro incorrectly included a semicolon in its
string literal definition. Right now, this wasn't causing any real
problem, but coming changes to the MODULE_INFO() macro make this more
sensitive. Specifically, when used with MODULE_AUTHOR(), this created
syntax errors during macro expansion:

    MODULE_AUTHOR(DRIVER_AUTHOR);

expands to:

    MODULE_INFO(author, "Joonyoung Shim <[email protected]>";)
                                                                  ^
                                                       syntax error

Remove the trailing semicolon from the DRIVER_AUTHOR definition.
Semicolons should only appear at the point of use, not in the macro
definition.

Reviewed-by: Hans Verkuil <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reviewed-by: Daniel Gomez <[email protected]>
Tested-by: Daniel Gomez <[email protected]>
Signed-off-by: Daniel Gomez <[email protected]>
2025-11-05 14:08:56 +01:00
Kees Cook 9de2198ab9 media: dvb-usb-v2: lmedm04: Fix firmware macro definitions
The firmware filename macros incorrectly included semicolons in their
string literal definitions. Right now, this wasn't causing any real
problem, but coming changes to the MODULE_INFO() macro make this more
sensitive. Specifically, when used with MODULE_FIRMWARE(), this
created syntax errors during macro expansion:

    MODULE_FIRMWARE(LME2510_C_S7395);

expands to:

    MODULE_INFO(firmware, "dvb-usb-lme2510c-s7395.fw";)
                                                     ^
                                          syntax error

Remove the trailing semicolons from all six firmware filename macro
definitions. Semicolons should only appear at the point of use, not in
the macro definition.

Reviewed-by: Hans Verkuil <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reviewed-by: Daniel Gomez <[email protected]>
Tested-by: Daniel Gomez <[email protected]>
Signed-off-by: Daniel Gomez <[email protected]>
2025-11-05 14:08:55 +01:00
Kees Cook 2b5e9f9b7e net: Convert struct sockaddr to fixed-size "sa_data[14]"
Revert struct sockaddr from flexible array to fixed 14-byte "sa_data",
to solve over 36,000 -Wflex-array-member-not-at-end warnings, since
struct sockaddr is embedded within many network structs.

With socket/proto sockaddr-based internal APIs switched to use struct
sockaddr_unsized, there should be no more uses of struct sockaddr that
depend on reading beyond the end of struct sockaddr::sa_data that might
trigger bounds checking.

Comparing an x86_64 "allyesconfig" vmlinux build before and after this
patch showed no new "ud1" instructions from CONFIG_UBSAN_BOUNDS nor any
new "field-spanning" memcpy CONFIG_FORTIFY_SOURCE instrumentations.

Cc: Gustavo A. R. Silva <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:33 -08:00
Kees Cook c1a799eef6 bpf: Convert bpf_sock_addr_kern "uaddr" to sockaddr_unsized
Change struct bpf_sock_addr_kern to use sockaddr_unsized for the "uaddr"
field instead of sockaddr. This improves type safety in the BPF cgroup
socket address filtering code.

The casting in __cgroup_bpf_run_filter_sock_addr() is updated to match the
new type, removing an unnecessary cast in the initialization and updating
the conditional assignment to use the appropriate sockaddr_unsized cast.

Additionally rename the "unspec" variable to "storage" to better align
with its usage.

No binary changes expected.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:33 -08:00
Kees Cook 8116d803e7 bpf: Convert cgroup sockaddr filters to use sockaddr_unsized consistently
Update BPF cgroup sockaddr filtering infrastructure to use sockaddr_unsized
consistently throughout the call chain, removing redundant explicit casts
from callers.

No binary changes expected.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:33 -08:00
Kees Cook 449f68f8ff net: Convert proto callbacks from sockaddr to sockaddr_unsized
Convert struct proto pre_connect(), connect(), bind(), and bind_add()
callback function prototypes from struct sockaddr to struct sockaddr_unsized.
This does not change per-implementation use of sockaddr for passing around
an arbitrarily sized sockaddr struct. Those will be addressed in future
patches.

Additionally removes the no longer referenced struct sockaddr from
include/net/inet_common.h.

No binary changes expected.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:33 -08:00
Kees Cook 3d39d34146 net: Remove struct sockaddr from net.h
Now that struct sockaddr is no longer used by net.h, remove it.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:33 -08:00
Kees Cook 85cb0757d7 net: Convert proto_ops connect() callbacks to use sockaddr_unsized
Update all struct proto_ops connect() callback function prototypes from
"struct sockaddr *" to "struct sockaddr_unsized *" to avoid lying to the
compiler about object sizes. Calls into struct proto handlers gain casts
that will be removed in the struct proto conversion patch.

No binary changes expected.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:32 -08:00
Kees Cook 0e50474fa5 net: Convert proto_ops bind() callbacks to use sockaddr_unsized
Update all struct proto_ops bind() callback function prototypes from
"struct sockaddr *" to "struct sockaddr_unsized *" to avoid lying to the
compiler about object sizes. Calls into struct proto handlers gain casts
that will be removed in the struct proto conversion patch.

No binary changes expected.

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:32 -08:00
Kees Cook bf33247a90 net: Add struct sockaddr_unsized for sockaddr of unknown length
Add flexible sockaddr structure to support addresses longer than the
traditional 14-byte struct sockaddr::sa_data limitation without
requiring the full 128-byte sa_data of struct sockaddr_storage. This
allows the network APIs to pass around a pointer to an object that
isn't lying to the compiler about how big it is, but must be accompanied
by its actual size as an additional parameter.

It's possible we may way to migrate to including the size with the
struct in the future, e.g.:

struct sockaddr_unsized {
	u16 sa_data_len;
	u16 sa_family;
	u8  sa_data[] __counted_by(sa_data_len);
};

Signed-off-by: Kees Cook <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
2025-11-04 19:10:32 -08:00
Kees Cook 0902b3cb23 kconfig: Avoid prompting for transitional symbols
The "transitional" symbol keyword, while working with the "olddefconfig"
target, was prompting during "oldconfig". This occurred because these
symbols were not being marked as user-defined when they received values
from transitional symbols that had user values. The "olddefconfig" target
explicitly doesn't prompt for anything, so this deficiency wasn't noticed.

The issue manifested when a symbol's value came from a transitional
symbol's user value but the receiving symbol wasn't marked with
SYMBOL_DEF_USER. Thus the "oldconfig" logic would then prompt for these
symbols unnecessarily.

Check after value calculation whether a symbol without a user value
gets its value from a single transitional symbol that does have a user
value. In such cases, mark the receiving symbol as user-defined to
prevent prompting.

Update regression tests to verify that symbols with transitional defaults
are not prompted in "oldconfig", except when conditional defaults evaluate
to 'no' and should legitimately be prompted.

Build tested with "make testconfig".

Reported-by: Linus Torvalds <[email protected]>
Closes: https://lore.kernel.org/lkml/CAHk-=wgZjUk4Cy2XgNkTrQoO8XCmNUHrTe5D519Fij1POK+3qw@mail.gmail.com/
Fixes: f9afce4f32 ("kconfig: Add transitional symbol attribute for migration support")
Cc: Vegard Nossum <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-10-07 08:21:23 -07:00
Kees Cook 23ef9d4397 kcfi: Rename CONFIG_CFI_CLANG to CONFIG_CFI
The kernel's CFI implementation uses the KCFI ABI specifically, and is
not strictly tied to a particular compiler. In preparation for GCC
supporting KCFI, rename CONFIG_CFI_CLANG to CONFIG_CFI (along with
associated options).

Use new "transitional" Kconfig option for old CONFIG_CFI_CLANG that will
enable CONFIG_CFI during olddefconfig.

Reviewed-by: Linus Walleij <[email protected]>
Reviewed-by: Nathan Chancellor <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-09-24 14:29:14 -07:00
Kees Cook f9afce4f32 kconfig: Add transitional symbol attribute for migration support
During kernel option migrations (e.g. CONFIG_CFI_CLANG to CONFIG_CFI),
existing .config files need to maintain backward compatibility while
preventing deprecated options from appearing in newly generated
configurations. This is challenging with existing Kconfig mechanisms
because:

1. Simply removing old options breaks existing .config files.
2. Manually listing an option as "deprecated" leaves it needlessly
   visible and still writes them to new .config files.
3. Using any method to remove visibility (.e.g no 'prompt', 'if n',
   etc) prevents the option from being processed at all.

Add a "transitional" attribute that creates symbols which are:
- Processed during configuration (can influence other symbols' defaults)
- Hidden from user menus (no prompts appear)
- Omitted from newly written .config files (gets migrated)
- Restricted to only having help sections (no defaults, selects, etc)
  making it truly just a "prior value pass-through" option.

The transitional syntax requires a type argument and prevents type
redefinition:

    config NEW_OPTION
        bool "New option"
        default OLD_OPTION

    config OLD_OPTION
        bool
        transitional
        help
          Transitional config for OLD_OPTION migration.

This allows seamless migration: olddefconfig processes existing
CONFIG_OLD_OPTION=y settings to enable CONFIG_NEW_OPTION=y, while
CONFIG_OLD_OPTION is omitted from newly generated .config files.

Added positive and negative testing via "testconfig" make target.

Co-developed-by: Vegard Nossum <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Reviewed-by: Nathan Chancellor <[email protected]>
Tested-by: Nathan Chancellor <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-09-24 14:23:35 -07:00
Kees Cook 64f4ea200e kconfig: Fix BrokenPipeError warnings in selftests
The kconfig test harness ("make testconfig") was generating BrokenPipeError
warnings when running interactive tests like oldaskconfig and oldconfig:

  /usr/lib/python3/dist-packages/_pytest/unraisableexception.py:85: PytestUnraisableExceptionWarning: Exception ignored in: <_io.BufferedWriter name=12>

  Traceback (most recent call last):
    File "/srv/code/scripts/kconfig/tests/conftest.py", line 127, in oldaskconfig
      return self._run_conf('--oldaskconfig', dot_config=dot_config,
             ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                            interactive=True, in_keys=in_keys)
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  BrokenPipeError: [Errno 32] Broken pipe

The issue occurred when the test framework attempted to write to stdin
after the conf subprocess had already exited.

Wrap stdin write operations in try/except to catch BrokenPipeError and
stop sending more input. Add explicit flush() after writes so we can see
delivery errors immediately. Ignore BrokenPipeError when closing stdin.
Explicitly call wait() to validate subprocess termination.

Reviewed-by: Nathan Chancellor <[email protected]>
Tested-by: Nathan Chancellor <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-09-24 14:23:35 -07:00
Kees Cook a40282dd3c gcc-plugins: Remove TODO_verify_il for GCC >= 16
GCC now runs TODO_verify_il automatically[1], so it is no longer exposed to
plugins. Only use the flag on GCC < 16.

Link: https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=9739ae9384dd7cd3bb1c7683d6b80b7a9116eaf8 [1]
Suggested-by: Christopher Fore <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Kees Cook <[email protected]>
2025-09-23 13:59:39 -07:00