ludocode / mpack

MPack - A C encoder/decoder for the MessagePack serialization format / msgpack.org[C]
MIT License
521 stars 82 forks source link

Segfault whenever *_init_filename is called more than once #111

Closed quadroli closed 5 days ago

quadroli commented 1 week ago

So, Amazing library by the way, I love it, I was looking for a convenient way/format to read and write data from my app and this is well structured. However it appears that if mpack_writer_init_filename() is called, one can not later on call mpack_tree_init_filename() even if opening two different files (fails for the same file as well), this has the implication that one can not read and write to the same file in the same program.

To further elaborate, this code snippet segfaults upon encountering mpack_tree_init_filename()

#include "mpack.h"
int main(void){ 
  mpack_writer_t *writer;
  mpack_writer_init_filename(writer, "conf.mp");
  mpack_start_map(writer, 1);
  mpack_write_utf8_cstr(writer, "theme");
  mpack_write_int(writer, 4);
  mpack_finish_map(writer);
  mpack_writer_destroy(writer);

  mpack_tree_t *tree;
  mpack_tree_init_filename(tree, "conf.mp", 0);
  mpack_tree_parse(tree);
  mpack_node_t root = mpack_tree_root(tree);
  int theme = mpack_node_int(mpack_node_map_cstr(root,"theme"));
  printf("theme %d\n", theme);
  mpack_tree_destroy(tree);

  return 0;
}
The backtrace shows: 0 memset () at src/string/x86_64/memset.s:55 1 0x00005555555fb4fb in __asan_memset () at /home/buildozer/aports/main/llvm-runtimes/src/llvm-project-18.1.8.src/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:67 2 0x000055555564d51c in mpack_tree_init_clear (tree=0x0) at mpack.c:5911 3 0x000055555564064d in mpack_tree_init_data (tree=0x0, data=0x502000000010 "\201\245theme\004", length=8) at mpack.c:5920 4 0x000055555564db78 in mpack_tree_init_stdfile_noclose (tree=0x0, stdfile=0x51a000000680, max_bytes=0) at mpack.c:6088 5 0x000055555564da26 in mpack_tree_init_stdfile (tree=0x0, stdfile=0x51a000000680, max_bytes=0, close_when_done=true) at mpack.c:6097 6 0x000055555564080d in mpack_tree_init_filename (tree=0x0, --Type for more, q to quit, c to continue without paging-- filename=0x55555566dba0 "conf.mp", max_bytes=0) at mpack.c:6114 7 0x000055555563b651 in main () at main.c:57
quadroli commented 1 week ago

Any assistance/guidance would be really appreciated as I believe this is not expected behaviour

quadroli commented 1 week ago

Also, if I comment out either of the blocks i.e. I either use the write/node API, it works just fine, issue is if I try using both in the same file Is there something I could be missing ?

quadroli commented 1 week ago

I tracked down the issue to tree and writer being uninitialised, So a work around would be adding

mpack_writer_t dummy_writer;
mpack_writer_t *writer = &dummy_writer;

and

mpack_tree_t dummy_tree;
mpack_tree_t *tree = &dummy_tree;

If it helps, I'm using Alpine Linux with Musl as the libc Compiler: clang18