From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 2178) id 08D863858D35; Wed, 8 Nov 2023 14:18:26 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 08D863858D35 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sourceware.org; s=default; t=1699453106; bh=xIEZIL2xkxtR94CPyNPKB9hnFpJObrRN7gr5gDi4PDc=; h=From:To:Subject:Date:From; b=j7kcdVO31xANIFBENInUrtjejsvLBsd2+NhGfj/6+PnOEHQrotbf7HRqidMcmbav7 ZC+sOaoQeKzd8VeRb4dAoYmCa8kvCpxWpZLEwmvja5+ODgNZwJAwN5xqZX4YizM6T6 sd7KaRku5dmL/Riy2RBXWUV0ZwqhBmpF1yk5DXI0= Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: Florian Weimer To: glibc-cvs@sourceware.org Subject: [glibc] stdlib: Avoid element self-comparisons in qsort X-Act-Checkin: glibc X-Git-Author: Florian Weimer X-Git-Refname: refs/heads/master X-Git-Oldrev: bf033c0072554366fe9617c283c982594059ad9d X-Git-Newrev: f8cfb6836e8d91bb789b2e7fd65338d6f5bd459c Message-Id: <20231108141826.08D863858D35@sourceware.org> Date: Wed, 8 Nov 2023 14:18:26 +0000 (GMT) List-Id: https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=f8cfb6836e8d91bb789b2e7fd65338d6f5bd459c commit f8cfb6836e8d91bb789b2e7fd65338d6f5bd459c Author: Florian Weimer Date: Wed Nov 8 15:18:02 2023 +0100 stdlib: Avoid element self-comparisons in qsort This improves compatibility with applications which assume that qsort does not invoke the comparison function with equal pointer arguments. The newly introduced branches should be predictable, as leading to a call to the comparison function. If the prediction fails, we avoid calling the function. Reviewed-by: Adhemerval Zanella Diff: --- stdlib/qsort.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/stdlib/qsort.c b/stdlib/qsort.c index fd32a165e7..ad110e8a89 100644 --- a/stdlib/qsort.c +++ b/stdlib/qsort.c @@ -136,7 +136,7 @@ siftdown (void *base, size_t size, size_t k, size_t n, if (j < n && cmp (base + (j * size), base + ((j + 1) * size), arg) < 0) j++; - if (cmp (base + (k * size), base + (j * size), arg) >= 0) + if (j == k || cmp (base + (k * size), base + (j * size), arg) >= 0) break; do_swap (base + (size * j), base + (k * size), size, swap_type); @@ -332,10 +332,12 @@ __qsort_r (void *const pbase, size_t total_elems, size_t size, that this algorithm runs much faster than others. */ do { - while ((*cmp) ((void *) left_ptr, (void *) mid, arg) < 0) + while (left_ptr != mid + && (*cmp) ((void *) left_ptr, (void *) mid, arg) < 0) left_ptr += size; - while ((*cmp) ((void *) mid, (void *) right_ptr, arg) < 0) + while (right_ptr != mid + && (*cmp) ((void *) mid, (void *) right_ptr, arg) < 0) right_ptr -= size; if (left_ptr < right_ptr)