using std::thread in a library loaded with dlopen leads to a sigsev

前端 未结 3 985
栀梦
栀梦 2021-01-04 14:12

I recently discovered a strange behaviour using std::thread and dlopen.

Basically, when I execute a std::thread in a library w

3条回答
  •  轮回少年
    2021-01-04 14:22

    The problem lies in libstdc++.

    • With C programs this doesn't happen.
    • With C++ programs built with libc++ this also doesn't happen.
    • With C++ programs built with libstdc++ statically this also doesn't happen.
    • With libraries build with libc++ this doesn't happen even if the caller program is built with libstdc++ dynamically.
    • When the program dlopens the library with RTLD_GLOBAL, this also doesn't happen.

    So one solution would be to switch to libc++. Obviously this only works if one never export any interface that relies on any std:: type. In particular, a library that only exports C-compatible interfaces should be OK.

    Another solution would be to have your library loaded with RTLD_GLOBAL (you may have to separate it in two, the main one and a small stub that just loads the main one with RTLD_GLOBAL).

    In parallel one should file a bug against libstdc++ and wait for a fix. There's no reason why it should be broken like that.

    If none of the above are viable options, then the only solution seems to involve a complete isolation between the caller and the multithreaded module. Make the multithreaded module a separate executable, fork-exec it from your plugin, marshal arguments/results to/from it via pipes.

    Finally, there's always the ugly workaround of preloading libpthread in the caller program.

提交回复
热议问题