From 8dcdb92047e4f15f65b4079eeeb55ca4eb5192c2 Mon Sep 17 00:00:00 2001 From: Null <35146309+BambooLqq@users.noreply.github.com> Date: Mon, 15 Apr 2024 12:40:00 +0800 Subject: [PATCH] fix crash in js_typed_array_slice caused by memory overlap (#379) Use memmove instead of memcpy to prevent UB. Fixes: https://github.com/quickjs-ng/quickjs/issues/378 Co-authored-by: zhang.yuping --- quickjs.c | 6 +++--- tests/test_builtin.js | 13 ++++++++++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/quickjs.c b/quickjs.c index 46e124a..bb23391 100644 --- a/quickjs.c +++ b/quickjs.c @@ -50327,9 +50327,9 @@ static JSValue js_typed_array_slice(JSContext *ctx, JSValue this_val, if (p1 != NULL && p->class_id == p1->class_id && typed_array_get_length(ctx, p1) >= count && typed_array_get_length(ctx, p) >= start + count) { - memcpy(p1->u.array.u.uint8_ptr, - p->u.array.u.uint8_ptr + (start << shift), - count << shift); + memmove(p1->u.array.u.uint8_ptr, + p->u.array.u.uint8_ptr + (start << shift), + count << shift); } else { for (n = 0; n < count; n++) { val = JS_GetPropertyValue(ctx, this_val, js_int32(start + n)); diff --git a/tests/test_builtin.js b/tests/test_builtin.js index e5ecb8c..22fc2e3 100644 --- a/tests/test_builtin.js +++ b/tests/test_builtin.js @@ -516,7 +516,7 @@ function test_eval() function test_typed_array() { - var buffer, a, i, str; + var buffer, a, i, str, b; a = new Uint8Array(4); assert(a.length, 4); @@ -569,6 +569,17 @@ function test_typed_array() assert(a.toString(), "1,2,3,4"); a.set([10, 11], 2); assert(a.toString(), "1,2,10,11"); + + a = new Uint8Array(buffer, 0, 4); + a.constructor = { + [Symbol.species]: function (len) { + return new Uint8Array(buffer, 1, len); + }, + }; + b = a.slice(); + assert(a.buffer, b.buffer); + assert(a.toString(), "0,0,0,255"); + assert(b.toString(), "0,0,255,255"); } function test_json()