]> git.kaiwu.me - njs.git/commitdiff
Fixed endless loop in Array.prototype.sort().
authorDmitry Volyntsev <xeioex@nginx.com>
Tue, 2 Jun 2020 14:59:30 +0000 (14:59 +0000)
committerDmitry Volyntsev <xeioex@nginx.com>
Tue, 2 Jun 2020 14:59:30 +0000 (14:59 +0000)
With non-consistent comparison function.

The issue was introduced in 1d0825906438.

src/njs_utils.c
src/test/njs_unit_test.c

index 065566c8d1562cd5a8db0f4959028f78bebb2ea7..c58cf34292a578ffb91d6ecf927a886fc0cae883 100644 (file)
@@ -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);
             }
         }
     }
index bdc439690cc73944946e71f986e1abd32ed570ba..7f89a1c513ecdd0c8b61325d1a20a7b11e7e429d 100644 (file)
@@ -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") },