Skip to content

Program coredump on exit when dlclose a dynamic loaded library which has atexit function calls #17908

Open

Description

@RazYang

Zig Version

0.11.0

Steps to Reproduce and Observed Behavior

We have two .c file:

  1. main.c
#include <stdio.h>
#include <dlfcn.h>

int main() {
    void * handle =dlopen("./libtarget.so", RTLD_LAZY);
    void (*hello)() = NULL;
    if(handle) {
        hello = dlsym(handle,"hello");
        hello();
        dlclose(handle);
    } else {
        fprintf(stderr, "%s\n",dlerror());
    }
    printf("exit\n");
}
  1. target.c
#include <stdio.h>
#include <stdlib.h>

void onexit(){
    printf("onexit\n");
}

void hello() {
    atexit(onexit);
    printf("hello\n");
}

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().

Activity

  1. added
    bug
    on Nov 7, 2023
  2. rootbeer commented on Nov 7, 2023

    @rootbeer
    Contributor

    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.

  3. RazYang commented on Nov 8, 2023

    @RazYang
    Author

    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:
    ldd

    (I don't understand the "python -m" stuff or the "ziglang", though --- is that some wrapper you're using?)

    In this case, I install zig by pip install ziglang(https://pypi.org/project/ziglang/)

    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)
    {
      struct link_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_t sz = (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));
    }

    image
    By contrast, there's no .fini_array section in zig cc compiled version:
    image
    image

  4. rootbeer commented on Nov 8, 2023

    @rootbeer
    Contributor

    I reproduced on 0.12.0-dev.1398+34826823c (recent, with some unrelated glibc fixes). (And with gcc for the native versions.)

    I think you're right its more about what happens on the dlclose path.

    If I add a "destructor" to target.c:

    __attribute__((destructor)) void onfini()  {
            fprintf(stderr, "onfini\n");
    }
    

    I see this get invoked when libtarget.so is built by Zig:

    $ ./main
    hello
    onfini
    exit
    Segmentation fault
    

    And the .fini/.fini_array sections show up in the Zig-built binary:

    $ objdump -h libtarget.so  | grep fini
     12 .fini         00000009  00000000000015dc  00000000000015dc  000005dc  2**2
     15 .fini_array   00000008  00000000000026d0  00000000000026d0  000006d0  2**3
    $ objdump -h libtarget-native.so  | grep fini
     12 .fini         00000009  00000000000011c0  00000000000011c0  000011c0  2**2
     17 .fini_array   00000010  0000000000003de8  0000000000003de8  00002de8  2**3
    

    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.

    It seems a reference to __cxa_finalize is 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_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:

    extern void* __dso_handle;
    extern void __cxa_finalize (void *);
    __attribute__((destructor)) void onfini()  {
            __cxa_finalize(__dso_handle);
    }
    

    (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 dlclose a no-op: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries

  5. RazYang commented on Nov 8, 2023

    @RazYang
    Author

    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).

    self.dso_handle_index = try linker_defined.addGlobal("__dso_handle", self);

    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.)

    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.

  6. bherw commented on Jan 8, 2024

    @bherw

    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?

  7. rootbeer commented on Jan 8, 2024

    @rootbeer
    Contributor

    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.

  8. bherw commented on Jan 9, 2024

    @bherw

    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)
    
  9. rootbeer commented on Jan 11, 2024

    @rootbeer
    Contributor

    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.

    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

  10. bherw commented on Jan 16, 2024

    @bherw

    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.

  11. SamWindell commented on Jun 21, 2024

    @SamWindell

    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.

    extern void* __dso_handle;
    extern void __cxa_finalize (void *);
    __attribute__((destructor)) void onfini()  {
            __cxa_finalize(__dso_handle);
    }

    Sorry if this is pestering, but I wonder if @kubkon has anything to chime in? I've seen your work on zig's linkers.

  12. RazYang commented on Jun 24, 2024

    @RazYang
    Author

    Sorry be late.
    From another point of view, we can address this issue by adding -v option. For zig(prettified):

    $ zig cc -v -shared -o libtarget.so target.o -target x86_64-linux-gnu.2.17
    LLD Link... ld.lld --error-limit=0 --image-base=0 
    --eh-frame-hdr -znow -m elf_x86_64 -shared -o libtarget.so 
    /home/user/.cache/zig/o/0ec85974bd77360470ce66bcb463444b/crti.o
     -dynamic-linker /lib64/ld-linux-x86-64.so.2 --no-undefined-version target.o --as-needed
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libm.so.6 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libpthread.so.0 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libc.so.6 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libdl.so.2 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/librt.so.1 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libld.so.2 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libutil.so.1 
    /home/user/.cache/zig/o/6bc638510d086deb532ca669deadfd37/libresolv.so.2 
    /home/user/.cache/zig/o/1d48c64eec1e503cf87531831703dd9e/libc_nonshared.a 
    /home/user/.cache/zig/o/1c392a5a8cc4298d3be1745947cd85d4/libcompiler_rt.a 
    /home/user/.cache/zig/o/11901875655e33e4007f29b7c08a54ed/crtn.o
    --allow-shlib-undefined
    
    

    And for clang(prettified):

    $ clang -v -shared -o libtarget.so target.o
     "/usr/bin/ld" --hash-style=both --build-id --eh-frame-hdr 
    -m elf_x86_64 -shared -o libtarget.so 
    /lib/x86_64-linux-gnu/crti.o 
    /usr/bin/../lib/gcc/x86_64-linux-gnu/12/crtbeginS.o 
    -L/usr/bin/../lib/gcc/x86_64-linux-gnu/12 
    -L/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../lib64 
    -L/lib/x86_64-linux-gnu -L/lib/../lib64 -L/usr/lib/x86_64-linux-gnu 
    -L/usr/lib/../lib64 -L/lib -L/usr/lib target.o 
    -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed 
    /usr/bin/../lib/gcc/x86_64-linux-gnu/12/crtendS.o
    /lib/x86_64-linux-gnu/crtn.o
    

    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:

    const crt_begin = try tc.getCompilerRt("crtbegin", .object);

    getCompilerRt not implemented
    pub fn getCompilerRt(tc: *const Toolchain, component: []const u8, file_kind: FileKind) ![]const u8 {

    getFilePath is located at:
    pub fn getFilePath(tc: *const Toolchain, name: []const u8) ![]const u8 {

  13. modified the milestones: 1.0.0, 0.16.0 on Aug 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions