Skip to contentSkip to conversation

perf bench: Fix undefined behavior in cmpworker()

PATCH Superseded Kuan-Wei Chiu 1 participant 2 messages Dec 9, 2024

Subsystems (2)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

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

The comparison function cmpworker() does not comply with the C standard's requirements for qsort() comparison functions. Specifically, it returns 0 when w1->tid < w2->tid, which is incorrect. According to the standard, the function must return a negative value in such cases to preserve proper ordering.

This violation causes undefined behavior, potentially leading to issues such as memory corruption in certain versions of 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")
---
 tools/perf/bench/epoll-wait.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/perf/bench/epoll-wait.c +1 -1
index ef5c4257844d..4868d610e9bf 100644
@@ -420,7 +420,7 @@ 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;
+	return w1->tid > w2->tid ? 1 : -1;
 }
 
 int bench_epoll_wait(int argc, const char **argv)
Signature · 1 line
2.34.1
#1 lore raw
Quoted 6 lines · Kuan-Wei Chiu

The comparison function cmpworker() does not comply with the C standard's requirements for qsort() comparison functions. Specifically, it returns 0 when w1->tid < w2->tid, which is incorrect. According to the standard, the function must return a negative value in such cases to preserve proper ordering.

Quoted 6 lines

This violation causes undefined behavior, potentially leading to issues such as memory corruption in certain versions of glibc [1].

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

I reviewed my commit message again and thought it might be clearer to explicitly mention, as in the previous patch, that the issue stems from violating symmetry and transitivity. The current cmpworker() can result in x > y but y = x, leading to undefined behavior. I'll wait for review comments before updating the patch description.

Regards,
Kuan-Wei