v8x 149.4.0-rc.1

Engine agnostic JavaScript
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
#![allow(non_snake_case, unused)]

use crate::jsc::core::{
  ctx_of, current_ctx, current_iso, intern, intern_ctx, iso_state, jsval,
};
use crate::jsc::jsc_sys::*;
use crate::support::{
  Maybe, MaybeBool, SharedPtrBase, SharedRef, UniquePtr, long,
};
use crate::{
  Allocator, ArrayBuffer, ArrayBufferView, BackingStore,
  BackingStoreDeleterCallback, Context, DataView, RealIsolate,
  SharedArrayBuffer, Uint8ClampedArray, Value,
};
use std::ffi::c_void;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};

#[repr(C)]
#[derive(Copy, Clone)]
struct MemorySpan {
  data: *mut u8,
  size: usize,
}

// Fallback detach tracking. JSC's C API has no detach primitive, so
// `v8__ArrayBuffer__Detach` neuters the buffer at the JS level via
// `ArrayBuffer.prototype.transfer()`. On a JSC build/framework where that path
// does NOT actually neuter the buffer (a wrapped no-copy buffer JSC refuses to
// transfer — observed on `JavaScriptCore.framework`), we still must report the
// buffer as detached for the C-ABI contract (`byte_length()==0`,
// `was_detached()==true`).
//
// The marker is stored as a `DontEnum` property ON THE ARRAYBUFFER OBJECT
// ITSELF, NOT in a side table keyed by object pointer: the rusty_v8 harness
// runs every `test_api` test in ONE shared process, and JSC reuses freed object
// pointers, so a pointer-keyed set leaks "detached" onto unrelated later
// buffers (e.g. `backing_store_data`). A per-object property is GC-scoped to
// the exact buffer and cannot alias another. `DETACHED_ANY` gates the property
// lookup so the common (nothing-detached, e.g. deno_core) hot path skips it.
const DETACH_PROP: &[u8] = b"__v8x_detached\0";
static DETACHED_ANY: AtomicUsize = AtomicUsize::new(0);

fn mark_detached(ctx: JSContextRef, obj: JSObjectRef) {
  unsafe {
    let key = JSStringCreateWithUTF8CString(
      DETACH_PROP.as_ptr() as *const std::os::raw::c_char
    );
    let mut exc: JSValueRef = ptr::null();
    // 4 == kJSPropertyAttributeDontEnum
    JSObjectSetProperty(
      ctx,
      obj,
      key,
      JSValueMakeBoolean(ctx, true),
      4,
      &mut exc,
    );
    JSStringRelease(key);
  }
  DETACHED_ANY.fetch_add(1, Ordering::SeqCst);
}

fn is_marked_detached(ctx: JSContextRef, obj: JSObjectRef) -> bool {
  if DETACHED_ANY.load(Ordering::SeqCst) == 0 {
    return false;
  }
  unsafe {
    let key = JSStringCreateWithUTF8CString(
      DETACH_PROP.as_ptr() as *const std::os::raw::c_char
    );
    let has = JSObjectHasProperty(ctx, obj, key);
    JSStringRelease(key);
    has
  }
}

struct BsInner {
  refcount: AtomicUsize,
  data: *mut c_void,
  byte_length: usize,
  is_shared: bool,

  deleter: BackingStoreDeleterCallback,
  deleter_data: *mut c_void,

  owns_malloc: bool,
}

unsafe extern "C" {
  fn malloc(size: usize) -> *mut c_void;
  fn calloc(count: usize, size: usize) -> *mut c_void;
  fn free(ptr: *mut c_void);
}

unsafe extern "C" fn noop_deleter(
  _data: *mut c_void,
  _len: usize,
  _deleter_data: *mut c_void,
) {
}

impl BsInner {
  fn boxed(
    data: *mut c_void,
    byte_length: usize,
    is_shared: bool,
    deleter: BackingStoreDeleterCallback,
    deleter_data: *mut c_void,
    owns_malloc: bool,
  ) -> *mut BsInner {
    Box::into_raw(Box::new(BsInner {
      refcount: AtomicUsize::new(1),
      data,
      byte_length,
      is_shared,
      deleter,
      deleter_data,
      owns_malloc,
    }))
  }

  fn new_allocated(byte_length: usize, is_shared: bool) -> *mut BsInner {
    let data = if byte_length == 0 {
      ptr::null_mut()
    } else {
      unsafe { calloc(byte_length, 1) }
    };
    BsInner::boxed(
      data,
      byte_length,
      is_shared,
      noop_deleter,
      ptr::null_mut(),
      true,
    )
  }

  unsafe fn destroy(ptr: *mut BsInner) {
    if ptr.is_null() {
      return;
    }
    let b = unsafe { Box::from_raw(ptr) };
    if !b.data.is_null() {
      if b.owns_malloc {
        unsafe { free(b.data) };
      } else {
        unsafe { (b.deleter)(b.data, b.byte_length, b.deleter_data) };
      }
    }
  }
}

#[inline]
fn bs_inner<'a>(p: *const BackingStore) -> Option<&'a BsInner> {
  unsafe { (p as *const BsInner).as_ref() }
}

#[inline]
fn sp_get(p: *const SharedPtrBase<BackingStore>) -> *mut BsInner {
  if p.is_null() {
    return ptr::null_mut();
  }
  unsafe { *(p as *const usize) as *mut BsInner }
}

#[inline]
fn sp_set(p: *mut SharedPtrBase<BackingStore>, inner: *mut BsInner) {
  unsafe {
    let words = p as *mut usize;
    *words = inner as usize;
    *words.add(1) = 0;
  }
}

#[inline]
fn make_shared_ref(inner: *mut BsInner) -> SharedRef<BackingStore> {
  let base: SharedPtrBase<BackingStore> = Default::default();

  let mut sref = unsafe {
    std::mem::transmute_copy::<
      SharedPtrBase<BackingStore>,
      SharedRef<BackingStore>,
    >(&base)
  };
  std::mem::forget(base);
  sp_set(
    &mut sref as *mut SharedRef<BackingStore>
      as *mut SharedPtrBase<BackingStore>,
    inner,
  );
  sref
}

fn backing_store_for_buffer(
  ctx: JSContextRef,
  buf: JSValueRef,
) -> SharedRef<BackingStore> {
  let obj = buf as JSObjectRef;
  let (data, len) = unsafe {
    (
      JSObjectGetArrayBufferBytesPtr(ctx, obj, ptr::null_mut()),
      JSObjectGetArrayBufferByteLength(ctx, obj, ptr::null_mut()),
    )
  };
  let inner =
    BsInner::boxed(data, len, false, noop_deleter, ptr::null_mut(), false);
  make_shared_ref(inner)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__New__with_byte_length(
  isolate: *mut RealIsolate,
  byte_length: usize,
) -> *const ArrayBuffer {
  let st = iso_state(isolate);
  let ctx =
    st.contexts.last().copied().unwrap_or(ptr::null_mut()) as JSContextRef;
  if ctx.is_null() {
    return ptr::null();
  }

  // Always back the buffer with a non-null allocation: a NoCopy ArrayBuffer
  // whose data pointer is null is treated as DETACHED by JSC, so any view over
  // a zero-length buffer would throw "ArrayBuffer has been detached". Allocate
  // at least one byte while still reporting byte_length to JSC.
  let data = unsafe { calloc(byte_length.max(1), 1) };
  unsafe extern "C" fn dealloc(bytes: *mut c_void, _ctx: *mut c_void) {
    if !bytes.is_null() {
      unsafe { free(bytes) };
    }
  }
  let obj = unsafe {
    JSObjectMakeArrayBufferWithBytesNoCopy(
      ctx,
      data,
      byte_length,
      Some(dealloc),
      ptr::null_mut(),
      ptr::null_mut(),
    )
  };
  intern_ctx::<ArrayBuffer>(ctx, obj as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__New__with_backing_store(
  isolate: *mut RealIsolate,
  backing_store: *const SharedRef<BackingStore>,
) -> *const ArrayBuffer {
  let st = iso_state(isolate);
  let ctx =
    st.contexts.last().copied().unwrap_or(ptr::null_mut()) as JSContextRef;
  if ctx.is_null() || backing_store.is_null() {
    return ptr::null();
  }
  let inner = sp_get(backing_store as *const SharedPtrBase<BackingStore>);
  if inner.is_null() {
    return ptr::null();
  }
  let (data, len) = unsafe { ((*inner).data, (*inner).byte_length) };

  unsafe { (*inner).refcount.fetch_add(1, Ordering::SeqCst) };
  unsafe extern "C" fn dealloc(_bytes: *mut c_void, ctx: *mut c_void) {
    crate::jsc::core::ffi_guard(
      || {
        let inner = ctx as *mut BsInner;
        if inner.is_null() {
          return;
        }
        if unsafe { (*inner).refcount.fetch_sub(1, Ordering::SeqCst) } == 1 {
          unsafe { BsInner::destroy(inner) };
        }
      },
      || (),
    )
  }
  let obj = unsafe {
    JSObjectMakeArrayBufferWithBytesNoCopy(
      ctx,
      data,
      len,
      Some(dealloc),
      inner as *mut c_void,
      ptr::null_mut(),
    )
  };
  intern_ctx::<ArrayBuffer>(ctx, obj as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__ByteLength(
  this: *const ArrayBuffer,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0;
  }
  let obj = jsval(this) as JSObjectRef;
  if is_marked_detached(ctx, obj) {
    return 0;
  }
  unsafe { JSObjectGetArrayBufferByteLength(ctx, obj, ptr::null_mut()) }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__Data(
  this: *const ArrayBuffer,
) -> *mut c_void {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null_mut();
  }
  let obj = jsval(this) as JSObjectRef;
  if is_marked_detached(ctx, obj) {
    return ptr::null_mut();
  }
  unsafe { JSObjectGetArrayBufferBytesPtr(ctx, obj, ptr::null_mut()) }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__IsDetachable(
  this: *const ArrayBuffer,
) -> bool {
  !this.is_null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__WasDetached(
  this: *const ArrayBuffer,
) -> bool {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return false;
  }
  let obj = jsval(this) as JSObjectRef;
  if is_marked_detached(ctx, obj) {
    return true;
  }
  // A detached ArrayBuffer reports a null bytes pointer in JSC. Freshly
  // created (incl. zero-length) buffers always have a non-null backing — our
  // `New__with_byte_length` allocates `byte_length.max(1)` precisely so an
  // empty-but-live buffer is distinguishable from a detached one here.
  let data =
    unsafe { JSObjectGetArrayBufferBytesPtr(ctx, obj, ptr::null_mut()) };
  data.is_null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__Detach(
  this: *const ArrayBuffer,
  key: *const Value,
) -> MaybeBool {
  let _ = key;
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return MaybeBool::Nothing;
  }
  let obj = jsval(this) as JSObjectRef;
  // Already detached (marked, or null bytes ptr): detaching twice is a no-op.
  if is_marked_detached(ctx, obj) {
    return MaybeBool::JustTrue;
  }
  let data =
    unsafe { JSObjectGetArrayBufferBytesPtr(ctx, obj, ptr::null_mut()) };
  if data.is_null() {
    return MaybeBool::JustTrue;
  }
  // JSC's C API exposes no detach primitive, so detach at the JS level via
  // `ArrayBuffer.prototype.transfer()` (ES2024), which neuters the receiver.
  unsafe {
    let mut exc: JSValueRef = ptr::null();
    let src = b"(function(buf){buf.transfer();})\0";
    let fs = JSStringCreateWithUTF8CString(
      src.as_ptr() as *const std::os::raw::c_char
    );
    let fnv =
      JSEvaluateScript(ctx, fs, ptr::null_mut(), ptr::null_mut(), 1, &mut exc);
    JSStringRelease(fs);
    if exc.is_null() {
      let fnobj = JSValueToObject(ctx, fnv, &mut exc);
      if !fnobj.is_null() {
        let args = [jsval(this)];
        JSObjectCallAsFunction(
          ctx,
          fnobj,
          ptr::null_mut(),
          1,
          args.as_ptr(),
          &mut exc,
        );
      }
    }
  }
  // If `transfer()` did not actually neuter the buffer (build lacking transfer,
  // or a no-copy buffer JSC refused to transfer), fall back to the marker set
  // so the C-ABI still observes the detach. When transfer worked, bytes ptr is
  // now null and we leave the set untouched (keeps the deno_core path clean).
  let after =
    unsafe { JSObjectGetArrayBufferBytesPtr(ctx, obj, ptr::null_mut()) };
  if !after.is_null() {
    mark_detached(ctx, obj);
  }
  MaybeBool::JustTrue
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__GetBackingStore(
  this: *const ArrayBuffer,
) -> SharedRef<BackingStore> {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return make_shared_ref(BsInner::new_allocated(0, false));
  }
  backing_store_for_buffer(ctx, jsval(this))
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__NewBackingStore__with_byte_length(
  isolate: *mut RealIsolate,
  byte_length: usize,
) -> *mut BackingStore {
  BsInner::new_allocated(byte_length, false) as *mut BackingStore
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__NewBackingStore__with_data(
  data: *mut c_void,
  byte_length: usize,
  deleter: BackingStoreDeleterCallback,
  deleter_data: *mut c_void,
) -> *mut BackingStore {
  BsInner::boxed(data, byte_length, false, deleter, deleter_data, false)
    as *mut BackingStore
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__BackingStore__Data(
  this: *const BackingStore,
) -> *mut c_void {
  bs_inner(this).map_or(ptr::null_mut(), |b| b.data)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__BackingStore__ByteLength(
  this: *const BackingStore,
) -> usize {
  bs_inner(this).map_or(0, |b| b.byte_length)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__BackingStore__IsShared(
  this: *const BackingStore,
) -> bool {
  bs_inner(this).map_or(false, |b| b.is_shared)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__BackingStore__IsResizableByUserJavaScript(
  this: *const BackingStore,
) -> bool {
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__BackingStore__DELETE(this: *mut BackingStore) {
  let inner = this as *mut BsInner;
  if inner.is_null() {
    return;
  }
  if unsafe { (*inner).refcount.fetch_sub(1, Ordering::SeqCst) } == 1 {
    unsafe { BsInner::destroy(inner) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__BackingStore__COPY(
  ptr: *const SharedPtrBase<BackingStore>,
) -> SharedPtrBase<BackingStore> {
  let inner = sp_get(ptr);
  if !inner.is_null() {
    unsafe { (*inner).refcount.fetch_add(1, Ordering::SeqCst) };
  }
  let mut out: SharedPtrBase<BackingStore> = Default::default();
  sp_set(&mut out, inner);
  out
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__BackingStore__CONVERT__std__unique_ptr(
  unique_ptr: UniquePtr<BackingStore>,
) -> SharedPtrBase<BackingStore> {
  let raw = unique_ptr.into_raw() as *mut BsInner;
  let mut out: SharedPtrBase<BackingStore> = Default::default();
  sp_set(&mut out, raw);
  out
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__BackingStore__get(
  ptr: *const SharedPtrBase<BackingStore>,
) -> *mut BackingStore {
  sp_get(ptr) as *mut BackingStore
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__BackingStore__reset(
  ptr: *mut SharedPtrBase<BackingStore>,
) {
  let inner = sp_get(ptr);
  if !inner.is_null() {
    if unsafe { (*inner).refcount.fetch_sub(1, Ordering::SeqCst) } == 1 {
      unsafe { BsInner::destroy(inner) };
    }
  }
  if !ptr.is_null() {
    sp_set(ptr, ptr::null_mut());
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__BackingStore__use_count(
  ptr: *const SharedPtrBase<BackingStore>,
) -> long {
  let inner = sp_get(ptr);
  if inner.is_null() {
    0
  } else {
    unsafe { (*inner).refcount.load(Ordering::SeqCst) as long }
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__Allocator__NewDefaultAllocator()
-> *mut Allocator {
  Box::into_raw(Box::new(0u8)) as *mut Allocator
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__Allocator__DELETE(this: *mut Allocator) {
  if !this.is_null() {
    unsafe { drop(Box::from_raw(this as *mut u8)) };
  }
}

// The allocator `std::shared_ptr` is modelled with a real, atomically
// refcounted control block so that `clone()` / drop behave like C++'s
// shared_ptr — i.e. `use_count()` is accurate and the underlying allocator is
// freed exactly once (when the last reference drops). The previous
// implementation bitwise-copied the two words and freed on every `reset`, which
// (a) reported a bogus use_count of 1 and (b) double-freed when more than one
// `SharedRef`/`SharedPtr` pointed at the same allocator — an abort that took
// down the whole `test_api` binary (`backing_store_segfault` et al.). Mirrors
// the QuickJS backend's `src/quickjs/allocator.rs`.
//
// `SharedPtrBase<Allocator>` is `[usize; 2]`:
//   word[0] = the `*mut Allocator` object pointer (0 when null)
//   word[1] = a `*mut AtomicUsize` control block (0 when null)
fn alloc_read_words(ptr: *const SharedPtrBase<Allocator>) -> (usize, usize) {
  if ptr.is_null() {
    return (0, 0);
  }
  let w = ptr as *const usize;
  unsafe { (*w, *w.add(1)) }
}

unsafe fn alloc_write_words(
  ptr: *mut SharedPtrBase<Allocator>,
  obj: usize,
  ctrl: usize,
) {
  let w = ptr as *mut usize;
  unsafe {
    *w = obj;
    *w.add(1) = ctrl;
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__ArrayBuffer__Allocator__COPY(
  ptr: *const SharedPtrBase<Allocator>,
) -> SharedPtrBase<Allocator> {
  let (obj, ctrl) = alloc_read_words(ptr);
  if ctrl != 0 {
    unsafe { (*(ctrl as *const AtomicUsize)).fetch_add(1, Ordering::Relaxed) };
  }
  let mut out: SharedPtrBase<Allocator> = Default::default();
  unsafe { alloc_write_words(&mut out, obj, ctrl) };
  out
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__ArrayBuffer__Allocator__CONVERT__std__unique_ptr(
  unique_ptr: UniquePtr<Allocator>,
) -> SharedPtrBase<Allocator> {
  let raw = unique_ptr.into_raw();
  let mut out: SharedPtrBase<Allocator> = Default::default();
  if raw.is_null() {
    return out;
  }
  let ctrl = Box::into_raw(Box::new(AtomicUsize::new(1)));
  unsafe { alloc_write_words(&mut out, raw as usize, ctrl as usize) };
  out
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__ArrayBuffer__Allocator__get(
  ptr: *const SharedPtrBase<Allocator>,
) -> *mut Allocator {
  alloc_read_words(ptr).0 as *mut Allocator
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__ArrayBuffer__Allocator__reset(
  ptr: *mut SharedPtrBase<Allocator>,
) {
  if ptr.is_null() {
    return;
  }
  let (obj, ctrl) = alloc_read_words(ptr);
  if ctrl != 0 {
    // Decrement; free the allocator + control block only on the last reference.
    let prev =
      unsafe { (*(ctrl as *const AtomicUsize)).fetch_sub(1, Ordering::AcqRel) };
    if prev == 1 {
      if obj != 0 {
        v8__ArrayBuffer__Allocator__DELETE(obj as *mut Allocator);
      }
      unsafe { drop(Box::from_raw(ctrl as *mut AtomicUsize)) };
    }
  }
  unsafe { alloc_write_words(ptr, 0, 0) };
}

#[unsafe(no_mangle)]
pub extern "C" fn std__shared_ptr__v8__ArrayBuffer__Allocator__use_count(
  ptr: *const SharedPtrBase<Allocator>,
) -> long {
  let (obj, ctrl) = alloc_read_words(ptr);
  if ctrl != 0 {
    unsafe { (*(ctrl as *const AtomicUsize)).load(Ordering::Acquire) as long }
  } else if obj != 0 {
    1
  } else {
    0
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__Buffer(
  this: *const ArrayBufferView,
) -> *const ArrayBuffer {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  let buf = unsafe {
    JSObjectGetTypedArrayBuffer(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  };
  if buf.is_null() {
    return ptr::null();
  }
  intern_ctx::<ArrayBuffer>(ctx, buf as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__Buffer__Data(
  this: *const ArrayBufferView,
) -> *mut c_void {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null_mut();
  }

  let buf = unsafe {
    JSObjectGetTypedArrayBuffer(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  };
  if buf.is_null() {
    return ptr::null_mut();
  }
  unsafe { JSObjectGetArrayBufferBytesPtr(ctx, buf, ptr::null_mut()) }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__ByteLength(
  this: *const ArrayBufferView,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0;
  }
  unsafe {
    JSObjectGetTypedArrayByteLength(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__ByteOffset(
  this: *const ArrayBufferView,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0;
  }
  unsafe {
    JSObjectGetTypedArrayByteOffset(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__TypedArray__Length(
  this: *const crate::TypedArray,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0;
  }
  unsafe {
    JSObjectGetTypedArrayLength(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__HasBuffer(
  this: *const ArrayBufferView,
) -> bool {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return false;
  }
  let buf = unsafe {
    JSObjectGetTypedArrayBuffer(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  };
  !buf.is_null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__GetContents(
  this: *const ArrayBufferView,
  storage: MemorySpan,
) -> MemorySpan {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return MemorySpan {
      data: ptr::null_mut(),
      size: 0,
    };
  }
  let obj = jsval(this) as JSObjectRef;
  // Compute the data pointer as ArrayBuffer base + byteOffset rather than
  // trusting JSObjectGetTypedArrayBytesPtr: for a typed array that is a VIEW
  // over an existing (e.g. pooled) ArrayBuffer, JSC returns the buffer base
  // (byteOffset NOT applied), so ops read from offset 0. Node's Buffer pools
  // many small buffers into one ArrayBuffer at increasing byteOffsets, so this
  // made every non-first pooled Buffer decode read stale bytes (e.g.
  // `Buffer.from("foo")` => "Hel"). Base + byteOffset is correct regardless.
  let (off, len) = unsafe {
    (
      JSObjectGetTypedArrayByteOffset(ctx, obj, ptr::null_mut()),
      JSObjectGetTypedArrayByteLength(ctx, obj, ptr::null_mut()),
    )
  };
  // Prefer ArrayBuffer base + byteOffset (correct for pooled VIEWS, where
  // JSObjectGetTypedArrayBytesPtr drops the offset). Fall back to the typed
  // array data pointer when the view has no materializable ArrayBuffer (e.g.
  // DataView / detached); that pointer already accounts for any offset.
  let base = unsafe {
    let buffer = JSObjectGetTypedArrayBuffer(ctx, obj, ptr::null_mut());
    if buffer.is_null() {
      ptr::null_mut()
    } else {
      JSObjectGetArrayBufferBytesPtr(ctx, buffer, ptr::null_mut())
    }
  };
  let data = if !base.is_null() {
    unsafe { (base as *mut u8).add(off) }
  } else {
    unsafe {
      JSObjectGetTypedArrayBytesPtr(ctx, obj, ptr::null_mut()) as *mut u8
    }
  };
  if data.is_null() {
    return MemorySpan {
      data: ptr::null_mut(),
      size: 0,
    };
  }
  MemorySpan { data, size: len }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SharedArrayBuffer__New__with_backing_store(
  isolate: *mut RealIsolate,
  backing_store: *const SharedRef<BackingStore>,
) -> *const SharedArrayBuffer {
  let st = iso_state(isolate);
  let ctx =
    st.contexts.last().copied().unwrap_or(ptr::null_mut()) as JSContextRef;
  if ctx.is_null() || backing_store.is_null() {
    return ptr::null();
  }
  let inner = sp_get(backing_store as *const SharedPtrBase<BackingStore>);
  if inner.is_null() {
    return ptr::null();
  }
  let (data, len) = unsafe { ((*inner).data, (*inner).byte_length) };
  unsafe { (*inner).refcount.fetch_add(1, Ordering::SeqCst) };
  unsafe extern "C" fn dealloc(_bytes: *mut c_void, ctx: *mut c_void) {
    crate::jsc::core::ffi_guard(
      || {
        let inner = ctx as *mut BsInner;
        if inner.is_null() {
          return;
        }
        if unsafe { (*inner).refcount.fetch_sub(1, Ordering::SeqCst) } == 1 {
          unsafe { BsInner::destroy(inner) };
        }
      },
      || (),
    )
  }
  let obj = unsafe {
    JSObjectMakeArrayBufferWithBytesNoCopy(
      ctx,
      data,
      len,
      Some(dealloc),
      inner as *mut c_void,
      ptr::null_mut(),
    )
  };
  intern_ctx::<SharedArrayBuffer>(ctx, obj as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SharedArrayBuffer__GetBackingStore(
  this: *const SharedArrayBuffer,
) -> SharedRef<BackingStore> {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return make_shared_ref(BsInner::new_allocated(0, true));
  }

  let mut sref = backing_store_for_buffer(ctx, jsval(this));
  let inner = sp_get(
    &sref as *const SharedRef<BackingStore>
      as *const SharedPtrBase<BackingStore>,
  );
  if !inner.is_null() {
    unsafe { (*inner).is_shared = true };
  }
  sref
}

#[inline]
fn make_typed_array(
  buf: *const ArrayBuffer,
  byte_offset: usize,
  length: usize,
  ty: JSTypedArrayType,
) -> JSValueRef {
  let ctx = current_ctx();
  if ctx.is_null() || buf.is_null() {
    return ptr::null();
  }
  // A zero-length view needs no shared storage, and JSC's
  // ...WithArrayBufferAndOffset path rejects offset==length==0 over an empty
  // buffer as out-of-bounds. Build a standalone empty typed array instead —
  // semantically identical (no elements to alias) and always succeeds.
  if length == 0 {
    let obj = unsafe { JSObjectMakeTypedArray(ctx, ty, 0, ptr::null_mut()) };
    return obj as JSValueRef;
  }
  let obj = unsafe {
    JSObjectMakeTypedArrayWithArrayBufferAndOffset(
      ctx,
      ty,
      jsval(buf) as JSObjectRef,
      byte_offset,
      length,
      ptr::null_mut(),
    )
  };
  obj as JSValueRef
}

macro_rules! typed_array_new {
  ($fn_name:ident, $ty_name:ident, $jsc_ty:expr) => {
    #[unsafe(no_mangle)]
    pub extern "C" fn $fn_name(
      buf_ptr: *const ArrayBuffer,
      byte_offset: usize,
      length: usize,
    ) -> *const crate::$ty_name {
      let v = make_typed_array(buf_ptr, byte_offset, length, $jsc_ty);
      intern::<crate::$ty_name>(v)
    }
  };
}

typed_array_new!(v8__Uint8Array__New, Uint8Array, kJSTypedArrayTypeUint8Array);
typed_array_new!(v8__Int8Array__New, Int8Array, kJSTypedArrayTypeInt8Array);
typed_array_new!(
  v8__Uint16Array__New,
  Uint16Array,
  kJSTypedArrayTypeUint16Array
);
typed_array_new!(v8__Int16Array__New, Int16Array, kJSTypedArrayTypeInt16Array);
typed_array_new!(
  v8__Uint32Array__New,
  Uint32Array,
  kJSTypedArrayTypeUint32Array
);
typed_array_new!(v8__Int32Array__New, Int32Array, kJSTypedArrayTypeInt32Array);
typed_array_new!(
  v8__Float32Array__New,
  Float32Array,
  kJSTypedArrayTypeFloat32Array
);
typed_array_new!(
  v8__Float64Array__New,
  Float64Array,
  kJSTypedArrayTypeFloat64Array
);
typed_array_new!(
  v8__BigInt64Array__New,
  BigInt64Array,
  kJSTypedArrayTypeBigInt64Array
);
typed_array_new!(
  v8__BigUint64Array__New,
  BigUint64Array,
  kJSTypedArrayTypeBigUint64Array
);

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBuffer__SetDetachKey(
  _this: *const ArrayBuffer,
  _key: *const Value,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ArrayBufferView__CopyContents(
  this: *const ArrayBufferView,
  dest: *mut c_void,
  byte_length: crate::support::int,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() || dest.is_null() || byte_length <= 0 {
    return 0;
  }
  let obj = jsval(this) as JSObjectRef;
  let (off, len) = unsafe {
    (
      JSObjectGetTypedArrayByteOffset(ctx, obj, ptr::null_mut()),
      JSObjectGetTypedArrayByteLength(ctx, obj, ptr::null_mut()),
    )
  };
  // Mirror `GetContents`: prefer ArrayBuffer base + byteOffset. For a typed
  // array that is a VIEW over an existing buffer (e.g. `new Uint8Array(buf, 2,
  // 4)` or a pooled Node Buffer), JSObjectGetTypedArrayBytesPtr returns the
  // buffer base with the byteOffset NOT applied, so copying from it reads the
  // wrong bytes. Fall back to the typed-array data pointer only when the view
  // has no materializable ArrayBuffer (that pointer already accounts for any
  // offset).
  let base = unsafe {
    let buffer = JSObjectGetTypedArrayBuffer(ctx, obj, ptr::null_mut());
    if buffer.is_null() {
      ptr::null_mut()
    } else {
      JSObjectGetArrayBufferBytesPtr(ctx, buffer, ptr::null_mut())
    }
  };
  let src = if !base.is_null() {
    unsafe { (base as *mut u8).add(off) }
  } else {
    unsafe {
      JSObjectGetTypedArrayBytesPtr(ctx, obj, ptr::null_mut()) as *mut u8
    }
  };
  if src.is_null() {
    return 0;
  }
  let n = len.min(byte_length as usize);
  unsafe {
    ptr::copy_nonoverlapping(src as *const u8, dest as *mut u8, n);
  }
  n
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__DataView__New(
  arraybuffer: *const ArrayBuffer,
  byte_offset: usize,
  length: usize,
) -> *const DataView {
  let ctx = current_ctx();
  if ctx.is_null() || arraybuffer.is_null() {
    return ptr::null();
  }

  unsafe {
    let mut exc: JSValueRef = ptr::null();
    let src = b"(function(buf,off,len){return new DataView(buf,off,len);})\0";
    let fs = JSStringCreateWithUTF8CString(
      src.as_ptr() as *const std::os::raw::c_char
    );
    let fnv =
      JSEvaluateScript(ctx, fs, ptr::null_mut(), ptr::null_mut(), 1, &mut exc);
    JSStringRelease(fs);
    if !exc.is_null() {
      return ptr::null();
    }
    let fnobj = JSValueToObject(ctx, fnv, &mut exc);
    if fnobj.is_null() {
      return ptr::null();
    }
    let args = [
      jsval(arraybuffer),
      JSValueMakeNumber(ctx, byte_offset as f64),
      JSValueMakeNumber(ctx, length as f64),
    ];
    let v = JSObjectCallAsFunction(
      ctx,
      fnobj,
      ptr::null_mut(),
      3,
      args.as_ptr(),
      &mut exc,
    );
    if !exc.is_null() || v.is_null() {
      return ptr::null();
    }
    intern_ctx::<DataView>(ctx, v)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SharedArrayBuffer__ByteLength(
  this: *const SharedArrayBuffer,
) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0;
  }
  unsafe {
    JSObjectGetArrayBufferByteLength(
      ctx,
      jsval(this) as JSObjectRef,
      ptr::null_mut(),
    )
  }
}

typed_array_new!(
  v8__Uint8ClampedArray__New,
  Uint8ClampedArray,
  kJSTypedArrayTypeUint8ClampedArray
);

#[unsafe(no_mangle)]
pub extern "C" fn v8__Float16Array__New(
  buf_ptr: *const ArrayBuffer,
  byte_offset: usize,
  length: usize,
) -> *const crate::Float16Array {
  let ctx = current_ctx();
  if ctx.is_null() || buf_ptr.is_null() {
    return ptr::null();
  }
  unsafe {
    let mut exc: JSValueRef = ptr::null();
    let src =
      b"(function(buf,off,len){return new Float16Array(buf,off,len);})\0";
    let fs = JSStringCreateWithUTF8CString(
      src.as_ptr() as *const std::os::raw::c_char
    );
    let fnv =
      JSEvaluateScript(ctx, fs, ptr::null_mut(), ptr::null_mut(), 1, &mut exc);
    JSStringRelease(fs);
    if !exc.is_null() {
      return ptr::null();
    }
    let fnobj = JSValueToObject(ctx, fnv, &mut exc);
    if fnobj.is_null() {
      return ptr::null();
    }
    let args = [
      jsval(buf_ptr),
      JSValueMakeNumber(ctx, byte_offset as f64),
      JSValueMakeNumber(ctx, length as f64),
    ];
    let v = JSObjectCallAsFunction(
      ctx,
      fnobj,
      ptr::null_mut(),
      3,
      args.as_ptr(),
      &mut exc,
    );
    if !exc.is_null() || v.is_null() {
      return ptr::null();
    }
    intern_ctx::<crate::Float16Array>(ctx, v)
  }
}

// ---------------------------------------------------------------------------
// Link-stubs for v8 C-ABI symbols that `test_api.rs` references but this
// backend doesn't implement yet. Each returns a benign default
// (null / 0 / false / `Nothing`) so the target LINKS and the many tests that
// don't touch these paths run; tests that do exercise them fail gracefully
// without crashing. Promote individual stubs to real implementations over time.
// ---------------------------------------------------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn v8__SharedArrayBuffer__NewBackingStore__with_data(
  _data: *mut std::os::raw::c_void,
  _byte_length: usize,
  _deleter: *const std::os::raw::c_void,
  _deleter_data: *mut std::os::raw::c_void,
) -> *mut std::os::raw::c_void {
  std::ptr::null_mut()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SharedArrayBuffer__New__with_byte_length(
  _isolate: *mut std::os::raw::c_void,
  _byte_length: usize,
) -> *const std::os::raw::c_void {
  std::ptr::null()
}