Solved C shared library __attribute__((constructor)) initializer getting bad values for argc and argv

Hi guys,

I'm working on a cross-platform open source project written in C that compiles into multiple shared libraries. One of those libraries has contructors and destructors defined like this:

__attribute__((constructor)) static void init(int argc, char ** argv, char ** envp)

__attribute__((destructor)) static void fini(void)

Our libraries work on every Linux distro we tried and also on MacOS X Sierra and later, but for some reason we get SEGVs on FreeBSD (we tried 11.0-RELEASE, 11.1-RELEASE and 12.0-CURRENT). When debugging, it seems that the argc and argv parameters that are fed into the function don't contain the correct values (see gdb frame #3 below, it's apparent from value for argc):

Program received signal SIGSEGV, Segmentation fault.
0x00000008023598ff in strlen () from /lib/
(gdb) bt
#0  0x00000008023598ff in strlen () from /lib/
#1  0x0000000800c6f6bd in path_strip (src=0x2 <error: Cannot access memory at address 0x2>)
    at /usr/home/ouroboros/ouroboros/src/lib/utils.c:45
#2  0x0000000800a57d35 in check_python (str=0x2 <error: Cannot access memory at address 0x2>)
    at /usr/home/ouroboros/ouroboros/src/lib/dev.c:311
#3  0x0000000800a578af in init (argc=6701056, argv=0x7fffffffe358, envp=0x801c79ed0) at /usr/home/ouroboros/ouroboros/src/lib/dev.c:331
#4  0x0000000800a5cc52 in __do_global_ctors_aux () from /usr/lib/
#5  0x0000000800a56ea6 in _init () from /usr/lib/
#6  0x00007fffffffda40 in ?? ()
#7  0x00000008006086b8 in ?? () from /libexec/
#8  0x0000000800607a4b in ?? () from /libexec/
#9  0x0000000800605669 in ?? () from /libexec/
#10 0x0000000000000000 in ?? ()

I'm trying to create a minimal reproducer for this problem, but simple examples with minimal functions work fine.

Is there someone that has a deep knowledge of how this works that could point me in the right direction of what could possibly cause this to happen so we can figure out the bug or get a minimal reproducer?


After trying some different configurations I think it's a bug in FreeBSD clang. When I compile the library using gcc it does work fine. Compiling using clang on linux and OSX works fine as well.