RC RANDOM CHAOS

Kees Cook deleted strncpy from the Linux kernel

Linux 7.2 removed strncpy after six years and about 362 commits. Here are the strscpy, strtomem_pad and memcpy replacements and when to use each.

· 2 min read
Kees Cook deleted strncpy from the Linux kernel

Linux 7.2 ships without a single caller of strncpy(). The merge landed on a Friday and removed the generic API along with the last per-architecture strncpy implementations. Getting there took about six years and roughly 362 commits to convert every user in the tree.

strncpy has been deprecated in the kernel for years, and the reasons are the ones that have tripped up C programmers for decades. The function copies up to a fixed number of bytes from source to destination. If the source string is shorter than that limit, strncpy pads the rest of the destination with NUL bytes. If the source is as long as or longer than the limit, it writes no terminating NUL at all. You get a buffer that looks like a string but is not NUL-terminated, and the next function that treats it as one reads past the end.

Sometimes padding, sometimes not terminating: that is what the kernel developers mean when they call the semantics counter-intuitive. The zero-filling is also a performance cost. Every short copy into a large buffer writes out the remaining bytes as NUL whether or not anything depends on them. Across a kernel’s worth of fixed-size fields, that adds up, and it hid real bugs where the termination simply never happened.

There is no single drop-in replacement, which is the point. The conversion forced each call site to say what the destination actually is:

  • strscpy() for NUL-terminated destinations.
  • strscpy_pad() for NUL-terminated destinations that also need zero-padding.
  • strtomem_pad() for non-NUL-terminated fixed-width fields.
  • memcpy_and_pad() for bounded copies with explicit padding.
  • memcpy() for known-length memory copies.

Each of those encodes a decision strncpy left implicit: is the target a C string or a fixed-width byte field, and does the unused tail need to be zeroed? strncpy answered both questions silently and often wrongly. The replacements make you answer them in the name of the function you call.

If you maintain out-of-tree modules or backport patches against recent kernels, strncpy is no longer available to you. Map each use to the destination’s contract rather than reaching for the nearest string copy. A field that other code reads as a C string wants strscpy(); add _pad only when the trailing bytes genuinely need to be zero. A fixed-width field that is never treated as a terminated string wants strtomem_pad() or memcpy_and_pad(), and a copy whose length you already know wants plain memcpy(). Picking the wrong one reintroduces exactly the ambiguity this work spent six years removing.

Share

Keep Reading

Latest on the Wire

Full wire →

New signal daily · RSS

Stay in the loop

New writing delivered when it's ready. No schedule, no spam.