Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 59bf184

Browse files
committedDec 24, 2024·
Fix undefined behavior in qsort comparison functions for rv_histogram
The freq variable is of type size_t, but the qsort comparison functions were directly returning a->freq - b->freq, which implicitly converts the result to an int. This conversion can cause overflow, leading to implementation-defined behavior. When freq values are sufficiently large, this issue may violate the antisymmetric and transitive properties required for comparison functions: Antisymmetry: If a < b, then b > a. Transitivity: If a < b and b < c, then a < c. Violating these properties results in undefined behavior in qsort, which could trigger memory corruption in some glibc implementations, posing a potential security risk. [1] Rewrite the comparison functions (cmp_dec and cmp_asc) to compare size_t values explicitly, ensuring correctness and avoiding overflow. Link: https://www.qualys.com/2024/01/30/qsort.txt [1]
1 parent f69d9dd commit 59bf184

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed
 

‎tools/rv_histogram.c

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,26 @@ static rv_hist_t rv_reg_stats[] = {
5151

5252
static int cmp_dec(const void *a, const void *b)
5353
{
54-
return ((rv_hist_t *) b)->freq - ((rv_hist_t *) a)->freq;
54+
const size_t a_freq = ((rv_hist_t *) a)->freq;
55+
const size_t b_freq = ((rv_hist_t *) b)->freq;
56+
57+
if (a_freq > b_freq)
58+
return -1;
59+
if (a_freq < b_freq)
60+
return 1;
61+
return 0;
5562
}
5663

5764
static int cmp_asc(const void *a, const void *b)
5865
{
59-
return ((rv_hist_t *) a)->freq - ((rv_hist_t *) b)->freq;
66+
const size_t a_freq = ((rv_hist_t *) a)->freq;
67+
const size_t b_freq = ((rv_hist_t *) b)->freq;
68+
69+
if (a_freq < b_freq)
70+
return -1;
71+
if (a_freq > b_freq)
72+
return 1;
73+
return 0;
6074
}
6175

6276
/* used to adjust the length of histogram bar */

0 commit comments

Comments
 (0)
Please sign in to comment.