Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / engine / array_buffers.lucb

#==============================================================================================
#
#   array_buffers - ArrayBuffer and SharedArrayBuffer objects: creation, finalization,
#                   detaching and the accessors
#
#   DESCRIPTION:
#       Port of quickjs.c "Typed Arrays" (lines 56731-57116): the element sizes of the
#       typed array classes, the ArrayBuffer constructors and host API, the finalizer,
#       ArrayBuffer.isView, the byteLength/maxByteLength/resizable/detached getters,
#       js_array_buffer_update_typed_arrays and JS_DetachArrayBuffer. An ArrayBuffer's
#       views (typed arrays and DataViews) are linked in its `array_list`.
#
#==============================================================================================

# mark: Element sizes ===========================================================================

# The log2 of the element size of each typed array class, from ClassId.uint8c_array.
let typed_array_size_log2_table: u8[12] = [
    0, 0, 0, 1, 1, 2, 2,
    3, 3,                   # BigInt64Array, BigUint64Array
    1, 2, 3,                # Float16Array, Float32Array, Float64Array
]

## The log2 of the element size of the typed array class `classid` (typed_array_size_log2).
func typed_array_size_log2(classid: ClassId) -> i32:
    return (i32)typed_array_size_log2_table[(usize)((u16)classid - (u16)ClassId.uint8c_array)]

## Whether `class_id` is one of the typed array classes (Uint8ClampedArray to
## Float64Array).
func is_typed_array_class(class_id: ClassId) -> bool:
    return (u16)class_id >= (u16)ClassId.uint8c_array and (u16)class_id <= (u16)ClassId.float64_array

# mark: Creating ArrayBuffers ===================================================================

## Whether `f` is js_array_buffer_free, the free function of buffers the engine allocates.
func is_array_buffer_free(f: FreeArrayBufferDataFunc?) -> bool:
    if let g = f:
        return (void*)g == (void*)js_array_buffer_free
    return false

## A new ArrayBuffer or SharedArrayBuffer (`class_id`) of `len` bytes. With `alloc_flag`
## its storage is allocated (and `buf`, if given, copied into it); without, it adopts
## `buf`, which `free_func` releases.
func js_array_buffer_constructor3(ctx: Context*, new_target: Value, len: u64, max_len: u64*?,
                                  class_id: ClassIdValue, buf: u8*?,
                                  free_func: FreeArrayBufferDataFunc?, opaque: void*?,
                                  alloc_flag: bool) -> Value!:
    let rt = ctx.rt

    if not alloc_flag and buf != none and max_len != none and not is_array_buffer_free(free_func):
        # not observable from JS land, only through C API misuse;
        # JS code cannot create externally managed buffers directly
        try js_throw_internal_error(ctx, "resizable ArrayBuffers not supported for externally managed buffers")
    let obj = try js_create_from_ctor(ctx, new_target, (u32)class_id)
    errdefer js_free_value(ctx, obj)
    # XXX: we are currently limited to 2 GB
    if len > 0x7fffffff:
        try js_throw_range_error(ctx, "invalid array buffer length")
    if let m = max_len:
        if *m > 0x7fffffff:
            try js_throw_range_error(ctx, "invalid max array buffer length")
    let abuf = (ArrayBuffer*)(try js_malloc(ctx, memory.size_of(ArrayBuffer)))
    errdefer js_free(ctx, abuf)
    abuf.byte_length = (i32)len
    abuf.max_byte_length = -1
    if let m = max_len:
        abuf.max_byte_length = (i32)*m
    if alloc_flag:
        if class_id == (u32)ClassId.shared_array_buffer and rt.sab_funcs.sab_alloc != none:
            let sab_alloc = rt.sab_funcs.sab_alloc else trap("unreachable")
            # TOOD(bnoordhuis) resizing backing memory for SABs atomically
            # is hard so we cheat and allocate |maxByteLength| bytes upfront
            var sab_alloc_len = len
            if let m = max_len:
                sab_alloc_len = *m
            # (as in C, a failed host allocation reports no exception)
            let data = sab_alloc(rt.sab_funcs.sab_opaque,
                                 (usize)cutils.max_int((i32)sab_alloc_len, 1)) else error(exception, "")
            abuf.data = (u8*)data
            _ = cutils.memset(data, 0, (usize)sab_alloc_len)
        else:
            # the allocation must be done after the object creation
            abuf.data = (u8*)(try js_mallocz(ctx, (usize)cutils.max_int((i32)len, 1)))
    else:
        if class_id == (u32)ClassId.shared_array_buffer:
            if let sab_dup = rt.sab_funcs.sab_dup:
                sab_dup(rt.sab_funcs.sab_opaque, buf)
        abuf.data = buf
    cutils.init_list_head(&abuf.array_list)
    abuf.detached = 0
    abuf.shared = (u8)(class_id == (u32)ClassId.shared_array_buffer)
    abuf.opaque = opaque
    abuf.free_func = free_func
    if alloc_flag:
        if let src = buf:
            _ = cutils.memcpy(abuf.data, src, (usize)len)
    js_set_opaque(obj, abuf)
    return obj

## Release the storage of an ArrayBuffer allocated by the engine.
func js_array_buffer_free(rt: Runtime*, opaque: void*?, ptr: void*?):
    js_free_rt(rt, ptr)

## A new ArrayBuffer or SharedArrayBuffer (`class_id`) of `len` zeroed bytes.
func js_array_buffer_constructor2(ctx: Context*, new_target: Value, len: u64, max_len: u64*?,
                                  class_id: ClassIdValue) -> Value!:
    return try js_array_buffer_constructor3(ctx, new_target, len, max_len, class_id,
                                            none, js_array_buffer_free, none, true)

## A new ArrayBuffer of `len` zeroed bytes.
func js_array_buffer_constructor1(ctx: Context*, new_target: Value, len: u64, max_len: u64*?) -> Value!:
    return try js_array_buffer_constructor2(ctx, new_target, len, max_len, (u32)ClassId.array_buffer)

## An ArrayBuffer (or a SharedArrayBuffer if `is_shared`) over the host's `buf` of `len`
## bytes, which `free_func` releases with `opaque` (JS_NewArrayBuffer).
pub func js_new_array_buffer(ctx: Context*, buf: u8*?, len: usize, free_func: FreeArrayBufferDataFunc?,
                             opaque: void*?, is_shared: bool) -> Value!:
    var class_id = (u32)ClassId.array_buffer
    if is_shared:
        class_id = (u32)ClassId.shared_array_buffer
    return try js_array_buffer_constructor3(ctx, js_undefined(), (u64)len, none, class_id,
                                            buf, free_func, opaque, false)

# create a new ArrayBuffer of length 'len' and copy 'buf' to it
## A new ArrayBuffer holding a copy of the `len` bytes at `buf` (JS_NewArrayBufferCopy).
pub func js_new_array_buffer_copy(ctx: Context*, buf: const u8*, len: usize) -> Value!:
    return try js_array_buffer_constructor3(ctx, js_undefined(), (u64)len, none,
                                            (u32)ClassId.array_buffer,
                                            (u8*)buf,
                                            js_array_buffer_free, none,
                                            true)

## The ArrayBuffer and SharedArrayBuffer constructors: `(length, options)`.
func js_array_buffer_constructor0(ctx: Context*, new_target: Value, argc: i32, argv: Value*,
                                  class_id: ClassIdValue) -> Value!:
    var len: u64 = 0
    var max_len: u64 = 0
    var pmax_len: u64*? = none

    try js_to_index(ctx, &len, argv[0])
    if argc >= 2 and js_is_object(argv[1]):
        let obj = try js_to_object(ctx, argv[1])
        let val = js_get_property(ctx, obj, atom_maxByteLength) catch failure:
            js_free_value(ctx, obj)
            error(failure.code, failure.message)
        js_free_value(ctx, obj)
        if not js_is_undefined(val):
            var i: i64 = 0
            try js_to_int64_free(ctx, &i, val)
            # don't have to check i < 0 because len >= 0
            if (i64)len > i or i > max_safe_integer:
                try js_throw_range_error(ctx, "invalid array buffer max length")
            max_len = (u64)i
            pmax_len = &max_len
    return try js_array_buffer_constructor2(ctx, new_target, len, pmax_len, class_id)

func js_array_buffer_constructor(ctx: Context*, new_target: Value, argc: i32, argv: Value*) -> Value!:
    return try js_array_buffer_constructor0(ctx, new_target, argc, argv, (u32)ClassId.array_buffer)

func js_shared_array_buffer_constructor(ctx: Context*, new_target: Value, argc: i32, argv: Value*) -> Value!:
    return try js_array_buffer_constructor0(ctx, new_target, argc, argv, (u32)ClassId.shared_array_buffer)

# mark: Finalizer and isView ====================================================================

# also used for SharedArrayBuffer
## Release an ArrayBuffer's storage and cut its views off from it.
func js_array_buffer_finalizer(rt: Runtime*, val: Value):
    let p = val.u.obj
    let opaque = p.u.opaque else return
    let abuf = (ArrayBuffer*)opaque
    # The ArrayBuffer finalizer may be called before the typed array finalizers using
    # it, so abuf.array_list is not necessarily empty.
    let head = &abuf.array_list
    var el = head.next else trap("unlinked array_list")
    while el != head:
        let el1 = el.next else trap("unlinked array_list")
        let ta = (TypedArray*)((u8*)el - memory.offset_of(TypedArray, link))
        ta.link.prev = none
        ta.link.next = none
        let p1 = ta.obj
        # Note: the typed array length and offset fields are not modified
        if p1.class_id != ClassId.dataview:
            p1.u.array.count = 0
            p1.u.array.u.ptr = none
        el = el1
    let sab_free = rt.sab_funcs.sab_free
    if abuf.shared != 0 and sab_free != none:
        let f = sab_free else trap("unreachable")
        f(rt.sab_funcs.sab_opaque, abuf.data)
    else:
        if let free_func = abuf.free_func:
            free_func(rt, abuf.opaque, abuf.data)
    js_free_rt(rt, abuf)

func js_array_buffer_is_view(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var res = false
    if argv[0].tag == Tag.object:
        let p = argv[0].u.obj
        if ((u16)p.class_id >= (u16)ClassId.uint8c_array and (u16)p.class_id <= (u16)ClassId.dataview):
            res = true
    return js_new_bool(res)

let js_array_buffer_funcs: CFunctionListEntry[2] = [
    CFunctionListEntry(name = "isView", def_type = def_cfunc, length = 1, generic = js_array_buffer_is_view),
    CFunctionListEntry(name = "[Symbol.species]", prop_flags = 1, def_type = def_cgetset, getter = js_get_this),
]

# mark: Errors and accessors ====================================================================

func js_throw_type_error_detached_array_buffer(ctx: Context*) -> never!:
    try js_throw_type_error(ctx, "ArrayBuffer is detached")

func js_throw_type_error_array_buffer_oob(ctx: Context*) -> never!:
    try js_throw_type_error(ctx, "ArrayBuffer is detached or resized")

# #sec-get-arraybuffer.prototype.detached
func js_array_buffer_get_detached(ctx: Context*, this_val: Value) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)ClassId.array_buffer))
    if abuf.shared != 0:
        try js_throw_type_error(ctx, "detached called on SharedArrayBuffer")
    return js_new_bool(abuf.detached != 0)

func js_array_buffer_get_byte_length(ctx: Context*, this_val: Value, class_id: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)class_id))
    # return 0 if detached
    return js_new_uint32((u32)abuf.byte_length)

func js_array_buffer_get_max_byte_length(ctx: Context*, this_val: Value, class_id: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)class_id))
    if array_buffer_is_resizable(abuf):
        return js_new_uint32((u32)abuf.max_byte_length)
    return js_new_uint32((u32)abuf.byte_length)

func js_array_buffer_get_resizable(ctx: Context*, this_val: Value, class_id: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)class_id))
    return js_new_bool(array_buffer_is_resizable(abuf))

# mark: Views and detaching =====================================================================

## After a resize, transfer or detach of `abuf`, recompute the length and storage of
## every typed array and DataView over it.
func js_array_buffer_update_typed_arrays(abuf: ArrayBuffer*):
    let len = (i64)abuf.byte_length
    let data = abuf.data
    # update lengths of all typed arrays backed by this array buffer
    let head = &abuf.array_list
    var el = head.next else trap("unlinked array_list")
    while el != head:
        let ta = (TypedArray*)((u8*)el - memory.offset_of(TypedArray, link))
        let p = ta.obj
        if p.class_id == ClassId.dataview:
            if ta.track_rab:
                if (i64)ta.offset < len:
                    ta.length = (u32)(len - (i64)ta.offset)
                else:
                    ta.length = 0
        else:
            p.u.array.count = 0
            p.u.array.u.ptr = none
            let size_log2 = (u32)typed_array_size_log2(p.class_id)
            let size_elem = (u32)1 << size_log2
            if ta.track_rab:
                if len >= (i64)ta.offset + (i64)size_elem:
                    p.u.array.count = (u32)((len - (i64)ta.offset) >> (i64)size_log2)
                    p.u.array.u.ptr = array_buffer_data_at(data, ta.offset)
            else:
                if len >= (i64)ta.offset + (i64)ta.length:
                    p.u.array.count = ta.length >> size_log2
                    p.u.array.u.ptr = array_buffer_data_at(data, ta.offset)
        el = el.next else trap("unlinked array_list")

## `&data[offset]`, none when the buffer has no storage.
func array_buffer_data_at(data: u8*?, offset: u32) -> void*?:
    if let d = data:
        return d + (usize)offset
    return none

## Detach the ArrayBuffer `obj`: release its storage and empty its views
## (JS_DetachArrayBuffer). Nothing if it is not an ArrayBuffer or already detached.
pub func js_detach_array_buffer(ctx: Context*, obj: Value):
    let opaque = js_get_opaque(obj, (u32)ClassId.array_buffer) else return
    let abuf = (ArrayBuffer*)opaque
    if abuf.detached != 0:
        return
    if let free_func = abuf.free_func:
        free_func(ctx.rt, abuf.opaque, abuf.data)
    abuf.data = none
    abuf.byte_length = 0
    abuf.detached = 1
    js_array_buffer_update_typed_arrays(abuf)

# get an ArrayBuffer or SharedArrayBuffer
func js_get_array_buffer_internal(ctx: Context*, obj: Value) -> ArrayBuffer*!:
    if obj.tag != Tag.object:
        try js_throw_type_error_invalid_class(ctx, (i32)ClassId.array_buffer)
    let p = obj.u.obj
    if p.class_id != ClassId.array_buffer and p.class_id != ClassId.shared_array_buffer:
        try js_throw_type_error_invalid_class(ctx, (i32)ClassId.array_buffer)
    return p.u.array_buffer

# WARNING: any JS call can detach the buffer and render the returned pointer invalid
## The storage of the ArrayBuffer `obj` and, in `*psize`, its length; none if it has no
## storage (JS_GetArrayBuffer). Fails if `obj` is not an ArrayBuffer or is detached.
pub func js_get_array_buffer(ctx: Context*, psize: usize*, obj: Value) -> u8*?!:
    *psize = 0
    let abuf = try js_get_array_buffer_internal(ctx, obj)
    if abuf.detached != 0:
        try js_throw_type_error_detached_array_buffer(ctx)
    *psize = (usize)abuf.byte_length
    return abuf.data

## Whether the ArrayBuffer is resizable (has a maxByteLength).
func array_buffer_is_resizable(abuf: const ArrayBuffer*) -> bool:
    return abuf.max_byte_length >= 0