[PATCH v1] libperf mmap: In user mmap rdpmc avoid undefined behavior

Ian Rogers posted 1 patch 4 months, 3 weeks ago
tools/lib/perf/mmap.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH v1] libperf mmap: In user mmap rdpmc avoid undefined behavior
Posted by Ian Rogers 4 months, 3 weeks ago
A shift left of a signed 64-bit s64 may overflow and result in
undefined behavior caught by ubsan. Switch to a u64 instead.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/lib/perf/mmap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/lib/perf/mmap.c b/tools/lib/perf/mmap.c
index c1a51d925e0e..ec124eb0ec0a 100644
--- a/tools/lib/perf/mmap.c
+++ b/tools/lib/perf/mmap.c
@@ -508,7 +508,7 @@ int perf_mmap__read_self(struct perf_mmap *map, struct perf_counts_values *count
 		idx = READ_ONCE(pc->index);
 		cnt = READ_ONCE(pc->offset);
 		if (pc->cap_user_rdpmc && idx) {
-			s64 evcnt = read_perf_counter(idx - 1);
+			u64 evcnt = read_perf_counter(idx - 1);
 			u16 width = READ_ONCE(pc->pmc_width);
 
 			evcnt <<= 64 - width;
-- 
2.51.0.384.g4c02a37b29-goog
Re: [PATCH v1] libperf mmap: In user mmap rdpmc avoid undefined behavior
Posted by Arnaldo Carvalho de Melo 4 months, 1 week ago
On Sun, Sep 14, 2025 at 11:24:37AM -0700, Ian Rogers wrote:
> A shift left of a signed 64-bit s64 may overflow and result in
> undefined behavior caught by ubsan. Switch to a u64 instead.

Thanks, applied to perf-tools-next,

- Arnaldo
 
> Signed-off-by: Ian Rogers <irogers@google.com>
> ---
>  tools/lib/perf/mmap.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/tools/lib/perf/mmap.c b/tools/lib/perf/mmap.c
> index c1a51d925e0e..ec124eb0ec0a 100644
> --- a/tools/lib/perf/mmap.c
> +++ b/tools/lib/perf/mmap.c
> @@ -508,7 +508,7 @@ int perf_mmap__read_self(struct perf_mmap *map, struct perf_counts_values *count
>  		idx = READ_ONCE(pc->index);
>  		cnt = READ_ONCE(pc->offset);
>  		if (pc->cap_user_rdpmc && idx) {
> -			s64 evcnt = read_perf_counter(idx - 1);
> +			u64 evcnt = read_perf_counter(idx - 1);
>  			u16 width = READ_ONCE(pc->pmc_width);
>  
>  			evcnt <<= 64 - width;
> -- 
> 2.51.0.384.g4c02a37b29-goog
>