From: Dmitry Volyntsev Date: Tue, 2 Jun 2020 14:59:30 +0000 (+0000) Subject: Fixed endless loop in Array.prototype.sort(). X-Git-Url: http://git.kaiwu.me/postgresql/log/contrib/postgres_fdw/static/gitweb.js?a=commitdiff_plain;h=61789fbe833a15e5998dffd3e318404b00d97e1f;p=njs.git Fixed endless loop in Array.prototype.sort(). With non-consistent comparison function. The issue was introduced in 1d0825906438. --- diff --git a/src/njs_utils.c b/src/njs_utils.c index 065566c8..c58cf342 100644 --- a/src/njs_utils.c +++ b/src/njs_utils.c @@ -241,7 +241,7 @@ void njs_qsort(void *arr, size_t n, size_t esize, njs_sort_cmp_t cmp, void *ctx) { int r; - u_char *base, *lt, *gt, *p, *end; + u_char *base, *lt, *gt, *c, *p, *end; njs_uint_t m4; njs_swap_t swap; njs_qsort_state_t stack[NJS_MAX_DEPTH], *sp; @@ -321,9 +321,8 @@ njs_qsort(void *arr, size_t n, size_t esize, njs_sort_cmp_t cmp, void *ctx) /* Insertion sort. */ for (p = base + esize; p < end; p += esize) { - while (p > base && cmp(p, p - esize, ctx) < 0) { - swap(p, p - esize, esize); - p -= esize; + for (c = p; c > base && cmp(c, c - esize, ctx) < 0; c -= esize) { + swap(c, c - esize, esize); } } } diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index bdc43969..7f89a1c5 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -6101,6 +6101,9 @@ static njs_unit_test_t njs_test[] = "a.sort((a, b) => b.r - a.r).map(v=>v.n).join('')"), njs_str("BDEAC") }, + { njs_str("[1,2,3].sort(()=>-1)"), + njs_str("3,2,1") }, + { njs_str("var count = 0;" "[4,3,2,1].sort(function(x, y) { if (count++ == 2) {throw Error('Oops'); }; return x - y })"), njs_str("Error: Oops") },