changeset 2570:7ade97e7d376

Fixed %TypedArray%.prototype.slice() with overlapping buffers.
author Dmitry Volyntsev <xeioex@nginx.com>
date Thu, 12 Jun 2025 15:34:39 -0700
parents 37e1253f004f
children fe90cd2cad82
files src/njs_typed_array.c
diffstat 1 files changed, 15 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/src/njs_typed_array.c	Thu Jun 12 15:16:41 2025 -0700
+++ b/src/njs_typed_array.c	Thu Jun 12 15:34:39 2025 -0700
@@ -912,6 +912,20 @@
 }
 
 
+static void
+njs_slice_memcpy(uint8_t *dst, const uint8_t *src, size_t len)
+{
+    if (dst + len <= src || dst >= src + len) {
+        /* no overlap: can use memcpy */
+        memcpy(dst, src, len);
+
+    } else {
+        while (len-- != 0)
+            *dst++ = *src++;
+    }
+}
+
+
 njs_int_t
 njs_typed_array_prototype_slice(njs_vm_t *vm, njs_value_t *args,
     njs_uint_t nargs, njs_index_t copy, njs_value_t *retval)
@@ -990,7 +1004,7 @@
             start = start * element_size;
             count = count * element_size;
 
-            memcpy(&new_buffer->u.u8[0], &buffer->u.u8[start], count);
+            njs_slice_memcpy(&new_buffer->u.u8[0], &buffer->u.u8[start], count);
 
         } else {
             for (i = 0; i < count; i++) {