Re: [PATCH bpf-next] selftests/bpf: Fix strncpy() fortify warning

From: Andrii Nakryiko
Date: Thu Oct 27 2022 - 16:10:19 EST


On Thu, Oct 27, 2022 at 4:34 AM Rong Tao <rtoax@xxxxxxxxxxx> wrote:
>
> From: Rong Tao <rongtao@xxxxxxxx>
>
> Compile samples/bpf, error:
> $ cd samples/bpf
> $ make
> ...
> In function ‘__enable_controllers’:
> samples/bpf/../../tools/testing/selftests/bpf/cgroup_helpers.c:80:17: warning: ‘strncpy’ specified bound 4097 equals destination size [-Wstringop-truncation]
> 80 | strncpy(enable, controllers, sizeof(enable));
> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> Signed-off-by: Rong Tao <rongtao@xxxxxxxx>
> ---
> tools/testing/selftests/bpf/cgroup_helpers.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/tools/testing/selftests/bpf/cgroup_helpers.c b/tools/testing/selftests/bpf/cgroup_helpers.c
> index e914cc45b766..a70e873b267e 100644
> --- a/tools/testing/selftests/bpf/cgroup_helpers.c
> +++ b/tools/testing/selftests/bpf/cgroup_helpers.c
> @@ -77,7 +77,7 @@ static int __enable_controllers(const char *cgroup_path, const char *controllers
> enable[len] = 0;
> close(fd);
> } else {
> - strncpy(enable, controllers, sizeof(enable));
> + strncpy(enable, controllers, sizeof(enable) - 1);

enable is not initialized, so we might end up with non-zero-terminated
string. Let's enable[0] = '\0'; at the beginning and then strncat()
here?

> }
>
> snprintf(path, sizeof(path), "%s/cgroup.subtree_control", cgroup_path);
> --
> 2.31.1
>