Re: [PATCH bpf-next] bpf: Replace strncpy() with strscpy_pad()

From: Yonghong Song
Date: Thu Mar 03 2022 - 13:17:48 EST




On 3/3/22 12:18 AM, Yuntao Wang wrote:
Using strncpy() on NUL-terminated strings is considered deprecated[1],
replace it with strscpy_pad().

[1] https://www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings

Signed-off-by: Yuntao Wang <ytcoode@xxxxxxxxx>
---
kernel/bpf/helpers.c | 8 +-------
1 file changed, 1 insertion(+), 7 deletions(-)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index ae64110a98b5..d03b28761a67 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -225,13 +225,7 @@ BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
if (unlikely(!task))
goto err_clear;
- strncpy(buf, task->comm, size);
-
- /* Verifier guarantees that size > 0. For task->comm exceeding
- * size, guarantee that buf is %NUL-terminated. Unconditionally
- * done here to save the size test.
- */
- buf[size - 1] = 0;
+ strscpy_pad(buf, task->comm, size);

The precise replacement should be strscpy(...), right?
I am not sure whether we want to do pad here or not, probably
not as it is mostly used by user space for string copy/print
and we don't have cases demanding padding yet.

Please keep the comment
/* Verifier guarantees that size > 0 */
this is important as strscpy will not do anything if size == 0.


return 0;
err_clear:
memset(buf, 0, size);