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