diff --git a/bridge.c b/bridge.c index c36008a..c263885 100644 --- a/bridge.c +++ b/bridge.c @@ -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) { diff --git a/bridge_test.go b/bridge_test.go index 8e39182..9cbdf35 100644 --- a/bridge_test.go +++ b/bridge_test.go @@ -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) @@ -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) diff --git a/callback_dispatch.go b/callback_dispatch.go index fc051de..bebbee0 100644 --- a/callback_dispatch.go +++ b/callback_dispatch.go @@ -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 diff --git a/context.go b/context.go index 153d592..e82c4a8 100644 --- a/context.go +++ b/context.go @@ -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 { diff --git a/error.go b/error.go index 281e9a7..6fbfb9b 100644 --- a/error.go +++ b/error.go @@ -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. diff --git a/runtime.go b/runtime.go index 4441c9a..9e87b21 100644 --- a/runtime.go +++ b/runtime.go @@ -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 @@ -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 @@ -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. diff --git a/runtime_test.go b/runtime_test.go index 44dda55..b9003bd 100644 --- a/runtime_test.go +++ b/runtime_test.go @@ -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)) } } @@ -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) diff --git a/value.go b/value.go index f0c441c..00dcb7c 100644 --- a/value.go +++ b/value.go @@ -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 diff --git a/value_test.go b/value_test.go index 14d825c..a87bfbb 100644 --- a/value_test.go +++ b/value_test.go @@ -4,6 +4,7 @@ import ( "errors" "math" "math/big" + "sync/atomic" "testing" "github.com/stretchr/testify/require" @@ -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) +}