Re: [PATCH 08/11] perf bpf: Use scnprintf() in snprintf_hex() and synthesize_bpf_prog_name()
From: Ian Rogers
Date: Mon Jun 08 2026 - 18:06:48 EST
On Mon, Jun 8, 2026 at 1:18 PM Arnaldo Carvalho de Melo <acme@xxxxxxxxxx> wrote:
>
> From: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>
>
> 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: 7b612e291a5affb1 ("perf tools: Synthesize PERF_RECORD_* for loaded BPF programs")
> Reported-by: sashiko-bot <sashiko-bot@xxxxxxxxxx>
> Cc: Song Liu <song@xxxxxxxxxx>
> Assisted-by: Claude Opus 4.6 <noreply@xxxxxxxxxxxxx>
> Signed-off-by: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>
Reviewed-by: Ian Rogers <irogers@xxxxxxxxxx>
Thanks,
Ian
> ---
> tools/perf/util/bpf-event.c | 11 ++++++-----
> 1 file changed, 6 insertions(+), 5 deletions(-)
>
> diff --git a/tools/perf/util/bpf-event.c b/tools/perf/util/bpf-event.c
> index a27945c279efb779..2c09842469f1f28c 100644
> --- a/tools/perf/util/bpf-event.c
> +++ b/tools/perf/util/bpf-event.c
> @@ -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;
> }
>
> --
> 2.54.0
>