-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathruntime.go
More file actions
1508 lines (1344 loc) · 37.7 KB
/
runtime.go
File metadata and controls
1508 lines (1344 loc) · 37.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package quickjs
/*
#include "bridge.h"
#include <time.h>
*/
import "C"
import (
"errors"
"fmt"
goruntime "runtime"
"strings"
"sync"
"sync/atomic"
"unsafe"
)
// InterruptHandler is a function type for interrupt handler.
// Return != 0 if the JS code needs to be interrupted
type InterruptHandler func() int
type interruptHandlerHolder struct {
fn InterruptHandler
}
// runtimeNewContextHook is used in tests to force JS_NewContext failure paths.
// It must remain nil in production.
var runtimeNewContextHook func(rt *C.JSRuntime) *C.JSContext
// runtimeInitContextHook is used in tests to force context initialization failure paths.
// It must remain nil in production.
var runtimeInitContextHook func(ctx *C.JSContext) C.JSValue
// runtimeEvalFunctionHook is used in tests to force JS_EvalFunction failure paths.
// It must remain nil in production.
var runtimeEvalFunctionHook func(ctx *C.JSContext, compiled C.JSValue) C.JSValue
// runtimeBootstrapStdOSHook and runtimeBootstrapTimersHook are used in tests
// to force bootstrap failure paths. They must remain nil in production.
var runtimeBootstrapStdOSHook func(ctx *Context) bool
var runtimeBootstrapTimersHook func(ctx *Context) bool
var runtimeApplyIntrinsicsHook func(ctx *C.JSContext, set IntrinsicSet) (handled bool, ok bool)
var runtimeApplyIntrinsicStepHook func(name string) (handled bool, ok bool)
// runtimeBootstrapStdOSInitHook is used in tests to force std/os init
// outcomes while keeping BootstrapStdOS owner/liveness checks active.
// Return (handled=true, ok=<result>) to override default C initialization.
var runtimeBootstrapStdOSInitHook func(ctx *Context) (handled bool, ok bool)
var errOwnerAccessDenied = errors.New("quickjs: owner access denied; runtime/context/value APIs must be called from the owner goroutine; if strict OS thread mode is enabled, also bind that goroutine with runtime.LockOSThread()")
var ownerCheckCurrentGoroutineID = currentGoroutineID
var ownerCheckCurrentThreadID = currentThreadID
var goroutineStack = goruntime.Stack
type classObjectIdentity struct {
contextID uint64
handleID int32
}
// Runtime represents a Javascript runtime with simplified interrupt handling
type Runtime struct {
mu sync.RWMutex
ref *C.JSRuntime
runtimeInfo *C.char
options *Options
ownerGoroutineID atomic.Uint64
ownerThreadID atomic.Uint64
interruptHandlerState atomic.Pointer[interruptHandlerHolder]
contexts sync.Map
contextsByID sync.Map
contextIDCounter atomic.Uint64
constructorRegistry sync.Map
classObjectRegistry sync.Map
classObjectIDsByCtx sync.Map
classObjectIDCounter atomic.Int32
closeOnce sync.Once
closed atomic.Bool
stdHandlersInitialized bool
}
// isAlive reports whether the runtime still has a valid native handle and
// has not started closing.
func (r *Runtime) isAlive() bool {
return r != nil && r.ref != nil && !r.closed.Load()
}
type Options struct {
timeout uint64
memoryLimit uint64
gcThreshold int64
maxStackSize uint64
canBlock bool
moduleImport bool
strip int
ownerGoroutineCheck bool
strictThreadAffinity bool
}
type Option func(*Options)
// ContextBootstrapOptions controls host bootstrap for new contexts.
type ContextBootstrapOptions struct {
loadStdOS bool
injectTimers bool
}
type ContextBootstrapOption func(*ContextBootstrapOptions)
// MemoryUsage mirrors QuickJS JSMemoryUsage fields.
type MemoryUsage struct {
MallocSize int64
MallocLimit int64
MemoryUsedSize int64
MallocCount int64
MemoryUsedCount int64
AtomCount int64
AtomSize int64
StrCount int64
StrSize int64
ObjCount int64
ObjSize int64
PropCount int64
PropSize int64
ShapeCount int64
ShapeSize int64
JSFuncCount int64
JSFuncSize int64
JSFuncCodeSize int64
JSFuncPC2LineCount int64
JSFuncPC2LineSize int64
CFuncCount int64
ArrayCount int64
FastArrayCount int64
FastArrayElements int64
BinaryObjectCount int64
BinaryObjectSize int64
}
// IntrinsicSet controls which QuickJS intrinsics are injected into a raw context.
type IntrinsicSet struct {
BaseObjects bool
Date bool
Eval bool
RegExp bool
JSON bool
Proxy bool
MapSet bool
TypedArrays bool
Promise bool
BigInt bool
WeakRef bool
Performance bool
DOMException bool
}
// IntrinsicOption modifies IntrinsicSet.
type IntrinsicOption func(*IntrinsicSet)
// NewIntrinsicSet builds an IntrinsicSet from options.
func NewIntrinsicSet(opts ...IntrinsicOption) IntrinsicSet {
set := IntrinsicSet{}
for _, opt := range opts {
if opt != nil {
opt(&set)
}
}
return normalizeIntrinsicSet(set)
}
// AllIntrinsics enables all QuickJS intrinsics.
func AllIntrinsics() IntrinsicSet {
return IntrinsicSet{
BaseObjects: true,
Date: true,
Eval: true,
RegExp: true,
JSON: true,
Proxy: true,
MapSet: true,
TypedArrays: true,
Promise: true,
BigInt: true,
WeakRef: true,
Performance: true,
DOMException: true,
}
}
// MinimalIntrinsics enables only base language objects.
func MinimalIntrinsics() IntrinsicSet {
return IntrinsicSet{BaseObjects: true}
}
// WithBaseObjects toggles base object intrinsic injection.
func WithBaseObjects(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.BaseObjects = enabled }
}
// WithDate toggles Date intrinsic injection.
func WithDate(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.Date = enabled }
}
// WithEval toggles eval intrinsic injection.
func WithEval(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.Eval = enabled }
}
// WithRegExp toggles RegExp intrinsic injection.
func WithRegExp(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.RegExp = enabled }
}
// WithJSON toggles JSON intrinsic injection.
func WithJSON(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.JSON = enabled }
}
// WithProxy toggles Proxy intrinsic injection.
func WithProxy(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.Proxy = enabled }
}
// WithMapSet toggles Map/Set intrinsic injection.
func WithMapSet(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.MapSet = enabled }
}
// WithTypedArrays toggles typed-array intrinsic injection.
func WithTypedArrays(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.TypedArrays = enabled }
}
// WithPromise toggles Promise intrinsic injection.
func WithPromise(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.Promise = enabled }
}
// WithBigInt toggles BigInt intrinsic injection.
func WithBigInt(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.BigInt = enabled }
}
// WithWeakRef toggles WeakRef intrinsic injection.
func WithWeakRef(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.WeakRef = enabled }
}
// WithPerformance toggles performance intrinsic injection.
func WithPerformance(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.Performance = enabled }
}
// WithDOMException toggles DOMException intrinsic injection.
func WithDOMException(enabled bool) IntrinsicOption {
return func(s *IntrinsicSet) { s.DOMException = enabled }
}
func normalizeIntrinsicSet(set IntrinsicSet) IntrinsicSet {
if set.Date || set.Eval || set.RegExp || set.JSON || set.Proxy || set.MapSet ||
set.TypedArrays || set.Promise || set.BigInt || set.WeakRef || set.Performance || set.DOMException {
set.BaseObjects = true
}
return set
}
// DefaultBootstrap enables the same bootstrap pipeline as Runtime.NewContext:
// std/os module registration plus global timer injection.
func DefaultBootstrap() ContextBootstrapOption {
return func(o *ContextBootstrapOptions) {
o.loadStdOS = true
o.injectTimers = true
}
}
// MinimalBootstrap enables std/os module registration but skips timer injection.
func MinimalBootstrap() ContextBootstrapOption {
return func(o *ContextBootstrapOptions) {
o.loadStdOS = true
o.injectTimers = false
}
}
// NoBootstrap disables all host bootstrap steps.
func NoBootstrap() ContextBootstrapOption {
return func(o *ContextBootstrapOptions) {
o.loadStdOS = false
o.injectTimers = false
}
}
// WithBootstrapStdOS toggles std/os module registration in bootstrap.
func WithBootstrapStdOS(enabled bool) ContextBootstrapOption {
return func(o *ContextBootstrapOptions) {
o.loadStdOS = enabled
}
}
// WithBootstrapTimers toggles timer injection in bootstrap.
//
// Timer injection imports setTimeout/clearTimeout from the "os" module, so
// enabling timers implicitly requires std/os registration. During option
// normalization, injectTimers=true forces loadStdOS=true.
func WithBootstrapTimers(enabled bool) ContextBootstrapOption {
return func(o *ContextBootstrapOptions) {
o.injectTimers = enabled
}
}
func newContextBootstrapOptions(opts ...ContextBootstrapOption) ContextBootstrapOptions {
cfg := ContextBootstrapOptions{
loadStdOS: true,
injectTimers: true,
}
for _, opt := range opts {
if opt != nil {
opt(&cfg)
}
}
// Timer bootstrap imports from "os", so keep std/os enabled when timers
// are requested even if options were applied in a conflicting order.
if cfg.injectTimers && !cfg.loadStdOS {
cfg.loadStdOS = true
}
return cfg
}
const defaultTimerBootstrapCode = `
import { setTimeout, clearTimeout } from "os";
globalThis.setTimeout = setTimeout;
globalThis.clearTimeout = clearTimeout;
`
func (r *Runtime) ensureOwnerAccess() bool {
if r == nil {
return false
}
if r.options == nil || r.options.ownerGoroutineCheck {
gid := ownerCheckCurrentGoroutineID()
if gid == 0 {
return false
}
if !r.claimOrVerifyOwnerGoroutine(gid) {
return false
}
}
if r.options != nil && r.options.strictThreadAffinity {
tid := ownerCheckCurrentThreadID()
if tid == 0 {
return false
}
if !r.claimOrVerifyOwnerThread(tid) {
return false
}
}
return true
}
func (r *Runtime) claimOrVerifyOwnerGoroutine(current uint64) bool {
owner := r.ownerGoroutineID.Load()
if owner == 0 {
return r.ownerGoroutineID.CompareAndSwap(0, current) || r.ownerGoroutineID.Load() == current
}
return owner == current
}
func (r *Runtime) claimOrVerifyOwnerThread(current uint64) bool {
owner := r.ownerThreadID.Load()
if owner == 0 {
return r.ownerThreadID.CompareAndSwap(0, current) || r.ownerThreadID.Load() == current
}
return owner == current
}
func currentGoroutineID() uint64 {
const prefix = "goroutine "
var buf [128]byte
n := goroutineStack(buf[:], false)
if n <= len(prefix) {
return 0
}
idx := len(prefix)
var id uint64
hasDigit := false
for idx < n {
c := buf[idx]
if c < '0' || c > '9' {
break
}
hasDigit = true
id = id*10 + uint64(c-'0')
idx++
}
if !hasDigit {
return 0
}
return id
}
func currentThreadID() uint64 {
return uint64(C.CurrentThreadID())
}
// WithExecuteTimeout will set the runtime's execute timeout; default is 0
func WithExecuteTimeout(timeout uint64) Option {
return func(o *Options) {
o.timeout = timeout
}
}
// WithMemoryLimit will set the runtime memory limit; if not set, it will be unlimit.
func WithMemoryLimit(memoryLimit uint64) Option {
return func(o *Options) {
o.memoryLimit = memoryLimit
}
}
// WithGCThreshold will set the runtime's GC threshold; default is -1 to disable automatic GC.
func WithGCThreshold(gcThreshold int64) Option {
return func(o *Options) {
o.gcThreshold = gcThreshold
}
}
// WithMaxStackSize will set max runtime's stack size; default is 0 disable maximum stack size check
func WithMaxStackSize(maxStackSize uint64) Option {
return func(o *Options) {
o.maxStackSize = maxStackSize
}
}
// WithCanBlock will set the runtime's can block; default is true
func WithCanBlock(canBlock bool) Option {
return func(o *Options) {
o.canBlock = canBlock
}
}
func WithModuleImport(moduleImport bool) Option {
return func(o *Options) {
o.moduleImport = moduleImport
}
}
func WithStripInfo(strip int) Option {
return func(o *Options) {
o.strip = strip
}
}
// WithOwnerGoroutineCheck enables/disables owner-goroutine checks.
// WARNING: disabling this check is unsafe and may cause data races or memory corruption.
func WithOwnerGoroutineCheck(enabled bool) Option {
return func(o *Options) {
o.ownerGoroutineCheck = enabled
}
}
// WithStrictOSThread enables strict OS-thread affinity checks.
func WithStrictOSThread(enabled bool) Option {
return func(o *Options) {
o.strictThreadAffinity = enabled
}
}
// NewRuntime creates a new quickjs runtime with simplified interrupt handling.
func NewRuntime(opts ...Option) *Runtime {
options := &Options{
timeout: 0,
memoryLimit: 0,
gcThreshold: -1,
maxStackSize: 0,
canBlock: true,
moduleImport: false,
strip: 1,
ownerGoroutineCheck: true,
strictThreadAffinity: false,
}
for _, opt := range opts {
opt(options)
}
rt := &Runtime{
ref: C.JS_NewRuntime(),
options: options,
}
registerRuntime(rt.ref, rt)
C.SetPromiseRejectionTracker(rt.ref, 1)
// Configure runtime options
if rt.options.memoryLimit > 0 {
rt.SetMemoryLimit(rt.options.memoryLimit)
}
if rt.options.gcThreshold >= -1 {
rt.SetGCThreshold(rt.options.gcThreshold)
}
rt.SetMaxStackSize(rt.options.maxStackSize)
if rt.options.canBlock {
C.JS_SetCanBlock(rt.ref, C.bool(true))
}
if rt.options.strip > 0 {
rt.SetStripInfo(rt.options.strip)
}
if rt.options.moduleImport {
rt.SetModuleImport(rt.options.moduleImport)
}
// Set timeout after other options (will override interrupt handler)
if rt.options.timeout > 0 {
rt.SetExecuteTimeout(rt.options.timeout)
}
return rt
}
// RunGC will call quickjs's garbage collector.
func (r *Runtime) RunGC() {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_RunGC(r.ref)
}
// SetAwaitPollSliceMs configures AwaitValue idle poll slice duration in milliseconds.
// Values <= 0 are ignored.
func SetAwaitPollSliceMs(timeoutMs int) {
if timeoutMs <= 0 {
return
}
C.SetAwaitPollSliceMs(C.int(timeoutMs))
}
// GetAwaitPollSliceMs returns AwaitValue idle poll slice duration in milliseconds.
func GetAwaitPollSliceMs() int {
return int(C.GetAwaitPollSliceMs())
}
// Close will free the runtime pointer with proper cleanup.
func (r *Runtime) Close() {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.closeOnce.Do(func() {
r.closed.Store(true)
var contexts []*Context
r.contexts.Range(func(_, value interface{}) bool {
if ctx, ok := value.(*Context); ok {
contexts = append(contexts, ctx)
}
return true
})
for _, ctx := range contexts {
ctx.Close()
}
r.mu.Lock()
defer r.mu.Unlock()
if r.ref == nil {
return
}
ref := r.ref
r.interruptHandlerState.Store(nil)
C.ClearInterruptHandler(ref)
C.SetPromiseRejectionTracker(ref, 0)
r.constructorRegistry.Range(func(key, _ interface{}) bool {
r.constructorRegistry.Delete(key)
return true
})
r.classObjectRegistry.Range(func(key, _ interface{}) bool {
r.classObjectRegistry.Delete(key)
return true
})
r.classObjectIDsByCtx.Range(func(key, _ interface{}) bool {
r.classObjectIDsByCtx.Delete(key)
return true
})
r.contextsByID.Range(func(key, _ interface{}) bool {
r.contextsByID.Delete(key)
return true
})
unregisterRuntime(ref)
if r.stdHandlersInitialized {
C.js_std_free_handlers(ref)
r.stdHandlersInitialized = false
}
C.JS_FreeRuntime(ref)
if r.runtimeInfo != nil {
C.free(unsafe.Pointer(r.runtimeInfo))
r.runtimeInfo = nil
}
r.ref = nil
})
}
// SetCanBlock will set the runtime's can block; default is true
func (r *Runtime) SetCanBlock(canBlock bool) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetCanBlock(r.ref, C.bool(canBlock))
}
// SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.
func (r *Runtime) SetMemoryLimit(limit uint64) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetMemoryLimit(r.ref, C.size_t(limit))
}
// SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.
func (r *Runtime) SetGCThreshold(threshold int64) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetGCThreshold(r.ref, C.size_t(threshold))
}
// GCThreshold returns the runtime GC threshold.
func (r *Runtime) GCThreshold() uint64 {
if r == nil {
return 0
}
if !r.ensureOwnerAccess() {
return 0
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return 0
}
return uint64(C.JS_GetGCThreshold(r.ref))
}
// SetDumpFlags configures runtime dump flags.
func (r *Runtime) SetDumpFlags(flags uint64) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetDumpFlags(r.ref, C.uint64_t(flags))
}
// DumpFlags returns runtime dump flags.
func (r *Runtime) DumpFlags() uint64 {
if r == nil {
return 0
}
if !r.ensureOwnerAccess() {
return 0
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return 0
}
return uint64(C.JS_GetDumpFlags(r.ref))
}
// SetInfo sets runtime informational string.
func (r *Runtime) SetInfo(info string) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if r.closed.Load() || r.ref == nil {
return
}
if r.runtimeInfo != nil {
C.free(unsafe.Pointer(r.runtimeInfo))
r.runtimeInfo = nil
}
if info == "" {
C.JS_SetRuntimeInfo(r.ref, nil)
return
}
r.runtimeInfo = C.CString(info)
C.JS_SetRuntimeInfo(r.ref, r.runtimeInfo)
}
// MemoryUsage returns runtime memory usage snapshot.
func (r *Runtime) MemoryUsage() MemoryUsage {
if r == nil {
return MemoryUsage{}
}
if !r.ensureOwnerAccess() {
return MemoryUsage{}
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return MemoryUsage{}
}
var s C.JSMemoryUsage
C.JS_ComputeMemoryUsage(r.ref, &s)
return MemoryUsage{
MallocSize: int64(s.malloc_size),
MallocLimit: int64(s.malloc_limit),
MemoryUsedSize: int64(s.memory_used_size),
MallocCount: int64(s.malloc_count),
MemoryUsedCount: int64(s.memory_used_count),
AtomCount: int64(s.atom_count),
AtomSize: int64(s.atom_size),
StrCount: int64(s.str_count),
StrSize: int64(s.str_size),
ObjCount: int64(s.obj_count),
ObjSize: int64(s.obj_size),
PropCount: int64(s.prop_count),
PropSize: int64(s.prop_size),
ShapeCount: int64(s.shape_count),
ShapeSize: int64(s.shape_size),
JSFuncCount: int64(s.js_func_count),
JSFuncSize: int64(s.js_func_size),
JSFuncCodeSize: int64(s.js_func_code_size),
JSFuncPC2LineCount: int64(s.js_func_pc2line_count),
JSFuncPC2LineSize: int64(s.js_func_pc2line_size),
CFuncCount: int64(s.c_func_count),
ArrayCount: int64(s.array_count),
FastArrayCount: int64(s.fast_array_count),
FastArrayElements: int64(s.fast_array_elements),
BinaryObjectCount: int64(s.binary_object_count),
BinaryObjectSize: int64(s.binary_object_size),
}
}
// DumpMemoryUsage returns a human-readable memory usage summary.
func (r *Runtime) DumpMemoryUsage() string {
if r == nil {
return ""
}
if !r.ensureOwnerAccess() {
return ""
}
r.mu.RLock()
if r.closed.Load() || r.ref == nil {
r.mu.RUnlock()
return ""
}
r.mu.RUnlock()
usage := r.MemoryUsage()
var b strings.Builder
fmt.Fprintf(&b, "malloc_size=%d\n", usage.MallocSize)
fmt.Fprintf(&b, "malloc_limit=%d\n", usage.MallocLimit)
fmt.Fprintf(&b, "memory_used_size=%d\n", usage.MemoryUsedSize)
fmt.Fprintf(&b, "malloc_count=%d\n", usage.MallocCount)
fmt.Fprintf(&b, "memory_used_count=%d\n", usage.MemoryUsedCount)
fmt.Fprintf(&b, "atom_count=%d atom_size=%d\n", usage.AtomCount, usage.AtomSize)
fmt.Fprintf(&b, "str_count=%d str_size=%d\n", usage.StrCount, usage.StrSize)
fmt.Fprintf(&b, "obj_count=%d obj_size=%d\n", usage.ObjCount, usage.ObjSize)
fmt.Fprintf(&b, "prop_count=%d prop_size=%d\n", usage.PropCount, usage.PropSize)
fmt.Fprintf(&b, "shape_count=%d shape_size=%d\n", usage.ShapeCount, usage.ShapeSize)
fmt.Fprintf(&b, "js_func_count=%d js_func_size=%d js_func_code_size=%d\n", usage.JSFuncCount, usage.JSFuncSize, usage.JSFuncCodeSize)
fmt.Fprintf(&b, "js_func_pc2line_count=%d js_func_pc2line_size=%d\n", usage.JSFuncPC2LineCount, usage.JSFuncPC2LineSize)
fmt.Fprintf(&b, "c_func_count=%d array_count=%d\n", usage.CFuncCount, usage.ArrayCount)
fmt.Fprintf(&b, "fast_array_count=%d fast_array_elements=%d\n", usage.FastArrayCount, usage.FastArrayElements)
fmt.Fprintf(&b, "binary_object_count=%d binary_object_size=%d", usage.BinaryObjectCount, usage.BinaryObjectSize)
return b.String()
}
// SetMaxStackSize will set max runtime's stack size;
func (r *Runtime) SetMaxStackSize(stack_size uint64) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetMaxStackSize(r.ref, C.size_t(stack_size))
}
// SetExecuteTimeout will set the runtime's execute timeout;
// This will override any user interrupt handler (expected behavior)
func (r *Runtime) SetExecuteTimeout(timeout uint64) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if r.closed.Load() || r.ref == nil {
return
}
C.SetExecuteTimeout(r.ref, C.time_t(timeout))
// Clear user interrupt handler since timeout takes precedence
r.interruptHandlerState.Store(nil)
}
// SetStripInfo sets the strip info for the runtime.
func (r *Runtime) SetStripInfo(strip int) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
// quickjs-ng does not expose a runtime-level JS_SetStripInfo API.
_ = strip
}
// SetModuleImport sets whether the runtime supports module import.
func (r *Runtime) SetModuleImport(moduleImport bool) {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.closed.Load() || r.ref == nil {
return
}
C.JS_SetModuleLoaderFunc2(r.ref, (*C.JSModuleNormalizeFunc)(unsafe.Pointer(nil)), (*C.JSModuleLoaderFunc2)(C.js_module_loader), (*C.JSModuleCheckSupportedImportAttributes)(C.js_module_check_attributes), unsafe.Pointer(nil))
}
// SetInterruptHandler sets a user interrupt handler using simplified approach.
// This will override any timeout handler (expected behavior)
func (r *Runtime) SetInterruptHandler(handler InterruptHandler) {
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 {
r.interruptHandlerState.Store(&interruptHandlerHolder{fn: handler})
} else {
r.interruptHandlerState.Store(nil)
}
if handler != nil {
// Simplified call - no handlerArgs complexity
C.SetInterruptHandler(r.ref)
} else {
C.ClearInterruptHandler(r.ref)
}
}
// ClearInterruptHandler clears the user interrupt handler
func (r *Runtime) ClearInterruptHandler() {
if r == nil {
return
}
if !r.ensureOwnerAccess() {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if r.ref == nil {
return
}
r.interruptHandlerState.Store(nil)
C.ClearInterruptHandler(r.ref)
}
// callInterruptHandler is called from C layer via runtime mapping (internal use)
func (r *Runtime) callInterruptHandler() int {
if r == nil {
return 0
}
holder := r.interruptHandlerState.Load()
if holder != nil && holder.fn != nil {
return holder.fn()
}
return 0 // No interrupt
}
// NewContext creates a new JavaScript context with default host bootstrap.
func (r *Runtime) NewContext() *Context {
return r.NewContextWithOptions(DefaultBootstrap())
}
// NewBareContext creates a JavaScript context without host bootstrap.
func (r *Runtime) NewBareContext() *Context {
return r.NewContextWithOptions(NoBootstrap())
}
// NewContextRaw creates a raw QuickJS context and applies selected intrinsics.
func (r *Runtime) NewContextRaw(intrinsics IntrinsicSet) *Context {
if r == nil {
return nil
}
if !r.ensureOwnerAccess() {
return nil
}
set := normalizeIntrinsicSet(intrinsics)
r.mu.Lock()
defer r.mu.Unlock()
if r.closed.Load() || r.ref == nil {
return nil
}
if !r.stdHandlersInitialized {
C.js_std_init_handlers(r.ref)
r.stdHandlersInitialized = true
}
var ctxRef *C.JSContext
if runtimeNewContextHook != nil {
ctxRef = runtimeNewContextHook(r.ref)
} else {
ctxRef = C.JS_NewContextRaw(r.ref)
}
if ctxRef == nil {
return nil
}
ctx := &Context{
contextID: r.nextContextID(),
ref: ctxRef,
runtime: r,
handleStore: newHandleStore(),