Import order issue with torch and pybind11 Library Statically Linked to libstdc++
Labels: module: abi, triaged, module: static linking

### 🐛 Describe the bug


I've encountered an issue when importing torch alongside another pybind11 library. The problem surfaces when torch is imported after the sample library, when that library statically links to libstdc++ and includes iostream (there may be other inludes to cause this as well). To rule out external factors, I've created a minimal pybind11 shared object (.so). This library essentially does nothing but includes iostream, links to libstdc++, and exposes an object to Python.

The following sequence will lead to a failure:

```python 
import testlib  # This is the noop library that merely includes <iostream> and is static linked to libstdc++
import torch
```
However, swapping the order works without any issues:
```python 
import torch
import testlib  # This is the noop library that merely includes <iostream>  and is static linked to libstdc++
```
Interestingly, if I remove the <iostream> inclusion from testlib, the order of imports doesn't matter and no errors arise. Additionally, if I link to libstdc++ dynamically, I encounter no issues, even with <iostream> included.

The call stack suggests a crash during some string conversion, potentially from an exception handler. Unfortunately, there aren't any debug messages sent to stderr or stdout. Yet, I'm speculating if this crash might be hiding a Thread-Local Storage (TLS) issue, as documented here: https://github.com/pytorch/pytorch/issues/2575.

SEGFAULT BT:
```
Program received signal SIGSEGV, Segmentation fault.
0x00007fffc24d242b in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
(gdb) bt
#0  0x00007fffc24d242b in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#1  0x00007fffc24d42cf in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007fffc24d4434 in std::codecvt<char16_t, char, __mbstate_t>::do_in(__mbstate_t&, char const*, char const*, char const*&, char16_t*, char16_t*, char16_t*&) const ()
   from /lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007fffc253d3ca in std::ostream& std::ostream::_M_insert<unsigned long>(unsigned long) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007fffa7f0687b in c10::detail::_str_wrapper<char const*, char const* const&, char const*, unsigned int const&>::call(char const* const&, char const* const&, char const* const&, unsigned int const&) () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#5  0x00007fffa7eff41a in torch::(anonymous namespace)::debugString(std::string, char const*, unsigned int) () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#6  0x00007fffa7f04755 in torch::Library::_fallback(torch::CppFunction&&) & () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#7  0x00007fffa7c550ef in at::native::TORCH_LIBRARY_IMPL_init___Conjugate_2(torch::Library&) () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#8  0x00007fffa7c58fd2 in torch::detail::TorchLibraryInit::TorchLibraryInit(torch::Library::Kind, void (*)(torch::Library&), char const*, c10::optional<c10::DispatchKey>, char const*, unsigned int) () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#9  0x00007fffa7b5773c in _GLOBAL__sub_I_ConjugateFallback.cpp () from /usr/local/lib/python3.10/dist-packages/torch/lib/libtorch_cpu.so
#10 0x00007ffff7fc947e in call_init (l=<optimized out>, argc=argc@entry=2, argv=argv@entry=0x7fffffffcea8, env=env@entry=0x7fffffffcec0) at ./elf/dl-init.c:70
#11 0x00007ffff7fc9568 in call_init (env=0x7fffffffcec0, argv=0x7fffffffcea8, argc=2, l=<optimized out>) at ./elf/dl-init.c:33
#12 _dl_init (main_map=0x555555fc39f0, argc=2, argv=0x7fffffffcea8, env=0x7fffffffcec0) at ./elf/dl-init.c:117
#13 0x00007ffff7d74c85 in __GI__dl_catch_exception (exception=<optimized out>, operate=<optimized out>, args=<optimized out>) at ./elf/dl-error-skeleton.c:182
#14 0x00007ffff7fd0ff6 in dl_open_worker (a=0x7fffffffa660) at ./elf/dl-open.c:808
#15 dl_open_worker (a=a@entry=0x7fffffffa660) at ./elf/dl-open.c:771
#16 0x00007ffff7d74c28 in __GI__dl_catch_exception (exception=<optimized out>, operate=<optimized out>, args=<optimized out>) at ./elf/dl-error-skeleton.c:208
#17 0x00007ffff7fd134e in _dl_open (file=<optimized out>, mode=-2147483646, caller_dlopen=0x5555557b960b, nsid=-2, argc=2, argv=<optimized out>, env=0x7fffffffcec0)
    at ./elf/dl-open.c:883
#18 0x00007ffff7c906bc in dlopen_doit (a=a@entry=0x7fffffffa8d0) at ./dlfcn/dlopen.c:56
#19 0x00007ffff7d74c28 in __GI__dl_catch_exception (exception=exception@entry=0x7fffffffa830, operate=<optimized out>, args=<optimized out>) at ./elf/dl-error-skeleton.c:208
#20 0x00007ffff7d74cf3 in __GI__dl_catch_error (objname=0x7fffffffa888, errstring=0x7fffffffa890, mallocedp=0x7fffffffa887, operate=<optimized out>, args=<optimized out>)
--Type <RET> for more, q to quit, c to continue without paging--
    at ./elf/dl-error-skeleton.c:227
#21 0x00007ffff7c901ae in _dlerror_run (operate=operate@entry=0x7ffff7c90660 <dlopen_doit>, args=args@entry=0x7fffffffa8d0) at ./dlfcn/dlerror.c:138
#22 0x00007ffff7c90748 in dlopen_implementation (dl_caller=<optimized out>, mode=<optimized out>, file=<optimized out>) at ./dlfcn/dlopen.c:71
#23 ___dlopen (file=<optimized out>, mode=<optimized out>) at ./dlfcn/dlopen.c:81
#24 0x00005555557b960b in ?? ()
#25 0x00005555557b80f7 in ?? ()
#26 0x00005555556b4969 in ?? ()
#27 0x000055555569f2c1 in _PyEval_EvalFrameDefault ()
#28 0x00005555556b470c in _PyFunction_Vectorcall ()
#29 0x00005555556a28a2 in _PyEval_EvalFrameDefault ()
#30 0x00005555556b470c in _PyFunction_Vectorcall ()
#31 0x000055555569cf52 in _PyEval_EvalFrameDefault ()
#32 0x00005555556b470c in _PyFunction_Vectorcall ()
#33 0x000055555569ce0d in _PyEval_EvalFrameDefault ()
#34 0x00005555556b470c in _PyFunction_Vectorcall ()
#35 0x000055555569ce0d in _PyEval_EvalFrameDefault ()
#36 0x00005555556b470c in _PyFunction_Vectorcall ()
#37 0x000055555569ce0d in _PyEval_EvalFrameDefault ()
#38 0x00005555556b470c in _PyFunction_Vectorcall ()
#39 0x00005555556b3b24 in ?? ()
#40 0x00005555557934af in _PyObject_CallMethodIdObjArgs ()
#41 0x00005555556c80ca in PyImport_ImportModuleLevelObject ()
#42 0x000055555569f9e5 in _PyEval_EvalFrameDefault ()
#43 0x000055555578de56 in ?? ()
#44 0x000055555578dcf6 in PyEval_EvalCode ()
```


C++ Test lib code, just create a pybind module so we can import in Python.
```
#include <iostream> //including this causes segfault on torch import, if torch is the next import
#include <pybind11/pybind11.h>

namespace py = pybind11;

PYBIND11_MODULE(nvcv, m)
{
    //noop
}
```





### Versions

Collecting environment information...
PyTorch version: 2.0.1+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.1 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.25.0
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.2.0-31-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA RTX A3000 Laptop GPU
Nvidia driver version: 535.86.10
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.3
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.3
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      39 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             16
On-line CPU(s) list:                0-15
Vendor ID:                          GenuineIntel
Model name:                         11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz
CPU family:                         6
Model:                              141
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           1
CPU max MHz:                        4800.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4992.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 invpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          384 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           10 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-15
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2+cu118
[pip3] torchnvjpeg==0.1.0
[pip3] triton==2.0.0
[conda] Could not collect