Function qsort_r() is not thread-safe. This results to division by zero if two threads call it at the same time, and both sort more than 1024 bytes of data. Function contains code fragment -- [A] if (phys_pages == 0) { phys_pages = sysconf() ... pagesize = sysconf() } [B] if (size / pagesize > phys_pages) -- The first thread detects phys_pages being zero on [A] and may not yet have assigned pagesize, when the second thread enters the code, sees phys_pages being nonzero at [A], and performs division by zero pagesize at [B]. BR -- Tero Mononen <tmo@iki.fi>
Created attachment 5152 [details] qsort_r-for-thread-safety.patch The same problem occurs in my environment too. I tried to create a patch and I attached the same patch file as following. Is my patch reasonable? Could you please check the my patch ? Thanks in advance, diff --git a/stdlib/msort.c b/stdlib/msort.c index 35cd4d0..2cc2abc 100644 --- a/stdlib/msort.c +++ b/stdlib/msort.c @@ -182,7 +182,7 @@ qsort_r (void *b, size_t n, size_t s, __compar_d_fn_t cmp, void *arg) static long int phys_pages; static int pagesize; - if (phys_pages == 0) + if (phys_pages == 0 || pagesize == 0) { phys_pages = __sysconf (_SC_PHYS_PAGES);
I used a slightly cheaper patch.
Created attachment 5154 [details] qsort.c The status is already RESOLVED, but just for information. I created a test program to reproduce this bug. You can reproduce by following step. # gcc -pthread qsort.c -o qsort # while [ 0 ] ; do ./qsort ; done Floating point exception It takes a few minutes to reproduce on my machine has 2 CPU and 2G memory.
Created attachment 5648 [details] Corrected test case (original has several bugs; does not test what it alleges to test)
Thank you very much for correcting the test case.