Hi there, I’m currently trying to wrap around my head with C interop while adding features to ocaml-ssl. I’m having trouble that my code is segfaulting.
Disclaimer: I’m a beginner in C so my code would most likely look funny to you, but please bear with me (and possibly suggest improvements)
Basically, I have this data structure:
const unsigned char *protocol_buffer = {
2, 'h', '2',
8, 'h', 't', 't', 'p', '/', '1', '.', '1'
};
And I want to transform this into an OCaml string list of ["h2"; "http/1.1"]
.
I currently have this code:
static value build_alpn_protocol_list(const unsigned char *protocol_buffer, unsigned int len)
{
value protocol_list;
int idx = 0;
int list_len = 0;
while (idx < len)
{
list_len++;
int proto_len = (int) protocol_buffer[idx++];
idx += proto_len;
}
protocol_list = caml_alloc(list_len, 0);
idx = 0;
int list_idx = 0;
while (idx < len)
{
int proto_len = (int) protocol_buffer[idx++];
char proto[proto_len + 1];
int i;
for (i = 0; i < proto_len; i++)
{
proto[i] = (char) protocol_buffer[idx++];
}
proto[proto_len] = '\0';
value p = caml_copy_string(proto);
Store_field(protocol_list, list_idx++, p);
}
return protocol_list;
}
If you notice there’s a value p
there, and if I tried to printf("%s\n", String_val(p))
it outputs both h2
and http/1.1
strings correctly inside the loop.
I managed to pass this protocol_list
into an OCaml callback, but it segfaulted when I tried to do List.length
on it. Assuming the output from ocamldebug is correct, it segfaulted in this line:
Time: 255 - pc: 10252 - module List
20 | _::l -> <|b|>length_aux (len + 1) l
My naive guess is that it is something related to GC on protocol_list
. (It might also be related to how I am passing and calling the callback, but I’d stop here first to isolate the problem. If you need me to provide the code that passes the callback do let me know).
Does anyone have any idea how to solve this? Thanks in advance!