boltffi_bindgen 0.24.1

Code generation library for BoltFFI - generates Swift, Kotlin, and TypeScript bindings
Documentation
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
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
#include <jni.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdatomic.h>
#include <{{ module_name }}.h>

static inline bool boltffi_exception_pending(JNIEnv* env) {
    return (*env)->ExceptionCheck(env);
}

static inline bool boltffi_consume_pending_exception(JNIEnv* env) {
    if (!boltffi_exception_pending(env)) return false;
    (*env)->ExceptionClear(env);
    return true;
}

static inline void boltffi_throw_out_of_memory(JNIEnv* env, const char* message) {
    jclass oom_class = (*env)->FindClass(env, "java/lang/OutOfMemoryError");
    if (oom_class == NULL) return;
    (*env)->ThrowNew(env, oom_class, message);
    (*env)->DeleteLocalRef(env, oom_class);
}

static inline void boltffi_throw_illegal_argument(JNIEnv* env, const char* message) {
    jclass exception_class = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
    if (exception_class == NULL) return;
    (*env)->ThrowNew(env, exception_class, message);
    (*env)->DeleteLocalRef(env, exception_class);
}

static inline void boltffi_throw_runtime(JNIEnv* env, const char* message) {
    jclass exception_class = (*env)->FindClass(env, "java/lang/RuntimeException");
    if (exception_class == NULL) return;
    (*env)->ThrowNew(env, exception_class, message);
    (*env)->DeleteLocalRef(env, exception_class);
}

static inline void boltffi_throw_status(JNIEnv* env, FfiStatus status, const char* fallback_message) {
    if (status.code == 3) {
        boltffi_throw_illegal_argument(env, "invalid argument");
    } else if (status.code == 4) {
        boltffi_throw_runtime(env, "operation cancelled");
    } else {
        boltffi_throw_runtime(env, fallback_message);
    }
}

static inline bool boltffi_try_jlong_to_usize(jlong value, uintptr_t* out_value) {
    if (value < 0) return false;
    uint64_t unsigned_value = (uint64_t)value;
    if (unsigned_value > (uint64_t)UINTPTR_MAX) return false;
    *out_value = (uintptr_t)unsigned_value;
    return true;
}

typedef struct {
    void (*free)(uint64_t handle);
    uint64_t (*clone)(uint64_t handle);
} BoltFFICallbackVTablePrefix;

static inline const BoltFFICallbackVTablePrefix* boltffi_callback_vtable_prefix(
    const BoltFFICallbackHandle* callback
) {
    return callback == NULL ? NULL : (const BoltFFICallbackVTablePrefix*)callback->vtable;
}

static inline void boltffi_release_callback_value(BoltFFICallbackHandle callback) {
    const BoltFFICallbackVTablePrefix* vtable = boltffi_callback_vtable_prefix(&callback);
    if (callback.handle != 0 && vtable != NULL && vtable->free != NULL) {
        vtable->free(callback.handle);
    }
}

static inline BoltFFICallbackHandle* boltffi_jvm_callback_handle_ref(jlong handle) {
    if (handle == 0) return NULL;
    return (BoltFFICallbackHandle*)(uintptr_t)handle;
}

static inline jlong boltffi_jvm_callback_handle_new_owned(
    JNIEnv* env,
    BoltFFICallbackHandle callback
) {
    if (callback.handle == 0 || callback.vtable == NULL) return 0;
    BoltFFICallbackHandle* stored_callback =
        (BoltFFICallbackHandle*)malloc(sizeof(BoltFFICallbackHandle));
    if (stored_callback == NULL) {
        boltffi_release_callback_value(callback);
        boltffi_throw_out_of_memory(env, "Failed to allocate callback handle");
        return 0;
    }
    *stored_callback = callback;
    return (jlong)(uintptr_t)stored_callback;
}

static inline void boltffi_jvm_callback_handle_release(BoltFFICallbackHandle* callback) {
    if (callback == NULL) return;
    boltffi_release_callback_value(*callback);
    free(callback);
}

static inline jlong boltffi_jvm_callback_handle_clone(
    JNIEnv* env,
    const BoltFFICallbackHandle* callback
) {
    const BoltFFICallbackVTablePrefix* vtable = boltffi_callback_vtable_prefix(callback);
    if (callback == NULL || callback->handle == 0 || vtable == NULL || vtable->clone == NULL) {
        return 0;
    }
    BoltFFICallbackHandle cloned_callback = {
        .handle = vtable->clone(callback->handle),
        .vtable = callback->vtable,
    };
    if (cloned_callback.handle == 0) {
        return 0;
    }
    return boltffi_jvm_callback_handle_new_owned(env, cloned_callback);
}

static inline jbyteArray boltffi_buf_to_jbytearray(JNIEnv* env, FfiBuf_u8 buf) {
    if (buf.ptr == NULL) {
        if (buf.len != 0) {
            boltffi_throw_runtime(env, "BoltFFI buffer pointer was null with non-zero length");
        }
        return NULL;
    }
    if (buf.len > (size_t)INT32_MAX) {
        {{ prefix }}_free_buf(buf);
        boltffi_throw_out_of_memory(env, "BoltFFI buffer too large for Java byte array");
        return NULL;
    }
    jsize len = (jsize)buf.len;
    jbyteArray arr = (*env)->NewByteArray(env, len);
    if (arr == NULL) {
        {{ prefix }}_free_buf(buf);
        return NULL;
    }
    (*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte*)buf.ptr);
    {{ prefix }}_free_buf(buf);
    if (boltffi_exception_pending(env)) {
        (*env)->DeleteLocalRef(env, arr);
        return NULL;
    }
    return arr;
}

static inline jbyteArray boltffi_status_buf_to_jbytearray(JNIEnv* env, FfiStatus status, FfiBuf_u8 buf) {
    if (status.code != 0) {
        if (buf.ptr != NULL) {
            {{ prefix }}_free_buf(buf);
        }
        boltffi_throw_status(env, status, "ffi call failed");
        return NULL;
    }
    return boltffi_buf_to_jbytearray(env, buf);
}

static inline uint32_t boltffi_le_u32(const uint8_t* bytes) {
    return
        ((uint32_t)bytes[0]) |
        ((uint32_t)bytes[1] << 8) |
        ((uint32_t)bytes[2] << 16) |
        ((uint32_t)bytes[3] << 24);
}

static inline jstring boltffi_utf8_buf_to_jstring(JNIEnv* env, FfiBuf_u8 buf) {
    if (buf.ptr == NULL) {
        if (buf.len != 0) {
            boltffi_throw_runtime(env, "BoltFFI string buffer pointer was null with non-zero length");
        }
        return NULL;
    }
    if (buf.len < 4) {
        {{ prefix }}_free_buf(buf);
        boltffi_throw_runtime(env, "BoltFFI string buffer missing length prefix");
        return NULL;
    }

    const uint8_t* bytes = (const uint8_t*)buf.ptr;
    size_t payload_len = (size_t)boltffi_le_u32(bytes);
    if (payload_len > buf.len - 4) {
        {{ prefix }}_free_buf(buf);
        boltffi_throw_runtime(env, "BoltFFI string buffer length prefix exceeded payload");
        return NULL;
    }
    if (payload_len == 0) {
        {{ prefix }}_free_buf(buf);
        return (*env)->NewString(env, NULL, 0);
    }
    if (payload_len > (size_t)INT32_MAX) {
        {{ prefix }}_free_buf(buf);
        boltffi_throw_out_of_memory(env, "BoltFFI string too large for Java string");
        return NULL;
    }

    const uint8_t* utf8 = bytes + 4;
    jchar stack_chars[64];
    jchar* chars = stack_chars;
    if (payload_len > sizeof(stack_chars) / sizeof(stack_chars[0])) {
        chars = (jchar*)malloc(payload_len * sizeof(jchar));
        if (chars == NULL) {
            {{ prefix }}_free_buf(buf);
            boltffi_throw_out_of_memory(env, "Failed to allocate Java string buffer");
            return NULL;
        }
    }

    size_t in_pos = 0;
    size_t out_pos = 0;
    bool invalid_utf8 = false;
    while (in_pos < payload_len) {
        uint8_t b0 = utf8[in_pos];
        if (b0 < 0x80) {
            chars[out_pos++] = (jchar)b0;
            in_pos += 1;
            continue;
        }

        uint32_t codepoint = 0;
        if ((b0 & 0xE0) == 0xC0) {
            if (in_pos + 1 >= payload_len) {
                invalid_utf8 = true;
                break;
            }
            uint8_t b1 = utf8[in_pos + 1];
            if ((b1 & 0xC0) != 0x80) {
                invalid_utf8 = true;
                break;
            }
            codepoint = ((uint32_t)(b0 & 0x1F) << 6) | (uint32_t)(b1 & 0x3F);
            if (codepoint < 0x80) {
                invalid_utf8 = true;
                break;
            }
            chars[out_pos++] = (jchar)codepoint;
            in_pos += 2;
            continue;
        }

        if ((b0 & 0xF0) == 0xE0) {
            if (in_pos + 2 >= payload_len) {
                invalid_utf8 = true;
                break;
            }
            uint8_t b1 = utf8[in_pos + 1];
            uint8_t b2 = utf8[in_pos + 2];
            if ((b1 & 0xC0) != 0x80 || (b2 & 0xC0) != 0x80) {
                invalid_utf8 = true;
                break;
            }
            codepoint =
                ((uint32_t)(b0 & 0x0F) << 12) |
                ((uint32_t)(b1 & 0x3F) << 6) |
                (uint32_t)(b2 & 0x3F);
            if (codepoint < 0x800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF)) {
                invalid_utf8 = true;
                break;
            }
            chars[out_pos++] = (jchar)codepoint;
            in_pos += 3;
            continue;
        }

        if ((b0 & 0xF8) == 0xF0) {
            if (in_pos + 3 >= payload_len) {
                invalid_utf8 = true;
                break;
            }
            uint8_t b1 = utf8[in_pos + 1];
            uint8_t b2 = utf8[in_pos + 2];
            uint8_t b3 = utf8[in_pos + 3];
            if ((b1 & 0xC0) != 0x80 || (b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
                invalid_utf8 = true;
                break;
            }
            codepoint =
                ((uint32_t)(b0 & 0x07) << 18) |
                ((uint32_t)(b1 & 0x3F) << 12) |
                ((uint32_t)(b2 & 0x3F) << 6) |
                (uint32_t)(b3 & 0x3F);
            if (codepoint < 0x10000 || codepoint > 0x10FFFF) {
                invalid_utf8 = true;
                break;
            }
            uint32_t surrogate = codepoint - 0x10000;
            chars[out_pos++] = (jchar)(0xD800 + (surrogate >> 10));
            chars[out_pos++] = (jchar)(0xDC00 + (surrogate & 0x3FF));
            in_pos += 4;
            continue;
        }

        invalid_utf8 = true;
        break;
    }

    jstring result = NULL;
    if (!invalid_utf8) {
        if (out_pos > (size_t)INT32_MAX) {
            boltffi_throw_out_of_memory(env, "BoltFFI string too large for Java string");
        } else {
            result = (*env)->NewString(env, chars, (jsize)out_pos);
        }
    }

    if (chars != stack_chars) {
        free(chars);
    }
    {{ prefix }}_free_buf(buf);

    if (invalid_utf8) {
        char message[96];
        snprintf(
            message,
            sizeof(message),
            "BoltFFI string buffer contained invalid UTF-8 at byte offset %zu",
            in_pos
        );
        boltffi_throw_runtime(env, message);
        return NULL;
    }
    return result;
}

static inline bool boltffi_lookup_static_method(
    JNIEnv* env,
    jclass cls,
    const char* name,
    const char* signature,
    jmethodID* out_method
) {
    *out_method = (*env)->GetStaticMethodID(env, cls, name, signature);
    if (*out_method != NULL) return true;
    boltffi_consume_pending_exception(env);
    return false;
}

typedef enum {
    BOLTFFI_GLOBAL_CLASS_OK = 0,
    BOLTFFI_GLOBAL_CLASS_MISSING = 1,
    BOLTFFI_GLOBAL_CLASS_FATAL = 2
} BoltFFIGlobalClassResult;

static inline BoltFFIGlobalClassResult boltffi_lookup_global_class(
    JNIEnv* env,
    const char* class_name,
    jclass* out_class
) {
    *out_class = NULL;
    jclass local_class = (*env)->FindClass(env, class_name);
    if (local_class == NULL) {
        boltffi_consume_pending_exception(env);
        return BOLTFFI_GLOBAL_CLASS_MISSING;
    }
    jclass global_class = (*env)->NewGlobalRef(env, local_class);
    (*env)->DeleteLocalRef(env, local_class);
    if (global_class == NULL) {
        boltffi_consume_pending_exception(env);
        return BOLTFFI_GLOBAL_CLASS_FATAL;
    }
    *out_class = global_class;
    return BOLTFFI_GLOBAL_CLASS_OK;
}

typedef enum {
    BOLTFFI_STATIC_CALL_CACHE_UNINIT = 0,
    BOLTFFI_STATIC_CALL_CACHE_INITING = 1,
    BOLTFFI_STATIC_CALL_CACHE_READY = 2,
    BOLTFFI_STATIC_CALL_CACHE_FAILED = 3
} BoltFFIStaticCallCacheState;

typedef struct {
    atomic_int state;
    jclass class_ref;
    jmethodID method;
} BoltFFIStaticCallCache;

#define BOLTFFI_STATIC_CALL_CACHE_INIT { 0, NULL, NULL }

static inline bool boltffi_static_call_cache_ensure(
    JNIEnv* env,
    BoltFFIStaticCallCache* cache,
    const char* class_name,
    const char* method_name,
    const char* method_signature
) {
    int state = atomic_load_explicit(&cache->state, memory_order_acquire);
    if (state == BOLTFFI_STATIC_CALL_CACHE_READY) return true;
    if (state == BOLTFFI_STATIC_CALL_CACHE_FAILED) return false;

    int expected = BOLTFFI_STATIC_CALL_CACHE_UNINIT;
    if (atomic_compare_exchange_strong_explicit(
            &cache->state,
            &expected,
            BOLTFFI_STATIC_CALL_CACHE_INITING,
            memory_order_acq_rel,
            memory_order_acquire)) {
        jclass class_ref = NULL;
        jmethodID method = NULL;
        BoltFFIGlobalClassResult class_result =
            boltffi_lookup_global_class(env, class_name, &class_ref);
        if (class_result != BOLTFFI_GLOBAL_CLASS_OK) {
            cache->class_ref = NULL;
            cache->method = NULL;
            atomic_store_explicit(
                &cache->state,
                BOLTFFI_STATIC_CALL_CACHE_FAILED,
                memory_order_release
            );
            return false;
        }
        if (!boltffi_lookup_static_method(env, class_ref, method_name, method_signature, &method)) {
            (*env)->DeleteGlobalRef(env, class_ref);
            cache->class_ref = NULL;
            cache->method = NULL;
            atomic_store_explicit(
                &cache->state,
                BOLTFFI_STATIC_CALL_CACHE_FAILED,
                memory_order_release
            );
            return false;
        }
        cache->class_ref = class_ref;
        cache->method = method;
        atomic_store_explicit(
            &cache->state,
            BOLTFFI_STATIC_CALL_CACHE_READY,
            memory_order_release
        );
        return true;
    }

    do {
        state = atomic_load_explicit(&cache->state, memory_order_acquire);
    } while (state == BOLTFFI_STATIC_CALL_CACHE_INITING);

    return state == BOLTFFI_STATIC_CALL_CACHE_READY;
}

static inline void boltffi_static_call_cache_reset(JNIEnv* env, BoltFFIStaticCallCache* cache) {
    if (cache->class_ref != NULL) {
        (*env)->DeleteGlobalRef(env, cache->class_ref);
        cache->class_ref = NULL;
    }
    cache->method = NULL;
    atomic_store_explicit(&cache->state, BOLTFFI_STATIC_CALL_CACHE_UNINIT, memory_order_release);
}

{%- if has_async %}
static JavaVM* g_jvm = NULL;
static jclass g_callback_class = NULL;
static jmethodID g_callback_method = NULL;
typedef enum {
    BOLTFFI_CALLBACK_INIT_OK = 0,
    BOLTFFI_CALLBACK_INIT_SKIPPED = 1,
    BOLTFFI_CALLBACK_INIT_FATAL = 2
} BoltFFICallbackInitResult;
static jint boltffi_attach_current_thread(JavaVM* vm, JNIEnv** env) {
#if defined(__ANDROID__)
    return (*vm)->AttachCurrentThread(vm, env, NULL);
#else
    return (*vm)->AttachCurrentThread(vm, (void**)env, NULL);
#endif
}

{%- for cb in callback_traits %}
static BoltFFICallbackInitResult init_{{ cb.trait_name }}_callbacks(JNIEnv* env);
{%- endfor %}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    g_jvm = vm;
    JNIEnv* env;
    if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }
    if (boltffi_lookup_global_class(env, "{{ package_path }}/Native", &g_callback_class) != BOLTFFI_GLOBAL_CLASS_OK) {
        g_callback_class = NULL;
        return JNI_ERR;
    }
    if (!boltffi_lookup_static_method(env, g_callback_class, "boltffiFutureContinuationCallback", "(JB)V", &g_callback_method)) {
        (*env)->DeleteGlobalRef(env, g_callback_class);
        g_callback_class = NULL;
        g_callback_method = NULL;
        return JNI_ERR;
    }
{%- for cb in callback_traits %}
    if (init_{{ cb.trait_name }}_callbacks(env) == BOLTFFI_CALLBACK_INIT_FATAL) {
        return JNI_ERR;
    }
{%- endfor %}
    return JNI_VERSION_1_6;
}

static void boltffi_jni_continuation_callback(uint64_t handle, int8_t poll_result) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) {
            return;
        }
        attached = 1;
    } else if (get_env_result != JNI_OK) {
        return;
    }
    (*env)->CallStaticVoidMethod(env, g_callback_class, g_callback_method, (jlong)handle, (jbyte)poll_result);
    boltffi_consume_pending_exception(env);
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
}
{%- endif %}

{%- for trampoline in closure_trampolines %}
{%- if trampoline.supports_proxy_wrap %}
JNIEXPORT jlong JNICALL {{ trampoline.proxy_clone_jni_name }}(JNIEnv* env, jclass cls, jlong handle) {
    (void)cls;
    return boltffi_jvm_callback_handle_clone(env, boltffi_jvm_callback_handle_ref(handle));
}

JNIEXPORT void JNICALL {{ trampoline.proxy_release_jni_name }}(JNIEnv* env, jclass cls, jlong handle) {
    (void)env; (void)cls;
    boltffi_jvm_callback_handle_release(boltffi_jvm_callback_handle_ref(handle));
}

JNIEXPORT {{ trampoline.proxy_sync_method.jni_return_type }} JNICALL {{ trampoline.proxy_sync_method.jni_name }}(JNIEnv *env, jclass cls, jlong handle{{ trampoline.proxy_sync_method.jni_params }}) {
    if (handle == 0) {
{%- if trampoline.proxy_sync_method.return_is_unit %}
        return;
{%- elif trampoline.proxy_sync_method.return_is_direct %}
        return 0;
{%- else %}
        return NULL;
{%- endif %}
    }
    bool _boltffi_input_error = false;
{%- for param in trampoline.proxy_sync_method.params %}
{%- if param.is_string() %}
    const char* _{{ param.name }}_c = {{ param.name }} ? (*env)->GetStringUTFChars(env, {{ param.name }}, NULL) : NULL;
    if ({{ param.name }} != NULL && _{{ param.name }}_c == NULL) _boltffi_input_error = true;
{%- endif %}
{%- if param.is_primitive_array() %}
{% include "_primitive_array_input.txt" %}
{%- endif %}
{%- if param.is_buffer() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    uintptr_t _{{ param.name }}_len = (_{{ param.name }}_ptr && _{{ param.name }}_size > 0) ? (uintptr_t)_{{ param.name }}_size : 0;
{%- endif %}
{%- if param.is_composite() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    {{ param.composite_c_type() }} _{{ param.name }}_val;
    if (_{{ param.name }}_ptr && _{{ param.name }}_size >= (jlong)sizeof({{ param.composite_c_type() }})) {
        memcpy(&_{{ param.name }}_val, _{{ param.name }}_ptr, sizeof({{ param.composite_c_type() }}));
    } else {
        memset(&_{{ param.name }}_val, 0, sizeof({{ param.composite_c_type() }}));
        _boltffi_input_error = true;
    }
{%- endif %}

{%- endfor %}
    BoltFFICallbackHandle* callback = boltffi_jvm_callback_handle_ref(handle);
{%- if trampoline.proxy_sync_method.return_is_direct %}
    {{ trampoline.proxy_sync_method.jni_c_return_type }} _result;
    memset(&_result, 0, sizeof(_result));
{%- elif trampoline.proxy_sync_method.return_composite_c_type.is_some() %}
    {{ trampoline.proxy_sync_method.return_composite_c_type.as_ref().unwrap() }} _composite_result = {0};
{%- elif !trampoline.proxy_sync_method.return_is_unit %}
    uint8_t* _out_ptr = NULL;
    uintptr_t _out_len = 0;
{%- endif %}
    if (_boltffi_input_error) goto boltffi_input_cleanup;
    if (callback == NULL || callback->handle == 0 || callback->vtable == NULL) {
        boltffi_throw_runtime(env, "invalid callback handle");
        goto boltffi_input_cleanup;
    }
    const {{ trampoline.vtable_type }}* vtable = (const {{ trampoline.vtable_type }}*)callback->vtable;
    if (vtable == NULL || vtable->{{ trampoline.proxy_sync_method.vtable_field }} == NULL) {
        boltffi_throw_runtime(env, "callback method unavailable");
        goto boltffi_input_cleanup;
    }
    FfiStatus _status = {0};
{%- if trampoline.proxy_sync_method.return_is_unit %}
    vtable->{{ trampoline.proxy_sync_method.vtable_field }}(callback->handle{% if trampoline.proxy_sync_method.params.len() > 0 %}, {% endif %}{% for param in trampoline.proxy_sync_method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_status);
{%- elif trampoline.proxy_sync_method.return_is_direct %}
    vtable->{{ trampoline.proxy_sync_method.vtable_field }}(callback->handle{% if trampoline.proxy_sync_method.params.len() > 0 %}, {% endif %}{% for param in trampoline.proxy_sync_method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_result, &_status);
{%- elif trampoline.proxy_sync_method.return_composite_c_type.is_some() %}
    vtable->{{ trampoline.proxy_sync_method.vtable_field }}(callback->handle{% if trampoline.proxy_sync_method.params.len() > 0 %}, {% endif %}{% for param in trampoline.proxy_sync_method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_composite_result, &_status);
{%- else %}
    vtable->{{ trampoline.proxy_sync_method.vtable_field }}(callback->handle{% if trampoline.proxy_sync_method.params.len() > 0 %}, {% endif %}{% for param in trampoline.proxy_sync_method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_out_ptr, &_out_len, &_status);
{%- endif %}
    if (_status.code != 0) {
        boltffi_throw_runtime(env, "callback invocation failed");
        goto boltffi_input_cleanup;
    }
boltffi_input_cleanup:
{%- for param in trampoline.proxy_sync_method.params %}
{%- if param.is_primitive_array() %}
{%- if param.array_has_stack_copy_fast_path() %}
    if (_{{ param.name }}_needs_release) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- else %}
    if (_{{ param.name }}_ptr != NULL) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- endif %}
{%- endif %}
{%- if param.is_string() %}
    if (_{{ param.name }}_c) (*env)->ReleaseStringUTFChars(env, {{ param.name }}, _{{ param.name }}_c);
{%- endif %}

{%- endfor %}
{%- if trampoline.proxy_sync_method.return_is_unit %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return;
{%- elif trampoline.proxy_sync_method.return_is_direct %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return 0;
    return {{ trampoline.proxy_sync_method.jni_return_expr }};
{%- elif trampoline.proxy_sync_method.return_composite_c_type.is_some() %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return NULL;
    jsize _comp_size = (jsize)sizeof(_composite_result);
    jbyteArray _arr = (*env)->NewByteArray(env, _comp_size);
    if (_arr != NULL) (*env)->SetByteArrayRegion(env, _arr, 0, _comp_size, (const jbyte*)&_composite_result);
    return _arr;
{%- else %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return NULL;
    FfiBuf_u8 _buf = {.ptr = _out_ptr, .len = (size_t)_out_len, .cap = (size_t)_out_len, .align = 1};
    return boltffi_buf_to_jbytearray(env, _buf);
{%- endif %}
}
{%- endif %}

static BoltFFIStaticCallCache g_{{ trampoline.signature_id }}_cache = BOLTFFI_STATIC_CALL_CACHE_INIT;

static {{ trampoline.c_return_type() }} {{ trampoline.trampoline_name }}(void* user_data{{ trampoline.c_params }}) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) {
{%- if trampoline.is_void() %}
            return;
{%- else %}
            {{ trampoline.c_return_type() }} zero = {0}; return zero;
{%- endif %}
        }
        attached = 1;
    } else if (get_env_result != JNI_OK) {
{%- if trampoline.is_void() %}
        return;
{%- else %}
        {{ trampoline.c_return_type() }} zero = {0}; return zero;
{%- endif %}
    }
    jlong handle = (jlong)(uintptr_t)user_data;
{%- for line in trampoline.setup_lines %}
    {{ line }}
{%- endfor %}
    if (!boltffi_static_call_cache_ensure(env, &g_{{ trampoline.signature_id }}_cache, "{{ trampoline.callbacks_class_jni_path }}", "call", "(J{{ trampoline.jni_params_signature }}){{ trampoline.jni_return_signature() }}")) {
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
{%- if trampoline.is_void() %}
        return;
{%- else %}
        {{ trampoline.c_return_type() }} zero = {0}; return zero;
{%- endif %}
    }
{%- if trampoline.is_void() %}
    (*env)->CallStaticVoidMethod(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    if (boltffi_consume_pending_exception(env)) {
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return;
    }
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
{%- else %}
{%- if trampoline.is_wire_encoded_return() %}
    jbyteArray _jarr = (jbyteArray)(*env)->{{ trampoline.jni_call_method() }}(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    FfiBuf_u8 _result = {0};
    if (boltffi_consume_pending_exception(env)) {
        if (_jarr != NULL) (*env)->DeleteLocalRef(env, _jarr);
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return _result;
    }
    if (_jarr != NULL) {
        jsize _len = (*env)->GetArrayLength(env, _jarr);
        uint8_t* _ptr = (uint8_t*)malloc((size_t)_len);
        if (_ptr != NULL) {
            (*env)->GetByteArrayRegion(env, _jarr, 0, _len, (jbyte*)_ptr);
            _result.ptr = _ptr;
            _result.len = (size_t)_len;
            _result.cap = (size_t)_len;
            _result.align = 1;
        }
        (*env)->DeleteLocalRef(env, _jarr);
    }
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
    return _result;
{%- elif trampoline.is_blittable_struct_return() %}
    jbyteArray _jarr = (jbyteArray)(*env)->{{ trampoline.jni_call_method() }}(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    {{ trampoline.c_return_type() }} _result = {0};
    if (boltffi_consume_pending_exception(env)) {
        if (_jarr != NULL) (*env)->DeleteLocalRef(env, _jarr);
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return _result;
    }
    if (_jarr != NULL) {
        jsize _len = (*env)->GetArrayLength(env, _jarr);
        if ((size_t)_len == sizeof({{ trampoline.c_return_type() }})) {
            (*env)->GetByteArrayRegion(env, _jarr, 0, _len, (jbyte*)&_result);
        }
        (*env)->DeleteLocalRef(env, _jarr);
    }
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
    return _result;
{%- elif trampoline.is_raw_pointer_return() %}
    jbyteArray _jarr = (jbyteArray)(*env)->{{ trampoline.jni_call_method() }}(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    uint8_t* _result = NULL;
    if (boltffi_consume_pending_exception(env)) {
        if (_jarr != NULL) (*env)->DeleteLocalRef(env, _jarr);
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return _result;
    }
    if (_jarr != NULL) {
        jsize _len = (*env)->GetArrayLength(env, _jarr);
        _result = (uint8_t*)malloc((size_t)_len + 1u);
        if (_result != NULL) {
            (*env)->GetByteArrayRegion(env, _jarr, 0, _len, (jbyte*)_result);
            _result[(size_t)_len] = 0;
        }
        (*env)->DeleteLocalRef(env, _jarr);
    }
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
    return _result;
{%- elif trampoline.is_callback_handle_return() %}
    jlong _handle_val = (*env)->CallStaticLongMethod(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    if (boltffi_consume_pending_exception(env)) {
        BoltFFICallbackHandle _zero = {0};
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return _zero;
    }
    BoltFFICallbackHandle _result = {{ trampoline.callback_create_fn() }}((uint64_t)_handle_val);
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
    return _result;
{%- else %}
    {{ trampoline.c_return_type() }} _result = {{ trampoline.jni_return_cast() }}(*env)->{{ trampoline.jni_call_method() }}(env, g_{{ trampoline.signature_id }}_cache.class_ref, g_{{ trampoline.signature_id }}_cache.method, handle{% if !trampoline.jni_call_args.is_empty() %}, {{ trampoline.jni_call_args }}{% endif %});
    if (boltffi_consume_pending_exception(env)) {
        {{ trampoline.c_return_type() }} _zero = {0};
{%- for line in trampoline.cleanup_lines %}
        {{ line }}
{%- endfor %}
        if (attached) {
            (*g_jvm)->DetachCurrentThread(g_jvm);
        }
        return _zero;
    }
{%- for line in trampoline.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) {
        (*g_jvm)->DetachCurrentThread(g_jvm);
    }
    return _result;
{%- endif %}
{%- endif %}
}
{%- endfor %}

{%- for wire_fn in wire_functions %}
{{ wire_fn }}
{%- endfor %}

JNIEXPORT jbyteArray JNICALL Java_{{ jni_prefix }}_Native_{{ prefix }}_1last_1error_1message(JNIEnv *env, jclass cls) {
    FfiString out = { 0 };
    FfiStatus status = {{ prefix }}_last_error_message(&out);
    if (status.code != 0 || out.ptr == NULL || out.len == 0) {
        {{ prefix }}_free_string(out);
        return (*env)->NewByteArray(env, 0);
    }
    jbyteArray result = (*env)->NewByteArray(env, (jsize)out.len);
    if (result != NULL) {
        (*env)->SetByteArrayRegion(env, result, 0, (jsize)out.len, (const jbyte*)out.ptr);
    }
    {{ prefix }}_free_string(out);
    return result;
}


{%- for func in functions %}

JNIEXPORT {{ func.return_info.jni_return }} JNICALL {{ func.jni_name }}(JNIEnv *env, jclass cls{{ func.jni_params }}) {
{%- if func.return_info.is_void() %}
    {{ func.ffi_name }}({% for param in func.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %});
{%- else %}
    {{ func.return_info.jni_return }} _result = {{ func.ffi_name }}({% for param in func.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %});
{%- if func.return_info.jni_return == "jboolean" %}
    return (jboolean)_result;
{%- else %}
    return _result;
{%- endif %}
{%- endif %}
}
{%- endfor %}

{%- for class in classes %}
{%- for ctor in class.ctors %}

{{ ctor }}
{%- endfor %}

JNIEXPORT void JNICALL Java_{{ class.jni_prefix }}_Native_{{ class.jni_ffi_prefix }}_1free(JNIEnv *env, jclass cls, jlong handle) {
    if (handle != 0) {{ class.ffi_prefix }}_free((void*)handle);
}

{%- for wire_method in class.wire_methods %}
{{ wire_method }}
{%- endfor %}

{%- for func in class.async_methods %}

JNIEXPORT jlong JNICALL {{ func.jni_create_name }}(JNIEnv *env, jclass cls, jlong handle{{ func.jni_params }}) {
    if (handle == 0) return 0;
    bool _boltffi_input_error = false;
{%- for param in func.params %}
{%- if param.is_string() %}
    const char* _{{ param.name }}_c = {{ param.name }} ? (*env)->GetStringUTFChars(env, {{ param.name }}, NULL) : NULL;
    if ({{ param.name }} != NULL && _{{ param.name }}_c == NULL) _boltffi_input_error = true;
{%- endif %}
{%- if param.is_primitive_array() %}
{% include "_primitive_array_input.txt" %}
{%- endif %}
{%- if param.is_buffer() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    uintptr_t _{{ param.name }}_len = (_{{ param.name }}_ptr && _{{ param.name }}_size > 0) ? (uintptr_t)_{{ param.name }}_size : 0;
{%- endif %}
{%- if param.is_composite() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    {{ param.composite_c_type() }} _{{ param.name }}_val;
    if (_{{ param.name }}_ptr && _{{ param.name }}_size >= (jlong)sizeof({{ param.composite_c_type() }})) {
        memcpy(&_{{ param.name }}_val, _{{ param.name }}_ptr, sizeof({{ param.composite_c_type() }}));
    } else {
        memset(&_{{ param.name }}_val, 0, sizeof({{ param.composite_c_type() }}));
        _boltffi_input_error = true;
    }
{%- endif %}
{%- endfor %}
    RustFutureHandle _handle = 0;
    if (_boltffi_input_error) goto boltffi_input_cleanup;
    _handle = {{ func.ffi_name }}((void*)handle{% for param in func.params %}, {{ param.ffi_arg() }}{% endfor %});
boltffi_input_cleanup:
{%- for param in func.params %}
{%- if param.is_primitive_array() %}
{%- if param.array_has_stack_copy_fast_path() %}
    if (_{{ param.name }}_needs_release) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- else %}
    if (_{{ param.name }}_ptr != NULL) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- endif %}
{%- endif %}
{%- if param.is_string() %}
    if (_{{ param.name }}_c != NULL) (*env)->ReleaseStringUTFChars(env, {{ param.name }}, _{{ param.name }}_c);
{%- endif %}
{%- endfor %}
    if (_boltffi_input_error) return 0;
    return (jlong)_handle;
}

JNIEXPORT void JNICALL {{ func.jni_poll_name }}(JNIEnv *env, jclass cls, jlong handle, jlong future, jlong contHandle) {
    {{ func.ffi_poll }}((RustFutureHandle)future, (uint64_t)contHandle, boltffi_jni_continuation_callback);
}

JNIEXPORT {{ func.complete_kind.jni_return() }} JNICALL {{ func.jni_complete_name }}(JNIEnv *env, jclass cls, jlong handle, jlong future) {
{%- if func.complete_kind.is_void() %}
    FfiStatus _status;
    {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return;
    }
{%- elif func.complete_kind.is_blittable_struct() %}
    FfiStatus _status;
    {{ func.complete_kind.c_type() }} _result = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return NULL;
    }
    jbyteArray _arr = (*env)->NewByteArray(env, (jsize)sizeof(_result));
    if (_arr != NULL) {
        (*env)->SetByteArrayRegion(env, _arr, 0, (jsize)sizeof(_result), (const jbyte*)&_result);
    }
    return _arr;
{%- elif func.complete_kind.is_wire_encoded() %}
    FfiStatus _status;
    FfiBuf_u8 _buf = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    return boltffi_status_buf_to_jbytearray(env, _status, _buf);
{%- else %}
    FfiStatus _status;
    {{ func.complete_kind.c_type() }} _result = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return 0;
    }
    return {{ func.complete_kind.return_expr() }};
{%- endif %}
}

JNIEXPORT void JNICALL {{ func.jni_cancel_name }}(JNIEnv *env, jclass cls, jlong handle, jlong future) {
    {{ func.ffi_cancel }}((RustFutureHandle)future);
}

JNIEXPORT void JNICALL {{ func.jni_free_name }}(JNIEnv *env, jclass cls, jlong handle, jlong future) {
    {{ func.ffi_free }}((RustFutureHandle)future);
}
{%- endfor %}
{%- for stream in class.streams %}

JNIEXPORT jlong JNICALL {{ stream.subscribe_jni }}(JNIEnv *env, jclass cls, jlong handle) {
    if (handle == 0) return 0;
    SubscriptionHandle _subscription = {{ stream.subscribe_ffi }}((void*)handle);
    return (jlong)_subscription;
}

JNIEXPORT void JNICALL {{ stream.poll_jni }}(JNIEnv *env, jclass cls, jlong subscription_handle, jlong contHandle) {
    if (subscription_handle == 0) return;
    {{ stream.poll_ffi }}((SubscriptionHandle)subscription_handle, (uint64_t)contHandle, boltffi_jni_continuation_callback);
}

JNIEXPORT jbyteArray JNICALL {{ stream.pop_batch_jni }}(JNIEnv *env, jclass cls, jlong subscription_handle, jlong max_count) {
    if (subscription_handle == 0) return NULL;
    uintptr_t _max_count = 0;
    if (!boltffi_try_jlong_to_usize(max_count, &_max_count)) {
        boltffi_throw_illegal_argument(env, "max_count must be a non-negative size");
        return NULL;
    }
{%- if stream.pop_batch_is_direct() %}
    if (_max_count == 0) {
        return (*env)->NewByteArray(env, 0);
    }
    if (_max_count > (uintptr_t)(SIZE_MAX / {{ stream.pop_batch_direct_item_size() }}u)) {
        boltffi_throw_illegal_argument(env, "max_count is too large");
        return NULL;
    }
    size_t _byte_capacity = (size_t)_max_count * {{ stream.pop_batch_direct_item_size() }}u;
    {{ stream.pop_batch_direct_item_c_type() }}* _items = ({{ stream.pop_batch_direct_item_c_type() }}*)malloc(_byte_capacity);
    if (_items == NULL) {
        boltffi_throw_out_of_memory(env, "Failed to allocate stream batch buffer");
        return NULL;
    }
    uintptr_t _count = {{ stream.pop_batch_ffi }}((SubscriptionHandle)subscription_handle, _items, _max_count);
    size_t _byte_len = (size_t)_count * {{ stream.pop_batch_direct_item_size() }}u;
    jbyteArray _result = (*env)->NewByteArray(env, (jsize)_byte_len);
    if (_result != NULL && _byte_len > 0) {
        (*env)->SetByteArrayRegion(env, _result, 0, (jsize)_byte_len, (const jbyte*)_items);
    }
    free(_items);
    return _result;
{%- else %}
    FfiBuf_u8 _buf = {{ stream.pop_batch_ffi }}((SubscriptionHandle)subscription_handle, _max_count);
    if (_buf.len == 0) {
        if (_buf.ptr != NULL) {{ prefix }}_free_buf(_buf);
        return (*env)->NewByteArray(env, 0);
    }
    return boltffi_buf_to_jbytearray(env, _buf);
{%- endif %}
}

JNIEXPORT jint JNICALL {{ stream.wait_jni }}(JNIEnv *env, jclass cls, jlong subscription_handle, jint timeout) {
    if (subscription_handle == 0) return -1;
    int32_t _result = {{ stream.wait_ffi }}((SubscriptionHandle)subscription_handle, (uint32_t)timeout);
    return (jint)_result;
}

JNIEXPORT void JNICALL {{ stream.unsubscribe_jni }}(JNIEnv *env, jclass cls, jlong subscription_handle) {
    if (subscription_handle == 0) return;
    {{ stream.unsubscribe_ffi }}((SubscriptionHandle)subscription_handle);
}

JNIEXPORT void JNICALL {{ stream.free_jni }}(JNIEnv *env, jclass cls, jlong subscription_handle) {
    if (subscription_handle == 0) return;
    {{ stream.free_ffi }}((SubscriptionHandle)subscription_handle);
}
{%- endfor %}
{%- endfor %}

{%- for func in async_functions %}

JNIEXPORT jlong JNICALL {{ func.jni_create_name }}(JNIEnv *env, jclass cls{{ func.jni_params }}) {
    bool _boltffi_input_error = false;
{%- for param in func.params %}
{%- if param.is_string() %}
    const char* _{{ param.name }}_c = {{ param.name }} ? (*env)->GetStringUTFChars(env, {{ param.name }}, NULL) : NULL;
    if ({{ param.name }} != NULL && _{{ param.name }}_c == NULL) _boltffi_input_error = true;
{%- endif %}
{%- if param.is_primitive_array() %}
{% include "_primitive_array_input.txt" %}
{%- endif %}
{%- if param.is_buffer() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    uintptr_t _{{ param.name }}_len = (_{{ param.name }}_ptr && _{{ param.name }}_size > 0) ? (uintptr_t)_{{ param.name }}_size : 0;
{%- endif %}
{%- if param.is_composite() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    {{ param.composite_c_type() }} _{{ param.name }}_val;
    if (_{{ param.name }}_ptr && _{{ param.name }}_size >= (jlong)sizeof({{ param.composite_c_type() }})) {
        memcpy(&_{{ param.name }}_val, _{{ param.name }}_ptr, sizeof({{ param.composite_c_type() }}));
    } else {
        memset(&_{{ param.name }}_val, 0, sizeof({{ param.composite_c_type() }}));
        _boltffi_input_error = true;
    }
{%- endif %}
{%- endfor %}
    RustFutureHandle _handle = 0;
    if (_boltffi_input_error) goto boltffi_input_cleanup;
    _handle = {{ func.ffi_name }}({% for param in func.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %});
boltffi_input_cleanup:
{%- for param in func.params %}
{%- if param.is_primitive_array() %}
{%- if param.array_has_stack_copy_fast_path() %}
    if (_{{ param.name }}_needs_release) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- else %}
    if (_{{ param.name }}_ptr != NULL) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- endif %}
{%- endif %}
{%- if param.is_string() %}
    if (_{{ param.name }}_c != NULL) (*env)->ReleaseStringUTFChars(env, {{ param.name }}, _{{ param.name }}_c);
{%- endif %}
{%- endfor %}
    if (_boltffi_input_error) return 0;
    return (jlong)_handle;
}

JNIEXPORT void JNICALL {{ func.jni_poll_name }}(JNIEnv *env, jclass cls, jlong future, jlong contHandle) {
    {{ func.ffi_poll }}((RustFutureHandle)future, (uint64_t)contHandle, boltffi_jni_continuation_callback);
}

JNIEXPORT {{ func.complete_kind.jni_return() }} JNICALL {{ func.jni_complete_name }}(JNIEnv *env, jclass cls, jlong future) {
{%- if func.complete_kind.is_void() %}
    FfiStatus _status;
    {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return;
    }
{%- elif func.complete_kind.is_blittable_struct() %}
    FfiStatus _status;
    {{ func.complete_kind.c_type() }} _result = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return NULL;
    }
    jbyteArray _arr = (*env)->NewByteArray(env, (jsize)sizeof(_result));
    if (_arr != NULL) {
        (*env)->SetByteArrayRegion(env, _arr, 0, (jsize)sizeof(_result), (const jbyte*)&_result);
    }
    return _arr;
{%- elif func.complete_kind.is_wire_encoded() %}
    FfiStatus _status;
    FfiBuf_u8 _buf = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    return boltffi_status_buf_to_jbytearray(env, _status, _buf);
{%- else %}
    FfiStatus _status;
    {{ func.complete_kind.c_type() }} _result = {{ func.ffi_complete }}((RustFutureHandle)future, &_status);
    if (_status.code != 0) {
        boltffi_throw_status(env, _status, "async call failed");
        return 0;
    }
    return {{ func.complete_kind.return_expr() }};
{%- endif %}
}

JNIEXPORT void JNICALL {{ func.jni_cancel_name }}(JNIEnv *env, jclass cls, jlong future) {
    {{ func.ffi_cancel }}((RustFutureHandle)future);
}

JNIEXPORT void JNICALL {{ func.jni_free_name }}(JNIEnv *env, jclass cls, jlong future) {
    {{ func.ffi_free }}((RustFutureHandle)future);
}
{%- endfor %}

{%- for cb in callback_traits %}

static jclass g_{{ cb.trait_name }}_callbacks_class = NULL;
static jmethodID g_{{ cb.trait_name }}_free_method = NULL;
static jmethodID g_{{ cb.trait_name }}_clone_method = NULL;
{%- for method in cb.sync_methods %}
static jmethodID g_{{ cb.trait_name }}_{{ method.ffi_name }}_method = NULL;
{%- endfor %}
{%- for method in cb.async_methods %}
static jmethodID g_{{ cb.trait_name }}_{{ method.ffi_name }}_method = NULL;
{%- endfor %}
{%- for method in cb.proxy_async_methods %}
static jmethodID {{ method.failure_method_id }} = NULL;
static jmethodID {{ method.success_method_id }} = NULL;
{%- endfor %}
{%- for method in cb.proxy_sync_methods %}

JNIEXPORT {{ method.jni_return_type }} JNICALL {{ method.jni_name }}(JNIEnv *env, jclass cls, jlong handle{{ method.jni_params }}) {
    if (handle == 0) {
{%- if method.return_is_unit %}
        return;
{%- elif method.return_is_direct %}
        return 0;
{%- else %}
        return NULL;
{%- endif %}
    }
    bool _boltffi_input_error = false;
{%- for param in method.params %}
{%- if param.is_string() %}
    const char* _{{ param.name }}_c = {{ param.name }} ? (*env)->GetStringUTFChars(env, {{ param.name }}, NULL) : NULL;
    if ({{ param.name }} != NULL && _{{ param.name }}_c == NULL) _boltffi_input_error = true;
{%- endif %}
{%- if param.is_primitive_array() %}
{% include "_primitive_array_input.txt" %}
{%- endif %}
{%- if param.is_buffer() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    uintptr_t _{{ param.name }}_len = (_{{ param.name }}_ptr && _{{ param.name }}_size > 0) ? (uintptr_t)_{{ param.name }}_size : 0;
{%- endif %}
{%- if param.is_composite() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    {{ param.composite_c_type() }} _{{ param.name }}_val;
    if (_{{ param.name }}_ptr && _{{ param.name }}_size >= (jlong)sizeof({{ param.composite_c_type() }})) {
        memcpy(&_{{ param.name }}_val, _{{ param.name }}_ptr, sizeof({{ param.composite_c_type() }}));
    } else {
        memset(&_{{ param.name }}_val, 0, sizeof({{ param.composite_c_type() }}));
        _boltffi_input_error = true;
    }
{%- endif %}

{%- endfor %}
    BoltFFICallbackHandle* callback = boltffi_jvm_callback_handle_ref(handle);
{%- if method.return_is_direct %}
    {{ method.jni_c_return_type }} _result;
    memset(&_result, 0, sizeof(_result));
{%- elif method.return_composite_c_type.is_some() %}
    {{ method.return_composite_c_type.as_ref().unwrap() }} _composite_result = {0};
{%- elif !method.return_is_unit %}
    uint8_t* _out_ptr = NULL;
    uintptr_t _out_len = 0;
{%- endif %}
    if (_boltffi_input_error) goto boltffi_input_cleanup;
    if (callback == NULL || callback->handle == 0 || callback->vtable == NULL) {
        boltffi_throw_runtime(env, "invalid callback handle");
        goto boltffi_input_cleanup;
    }
    const {{ cb.vtable_type }}* vtable = (const {{ cb.vtable_type }}*)callback->vtable;
    if (vtable == NULL || vtable->{{ method.vtable_field }} == NULL) {
        boltffi_throw_runtime(env, "callback method unavailable");
        goto boltffi_input_cleanup;
    }
    FfiStatus _status = {0};
{%- if method.return_is_unit %}
    vtable->{{ method.vtable_field }}(callback->handle{% if method.params.len() > 0 %}, {% endif %}{% for param in method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_status);
{%- elif method.return_is_direct %}
    vtable->{{ method.vtable_field }}(callback->handle{% if method.params.len() > 0 %}, {% endif %}{% for param in method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_result, &_status);
{%- elif method.return_composite_c_type.is_some() %}
    vtable->{{ method.vtable_field }}(callback->handle{% if method.params.len() > 0 %}, {% endif %}{% for param in method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_composite_result, &_status);
{%- else %}
    vtable->{{ method.vtable_field }}(callback->handle{% if method.params.len() > 0 %}, {% endif %}{% for param in method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}, &_out_ptr, &_out_len, &_status);
{%- endif %}
    if (_status.code != 0) {
        boltffi_throw_runtime(env, "callback invocation failed");
        goto boltffi_input_cleanup;
    }
boltffi_input_cleanup:
{%- for param in method.params %}
{%- if param.is_primitive_array() %}
{%- if param.array_has_stack_copy_fast_path() %}
    if (_{{ param.name }}_needs_release) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- else %}
    if (_{{ param.name }}_ptr != NULL) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- endif %}
{%- endif %}
{%- if param.is_string() %}
    if (_{{ param.name }}_c) (*env)->ReleaseStringUTFChars(env, {{ param.name }}, _{{ param.name }}_c);
{%- endif %}

{%- endfor %}
{%- if method.return_is_unit %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return;
{%- elif method.return_is_direct %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return 0;
    return {{ method.jni_return_expr }};
{%- elif method.return_composite_c_type.is_some() %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return NULL;
    jsize _comp_size = (jsize)sizeof(_composite_result);
    jbyteArray _arr = (*env)->NewByteArray(env, _comp_size);
    if (_arr != NULL) (*env)->SetByteArrayRegion(env, _arr, 0, _comp_size, (const jbyte*)&_composite_result);
    return _arr;
{%- else %}
    if (boltffi_exception_pending(env) || _boltffi_input_error) return NULL;
    FfiBuf_u8 _buf = {.ptr = _out_ptr, .len = (size_t)_out_len, .cap = (size_t)_out_len, .align = 1};
    return boltffi_buf_to_jbytearray(env, _buf);
{%- endif %}
}
{%- endfor %}
{%- for method in cb.proxy_async_methods %}

static void {{ cb.trait_name }}_{{ method.vtable_field }}_proxy_callback(uint64_t callback_data{% if method.is_wire() %}, const uint8_t* result_ptr, size_t result_len{% elif method.has_return() %}, {{ method.return_c_type() }} result{% endif %}, FfiStatus status) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) {
            return;
        }
        attached = 1;
    } else if (get_env_result != JNI_OK) {
        return;
    }
    if (status.code != 0) {
        (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.failure_method_id }}, (jlong)callback_data);
        boltffi_consume_pending_exception(env);
        if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
        return;
    }
{%- if method.is_wire() %}
    jbyteArray _result = (*env)->NewByteArray(env, (jsize)result_len);
    if (_result == NULL) {
        boltffi_consume_pending_exception(env);
        (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.failure_method_id }}, (jlong)callback_data);
        boltffi_consume_pending_exception(env);
        if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
        return;
    }
    if (result_len > 0 && result_ptr != NULL) {
        (*env)->SetByteArrayRegion(env, _result, 0, (jsize)result_len, (const jbyte*)result_ptr);
        if ((*env)->ExceptionCheck(env)) {
            (*env)->ExceptionClear(env);
            (*env)->DeleteLocalRef(env, _result);
            (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.failure_method_id }}, (jlong)callback_data);
            boltffi_consume_pending_exception(env);
            if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
            return;
        }
    }
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.success_method_id }}, (jlong)callback_data, _result);
    (*env)->DeleteLocalRef(env, _result);
{%- elif method.has_return() %}
{%- if method.return_c_type() == "BoltFFICallbackHandle" %}
    jlong _result_handle = boltffi_jvm_callback_handle_new_owned(env, result);
    if (boltffi_exception_pending(env)) {
        boltffi_consume_pending_exception(env);
        (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.failure_method_id }}, (jlong)callback_data);
        boltffi_consume_pending_exception(env);
        if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
        return;
    }
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.success_method_id }}, (jlong)callback_data, _result_handle);
{%- else %}
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.success_method_id }}, (jlong)callback_data, result);
{%- endif %}
{%- else %}
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, {{ method.success_method_id }}, (jlong)callback_data);
{%- endif %}
    boltffi_consume_pending_exception(env);
    if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
}

JNIEXPORT void JNICALL {{ method.jni_name }}(JNIEnv *env, jclass cls, jlong handle{{ method.jni_params }}) {
    if (handle == 0) {
        boltffi_throw_runtime(env, "invalid callback handle");
        return;
    }
    bool _boltffi_input_error = false;
{%- for param in method.params %}
{%- if param.is_string() %}
    const char* _{{ param.name }}_c = {{ param.name }} ? (*env)->GetStringUTFChars(env, {{ param.name }}, NULL) : NULL;
    if ({{ param.name }} != NULL && _{{ param.name }}_c == NULL) _boltffi_input_error = true;
{%- endif %}
{%- if param.is_primitive_array() %}
{% include "_primitive_array_input.txt" %}
{%- endif %}
{%- if param.is_buffer() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    uintptr_t _{{ param.name }}_len = (_{{ param.name }}_ptr && _{{ param.name }}_size > 0) ? (uintptr_t)_{{ param.name }}_size : 0;
{%- endif %}
{%- if param.is_composite() %}
    jlong _{{ param.name }}_size = (*env)->GetDirectBufferCapacity(env, {{ param.name }});
    uint8_t* _{{ param.name }}_ptr = (uint8_t*)(*env)->GetDirectBufferAddress(env, {{ param.name }});
    {{ param.composite_c_type() }} _{{ param.name }}_val;
    if (_{{ param.name }}_ptr && _{{ param.name }}_size >= (jlong)sizeof({{ param.composite_c_type() }})) {
        memcpy(&_{{ param.name }}_val, _{{ param.name }}_ptr, sizeof({{ param.composite_c_type() }}));
    } else {
        memset(&_{{ param.name }}_val, 0, sizeof({{ param.composite_c_type() }}));
        _boltffi_input_error = true;
    }
{%- endif %}

{%- endfor %}
    BoltFFICallbackHandle* callback = boltffi_jvm_callback_handle_ref(handle);
    if (_boltffi_input_error) goto boltffi_input_cleanup;
    if (callback == NULL || callback->handle == 0 || callback->vtable == NULL) {
        boltffi_throw_runtime(env, "invalid callback handle");
        goto boltffi_input_cleanup;
    }
    const {{ cb.vtable_type }}* vtable = (const {{ cb.vtable_type }}*)callback->vtable;
    if (vtable == NULL || vtable->{{ method.vtable_field }} == NULL) {
        boltffi_throw_runtime(env, "callback method unavailable");
        goto boltffi_input_cleanup;
    }
    vtable->{{ method.vtable_field }}(
        callback->handle{% if method.params.len() > 0 %}, {% endif %}{% for param in method.params %}{{ param.ffi_arg() }}{% if !loop.last %}, {% endif %}{% endfor %}{% if method.params.len() > 0 %}, {% endif %}{{ cb.trait_name }}_{{ method.vtable_field }}_proxy_callback,
        (uint64_t)callbackData
    );
boltffi_input_cleanup:
{%- for param in method.params %}
{%- if param.is_primitive_array() %}
{%- if param.array_has_stack_copy_fast_path() %}
    if (_{{ param.name }}_needs_release) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- else %}
    if (_{{ param.name }}_ptr != NULL) (*env)->{{ param.array_release_elements_fn() }}(env, {{ param.name }}, ({{ param.array_elements_ptr_type() }})_{{ param.name }}_ptr, {{ param.array_release_mode() }});
{%- endif %}
{%- endif %}
{%- if param.is_string() %}
    if (_{{ param.name }}_c) (*env)->ReleaseStringUTFChars(env, {{ param.name }}, _{{ param.name }}_c);
{%- endif %}

{%- endfor %}
}
{%- endfor %}

static void {{ cb.trait_name }}_vtable_free(uint64_t handle) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) return;
        attached = 1;
    } else if (get_env_result != JNI_OK) return;
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_free_method, (jlong)handle);
    boltffi_consume_pending_exception(env);
    if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
}

static uint64_t {{ cb.trait_name }}_vtable_clone(uint64_t handle) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) return 0;
        attached = 1;
    } else if (get_env_result != JNI_OK) return 0;
    jlong result = (*env)->CallStaticLongMethod(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_clone_method, (jlong)handle);
    if (boltffi_consume_pending_exception(env)) {
        if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
        return 0;
    }
    if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
    return (uint64_t)result;
}

JNIEXPORT jlong JNICALL {{ cb.proxy_clone_jni_name }}(JNIEnv* env, jclass cls, jlong handle) {
    (void)cls;
    return boltffi_jvm_callback_handle_clone(env, boltffi_jvm_callback_handle_ref(handle));
}

JNIEXPORT void JNICALL {{ cb.proxy_release_jni_name }}(JNIEnv* env, jclass cls, jlong handle) {
    (void)env; (void)cls;
    boltffi_jvm_callback_handle_release(boltffi_jvm_callback_handle_ref(handle));
}

{%- for method in cb.sync_methods %}

static void {{ cb.trait_name }}_vtable_{{ method.ffi_name }}(uint64_t handle{% for param in method.c_params %}, {{ param.c_type }} {{ param.name }}{% endfor %}, FfiStatus* {{ method.status_param_name() }}) {
    JNIEnv* env;
    int attached = 0;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) {
            {{ method.status_param_name() }}->code = 1;
            return;
        }
        attached = 1;
    } else if (get_env_result != JNI_OK) {
        {{ method.status_param_name() }}->code = 1;
        return;
    }
{%- for line in method.setup_lines %}
    {{ line }}
{%- endfor %}
{%- if method.is_wire_encoded_return() %}
    *{{ method.out_ptr_name() }} = NULL;
    *{{ method.out_len_name() }} = 0;
    jbyteArray _jarr = (jbyteArray)(*env)->CallStaticObjectMethod(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_{{ method.ffi_name }}_method, (jlong)handle{% for arg in method.jni_args %}, {{ arg }}{% endfor %});
    if (boltffi_consume_pending_exception(env)) {
        {{ method.status_param_name() }}->code = 1;
        goto cleanup;
    }
    if (_jarr != NULL) {
        jsize _len = (*env)->GetArrayLength(env, _jarr);
        if (_len > 0) {
            uint8_t* _ptr = (uint8_t*)malloc((size_t)_len);
            (*env)->GetByteArrayRegion(env, _jarr, 0, _len, (jbyte*)_ptr);
            if (_ptr == NULL) {
                boltffi_throw_out_of_memory(env, "Failed to allocate callback return buffer");
                {{ method.status_param_name() }}->code = 1;
                (*env)->DeleteLocalRef(env, _jarr);
                goto cleanup;
            }
            *{{ method.out_ptr_name() }} = _ptr;
            *{{ method.out_len_name() }} = (uintptr_t)_len;
        }
        (*env)->DeleteLocalRef(env, _jarr);
    }
{%- elif method.has_return() %}
    {{ method.jni_return_type() }} _result = (*env)->CallStatic{{ method.jni_call_type() }}Method(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_{{ method.ffi_name }}_method, (jlong)handle{% for arg in method.jni_args %}, {{ arg }}{% endfor %});
    if (boltffi_consume_pending_exception(env)) {
        {{ method.status_param_name() }}->code = 1;
        goto cleanup;
    }
    *{{ method.out_ptr_name() }} = ({{ method.c_return_type() }})_result;
{%- else %}
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_{{ method.ffi_name }}_method, (jlong)handle{% for arg in method.jni_args %}, {{ arg }}{% endfor %});
    if (boltffi_consume_pending_exception(env)) {
        {{ method.status_param_name() }}->code = 1;
        goto cleanup;
    }
{%- endif %}
    {{ method.status_param_name() }}->code = 0;
cleanup:
{%- for line in method.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
}
{%- endfor %}
{%- for method in cb.async_methods %}

static void {{ cb.trait_name }}_vtable_{{ method.ffi_name }}(uint64_t handle{% for param in method.c_params %}, {{ param.c_type }} {{ param.name }}{% endfor %}, void (*callback)(uint64_t{% if method.is_wire() %}, const uint8_t*, size_t{% elif method.has_return() %}, {{ method.return_c_type() }}{% endif %}, FfiStatus), uint64_t callback_data) {
    JNIEnv* env;
    int attached = 0;
    bool _boltffi_dispatch_succeeded = false;
    jint get_env_result = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (boltffi_attach_current_thread(g_jvm, &env) != JNI_OK) {
{%- if method.is_wire() %}
            callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
{%- elif method.has_return() %}
            callback((uint64_t)callback_data, ({{ method.return_c_type() }}){0}, (FfiStatus){.code = 1});
{%- else %}
            callback((uint64_t)callback_data, (FfiStatus){.code = 1});
{%- endif %}
            return;
        }
        attached = 1;
    } else if (get_env_result != JNI_OK) {
{%- if method.is_wire() %}
        callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
{%- elif method.has_return() %}
        callback((uint64_t)callback_data, ({{ method.return_c_type() }}){0}, (FfiStatus){.code = 1});
{%- else %}
        callback((uint64_t)callback_data, (FfiStatus){.code = 1});
{%- endif %}
        return;
    }
{%- for line in method.setup_lines %}
    {{ line }}
{%- endfor %}
    (*env)->CallStaticVoidMethod(env, g_{{ cb.trait_name }}_callbacks_class, g_{{ cb.trait_name }}_{{ method.ffi_name }}_method, (jlong)handle{% for arg in method.jni_args %}, {{ arg }}{% endfor %}, (jlong)callback, (jlong)callback_data);
    if (!boltffi_consume_pending_exception(env)) {
        _boltffi_dispatch_succeeded = true;
    }
cleanup:
{%- for line in method.cleanup_lines %}
    {{ line }}
{%- endfor %}
    if (attached) (*g_jvm)->DetachCurrentThread(g_jvm);
    if (_boltffi_dispatch_succeeded) return;
{%- if method.is_wire() %}
    callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
{%- elif method.has_return() %}
    callback((uint64_t)callback_data, ({{ method.return_c_type() }}){0}, (FfiStatus){.code = 1});
{%- else %}
    callback((uint64_t)callback_data, (FfiStatus){.code = 1});
{%- endif %}
}
{%- endfor %}

static {{ cb.vtable_type }} g_{{ cb.trait_name }}_vtable = {
    .free = {{ cb.trait_name }}_vtable_free,
    .clone = {{ cb.trait_name }}_vtable_clone,
{%- for method in cb.sync_methods %}
    .{{ method.ffi_name }} = {{ cb.trait_name }}_vtable_{{ method.ffi_name }},
{%- endfor %}
{%- for method in cb.async_methods %}
    .{{ method.ffi_name }} = {{ cb.trait_name }}_vtable_{{ method.ffi_name }},
{%- endfor %}
};

static BoltFFICallbackInitResult init_{{ cb.trait_name }}_callbacks(JNIEnv* env) {
    BoltFFIGlobalClassResult class_result =
        boltffi_lookup_global_class(env, "{{ cb.callbacks_class }}", &g_{{ cb.trait_name }}_callbacks_class);
    if (class_result == BOLTFFI_GLOBAL_CLASS_MISSING) {
        return BOLTFFI_CALLBACK_INIT_SKIPPED;
    }
    if (class_result != BOLTFFI_GLOBAL_CLASS_OK) {
        return BOLTFFI_CALLBACK_INIT_FATAL;
    }
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "free", "(J)V", &g_{{ cb.trait_name }}_free_method)) goto fail;
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "clone", "(J)J", &g_{{ cb.trait_name }}_clone_method)) goto fail;
{%- for method in cb.sync_methods %}
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "{{ method.jni_method_name }}", "{{ method.jni_signature }}", &g_{{ cb.trait_name }}_{{ method.ffi_name }}_method)) goto fail;
{%- endfor %}
{%- for method in cb.async_methods %}
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "{{ method.jni_method_name }}", "{{ method.jni_signature }}", &g_{{ cb.trait_name }}_{{ method.ffi_name }}_method)) goto fail;
{%- endfor %}
{%- for method in cb.proxy_async_methods %}
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "{{ method.success_method_name }}", "{{ method.success_signature }}", &{{ method.success_method_id }})) goto fail;
    if (!boltffi_lookup_static_method(env, g_{{ cb.trait_name }}_callbacks_class, "{{ method.failure_method_name }}", "(J)V", &{{ method.failure_method_id }})) goto fail;
{%- endfor %}
    {{ cb.register_fn }}(&g_{{ cb.trait_name }}_vtable);
    return BOLTFFI_CALLBACK_INIT_OK;
fail:
    (*env)->DeleteGlobalRef(env, g_{{ cb.trait_name }}_callbacks_class);
    g_{{ cb.trait_name }}_callbacks_class = NULL;
    return BOLTFFI_CALLBACK_INIT_FATAL;
}
{%- endfor %}

{%- if has_async %}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        return;
    }
    if (g_callback_class != NULL) {
        (*env)->DeleteGlobalRef(env, g_callback_class);
        g_callback_class = NULL;
    }
    g_callback_method = NULL;
{%- for trampoline in closure_trampolines %}
    boltffi_static_call_cache_reset(env, &g_{{ trampoline.signature_id }}_cache);
{%- endfor %}
{%- for cb in callback_traits %}
    if (g_{{ cb.trait_name }}_callbacks_class != NULL) {
        (*env)->DeleteGlobalRef(env, g_{{ cb.trait_name }}_callbacks_class);
        g_{{ cb.trait_name }}_callbacks_class = NULL;
    }
    g_{{ cb.trait_name }}_free_method = NULL;
    g_{{ cb.trait_name }}_clone_method = NULL;
{%- for method in cb.sync_methods %}
    g_{{ cb.trait_name }}_{{ method.ffi_name }}_method = NULL;
{%- endfor %}
{%- for method in cb.async_methods %}
    g_{{ cb.trait_name }}_{{ method.ffi_name }}_method = NULL;
{%- endfor %}
{%- for method in cb.proxy_async_methods %}
    {{ method.success_method_id }} = NULL;
    {{ method.failure_method_id }} = NULL;
{%- endfor %}
{%- endfor %}
}
{%- endif %}

{%- for invoker in async_callback_invokers %}

JNIEXPORT void JNICALL {{ invoker.jni_fn_name }}(JNIEnv* env, jclass cls, jlong callback_ptr, jlong callback_data{% if invoker.has_result() %}, {{ invoker.jni_result_type() }} result{% endif %}) {
{%- if invoker.is_wire() %}
    void (*callback)(uint64_t, const uint8_t*, size_t, FfiStatus) = (void (*)(uint64_t, const uint8_t*, size_t, FfiStatus))callback_ptr;
    if (result == NULL) {
        callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
        return;
    }
    jsize _len = (*env)->GetArrayLength(env, result);
    uint8_t* _copy = NULL;
    if (_len > 0) {
        _copy = (uint8_t*)malloc((size_t)_len);
        if (_copy == NULL) {
            callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
            return;
        }
        (*env)->GetByteArrayRegion(env, result, 0, _len, (jbyte*)_copy);
        if ((*env)->ExceptionCheck(env)) {
            free(_copy);
            (*env)->ExceptionClear(env);
            callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
            return;
        }
    }
    callback((uint64_t)callback_data, (const uint8_t*)_copy, (size_t)_len, (FfiStatus){.code = 0});
    if (_copy != NULL) {
        free(_copy);
    }
{%- elif invoker.has_result() %}
    (void)env; (void)cls;
    void (*callback)(uint64_t, {{ invoker.c_result_type() }}, FfiStatus) = (void (*)(uint64_t, {{ invoker.c_result_type() }}, FfiStatus))callback_ptr;
{%- if invoker.is_callback_handle() %}
    {{ invoker.c_result_type() }} converted_result = {{ invoker.result_create_fn() }}((uint64_t)result);
    callback((uint64_t)callback_data, converted_result, (FfiStatus){.code = 0});
{%- else %}
    callback((uint64_t)callback_data, ({{ invoker.c_result_type() }})result, (FfiStatus){.code = 0});
{%- endif %}
{%- else %}
    (void)env; (void)cls;
    void (*callback)(uint64_t, FfiStatus) = (void (*)(uint64_t, FfiStatus))callback_ptr;
    callback((uint64_t)callback_data, (FfiStatus){.code = 0});
{%- endif %}
}

JNIEXPORT void JNICALL {{ invoker.jni_failure_fn_name }}(JNIEnv* env, jclass cls, jlong callback_ptr, jlong callback_data) {
{%- if invoker.is_wire() %}
    (void)env; (void)cls;
    void (*callback)(uint64_t, const uint8_t*, size_t, FfiStatus) = (void (*)(uint64_t, const uint8_t*, size_t, FfiStatus))callback_ptr;
    callback((uint64_t)callback_data, NULL, 0, (FfiStatus){.code = 1});
{%- elif invoker.has_result() %}
    (void)env; (void)cls;
    void (*callback)(uint64_t, {{ invoker.c_result_type() }}, FfiStatus) = (void (*)(uint64_t, {{ invoker.c_result_type() }}, FfiStatus))callback_ptr;
{%- if invoker.is_callback_handle() %}
    {{ invoker.c_result_type() }} zero_result = {0};
    callback((uint64_t)callback_data, zero_result, (FfiStatus){.code = 1});
{%- else %}
    callback((uint64_t)callback_data, ({{ invoker.c_result_type() }}){0}, (FfiStatus){.code = 1});
{%- endif %}
{%- else %}
    (void)env; (void)cls;
    void (*callback)(uint64_t, FfiStatus) = (void (*)(uint64_t, FfiStatus))callback_ptr;
    callback((uint64_t)callback_data, (FfiStatus){.code = 1});
{%- endif %}
}
{%- endfor %}