use templates for human type conversions
[ldk-java] / java_strings.py
1 from bindingstypes import *
2
3 class Consts:
4     def __init__(self, DEBUG):
5
6         self.c_type_map = dict(
7             uint8_t = ['byte'],
8             uint16_t = ['short'],
9             uint32_t = ['int'],
10             long = ['long'],
11         )
12
13         self.to_hu_conv_templates = dict(
14             ptr = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});',
15             default = '{human_type} {var_name}_hu_conv = new {human_type}(null, {var_name});'
16         )
17
18         self.common_base = """package org.ldk.structs;
19 import java.util.LinkedList;
20 class CommonBase {
21         long ptr;
22         LinkedList<Object> ptrs_to = new LinkedList();
23         protected CommonBase(long ptr) { this.ptr = ptr; }
24         public long _test_only_get_ptr() { return this.ptr; }
25 }
26 """
27
28         self.c_file_pfx = """#include \"org_ldk_impl_bindings.h\"
29 #include <rust_types.h>
30 #include <lightning.h>
31 #include <string.h>
32 #include <stdatomic.h>
33 #include <stdlib.h>
34 """
35
36         if not DEBUG:
37             self.c_file_pfx = self.c_file_pfx + """#define MALLOC(a, _) malloc(a)
38 #define FREE(p) if ((long)(p) > 1024) { free(p); }
39 #define DO_ASSERT(a) (void)(a)
40 #define CHECK(a)
41 """
42         else:
43             self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
44 // Always run a, then assert it is true:
45 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
46 // Assert a is true or do nothing
47 #define CHECK(a) DO_ASSERT(a)
48
49 // Running a leak check across all the allocations and frees of the JDK is a mess,
50 // so instead we implement our own naive leak checker here, relying on the -wrap
51 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
52 // and free'd in Rust or C across the generated bindings shared library.
53 #include <threads.h>
54 #include <execinfo.h>
55 #include <unistd.h>
56 static mtx_t allocation_mtx;
57
58 void __attribute__((constructor)) init_mtx() {
59         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
60 }
61
62 #define BT_MAX 128
63 typedef struct allocation {
64         struct allocation* next;
65         void* ptr;
66         const char* struct_name;
67         void* bt[BT_MAX];
68         int bt_len;
69 } allocation;
70 static allocation* allocation_ll = NULL;
71
72 void* __real_malloc(size_t len);
73 void* __real_calloc(size_t nmemb, size_t len);
74 static void new_allocation(void* res, const char* struct_name) {
75         allocation* new_alloc = __real_malloc(sizeof(allocation));
76         new_alloc->ptr = res;
77         new_alloc->struct_name = struct_name;
78         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
79         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
80         new_alloc->next = allocation_ll;
81         allocation_ll = new_alloc;
82         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
83 }
84 static void* MALLOC(size_t len, const char* struct_name) {
85         void* res = __real_malloc(len);
86         new_allocation(res, struct_name);
87         return res;
88 }
89 void __real_free(void* ptr);
90 static void alloc_freed(void* ptr) {
91         allocation* p = NULL;
92         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
93         allocation* it = allocation_ll;
94         while (it->ptr != ptr) {
95                 p = it; it = it->next;
96                 if (it == NULL) {
97                         fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
98                         void* bt[BT_MAX];
99                         int bt_len = backtrace(bt, BT_MAX);
100                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
101                         fprintf(stderr, "\\n\\n");
102                         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
103                         return; // addrsan should catch malloc-unknown and print more info than we have
104                 }
105         }
106         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
107         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
108         DO_ASSERT(it->ptr == ptr);
109         __real_free(it);
110 }
111 static void FREE(void* ptr) {
112         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
113         alloc_freed(ptr);
114         __real_free(ptr);
115 }
116
117 void* __wrap_malloc(size_t len) {
118         void* res = __real_malloc(len);
119         new_allocation(res, "malloc call");
120         return res;
121 }
122 void* __wrap_calloc(size_t nmemb, size_t len) {
123         void* res = __real_calloc(nmemb, len);
124         new_allocation(res, "calloc call");
125         return res;
126 }
127 void __wrap_free(void* ptr) {
128         if (ptr == NULL) return;
129         alloc_freed(ptr);
130         __real_free(ptr);
131 }
132
133 void* __real_realloc(void* ptr, size_t newlen);
134 void* __wrap_realloc(void* ptr, size_t len) {
135         if (ptr != NULL) alloc_freed(ptr);
136         void* res = __real_realloc(ptr, len);
137         new_allocation(res, "realloc call");
138         return res;
139 }
140 void __wrap_reallocarray(void* ptr, size_t new_sz) {
141         // Rust doesn't seem to use reallocarray currently
142         DO_ASSERT(false);
143 }
144
145 void __attribute__((destructor)) check_leaks() {
146         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
147                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
148                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
149                 fprintf(stderr, "\\n\\n");
150         }
151         DO_ASSERT(allocation_ll == NULL);
152 }
153 """
154         self.c_file_pfx = self.c_file_pfx + """
155 static jmethodID ordinal_meth = NULL;
156 static jmethodID slicedef_meth = NULL;
157 static jclass slicedef_cls = NULL;
158 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
159         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
160         CHECK(ordinal_meth != NULL);
161         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
162         CHECK(slicedef_meth != NULL);
163         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
164         CHECK(slicedef_cls != NULL);
165 }
166
167 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
168         return *((bool*)ptr);
169 }
170 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
171         return *((long*)ptr);
172 }
173 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
174         FREE((void*)ptr);
175 }
176 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * env, jclass _b, jlong ptr, jlong len) {
177         jbyteArray ret_arr = (*env)->NewByteArray(env, len);
178         (*env)->SetByteArrayRegion(env, ret_arr, 0, len, (unsigned char*)ptr);
179         return ret_arr;
180 }
181 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * env, jclass _b, jlong slice_ptr) {
182         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
183         jbyteArray ret_arr = (*env)->NewByteArray(env, slice->datalen);
184         (*env)->SetByteArrayRegion(env, ret_arr, 0, slice->datalen, slice->data);
185         return ret_arr;
186 }
187 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * env, jclass _b, jbyteArray bytes) {
188         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
189         vec->datalen = (*env)->GetArrayLength(env, bytes);
190         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
191         (*env)->GetByteArrayRegion (env, bytes, 0, vec->datalen, vec->data);
192         return (long)vec;
193 }
194 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_txpointer_1get_1buffer (JNIEnv * env, jclass _b, jlong ptr) {
195         LDKTransaction *txdata = (LDKTransaction*)ptr;
196         LDKu8slice slice;
197         slice.data = txdata->data;
198         slice.datalen = txdata->datalen;
199         return Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes(env, _b, (long)&slice);
200 }
201 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
202         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
203         txdata->datalen = (*env)->GetArrayLength(env, bytes);
204         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
205         txdata->data_is_owned = false;
206         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
207         return (long)txdata;
208 }
209 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
210         LDKTransaction *tx = (LDKTransaction*)ptr;
211         tx->data_is_owned = true;
212         Transaction_free(*tx);
213         FREE((void*)ptr);
214 }
215 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
216         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
217         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
218         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
219         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
220         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
221         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
222         return (long)vec->datalen;
223 }
224 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * env, jclass _b) {
225         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
226         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
227         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
228         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
229         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
230         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
231         vec->data = NULL;
232         vec->datalen = 0;
233         return (long)vec;
234 }
235
236 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
237 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
238 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
239 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
240
241 _Static_assert(sizeof(jlong) == sizeof(int64_t), "We assume that j-types are the same as C types");
242 _Static_assert(sizeof(jbyte) == sizeof(char), "We assume that j-types are the same as C types");
243 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
244
245 typedef jlongArray int64_tArray;
246 typedef jbyteArray int8_tArray;
247
248 """
249
250         self.hu_struct_file_prefix = """package org.ldk.structs;
251
252 import org.ldk.impl.bindings;
253 import org.ldk.enums.*;
254 import org.ldk.util.*;
255 import java.util.Arrays;
256
257 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
258 """
259         self.c_fn_ty_pfx = "JNIEXPORT "
260         self.c_fn_name_pfx = "JNICALL Java_org_ldk_impl_bindings_"
261         self.c_fn_args_pfx = "JNIEnv *env, jclass clz"
262         self.file_ext = ".java"
263         self.ptr_c_ty = "int64_t"
264         self.ptr_native_ty = "long"
265         self.result_c_ty = "jclass"
266         self.ptr_arr = "jobjectArray"
267         self.get_native_arr_len_call = ("(*env)->GetArrayLength(env, ", ")")
268         self.get_native_arr_ptr_call = ("(*env)->GetPrimitiveArrayCritical(env, ", ", NULL)")
269
270     def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
271         return "(*env)->ReleasePrimitiveArrayCritical(env, " + arr_var + ", " + arr_ptr_var + ", 0)"
272     def create_native_arr_call(self, arr_len, ty_info):
273         if ty_info.c_ty == "int8_tArray":
274             return "(*env)->NewByteArray(env, " + arr_len + ")"
275         else:
276             return "(*env)->New" + ty_info.java_ty.strip("[]").title() + "Array(env, " + arr_len + ")"
277     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
278         if ty_info.c_ty == "int8_tArray":
279             return ("(*env)->SetByteArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", ", ")")
280         else:
281             assert False
282     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
283         if ty_info.c_ty == "int8_tArray":
284             if copy:
285                 return "(*env)->GetByteArrayRegion(env, " + arr_name + ", 0, " + arr_len + ", " + dest_name + ")"
286             else:
287                 return "(*env)->GetByteArrayElements (env, " + arr_name + ", NULL)"
288         elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
289             return "(*env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (env, " + arr_name + ", NULL)"
290         else:
291             return None
292     def get_native_arr_elem(self, arr_name, idxc, ty_info):
293         if self.get_native_arr_contents(arr_name, "", "", ty_info, False) is None:
294             return "(*env)->GetObjectArrayElement(env, " + arr_name + ", " + idxc + ")"
295         else:
296             assert False # Only called if above is None
297     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
298         if ty_info.c_ty == "int8_tArray":
299             return "(*env)->ReleaseByteArrayElements(env, " + arr_name + ", (int8_t*)" + dest_name + ", 0);"
300         else:
301             return "(*env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements(env, " + arr_name + ", " + dest_name + ", 0)"
302
303     def init_str(self, c_array_class_caches):
304         res = ""
305         for ty in c_array_class_caches:
306             res = res + "static jclass " + ty + "_clz = NULL;\n"
307         res = res + "JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass clz) {\n"
308         for ty in c_array_class_caches:
309             res = res + "\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n"
310             res = res + "\tCHECK(" + ty + "_clz != NULL);\n"
311             res = res + "\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n"
312         res = res + "}\n"
313         return res
314
315     def native_c_unitary_enum_map(self, struct_name, variants):
316         out_java_enum = "package org.ldk.enums;\n\n"
317         out_java = ""
318         out_c = ""
319         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_from_java(" + self.c_fn_args_pfx + ") {\n"
320         out_c = out_c + "\tswitch ((*env)->CallIntMethod(env, clz, ordinal_meth)) {\n"
321
322         out_java_enum = out_java_enum + "public enum " + struct_name + " {\n"
323         ord_v = 0
324         for var in variants:
325             out_java_enum = out_java_enum + "\t" + var + ",\n"
326             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
327             ord_v = ord_v + 1
328         out_java_enum = out_java_enum + "\t; static native void init();\n"
329         out_java_enum = out_java_enum + "\tstatic { init(); }\n"
330         out_java_enum = out_java_enum + "}"
331         out_java = out_java + "\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n"
332         out_c = out_c + "\t}\n"
333         out_c = out_c + "\tabort();\n"
334         out_c = out_c + "}\n"
335
336         out_c = out_c + "static jclass " + struct_name + "_class = NULL;\n"
337         for var in variants:
338             out_c = out_c + "static jfieldID " + struct_name + "_" + var + " = NULL;\n"
339         out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
340         out_c = out_c + "\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n"
341         out_c = out_c + "\tCHECK(" + struct_name + "_class != NULL);\n"
342         for var in variants:
343             out_c = out_c + "\t" + struct_name + "_" + var + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + var + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n"
344             out_c = out_c + "\tCHECK(" + struct_name + "_" + var + " != NULL);\n"
345         out_c = out_c + "}\n"
346         out_c = out_c + "static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n"
347         out_c = out_c + "\tswitch (val) {\n"
348         ord_v = 0
349         for var in variants:
350             out_c = out_c + "\t\tcase " + var + ":\n"
351             out_c = out_c + "\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + var + ");\n"
352             ord_v = ord_v + 1
353         out_c = out_c + "\t\tdefault: abort();\n"
354         out_c = out_c + "\t}\n"
355         out_c = out_c + "}\n\n"
356
357         return (out_c, out_java_enum, out_java)
358
359     def c_unitary_enum_to_native_call(self, ty_info):
360         return (ty_info.rust_obj + "_to_java(env, ", ")")
361     def native_unitary_enum_to_c_call(self, ty_info):
362         return (ty_info.rust_obj + "_from_java(env, ", ")")
363
364     def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
365         out_c = ""
366         for var in variants:
367             out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
368             out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
369         out_c = out_c + self.c_fn_ty_pfx + "void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (" + self.c_fn_args_pfx + ") {\n"
370         for var_name in variants:
371             out_c = out_c + "\t" + struct_name + "_" + var_name + "_class =\n"
372             out_c = out_c + "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n"
373             out_c = out_c + "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
374             out_c = out_c + "\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n"
375             out_c = out_c + "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
376         out_c = out_c + "}\n"
377         return out_c
378
379     def c_complex_enum_pass_ty(self, struct_name):
380         return "jobject"
381
382     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
383         ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
384         for param in c_params:
385             ret = ret + ", " + param
386         return ret + ")"
387
388     def native_c_map_trait(self, struct_name, field_vars, field_fns):
389         out_java_trait = ""
390         out_java = ""
391
392         # First generate most of the Java code, note that we need information about java method argument strings for C
393         out_java_trait = out_java_trait + self.hu_struct_file_prefix
394         out_java_trait = out_java_trait + "public class " + struct_name.replace("LDK","") + " extends CommonBase {\n"
395         out_java_trait = out_java_trait + "\tfinal bindings." + struct_name + " bindings_instance;\n"
396         out_java_trait = out_java_trait + "\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n"
397         out_java_trait = out_java_trait + "\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg"
398         for var in field_vars:
399             if isinstance(var, ConvInfo):
400                 out_java_trait = out_java_trait + ", " + var.java_hu_ty + " " + var.arg_name
401             else:
402                 out_java_trait = out_java_trait + ", bindings." + var[0] + " " + var[1]
403         out_java_trait = out_java_trait + ") {\n"
404         out_java_trait = out_java_trait + "\t\tsuper(bindings." + struct_name + "_new(arg"
405         for var in field_vars:
406             if isinstance(var, ConvInfo):
407                 if var.from_hu_conv is not None:
408                     out_java_trait = out_java_trait + ", " + var.from_hu_conv[0]
409                 else:
410                     out_java_trait = out_java_trait + ", " + var.arg_name
411             else:
412                 out_java_trait = out_java_trait + ", " + var[1]
413         out_java_trait = out_java_trait + "));\n"
414         out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(arg);\n"
415         for var in field_vars:
416             if isinstance(var, ConvInfo):
417                 if var.from_hu_conv is not None and var.from_hu_conv[1] != "":
418                     out_java_trait = out_java_trait + "\t\t" + var.from_hu_conv[1] + ";\n"
419             else:
420                 out_java_trait = out_java_trait + "\t\tthis.ptrs_to.add(" + var[1] + ");\n"
421         out_java_trait = out_java_trait + "\t\tthis.bindings_instance = arg;\n"
422         out_java_trait = out_java_trait + "\t}\n"
423         out_java_trait = out_java_trait + "\t@Override @SuppressWarnings(\"deprecation\")\n"
424         out_java_trait = out_java_trait + "\tprotected void finalize() throws Throwable {\n"
425         out_java_trait = out_java_trait + "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n"
426         out_java_trait = out_java_trait + "\t}\n\n"
427
428         java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
429         java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
430         for var in field_vars:
431             if isinstance(var, ConvInfo):
432                 java_trait_constr = java_trait_constr + ", " + var.java_hu_ty + " " + var.arg_name
433             else:
434                 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
435                 # Java-implemented version, so we require users pass a Java implementation here :/
436                 java_trait_constr = java_trait_constr + ", " + var[0].replace("LDK", "") + "." + var[0].replace("LDK", "") + "Interface " + var[1] + "_impl"
437         java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
438         java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
439         out_java_trait = out_java_trait + "\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n"
440         out_java = out_java + "\tpublic interface " + struct_name + " {\n"
441         java_meths = []
442         for fn_line in field_fns:
443             java_meth_descr = "("
444             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
445                 out_java = out_java + "\t\t " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
446                 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
447                 out_java_trait = out_java_trait + "\t\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
448
449                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
450                     if idx >= 1:
451                         out_java = out_java + ", "
452                         java_trait_constr = java_trait_constr + ", "
453                         out_java_trait = out_java_trait + ", "
454                     out_java = out_java + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
455                     out_java_trait = out_java_trait + arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name
456                     java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
457                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
458                 java_meth_descr = java_meth_descr + ")" + fn_line.ret_ty_info.java_fn_ty_arg
459                 java_meths.append((fn_line.fn_name, java_meth_descr))
460
461                 out_java = out_java + ");\n"
462                 out_java_trait = out_java_trait + ");\n"
463                 java_trait_constr = java_trait_constr + ") {\n"
464
465                 for arg_info in fn_line.args_ty:
466                     if arg_info.to_hu_conv is not None:
467                         java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
468
469                 if fn_line.ret_ty_info.java_ty != "void":
470                     java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
471                 else:
472                     java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.fn_name + "("
473
474                 for idx, arg_info in enumerate(fn_line.args_ty):
475                     if idx != 0:
476                         java_trait_constr = java_trait_constr + ", "
477                     if arg_info.to_hu_conv_name is not None:
478                         java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
479                     else:
480                         java_trait_constr = java_trait_constr + arg_info.arg_name
481
482                 java_trait_constr = java_trait_constr + ");\n"
483                 if fn_line.ret_ty_info.java_ty != "void":
484                     if fn_line.ret_ty_info.from_hu_conv is not None:
485                         java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
486                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
487                             java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
488                         #if fn_line.ret_ty_info.rust_obj in result_types:
489                         # XXX: We need to handle this in conversion logic so that its cross-language!
490                             # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
491                         #    java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
492                         java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
493                     else:
494                         java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
495                 java_trait_constr = java_trait_constr + "\t\t\t}\n"
496         java_trait_constr = java_trait_constr + "\t\t}"
497         for var in field_vars:
498             if isinstance(var, ConvInfo):
499                 java_trait_constr = java_trait_constr + ", " + var.arg_name
500             else:
501                 java_trait_constr = java_trait_constr + ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
502         out_java_trait = out_java_trait + "\t}\n"
503         out_java_trait = out_java_trait + java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n"
504
505         out_java = out_java + "\t}\n"
506
507         out_java = out_java + "\tpublic static native long " + struct_name + "_new(" + struct_name + " impl"
508         for var in field_vars:
509             if isinstance(var, ConvInfo):
510                 out_java = out_java + ", " + var.java_ty + " " + var.arg_name
511             else:
512                 out_java = out_java + ", " + var[0] + " " + var[1]
513         out_java = out_java + ");\n"
514         out_java = out_java + "\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n"
515
516         # Now that we've written out our java code (and created java_meths), generate C
517         out_c = "typedef struct " + struct_name + "_JCalls {\n"
518         out_c = out_c + "\tatomic_size_t refcnt;\n"
519         out_c = out_c + "\tJavaVM *vm;\n"
520         out_c = out_c + "\tjweak o;\n"
521         for var in field_vars:
522             if isinstance(var, ConvInfo):
523                 # We're a regular ol' field
524                 pass
525             else:
526                 # We're a supertrait
527                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
528         for fn in field_fns:
529             if fn.fn_name != "free" and fn.fn_name != "clone":
530                 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
531         out_c = out_c + "} " + struct_name + "_JCalls;\n"
532
533         for fn_line in field_fns:
534             if fn_line.fn_name == "free":
535                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
536                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
537                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
538                 out_c = out_c + "\t\tJNIEnv *env;\n"
539                 out_c = out_c + "\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
540                 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
541                 out_c = out_c + "\t\tFREE(j_calls);\n"
542                 out_c = out_c + "\t}\n}\n"
543
544         for idx, fn_line in enumerate(field_fns):
545             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
546                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
547                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
548                 if fn_line.self_is_const:
549                     out_c = out_c + "const void* this_arg"
550                 else:
551                     out_c = out_c + "void* this_arg"
552
553                 for idx, arg in enumerate(fn_line.args_ty):
554                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
555
556                 out_c = out_c + ") {\n"
557                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
558                 out_c = out_c + "\tJNIEnv *env;\n"
559                 out_c = out_c + "\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
560
561                 for arg_info in fn_line.args_ty:
562                     if arg_info.ret_conv is not None:
563                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
564                         out_c = out_c + arg_info.arg_name
565                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
566
567                 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
568                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
569                     out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
570                 elif not fn_line.ret_ty_info.passed_as_ptr:
571                     out_c = out_c + "\treturn (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
572                 else:
573                     out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret = (" + fn_line.ret_ty_info.rust_obj + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
574
575                 for idx, arg_info in enumerate(fn_line.args_ty):
576                     if arg_info.ret_conv is not None:
577                         out_c = out_c + ", " + arg_info.ret_conv_name
578                     else:
579                         out_c = out_c + ", " + arg_info.arg_name
580                 out_c = out_c + ");\n"
581                 if fn_line.ret_ty_info.arg_conv is not None:
582                     out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
583
584                 out_c = out_c + "}\n"
585
586         # Write out a clone function whether we need one or not, as we use them in moving to rust
587         out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
588         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
589         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
590         for var in field_vars:
591             if not isinstance(var, ConvInfo):
592                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
593         out_c = out_c + "\treturn (void*) this_arg;\n"
594         out_c = out_c + "}\n"
595
596         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
597         for var in field_vars:
598             if isinstance(var, ConvInfo):
599                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
600             else:
601                 out_c = out_c + ", jobject " + var[1]
602         out_c = out_c + ") {\n"
603
604         out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
605         out_c = out_c + "\tCHECK(c != NULL);\n"
606         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
607         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
608         out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
609         out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
610
611         for (fn_name, java_meth_descr) in java_meths:
612             if fn_name != "free" and fn_name != "clone":
613                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
614                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
615
616         for var in field_vars:
617             if isinstance(var, ConvInfo) and var.arg_conv is not None:
618                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
619         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
620         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
621         for fn_line in field_fns:
622             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
623                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
624             elif fn_line.fn_name == "free":
625                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
626             else:
627                 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
628         for var in field_vars:
629             if isinstance(var, ConvInfo):
630                 if var.arg_conv_name is not None:
631                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
632                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
633                 else:
634                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
635                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
636             else:
637                 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1] + "),\n"
638         out_c = out_c + "\t};\n"
639         for var in field_vars:
640             if not isinstance(var, ConvInfo):
641                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
642         out_c = out_c + "\treturn ret;\n"
643         out_c = out_c + "}\n"
644
645         out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new (" + self.c_fn_args_pfx + ", jobject o"
646         for var in field_vars:
647             if isinstance(var, ConvInfo):
648                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
649             else:
650                 out_c = out_c + ", jobject " + var[1]
651         out_c = out_c + ") {\n"
652         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
653         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
654         for var in field_vars:
655             if isinstance(var, ConvInfo):
656                 out_c = out_c + ", " + var.arg_name
657             else:
658                 out_c = out_c + ", " + var[1]
659         out_c = out_c + ");\n"
660         out_c = out_c + "\treturn (long)res_ptr;\n"
661         out_c = out_c + "}\n"
662
663         out_c = out_c + self.c_fn_ty_pfx + "jobject " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " val) {\n"
664         out_c = out_c + "\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n"
665         out_c = out_c + "\tCHECK(ret != NULL);\n"
666         out_c = out_c + "\treturn ret;\n"
667         out_c = out_c + "}\n"
668
669         return (out_java, out_java_trait, out_c)
670
671     def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
672         java_hu_type = struct_name.replace("LDK", "")
673         out_java_enum = ""
674         out_java = ""
675         out_c = ""
676
677         out_java_enum += (self.hu_struct_file_prefix)
678         out_java_enum += ("public class " + java_hu_type + " extends CommonBase {\n")
679         out_java_enum += ("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
680         out_java_enum += ("\t@Override @SuppressWarnings(\"deprecation\")\n")
681         out_java_enum += ("\tprotected void finalize() throws Throwable {\n")
682         out_java_enum += ("\t\tsuper.finalize();\n")
683         out_java_enum += ("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
684         out_java_enum += ("\t}\n")
685         out_java_enum += ("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
686         out_java_enum += ("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
687         java_hu_subclasses = ""
688
689         init_meth_jty_strs = {}
690
691         out_java +=  ("\tpublic static class " + struct_name + " {\n")
692         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
693         for var in variant_list:
694             out_java +=  ("\t\tpublic final static class " + var.var_name + " extends " + struct_name + " {\n")
695             java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var.var_name + " extends " + java_hu_type + " {\n"
696             out_java_enum += ("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var.var_name + ".class) {\n")
697             out_java_enum += ("\t\t\treturn new " + var.var_name + "(ptr, (bindings." + struct_name + "." + var.var_name + ")raw_val);\n")
698             init_meth_jty_str = ""
699             init_meth_params = ""
700             init_meth_body = ""
701             hu_conv_body = ""
702             for idx, field_ty in enumerate(var.fields):
703                 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
704                 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
705                 if field_ty.to_hu_conv is not None:
706                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
707                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
708                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
709                 else:
710                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
711                 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
712                 if idx > 0:
713                     init_meth_params = init_meth_params + ", "
714                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
715                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
716             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
717             out_java +=  (init_meth_body)
718             out_java +=  ("}\n")
719             out_java += ("\t\t}\n")
720             out_java_enum += ("\t\t}\n")
721             java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var.var_name + "(long ptr, bindings." + struct_name + "." + var.var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
722             java_hu_subclasses = java_hu_subclasses + hu_conv_body
723             java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
724             init_meth_jty_strs[var.var_name] = init_meth_jty_str
725         out_java += ("\t\tstatic native void init();\n")
726         out_java += ("\t}\n")
727         out_java_enum += ("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
728         out_java_enum += (java_hu_subclasses)
729         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
730         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
731
732         out_c += (self.c_complex_enum_pfx(struct_name, [x.var_name for x in variant_list], init_meth_jty_strs))
733
734         out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
735         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
736         out_c += ("\tswitch(obj->tag) {\n")
737         for var in variant_list:
738             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
739             c_params = []
740             for idx, field_map in enumerate(var.fields):
741                 if field_map.ret_conv is not None:
742                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
743                     out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
744                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
745                     c_params.append(field_map.ret_conv_name)
746                 else:
747                     c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
748             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
749             out_c += ("\t\t}\n")
750         out_c += ("\t\tdefault: abort();\n")
751         out_c += ("\t}\n}\n")
752         out_java_enum += ("}\n")
753         return (out_java, out_java_enum, out_c)