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
3 changes: 1 addition & 2 deletions bridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -863,9 +863,8 @@ static void clearTimeoutState(JSRuntime *rt);
// Simplified interrupt handler (no handlerArgs complexity)
// quickjs-ng v0.18.0+: JSInterruptHandler takes JSContext*, not JSRuntime*
int interruptHandler(JSContext *ctx, void *opaque) {
(void)ctx;
JSRuntime *runtimePtr = (JSRuntime*)opaque;
return goInterruptHandler(runtimePtr);
return goInterruptHandler(ctx, runtimePtr);
}

void SetInterruptHandler(JSRuntime *rt) {
Expand Down
4 changes: 2 additions & 2 deletions bridge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func TestBridgeMappingCorruptionFailClosed(t *testing.T) {
runtimeMapping.Store(rt.ref, "corrupted-runtime")
require.Nil(t, getRuntimeFromJS(rt.ref))
require.NotPanics(t, func() {
_ = goInterruptHandler(rt.ref)
_ = goInterruptHandler(ctx.ref, rt.ref)
})

registerContext(ctx.ref, ctx)
Expand Down Expand Up @@ -252,7 +252,7 @@ func TestBridgeMappingCloseContractStress(t *testing.T) {
require.Nil(t, getContextFromJS(ctxRef))
require.Nil(t, getRuntimeFromJS(rtRef))
require.NotPanics(t, func() {
_ = goInterruptHandler(rtRef)
_ = goInterruptHandler(ctxRef, rtRef)
})

contextMapping.Delete(ctxRef)
Expand Down
4 changes: 2 additions & 2 deletions callback_dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ func getContextAndObject(ctx *C.JSContext, magic C.int, notFoundErr proxyError)
}

//export goInterruptHandler
func goInterruptHandler(runtimePtr *C.JSRuntime) C.int {
func goInterruptHandler(ctx *C.JSContext, runtimePtr *C.JSRuntime) C.int {
runtime := getRuntimeFromJS(runtimePtr)
if runtime == nil {
return C.int(0)
}
return C.int(runtime.callInterruptHandler())
return C.int(runtime.callInterruptHandler(getContextFromJS(ctx)))
}

//export goDynamicImport
Expand Down
19 changes: 19 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,25 @@ func (ctx *Context) NewGlobalSymbolWithoutDescription() *Value {
return ctx.newSymbol(nil, true)
}

// NewPrivateSymbol returns a symbol visible only to C/Go code (not to JS).
func (ctx *Context) NewPrivateSymbol(description string) *Value {
if !ctx.hasValidRef() {
return nil
}
desc := C.CString(description)
defer C.free(unsafe.Pointer(desc))
return &Value{ctx: ctx, ref: C.JS_NewPrivateSymbol(ctx.ref, desc)}
}

// ResetUncatchableError makes a pending uncatchable exception catchable again
// (see JS_ResetUncatchableError).
func (ctx *Context) ResetUncatchableError() {
if !ctx.hasValidRef() {
return
}
C.JS_ResetUncatchableError(ctx.ref)
}

// String returns a string value with given string.
// Deprecated: Use NewString() instead.
func (ctx *Context) String(v string) *Value {
Expand Down
11 changes: 6 additions & 5 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import "fmt"

// Error represents a JavaScript error with detailed information.
type Error struct {
Name string // Error name (e.g., "TypeError", "ReferenceError")
Message string // Error message
Cause string // Error cause
Stack string // Stack trace
JSONString string // Serialized JSON string
Name string // Error name (e.g., "TypeError", "ReferenceError")
Message string // Error message
Cause string // Error cause
Stack string // Stack trace
JSONString string // Serialized JSON string
Uncatchable bool // true when JS_IsUncatchableError (e.g. OOM / InternalError)
}

// Error implements the error interface.
Expand Down
47 changes: 38 additions & 9 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ import (
// Return != 0 if the JS code needs to be interrupted
type InterruptHandler func() int

// ContextInterruptHandler receives the executing JS context when interrupting.
type ContextInterruptHandler func(ctx *Context) int

type interruptHandlerHolder struct {
fn InterruptHandler
fn InterruptHandler
contextFn ContextInterruptHandler
}

// ErrDynamicImportPending indicates the DynamicImportHandler will finish later
Expand Down Expand Up @@ -1099,16 +1103,35 @@ func (r *Runtime) SetInterruptHandler(handler InterruptHandler) {
}
if handler != nil {
r.interruptHandlerState.Store(&interruptHandlerHolder{fn: handler})
} else {
r.interruptHandlerState.Store(nil)
C.SetInterruptHandler(r.ref)
return
}
r.interruptHandlerState.Store(nil)
C.ClearInterruptHandler(r.ref)
}

// SetContextInterruptHandler sets a context-aware interrupt handler.
// Prefer this over SetInterruptHandler when the interrupting context matters.
// Overrides timeout handlers (same slot as SetInterruptHandler).
func (r *Runtime) SetContextInterruptHandler(handler ContextInterruptHandler) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if r.closed.Load() || r.ref == nil {
return
}
if handler != nil {
// Simplified call - no handlerArgs complexity
r.interruptHandlerState.Store(&interruptHandlerHolder{contextFn: handler})
C.SetInterruptHandler(r.ref)
} else {
C.ClearInterruptHandler(r.ref)
return
}
r.interruptHandlerState.Store(nil)
C.ClearInterruptHandler(r.ref)
}

// ClearInterruptHandler clears the user interrupt handler
Expand All @@ -1129,15 +1152,21 @@ func (r *Runtime) ClearInterruptHandler() {
}

// callInterruptHandler is called from C layer via runtime mapping (internal use)
func (r *Runtime) callInterruptHandler() int {
func (r *Runtime) callInterruptHandler(ctx *Context) int {
if r == nil {
return 0
}
holder := r.interruptHandlerState.Load()
if holder != nil && holder.fn != nil {
if holder == nil {
return 0
}
if holder.contextFn != nil {
return holder.contextFn(ctx)
}
if holder.fn != nil {
return holder.fn()
}
return 0 // No interrupt
return 0
}

// NewContext creates a new JavaScript context with default host bootstrap.
Expand Down
6 changes: 3 additions & 3 deletions runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,13 +413,13 @@ func TestCallInterruptHandler_DirectCall(t *testing.T) {

// Test return 0 branch when no handler is set
rt.ClearInterruptHandler()
require.Equal(t, 0, rt.callInterruptHandler())
require.Equal(t, 0, rt.callInterruptHandler(nil))

// Test handler invocation with different return values
testCases := []int{0, 1, 42, -1}
for _, expected := range testCases {
rt.SetInterruptHandler(func() int { return expected })
require.Equal(t, expected, rt.callInterruptHandler())
require.Equal(t, expected, rt.callInterruptHandler(nil))
}
}

Expand Down Expand Up @@ -1581,7 +1581,7 @@ func TestRuntimeNilAndZeroValueGuards(t *testing.T) {
require.Nil(t, nilRT.NewBareContext())
require.Nil(t, nilRT.NewContextRaw(MinimalIntrinsics()))
require.Nil(t, nilRT.NewContextWithOptions(DefaultBootstrap()))
require.Equal(t, 0, nilRT.callInterruptHandler())
require.Equal(t, 0, nilRT.callInterruptHandler(nil))
nilRT.registerOwnedContext(nil)
nilRT.unregisterOwnedContext(nil, 0)
nilRT.registerConstructorClassID(dummyRef, 1)
Expand Down
33 changes: 33 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,42 @@ func (v *Value) ToError() error {
err.JSONString = jsonString
}

err.Uncatchable = v.IsUncatchableError()

return err
}

// IsUncatchableError reports whether the value is an uncatchable JS error
// (e.g. OOM or InternalError after quickjs-ng v0.18.0).
func (v *Value) IsUncatchableError() bool {
return v != nil && bool(C.JS_IsUncatchableError(v.ref))
}

// GetValue gets a property using a JS value key (string/symbol/private symbol/index).
// Does not consume key; caller retains ownership.
func (v *Value) GetValue(key *Value) *Value {
if !v.isAlive() || !key.belongsTo(v.ctx) {
return nil
}
dupKey := C.JS_DupValue(v.ctx.ref, key.ref)
return &Value{ctx: v.ctx, ref: C.JS_GetPropertyValue(v.ctx.ref, v.ref, dupKey)}
}

// SetValue sets a property using a JS value key. Caller retains key and val.
// flags is a mix of Prop* constants; when 0, JS_PROP_C_W_E is used.
func (v *Value) SetValue(key, val *Value, flags int) bool {
if !v.isAlive() || !key.belongsTo(v.ctx) || !val.belongsTo(v.ctx) {
return false
}
if flags == 0 {
flags = int(C.JS_PROP_C_W_E)
}
dupKey := C.JS_DupValue(v.ctx.ref, key.ref)
dupVal := C.JS_DupValue(v.ctx.ref, val.ref)
ret := C.JS_SetPropertyValue(v.ctx.ref, v.ref, dupKey, dupVal, C.int(flags))
return ret == 1
}

// propertyEnum is a wrapper around JSValue.
func (v *Value) propertyEnum() ([]*propertyEnum, error) {
var ptr *C.JSPropertyEnum
Expand Down
122 changes: 122 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"
"sync/atomic"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -2469,3 +2470,124 @@ func TestValueCallConstructorComprehensive(t *testing.T) {
}
})
}

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

_ = ctx.ThrowInternalError("inspect")
require.True(t, ctx.HasException())
excErr := ctx.Exception()
require.Error(t, excErr)
typed, ok := excErr.(*Error)
require.True(t, ok)
require.True(t, typed.Uncatchable)

_ = ctx.ThrowInternalError("pending")
require.True(t, ctx.HasException())
ctx.ResetUncatchableError()
ex := ctx.Exception()
require.Error(t, ex)

obj := ctx.Eval(`({})`)
defer obj.Free()
priv := ctx.NewPrivateSymbol("slot")
defer priv.Free()
pub := ctx.NewSymbol("pub")
defer pub.Free()

val := ctx.NewInt32(7)
require.True(t, obj.SetValue(priv, val, 0))
val.Free()
got := obj.GetValue(priv)
defer got.Free()
require.EqualValues(t, 7, got.ToInt32())

pubVal := ctx.NewString("visible")
require.True(t, obj.SetValue(pub, pubVal, 0))
pubVal.Free()
gotPub := obj.GetValue(pub)
defer gotPub.Free()
require.Equal(t, "visible", gotPub.ToString())

explicit := ctx.NewInt32(9)
require.True(t, obj.SetValue(priv, explicit, PropWritable|PropConfigurable|PropEnumerable))
explicit.Free()

other := rt.NewContext()
foreignKey := other.NewString("foreign")
foreignVal := other.NewInt32(1)
require.Nil(t, obj.GetValue(foreignKey))
require.False(t, obj.SetValue(foreignKey, got, 0))
require.False(t, obj.SetValue(priv, foreignVal, 0))
foreignKey.Free()
foreignVal.Free()
other.Close()

require.Nil(t, (*Value)(nil).GetValue(priv))
require.False(t, (*Value)(nil).SetValue(priv, got, 0))
require.Nil(t, (*Context)(nil).NewPrivateSymbol("x"))
(*Context)(nil).ResetUncatchableError()
closedCtx := rt.NewContext()
closedCtx.Close()
require.Nil(t, closedCtx.NewPrivateSymbol("closed"))
closedCtx.ResetUncatchableError()
require.False(t, (*Value)(nil).IsUncatchableError())
}

func TestContextInterruptHandlerReceivesContext(t *testing.T) {
rt := NewRuntime()
defer rt.Close()

ctx := rt.NewContext()
defer ctx.Close()

var seen *Context
rt.SetContextInterruptHandler(func(c *Context) int {
seen = c
return 1
})

result := ctx.Eval(`while(true){}`)
defer result.Free()
require.True(t, result.IsException())
err := ctx.Exception()
require.Error(t, err)
require.Contains(t, err.Error(), "interrupted")
require.NotNil(t, seen)
require.Equal(t, ctx, seen)

rt.SetContextInterruptHandler(nil)
}

func TestContextInterruptHandlerFailClosed(t *testing.T) {
oldGIDHook := ownerCheckCurrentGoroutineID
oldThreadHook := ownerCheckCurrentThreadID
defer func() {
ownerCheckCurrentGoroutineID = oldGIDHook
ownerCheckCurrentThreadID = oldThreadHook
}()

var gid atomic.Uint64
gid.Store(701)
ownerCheckCurrentGoroutineID = func() uint64 { return gid.Load() }
ownerCheckCurrentThreadID = func() uint64 { return 1 }

var nilRT *Runtime
nilRT.SetContextInterruptHandler(func(ctx *Context) int { return 1 })
require.Equal(t, 0, nilRT.callInterruptHandler(nil))

rt := NewRuntime()
rt.interruptHandlerState.Store(&interruptHandlerHolder{})
require.Equal(t, 0, rt.callInterruptHandler(nil))

gid.Store(702)
rt.SetContextInterruptHandler(func(ctx *Context) int { return 1 })
gid.Store(701)

rt.Close()
rt.SetContextInterruptHandler(func(ctx *Context) int { return 1 })
rt.SetContextInterruptHandler(nil)
}
Loading