Skip to content

libc/stdlib: recurse into the smaller qsort() partition - #7652

Open
hyunjongkim123 wants to merge 1 commit into
Samsung:masterfrom
hyunjongkim123:fix_crash_lib_libc_stdlib
Open

hyunjongkim123 wants to merge 1 commit into
Samsung:masterfrom
hyunjongkim123:fix_crash_lib_libc_stdlib

Conversation

@hyunjongkim123

@hyunjongkim123 hyunjongkim123 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

qsort() always recursed into the left partition and iterated over the right one, so the recursion depth depends on how the pivots fall and can approach nmemb / 2 in the worst case.

Compare the two partitions, recurse into the smaller one and loop on the larger one instead. Each recursion then handles at most half of the remaining elements, so the depth is bounded by log2(nmemb) for any input order and the stack qsort() needs stays at a few hundred bytes. This is the form the upstream FreeBSD qsort.c.

@seokhun-eom24

Copy link
Copy Markdown
Contributor

Could you link the reference you mentioned in commit?

@hyunjongkim123
hyunjongkim123 force-pushed the fix_crash_lib_libc_stdlib branch from 18f765c to abe6073 Compare November 30, 2026 01:17
@hyunjongkim123

Copy link
Copy Markdown
Contributor Author

Could you link the reference you mentioned in commit?

The reference I can point to directly is the upstream FreeBSD qsort.c
this file is derived from, which recurses into the smaller partition and
loops on the larger one (the d1 <= d2 branch near the end of qsort()):
https://github.com/freebsd/freebsd-src/blob/main/lib/libc/stdlib/qsort.c

I also cited Hoare 1962 / Sedgewick 1978 as the textbook source in the
commit message, but I cannot link a freely readable copy of either paper,
so I have dropped that sentence and replaced it with the FreeBSD link.

Comment thread lib/libc/stdlib/lib_qsort.c Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you update hrere?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the description.

@hyunjongkim123
hyunjongkim123 force-pushed the fix_crash_lib_libc_stdlib branch from abe6073 to 1bfc6fa Compare December 1, 2026 01:45
qsort() always recursed into the left partition and iterated over the
right one, so the recursion depth depends on how the pivots fall and
can approach nmemb / 2 in the worst case.

Compare the two partitions, recurse into the smaller one and loop on
the larger one instead. Each recursion then handles at most half of the
remaining elements, so the depth is bounded by log2(nmemb) for any
input order and the stack qsort() needs stays at a few hundred bytes.
This is the form the upstream FreeBSD qsort.c, which this file is
derived from, uses today:
https://github.com/freebsd/freebsd-src/blob/main/lib/libc/stdlib/qsort.c
The number of comparisons and swaps is unchanged.

Verified against glibc qsort() on random, sorted, reversed, alternating
and a 100k-element adversarial permutation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@hyunjongkim123
hyunjongkim123 force-pushed the fix_crash_lib_libc_stdlib branch from 1bfc6fa to 3bee4cf Compare December 1, 2026 06:04
@seokhun-eom24

Copy link
Copy Markdown
Contributor

🤖 AI Code Review · 3bee4cf15889

PR Summary: The qsort implementation is modified to recurse into the smaller partition and iterate (loop) on the larger one, instead of always recursing on the left and iterating on the right. This bounds recursion depth at log2(nmemb) for adversarial inputs. The partitioning logic is unchanged; only the post-partition recursion/iteration strategy differs. The left partition starts at base and the right at pn - rr, both correctly handled in all branches.

📋 Findings Overview (0 issues)

✅ Checked with no findings: Memory Leaks, Crashes, Hangs, Correctness

@mangeshraut712 mangeshraut712 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against the merge-base (f1a9dc97); the branch is 17 commits behind master but the change is a single self-contained file. Not an approval — that's for a maintainer.

The claim holds, and it's dramatic under an adversarial comparator

I built lib/libc/stdlib/lib_qsort.c from master and from this branch on the host, instrumented the recursive call with a depth counter, and drove both with a McIlroy-style median-of-3 killer (values are "gas" until chosen as a pivot, then frozen so each split is 1 | n−1):

n         master depth    PR depth    log2(n)
1,000            217            5       10.0
4,000            875            6       12.0
16,000         3,419            7       14.0
64,000        13,613            9       16.0
256,000   STACK OVERFLOW       11       18.0

On master the depth grows linearly (about 0.21·n with my killer) and the process dies with a segfault at 256k elements. On this branch it grows logarithmically and tops out at 11. That's exactly the bound you describe.

One precision note on the wording: the description says the old depth "can approach nmemb / 2". I measured about 0.21·n rather than 0.5·n — my killer isn't optimal, so the constant differs, but the order of growth (linear, unbounded) is the same and that's what matters for the stack. "Can grow linearly with nmemb" would be the safest phrasing.

No behaviour change on ordinary inputs

On 200k elements across five shapes — sorted, reverse-sorted, all-equal, organ-pipe, random — both versions sort correctly and produce byte-identical output to each other and to libc qsort. Random-input depth drops from 21 (master) to 11 (this branch) as a bonus, though master is already shallow on all five (the med3 pivot does its job there), so the real value of this change is entirely in the adversarial case above.

The diff itself

  • rl = pb - pa / rr = pd - pc are the left and right partition byte sizes; recursing on the smaller and goto loop on the larger is the standard form.
  • Right-partition base is pn - rr, left keeps base — both correct, and consistent with the old pn - r.
  • Both rl > size / rr > size guards are preserved in each arm, so 0- and 1-element partitions are skipped exactly as before.

One nit, not a blocker

The old comment on the right-hand branch ("Iterate rather than recurse to save stack space") is gone, which is right — it was only half true. The new block comment explains the invariant well.

Nice fix; this closes a genuine stack-exhaustion vector in a libc primitive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants