[double-free, with XXX] More conv for traits
[ldk-java] / typescript_strings.py
1 class Consts:
2     def __init__(self, DEBUG):
3         self.common_base = """
4             export default class CommonBase {
5                 ptr: number;
6                 ptrs_to: object[] = new Array(); // new LinkedList(); TODO: build linked list implementation
7                 protected constructor(ptr: number) { this.ptr = ptr; }
8                 public _test_only_get_ptr(): number { return this.ptr; }
9             }
10         """
11
12         self.c_file_pfx = """#include <rust_types.h>
13 #include <stdatomic.h>
14 #include <lightning.h>
15
16 // These should be provided...somehow...
17 void *memset(void *s, int c, size_t n);
18 void *memcpy(void *dest, const void *src, size_t n);
19 int memcmp(const void *s1, const void *s2, size_t n);
20
21 void __attribute__((noreturn)) abort(void);
22 void assert(scalar expression);
23 """
24
25         if not DEBUG:
26             self.c_file_pfx = self.c_file_pfx + """
27 void *malloc(size_t size);
28 void free(void *ptr);
29
30 #define MALLOC(a, _) malloc(a)
31 #define FREE(p) if ((long)(p) > 1024) { free(p); }
32 #define DO_ASSERT(a) (void)(a)
33 #define CHECK(a)
34 """
35         else:
36             self.c_file_pfx = self.c_file_pfx + """
37 // Always run a, then assert it is true:
38 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
39 // Assert a is true or do nothing
40 #define CHECK(a) DO_ASSERT(a)
41
42 // Running a leak check across all the allocations and frees of the JDK is a mess,
43 // so instead we implement our own naive leak checker here, relying on the -wrap
44 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
45 // and free'd in Rust or C across the generated bindings shared library.
46
47 #define BT_MAX 128
48 typedef struct allocation {
49         struct allocation* next;
50         void* ptr;
51         const char* struct_name;
52 } allocation;
53 static allocation* allocation_ll = NULL;
54
55 void* __real_malloc(size_t len);
56 void* __real_calloc(size_t nmemb, size_t len);
57 static void new_allocation(void* res, const char* struct_name) {
58         allocation* new_alloc = __real_malloc(sizeof(allocation));
59         new_alloc->ptr = res;
60         new_alloc->struct_name = struct_name;
61         new_alloc->next = allocation_ll;
62         allocation_ll = new_alloc;
63 }
64 static void* MALLOC(size_t len, const char* struct_name) {
65         void* res = __real_malloc(len);
66         new_allocation(res, struct_name);
67         return res;
68 }
69 void __real_free(void* ptr);
70 static void alloc_freed(void* ptr) {
71         allocation* p = NULL;
72         allocation* it = allocation_ll;
73         while (it->ptr != ptr) {
74                 p = it; it = it->next;
75                 if (it == NULL) {
76                         //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
77                         return; // addrsan should catch malloc-unknown and print more info than we have
78                 }
79         }
80         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
81         DO_ASSERT(it->ptr == ptr);
82         __real_free(it);
83 }
84 static void FREE(void* ptr) {
85         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
86         alloc_freed(ptr);
87         __real_free(ptr);
88 }
89
90 void* __wrap_malloc(size_t len) {
91         void* res = __real_malloc(len);
92         new_allocation(res, "malloc call");
93         return res;
94 }
95 void* __wrap_calloc(size_t nmemb, size_t len) {
96         void* res = __real_calloc(nmemb, len);
97         new_allocation(res, "calloc call");
98         return res;
99 }
100 void __wrap_free(void* ptr) {
101         if (ptr == NULL) return;
102         alloc_freed(ptr);
103         __real_free(ptr);
104 }
105
106 void* __real_realloc(void* ptr, size_t newlen);
107 void* __wrap_realloc(void* ptr, size_t len) {
108         if (ptr != NULL) alloc_freed(ptr);
109         void* res = __real_realloc(ptr, len);
110         new_allocation(res, "realloc call");
111         return res;
112 }
113 void __wrap_reallocarray(void* ptr, size_t new_sz) {
114         // Rust doesn't seem to use reallocarray currently
115         DO_ASSERT(false);
116 }
117
118 void __attribute__((destructor)) check_leaks() {
119         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
120                 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
121         }
122         DO_ASSERT(allocation_ll == NULL);
123 }
124 """
125         self.c_file_pfx = self.c_file_pfx + """
126 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
127 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
128 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
129 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
130
131 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
132
133 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
134 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
135 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
136
137 typedef bool jboolean;
138
139 """
140
141         self.hu_struct_file_prefix = f"""
142 import CommonBase from './CommonBase';
143 import * as bindings from '../bindings' // TODO: figure out location
144
145 """
146         self.c_fn_ty_pfx = ""
147         self.c_fn_name_pfx = ""
148         self.c_fn_args_pfx = "void* ctx_TODO"
149         self.file_ext = ".ts"
150         self.ptr_c_ty = "uint32_t"
151         self.ptr_native_ty = "uint32_t"
152         self.result_c_ty = "uint32_t"
153         self.ptr_arr = "uint32_tArray"
154         self.get_native_arr_len_call = ("", ".len")
155         self.get_native_arr_ptr_call = ("", ".ptr")
156
157     def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
158         return None
159     def create_native_arr_call(self, arr_len, ty_info):
160         if ty_info.c_ty == "int8_tArray":
161             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
162         elif ty_info.c_ty == "int64_tArray":
163             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
164         elif ty_info.c_ty == "uint32_tArray":
165             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
166         else:
167             print("Need to create arr!", ty_info.c_ty)
168             return ty_info.c_ty
169     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
170         if ty_info.c_ty == "int8_tArray":
171             return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
172         else:
173             assert False
174     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
175         if ty_info.c_ty == "int8_tArray":
176             if copy:
177                 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
178             else:
179                 return arr_name + ".ptr"
180         else:
181             return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
182     def get_native_arr_elem(self, arr_name, idxc, ty_info):
183         assert False # Only called if above is None
184     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
185         if ty_info.c_ty == "int8_tArray":
186             return None
187         else:
188             return None
189
190     def init_str(self, c_array_class_caches):
191         return ""
192
193     def native_c_unitary_enum_map(self, struct_name, variants):
194         out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
195         out_c = out_c + "\tswitch (ord) {\n"
196         ord_v = 0
197
198         out_typescript_enum_fields = ""
199
200         for var in variants:
201             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
202             ord_v = ord_v + 1
203             out_typescript_enum_fields += f"{var},\n\t\t\t\t"
204         out_c = out_c + "\t}\n"
205         out_c = out_c + "\tabort();\n"
206         out_c = out_c + "}\n"
207
208         out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
209         out_c = out_c + "\tswitch (val) {\n"
210         ord_v = 0
211         for var in variants:
212             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
213             ord_v = ord_v + 1
214         out_c = out_c + "\t\tdefault: abort();\n"
215         out_c = out_c + "\t}\n"
216         out_c = out_c + "}\n"
217
218         out_typescript_enum = f"""
219             export enum {struct_name} {{
220                 {out_typescript_enum_fields}
221             }}
222         """
223
224         return (out_c, out_typescript_enum, "")
225
226     def c_unitary_enum_to_native_call(self, ty_info):
227         return (ty_info.rust_obj + "_to_js(", ")")
228     def native_unitary_enum_to_c_call(self, ty_info):
229         return (ty_info.rust_obj + "_from_js(", ")")
230
231     def c_complex_enum_pass_ty(self, struct_name):
232         return "uint32_t"
233
234     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
235         ret = "0 /* " + struct_name + " - " + variant + " */"
236         for param in c_params:
237             ret = ret + "; (void) " + param
238         return ret
239
240     def native_c_map_trait(self, struct_name, field_var_convs, field_fn_lines):
241         return ("", "", "")
242
243     def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
244         java_hu_type = struct_name.replace("LDK", "")
245
246         out_java_enum = ""
247         out_java = ""
248         out_c = ""
249
250         out_java_enum += (self.hu_struct_file_prefix)
251         out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
252         out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
253         out_java_enum += ("\tprotected finalize() {\n")
254         out_java_enum += ("\t\tsuper.finalize();\n")
255         out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
256         out_java_enum += ("\t}\n")
257         out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
258         out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
259         java_hu_subclasses = ""
260
261         out_java +=  ("\tpublic static class " + struct_name + " {\n")
262         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
263         for var in variant_list:
264             out_java +=  ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
265             java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
266             out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
267             out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
268             init_meth_params = ""
269             init_meth_body = ""
270             hu_conv_body = ""
271             for idx, field_ty in enumerate(var.fields):
272                 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
273                 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
274                 if field_ty.to_hu_conv is not None:
275                     hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
276                     hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
277                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
278                 else:
279                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
280                 if idx > 0:
281                     init_meth_params = init_meth_params + ", "
282                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
283                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
284             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
285             out_java +=  (init_meth_body)
286             out_java +=  ("}\n")
287             out_java += ("\t\t}\n")
288             out_java_enum += ("\t\t}\n")
289             java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
290             java_hu_subclasses = java_hu_subclasses + hu_conv_body
291             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
292         out_java += ("\t\tstatic native void init();\n")
293         out_java += ("\t}\n")
294         out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
295         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
296         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
297
298         out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
299         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
300         out_c += ("\tswitch(obj->tag) {\n")
301         for var in variant_list:
302             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
303             c_params = []
304             for idx, field_map in enumerate(var.fields):
305                 if field_map.ret_conv is not None:
306                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
307                     out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
308                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
309                     c_params.append(field_map.ret_conv_name)
310                 else:
311                     c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
312             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
313             out_c += ("\t\t}\n")
314         out_c += ("\t\tdefault: abort();\n")
315         out_c += ("\t}\n}\n")
316         out_java_enum += ("}\n")
317         out_java_enum += (java_hu_subclasses)
318         return (out_java, out_java_enum, out_c)