Skip to content

Commit e93cca6

Browse files
committed
Fix integer overflow in the TypedArray sort index array allocation
1 parent 35e195c commit e93cca6

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

‎api-test.c‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1390,6 +1390,48 @@ static void detach_array_buffer_free_once(void)
13901390
JS_FreeRuntime(rt);
13911391
}
13921392

1393+
static void free_array_buffer_data(JSRuntime *rt, void *opaque, void *ptr)
1394+
{
1395+
free(ptr);
1396+
}
1397+
1398+
static void typed_array_sort_index_overflow(void)
1399+
{
1400+
const size_t len = 0x40000010; /* 2**30 + 16 */
1401+
JSMemoryUsage stats;
1402+
JSValue global, buffer, ret;
1403+
JSRuntime *rt;
1404+
JSContext *ctx;
1405+
uint8_t *buf;
1406+
1407+
/* the data is never read, but keep it real memory so a regression
1408+
corrupts the heap in a way ASan can see rather than segfaulting */
1409+
buf = calloc(1, len);
1410+
rt = new_runtime();
1411+
ctx = JS_NewContext(rt);
1412+
1413+
buffer = JS_NewArrayBuffer(ctx, buf, len, free_array_buffer_data, NULL,
1414+
false);
1415+
assert(JS_IsArrayBuffer(buffer));
1416+
global = JS_GetGlobalObject(ctx);
1417+
JS_SetPropertyStr(ctx, global, "buf", buffer);
1418+
JS_FreeValue(ctx, global);
1419+
1420+
/* Cap memory so that the correctly computed 4 GB index array also
1421+
fails to allocate on 64 bit platforms; the undersized allocation a
1422+
32 bit platform computes fits well within the cap. */
1423+
JS_ComputeMemoryUsage(rt, &stats);
1424+
JS_SetMemoryLimit(rt, (size_t)stats.malloc_size + 1024 * 1024);
1425+
1426+
ret = eval(ctx, "new Uint8Array(buf).sort((a, b) => a - b)");
1427+
assert(JS_IsException(ret));
1428+
assert(JS_HasException(ctx));
1429+
JS_FreeValue(ctx, ret);
1430+
1431+
JS_FreeContext(ctx);
1432+
JS_FreeRuntime(rt);
1433+
}
1434+
13931435
int main(void)
13941436
{
13951437
cfunctions();
@@ -1418,5 +1460,6 @@ int main(void)
14181460
new_symbol();
14191461
bulk_free_macros();
14201462
detach_array_buffer_free_once();
1463+
typed_array_sort_index_overflow();
14211464
return 0;
14221465
}

‎quickjs.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61107,7 +61107,7 @@ static JSValue js_typed_array_sort(JSContext *ctx, JSValueConst this_val,
6110761107
size_t i, j;
6110861108

6110961109
/* XXX: a stable sort would use less memory */
61110-
array_idx = js_malloc(ctx, len * sizeof(array_idx[0]));
61110+
array_idx = js_calloc(ctx, len, sizeof(array_idx[0]));
6111161111
if (!array_idx)
6111261112
return JS_EXCEPTION;
6111361113
for(i = 0; i < len; i++)

0 commit comments

Comments
 (0)