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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
//! JSC-backed shims for the "function" family:
//! Function / FunctionCallbackInfo / ReturnValue / Template / ObjectTemplate /
//! Signature / External.
#![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::{
  Context, Data, External, Function, FunctionCallback, FunctionCallbackInfo,
  FunctionTemplate, Name, Object, ObjectTemplate, PropertyAttribute,
  RealIsolate, Signature, String, Value,
};
use std::convert::TryFrom;
use std::os::raw::{c_char, c_void};
use std::ptr;

#[repr(C)]
struct FnJSClassDefinition {
  version: std::os::raw::c_int,
  attributes: u32,
  className: *const c_char,
  parentClass: JSClassRef,
  staticValues: *const c_void,
  staticFunctions: *const c_void,
  initialize: *const c_void,
  finalize: *const c_void,
  hasProperty: *const c_void,
  getProperty: *const c_void,
  setProperty: *const c_void,
  deleteProperty: *const c_void,
  getPropertyNames: *const c_void,
  callAsFunction: *const c_void,
  callAsConstructor: *const c_void,
  hasInstance: *const c_void,
  convertToType: *const c_void,
}

#[repr(C)]
struct RawReturnValue(usize);

#[repr(C)]
struct RawFunctionCallbackInfoParts {
  isolate: *mut RealIsolate,
  return_value: usize,
  data: *const Value,
  length: crate::support::int,
}

struct FnBridge {
  callback: FunctionCallback,
  data: JSValueRef,
  ctx: JSGlobalContextRef,
}

#[repr(C)]
struct CbInfo {
  isolate: *mut RealIsolate,
  ctx: JSContextRef,
  this: JSValueRef,
  data: JSValueRef,
  new_target: JSValueRef,
  is_construct: bool,
  args: Vec<JSValueRef>,

  return_slot: Box<JSValueRef>,
}

struct FnTemplate {
  callback: FunctionCallback,
  data: JSValueRef,
  length: i32,
  class_name: Option<std::string::String>,
  proto: *mut ObjTemplate,
  instance: *mut ObjTemplate,
  parent: *const FnTemplate,

  props: Vec<(JSValueRef, JSValueRef, u32)>,

  constructable: bool,

  cached_proto: JSValueRef,
}

struct TemplAccessor {
  key: JSValueRef,
  getter: *const FnTemplate,
  setter: *const FnTemplate,
  attr: u32,
}

struct ObjTemplate {
  internal_field_count: i32,
  props: Vec<(JSValueRef, JSValueRef, u32)>,
  accessors: Vec<TemplAccessor>,

  parent_fn: *const FnTemplate,
}

thread_local! {
    static FN_CLASS: std::cell::Cell<JSClassRef> = const { std::cell::Cell::new(ptr::null_mut()) };
}

fn fn_class() -> JSClassRef {
  FN_CLASS.with(|c| {
    let existing = c.get();
    if !existing.is_null() {
      return existing;
    }
    let def = FnJSClassDefinition {
      version: 0,
      attributes: 0,
      className: c"v8jsc_fn".as_ptr(),
      parentClass: ptr::null_mut(),
      staticValues: ptr::null(),
      staticFunctions: ptr::null(),
      initialize: ptr::null(),
      finalize: fn_finalize as *const c_void,
      hasProperty: ptr::null(),
      getProperty: ptr::null(),
      setProperty: ptr::null(),
      deleteProperty: ptr::null(),
      getPropertyNames: ptr::null(),
      callAsFunction: fn_trampoline as *const c_void,
      callAsConstructor: fn_construct_trampoline as *const c_void,
      hasInstance: ptr::null(),
      convertToType: ptr::null(),
    };
    let cls =
      unsafe { JSClassCreate(&def as *const _ as *const JSClassDefinition) };
    c.set(cls);
    cls
  })
}

unsafe extern "C" fn fn_finalize(object: JSObjectRef) {
  crate::jsc::core::ffi_guard(
    || {
      let p = unsafe { JSObjectGetPrivate(object) } as *mut FnBridge;
      if !p.is_null() {
        drop(unsafe { Box::from_raw(p) });
      }
    },
    || (),
  )
}

unsafe fn dispatch(
  ctx: JSContextRef,
  bridge: &FnBridge,
  this: JSValueRef,
  new_target: JSValueRef,
  is_construct: bool,
  argc: usize,
  argv: *const JSValueRef,
  out_exc: *mut JSValueRef,
) -> JSValueRef {
  let mut args = Vec::with_capacity(argc);
  for i in 0..argc {
    args.push(unsafe { *argv.add(i) });
  }

  let iso = current_iso();
  crate::jsc::core::clear_pending_exception(iso);
  let info = Box::new(CbInfo {
    isolate: iso,
    ctx,
    this,
    data: bridge.data,
    new_target,
    is_construct,
    args,
    return_slot: Box::new(ptr::null()),
  });
  let info_ptr = Box::into_raw(info) as *const FunctionCallbackInfo;
  unsafe { (bridge.callback)(info_ptr) };

  let info = unsafe { Box::from_raw(info_ptr as *mut CbInfo) };
  let ret = *info.return_slot;

  let pending = crate::jsc::core::peek_pending_exception(iso);
  if !pending.is_null() {
    if !out_exc.is_null() {
      unsafe { *out_exc = pending };
    }
    crate::jsc::core::clear_pending_exception(iso);
    return unsafe { JSValueMakeUndefined(ctx) };
  }
  if ret.is_null() {
    unsafe { JSValueMakeUndefined(ctx) }
  } else {
    ret
  }
}

unsafe extern "C" fn fn_trampoline(
  ctx: JSContextRef,
  function: JSObjectRef,
  this_object: JSObjectRef,
  argc: usize,
  argv: *const JSValueRef,
  exception: *mut JSValueRef,
) -> JSValueRef {
  crate::jsc::core::ffi_guard(
    || {
      let bridge = unsafe { JSObjectGetPrivate(function) } as *const FnBridge;
      if bridge.is_null() {
        return unsafe { JSValueMakeUndefined(ctx) };
      }
      unsafe {
        dispatch(
          ctx,
          &*bridge,
          this_object as JSValueRef,
          JSValueMakeUndefined(ctx),
          false,
          argc,
          argv,
          exception,
        )
      }
    },
    || unsafe { panic_to_exception(ctx, exception) },
  )
}

/// Fallback for a panicking call/construct trampoline: surface the panic as a
/// thrown JS exception (so the JS call fails deterministically instead of
/// aborting the process) and return `undefined`.
unsafe fn panic_to_exception(
  ctx: JSContextRef,
  exception: *mut JSValueRef,
) -> JSValueRef {
  unsafe {
    if !exception.is_null() && (*exception).is_null() {
      let msg = JSStringCreateWithUTF8CString(
        c"v82jsc: rust panic in native callback".as_ptr(),
      );
      let s = JSValueMakeString(ctx, msg);
      JSStringRelease(msg);
      *exception = s;
    }
    JSValueMakeUndefined(ctx)
  }
}

unsafe extern "C" fn fn_construct_trampoline(
  ctx: JSContextRef,
  function: JSObjectRef,
  argc: usize,
  argv: *const JSValueRef,
  exception: *mut JSValueRef,
) -> JSObjectRef {
  crate::jsc::core::ffi_guard(
    || {
      let bridge = unsafe { JSObjectGetPrivate(function) } as *const FnBridge;
      if bridge.is_null() {
        return unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) };
      }

      let this = unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) };
      unsafe {
        let proto_key = JSStringCreateWithUTF8CString(c"prototype".as_ptr());
        let mut exc: JSValueRef = ptr::null();
        let proto = JSObjectGetProperty(ctx, function, proto_key, &mut exc);
        JSStringRelease(proto_key);
        if !proto.is_null() && JSValueIsObject(ctx, proto) {
          JSObjectSetPrototype(ctx, this, proto);
        }
      }
      let r = unsafe {
        dispatch(
          ctx,
          &*bridge,
          this as JSValueRef,
          function as JSValueRef,
          true,
          argc,
          argv,
          exception,
        )
      };

      if !exception.is_null() && !unsafe { *exception }.is_null() {
        return unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) };
      }

      if !r.is_null() && unsafe { JSValueIsObject(ctx, r) } {
        r as JSObjectRef
      } else {
        this
      }
    },
    || unsafe {
      panic_to_exception(ctx, exception);
      JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut())
    },
  )
}

unsafe fn make_function(
  ctx: JSContextRef,
  callback: FunctionCallback,
  data: JSValueRef,
) -> JSObjectRef {
  unsafe { make_function_len(ctx, callback, data, 0) }
}

thread_local! {
    static STR_LENGTH: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_NAME: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_PROTOTYPE: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_FUNCTION: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_OBJECT: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_DEFINE_PROPERTY: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_VALUE: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
    static STR_CONFIGURABLE: std::cell::Cell<JSStringRef> = const { std::cell::Cell::new(ptr::null_mut()) };
}

#[inline]
unsafe fn cached_str(
  cell: &'static std::thread::LocalKey<std::cell::Cell<JSStringRef>>,
  lit: *const std::os::raw::c_char,
) -> JSStringRef {
  cell.with(|c| {
    let existing = c.get();
    if !existing.is_null() {
      return existing;
    }
    let s = unsafe { JSStringCreateWithUTF8CString(lit) };

    let s = unsafe { JSStringRetain(s) };
    c.set(s);
    s
  })
}

unsafe fn make_function_len(
  ctx: JSContextRef,
  callback: FunctionCallback,
  data: JSValueRef,
  length: i32,
) -> JSObjectRef {
  let gctx = unsafe { JSContextGetGlobalContext(ctx) };
  if !data.is_null() {
    unsafe { JSValueProtect(gctx, data) };
  }
  let bridge = Box::new(FnBridge {
    callback,
    data,
    ctx: gctx,
  });
  let obj = unsafe {
    JSObjectMake(ctx, fn_class(), Box::into_raw(bridge) as *mut c_void)
  };

  let key = unsafe { cached_str(&STR_LENGTH, c"length".as_ptr()) };
  let lenval = unsafe { JSValueMakeNumber(ctx, length.max(0) as f64) };
  let mut exc: JSValueRef = ptr::null();
  unsafe {
    JSObjectSetProperty(ctx, obj, key, lenval, 2 | 4, &mut exc);
  }

  unsafe {
    let fp = function_prototype(ctx);
    if !fp.is_null() {
      JSObjectSetPrototype(ctx, obj, fp);
    }
  }
  obj
}

unsafe fn function_prototype(ctx: JSContextRef) -> JSValueRef {
  // Fetch `Function.prototype` FRESH from the current context every time. It
  // must NOT be cached keyed by the global-context pointer: deno_core creates
  // and disposes a JsRuntime (and thus a JSGlobalContextRef) per test, and the
  // allocator readily reuses a freed gctx's address for the next runtime. A
  // pointer-keyed cache then returns the *dangling* Function.prototype of the
  // freed context; using it as a new object's prototype corrupts JSC's
  // structure chain and sends `JSObject::didBecomePrototype` into unbounded
  // recursion → stack-overflow SIGSEGV that non-deterministically truncated the
  // whole binary (denoland/divybot#653). `Function.prototype` is a permanent
  // global of the live context, so it needs no protect.
  unsafe {
    let global = JSContextGetGlobalObject(ctx);
    let fkey = cached_str(&STR_FUNCTION, c"Function".as_ptr());
    let mut exc: JSValueRef = ptr::null();
    let func_ctor = JSObjectGetProperty(ctx, global, fkey, &mut exc);
    if func_ctor.is_null() || !JSValueIsObject(ctx, func_ctor) {
      return ptr::null();
    }
    let pkey = cached_str(&STR_PROTOTYPE, c"prototype".as_ptr());
    JSObjectGetProperty(ctx, func_ctor as JSObjectRef, pkey, &mut exc)
  }
}

#[inline]
fn cbinfo<'a>(this: *const FunctionCallbackInfo) -> &'a mut CbInfo {
  unsafe { &mut *(this as *mut CbInfo) }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__External__New(
  isolate: *mut RealIsolate,
  value: *mut c_void,
) -> *const External {
  // V8 permits `External::new` on a bare HandleScope (no entered Context);
  // fall back to the isolate's base context so the object can be created.
  let ctx = crate::jsc::core::ensure_ctx(isolate);
  if ctx.is_null() {
    return ptr::null();
  }

  let obj = unsafe { JSObjectMake(ctx, ext_class(), value) };
  intern_ctx::<External>(ctx, obj as JSValueRef)
}

thread_local! {
    static EXT_CLASS: std::cell::Cell<JSClassRef> = const { std::cell::Cell::new(ptr::null_mut()) };
}

fn ext_class() -> JSClassRef {
  EXT_CLASS.with(|c| {
    let existing = c.get();
    if !existing.is_null() {
      return existing;
    }
    let def = FnJSClassDefinition {
      version: 0,
      attributes: 0,
      className: c"v8jsc_external".as_ptr(),
      parentClass: ptr::null_mut(),
      staticValues: ptr::null(),
      staticFunctions: ptr::null(),
      initialize: ptr::null(),
      finalize: ptr::null(),
      hasProperty: ptr::null(),
      getProperty: ptr::null(),
      setProperty: ptr::null(),
      deleteProperty: ptr::null(),
      getPropertyNames: ptr::null(),
      callAsFunction: ptr::null(),
      callAsConstructor: ptr::null(),
      hasInstance: ptr::null(),
      convertToType: ptr::null(),
    };
    let cls =
      unsafe { JSClassCreate(&def as *const _ as *const JSClassDefinition) };
    c.set(cls);
    cls
  })
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__External__Value(this: *const External) -> *mut c_void {
  if this.is_null() {
    return ptr::null_mut();
  }
  unsafe { JSObjectGetPrivate(jsval(this) as JSObjectRef) }
}

pub(crate) fn value_is_external(v: JSValueRef) -> bool {
  if v.is_null() {
    return false;
  }
  let ctx = current_ctx();
  if ctx.is_null() {
    return false;
  }
  unsafe { JSValueIsObjectOfClass(ctx, v, ext_class()) }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__New(
  context: *const Context,
  callback: FunctionCallback,
  data_or_null: *const Value,
  length: i32,
  constructor_behavior: crate::ConstructorBehavior,
  side_effect_type: crate::SideEffectType,
) -> *const Function {
  let _ = (constructor_behavior, side_effect_type);
  let ctx = ctx_of(context) as JSContextRef;
  if ctx.is_null() {
    return ptr::null();
  }
  let f =
    unsafe { make_function_len(ctx, callback, jsval(data_or_null), length) };
  intern_ctx::<Function>(ctx, f as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__Call(
  this: *const Function,
  context: *const Context,
  recv: *const Value,
  argc: crate::support::int,
  argv: *const *const Value,
) -> *const Value {
  let ctx = ctx_of(context) as JSContextRef;
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  // Once execution has been terminated, the JS loop only resumes through call
  // boundaries like this one (e.g. deno resolving a completed op). A tight CPU
  // loop unwinds via the watchdog, but a loop that yields on `await` does not —
  // so refuse to re-enter JS and surface an empty (undefined) pending exception
  // that deno turns into "execution terminated".
  let iso = crate::jsc::core::current_iso();
  if !iso.is_null() && crate::jsc::terminate::is_terminating(iso) {
    let undef = unsafe { JSValueMakeUndefined(ctx) };
    crate::jsc::core::record_pending_exception(ctx, undef);
    return ptr::null();
  }
  let func = jsval(this) as JSObjectRef;
  let recv_obj = if recv.is_null() {
    ptr::null_mut()
  } else {
    jsval(recv) as JSObjectRef
  };
  let n = argc.max(0) as usize;
  let mut args: Vec<JSValueRef> = Vec::with_capacity(n);
  for i in 0..n {
    let p = unsafe { *argv.add(i) };
    args.push(jsval(p));
  }
  let mut exc: JSValueRef = ptr::null();
  let r = unsafe {
    JSObjectCallAsFunction(ctx, func, recv_obj, n, args.as_ptr(), &mut exc)
  };
  if r.is_null() {
    if !exc.is_null() && std::env::var("V82JSC_DEBUG").is_ok() {
      unsafe {
        let s = JSValueToStringCopy(ctx, exc, ptr::null_mut());
        if !s.is_null() {
          let max = JSStringGetMaximumUTF8CStringSize(s);
          let mut buf = vec![0u8; max];
          let n = JSStringGetUTF8CString(s, buf.as_mut_ptr() as *mut _, max);
          JSStringRelease(s);
          buf.truncate(n.saturating_sub(1));
          eprintln!(
            "[v82jsc] Function__Call threw: {}",
            std::string::String::from_utf8_lossy(&buf)
          );
        }
      }
    }

    if !exc.is_null() {
      crate::jsc::core::record_pending_exception(ctx, exc);
    }
    return ptr::null();
  }
  intern_ctx::<Value>(ctx, r)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__NewInstance(
  this: *const Function,
  context: *const Context,
  argc: crate::support::int,
  argv: *const *const Value,
) -> *const Object {
  let ctx = ctx_of(context) as JSContextRef;
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  let func = jsval(this) as JSObjectRef;
  let n = argc.max(0) as usize;
  let mut args: Vec<JSValueRef> = Vec::with_capacity(n);
  for i in 0..n {
    args.push(jsval(unsafe { *argv.add(i) }));
  }
  let mut exc: JSValueRef = ptr::null();
  let r =
    unsafe { JSObjectCallAsConstructor(ctx, func, n, args.as_ptr(), &mut exc) };
  if r.is_null() {
    return ptr::null();
  }
  intern_ctx::<Object>(ctx, r as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__SetName(
  this: *const Function,
  name: *const String,
) {
  if this.is_null() || name.is_null() {
    return;
  }
  let ctx = current_ctx();
  if ctx.is_null() {
    return;
  }
  let obj = jsval(this) as JSObjectRef;
  // A function inherits `name` (value "") from `Function.prototype` as a
  // non-writable data property. A plain `[[Set]]` (`JSObjectSetProperty`) walks
  // the prototype chain, finds that non-writable `name`, and silently does
  // nothing — so the op's real name never sticks and `fn.name` reads "". Force
  // an *own*, configurable `name` via `Object.defineProperty`, matching V8's
  // function-name descriptor (writable:false, enumerable:false, configurable).
  unsafe { define_own_name(ctx, obj, jsval(name)) };
}

/// `Object.defineProperty(obj, "name", { value, writable:false,
/// enumerable:false, configurable:true })`. Used to overwrite the inherited
/// non-writable `Function.prototype.name`, which a plain `[[Set]]` can't shadow.
unsafe fn define_own_name(
  ctx: JSContextRef,
  obj: JSObjectRef,
  value: JSValueRef,
) {
  unsafe {
    let global = JSContextGetGlobalObject(ctx);
    let okey = cached_str(&STR_OBJECT, c"Object".as_ptr());
    let mut exc: JSValueRef = ptr::null();
    let object_ctor = JSObjectGetProperty(ctx, global, okey, &mut exc);
    if object_ctor.is_null() || !JSValueIsObject(ctx, object_ctor) {
      return;
    }
    let dpkey = cached_str(&STR_DEFINE_PROPERTY, c"defineProperty".as_ptr());
    let define =
      JSObjectGetProperty(ctx, object_ctor as JSObjectRef, dpkey, &mut exc);
    if define.is_null() || !JSValueIsObject(ctx, define) {
      return;
    }
    let define = define as JSObjectRef;
    if !JSObjectIsFunction(ctx, define) {
      return;
    }

    let desc = JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut());
    let value_str = cached_str(&STR_VALUE, c"value".as_ptr());
    JSObjectSetProperty(ctx, desc, value_str, value, 0, &mut exc);
    let conf_str = cached_str(&STR_CONFIGURABLE, c"configurable".as_ptr());
    JSObjectSetProperty(
      ctx,
      desc,
      conf_str,
      JSValueMakeBoolean(ctx, true),
      0,
      &mut exc,
    );

    let name_key = cached_str(&STR_NAME, c"name".as_ptr());
    let name_val = JSValueMakeString(ctx, name_key);
    let args = [obj as JSValueRef, name_val, desc as JSValueRef];
    JSObjectCallAsFunction(
      ctx,
      define,
      ptr::null_mut(),
      args.len(),
      args.as_ptr(),
      &mut exc,
    );
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__CreateCodeCache(
  script: *const Function,
) -> *mut crate::CachedData<'static> {
  // JSC has no bytecode-cache export; return a placeholder (non-null) cache so
  // deno's CJS path (`function.create_code_cache().ok_or_else(...)`) doesn't
  // hard-error. The consume path rejects it and recompiles. Mirrors the
  // UnboundModuleScript placeholder.
  let _ = script;
  crate::jsc::module::make_placeholder_code_cache()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__GetIsolate(
  this: *const FunctionCallbackInfo,
) -> *mut RealIsolate {
  if this.is_null() {
    return current_iso();
  }
  cbinfo(this).isolate
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__GetParts(
  this: *const FunctionCallbackInfo,
) -> RawFunctionCallbackInfoParts {
  if this.is_null() {
    return RawFunctionCallbackInfoParts {
      isolate: current_iso(),
      return_value: 0,
      data: ptr::null(),
      length: 0,
    };
  }
  let info = cbinfo(this);
  let slot = &mut *info.return_slot as *mut JSValueRef;
  RawFunctionCallbackInfoParts {
    isolate: info.isolate,
    return_value: slot as usize,
    data: info.data as *const Value,
    length: info.args.len() as crate::support::int,
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__Data(
  this: *const FunctionCallbackInfo,
) -> *const Value {
  if this.is_null() {
    return ptr::null();
  }
  let info = cbinfo(this);
  if info.data.is_null() {
    return (unsafe { JSValueMakeUndefined(info.ctx) }) as *const Value;
  }
  info.data as *const Value
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__This(
  this: *const FunctionCallbackInfo,
) -> *const Object {
  if this.is_null() {
    return ptr::null();
  }
  let info = cbinfo(this);
  info.this as *const Object
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__Get(
  this: *const FunctionCallbackInfo,
  index: crate::support::int,
) -> *const Value {
  if this.is_null() {
    return ptr::null();
  }
  let info = cbinfo(this);
  if index < 0 {
    return (unsafe { JSValueMakeUndefined(info.ctx) }) as *const Value;
  }
  match info.args.get(index as usize) {
    Some(&v) => v as *const Value,
    None => (unsafe { JSValueMakeUndefined(info.ctx) }) as *const Value,
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__Length(
  this: *const FunctionCallbackInfo,
) -> crate::support::int {
  if this.is_null() {
    return 0;
  }
  cbinfo(this).args.len() as crate::support::int
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__GetReturnValue(
  this: *const FunctionCallbackInfo,
) -> usize {
  if this.is_null() {
    return 0;
  }
  let info = cbinfo(this);
  (&mut *info.return_slot as *mut JSValueRef) as usize
}

#[inline]
unsafe fn rv_slot(this: *mut RawReturnValue) -> *mut JSValueRef {
  if this.is_null() {
    return ptr::null_mut();
  }
  unsafe { (*this).0 as *mut JSValueRef }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Set(
  this: *mut RawReturnValue,
  value: *const Value,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    unsafe { *slot = jsval(value) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Set__Bool(
  this: *mut RawReturnValue,
  value: bool,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeBoolean(current_ctx(), value) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Set__Int32(
  this: *mut RawReturnValue,
  value: i32,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeNumber(current_ctx(), value as f64) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Set__Uint32(
  this: *mut RawReturnValue,
  value: u32,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeNumber(current_ctx(), value as f64) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Set__Double(
  this: *mut RawReturnValue,
  value: f64,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeNumber(current_ctx(), value) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__SetNull(this: *mut RawReturnValue) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeNull(current_ctx()) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__SetUndefined(
  this: *mut RawReturnValue,
) {
  let slot = unsafe { rv_slot(this) };
  if !slot.is_null() {
    let v = unsafe { JSValueMakeUndefined(current_ctx()) };
    unsafe { *slot = v };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Template__Set(
  this: *const crate::Template,
  key: *const Name,
  value: *const Data,
  attr: PropertyAttribute,
) {
  if this.is_null() {
    return;
  }

  let raw = this as *const c_void as usize;
  with_template_props(raw, |props| {
    props.push((jsval(key), jsval(value), attr.as_u32_lenient()));
  });
}

trait AttrU32 {
  fn as_u32_lenient(&self) -> u32;
}
impl AttrU32 for PropertyAttribute {
  fn as_u32_lenient(&self) -> u32 {
    unsafe { *(self as *const PropertyAttribute as *const u32) }
  }
}

thread_local! {
    static TEMPLATES: std::cell::RefCell<std::collections::HashMap<usize, TemplKind>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

#[derive(Clone, Copy)]
enum TemplKind {
  Func,
  Obj,
}

fn register_template(p: usize, kind: TemplKind) {
  TEMPLATES.with(|t| {
    t.borrow_mut().insert(p, kind);
  });
}

pub(crate) fn is_template_ptr(p: *const c_void) -> bool {
  if p.is_null() {
    return false;
  }
  TEMPLATES.with(|t| t.borrow().contains_key(&(p as usize)))
}

fn with_template_props(
  p: usize,
  f: impl FnOnce(&mut Vec<(JSValueRef, JSValueRef, u32)>),
) {
  let kind = TEMPLATES.with(|t| t.borrow().get(&p).copied());
  match kind {
    Some(TemplKind::Func) => {
      let t = unsafe { &mut *(p as *mut FnTemplate) };
      f(&mut t.props);
    }
    Some(TemplKind::Obj) => {
      let t = unsafe { &mut *(p as *mut ObjTemplate) };
      f(&mut t.props);
    }
    None => {}
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__New(
  isolate: *mut RealIsolate,
  callback: FunctionCallback,
  data_or_null: *const Value,
  signature_or_null: *const Signature,
  length: i32,
  constructor_behavior: crate::ConstructorBehavior,
  side_effect_type: crate::SideEffectType,
  c_functions: *const crate::fast_api::CFunction,
  c_functions_len: usize,
) -> *const FunctionTemplate {
  let _ = (
    isolate,
    signature_or_null,
    side_effect_type,
    c_functions,
    c_functions_len,
  );
  let constructable =
    matches!(constructor_behavior, crate::ConstructorBehavior::Allow);
  let proto = Box::into_raw(Box::new(ObjTemplate {
    internal_field_count: 0,
    props: Vec::new(),
    accessors: Vec::new(),
    parent_fn: ptr::null(),
  }));
  let instance = Box::into_raw(Box::new(ObjTemplate {
    internal_field_count: 0,
    props: Vec::new(),
    accessors: Vec::new(),
    parent_fn: ptr::null(),
  }));
  register_template(proto as usize, TemplKind::Obj);
  register_template(instance as usize, TemplKind::Obj);
  let t = Box::into_raw(Box::new(FnTemplate {
    callback,
    data: jsval(data_or_null),
    length,
    class_name: None,
    proto,
    instance,
    parent: ptr::null(),
    props: Vec::new(),
    constructable,
    cached_proto: ptr::null(),
  }));

  unsafe { (*instance).parent_fn = t };
  register_template(t as usize, TemplKind::Func);
  t as *const FunctionTemplate
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__GetFunction(
  this: *const FunctionTemplate,
  context: *const Context,
) -> *const Function {
  if this.is_null() {
    return ptr::null();
  }
  let ctx = ctx_of(context) as JSContextRef;
  if ctx.is_null() {
    return ptr::null();
  }
  let t = unsafe { &*(this as *const FnTemplate) };
  let f = unsafe { make_function_len(ctx, t.callback, t.data, t.length) };

  if let Some(name) = &t.class_name {
    if let Ok(cname) = std::ffi::CString::new(name.as_str()) {
      let nameval = unsafe {
        let s = JSStringCreateWithUTF8CString(cname.as_ptr());
        let v = JSValueMakeString(ctx, s);
        JSStringRelease(s);
        v
      };
      // Force an own `name` — a plain set can't shadow the inherited
      // non-writable `Function.prototype.name` (see `v8__Function__SetName`).
      unsafe { define_own_name(ctx, f, nameval) };
    }
  }

  apply_props(ctx, f, &t.props);

  if t.constructable {
    let proto_obj =
      unsafe { build_prototype_object(ctx, this as *const FnTemplate) };
    let key = unsafe { cached_str(&STR_PROTOTYPE, c"prototype".as_ptr()) };
    let mut exc: JSValueRef = ptr::null();
    unsafe {
      JSObjectSetProperty(ctx, f, key, proto_obj as JSValueRef, 0, &mut exc);
    }
  }

  intern_ctx::<Function>(ctx, f as JSValueRef)
}

unsafe fn build_prototype_object(
  ctx: JSContextRef,
  tp: *const FnTemplate,
) -> JSObjectRef {
  let t = unsafe { &mut *(tp as *mut FnTemplate) };
  if !t.cached_proto.is_null() {
    return t.cached_proto as JSObjectRef;
  }
  let proto_obj =
    unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) };
  let proto = unsafe { &*t.proto };
  if !proto.props.is_empty() {
    apply_props(ctx, proto_obj, &proto.props);
  }
  apply_accessors(ctx, proto_obj, &proto.accessors);

  if !t.parent.is_null() {
    let parent_proto = unsafe { build_prototype_object(ctx, t.parent) };
    unsafe { JSObjectSetPrototype(ctx, proto_obj, parent_proto as JSValueRef) };
  }

  let gctx = unsafe { JSContextGetGlobalContext(ctx) };
  unsafe { JSValueProtect(gctx, proto_obj as JSValueRef) };
  t.cached_proto = proto_obj as JSValueRef;
  proto_obj
}

fn apply_props(
  ctx: JSContextRef,
  obj: JSObjectRef,
  props: &[(JSValueRef, JSValueRef, u32)],
) {
  for &(key, value, attr) in props {
    if key.is_null() {
      continue;
    }
    let mut exc: JSValueRef = ptr::null();
    let keystr = unsafe { JSValueToStringCopy(ctx, key, &mut exc) };
    if keystr.is_null() {
      continue;
    }

    let value = materialize_template_value(ctx, value);
    unsafe {
      JSObjectSetProperty(ctx, obj, keystr, value, attr, &mut exc);
      JSStringRelease(keystr);
    }
  }
}

fn materialize_template_value(
  ctx: JSContextRef,
  value: JSValueRef,
) -> JSValueRef {
  if value.is_null() {
    return value;
  }
  let raw = value as *const c_void as usize;
  let kind = TEMPLATES.with(|t| t.borrow().get(&raw).copied());
  match kind {
    Some(TemplKind::Func) => {
      let f = v8__FunctionTemplate__GetFunction(
        value as *const FunctionTemplate,
        ctx as *const Context,
      );
      if f.is_null() { value } else { jsval(f) }
    }
    Some(TemplKind::Obj) => {
      let o = v8__ObjectTemplate__NewInstance(
        value as *const ObjectTemplate,
        ctx as *const Context,
      );
      if o.is_null() { value } else { jsval(o) }
    }
    None => value,
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__Inherit(
  this: *const FunctionTemplate,
  parent: *const FunctionTemplate,
) {
  if this.is_null() {
    return;
  }
  let t = unsafe { &mut *(this as *mut FnTemplate) };
  t.parent = parent as *const FnTemplate;
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__PrototypeTemplate(
  this: *const FunctionTemplate,
) -> *const ObjectTemplate {
  if this.is_null() {
    return ptr::null();
  }
  let t = unsafe { &*(this as *const FnTemplate) };
  t.proto as *const ObjectTemplate
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__InstanceTemplate(
  this: *const FunctionTemplate,
) -> *const ObjectTemplate {
  if this.is_null() {
    return ptr::null();
  }
  let t = unsafe { &*(this as *const FnTemplate) };
  t.instance as *const ObjectTemplate
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__SetClassName(
  this: *const FunctionTemplate,
  name: *const String,
) {
  if this.is_null() || name.is_null() {
    return;
  }
  let t = unsafe { &mut *(this as *mut FnTemplate) };
  let ctx = current_ctx();
  if ctx.is_null() {
    return;
  }
  let mut exc: JSValueRef = ptr::null();
  let s = unsafe { JSValueToStringCopy(ctx, jsval(name), &mut exc) };
  if s.is_null() {
    return;
  }
  let max = unsafe { JSStringGetMaximumUTF8CStringSize(s) };
  let mut buf = vec![0u8; max];
  let n =
    unsafe { JSStringGetUTF8CString(s, buf.as_mut_ptr() as *mut c_char, max) };
  unsafe { JSStringRelease(s) };
  if n > 0 {
    buf.truncate(n - 1);
    if let Ok(name) = std::string::String::from_utf8(buf) {
      t.class_name = Some(name);
    }
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__New(
  isolate: *mut RealIsolate,
  templ: *const FunctionTemplate,
) -> *const ObjectTemplate {
  let _ = (isolate, templ);
  let t = Box::into_raw(Box::new(ObjTemplate {
    internal_field_count: 0,
    props: Vec::new(),
    accessors: Vec::new(),
    parent_fn: ptr::null(),
  }));
  register_template(t as usize, TemplKind::Obj);
  t as *const ObjectTemplate
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__NewInstance(
  this: *const ObjectTemplate,
  context: *const Context,
) -> *const Object {
  let ctx = ctx_of(context) as JSContextRef;
  if ctx.is_null() {
    return ptr::null();
  }
  let obj = unsafe { JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut()) };
  if !this.is_null() {
    let t = unsafe { &*(this as *const ObjTemplate) };

    if !t.parent_fn.is_null() {
      let proto_obj = unsafe { build_prototype_object(ctx, t.parent_fn) };
      unsafe { JSObjectSetPrototype(ctx, obj, proto_obj as JSValueRef) };
    }

    apply_props(ctx, obj, &t.props);
    apply_accessors(ctx, obj, &t.accessors);
  }
  intern_ctx::<Object>(ctx, obj as JSValueRef)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetAccessorProperty(
  this: *const ObjectTemplate,
  key: *const Name,
  getter: *const FunctionTemplate,
  setter: *const FunctionTemplate,
  attr: PropertyAttribute,
) {
  if this.is_null() {
    return;
  }
  let t = unsafe { &mut *(this as *mut ObjTemplate) };
  t.accessors.push(TemplAccessor {
    key: jsval(key),
    getter: getter as *const FnTemplate,
    setter: setter as *const FnTemplate,
    attr: attr.as_u32_lenient(),
  });
}

fn apply_accessors(
  ctx: JSContextRef,
  obj: JSObjectRef,
  accessors: &[TemplAccessor],
) {
  if accessors.is_empty() {
    return;
  }
  unsafe {
    let global = JSContextGetGlobalObject(ctx);
    let okey = JSStringCreateWithUTF8CString(c"Object".as_ptr());
    let mut exc: JSValueRef = ptr::null();
    let object_ctor = JSObjectGetProperty(ctx, global, okey, &mut exc);
    JSStringRelease(okey);
    if object_ctor.is_null() || !JSValueIsObject(ctx, object_ctor) {
      return;
    }
    let dpkey = JSStringCreateWithUTF8CString(c"defineProperty".as_ptr());
    let define =
      JSObjectGetProperty(ctx, object_ctor as JSObjectRef, dpkey, &mut exc);
    JSStringRelease(dpkey);
    if define.is_null() || !JSValueIsObject(ctx, define) {
      return;
    }

    let get_str = JSStringCreateWithUTF8CString(c"get".as_ptr());
    let set_str = JSStringCreateWithUTF8CString(c"set".as_ptr());
    let enum_str = JSStringCreateWithUTF8CString(c"enumerable".as_ptr());
    let conf_str = JSStringCreateWithUTF8CString(c"configurable".as_ptr());

    for acc in accessors {
      if acc.key.is_null() {
        continue;
      }
      let desc = JSObjectMake(ctx, ptr::null_mut(), ptr::null_mut());
      if !acc.getter.is_null() {
        let gf = v8__FunctionTemplate__GetFunction(
          acc.getter as *const FunctionTemplate,
          ctx as *const Context,
        );
        if !gf.is_null() {
          JSObjectSetProperty(ctx, desc, get_str, jsval(gf), 0, &mut exc);
        }
      }
      if !acc.setter.is_null() {
        let sf = v8__FunctionTemplate__GetFunction(
          acc.setter as *const FunctionTemplate,
          ctx as *const Context,
        );
        if !sf.is_null() {
          JSObjectSetProperty(ctx, desc, set_str, jsval(sf), 0, &mut exc);
        }
      }

      let enumerable = (acc.attr & 2) == 0;
      let configurable = (acc.attr & 4) == 0;
      JSObjectSetProperty(
        ctx,
        desc,
        enum_str,
        JSValueMakeBoolean(ctx, enumerable),
        0,
        &mut exc,
      );
      JSObjectSetProperty(
        ctx,
        desc,
        conf_str,
        JSValueMakeBoolean(ctx, configurable),
        0,
        &mut exc,
      );

      let args = [obj as JSValueRef, acc.key, desc as JSValueRef];
      JSObjectCallAsFunction(
        ctx,
        define as JSObjectRef,
        object_ctor as JSObjectRef,
        3,
        args.as_ptr(),
        &mut exc,
      );
    }

    JSStringRelease(get_str);
    JSStringRelease(set_str);
    JSStringRelease(enum_str);
    JSStringRelease(conf_str);
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetIndexedPropertyHandler(
  this: *const ObjectTemplate,
  getter: Option<crate::IndexedPropertyGetterCallback>,
  setter: Option<crate::IndexedPropertySetterCallback>,
  query: Option<crate::IndexedPropertyQueryCallback>,
  deleter: Option<crate::IndexedPropertyDeleterCallback>,
  enumerator: Option<crate::IndexedPropertyEnumeratorCallback>,
  definer: Option<crate::IndexedPropertyDefinerCallback>,
  descriptor: Option<crate::IndexedPropertyDescriptorCallback>,
  data_or_null: *const Value,
  flags: crate::PropertyHandlerFlags,
) {
  let _ = (
    this,
    getter,
    setter,
    query,
    deleter,
    enumerator,
    definer,
    descriptor,
    data_or_null,
    flags,
  );
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetInternalFieldCount(
  this: *const ObjectTemplate,
  value: crate::support::int,
) {
  if this.is_null() {
    return;
  }
  let t = unsafe { &mut *(this as *mut ObjTemplate) };
  t.internal_field_count = value;
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetNamedPropertyHandler(
  this: *const ObjectTemplate,
  getter: Option<crate::NamedPropertyGetterCallback>,
  setter: Option<crate::NamedPropertySetterCallback>,
  query: Option<crate::NamedPropertyQueryCallback>,
  deleter: Option<crate::NamedPropertyDeleterCallback>,
  enumerator: Option<crate::NamedPropertyEnumeratorCallback>,
  definer: Option<crate::NamedPropertyDefinerCallback>,
  descriptor: Option<crate::NamedPropertyDescriptorCallback>,
  data_or_null: *const Value,
  flags: crate::PropertyHandlerFlags,
) {
  let _ = (
    this,
    getter,
    setter,
    query,
    deleter,
    enumerator,
    definer,
    descriptor,
    data_or_null,
    flags,
  );
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionCallbackInfo__NewTarget(
  this: *const FunctionCallbackInfo,
) -> *const Value {
  if this.is_null() {
    return ptr::null();
  }
  let info = cbinfo(this);
  if info.is_construct && !info.new_target.is_null() {
    return info.new_target as *const Value;
  }
  (unsafe { JSValueMakeUndefined(info.ctx) }) as *const Value
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__PropertyCallbackInfo__GetIsolate(
  _this: *const c_void,
) -> *mut RealIsolate {
  crate::jsc::core::current_iso()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__PropertyCallbackInfo__GetReturnValue(
  _this: *const c_void,
) -> usize {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__PropertyCallbackInfo__Holder(
  _this: *const c_void,
) -> *const Object {
  ptr::null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__PropertyCallbackInfo__ShouldThrowOnError(
  _this: *const c_void,
) -> bool {
  false
}

// ---------------------------------------------------------------------------
// 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__FunctionCallbackInfo__IsConstructCall(
  _this: *const std::os::raw::c_void,
) -> bool {
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__FunctionTemplate__SetAccessorProperty(
  _this: *const std::os::raw::c_void,
  _key: *const std::os::raw::c_void,
  _getter: *const std::os::raw::c_void,
  _setter: *const std::os::raw::c_void,
  _attr: crate::PropertyAttribute,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__GetName(
  _this: *const std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  std::ptr::null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__GetScriptColumnNumber(
  _this: *const std::os::raw::c_void,
) -> crate::support::int {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__GetScriptLineNumber(
  _this: *const std::os::raw::c_void,
) -> crate::support::int {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__GetScriptOrigin(
  _this: *const std::os::raw::c_void,
  _out: *mut std::os::raw::c_void,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Function__ScriptId(
  _this: *const std::os::raw::c_void,
) -> crate::support::int {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__InternalFieldCount(
  _this: *const std::os::raw::c_void,
) -> crate::support::int {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetImmutableProto(
  _this: *const std::os::raw::c_void,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ObjectTemplate__SetNativeDataProperty(
  _this: *const std::os::raw::c_void,
  _key: *const std::os::raw::c_void,
  _getter: *const std::os::raw::c_void,
  _setter: *const std::os::raw::c_void,
  _data_or_null: *const std::os::raw::c_void,
  _attr: crate::PropertyAttribute,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__PropertyCallbackInfo__Data(
  _this: *const std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  std::ptr::null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__Get(
  _this: *const std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  std::ptr::null()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ReturnValue__Value__SetEmptyString(
  _this: *mut std::os::raw::c_void,
) {
}

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

#[unsafe(no_mangle)]
pub extern "C" fn v8__Template__SetIntrinsicDataProperty(
  _this: *const std::os::raw::c_void,
  _key: *const std::os::raw::c_void,
  _intrinsic: crate::Intrinsic,
  _attr: crate::PropertyAttribute,
) {
}