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")
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
15 self.passed_as_ptr = passed_as_ptr
17 self.var_name = var_name
18 self.arr_len = arr_len
19 self.arr_access = arr_access
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
36 out_c.write(self.c_ty)
37 out_java.write(self.java_ty)
40 if self.arg_name != "":
41 out_java.write(" " + self.arg_name)
42 out_c.write(" " + self.arg_name)
44 out_java.write(" arg")
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()
52 def camel_to_snake(s):
53 # Convert camel case to snake case, in a way that appears to match cbindgen
59 if lastchar.isupper():
60 if not char.isupper() and not lastund:
65 ret = ret + lastchar.lower()
68 if char.isupper() and not lastund:
76 return (ret + lastchar.lower()).strip("_")
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 "):
85 if fn_arg.startswith("const "):
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"
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"
108 if fn_arg.startswith("void"):
112 fn_arg = fn_arg[4:].strip()
113 elif fn_arg.startswith("bool"):
117 fn_arg = fn_arg[4:].strip()
118 elif fn_arg.startswith("uint8_t"):
122 fn_arg = fn_arg[7:].strip()
123 elif fn_arg.startswith("uint16_t"):
127 fn_arg = fn_arg[8:].strip()
128 elif fn_arg.startswith("uint32_t"):
132 fn_arg = fn_arg[8:].strip()
133 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
137 if fn_arg.startswith("uint64_t"):
138 fn_arg = fn_arg[8:].strip()
140 fn_arg = fn_arg[9:].strip()
141 elif is_const and fn_arg.startswith("char *"):
144 fn_ty_arg = "Ljava/lang/String;"
145 fn_arg = fn_arg[6:].strip()
147 ma = var_ty_regex.match(fn_arg)
148 if ma.group(1).strip() in unitary_enums:
149 java_ty = ma.group(1).strip()
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()
159 fn_arg = ma.group(2).strip()
160 rust_obj = ma.group(1).strip()
163 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
164 fn_arg = fn_arg.replace("*", "").strip()
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)
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)
185 def map_type(fn_arg, print_void, ret_arr_len, is_free):
186 ty_info = java_c_types(fn_arg, ret_arr_len)
188 if ty_info.c_ty == "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)
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
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)
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,
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:
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}"
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")
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
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")
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)
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)
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)
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)
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)
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)
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)
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 ")
328 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
330 if ret_info.ret_conv is not None:
331 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
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")
337 for idx, arg in enumerate(re_match.group(3).split(',')):
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)
348 out_java.write(");\n")
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");
355 if ret_info.ret_conv is not None:
356 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
358 out_c.write("\treturn ");
360 if c_call_string is None:
361 out_c.write(re_match.group(2) + "(")
363 out_c.write(c_call_string)
364 for idx, info in enumerate(arg_names):
365 if info.arg_conv_name is not None:
368 elif c_call_string is not None:
370 out_c.write(info.arg_conv_name)
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 + ";")
377 out_c.write("\n}\n\n")
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")
386 for idx, struct_line in enumerate(field_lines):
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 == "")
399 out_java_enum.write(struct_line + "\n")
400 out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
403 out_c.write("\tabort();\n")
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")
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")
429 out_c.write("\t\tdefault: abort();\n")
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):
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 == "")
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 = ""
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
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");
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")
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")
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
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")
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")
522 out_java.write("\tpublic interface " + struct_name + " {\n")
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)
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(")
533 out_c.write("const void* this_arg")
535 out_c.write("void* this_arg")
538 for idx, arg in enumerate(fn_line.group(4).split(',')):
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)
552 out_java.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")
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")
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")
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");
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)
576 out_c.write(", " + arg_info.arg_name)
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")
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")
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")
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")
608 out_java.write("\t}\n")
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")
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")
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")
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))
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))
659 out_c.write("\treturn (long)res_ptr;\n")
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")
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")
674 out_c.write("""#include \"org_ldk_impl_bindings.h\"
675 #include <rust_types.h>
676 #include <lightning.h>
678 #include <stdatomic.h>
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")
686 out_c.write("""#include <assert.h>
687 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
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.
694 #include <execinfo.h>
696 static mtx_t allocation_mtx;
698 void __attribute__((constructor)) init_mtx() {
699 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
703 typedef struct allocation {
704 struct allocation* next;
706 const char* struct_name;
710 static allocation* allocation_ll = NULL;
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);
724 static void* MALLOC(size_t len, const char* struct_name) {
725 void* res = __real_malloc(len);
726 new_allocation(res, struct_name);
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);
740 static void FREE(void* ptr) {
745 void* __wrap_malloc(size_t len) {
746 void* res = __real_malloc(len);
747 new_allocation(res, "malloc call");
750 void* __wrap_calloc(size_t nmemb, size_t len) {
751 void* res = __real_calloc(nmemb, len);
752 new_allocation(res, "calloc call");
755 void __wrap_free(void* ptr) {
760 void* __real_realloc(void* ptr, size_t newlen);
761 void* __wrap_realloc(void* ptr, size_t len) {
763 void* res = __real_realloc(ptr, len);
764 new_allocation(res, "realloc call");
767 void __wrap_reallocarray(void* ptr, size_t new_sz) {
768 // Rust doesn't seem to use reallocarray currently
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");
778 DO_ASSERT(allocation_ll == NULL);
781 out_java.write("""package org.ldk.impl;
782 import org.ldk.enums.*;
784 public class bindings {
785 public static class VecOrSliceDef {
789 public VecOrSliceDef(long dataptr, long datalen, long stride) {
790 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
794 System.loadLibrary(\"lightningjni\");
795 init(java.lang.Enum.class, VecOrSliceDef.class);
797 static native void init(java.lang.Class c, java.lang.Class slicedef);
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();
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);
823 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
824 return *((bool*)ptr);
826 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
827 return *((long*)ptr);
829 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
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);
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);
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);
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);
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;
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");
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");
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
893 in_block_comment = False
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]*);$")
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;"))
916 result_templ_structs = set()
917 union_enum_items = {}
918 result_ptr_struct_items = {}
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("} "):
929 obj_lines = cur_block_obj.split("\n")
931 result_contents = None
932 is_unitary_enum = False
933 is_union_enum = False
939 for idx, struct_line in enumerate(obj_lines):
940 if struct_line.strip().startswith("/*"):
941 in_block_comment = True
943 if struct_line.endswith("*/"):
944 in_block_comment = False
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
954 elif struct_name_match.group(1) == "union":
956 if line_indicates_opaque_regex.match(struct_line):
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_"):
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)
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))
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)
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)
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")
1017 out_c.write("\tret->" + e + " = " + e + ";\n")
1018 out_c.write("\treturn (long)ret;\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")
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")
1038 out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
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")
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")
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
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)
1085 if line.startswith("#include <"):
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")
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")
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")
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")
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
1131 assert(line == "\n")
1133 out_java.write("}\n")