Skip to content

Commit

Permalink
Fixed Array.prototype.sort() with --debug=YES and --debug-memory=YES.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
xeioex committed Oct 6, 2023
1 parent f781317 commit 280d112
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/njs_array.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down
8 changes: 8 additions & 0 deletions src/njs_mp.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down

0 comments on commit 280d112

Please sign in to comment.