Skip to contentSkip to conversation

perf bench: Fix undefined behavior in cmpworker()

PATCH Applied Kuan-Wei Chiu 3 participants 3 messages Jan 16, 2025 – Jan 20, 2025

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 perf bench: Fix undefined behavior in cmpworker()

The comparison function cmpworker() violates the C standard's requirements for qsort() comparison functions, which mandate symmetry and transitivity:

Symmetry: If x < y, then y > x.
Transitivity: If x < y and y < z, then x < z.

In its current implementation, cmpworker() incorrectly returns 0 when w1->tid < w2->tid, which breaks both symmetry and transitivity. This violation causes undefined behavior, potentially leading to issues such as memory corruption in glibc [1].

Fix the issue by returning -1 when w1->tid < w2->tid, ensuring compliance with the C standard and preventing undefined behavior.

Fixes 121dd9ea0116 ("perf bench: Add epoll parallel epoll_wait benchmark")

---
Changes in v3:
- Perform a full comparison for clarity, as suggested by James.

 tools/perf/bench/epoll-wait.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
tools/perf/bench/epoll-wait.c +6 -1
index ef5c4257844d..20fe4f72b4af 100644
@@ -420,7 +420,12 @@ static int cmpworker(const void *p1, const void *p2)
 
 	struct worker *w1 = (struct worker *) p1;
 	struct worker *w2 = (struct worker *) p2;
-	return w1->tid > w2->tid;
+
+	if (w1->tid > w2->tid)
+		return 1;
+	if (w1->tid < w2->tid)
+		return -1;
+	return 0;
 }
 
 int bench_epoll_wait(int argc, const char **argv)
Signature · 1 line
2.34.1
reviewer Reviewed-by on v3 1/1
#1 lore raw
Quoted 15 lines · Kuan-Wei Chiu

The comparison function cmpworker() violates the C standard's requirements for qsort() comparison functions, which mandate symmetry and transitivity:

Symmetry: If x < y, then y > x.
Transitivity: If x < y and y < z, then x < z.

In its current implementation, cmpworker() incorrectly returns 0 when w1->tid < w2->tid, which breaks both symmetry and transitivity. This violation causes undefined behavior, potentially leading to issues such as memory corruption in glibc [1].

Fix the issue by returning -1 when w1->tid < w2->tid, ensuring compliance with the C standard and preventing undefined behavior.

Quoted 8 lines
Fixes 121dd9ea0116 ("perf bench: Add epoll parallel epoll_wait benchmark")

---
Changes in v3:
- Perform a full comparison for clarity, as suggested by James.

maintainer Applied
#2 lore raw
In reply to Kuan-Wei Chiu
Quoted 8 lines · Kuan-Wei Chiu

The comparison function cmpworker() violates the C standard's requirements for qsort() comparison functions, which mandate symmetry and transitivity:

Symmetry: If x < y, then y > x.
Transitivity: If x < y and y < z, then x < z.

[...]

Applied to perf-tools-next, thanks!

Best regards,
Namhyung