Fix eager native SNI initialization on non-Windows platforms - #4700
shreyarao4 wants to merge 1 commit into
Conversation
Fixes a crash where SNILoadHandle's native SNI initialization (SniInitialize(), Windows-only) can run on non-Windows platforms, throwing DllNotFoundException
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
That load behaviour is very eager - the code paths are unreachable as a result of |
|
I have not verified on any other platforms, but please note this is using Mono runtime. dotnet/runtime#77513 confirms this behavior on Mono. Mono eagerly runs a beforefieldinit type's static constructor even when the accessing code path is never taken. |
|
/azp run |
|
Azure Pipelines: Successfully started running 2 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4700 +/- ##
==========================================
- Coverage 66.21% 64.33% -1.89%
==========================================
Files 290 285 -5
Lines 45063 68064 +23001
==========================================
+ Hits 29838 43788 +13950
- Misses 15225 24276 +9051
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Description
After #4465, the same SqlClient code is built for both Windows and non-Windows platforms, with native or managed SNI selected at runtime.
SNILoadHandle contains a static singleton:
internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();Because SNILoadHandle has no explicit static constructor, its treated as beforefieldinit. This allows the runtime to initialize the type before SingletonInstance is actually accessed.
The SNILoadHandle constructor calls the Windows-only native SNI initialization:
SniNativeWrapper.SniInitialize();On non-Windows platforms, managed SNI is selected and SNILoadHandle should not be initialized. However, because of beforefieldinit, the runtime can initialize SNILoadHandle merely because it is referenced by JIT-compiled code.
This causes the Windows-only native SNI library to be loaded on non-Windows platforms and results in the following DllNotFoundException.
Solution
Added an explicit static constructor to SNILoadHandle.
This removes the beforefieldinit behavior and ensures that static initialization happens only when SNILoadHandle is actually accessed.
Therefore, on Linux, SNILoadHandle is not initialized when the managed SNI path is selected, and the Windows-only native SNI library is never loaded.
Testing
Verified on Linux/s390x: ManualTests previously crashed with the DllNotFoundException above; after this change, tests run sucessfully.
Environment
Linux s390x
Mono runtime
@giritrivedi