selftests/bpf: NUL-terminate bpftool command output

run_command() writes a bpftool command's output into a caller-supplied
buffer, and every caller treats that buffer as a C string.

However fread() reports a byte count and doesn't terminate the
string. The helper does not terminate either, so callers have to zero
the buffer first. prog_tests/bpftool_metadata.c does not, for example.

Read one byte less and terminate in the helper.

Fixes: f21fae5774 ("selftests/bpf: Add a few helpers for bpftool testing")
Acked-by: Eduard Zingerman <eddyz87@gmail.com>
Signed-off-by: Ihor Solodrai <ihor.solodrai@linux.dev>
Link: https://lore.kernel.org/r/20260828215207.3105313-5-ihor.solodrai@linux.dev
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
This commit is contained in:
Ihor Solodrai 2026-08-28 14:52:05 -07:00 committed by Alexei Starovoitov
parent 122255fb19
commit 4f8a4c76f6

View File

@ -53,6 +53,7 @@ static int run_command(char *args, char *output_buf, size_t output_max_len)
static char bpftool_path[PATH_MAX] = {};
bool suppress_output = !(output_buf && output_max_len);
char command[BPFTOOL_FULL_CMD_MAX_LEN];
size_t n;
FILE *f;
int ret;
@ -68,8 +69,10 @@ static int run_command(char *args, char *output_buf, size_t output_max_len)
if (!f)
return 1;
if (!suppress_output)
fread(output_buf, 1, output_max_len, f);
if (!suppress_output) {
n = fread(output_buf, 1, output_max_len - 1, f);
output_buf[n] = '\0';
}
ret = pclose(f);
return ret;