perf bpf: Use scnprintf() in snprintf_hex() and synthesize_bpf_prog_name()

Both functions accumulate formatted output via ret += snprintf(buf + ret,
size - ret, ...).  If the buffer is too small and snprintf() returns more
than the remaining space, ret exceeds size and the next 'size - ret'
underflows, causing snprintf() to write past the buffer end.

Switch to scnprintf() which returns the actual number of bytes written,
making the accumulation safe.

Fixes: 7b612e291a ("perf tools: Synthesize PERF_RECORD_* for loaded BPF programs")
Reported-by: sashiko-bot <sashiko-bot@kernel.org>
Reviewed-by: Ian Rogers <irogers@google.com>
Cc: Song Liu <song@kernel.org>
Assisted-by: Claude:claude-opus-4.6
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
This commit is contained in:
Arnaldo Carvalho de Melo 2026-06-07 14:23:15 -03:00
parent b145137fec
commit cab3a9331e

View File

@ -36,7 +36,7 @@ static int snprintf_hex(char *buf, size_t size, unsigned char *data, size_t len)
size_t i;
for (i = 0; i < len; i++)
ret += snprintf(buf + ret, size - ret, "%02x", data[i]);
ret += scnprintf(buf + ret, size - ret, "%02x", data[i]);
return ret;
}
@ -140,7 +140,7 @@ static int synthesize_bpf_prog_name(char *buf, int size,
const struct btf_type *t;
int name_len;
name_len = snprintf(buf, size, "bpf_prog_");
name_len = scnprintf(buf, size, "bpf_prog_");
name_len += snprintf_hex(buf + name_len, size - name_len,
prog_tags[sub_id], BPF_TAG_SIZE);
if (btf) {
@ -153,9 +153,10 @@ static int synthesize_bpf_prog_name(char *buf, int size,
short_name = info->name;
} else
short_name = "F";
if (short_name)
name_len += snprintf(buf + name_len, size - name_len,
"_%s", short_name);
if (short_name) {
name_len += scnprintf(buf + name_len, size - name_len,
"_%s", short_name);
}
return name_len;
}