@@ -43,13 +43,155 @@ public static void Trace(string msg)
4343 }
4444 }
4545
46+ private static bool s_moduleUnloadPrevented ;
47+
48+ /// <summary>
49+ /// Pins this native host module in memory so the OS never unloads it.
50+ /// </summary>
51+ /// <remarks>
52+ /// This native host is compiled with NativeAOT, so it embeds a .NET runtime whose
53+ /// per-thread cleanup is registered with the OS via a <c>pthread_key</c> destructor that
54+ /// points into this module's own code. Node.js unloads (<c>dlclose</c>) an addon when the
55+ /// environment that loaded it is torn down. When a <c>worker_threads</c> Worker loads this
56+ /// module and is then terminated, Node unloads the module while the worker's OS thread is
57+ /// still alive; the still-registered destructor then points at unmapped memory and the
58+ /// process crashes with SIGSEGV as the thread exits (glibc <c>__nptl_deallocate_tsd</c>).
59+ /// Keeping the module mapped for the lifetime of the process keeps that destructor valid.
60+ /// <para/>
61+ /// This is scoped to Linux (glibc) and macOS, where the native host can be unloaded before
62+ /// the worker thread exits; on Windows module/thread teardown does not hit this issue. The
63+ /// pin is best-effort: any failure is traced but does not block init.
64+ /// </remarks>
65+ private static unsafe void PreventModuleUnload ( )
66+ {
67+ if ( s_moduleUnloadPrevented )
68+ {
69+ return ;
70+ }
71+
72+ s_moduleUnloadPrevented = true ;
73+
74+ bool isMacOS = RuntimeInformation . IsOSPlatform ( OSPlatform . OSX ) ;
75+ if ( ! RuntimeInformation . IsOSPlatform ( OSPlatform . Linux ) && ! isMacOS )
76+ {
77+ return ;
78+ }
79+
80+ try
81+ {
82+ // Resolve the file path of this shared library from the address of one of its
83+ // own functions, then re-open it with RTLD_NODELETE so it is never unmapped.
84+ nint moduleFunction =
85+ ( nint ) ( delegate * unmanaged[ Cdecl] < napi_env , napi_value , napi_value > )
86+ & InitializeModule ;
87+
88+ nint fileName = default ;
89+ if ( DlAddr ( moduleFunction , out Dl_info info ) != 0 )
90+ {
91+ fileName = info . dli_fname ;
92+ }
93+
94+ if ( fileName != default )
95+ {
96+ // RTLD_NOLOAD resolves the already-loaded module without loading a new copy;
97+ // RTLD_NODELETE keeps it mapped for the process lifetime. The extra (never
98+ // released) reference also prevents Node's dlclose from unmapping it.
99+ const int RTLD_LAZY = 0x0001 ;
100+ const int RTLD_NOLOAD_LINUX = 0x0004 ;
101+ const int RTLD_NODELETE_LINUX = 0x1000 ;
102+ const int RTLD_NOLOAD_MACOS = 0x0010 ;
103+ const int RTLD_NODELETE_MACOS = 0x0080 ;
104+ int flags = RTLD_LAZY | ( isMacOS ?
105+ RTLD_NOLOAD_MACOS | RTLD_NODELETE_MACOS :
106+ RTLD_NOLOAD_LINUX | RTLD_NODELETE_LINUX ) ;
107+ nint handle = DlOpen ( fileName , flags ) ;
108+ Trace ( $ " Pinned native host module ({ ( handle != default ? "ok" : "no-op" ) } ).") ;
109+ }
110+ else
111+ {
112+ Trace ( " Could not resolve native host module path to pin it." ) ;
113+ }
114+ }
115+ catch ( Exception ex )
116+ {
117+ Trace ( " Failed to pin native host module: " + ex ) ;
118+ }
119+ }
120+
121+ // dladdr and dlopen are exported by libSystem on macOS. On Linux they are exported by
122+ // libc.so.6 on glibc >= 2.34, but by libdl.so.2 on older glibc versions.
123+ private static int DlAddr ( nint addr , out Dl_info info )
124+ {
125+ if ( RuntimeInformation . IsOSPlatform ( OSPlatform . OSX ) )
126+ {
127+ return DlAddrLibSystem ( addr , out info ) ;
128+ }
129+
130+ try
131+ {
132+ return DlAddrLibc ( addr , out info ) ;
133+ }
134+ catch ( Exception ex ) when ( ex is EntryPointNotFoundException or DllNotFoundException )
135+ {
136+ return DlAddrLibdl ( addr , out info ) ;
137+ }
138+ }
139+
140+ private static nint DlOpen ( nint fileName , int flags )
141+ {
142+ if ( RuntimeInformation . IsOSPlatform ( OSPlatform . OSX ) )
143+ {
144+ return DlOpenLibSystem ( fileName , flags ) ;
145+ }
146+
147+ try
148+ {
149+ return DlOpenLibc ( fileName , flags ) ;
150+ }
151+ catch ( Exception ex ) when ( ex is EntryPointNotFoundException or DllNotFoundException )
152+ {
153+ return DlOpenLibdl ( fileName , flags ) ;
154+ }
155+ }
156+
157+ [ StructLayout ( LayoutKind . Sequential ) ]
158+ private struct Dl_info
159+ {
160+ public nint dli_fname ;
161+ public nint dli_fbase ;
162+ public nint dli_sname ;
163+ public nint dli_saddr ;
164+ }
165+
166+ [ LibraryImport ( "libc.so.6" , EntryPoint = "dladdr" ) ]
167+ private static partial int DlAddrLibc ( nint addr , out Dl_info info ) ;
168+
169+ [ LibraryImport ( "libdl.so.2" , EntryPoint = "dladdr" ) ]
170+ private static partial int DlAddrLibdl ( nint addr , out Dl_info info ) ;
171+
172+ [ LibraryImport ( "libc.so.6" , EntryPoint = "dlopen" ) ]
173+ private static partial nint DlOpenLibc ( nint filename , int flags ) ;
174+
175+ [ LibraryImport ( "libdl.so.2" , EntryPoint = "dlopen" ) ]
176+ private static partial nint DlOpenLibdl ( nint filename , int flags ) ;
177+
178+ [ LibraryImport ( "/usr/lib/libSystem.B.dylib" , EntryPoint = "dladdr" ) ]
179+ private static partial int DlAddrLibSystem ( nint addr , out Dl_info info ) ;
180+
181+ [ LibraryImport ( "/usr/lib/libSystem.B.dylib" , EntryPoint = "dlopen" ) ]
182+ private static partial nint DlOpenLibSystem ( nint filename , int flags ) ;
183+
46184 [ UnmanagedCallersOnly (
47185 EntryPoint = nameof ( napi_register_module_v1 ) ,
48186 CallConvs = new [ ] { typeof ( CallConvCdecl ) } ) ]
49187 public static napi_value InitializeModule ( napi_env env , napi_value exports )
50188 {
51189 Trace ( $ "> NativeHost.InitializeModule({ env . Handle : X8} , { exports . Handle : X8} )") ;
52190
191+ // Ensure this native module stays loaded for the lifetime of the process. See
192+ // PreventModuleUnload() for details on the worker-thread teardown crash this avoids.
193+ PreventModuleUnload ( ) ;
194+
53195 s_jsRuntime ??= new NodejsRuntime ( ) ;
54196
55197 // The native host JSValueScope is not disposed after a successful initialization. It
0 commit comments