Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions bridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#include "quickjs-libc.h"
#include "cutils.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef _WIN32
Expand Down Expand Up @@ -854,6 +856,20 @@ JSValue CreateClassInstance(JSContext *ctx, JSValue constructor,
return obj;
}

// ============================================================================
// ARRAY BUFFER HELPERS
// ============================================================================

void *QuickjsGoArrayBufferRealloc(JSRuntime *rt, void *opaque, void *ptr, size_t size) {
(void)rt;
(void)opaque;
if (size == 0) {
free(ptr);
return NULL;
}
return realloc(ptr, size);
}

// ============================================================================
// INTERRUPT HANDLERS
// ============================================================================
Expand Down
1 change: 1 addition & 0 deletions bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ extern void ClearInterruptHandler(JSRuntime *rt);
extern void SetExecuteTimeout(JSRuntime *rt, time_t timeout);
extern void SetPromiseRejectionTracker(JSRuntime *rt, int enabled);
extern int GetTimeoutOpaqueCount(void);
extern void *QuickjsGoArrayBufferRealloc(JSRuntime *rt, void *opaque, void *ptr, size_t size);

// Dynamic import (quickjs-ng v0.18.0+)
extern void SetDefaultDynamicImportFunc(JSRuntime *rt);
Expand Down
113 changes: 113 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (

/*
#include <stdint.h> // for uintptr_t
#include <stdlib.h>
#include <string.h>
#include "bridge.h"
*/
import "C"
Expand Down Expand Up @@ -484,14 +486,125 @@ func (ctx *Context) String(v string) *Value {
return ctx.NewString(v)
}

// ArrayBufferOptions configures NewArrayBufferFromBytes.
type ArrayBufferOptions struct {
// MaxByteLength enables a resizable ArrayBuffer when > len(data).
// 0 keeps a fixed-length buffer.
MaxByteLength int
}

// arrayBufferCallocHook overrides calloc for ArrayBuffer allocation in tests.
var arrayBufferCallocHook func(size int) unsafe.Pointer

func allocArrayBufferBytes(size int) unsafe.Pointer {
if hook := arrayBufferCallocHook; hook != nil {
return hook(size)
}
return C.calloc(1, C.size_t(size))
}

func forceArrayBufferCallocFailureForTest(enable bool) func() {
prev := arrayBufferCallocHook
if enable {
arrayBufferCallocHook = func(size int) unsafe.Pointer { return nil }
} else {
arrayBufferCallocHook = nil
}
return func() { arrayBufferCallocHook = prev }
}

// NewArrayBuffer returns a ArrayBuffer value with given binary data.
func (ctx *Context) NewArrayBuffer(binaryData []byte) *Value {
if !ctx.hasValidRef() {
return nil
}
if len(binaryData) == 0 {
return &Value{ctx: ctx, ref: C.JS_NewArrayBufferCopy(ctx.ref, nil, 0)}
}
return &Value{ctx: ctx, ref: C.JS_NewArrayBufferCopy(ctx.ref, (*C.uchar)(&binaryData[0]), C.size_t(len(binaryData)))}
}

// NewResizableArrayBuffer creates a zero-filled resizable ArrayBuffer owned by QuickJS.
// maxByteLength must be >= length.
func (ctx *Context) NewResizableArrayBuffer(length, maxByteLength int) *Value {
if !ctx.hasValidRef() || length < 0 || maxByteLength < length {
return nil
}
allocSize := maxByteLength
if allocSize == 0 {
allocSize = length
}
var buf unsafe.Pointer
if allocSize > 0 {
buf = allocArrayBufferBytes(allocSize)
if buf == nil {
return nil
}
}
return &Value{
ctx: ctx,
ref: C.JS_NewArrayBuffer(
ctx.ref,
(*C.uint8_t)(buf),
C.size_t(length),
C.size_t(maxByteLength),
(*C.JSReallocArrayBufferDataFunc)(C.QuickjsGoArrayBufferRealloc),
nil,
C.bool(false),
),
}
}

// NewArrayBufferFromBytes wraps or copies bytes into an ArrayBuffer.
// When MaxByteLength == 0, the slice is used zero-copy without a realloc callback;
// the caller must keep data alive until the ArrayBuffer is freed or detached.
// When MaxByteLength > 0, bytes are copied into a QuickJS-owned resizable buffer.
func (ctx *Context) NewArrayBufferFromBytes(data []byte, opts ArrayBufferOptions) *Value {
if !ctx.hasValidRef() {
return nil
}
if opts.MaxByteLength < 0 || (opts.MaxByteLength > 0 && opts.MaxByteLength < len(data)) {
return nil
}
if opts.MaxByteLength == 0 {
if len(data) == 0 {
return ctx.NewArrayBuffer(nil)
}
return &Value{
ctx: ctx,
ref: C.JS_NewArrayBuffer(
ctx.ref,
(*C.uint8_t)(unsafe.Pointer(&data[0])),
C.size_t(len(data)),
0,
nil,
nil,
C.bool(false),
),
}
}

buf := allocArrayBufferBytes(opts.MaxByteLength)
if buf == nil {
return nil
}
if len(data) > 0 {
C.memcpy(buf, unsafe.Pointer(&data[0]), C.size_t(len(data)))
}
return &Value{
ctx: ctx,
ref: C.JS_NewArrayBuffer(
ctx.ref,
(*C.uint8_t)(buf),
C.size_t(len(data)),
C.size_t(opts.MaxByteLength),
(*C.JSReallocArrayBufferDataFunc)(C.QuickjsGoArrayBufferRealloc),
nil,
C.bool(false),
),
}
}

// ArrayBuffer returns a ArrayBuffer value with given binary data.
// Deprecated: Use NewArrayBuffer() instead.
func (ctx *Context) ArrayBuffer(binaryData []byte) *Value {
Expand Down
8 changes: 8 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -1417,6 +1417,14 @@ func (v *Value) SetImmutableArrayBuffer(immutable bool) bool {
return C.JS_SetImmutableArrayBuffer(v.ref, C.bool(immutable)) == 0
}

// DetachArrayBuffer detaches the ArrayBuffer backing store.
func (v *Value) DetachArrayBuffer() {
if v == nil || !v.hasValidContext() || !v.IsByteArray() {
return
}
C.JS_DetachArrayBuffer(v.ctx.ref, v.ref)
}

// resolveClassIDFromInheritance attempts to resolve classID by checking if this constructor
// extends a registered class and should use the parent's classID
func (v *Value) resolveClassIDFromInheritance() (uint32, bool) {
Expand Down
84 changes: 84 additions & 0 deletions value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"math"
"math/big"
goruntime "runtime"
"sync/atomic"
"testing"

Expand Down Expand Up @@ -2471,6 +2472,89 @@ func TestValueCallConstructorComprehensive(t *testing.T) {
})
}

func TestResizableAndExternalArrayBuffer(t *testing.T) {
rt := NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()

ab := ctx.NewResizableArrayBuffer(4, 16)
require.NotNil(t, ab)
defer ab.Free()
require.True(t, ab.IsByteArray())

resized := ctx.Eval(`
(function(buf) {
buf.resize(8);
return buf.byteLength;
})
`)
defer resized.Free()
result := resized.Execute(ctx.NewUndefined(), ab)
defer result.Free()
require.False(t, result.IsException(), "%v", ctx.Exception())
require.EqualValues(t, 8, result.ToInt32())

data := []byte{1, 2, 3, 4}
ext := ctx.NewArrayBufferFromBytes(data, ArrayBufferOptions{})
require.NotNil(t, ext)
defer ext.Free()
bytes, err := ext.ToByteArray(4)
require.NoError(t, err)
require.Equal(t, data, bytes)
goruntime.KeepAlive(data)

copied := ctx.NewArrayBufferFromBytes([]byte{9, 8}, ArrayBufferOptions{MaxByteLength: 8})
require.NotNil(t, copied)
defer copied.Free()
require.True(t, copied.IsByteArray())

detachTarget := ctx.NewArrayBuffer([]byte{1, 2, 3, 4})
require.NotNil(t, detachTarget)
detachTarget.DetachArrayBuffer()
_, err = detachTarget.ToByteArray(4)
require.Error(t, err)
detachTarget.Free()

require.Nil(t, (*Context)(nil).NewResizableArrayBuffer(1, 2))
require.Nil(t, (*Context)(nil).NewArrayBuffer(nil))
require.Nil(t, (*Context)(nil).NewArrayBufferFromBytes(nil, ArrayBufferOptions{}))
require.Nil(t, ctx.NewResizableArrayBuffer(8, 4))
require.Nil(t, ctx.NewResizableArrayBuffer(-1, 0))
require.Nil(t, ctx.NewArrayBufferFromBytes([]byte{1}, ArrayBufferOptions{MaxByteLength: -1}))
require.Nil(t, ctx.NewArrayBufferFromBytes([]byte{1, 2, 3}, ArrayBufferOptions{MaxByteLength: 2}))

emptyResizable := ctx.NewResizableArrayBuffer(0, 0)
require.NotNil(t, emptyResizable)
emptyResizable.Free()

emptyExt := ctx.NewArrayBufferFromBytes(nil, ArrayBufferOptions{})
require.NotNil(t, emptyExt)
emptyExt.Free()

emptyCopy := ctx.NewArrayBufferFromBytes(nil, ArrayBufferOptions{MaxByteLength: 4})
require.NotNil(t, emptyCopy)
emptyCopy.Free()

restoreAlloc := forceArrayBufferCallocFailureForTest(true)
require.Nil(t, ctx.NewResizableArrayBuffer(4, 8))
require.Nil(t, ctx.NewArrayBufferFromBytes([]byte{1}, ArrayBufferOptions{MaxByteLength: 8}))
restoreAlloc()
_ = forceArrayBufferCallocFailureForTest(false)

notBuffer := ctx.NewString("x")
notBuffer.DetachArrayBuffer()
notBuffer.Free()

closedCtx := rt.NewContext()
closedCtx.Close()
require.Nil(t, closedCtx.NewArrayBuffer(nil))
require.Nil(t, closedCtx.NewResizableArrayBuffer(1, 2))
require.Nil(t, closedCtx.NewArrayBufferFromBytes(nil, ArrayBufferOptions{}))

(*Value)(nil).DetachArrayBuffer()
}

func TestUncatchablePrivateSymbolAndPropertyValue(t *testing.T) {
rt := NewRuntime()
defer rt.Close()
Expand Down
Loading