5 print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/ /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.passed_as_ptr = ty_info.passed_as_ptr
27 self.rust_obj = ty_info.rust_obj
28 self.c_ty = ty_info.c_ty
29 self.java_ty = ty_info.java_ty
30 self.java_fn_ty_arg = ty_info.java_fn_ty_arg
31 self.arg_name = arg_name
32 self.arg_conv = arg_conv
33 self.arg_conv_name = arg_conv_name
34 self.ret_conv = ret_conv
35 self.ret_conv_name = ret_conv_name
38 out_c.write(self.c_ty)
39 out_java.write(self.java_ty)
42 if self.arg_name != "":
43 out_java.write(" " + self.arg_name)
44 out_c.write(" " + self.arg_name)
46 out_java.write(" arg")
48 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
49 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
50 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
52 with open(sys.argv[1]) as in_h:
54 reg_fn = reg_fn_regex.match(line)
55 if reg_fn is not None:
56 if reg_fn.group(2).endswith("_clone"):
57 clone_fns.add(reg_fn.group(2))
59 arr_fn = fn_ret_arr_regex.match(line)
60 if arr_fn is not None:
61 if arr_fn.group(2).endswith("_clone"):
62 clone_fns.add(arr_fn.group(2))
65 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
66 opaque_structs = set()
70 def camel_to_snake(s):
71 # Convert camel case to snake case, in a way that appears to match cbindgen
77 if lastchar.isupper():
78 if not char.isupper() and not lastund:
83 ret = ret + lastchar.lower()
86 if char.isupper() and not lastund:
94 return (ret + lastchar.lower()).strip("_")
96 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([0-9]*)\]")
97 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
98 def java_c_types(fn_arg, ret_arr_len):
99 fn_arg = fn_arg.strip()
100 if fn_arg.startswith("MUST_USE_RES "):
103 if fn_arg.startswith("const "):
111 if fn_arg.startswith("LDKThirtyTwoBytes"):
112 fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
113 assert var_is_arr_regex.match(fn_arg[8:])
114 rust_obj = "LDKThirtyTwoBytes"
116 if fn_arg.startswith("LDKPublicKey"):
117 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
118 assert var_is_arr_regex.match(fn_arg[8:])
119 rust_obj = "LDKPublicKey"
120 arr_access = "compressed_form"
121 if fn_arg.startswith("LDKSecretKey"):
122 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
123 assert var_is_arr_regex.match(fn_arg[8:])
124 rust_obj = "LDKSecretKey"
126 if fn_arg.startswith("LDKSignature"):
127 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
128 assert var_is_arr_regex.match(fn_arg[8:])
129 rust_obj = "LDKSignature"
130 arr_access = "compact_form"
132 if fn_arg.startswith("void"):
136 fn_arg = fn_arg[4:].strip()
137 elif fn_arg.startswith("bool"):
141 fn_arg = fn_arg[4:].strip()
142 elif fn_arg.startswith("uint8_t"):
146 fn_arg = fn_arg[7:].strip()
147 elif fn_arg.startswith("uint16_t"):
151 fn_arg = fn_arg[8:].strip()
152 elif fn_arg.startswith("uint32_t"):
156 fn_arg = fn_arg[8:].strip()
157 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
161 if fn_arg.startswith("uint64_t"):
162 fn_arg = fn_arg[8:].strip()
164 fn_arg = fn_arg[9:].strip()
165 elif is_const and fn_arg.startswith("char *"):
168 fn_ty_arg = "Ljava/lang/String;"
169 fn_arg = fn_arg[6:].strip()
171 ma = var_ty_regex.match(fn_arg)
172 if ma.group(1).strip() in unitary_enums:
173 java_ty = ma.group(1).strip()
175 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
176 fn_arg = ma.group(2).strip()
177 rust_obj = ma.group(1).strip()
183 fn_arg = ma.group(2).strip()
184 rust_obj = ma.group(1).strip()
187 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
188 fn_arg = fn_arg.replace("*", "").strip()
194 var_is_arr = var_is_arr_regex.match(fn_arg)
195 if var_is_arr is not None or ret_arr_len is not None:
196 assert(not take_by_ptr)
198 java_ty = java_ty + "[]"
199 c_ty = c_ty + "Array"
200 if var_is_arr is not None:
201 if var_is_arr.group(1) == "":
202 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
203 passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access)
204 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
205 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)
206 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,
207 is_ptr=is_ptr, var_name=fn_arg, arr_len=None, arr_access=None)
209 def map_type(fn_arg, print_void, ret_arr_len, is_free):
210 ty_info = java_c_types(fn_arg, ret_arr_len)
212 if ty_info.c_ty == "void":
214 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
215 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
217 if ty_info.c_ty.endswith("Array"):
218 arr_len = ty_info.arr_len
219 if arr_len is not None:
220 arr_name = ty_info.var_name
223 arr_len = ret_arr_len
224 assert(ty_info.c_ty == "jbyteArray")
225 if ty_info.rust_obj is not None:
226 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
227 arg_conv = arg_conv + "DO_ASSERT((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
228 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
229 arr_access = ("", "." + ty_info.arr_access)
231 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
232 arg_conv = arg_conv + "DO_ASSERT((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
233 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
234 arr_access = ("*", "")
235 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
237 arg_conv_name = arr_name + "_ref",
238 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
239 "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", " + arr_access[0],
240 arr_access[1] + ");"),
241 ret_conv_name = arr_name + "_arr")
242 elif ty_info.var_name != "":
243 # If we have a parameter name, print it (noting that it may indicate its a pointer)
244 if ty_info.rust_obj is not None:
245 assert(ty_info.passed_as_ptr)
246 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
247 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
248 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
249 if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns and not ty_info.is_ptr and not is_free:
250 # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
251 opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
252 opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
253 if not ty_info.is_ptr:
254 if ty_info.rust_obj in unitary_enums:
255 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
256 arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
257 arg_conv_name = ty_info.var_name + "_conv",
258 ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
259 ret_conv_name = ty_info.var_name + "_conv")
260 if ty_info.rust_obj in opaque_structs:
261 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"
262 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"
263 ret_conv_suf = ret_conv_suf + "long " + ty_info.var_name + "_ref;\n"
264 ret_conv_suf = ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
265 ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner | 1;\n"
266 ret_conv_suf = ret_conv_suf + "} else {\n"
267 ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)&" + ty_info.var_name + "_var;\n"
268 ret_conv_suf = ret_conv_suf + "}"
269 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
270 arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv",
271 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", ret_conv_suf),
272 ret_conv_name = ty_info.var_name + "_ref")
273 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
274 if ty_info.rust_obj in trait_structs:
276 base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
277 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
278 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
280 base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
281 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
282 arg_conv = base_conv,
283 arg_conv_name = ty_info.var_name + "_conv",
284 ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
285 if ty_info.rust_obj != "LDKu8slice":
286 # Don't bother free'ing slices passed in - Rust doesn't auto-free the
287 # underlying unlike Vecs, and it gives Java more freedom.
288 base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
289 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
290 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
291 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
294 if ty_info.rust_obj in opaque_structs:
295 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
296 arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv",
297 ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
298 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
299 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
300 arg_conv_name = ty_info.var_name + "_conv",
301 ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
303 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
304 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
305 elif ty_info.java_ty == "String":
306 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
307 arg_conv = None, arg_conv_name = None,
308 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
310 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
311 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
313 # We don't have a parameter name, and want one, just call it arg
314 if ty_info.rust_obj is not None:
315 assert(not is_free or ty_info.rust_obj not in opaque_structs);
316 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
317 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
318 arg_conv_name = "arg_conv",
319 ret_conv = None, ret_conv_name = None)
322 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
323 arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
325 # We don't have a parameter name, and don't want one (cause we're returning)
326 if ty_info.rust_obj is not None:
327 if not ty_info.is_ptr:
328 if ty_info.rust_obj in unitary_enums:
329 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
330 arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
331 arg_conv_name = "ret",
332 ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
333 if ty_info.rust_obj in opaque_structs:
334 # If we're returning a newly-allocated struct, we don't want Rust to ever
335 # free, instead relying on the Java GC to lose the ref. We undo this in
336 # any _free function.
337 # To avoid any issues, we first assert that the incoming object is non-ref.
338 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
339 ret_conv = (ty_info.rust_obj + " ret = ", ";"),
340 ret_conv_name = "((long)ret.inner) | (ret.is_owned ? 1 : 0)",
341 arg_conv = None, arg_conv_name = None)
343 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
344 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
345 ret_conv_name = "(long)ret",
346 arg_conv = None, arg_conv_name = None)
348 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
349 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
350 arg_conv = None, arg_conv_name = None)
352 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
353 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
355 def map_fn(line, re_match, ret_arr_len, c_call_string):
356 out_java.write("\t// " + line)
357 out_java.write("\tpublic static native ")
358 out_c.write("JNIEXPORT ")
360 is_free = re_match.group(2).endswith("_free")
361 struct_meth = re_match.group(2).split("_")[0]
363 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
366 if ret_info.ret_conv is not None:
367 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
369 out_java.write(" " + re_match.group(2) + "(")
370 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
374 args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs
375 for idx, arg in enumerate(re_match.group(3).split(',')):
380 arg_conv_info = map_type(arg, False, None, is_free)
381 if arg_conv_info.c_ty != "void":
382 arg_conv_info.print_ty()
383 arg_conv_info.print_name()
384 if arg_conv_info.arg_name == "this_arg":
386 if arg_conv_info.passed_as_ptr and not arg_conv_info.rust_obj in opaque_structs:
387 if not arg_conv_info.rust_obj in trait_structs and not arg_conv_info.rust_obj in unitary_enums:
388 print(re_match.group(2) + " bad - " + arg_conv_info.rust_obj)
390 arg_names.append(arg_conv_info)
392 out_java_struct = None
393 if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
394 out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
396 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
397 out_java_struct.close()
398 out_java_struct = None
400 out_java_struct.write("\tpublic ")
401 meth_n = re_match.group(2)[len(struct_meth) + 1:]
402 if ret_info.rust_obj == "LDK" + struct_meth:
403 out_java_struct.write(struct_meth + "(")
404 elif ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
405 out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " " + meth_n + "(")
407 out_java_struct.write(ret_info.java_ty + " " + meth_n + "(")
408 for idx, arg in enumerate(arg_names):
410 if not takes_self or idx > 1:
411 out_java_struct.write(", ")
412 if arg.java_ty != "void" and arg.arg_name != "this_arg":
413 if arg.passed_as_ptr:
414 if arg.rust_obj in opaque_structs or arg.rust_obj in trait_structs:
415 out_java_struct.write(arg.rust_obj.replace("LDK", "") + " " + arg.arg_name)
417 out_java_struct.write(arg.rust_obj + " " + arg.arg_name)
419 out_java_struct.write(arg.java_ty + " " + arg.arg_name)
422 out_java.write(");\n")
424 if out_java_struct is not None:
425 out_java_struct.write(") {\n")
427 for info in arg_names:
428 if info.arg_conv is not None:
429 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
431 if ret_info.ret_conv is not None:
432 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
434 out_c.write("\treturn ");
436 if c_call_string is None:
437 out_c.write(re_match.group(2) + "(")
439 out_c.write(c_call_string)
440 for idx, info in enumerate(arg_names):
441 if info.arg_conv_name is not None:
444 elif c_call_string is not None:
446 out_c.write(info.arg_conv_name)
448 if ret_info.ret_conv is not None:
449 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
450 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
453 out_c.write("\n}\n\n")
454 if out_java_struct is not None:
455 out_java_struct.write("\t\t")
456 if ret_info.rust_obj == "LDK" + struct_meth:
457 out_java_struct.write("super(")
458 elif ret_info.java_ty != "void" and not ret_info.passed_as_ptr:
459 out_java_struct.write(ret_info.java_ty + " ret = ")
460 elif ret_info.java_ty != "void":
461 out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " ret = ")
462 if ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
463 out_java_struct.write("new " + ret_info.rust_obj.replace("LDK", "") + "(null, ")
464 out_java_struct.write("bindings." + re_match.group(2) + "(")
465 for idx, info in enumerate(arg_names):
467 out_java_struct.write(", ")
468 if info.arg_name == "this_arg":
469 out_java_struct.write("this.ptr")
470 elif info.passed_as_ptr and info.rust_obj in opaque_structs:
471 out_java_struct.write(info.arg_name + ".ptr & ~1")
472 elif info.passed_as_ptr and info.rust_obj in trait_structs:
473 out_java_struct.write(info.arg_name + ".ptr")
475 out_java_struct.write(info.arg_name)
476 out_java_struct.write(")")
477 if ret_info.rust_obj == "LDK" + struct_meth:
478 out_java_struct.write(");\n")
479 elif ret_info.rust_obj in opaque_structs:
480 out_java_struct.write(");\n")
481 elif ret_info.rust_obj in trait_structs:
482 out_java_struct.write(");\n\t\tret.ptrs_to.add(this);\n")
484 out_java_struct.write(";\n")
486 for info in arg_names:
487 if info.arg_name == "this_arg":
489 elif info.passed_as_ptr and (info.rust_obj in opaque_structs or info.rust_obj in trait_structs):
490 out_java_struct.write("\t\tthis.ptrs_to.add(" + info.arg_name + ");\n")
492 if ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
493 out_java_struct.write("\t\treturn ret;\n")
494 out_java_struct.write("\t}\n\n")
495 out_java_struct.close()
497 def map_unitary_enum(struct_name, field_lines):
498 with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
499 out_java_enum.write("package org.ldk.enums;\n\n")
500 unitary_enums.add(struct_name)
501 out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
502 out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
504 for idx, struct_line in enumerate(field_lines):
506 out_java_enum.write("public enum " + struct_name + " {\n")
507 elif idx == len(field_lines) - 3:
508 assert(struct_line.endswith("_Sentinel,"))
509 elif idx == len(field_lines) - 2:
510 out_java_enum.write("\t; static native void init();\n")
511 out_java_enum.write("\tstatic { init(); }\n")
512 out_java_enum.write("}")
513 out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
514 elif idx == len(field_lines) - 1:
515 assert(struct_line == "")
517 out_java_enum.write(struct_line + "\n")
518 out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
521 out_c.write("\tabort();\n")
525 out_c.write("static jclass " + struct_name + "_class = NULL;\n")
526 for idx, struct_line in enumerate(field_lines):
527 if idx > 0 and idx < len(field_lines) - 3:
528 variant = struct_line.strip().strip(",")
529 out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
530 out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
531 out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
532 out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
533 for idx, struct_line in enumerate(field_lines):
534 if idx > 0 and idx < len(field_lines) - 3:
535 variant = struct_line.strip().strip(",")
536 out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
537 out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
539 out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
540 out_c.write("\tswitch (val) {\n")
541 for idx, struct_line in enumerate(field_lines):
542 if idx > 0 and idx < len(field_lines) - 3:
543 variant = struct_line.strip().strip(",")
544 out_c.write("\t\tcase " + variant + ":\n")
545 out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
547 out_c.write("\t\tdefault: abort();\n")
551 def map_complex_enum(struct_name, union_enum_items):
552 tag_field_lines = union_enum_items["field_lines"]
553 init_meth_jty_strs = {}
554 for idx, struct_line in enumerate(tag_field_lines):
556 out_java.write("\tpublic static class " + struct_name + " {\n")
557 out_java.write("\t\tprivate " + struct_name + "() {}\n")
558 elif idx == len(tag_field_lines) - 3:
559 assert(struct_line.endswith("_Sentinel,"))
560 elif idx == len(tag_field_lines) - 2:
561 out_java.write("\t\tstatic native void init();\n")
562 out_java.write("\t}\n")
563 elif idx == len(tag_field_lines) - 1:
564 assert(struct_line == "")
566 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
567 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
568 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
569 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
570 init_meth_jty_str = ""
571 init_meth_params = ""
573 if "LDK" + var_name in union_enum_items:
574 enum_var_lines = union_enum_items["LDK" + var_name]
575 for idx, field in enumerate(enum_var_lines):
576 if idx != 0 and idx < len(enum_var_lines) - 2:
577 field_ty = java_c_types(field.strip(' ;'), None)
578 out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
579 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
581 init_meth_params = init_meth_params + ", "
582 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
583 init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
584 out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
585 out_java.write(init_meth_body)
586 out_java.write("}\n")
587 out_java.write("\t\t}\n")
588 init_meth_jty_strs[var_name] = init_meth_jty_str
589 out_java.write("\tstatic { " + struct_name + ".init(); }\n")
590 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
592 out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
593 for idx, struct_line in enumerate(tag_field_lines):
594 if idx != 0 and idx < len(tag_field_lines) - 3:
595 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
596 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
597 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
598 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
599 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")
600 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
602 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")
603 out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
604 out_c.write("\tswitch(obj->tag) {\n")
605 for idx, struct_line in enumerate(tag_field_lines):
606 if idx != 0 and idx < len(tag_field_lines) - 3:
607 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
608 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
610 if "LDK" + var_name in union_enum_items:
611 enum_var_lines = union_enum_items["LDK" + var_name]
612 for idx, field in enumerate(enum_var_lines):
613 if idx != 0 and idx < len(enum_var_lines) - 2:
614 field_map = map_type(field.strip(' ;'), False, None, False)
615 if field_map.ret_conv is not None:
616 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
617 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
618 out_c.write(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
619 c_params_text = c_params_text + ", " + field_map.ret_conv_name
621 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
622 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
623 out_c.write("\t\t}\n")
624 out_c.write("\t\tdefault: abort();\n")
625 out_c.write("\t}\n}\n")
627 def map_trait(struct_name, field_var_lines, trait_fn_lines):
628 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
629 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
630 out_c.write("\tatomic_size_t refcnt;\n")
631 out_c.write("\tJavaVM *vm;\n")
632 out_c.write("\tjweak o;\n")
633 for var_line in field_var_lines:
634 if var_line.group(1) in trait_structs:
635 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
636 for fn_line in trait_fn_lines:
637 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
638 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
639 out_c.write("} " + struct_name + "_JCalls;\n")
641 out_java_trait.write("package org.ldk.structs;\n\n")
642 out_java_trait.write("import org.ldk.impl.bindings;\n\n")
643 out_java_trait.write("import org.ldk.enums.*;\n\n")
644 out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
645 out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
646 out_java_trait.write("\tpublic " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
647 for var_line in field_var_lines:
648 if var_line.group(1) in trait_structs:
649 out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
650 out_java_trait.write(") {\n")
651 out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
652 for var_line in field_var_lines:
653 if var_line.group(1) in trait_structs:
654 out_java_trait.write(", " + var_line.group(2))
655 out_java_trait.write("));\n")
656 out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
657 out_java_trait.write("\t}\n")
658 out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
659 out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
660 out_java_trait.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
661 out_java_trait.write("\t}\n\n")
663 out_java.write("\tpublic interface " + struct_name + " {\n")
665 for fn_line in trait_fn_lines:
666 java_meth_descr = "("
667 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
668 ret_ty_info = java_c_types(fn_line.group(1), None)
670 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
671 is_const = fn_line.group(3) is not None
672 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
674 out_c.write("const void* this_arg")
676 out_c.write("void* this_arg")
679 for idx, arg in enumerate(fn_line.group(4).split(',')):
685 arg_conv_info = map_type(arg, True, None, False)
686 out_c.write(arg.strip())
687 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
688 arg_names.append(arg_conv_info)
689 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
690 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
691 java_meths.append(java_meth_descr)
693 out_java.write(");\n")
695 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
696 out_c.write("\tJNIEnv *env;\n")
697 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
699 for arg_info in arg_names:
700 if arg_info.ret_conv is not None:
701 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
702 out_c.write(arg_info.arg_name)
703 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
705 out_c.write("\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tDO_ASSERT(obj != NULL);\n")
706 if ret_ty_info.c_ty.endswith("Array"):
707 assert(ret_ty_info.c_ty == "jbyteArray")
708 out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.group(2) + "_meth")
709 elif not ret_ty_info.passed_as_ptr:
710 out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.group(2) + "_meth")
712 out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.group(2) + "_meth");
714 for arg_info in arg_names:
715 if arg_info.ret_conv is not None:
716 out_c.write(", " + arg_info.ret_conv_name)
718 out_c.write(", " + arg_info.arg_name)
720 if ret_ty_info.c_ty.endswith("Array"):
721 out_c.write("\t" + ret_ty_info.rust_obj + " ret;\n")
722 out_c.write("\tDO_ASSERT((*env)->GetArrayLength(env, jret) == " + ret_ty_info.arr_len + ");\n")
723 out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret." + ret_ty_info.arr_access + ");\n")
724 out_c.write("\treturn ret;\n")
726 if ret_ty_info.passed_as_ptr:
727 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
728 out_c.write("\tFREE(ret);\n")
729 out_c.write("\treturn res;\n")
731 elif fn_line.group(2) == "free":
732 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
733 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
734 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
735 out_c.write("\t\tJNIEnv *env;\n")
736 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
737 out_c.write("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
738 out_c.write("\t\tFREE(j_calls);\n")
739 out_c.write("\t}\n}\n")
741 # Write out a clone function whether we need one or not, as we use them in moving to rust
742 out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
743 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
744 out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
745 for var_line in field_var_lines:
746 if var_line.group(1) in trait_structs:
747 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
748 out_c.write("\treturn (void*) this_arg;\n")
751 out_java.write("\t}\n")
753 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
754 out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
755 for var_line in field_var_lines:
756 if var_line.group(1) in trait_structs:
757 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
758 out_c.write(", jobject " + var_line.group(2))
759 out_java.write(");\n")
762 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
763 out_c.write("\tDO_ASSERT(c != NULL);\n")
764 out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
765 out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
766 out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
767 out_c.write("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
768 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
769 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
770 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
771 out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
772 out_c.write("\n\t" + struct_name + " ret = {\n")
773 out_c.write("\t\t.this_arg = (void*) calls,\n")
774 for fn_line in trait_fn_lines:
775 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
776 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
777 elif fn_line.group(2) == "free":
778 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
780 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
781 for var_line in field_var_lines:
782 if var_line.group(1) in trait_structs:
783 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
784 out_c.write("\t};\n")
785 for var_line in field_var_lines:
786 if var_line.group(1) in trait_structs:
787 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
788 out_c.write("\treturn ret;\n")
791 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
792 for var_line in field_var_lines:
793 if var_line.group(1) in trait_structs:
794 out_c.write(", jobject " + var_line.group(2))
796 out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
797 out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
798 for var_line in field_var_lines:
799 if var_line.group(1) in trait_structs:
800 out_c.write(", " + var_line.group(2))
802 out_c.write("\treturn (long)res_ptr;\n")
805 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
806 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")
807 out_c.write("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
808 out_c.write("\tDO_ASSERT(ret != NULL);\n")
809 out_c.write("\treturn ret;\n")
812 for fn_line in trait_fn_lines:
813 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
814 is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
815 if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
816 dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_call_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
817 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(2) + ")(this_arg_conv->this_arg")
819 out_c.write("""#include \"org_ldk_impl_bindings.h\"
820 #include <rust_types.h>
821 #include <lightning.h>
823 #include <stdatomic.h>
826 if sys.argv[4] == "false":
827 out_c.write("#define MALLOC(a, _) malloc(a)\n")
828 out_c.write("#define FREE free\n")
829 out_c.write("#define DO_ASSERT(a) (void)(a)\n")
831 out_c.write("""#include <assert.h>
832 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
834 // Running a leak check across all the allocations and frees of the JDK is a mess,
835 // so instead we implement our own naive leak checker here, relying on the -wrap
836 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
837 // and free'd in Rust or C across the generated bindings shared library.
839 #include <execinfo.h>
841 static mtx_t allocation_mtx;
843 void __attribute__((constructor)) init_mtx() {
844 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
848 typedef struct allocation {
849 struct allocation* next;
851 const char* struct_name;
855 static allocation* allocation_ll = NULL;
857 void* __real_malloc(size_t len);
858 void* __real_calloc(size_t nmemb, size_t len);
859 static void new_allocation(void* res, const char* struct_name) {
860 allocation* new_alloc = __real_malloc(sizeof(allocation));
861 new_alloc->ptr = res;
862 new_alloc->struct_name = struct_name;
863 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
864 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
865 new_alloc->next = allocation_ll;
866 allocation_ll = new_alloc;
867 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
869 static void* MALLOC(size_t len, const char* struct_name) {
870 void* res = __real_malloc(len);
871 new_allocation(res, struct_name);
874 void __real_free(void* ptr);
875 static void alloc_freed(void* ptr) {
876 allocation* p = NULL;
877 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
878 allocation* it = allocation_ll;
879 while (it->ptr != ptr) { p = it; it = it->next; }
880 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
881 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
882 DO_ASSERT(it->ptr == ptr);
885 static void FREE(void* ptr) {
890 void* __wrap_malloc(size_t len) {
891 void* res = __real_malloc(len);
892 new_allocation(res, "malloc call");
895 void* __wrap_calloc(size_t nmemb, size_t len) {
896 void* res = __real_calloc(nmemb, len);
897 new_allocation(res, "calloc call");
900 void __wrap_free(void* ptr) {
905 void* __real_realloc(void* ptr, size_t newlen);
906 void* __wrap_realloc(void* ptr, size_t len) {
908 void* res = __real_realloc(ptr, len);
909 new_allocation(res, "realloc call");
912 void __wrap_reallocarray(void* ptr, size_t new_sz) {
913 // Rust doesn't seem to use reallocarray currently
917 void __attribute__((destructor)) check_leaks() {
918 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
919 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
920 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
921 fprintf(stderr, "\\n\\n");
923 DO_ASSERT(allocation_ll == NULL);
926 out_java.write("""package org.ldk.impl;
927 import org.ldk.enums.*;
929 public class bindings {
930 public static class VecOrSliceDef {
934 public VecOrSliceDef(long dataptr, long datalen, long stride) {
935 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
939 System.loadLibrary(\"lightningjni\");
940 init(java.lang.Enum.class, VecOrSliceDef.class);
942 static native void init(java.lang.Class c, java.lang.Class slicedef);
944 public static native boolean deref_bool(long ptr);
945 public static native long deref_long(long ptr);
946 public static native void free_heap_ptr(long ptr);
947 public static native byte[] read_bytes(long ptr, long len);
948 public static native byte[] get_u8_slice_bytes(long slice_ptr);
949 public static native long bytes_to_u8_vec(byte[] bytes);
950 public static native long new_txpointer_copy_data(byte[] txdata);
951 public static native long vec_slice_len(long vec);
952 public static native long new_empty_slice_vec();
956 static jmethodID ordinal_meth = NULL;
957 static jmethodID slicedef_meth = NULL;
958 static jclass slicedef_cls = NULL;
959 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
960 ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
961 DO_ASSERT(ordinal_meth != NULL);
962 slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
963 DO_ASSERT(slicedef_meth != NULL);
964 slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
965 DO_ASSERT(slicedef_cls != NULL);
968 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
969 return *((bool*)ptr);
971 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
972 return *((long*)ptr);
974 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
977 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
978 jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
979 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
982 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
983 LDKu8slice *slice = (LDKu8slice*)slice_ptr;
984 jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
985 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
988 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
989 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
990 vec->datalen = (*_env)->GetArrayLength(_env, bytes);
991 vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
992 (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
995 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
996 LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
997 txdata->datalen = (*env)->GetArrayLength(env, bytes);
998 txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
999 txdata->data_is_owned = true;
1000 (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1001 return (long)txdata;
1003 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1004 // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1005 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1006 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1007 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1008 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1009 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1010 return (long)vec->datalen;
1012 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1013 // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1014 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1015 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1016 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1017 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1018 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1024 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1025 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1026 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1027 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1031 with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1032 out_java_struct.write("""package org.ldk.structs;
1033 import java.util.LinkedList;
1036 LinkedList<Object> ptrs_to = new LinkedList();
1037 protected CommonBase(long ptr) { this.ptr = ptr; }
1038 public long _test_only_get_ptr() { return this.ptr; }
1042 in_block_comment = False
1043 cur_block_obj = None
1045 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1047 line_indicates_result_regex = re.compile("^ (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1048 line_indicates_vec_regex = re.compile("^ ([A-Za-z_0-9]*) \*data;$")
1049 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
1050 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1051 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1052 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1053 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
1054 line_field_var_regex = re.compile("^ ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1055 assert(line_field_var_regex.match(" LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1056 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1057 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1058 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1059 struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1060 assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1062 result_templ_structs = set()
1063 union_enum_items = {}
1064 result_ptr_struct_items = {}
1066 if in_block_comment:
1067 if line.endswith("*/\n"):
1068 in_block_comment = False
1069 elif cur_block_obj is not None:
1070 cur_block_obj = cur_block_obj + line
1071 if line.startswith("} "):
1075 obj_lines = cur_block_obj.split("\n")
1077 result_contents = None
1078 is_unitary_enum = False
1079 is_union_enum = False
1083 field_var_lines = []
1085 for idx, struct_line in enumerate(obj_lines):
1086 if struct_line.strip().startswith("/*"):
1087 in_block_comment = True
1088 if in_block_comment:
1089 if struct_line.endswith("*/"):
1090 in_block_comment = False
1092 struct_name_match = struct_name_regex.match(struct_line)
1093 if struct_name_match is not None:
1094 struct_name = struct_name_match.group(3)
1095 if struct_name_match.group(1) == "enum":
1096 if not struct_name.endswith("_Tag"):
1097 is_unitary_enum = True
1099 is_union_enum = True
1100 elif struct_name_match.group(1) == "union":
1102 if line_indicates_opaque_regex.match(struct_line):
1104 result_match = line_indicates_result_regex.match(struct_line)
1105 if result_match is not None:
1106 result_contents = result_match.group(1)
1107 vec_ty_match = line_indicates_vec_regex.match(struct_line)
1108 if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1109 vec_ty = vec_ty_match.group(1)
1110 elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1112 trait_fn_match = line_indicates_trait_regex.match(struct_line)
1113 if trait_fn_match is not None:
1114 trait_fn_lines.append(trait_fn_match)
1115 field_var_match = line_field_var_regex.match(struct_line)
1116 if field_var_match is not None:
1117 field_var_lines.append(field_var_match)
1118 field_lines.append(struct_line)
1120 assert(struct_name is not None)
1121 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))
1122 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))
1123 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))
1124 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))
1125 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))
1126 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))
1127 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))
1130 opaque_structs.add(struct_name)
1131 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1132 out_java_struct.write("package org.ldk.structs;\n\n")
1133 out_java_struct.write("import org.ldk.impl.bindings;\n")
1134 out_java_struct.write("import org.ldk.enums.*;\n\n")
1135 out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1136 out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1137 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1138 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1139 out_java_struct.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
1140 out_java_struct.write("\t}\n\n")
1141 elif result_contents is not None:
1142 result_templ_structs.add(struct_name)
1143 assert result_contents in result_ptr_struct_items
1144 elif struct_name.startswith("LDKCResultPtr_"):
1145 for line in field_lines:
1146 if line.endswith("*result;"):
1147 res_ty = line[:-8].strip()
1148 elif line.endswith("*err;"):
1149 err_ty = line[:-5].strip()
1150 result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1152 out_java.write("\tpublic static native long " + struct_name + "_new(")
1153 out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1154 for idx, line in enumerate(field_lines):
1155 if idx != 0 and idx < len(field_lines) - 2:
1156 ty_info = java_c_types(line.strip(';'), None)
1158 out_java.write(", ")
1159 e = chr(ord('a') + idx - 1)
1160 out_java.write(ty_info.java_ty + " " + e)
1161 out_c.write(", " + ty_info.c_ty + " " + e)
1162 out_java.write(");\n")
1163 out_c.write(") {\n")
1164 out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1165 for idx, line in enumerate(field_lines):
1166 if idx != 0 and idx < len(field_lines) - 2:
1167 ty_info = map_type(line.strip(';'), False, None, False)
1168 e = chr(ord('a') + idx - 1)
1169 if ty_info.arg_conv is not None:
1170 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1171 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1173 out_c.write("\tret->" + e + " = " + e + ";\n")
1174 out_c.write("\treturn (long)ret;\n")
1176 elif vec_ty is not None:
1177 if vec_ty in opaque_structs:
1178 out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1179 out_c.write("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1181 out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1182 out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1183 out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1184 if vec_ty in opaque_structs:
1185 out_c.write("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1186 out_c.write("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1187 out_c.write("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1188 out_c.write("\t\tDO_ASSERT((((long)vec->data[i].inner) & 1) == 0);\n")
1189 out_c.write("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1190 out_c.write("\t}\n")
1191 out_c.write("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1192 out_c.write("\treturn ret;\n")
1194 out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1197 ty_info = map_type(vec_ty + " arr_elem", False, None, False)
1198 if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1199 out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1200 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")
1201 out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1202 out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1203 out_c.write("\tif (ret->datalen == 0) {\n")
1204 out_c.write("\t\tret->data = NULL;\n")
1205 out_c.write("\t} else {\n")
1206 out_c.write("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1207 out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1208 out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1209 if ty_info.arg_conv is not None:
1210 out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1211 out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1212 out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1214 out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
1215 out_c.write("\t\t}\n")
1216 out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1217 out_c.write("\t}\n")
1218 out_c.write("\treturn (long)ret;\n")
1221 assert(struct_name.endswith("_Tag"))
1222 struct_name = struct_name[:-4]
1223 union_enum_items[struct_name] = {"field_lines": field_lines}
1224 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1225 enum_var_name = struct_name.split("_")
1226 union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1227 elif struct_name in union_enum_items:
1228 map_complex_enum(struct_name, union_enum_items[struct_name])
1229 elif is_unitary_enum:
1230 map_unitary_enum(struct_name, field_lines)
1231 elif len(trait_fn_lines) > 0:
1232 trait_structs.add(struct_name)
1233 map_trait(struct_name, field_var_lines, trait_fn_lines)
1234 cur_block_obj = None
1236 fn_ptr = fn_ptr_regex.match(line)
1237 fn_ret_arr = fn_ret_arr_regex.match(line)
1238 reg_fn = reg_fn_regex.match(line)
1239 const_val = const_val_regex.match(line)
1241 if line.startswith("#include <"):
1243 elif line.startswith("/*"):
1244 #out_java.write("\t" + line)
1245 if not line.endswith("*/\n"):
1246 in_block_comment = True
1247 elif line.startswith("typedef enum "):
1248 cur_block_obj = line
1249 elif line.startswith("typedef struct "):
1250 cur_block_obj = line
1251 elif line.startswith("typedef union "):
1252 cur_block_obj = line
1253 elif line.startswith("typedef "):
1254 alias_match = struct_alias_regex.match(line)
1255 if alias_match.group(1) in result_templ_structs:
1256 out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1257 out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
1258 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")
1259 out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1261 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")
1262 contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1263 res_ty, err_ty = result_ptr_struct_items[contents_ty]
1264 out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1265 out_c.write("\tif (val->result_ok) {\n")
1266 if res_ty not in opaque_structs:
1267 out_c.write("\t\treturn (long)val->contents.result;\n")
1269 out_c.write("\t\treturn (long)(val->contents.result->inner) | (val->contents.result->is_owned ? 1 : 0);\n")
1270 out_c.write("\t} else {\n")
1271 if err_ty not in opaque_structs:
1272 out_c.write("\t\treturn (long)val->contents.err;\n")
1274 out_c.write("\t\treturn (long)(val->contents.err->inner) | (val->contents.err->is_owned ? 1 : 0);\n")
1275 out_c.write("\t}\n}\n")
1277 elif fn_ptr is not None:
1278 map_fn(line, fn_ptr, None, None)
1279 elif fn_ret_arr is not None:
1280 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1281 elif reg_fn is not None:
1282 map_fn(line, reg_fn, None, None)
1283 elif const_val_regex is not None:
1284 # TODO Map const variables
1287 assert(line == "\n")
1289 out_java.write("}\n")
1290 for struct_name in opaque_structs:
1291 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1292 out_java_struct.write("}\n")
1293 for struct_name in trait_structs:
1294 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1295 out_java_struct.write("}\n")