5 print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /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):
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
21 def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
22 assert(ty_info.c_ty is not None)
23 assert(ty_info.java_ty is not None)
24 assert(arg_name is not None)
25 self.c_ty = ty_info.c_ty
26 self.java_ty = ty_info.java_ty
27 self.java_fn_ty_arg = ty_info.java_fn_ty_arg
28 self.arg_name = arg_name
29 self.arg_conv = arg_conv
30 self.arg_conv_name = arg_conv_name
31 self.ret_conv = ret_conv
32 self.ret_conv_name = ret_conv_name
35 out_c.write(self.c_ty)
36 out_java.write(self.java_ty)
39 if self.arg_name != "":
40 out_java.write(" " + self.arg_name)
41 out_c.write(" " + self.arg_name)
43 out_java.write(" arg")
46 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[3], "w") as out_c:
47 opaque_structs = set()
51 var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
52 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
53 def java_c_types(fn_arg, ret_arr_len):
54 fn_arg = fn_arg.strip()
55 if fn_arg.startswith("MUST_USE_RES "):
58 if fn_arg.startswith("const "):
65 if fn_arg.startswith("void"):
69 fn_arg = fn_arg[4:].strip()
70 elif fn_arg.startswith("bool"):
74 fn_arg = fn_arg[4:].strip()
75 elif fn_arg.startswith("uint8_t"):
79 fn_arg = fn_arg[7:].strip()
80 elif fn_arg.startswith("uint16_t"):
84 fn_arg = fn_arg[8:].strip()
85 elif fn_arg.startswith("uint32_t"):
89 fn_arg = fn_arg[8:].strip()
90 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
94 if fn_arg.startswith("uint64_t"):
95 fn_arg = fn_arg[8:].strip()
97 fn_arg = fn_arg[9:].strip()
98 elif is_const and fn_arg.startswith("char *"):
101 fn_ty_arg = "Ljava/lang/String;"
102 fn_arg = fn_arg[6:].strip()
104 ma = var_ty_regex.match(fn_arg)
105 if ma.group(1).strip() in unitary_enums:
106 java_ty = ma.group(1).strip()
108 fn_ty_arg = "Lorg/ldk/impl/bindings$" + ma.group(1).strip() + ";"
109 fn_arg = ma.group(2).strip()
110 rust_obj = ma.group(1).strip()
116 fn_arg = ma.group(2).strip()
117 rust_obj = ma.group(1).strip()
120 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
121 fn_arg = fn_arg.replace("*", "").strip()
127 var_is_arr = var_is_arr_regex.match(fn_arg)
128 if var_is_arr is not None or ret_arr_len is not None:
129 assert(not take_by_ptr)
131 java_ty = java_ty + "[]"
132 c_ty = c_ty + "Array"
133 if var_is_arr is not None:
134 return TypeInfo(rust_obj=None, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
135 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
136 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,
137 is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
139 def map_type(fn_arg, print_void, ret_arr_len, is_free):
140 ty_info = java_c_types(fn_arg, ret_arr_len)
142 if ty_info.c_ty == "void":
144 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
145 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
147 if ty_info.c_ty.endswith("Array"):
148 arr_len = ty_info.arr_len
149 if arr_len is not None:
150 arr_name = ty_info.var_name
153 arr_len = ret_arr_len
154 assert(ty_info.c_ty == "jbyteArray")
155 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
156 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
157 "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
158 "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
159 arg_conv_name = arr_name + "_ref",
160 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
161 "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
163 ret_conv_name = arr_name + "_arr")
164 elif ty_info.var_name != "":
165 # If we have a parameter name, print it (noting that it may indicate its a pointer)
166 if ty_info.rust_obj is not None:
167 assert(ty_info.passed_as_ptr)
168 if not ty_info.is_ptr:
169 if ty_info.rust_obj in unitary_enums:
170 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
171 arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
172 arg_conv_name = ty_info.var_name + "_conv",
173 ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
174 ret_conv_name = ty_info.var_name + "_conv")
175 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
176 if ty_info.rust_obj in trait_structs:
178 base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
179 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
180 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
182 base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
183 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
184 arg_conv = base_conv,
185 arg_conv_name = ty_info.var_name + "_conv",
186 ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
187 if ty_info.rust_obj != "LDKu8slice":
188 # Don't bother free'ing slices passed in - we often pass them Rust -> Rust
189 base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
190 if ty_info.rust_obj in opaque_structs:
191 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
192 arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
193 arg_conv_name = ty_info.var_name + "_conv",
194 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
196 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
197 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
198 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
201 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
202 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
203 arg_conv_name = ty_info.var_name + "_conv",
204 ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
206 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
207 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
208 elif ty_info.java_ty == "String":
209 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
210 arg_conv = None, arg_conv_name = None,
211 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
213 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
214 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
216 # We don't have a parameter name, and want one, just call it arg
217 if ty_info.rust_obj is not None:
218 assert(not is_free or ty_info.rust_obj not in opaque_structs);
219 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
220 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
221 arg_conv_name = "arg_conv",
222 ret_conv = None, ret_conv_name = None)
225 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
226 arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
228 # We don't have a parameter name, and don't want one (cause we're returning)
229 if ty_info.rust_obj is not None:
230 if not ty_info.is_ptr:
231 if ty_info.rust_obj in unitary_enums:
232 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
233 arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
234 arg_conv_name = "ret",
235 ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
236 if ty_info.rust_obj in opaque_structs:
237 # If we're returning a newly-allocated struct, we don't want Rust to ever
238 # free, instead relying on the Java GC to lose the ref. We undo this in
239 # any _free function.
240 # To avoid any issues, we first assert that the incoming object is non-ref.
241 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
242 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nDO_ASSERT(ret->is_owned);\nret->is_owned = false;"),
243 ret_conv_name = "(long)ret",
244 arg_conv = None, arg_conv_name = None)
246 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
247 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
248 ret_conv_name = "(long)ret",
249 arg_conv = None, arg_conv_name = None)
251 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
252 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
253 arg_conv = None, arg_conv_name = None)
255 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
256 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
258 def map_fn(line, re_match, ret_arr_len, c_call_string):
259 out_java.write("\t// " + line)
260 out_java.write("\tpublic static native ")
261 out_c.write("JNIEXPORT ")
263 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
265 if ret_info.ret_conv is not None:
266 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
268 out_java.write(" " + re_match.group(2) + "(")
269 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
272 for idx, arg in enumerate(re_match.group(3).split(',')):
277 arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
278 if arg_conv_info.c_ty != "void":
279 arg_conv_info.print_ty()
280 arg_conv_info.print_name()
281 arg_names.append(arg_conv_info)
283 out_java.write(");\n")
286 for info in arg_names:
287 if info.arg_conv is not None:
288 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
290 if ret_info.ret_conv is not None:
291 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
293 out_c.write("\treturn ");
295 if c_call_string is None:
296 out_c.write(re_match.group(2) + "(")
298 out_c.write(c_call_string)
299 for idx, info in enumerate(arg_names):
300 if info.arg_conv_name is not None:
303 elif c_call_string is not None:
305 out_c.write(info.arg_conv_name)
307 if ret_info.ret_conv is not None:
308 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
309 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
312 out_c.write("\n}\n\n")
314 def map_trait(struct_name, field_var_lines, trait_fn_lines):
315 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
316 out_c.write("\tatomic_size_t refcnt;\n")
317 out_c.write("\tJavaVM *vm;\n")
318 out_c.write("\tjobject o;\n")
319 for var_line in field_var_lines:
320 if var_line.group(1) in trait_structs:
321 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
322 for fn_line in trait_fn_lines:
323 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
324 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
325 out_c.write("} " + struct_name + "_JCalls;\n")
327 out_java.write("\tpublic interface " + struct_name + " {\n")
329 for fn_line in trait_fn_lines:
330 java_meth_descr = "("
331 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
332 ret_ty_info = java_c_types(fn_line.group(1), None)
334 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
335 is_const = fn_line.group(3) is not None
336 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
338 out_c.write("const void* this_arg")
340 out_c.write("void* this_arg")
343 for idx, arg in enumerate(fn_line.group(4).split(',')):
349 arg_conv_info = map_type(arg, True, None, False)
350 out_c.write(arg.strip())
351 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
352 arg_names.append(arg_conv_info)
353 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
354 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
355 java_meths.append(java_meth_descr)
357 out_java.write(");\n")
359 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
360 out_c.write("\tJNIEnv *env;\n")
361 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
363 for arg_info in arg_names:
364 if arg_info.ret_conv is not None:
365 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
366 out_c.write(arg_info.arg_name)
367 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
369 if not ret_ty_info.passed_as_ptr:
370 out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
372 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");
374 for arg_info in arg_names:
375 if arg_info.ret_conv is not None:
376 out_c.write(", " + arg_info.ret_conv_name)
378 out_c.write(", " + arg_info.arg_name)
381 if ret_ty_info.passed_as_ptr:
382 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
383 out_c.write("\tFREE(ret);\n")
384 out_c.write("\treturn res;\n")
386 elif fn_line.group(2) == "free":
387 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
388 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
389 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
390 out_c.write("\t\tJNIEnv *env;\n")
391 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
392 out_c.write("\t\t(*env)->DeleteGlobalRef(env, j_calls->o);\n")
393 out_c.write("\t\tFREE(j_calls);\n")
394 out_c.write("\t}\n}\n")
396 # Write out a clone function whether we need one or not, as we use them in moving to rust
397 out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
398 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
399 out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
400 for var_line in field_var_lines:
401 if var_line.group(1) in trait_structs:
402 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
403 out_c.write("\treturn (void*) this_arg;\n")
406 out_java.write("\t}\n")
408 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
409 out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
410 for var_line in field_var_lines:
411 if var_line.group(1) in trait_structs:
412 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
413 out_c.write(", jobject " + var_line.group(2))
414 out_java.write(");\n")
417 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
418 out_c.write("\tDO_ASSERT(c != NULL);\n")
419 out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
420 out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
421 out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
422 out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
423 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
424 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
425 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
426 out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
427 out_c.write("\n\t" + struct_name + " ret = {\n")
428 out_c.write("\t\t.this_arg = (void*) calls,\n")
429 for fn_line in trait_fn_lines:
430 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
431 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
432 elif fn_line.group(2) == "free":
433 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
435 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
436 for var_line in field_var_lines:
437 if var_line.group(1) in trait_structs:
438 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
439 out_c.write("\t};\n")
440 for var_line in field_var_lines:
441 if var_line.group(1) in trait_structs:
442 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
443 out_c.write("\treturn ret;\n")
446 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
447 for var_line in field_var_lines:
448 if var_line.group(1) in trait_structs:
449 out_c.write(", jobject " + var_line.group(2))
451 out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
452 out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
453 for var_line in field_var_lines:
454 if var_line.group(1) in trait_structs:
455 out_c.write(", " + var_line.group(2))
457 out_c.write("\treturn (long)res_ptr;\n")
460 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
461 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")
462 out_c.write("\treturn ((" + struct_name + "_JCalls*)val)->o;\n")
465 for fn_line in trait_fn_lines:
466 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
467 is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
468 if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
469 dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
470 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")
472 out_java.write("""package org.ldk.impl;
474 public class bindings {
476 System.loadLibrary(\"lightningjni\");
477 init(java.lang.Enum.class);
480 out_c.write("""#include \"org_ldk_impl_bindings.h\"
481 #include <rust_types.h>
482 #include <lightning.h>
484 #include <stdatomic.h>
487 if sys.argv[4] == "false":
488 out_c.write("#define MALLOC(a, _) malloc(a)\n")
489 out_c.write("#define FREE free\n")
490 out_c.write("#define DO_ASSERT(a) (void)(a)\n")
492 out_c.write("""#include <assert.h>
493 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
496 static mtx_t allocation_mtx;
498 void __attribute__((constructor)) init_mtx() {
499 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
502 typedef struct allocation {
503 struct allocation* next;
505 const char* struct_name;
507 static allocation* allocation_ll = NULL;
509 void* MALLOC(size_t len, const char* struct_name) {
510 void* res = malloc(len);
511 allocation* new_alloc = malloc(sizeof(allocation));
512 new_alloc->ptr = res;
513 new_alloc->struct_name = struct_name;
514 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
515 new_alloc->next = allocation_ll;
516 allocation_ll = new_alloc;
517 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
521 void FREE(void* ptr) {
522 allocation* p = NULL;
523 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
524 allocation* it = allocation_ll;
525 while (it->ptr != ptr) { p = it; it = it->next; }
526 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
527 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
528 DO_ASSERT(it->ptr == ptr);
533 void __attribute__((destructor)) check_leaks() {
534 for (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr); }
535 DO_ASSERT(allocation_ll == NULL);
540 static native void init(java.lang.Class c);
542 public static native boolean deref_bool(long ptr);
543 public static native long deref_long(long ptr);
544 public static native void free_heap_ptr(long ptr);
545 public static native byte[] get_u8_slice_bytes(long slice_ptr);
546 public static native long bytes_to_u8_vec(byte[] bytes);
547 public static native long u8_vec_len(long vec);
551 jmethodID ordinal_meth = NULL;
552 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class) {
553 ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
554 DO_ASSERT(ordinal_meth != NULL);
557 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
558 return *((bool*)ptr);
560 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
561 return *((long*)ptr);
563 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
566 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
567 LDKu8slice *slice = (LDKu8slice*)slice_ptr;
568 jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
569 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
572 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
573 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
574 vec->datalen = (*_env)->GetArrayLength(_env, bytes);
575 vec->data = (uint8_t*)malloc(vec->datalen); // May be freed by rust, so don't track allocation
576 (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
579 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_u8_1vec_1len (JNIEnv * env, jclass _a, jlong ptr) {
580 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
581 return (long)vec->datalen;
584 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
585 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
586 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
587 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
591 # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
592 out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
593 out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
594 out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
595 out_c.write("\treturn (long)key;\n") # TODO: rm me
596 out_c.write("}\n") # TODO: rm me
598 in_block_comment = False
601 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
602 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
603 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
604 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
606 line_indicates_result_regex = re.compile("^ bool result_ok;$")
607 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
608 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
609 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
610 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
611 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
612 line_field_var_regex = re.compile("^ ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
613 assert(line_field_var_regex.match(" LDKMessageSendEventsProvider MessageSendEventsProvider;"))
614 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
615 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
616 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
617 struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
618 assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
620 result_templ_structs = set()
623 #out_java.write("\t" + line)
624 if line.endswith("*/\n"):
625 in_block_comment = False
626 elif cur_block_obj is not None:
627 cur_block_obj = cur_block_obj + line
628 if line.startswith("} "):
631 obj_lines = cur_block_obj.split("\n")
634 is_unitary_enum = False
635 is_union_enum = False
640 for idx, struct_line in enumerate(obj_lines):
641 if struct_line.strip().startswith("/*"):
642 in_block_comment = True
644 if struct_line.endswith("*/"):
645 in_block_comment = False
647 struct_name_match = struct_name_regex.match(struct_line)
648 if struct_name_match is not None:
649 struct_name = struct_name_match.group(3)
650 if struct_name_match.group(1) == "enum":
651 if not struct_name.endswith("_Tag"):
652 is_unitary_enum = True
655 elif struct_name_match.group(1) == "union":
657 if line_indicates_opaque_regex.match(struct_line):
659 elif line_indicates_result_regex.match(struct_line):
661 trait_fn_match = line_indicates_trait_regex.match(struct_line)
662 if trait_fn_match is not None:
663 trait_fn_lines.append(trait_fn_match)
664 field_var_match = line_field_var_regex.match(struct_line)
665 if field_var_match is not None:
666 field_var_lines.append(field_var_match)
667 field_lines.append(struct_line)
669 assert(struct_name is not None)
670 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union))
671 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union))
672 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union))
673 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union))
674 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque))
676 opaque_structs.add(struct_name)
678 result_templ_structs.add(struct_name)
679 elif is_unitary_enum:
680 unitary_enums.add(struct_name)
681 out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
682 out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
684 for idx, struct_line in enumerate(field_lines):
686 out_java.write("\tpublic enum " + struct_name + " {\n")
687 elif idx == len(field_lines) - 3:
688 assert(struct_line.endswith("_Sentinel,"))
689 elif idx == len(field_lines) - 2:
690 out_java.write("\t}\n")
691 elif idx == len(field_lines) - 1:
692 assert(struct_line == "")
694 out_java.write("\t" + struct_line + "\n")
695 out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
698 out_c.write("\tabort();\n")
702 out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
703 out_c.write("\t// TODO: This is pretty inefficient, we really need to cache the field IDs and class\n")
704 out_c.write("\tjclass enum_class = (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + ";\");\n")
705 out_c.write("\tDO_ASSERT(enum_class != NULL);\n")
706 out_c.write("\tswitch (val) {\n")
707 for idx, struct_line in enumerate(field_lines):
708 if idx > 0 and idx < len(field_lines) - 3:
709 variant = struct_line.strip().strip(",")
710 out_c.write("\t\tcase " + variant + ": {\n")
711 out_c.write("\t\t\tjfieldID field = (*env)->GetStaticFieldID(env, enum_class, \"" + variant + "\", \"Lorg/ldk/impl/bindings$" + struct_name + ";\");\n")
712 out_c.write("\t\t\tDO_ASSERT(field != NULL);\n")
713 out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, enum_class, field);\n")
714 out_c.write("\t\t}\n")
716 out_c.write("\t\tdefault: abort();\n")
719 elif len(trait_fn_lines) > 0:
720 trait_structs.add(struct_name)
721 map_trait(struct_name, field_var_lines, trait_fn_lines)
724 fn_ptr = fn_ptr_regex.match(line)
725 fn_ret_arr = fn_ret_arr_regex.match(line)
726 reg_fn = reg_fn_regex.match(line)
727 const_val = const_val_regex.match(line)
729 if line.startswith("#include <"):
731 elif line.startswith("/*"):
732 #out_java.write("\t" + line)
733 if not line.endswith("*/\n"):
734 in_block_comment = True
735 elif line.startswith("typedef enum "):
737 elif line.startswith("typedef struct "):
739 elif line.startswith("typedef union "):
741 elif line.startswith("typedef "):
742 alias_match = struct_alias_regex.match(line)
743 if alias_match.group(1) in result_templ_structs:
744 out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
745 out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
746 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")
747 out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
749 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")
750 out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
751 out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
752 out_c.write("\t} else {\n")
753 out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
754 out_c.write("\t}\n}\n")
756 elif fn_ptr is not None:
757 map_fn(line, fn_ptr, None, None)
758 elif fn_ret_arr is not None:
759 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
760 elif reg_fn is not None:
761 map_fn(line, reg_fn, None, None)
762 elif const_val_regex is not None:
763 # TODO Map const variables
768 out_java.write("}\n")