You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Program coredump on exit when dlclose a dynamic loaded library which has atexit function calls #17908
The command python -m ziglang cc -fPIC -c target.c -target x86_64-linux-gnu.2.17 && python -m ziglang cc -shared -o libtarget.so target.o -target x86_64-linux-gnu.2.17 && clang main.c -o main && ./main triggers a core dump in __run_exit_handlers due to the presence of atexit(onexit) in libtarget.so. Even after calling dlclose, the onexit function remains in __exit_funcs. When the program exits normally, libc attempts to call onexit in the __run_exit_handlers function, leading to the core dump.
hello
exit
zsh: segmentation fault ./main
Expected Behavior
When using clang, everyting seems fine. The command clang -fPIC -c target.c && clang -shared -o libtarget.so target.o && clang main.c -o main && ./main prints the following output:
hello
onexit
exit
In this case, the onexit function is correctly called upon using dlclose().
The semantics of atexit are defined by the linked C library, more than by Zig. It looks like your target is correct (its has gnu, and thus should link in glibc). But, you don't have an -lc argument on the Zig commandlines, and I think that is also needed to link in the C library? (I don't understand the "python -m" stuff or the "ziglang", though --- is that some wrapper you're using?)
You might use readelf or objdump to inspect the intermediate objects to see if they contain references to glibc symbols for atexit (you should see dynamic refences to the glibc-versioned __cxa_atexit symbol).
Alternatively, you could try side-stepping the problem by labeling your in-dso cleanup handler with __attribute__(destructor)? That said, the GNU atexit is documented to handle shared-library-unload atexit correctly, so what you have should be workable.
The semantics of atexit are defined by the linked C library, more th
an by Zig. It looks like your target is correct (its has gnu, and thus should link in glibc). But, you don't have an -lc argument on the Zig commandlines, and I think that is also needed to link in the C library? >
glibc seems automatically linked by linker:
(I don't understand the "python -m" stuff or the "ziglang", though --- is that some wrapper you're using?)
You might use readelf or objdump to inspect the intermediate objects to see if they contain references to glibc symbols for atexit (you should see dynamic refences to the glibc-versioned __cxa_atexit symbol).
Alternatively, you could try side-stepping the problem by labeling your in-dso cleanup handler with __attribute__(destructor)? That said, the GNU atexit is documented to handle shared-library-unload atexit correctly, so what you have should be workable.
I go deeper into glibc internals, finding that the difference of call stack on dlclose between zig cc compiled version and clang compiled version located in the glibc _dl_call_fini. In clang version, dlclose calls functions in .fini_array
void_dl_call_fini (void*closure_map)
{
structlink_map*map=closure_map;
/* When debugging print a message first. */if (__glibc_unlikely (GLRO(dl_debug_mask) &DL_DEBUG_IMPCALLS))
_dl_debug_printf ("\ncalling fini: %s [%lu]\n\n", map->l_name, map->l_ns);
/* Make sure nothing happens if we are called twice. */map->l_init_called=0;
ElfW(Dyn) *fini_array=map->l_info[DT_FINI_ARRAY];
if (fini_array!=NULL)
{
ElfW(Addr) *array= (ElfW(Addr) *) (map->l_addr+fini_array->d_un.d_ptr);
size_tsz= (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val
/ sizeof (ElfW(Addr)));
while (sz-->0)
((fini_t) array[sz]) ();
}
/* Next try the old-style destructor. */ElfW(Dyn) *fini=map->l_info[DT_FINI];
if (fini!=NULL)
DL_CALL_DT_FINI (map, ((void*) map->l_addr+fini->d_un.d_ptr));
}
By contrast, there's no .fini_array section in zig cc compiled version:
So I think Zig is not generating the .fini section when its "not used". (I'm not sure why this section shows up in the gcc/clang builds, though). I'm pretty sure this section isn't relevant for atexit registered callbacks. An atexit call creates a fully run-time callback, not one that a compiler/linker could put into a fini section. Oh, unless this fini is being used to trigger a call to the atexit cleanup handlers? And Zig isn't linking that in when building the libtarget.so .... Ah, yeah, the fini_array is 16 bytes in gcc-built version, and 8 bytes in Zig-built.
So, I think Zig needs to, when linking C or C++ shared library code (and maybe with additional caveats?), add a destructor (.fini) call to __cxa_finalize. However, that needs to pass along the "current shared library" (this is the __dso_handle in gcc .. I'm not sure if that's a standard symbol name, or something gcc-specific).
Alternatively, Zig could declare that unloading shared libraries is not a thing (like Musl does[2]). I'm not sure where the boundary between Zig runtime and C runtime is exactly ...
In the short-term, it seems like you can use the __attribute__((destructor)) annotation on C code you'd like to see run during shared library unload (instead of using atexit). Oh! Or you can use this to invoke the finalizer and still use atexit:
So, I think Zig needs to, when linking C or C++ shared library code (and maybe with additional caveats?), add a destructor (.fini) call to __cxa_finalize. However, that needs to pass along the "current shared library" (this is the __dso_handle in gcc .. I'm not sure if that's a standard symbol name, or something gcc-specific).
__dso_handle seems to be a convention, which I found zig also add __dso_handle symbol when linking. So it's should be a proper solution for this issue by adding __cxa_finalize(__dso_handle).
And, it's part of crt, for debian bookworm, the .fini_array section of calling __do_global_dtors_aux located in /usr/lib/gcc/x86_64-linux-gnu/12/crtbegin.o.
Hi, I just ran into this issue with a library I'm working on. Is there anything I can do to help to get this fixed? It looks like you've figured out a fix; do we just need to make a PR for this issue?
I think we know what code is missing, but I, at least, don't understand where in Zig the fix would go. I'm not entirely sure if this is a pure C-compatibility issue, or if its an issue for Zig-native libraries. And there are probably a load of subtle issues around destructors and finalizers that might crop up when trying to fix this too.
The known work-arounds seem to be targetting the Musl C runtime instead of glibc (musl basically no-ops dlclose), or adding an __attribute__((destructor)) function in the C library to invoke the expected cleanup.
For context, I'm trying to build a shared object from C++ sources that has a number of dependencies statically linked in via vcpkg. The .so is redistributable; I don't control the callers. I'm using x86_64-linux-gnu.2.25 as my target. I don't use atexit directly, but it looks like libressl/openssl and grpc are calling it.
I tried building my so with musl, which seems feasible, but I'm having issues with cmake not finding zig ar. On reflection, however, I don't think building the shared object with musl would help: If I understood correctly, the dlclose implementation musl provides would affect the behaviour of the loader/consumer of the shared object, not the shared object itself. I can't dictate to my callers to use musl, so that wouldn't help.
I tried adding the __attribute__((destructor)) workaround that calls cka_finalize to the shared object, but that didn't fix the issue for me. With print debugging, I can observe the module being loaded and unloaded (and the onfini being called on module unload) multiple times during a test run (expected, as the test loads and unloads the shared object), but on program exit, the test program still crashes.
Valgrind:
==459178== Thread 1:
==459178== Jump to the invalid address stated on the next line
==459178== at 0x18A55E40: ???
==459178== by 0x525B494: __run_exit_handlers (exit.c:113)
==459178== by 0x525B60F: exit (exit.c:143)
==459178== by 0x523FD96: (below main) (libc_start_call_main.h:74)
==459178== Address 0x18a55e40 is not stack'd, malloc'd or (recently) free'd
==459178==
==459178==
==459178== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==459178== Access not within mapped region at address 0x18A55E40
==459178== at 0x18A55E40: ???
==459178== by 0x525B494: __run_exit_handlers (exit.c:113)
==459178== by 0x525B60F: exit (exit.c:143)
==459178== by 0x523FD96: (below main) (libc_start_call_main.h:74)
Yeah, I think you're right that Musl won't help for the case of building a shared library for others to link with later.
If you're seeing that onfini is being invoked correctly, then perhaps the problem is with the __dso_handle? As I understand it, that "global" should be a unique value per loaded shared library. It is used to label registered atexit handlers. Then __cxa_finalize(__dso_handle) can unregister handlers owned by the library that is going away (which would probably prevent the error you're seeing when the main binary exits and runs all the remaining atexit handlers). I get the impression that a __dso_handle of NULL is a special case (for the main program), so if its not being initialized correctly, perhaps that could lead to this behavior. That said, I'm not sure how to fix that without presumably making changes to the Zig linker.
I tried logging the __dso_handle in the onfini function before the call to __cka_finalize and I got the same non-zero address every time; then the program still crashed on exit after the last call to onfini. So at least we know Zig is not giving a corrupt value for it.
I tried the workarounds suggested in that thread, but they didn't seem to have an effect.
I'd love to get some traction behind fixing this, it's still a major problem for writing audio plugins on Linux that make use of C++ libraries. The audio plugin (a dynamic library) crashes 100% of the time due to this problem.
For now however, the combination the snippet below and using the -fno-use-cxa-atexit flag was a sucessful workaround for me. But I suspect this is very fragile workaround - presumably the code should have atexit. Thank you to those who investigated this in the comments above.
If manully link with crtbeginS.o and crtendS.o when compiling dynamic linked library, coredump just disappear.
In source code of zig, There are two function getCompilerRt and getFilePath to address the path of crt(begin|end).o:
Activity
rootbeer commentedon Nov 7, 2023
The semantics of
atexitare defined by the linked C library, more than by Zig. It looks like your target is correct (its hasgnu, and thus should link in glibc). But, you don't have an-lcargument on the Zig commandlines, and I think that is also needed to link in the C library? (I don't understand the "python -m" stuff or the "ziglang", though --- is that some wrapper you're using?)You might use readelf or objdump to inspect the intermediate objects to see if they contain references to glibc symbols for
atexit(you should see dynamic refences to the glibc-versioned__cxa_atexitsymbol).Alternatively, you could try side-stepping the problem by labeling your in-dso cleanup handler with
__attribute__(destructor)? That said, the GNU atexit is documented to handle shared-library-unload atexit correctly, so what you have should be workable.RazYang commentedon Nov 8, 2023
glibc seems automatically linked by linker:

In this case, I install zig by
pip install ziglang(https://pypi.org/project/ziglang/)I go deeper into glibc internals, finding that the difference of call stack on dlclose between zig cc compiled version and clang compiled version located in the glibc
_dl_call_fini. In clang version, dlclose calls functions in .fini_arrayBy contrast, there's no .fini_array section in zig cc compiled version:
rootbeer commentedon Nov 8, 2023
I reproduced on 0.12.0-dev.1398+34826823c (recent, with some unrelated glibc fixes). (And with
gccfor the native versions.)I think you're right its more about what happens on the
dlclosepath.If I add a "destructor" to target.c:
I see this get invoked when libtarget.so is built by Zig:
And the
.fini/.fini_arraysections show up in the Zig-built binary:So I think Zig is not generating the .fini section when its "not used". (I'm not sure why this section shows up in the gcc/clang builds, though). I'm pretty sure this section isn't relevant for
atexitregistered callbacks. An atexit call creates a fully run-time callback, not one that a compiler/linker could put into a fini section. Oh, unless this fini is being used to trigger a call to the atexit cleanup handlers? And Zig isn't linking that in when building the libtarget.so .... Ah, yeah, thefini_arrayis 16 bytes in gcc-built version, and 8 bytes in Zig-built.It seems a reference to
__cxa_finalizeis built into the native version, but not the Zig version. See https://refspecs.linuxbase.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib---cxa-finalize.html This function is doing exactly the thing we're missing (walking the atexit-registered handlers, looking for ones registered by the "current" shared library) [1]. It seems in the native version a call to this method is registered in the destructor (.fini_array) list. But that isn't happening in Zig.So gcc (and presumably clang) compiles in a
__do_global_dtors_aux(see https://github.com/gcc-mirror/gcc/blob/f27246b009636aff4733ccfca1a42c3914d7d9c6/libgcc/crtstuff.c#L388), which invokes__cxa_finalize. (I'm curious why this isn't part of the glibc C-runtime libraries. Odd.)So, I think Zig needs to, when linking C or C++ shared library code (and maybe with additional caveats?), add a destructor (
.fini) call to__cxa_finalize. However, that needs to pass along the "current shared library" (this is the__dso_handlein gcc .. I'm not sure if that's a standard symbol name, or something gcc-specific).Alternatively, Zig could declare that unloading shared libraries is not a thing (like Musl does[2]). I'm not sure where the boundary between Zig runtime and C runtime is exactly ...
In the short-term, it seems like you can use the
__attribute__((destructor))annotation on C code you'd like to see run during shared library unload (instead of using atexit). Oh! Or you can use this to invoke the finalizer and still use atexit:(Adding that runs the atexit handler at the correct time and fixes the segfault for me.)
Notes:
[1] The glibc __cxa_finalize implementation is in its stdlib/.
[2] Not strictly related but it seems the Musl C library avoids this issue (and many others!) by making
dlclosea no-op: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-librariesRazYang commentedon Nov 8, 2023
__dso_handleseems to be a convention, which I found zig also add __dso_handle symbol when linking. So it's should be a proper solution for this issue by adding__cxa_finalize(__dso_handle).zig/src/link/Elf.zig
Line 3119 in ee47643
And, it's part of
crt, for debian bookworm, the .fini_array section of calling__do_global_dtors_auxlocated in/usr/lib/gcc/x86_64-linux-gnu/12/crtbegin.o.bherw commentedon Jan 8, 2024
Hi, I just ran into this issue with a library I'm working on. Is there anything I can do to help to get this fixed? It looks like you've figured out a fix; do we just need to make a PR for this issue?
rootbeer commentedon Jan 8, 2024
I think we know what code is missing, but I, at least, don't understand where in Zig the fix would go. I'm not entirely sure if this is a pure C-compatibility issue, or if its an issue for Zig-native libraries. And there are probably a load of subtle issues around destructors and finalizers that might crop up when trying to fix this too.
The known work-arounds seem to be targetting the Musl C runtime instead of glibc (musl basically no-ops
dlclose), or adding an__attribute__((destructor))function in the C library to invoke the expected cleanup.bherw commentedon Jan 9, 2024
For context, I'm trying to build a shared object from C++ sources that has a number of dependencies statically linked in via vcpkg. The .so is redistributable; I don't control the callers. I'm using x86_64-linux-gnu.2.25 as my target. I don't use atexit directly, but it looks like libressl/openssl and grpc are calling it.
I tried building my so with musl, which seems feasible, but I'm having issues with cmake not finding
zig ar. On reflection, however, I don't think building the shared object with musl would help: If I understood correctly, the dlclose implementation musl provides would affect the behaviour of the loader/consumer of the shared object, not the shared object itself. I can't dictate to my callers to use musl, so that wouldn't help.I tried adding the
__attribute__((destructor))workaround that calls cka_finalize to the shared object, but that didn't fix the issue for me. With print debugging, I can observe the module being loaded and unloaded (and theonfinibeing called on module unload) multiple times during a test run (expected, as the test loads and unloads the shared object), but on program exit, the test program still crashes.Valgrind:
rootbeer commentedon Jan 11, 2024
Yeah, I think you're right that Musl won't help for the case of building a shared library for others to link with later.
If you're seeing that
onfiniis being invoked correctly, then perhaps the problem is with the__dso_handle? As I understand it, that "global" should be a unique value per loaded shared library. It is used to label registeredatexithandlers. Then__cxa_finalize(__dso_handle)can unregister handlers owned by the library that is going away (which would probably prevent the error you're seeing when the main binary exits and runs all the remaining atexit handlers). I get the impression that a__dso_handleof NULL is a special case (for the main program), so if its not being initialized correctly, perhaps that could lead to this behavior. That said, I'm not sure how to fix that without presumably making changes to the Zig linker.It could be your problem is more about C++, though? E.g., this StackOverflow answer my have other leads you can follow: https://stackoverflow.com/a/48256026/960524
bherw commentedon Jan 16, 2024
I tried logging the
__dso_handlein theonfinifunction before the call to__cka_finalizeand I got the same non-zero address every time; then the program still crashed on exit after the last call to onfini. So at least we know Zig is not giving a corrupt value for it.I tried the workarounds suggested in that thread, but they didn't seem to have an effect.
SamWindell commentedon Jun 21, 2024
I'd love to get some traction behind fixing this, it's still a major problem for writing audio plugins on Linux that make use of C++ libraries. The audio plugin (a dynamic library) crashes 100% of the time due to this problem.
For now however, the combination the snippet below and using the
-fno-use-cxa-atexitflag was a sucessful workaround for me. But I suspect this is very fragile workaround - presumably the code should have atexit. Thank you to those who investigated this in the comments above.Sorry if this is pestering, but I wonder if @kubkon has anything to chime in? I've seen your work on zig's linkers.
RazYang commentedon Jun 24, 2024
Sorry be late.
From another point of view, we can address this issue by adding
-voption. For zig(prettified):And for clang(prettified):
If manully link with
crtbeginS.oandcrtendS.owhen compiling dynamic linked library, coredump just disappear.In source code of zig, There are two function
getCompilerRtandgetFilePathto address the path of crt(begin|end).o:zig/lib/compiler/aro/aro/toolchains/Linux.zig
Line 249 in ab4c461
getCompilerRtnot implementedzig/lib/compiler/aro/aro/Toolchain.zig
Line 363 in ab4c461
getFilePathis located at:zig/lib/compiler/aro/aro/Toolchain.zig
Line 253 in ab4c461
T0053/T0104/T0105: record what the research found, and what was measu…
T0105.1: a gameplay module can be genuinely unloaded now
fix: run a zig-built library's exit handlers when it is unloaded