经过六年努力与 360 个补丁的更迭,Linux 内核移除了 strncpy API
Linux eliminates the strncpy API after six years of work, 360 patches

原始链接: https://www.phoronix.com/news/Linux-7.2-Drops-strncpy

经过六年的开发和 360 多次提交,Linux 内核在 7.2 版本中正式移除了 `strncpy()` API。由于其反直觉的空字符(NUL)终止行为以及低效的填充机制,`strncpy()` 长期以来被视为“持久的错误源”,此次替换旨在提升内核的安全性和性能。 开发人员现在需根据具体使用场景,选用更稳健的替代方案: * **`strscpy()`**:用于标准的空字符终止字符串。 * **`strscpy_pad()`**:用于需要补零的空字符终止字符串。 * **`strtomem_pad()`**:用于无需空字符终止的定长字段。 * **`memcpy_and_pad()`**:用于需要显式填充的定界拷贝。 * **`memcpy()`**:用于简单的已知长度内存拷贝。 此次过渡的完成标志着所有 CPU 架构中 `strncpy` 的剩余实现已被全部移除,大幅精简了内核代码库。

Linux 内核已正式废除 `strncpy` API,这项工程历时六年,共包含 360 个补丁。`strncpy` 因其反直觉的空字符(NUL)终止行为以及会导致性能损耗的填充零操作而长期受到诟病,一直是 C 语言系统编程中导致漏洞的顽疾。 Hacker News 上的讨论强调了几个核心议题: * **“字符串”问题:** 许多开发者认为,C 语言缺乏原生的安全字符串类型,只能依赖以 NUL 结尾的字符数组,这是困扰系统编程数十年的根本性设计缺陷。 * **胖指针(Fat Pointers)的必要性:** 专家提倡使用“胖指针”(即指针与长度配对),以防止常见的内存相关错误。尽管有人认为基于结束符的值在 20 世纪 70 年代的硬件限制下是必要的折衷,但许多人认为业界在采用现代替代方案方面进展过于缓慢。 * **基础设施的本质:** 这一变更所耗费的漫长时间凸显了“关键基础设施的悖论”:尽管代码确实存在问题,但由于内核被数十亿台设备使用,重构所需的规模和严谨性决定了必须采取缓慢、系统化的方法,而这远非简单的自动化编码任务所能比拟。
相关文章

原文
Linux 7.2 has finally eliminated the strncpy API from the Linux kernel. The strncpy() function for copying up to a specified number of bytes has long been deprecated and after six years of work and hundreds of patches, no more users of the strncpy interface within the Linux kernel remained that it has now been eliminated.

The strncpy function within the Linux kernel has been a "persistent source of bugs" for years due to counter-intuitive semantics and behavior around NUL termination along with performance issues due to redundant zero-filling of the destination. It took work over the last six years with around 362 commits to eliminate users of strncpy code within the kernel, but they are over the finish line for Linux 7.2.

strncpy


This merge on Friday eliminated the strncpy API and the last per CPU architecture strncpy implementations.

In place of strncpy, Linux kernel code should use strscpy() for NUL terminated destinations, strscpy_pad() for NUl-terminated destinations with zero-padding, strtomem_pad() for non-NUL-terminated fixed-width fields, memcpy_and_pad() for bounded copies with explicit padding, or memcpy() for known-length memory copies.

联系我们 contact @ memedata.com