Intercept all malloc/free, even in Rust!
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 6:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/enums/ /path/to/bindings/output.c debug")
6     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
7     sys.exit(1)
8
9 class TypeInfo:
10     def __init__(self, rust_obj, java_ty, java_fn_ty_arg, c_ty, passed_as_ptr, is_ptr, var_name, arr_len):
11         self.rust_obj = rust_obj
12         self.java_ty = java_ty
13         self.java_fn_ty_arg = java_fn_ty_arg
14         self.c_ty = c_ty
15         self.passed_as_ptr = passed_as_ptr
16         self.is_ptr = is_ptr
17         self.var_name = var_name
18         self.arr_len = arr_len
19
20 class ConvInfo:
21     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
22         assert(ty_info.c_ty is not None)
23         assert(ty_info.java_ty is not None)
24         assert(arg_name is not None)
25         self.c_ty = ty_info.c_ty
26         self.java_ty = ty_info.java_ty
27         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
28         self.arg_name = arg_name
29         self.arg_conv = arg_conv
30         self.arg_conv_name = arg_conv_name
31         self.ret_conv = ret_conv
32         self.ret_conv_name = ret_conv_name
33
34     def print_ty(self):
35         out_c.write(self.c_ty)
36         out_java.write(self.java_ty)
37
38     def print_name(self):
39         if self.arg_name != "":
40             out_java.write(" " + self.arg_name)
41             out_c.write(" " + self.arg_name)
42         else:
43             out_java.write(" arg")
44             out_c.write(" arg")
45
46 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
47     opaque_structs = set()
48     trait_structs = set()
49     unitary_enums = set()
50
51     def camel_to_snake(s):
52         # Convert camel case to snake case, in a way that appears to match cbindgen
53         con = "_"
54         ret = ""
55         lastchar = ""
56         lastund = False
57         for char in s:
58             if lastchar.isupper():
59                 if not char.isupper() and not lastund:
60                     ret = ret + "_"
61                     lastund = True
62                 else:
63                     lastund = False
64                 ret = ret + lastchar.lower()
65             else:
66                 ret = ret + lastchar
67                 if char.isupper() and not lastund:
68                     ret = ret + "_"
69                     lastund = True
70                 else:
71                     lastund = False
72             lastchar = char
73             if char.isnumeric():
74                 lastund = True
75         return (ret + lastchar.lower()).strip("_")
76
77     var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([0-9]*)\]")
78     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
79     def java_c_types(fn_arg, ret_arr_len):
80         fn_arg = fn_arg.strip()
81         if fn_arg.startswith("MUST_USE_RES "):
82             fn_arg = fn_arg[13:]
83         is_const = False
84         if fn_arg.startswith("const "):
85             fn_arg = fn_arg[6:]
86             is_const = True
87
88         is_ptr = False
89         take_by_ptr = False
90         rust_obj = None
91         if fn_arg.startswith("LDKThirtyTwoBytes"):
92             fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
93             assert var_is_arr_regex.match(fn_arg[8:])
94             rust_obj = "LDKThirtyTwoBytes"
95
96         if fn_arg.startswith("void"):
97             java_ty = "void"
98             c_ty = "void"
99             fn_ty_arg = "V"
100             fn_arg = fn_arg[4:].strip()
101         elif fn_arg.startswith("bool"):
102             java_ty = "boolean"
103             c_ty = "jboolean"
104             fn_ty_arg = "Z"
105             fn_arg = fn_arg[4:].strip()
106         elif fn_arg.startswith("uint8_t"):
107             java_ty = "byte"
108             c_ty = "jbyte"
109             fn_ty_arg = "B"
110             fn_arg = fn_arg[7:].strip()
111         elif fn_arg.startswith("uint16_t"):
112             java_ty = "short"
113             c_ty = "jshort"
114             fn_ty_arg = "S"
115             fn_arg = fn_arg[8:].strip()
116         elif fn_arg.startswith("uint32_t"):
117             java_ty = "int"
118             c_ty = "jint"
119             fn_ty_arg = "I"
120             fn_arg = fn_arg[8:].strip()
121         elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
122             java_ty = "long"
123             c_ty = "jlong"
124             fn_ty_arg = "J"
125             if fn_arg.startswith("uint64_t"):
126                 fn_arg = fn_arg[8:].strip()
127             else:
128                 fn_arg = fn_arg[9:].strip()
129         elif is_const and fn_arg.startswith("char *"):
130             java_ty = "String"
131             c_ty = "const char*"
132             fn_ty_arg = "Ljava/lang/String;"
133             fn_arg = fn_arg[6:].strip()
134         else:
135             ma = var_ty_regex.match(fn_arg)
136             if ma.group(1).strip() in unitary_enums:
137                 java_ty = ma.group(1).strip()
138                 c_ty = "jclass"
139                 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
140                 fn_arg = ma.group(2).strip()
141                 rust_obj = ma.group(1).strip()
142                 take_by_ptr = True
143             else:
144                 java_ty = "long"
145                 c_ty = "jlong"
146                 fn_ty_arg = "J"
147                 fn_arg = ma.group(2).strip()
148                 rust_obj = ma.group(1).strip()
149                 take_by_ptr = True
150
151         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
152             fn_arg = fn_arg.replace("*", "").strip()
153             is_ptr = True
154             c_ty = "jlong"
155             java_ty = "long"
156             fn_ty_arg = "J"
157
158         var_is_arr = var_is_arr_regex.match(fn_arg)
159         if var_is_arr is not None or ret_arr_len is not None:
160             assert(not take_by_ptr)
161             assert(not is_ptr)
162             java_ty = java_ty + "[]"
163             c_ty = c_ty + "Array"
164             if var_is_arr is not None:
165                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
166                     passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
167         return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
168             is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
169
170     def map_type(fn_arg, print_void, ret_arr_len, is_free):
171         ty_info = java_c_types(fn_arg, ret_arr_len)
172
173         if ty_info.c_ty == "void":
174             if not print_void:
175                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
176                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
177
178         if ty_info.c_ty.endswith("Array"):
179             arr_len = ty_info.arr_len
180             if arr_len is not None:
181                 arr_name = ty_info.var_name
182             else:
183                 arr_name = "ret"
184                 arr_len = ret_arr_len
185             assert(ty_info.c_ty == "jbyteArray")
186             if ty_info.rust_obj is not None:
187                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n" + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref.data);"
188                 arr_access = ("", ".data")
189             else:
190                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
191                 arr_access = ("*", "")
192             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
193                 arg_conv = arg_conv,
194                 arg_conv_name = arr_name + "_ref",
195                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
196                     "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", " + arr_access[0],
197                     arr_access[1] + ");"),
198                 ret_conv_name = arr_name + "_arr")
199         elif ty_info.var_name != "":
200             # If we have a parameter name, print it (noting that it may indicate its a pointer)
201             if ty_info.rust_obj is not None:
202                 assert(ty_info.passed_as_ptr)
203                 if not ty_info.is_ptr:
204                     if ty_info.rust_obj in unitary_enums:
205                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
206                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
207                             arg_conv_name = ty_info.var_name + "_conv",
208                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
209                             ret_conv_name = ty_info.var_name + "_conv")
210                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
211                     if ty_info.rust_obj in trait_structs:
212                         if not is_free:
213                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
214                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
215                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
216                         else:
217                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
218                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
219                             arg_conv = base_conv,
220                             arg_conv_name = ty_info.var_name + "_conv",
221                             ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
222                     if ty_info.rust_obj != "LDKu8slice":
223                         # Don't bother free'ing slices passed in - Rust doesn't auto-free the
224                         # underlying unlike Vecs, and it gives Java more freedom.
225                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
226                     if ty_info.rust_obj in opaque_structs:
227                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
228                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
229                             arg_conv_name = ty_info.var_name + "_conv",
230                             ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
231
232                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
233                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
234                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
235                 else:
236                     assert(not is_free)
237                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
238                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
239                         arg_conv_name = ty_info.var_name + "_conv",
240                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
241             elif ty_info.is_ptr:
242                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
243                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
244             elif ty_info.java_ty == "String":
245                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
246                     arg_conv = None, arg_conv_name = None,
247                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
248             else:
249                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
250                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
251         elif not print_void:
252             # We don't have a parameter name, and want one, just call it arg
253             if ty_info.rust_obj is not None:
254                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
255                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
256                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
257                     arg_conv_name = "arg_conv",
258                     ret_conv = None, ret_conv_name = None)
259             else:
260                 assert(not is_free)
261                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
262                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
263         else:
264             # We don't have a parameter name, and don't want one (cause we're returning)
265             if ty_info.rust_obj is not None:
266                 if not ty_info.is_ptr:
267                     if ty_info.rust_obj in unitary_enums:
268                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
269                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
270                             arg_conv_name = "ret",
271                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
272                     if ty_info.rust_obj in opaque_structs:
273                         # If we're returning a newly-allocated struct, we don't want Rust to ever
274                         # free, instead relying on the Java GC to lose the ref. We undo this in
275                         # any _free function.
276                         # To avoid any issues, we first assert that the incoming object is non-ref.
277                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
278                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nDO_ASSERT(ret->is_owned);\nret->is_owned = false;"),
279                             ret_conv_name = "(long)ret",
280                             arg_conv = None, arg_conv_name = None)
281                     else:
282                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
283                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
284                             ret_conv_name = "(long)ret",
285                             arg_conv = None, arg_conv_name = None)
286                 else:
287                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
288                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
289                         arg_conv = None, arg_conv_name = None)
290             else:
291                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
292                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
293
294     def map_fn(line, re_match, ret_arr_len, c_call_string):
295         out_java.write("\t// " + line)
296         out_java.write("\tpublic static native ")
297         out_c.write("JNIEXPORT ")
298
299         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
300         ret_info.print_ty()
301         if ret_info.ret_conv is not None:
302             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
303
304         out_java.write(" " + re_match.group(2) + "(")
305         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
306
307         arg_names = []
308         for idx, arg in enumerate(re_match.group(3).split(',')):
309             if idx != 0:
310                 out_java.write(", ")
311             if arg != "void":
312                 out_c.write(", ")
313             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
314             if arg_conv_info.c_ty != "void":
315                 arg_conv_info.print_ty()
316                 arg_conv_info.print_name()
317             arg_names.append(arg_conv_info)
318
319         out_java.write(");\n")
320         out_c.write(") {\n")
321
322         for info in arg_names:
323             if info.arg_conv is not None:
324                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
325
326         if ret_info.ret_conv is not None:
327             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
328         else:
329             out_c.write("\treturn ");
330
331         if c_call_string is None:
332             out_c.write(re_match.group(2) + "(")
333         else:
334             out_c.write(c_call_string)
335         for idx, info in enumerate(arg_names):
336             if info.arg_conv_name is not None:
337                 if idx != 0:
338                     out_c.write(", ")
339                 elif c_call_string is not None:
340                     continue
341                 out_c.write(info.arg_conv_name)
342         out_c.write(")")
343         if ret_info.ret_conv is not None:
344             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
345             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
346         else:
347             out_c.write(";")
348         out_c.write("\n}\n\n")
349
350     def map_unitary_enum(struct_name, field_lines):
351         with open(sys.argv[3] + "/" + struct_name + ".java", "w") as out_java_enum:
352             out_java_enum.write("package org.ldk.enums;\n\n")
353             unitary_enums.add(struct_name)
354             out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
355             out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
356             ord_v = 0
357             for idx, struct_line in enumerate(field_lines):
358                 if idx == 0:
359                     out_java_enum.write("public enum " + struct_name + " {\n")
360                 elif idx == len(field_lines) - 3:
361                     assert(struct_line.endswith("_Sentinel,"))
362                 elif idx == len(field_lines) - 2:
363                     out_java_enum.write("\t; static native void init();\n")
364                     out_java_enum.write("\tstatic { init(); }\n")
365                     out_java_enum.write("}")
366                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
367                 elif idx == len(field_lines) - 1:
368                     assert(struct_line == "")
369                 else:
370                     out_java_enum.write(struct_line + "\n")
371                     out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
372                     ord_v = ord_v + 1
373             out_c.write("\t}\n")
374             out_c.write("\tabort();\n")
375             out_c.write("}\n")
376
377             ord_v = 0
378             out_c.write("static jclass " + struct_name + "_class = NULL;\n")
379             for idx, struct_line in enumerate(field_lines):
380                 if idx > 0 and idx < len(field_lines) - 3:
381                     variant = struct_line.strip().strip(",")
382                     out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
383             out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
384             out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
385             out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
386             for idx, struct_line in enumerate(field_lines):
387                 if idx > 0 and idx < len(field_lines) - 3:
388                     variant = struct_line.strip().strip(",")
389                     out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
390                     out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
391             out_c.write("}\n")
392             out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
393             out_c.write("\tswitch (val) {\n")
394             for idx, struct_line in enumerate(field_lines):
395                 if idx > 0 and idx < len(field_lines) - 3:
396                     variant = struct_line.strip().strip(",")
397                     out_c.write("\t\tcase " + variant + ":\n")
398                     out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
399                     ord_v = ord_v + 1
400             out_c.write("\t\tdefault: abort();\n")
401             out_c.write("\t}\n")
402             out_c.write("}\n\n")
403
404     def map_complex_enum(struct_name, union_enum_items):
405         tag_field_lines = union_enum_items["field_lines"]
406         init_meth_jty_strs = {}
407         for idx, struct_line in enumerate(tag_field_lines):
408             if idx == 0:
409                 out_java.write("\tpublic static class " + struct_name + " {\n")
410                 out_java.write("\t\tprivate " + struct_name + "() {}\n")
411             elif idx == len(tag_field_lines) - 3:
412                 assert(struct_line.endswith("_Sentinel,"))
413             elif idx == len(tag_field_lines) - 2:
414                 out_java.write("\t\tstatic native void init();\n")
415                 out_java.write("\t}\n")
416             elif idx == len(tag_field_lines) - 1:
417                 assert(struct_line == "")
418             else:
419                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
420                 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
421                 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
422                 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
423                 init_meth_jty_str = ""
424                 init_meth_params = ""
425                 init_meth_body = ""
426                 if "LDK" + var_name in union_enum_items:
427                     enum_var_lines = union_enum_items["LDK" + var_name]
428                     for idx, field in enumerate(enum_var_lines):
429                         if idx != 0 and idx < len(enum_var_lines) - 2:
430                             field_ty = java_c_types(field.strip(' ;'), None)
431                             out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
432                             init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
433                             if idx > 1:
434                                 init_meth_params = init_meth_params + ", "
435                             init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
436                             init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
437                     out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
438                     out_java.write(init_meth_body)
439                     out_java.write("}\n")
440                 out_java.write("\t\t}\n")
441                 init_meth_jty_strs[var_name] = init_meth_jty_str
442         out_java.write("\tstatic { " + struct_name + ".init(); }\n")
443         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
444
445         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
446         for idx, struct_line in enumerate(tag_field_lines):
447             if idx != 0 and idx < len(tag_field_lines) - 3:
448                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
449                 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
450                 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
451                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
452                 out_c.write("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
453                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
454         out_c.write("}\n")
455         out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * env, jclass _c, jlong ptr) {\n")
456         out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
457         out_c.write("\tswitch(obj->tag) {\n")
458         for idx, struct_line in enumerate(tag_field_lines):
459             if idx != 0 and idx < len(tag_field_lines) - 3:
460                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
461                 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
462                 c_params_text = ""
463                 if "LDK" + var_name in union_enum_items:
464                     enum_var_lines = union_enum_items["LDK" + var_name]
465                     for idx, field in enumerate(enum_var_lines):
466                         if idx != 0 and idx < len(enum_var_lines) - 2:
467                             field_map = map_type(field.strip(' ;'), False, None, False)
468                             if field_map.ret_conv is not None:
469                                 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
470                                 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
471                                 out_c.write(field_map.ret_conv[1] + "\n")
472                                 c_params_text = c_params_text + ", " + field_map.ret_conv_name
473                             else:
474                                 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
475                 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
476                 out_c.write("\t\t}\n")
477         out_c.write("\t\tdefault: abort();\n")
478         out_c.write("\t}\n}\n")
479
480     def map_trait(struct_name, field_var_lines, trait_fn_lines):
481         out_c.write("typedef struct " + struct_name + "_JCalls {\n")
482         out_c.write("\tatomic_size_t refcnt;\n")
483         out_c.write("\tJavaVM *vm;\n")
484         out_c.write("\tjobject o;\n")
485         for var_line in field_var_lines:
486             if var_line.group(1) in trait_structs:
487                 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
488         for fn_line in trait_fn_lines:
489             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
490                 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
491         out_c.write("} " + struct_name + "_JCalls;\n")
492
493         out_java.write("\tpublic interface " + struct_name + " {\n")
494         java_meths = []
495         for fn_line in trait_fn_lines:
496             java_meth_descr = "("
497             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
498                 ret_ty_info = java_c_types(fn_line.group(1), None)
499
500                 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
501                 is_const = fn_line.group(3) is not None
502                 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
503                 if is_const:
504                     out_c.write("const void* this_arg")
505                 else:
506                     out_c.write("void* this_arg")
507
508                 arg_names = []
509                 for idx, arg in enumerate(fn_line.group(4).split(',')):
510                     if arg == "":
511                         continue
512                     if idx >= 2:
513                         out_java.write(", ")
514                     out_c.write(", ")
515                     arg_conv_info = map_type(arg, True, None, False)
516                     out_c.write(arg.strip())
517                     out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
518                     arg_names.append(arg_conv_info)
519                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
520                 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
521                 java_meths.append(java_meth_descr)
522
523                 out_java.write(");\n")
524                 out_c.write(") {\n")
525                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
526                 out_c.write("\tJNIEnv *env;\n")
527                 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
528
529                 for arg_info in arg_names:
530                     if arg_info.ret_conv is not None:
531                         out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
532                         out_c.write(arg_info.arg_name)
533                         out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
534
535                 if ret_ty_info.c_ty.endswith("Array"):
536                     assert(ret_ty_info.c_ty == "jbyteArray")
537                     out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
538                 elif not ret_ty_info.passed_as_ptr:
539                     out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
540                 else:
541                     out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*env)->CallLongMethod(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth");
542
543                 for arg_info in arg_names:
544                     if arg_info.ret_conv is not None:
545                         out_c.write(", " + arg_info.ret_conv_name)
546                     else:
547                         out_c.write(", " + arg_info.arg_name)
548                 out_c.write(");\n");
549                 if ret_ty_info.c_ty.endswith("Array"):
550                     out_c.write("\tLDKThirtyTwoBytes ret;\n")
551                     out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret.data);\n")
552                     out_c.write("\treturn ret;\n")
553
554                 if ret_ty_info.passed_as_ptr:
555                     out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
556                     out_c.write("\tFREE(ret);\n")
557                     out_c.write("\treturn res;\n")
558                 out_c.write("}\n")
559             elif fn_line.group(2) == "free":
560                 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
561                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
562                 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
563                 out_c.write("\t\tJNIEnv *env;\n")
564                 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
565                 out_c.write("\t\t(*env)->DeleteGlobalRef(env, j_calls->o);\n")
566                 out_c.write("\t\tFREE(j_calls);\n")
567                 out_c.write("\t}\n}\n")
568
569         # Write out a clone function whether we need one or not, as we use them in moving to rust
570         out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
571         out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
572         out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
573         for var_line in field_var_lines:
574             if var_line.group(1) in trait_structs:
575                 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
576         out_c.write("\treturn (void*) this_arg;\n")
577         out_c.write("}\n")
578
579         out_java.write("\t}\n")
580
581         out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
582         out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
583         for var_line in field_var_lines:
584             if var_line.group(1) in trait_structs:
585                 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
586                 out_c.write(", jobject " + var_line.group(2))
587         out_java.write(");\n")
588         out_c.write(") {\n")
589
590         out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
591         out_c.write("\tDO_ASSERT(c != NULL);\n")
592         out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
593         out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
594         out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
595         out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
596         for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
597             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
598                 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
599                 out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
600         out_c.write("\n\t" + struct_name + " ret = {\n")
601         out_c.write("\t\t.this_arg = (void*) calls,\n")
602         for fn_line in trait_fn_lines:
603             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
604                 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
605             elif fn_line.group(2) == "free":
606                 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
607             else:
608                 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
609         for var_line in field_var_lines:
610             if var_line.group(1) in trait_structs:
611                 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
612         out_c.write("\t};\n")
613         for var_line in field_var_lines:
614             if var_line.group(1) in trait_structs:
615                 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
616         out_c.write("\treturn ret;\n")
617         out_c.write("}\n")
618
619         out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
620         for var_line in field_var_lines:
621             if var_line.group(1) in trait_structs:
622                 out_c.write(", jobject " + var_line.group(2))
623         out_c.write(") {\n")
624         out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
625         out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
626         for var_line in field_var_lines:
627             if var_line.group(1) in trait_structs:
628                 out_c.write(", " + var_line.group(2))
629         out_c.write(");\n")
630         out_c.write("\treturn (long)res_ptr;\n")
631         out_c.write("}\n")
632
633         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
634         out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (JNIEnv * env, jclass _a, jlong val) {\n")
635         out_c.write("\treturn ((" + struct_name + "_JCalls*)val)->o;\n")
636         out_c.write("}\n")
637
638         for fn_line in trait_fn_lines:
639             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
640             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
641             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
642                 dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
643                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(arg_conv->" + fn_line.group(2) + ")(arg_conv->this_arg")
644
645     out_c.write("""#include \"org_ldk_impl_bindings.h\"
646 #include <rust_types.h>
647 #include <lightning.h>
648 #include <string.h>
649 #include <stdatomic.h>
650 """)
651
652     if sys.argv[4] == "false":
653         out_c.write("#define MALLOC(a, _) malloc(a)\n")
654         out_c.write("#define FREE free\n")
655         out_c.write("#define DO_ASSERT(a) (void)(a)\n")
656     else:
657         out_c.write("""#include <assert.h>
658 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
659
660 // Running a leak check across all the allocations and frees of the JDK is a mess,
661 // so instead we implement our own naive leak checker here, relying on the -wrap
662 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
663 // and free'd in Rust or C across the generated bindings shared library.
664 #include <threads.h>
665 #include <execinfo.h>
666 #include <unistd.h>
667 static mtx_t allocation_mtx;
668
669 void __attribute__((constructor)) init_mtx() {
670         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
671 }
672
673 #define BT_MAX 128
674 typedef struct allocation {
675         struct allocation* next;
676         void* ptr;
677         const char* struct_name;
678         void* bt[BT_MAX];
679         int bt_len;
680 } allocation;
681 static allocation* allocation_ll = NULL;
682
683 void* __real_malloc(size_t len);
684 void* __real_calloc(size_t nmemb, size_t len);
685 static void new_allocation(void* res, const char* struct_name) {
686         allocation* new_alloc = __real_malloc(sizeof(allocation));
687         new_alloc->ptr = res;
688         new_alloc->struct_name = struct_name;
689         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
690         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
691         new_alloc->next = allocation_ll;
692         allocation_ll = new_alloc;
693         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
694 }
695 static void* MALLOC(size_t len, const char* struct_name) {
696         void* res = __real_malloc(len);
697         new_allocation(res, struct_name);
698         return res;
699 }
700 void __real_free(void* ptr);
701 static void alloc_freed(void* ptr) {
702         allocation* p = NULL;
703         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
704         allocation* it = allocation_ll;
705         while (it->ptr != ptr) { p = it; it = it->next; }
706         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
707         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
708         DO_ASSERT(it->ptr == ptr);
709         __real_free(it);
710 }
711 static void FREE(void* ptr) {
712         alloc_freed(ptr);
713         __real_free(ptr);
714 }
715
716 void* __wrap_malloc(size_t len) {
717         void* res = __real_malloc(len);
718         new_allocation(res, "malloc call");
719         return res;
720 }
721 void* __wrap_calloc(size_t nmemb, size_t len) {
722         void* res = __real_calloc(nmemb, len);
723         new_allocation(res, "calloc call");
724         return res;
725 }
726 void __wrap_free(void* ptr) {
727         alloc_freed(ptr);
728         __real_free(ptr);
729 }
730
731 void* __real_realloc(void* ptr, size_t newlen);
732 void* __wrap_realloc(void* ptr, size_t len) {
733         alloc_freed(ptr);
734         void* res = __real_realloc(ptr, len);
735         new_allocation(res, "realloc call");
736         return res;
737 }
738 void __wrap_reallocarray(void* ptr, size_t new_sz) {
739         // Rust doesn't seem to use reallocarray currently
740         assert(false);
741 }
742
743 void __attribute__((destructor)) check_leaks() {
744         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
745                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
746                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
747                 fprintf(stderr, "\\n\\n");
748         }
749         DO_ASSERT(allocation_ll == NULL);
750 }
751 """)
752     out_java.write("""package org.ldk.impl;
753 import org.ldk.enums.*;
754
755 public class bindings {
756         public static class VecOrSliceDef {
757                 public long dataptr;
758                 public long datalen;
759                 public long stride;
760                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
761                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
762                 }
763         }
764         static {
765                 System.loadLibrary(\"lightningjni\");
766                 init(java.lang.Enum.class, VecOrSliceDef.class);
767         }
768         static native void init(java.lang.Class c, java.lang.Class slicedef);
769
770         public static native boolean deref_bool(long ptr);
771         public static native long deref_long(long ptr);
772         public static native void free_heap_ptr(long ptr);
773         public static native byte[] read_bytes(long ptr, long len);
774         public static native byte[] get_u8_slice_bytes(long slice_ptr);
775         public static native long bytes_to_u8_vec(byte[] bytes);
776         public static native long new_txpointer_copy_data(byte[] txdata);
777         public static native long vec_slice_len(long vec);
778         public static native long new_empty_slice_vec();
779
780 """)
781     out_c.write("""
782 static jmethodID ordinal_meth = NULL;
783 static jmethodID slicedef_meth = NULL;
784 static jclass slicedef_cls = NULL;
785 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
786         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
787         DO_ASSERT(ordinal_meth != NULL);
788         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
789         DO_ASSERT(slicedef_meth != NULL);
790         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
791         DO_ASSERT(slicedef_cls != NULL);
792 }
793
794 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
795         return *((bool*)ptr);
796 }
797 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
798         return *((long*)ptr);
799 }
800 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
801         FREE((void*)ptr);
802 }
803 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
804         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
805         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
806         return ret_arr;
807 }
808 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
809         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
810         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
811         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
812         return ret_arr;
813 }
814 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
815         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
816         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
817         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
818         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
819         return (long)vec;
820 }
821 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
822         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
823         txdata->datalen = (*env)->GetArrayLength(env, bytes);
824         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
825         txdata->data_is_owned = true;
826         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
827         return (long)txdata;
828 }
829 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
830         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
831         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
832         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
833         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
834         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
835         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
836         return (long)vec->datalen;
837 }
838 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
839         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
840         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
841         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
842         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
843         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
844         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
845         vec->data = NULL;
846         vec->datalen = 0;
847         return (long)vec;
848 }
849
850 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
851 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
852 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
853 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
854
855 """)
856
857     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
858     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
859     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
860     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
861     out_c.write("\treturn (long)key;\n") # TODO: rm me
862     out_c.write("}\n") # TODO: rm me
863
864     in_block_comment = False
865     cur_block_obj = None
866
867     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
868     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
869     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
870     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
871
872     line_indicates_result_regex = re.compile("^   bool result_ok;$")
873     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
874     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
875     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
876     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
877     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
878     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
879     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
880     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
881     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
882     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
883     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
884     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
885     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
886
887     result_templ_structs = set()
888     union_enum_items = {}
889     for line in in_h:
890         if in_block_comment:
891             if line.endswith("*/\n"):
892                 in_block_comment = False
893         elif cur_block_obj is not None:
894             cur_block_obj  = cur_block_obj + line
895             if line.startswith("} "):
896                 field_lines = []
897                 struct_name = None
898                 vec_ty = None
899                 obj_lines = cur_block_obj.split("\n")
900                 is_opaque = False
901                 is_result = False
902                 is_unitary_enum = False
903                 is_union_enum = False
904                 is_union = False
905                 is_tuple = False
906                 trait_fn_lines = []
907                 field_var_lines = []
908
909                 for idx, struct_line in enumerate(obj_lines):
910                     if struct_line.strip().startswith("/*"):
911                         in_block_comment = True
912                     if in_block_comment:
913                         if struct_line.endswith("*/"):
914                             in_block_comment = False
915                     else:
916                         struct_name_match = struct_name_regex.match(struct_line)
917                         if struct_name_match is not None:
918                             struct_name = struct_name_match.group(3)
919                             if struct_name_match.group(1) == "enum":
920                                 if not struct_name.endswith("_Tag"):
921                                     is_unitary_enum = True
922                                 else:
923                                     is_union_enum = True
924                             elif struct_name_match.group(1) == "union":
925                                 is_union = True
926                         if line_indicates_opaque_regex.match(struct_line):
927                             is_opaque = True
928                         elif line_indicates_result_regex.match(struct_line):
929                             is_result = True
930                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
931                         if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
932                             vec_ty = vec_ty_match.group(1)
933                         elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
934                             is_tuple = True
935                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
936                         if trait_fn_match is not None:
937                             trait_fn_lines.append(trait_fn_match)
938                         field_var_match = line_field_var_regex.match(struct_line)
939                         if field_var_match is not None:
940                             field_var_lines.append(field_var_match)
941                         field_lines.append(struct_line)
942
943                 assert(struct_name is not None)
944                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or is_result or vec_ty is not None))
945                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or is_result or vec_ty is not None))
946                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or is_result or vec_ty is not None))
947                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or is_result or vec_ty is not None))
948                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_result or vec_ty is not None))
949                 assert(not is_result or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or vec_ty is not None))
950                 assert(vec_ty is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or is_result))
951
952                 if is_opaque:
953                     opaque_structs.add(struct_name)
954                     out_java.write("\tpublic static native long " + struct_name + "_optional_none();\n")
955                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1optional_1none (JNIEnv * env, jclass _a) {\n")
956                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
957                     out_c.write("\tret->inner = NULL;\n")
958                     out_c.write("\treturn (long)ret;\n")
959                     out_c.write("}\n")
960                 elif is_result:
961                     result_templ_structs.add(struct_name)
962                 elif is_tuple:
963                     out_java.write("\tpublic static native long " + struct_name + "_new(")
964                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
965                     for idx, line in enumerate(field_lines):
966                         if idx != 0 and idx < len(field_lines) - 2:
967                             ty_info = java_c_types(line.strip(';'), None)
968                             if idx != 1:
969                                 out_java.write(", ")
970                             e = chr(ord('a') + idx - 1)
971                             out_java.write(ty_info.java_ty + " " + e)
972                             out_c.write(", " + ty_info.c_ty + " " + e)
973                     out_java.write(");\n")
974                     out_c.write(") {\n")
975                     out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
976                     for idx, line in enumerate(field_lines):
977                         if idx != 0 and idx < len(field_lines) - 2:
978                             ty_info = map_type(line.strip(';'), False, None, False)
979                             e = chr(ord('a') + idx - 1)
980                             if ty_info.arg_conv is not None:
981                                 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
982                                 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
983                             else:
984                                 out_c.write("\tret->" + e + " = " + e + ";\n")
985                     out_c.write("\treturn (long)ret;\n")
986                     out_c.write("}\n")
987                 elif vec_ty is not None:
988                     out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
989                     out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
990                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
991                     out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
992                     out_c.write("}\n")
993
994                     ty_info = map_type(vec_ty + " arr_elem", False, None, False)
995                     out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
996                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *env, jclass _b, j" + ty_info.java_ty + "Array elems){\n")
997                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
998                     out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
999                     out_c.write("\tif (ret->datalen == 0) {\n")
1000                     out_c.write("\t\tret->data = NULL;\n")
1001                     out_c.write("\t} else {\n")
1002                     out_c.write("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1003                     assert len(ty_info.java_fn_ty_arg) == 1 # ie we're a primitive of some form
1004                     out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1005                     out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1006                     if ty_info.arg_conv is not None:
1007                         out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1008                         out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1009                         out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1010                     else:
1011                         out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
1012                     out_c.write("\t\t}\n")
1013                     out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1014                     out_c.write("\t}\n")
1015                     out_c.write("\treturn (long)ret;\n")
1016                     out_c.write("}\n")
1017                 elif is_union_enum:
1018                     assert(struct_name.endswith("_Tag"))
1019                     struct_name = struct_name[:-4]
1020                     union_enum_items[struct_name] = {"field_lines": field_lines}
1021                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1022                     enum_var_name = struct_name.split("_")
1023                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1024                 elif struct_name in union_enum_items:
1025                     map_complex_enum(struct_name, union_enum_items[struct_name])
1026                 elif is_unitary_enum:
1027                     map_unitary_enum(struct_name, field_lines)
1028                 elif len(trait_fn_lines) > 0:
1029                     trait_structs.add(struct_name)
1030                     map_trait(struct_name, field_var_lines, trait_fn_lines)
1031                 cur_block_obj = None
1032         else:
1033             fn_ptr = fn_ptr_regex.match(line)
1034             fn_ret_arr = fn_ret_arr_regex.match(line)
1035             reg_fn = reg_fn_regex.match(line)
1036             const_val = const_val_regex.match(line)
1037
1038             if line.startswith("#include <"):
1039                 pass
1040             elif line.startswith("/*"):
1041                 #out_java.write("\t" + line)
1042                 if not line.endswith("*/\n"):
1043                     in_block_comment = True
1044             elif line.startswith("typedef enum "):
1045                 cur_block_obj = line
1046             elif line.startswith("typedef struct "):
1047                 cur_block_obj = line
1048             elif line.startswith("typedef union "):
1049                 cur_block_obj = line
1050             elif line.startswith("typedef "):
1051                 alias_match =  struct_alias_regex.match(line)
1052                 if alias_match.group(1) in result_templ_structs:
1053                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1054                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
1055                     out_c.write("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
1056                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1057                     out_c.write("}\n")
1058                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1inner (JNIEnv * env, jclass _a, jlong arg) {\n")
1059                     out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
1060                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
1061                     out_c.write("\t} else {\n")
1062                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
1063                     out_c.write("\t}\n}\n")
1064                 pass
1065             elif fn_ptr is not None:
1066                 map_fn(line, fn_ptr, None, None)
1067             elif fn_ret_arr is not None:
1068                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1069             elif reg_fn is not None:
1070                 map_fn(line, reg_fn, None, None)
1071             elif const_val_regex is not None:
1072                 # TODO Map const variables
1073                 pass
1074             else:
1075                 assert(line == "\n")
1076
1077     out_java.write("}\n")