]> git.kaiwu.me - njs.git/commitdiff
Fixed Array.prototype.sort() with --debug=YES and --debug-memory=YES.
authorDmitry Volyntsev <xeioex@nginx.com>
Fri, 6 Oct 2023 23:52:23 +0000 (16:52 -0700)
committerDmitry Volyntsev <xeioex@nginx.com>
Fri, 6 Oct 2023 23:52:23 +0000 (16:52 -0700)
Previously, --debug-memory=YES activated a different allocation
mechanism that was not able to properly handle the 0 size allocation.
Specifically, njs_mp_free() failed to find a block to free when the size
of the block is 0.

The fix is to alloc at least 1 byte in the --debug-memory=YES mode.

src/njs_array.c
src/njs_mp.c

index e8d1c6bd809f1223747a91a07fdbfd84fb34e01c..d7701bb73c65b2de70ad51c36b7dc4e6e70e7c63 100644 (file)
@@ -2782,6 +2782,8 @@ njs_sort_indexed_properties(njs_vm_t *vm, njs_value_t *obj, int64_t length,
     njs_array_sort_ctx_t   ctx;
     njs_array_sort_slot_t  *p, *end, *slots, *newslots;
 
+    njs_assert(length != 0);
+
     slots = NULL;
     keys = NULL;
     ctx.vm = vm;
@@ -2993,6 +2995,12 @@ njs_array_prototype_sort(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
         return ret;
     }
 
+    slots = NULL;
+
+    if (length == 0) {
+        goto done;
+    }
+
     /* Satisfy gcc -O3 */
     nslots = 0;
 
@@ -3027,6 +3035,8 @@ njs_array_prototype_sort(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
         }
     }
 
+done:
+
     njs_value_assign(retval, this);
 
     ret = NJS_OK;
@@ -3083,11 +3093,19 @@ njs_array_prototype_to_sorted(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
         return NJS_ERROR;
     }
 
-    slots = njs_sort_indexed_properties(vm, this, length, compare, 0, &nslots,
-                                        &nunds);
-    if (njs_slow_path(slots == NULL)) {
-        ret = NJS_ERROR;
-        goto exception;
+    if (length != 0) {
+        slots = njs_sort_indexed_properties(vm, this, length, compare, 0,
+                                            &nslots, &nunds);
+        if (njs_slow_path(slots == NULL)) {
+            ret = NJS_ERROR;
+            goto exception;
+        }
+
+    } else {
+        slots = NULL;
+        length = 0;
+        nslots = 0;
+        nunds = 0;
     }
 
     njs_assert(length == (nslots + nunds));
index 5be4b7e71ac9591933371ce449eff6a272b59044..4288343e9addaf041c6c1f562b3ae22c25a86037 100644 (file)
@@ -592,6 +592,14 @@ njs_mp_alloc_large(njs_mp_t *mp, size_t alignment, size_t size)
         return NULL;
     }
 
+#if (NJS_DEBUG)
+    /*
+     * Ensure that the size is not zero, otherwise njs_mp_find_block()
+     * will not be able to find the block.
+     */
+    size += size == 0;
+#endif
+
     if (njs_is_power_of_two(size)) {
         block = njs_malloc(sizeof(njs_mp_block_t));
         if (njs_slow_path(block == NULL)) {