[PATCH] selftests/perf_events: Fix mmap() error check in sigtrap_threads

Hongfu Li posted 1 patch 1 month ago
tools/testing/selftests/perf_events/watermark_signal.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH] selftests/perf_events: Fix mmap() error check in sigtrap_threads
Posted by Hongfu Li 1 month ago
In sigtrap_threads(), the return value of mmap() is checked against
NULL.  mmap() returns MAP_FAILED, which is (void *)-1, not NULL, when
it fails.  Since MAP_FAILED is non-zero and non-NULL, the condition
"p == NULL" will never be true on failure, causing the program to
proceed with an invalid pointer and segfault if mmap() actually fails
under memory pressure.

Signed-off-by: Hongfu Li <lihongfu@kylinos.cn>
---
 tools/testing/selftests/perf_events/watermark_signal.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/testing/selftests/perf_events/watermark_signal.c b/tools/testing/selftests/perf_events/watermark_signal.c
index 0f64b9b17081..a84709cabd8b 100644
--- a/tools/testing/selftests/perf_events/watermark_signal.c
+++ b/tools/testing/selftests/perf_events/watermark_signal.c
@@ -102,7 +102,7 @@ TEST(watermark_signal)
 	}
 
 	p = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
-	if (p == NULL) {
+	if (p == MAP_FAILED) {
 		perror("mmap");
 		goto cleanup;
 	}
-- 
2.25.1
Re: [PATCH] selftests/perf_events: Fix mmap() error check in sigtrap_threads
Posted by Wei Yang 1 month ago
On Wed, May 13, 2026 at 10:58:38AM +0800, Hongfu Li wrote:
>In sigtrap_threads(), the return value of mmap() is checked against
>NULL.  mmap() returns MAP_FAILED, which is (void *)-1, not NULL, when
>it fails.  Since MAP_FAILED is non-zero and non-NULL, the condition
>"p == NULL" will never be true on failure, causing the program to
>proceed with an invalid pointer and segfault if mmap() actually fails
>under memory pressure.
>
>Signed-off-by: Hongfu Li <lihongfu@kylinos.cn>

Ah, looks you are right.

Reviewed-by: Wei Yang <richard.weiyang@gmail.com>

>---
> tools/testing/selftests/perf_events/watermark_signal.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
>diff --git a/tools/testing/selftests/perf_events/watermark_signal.c b/tools/testing/selftests/perf_events/watermark_signal.c
>index 0f64b9b17081..a84709cabd8b 100644
>--- a/tools/testing/selftests/perf_events/watermark_signal.c
>+++ b/tools/testing/selftests/perf_events/watermark_signal.c
>@@ -102,7 +102,7 @@ TEST(watermark_signal)
> 	}
> 
> 	p = mmap(NULL, 2 * page_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
>-	if (p == NULL) {
>+	if (p == MAP_FAILED) {
> 		perror("mmap");
> 		goto cleanup;
> 	}
>-- 
>2.25.1

-- 
Wei Yang
Help you, Help me