Skip to content

Commit ff3062b

Browse files
committed
NativeMethods: setup shutdown handler only when init succeeds
Only set up the object with the `git_libgit2_shutdown` finalizer when `git_libgit2_init` has succeeded. This ensures that setting up the finalizer is the last thing that we do in the static constructor for `NativeMethods`, meaning that any exception trying to p/invoke `git_libgit2_init` remains catch-able.
1 parent b6bac28 commit ff3062b

File tree

1 file changed

+25
-22
lines changed

1 file changed

+25
-22
lines changed

LibGit2Sharp/Core/NativeMethods.cs

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,7 @@ internal static class NativeMethods
1919
// This will handle initialization and shutdown of the underlying
2020
// native library.
2121
#pragma warning disable 0414
22-
private static readonly LibraryLifetimeObject lifetimeObject;
23-
24-
private sealed class LibraryLifetimeObject : CriticalFinalizerObject
25-
{
26-
[MethodImpl(MethodImplOptions.NoInlining)]
27-
public LibraryLifetimeObject()
28-
{
29-
// Configure the OpenSSL locking on the true initialization
30-
// of the library.
31-
if (git_libgit2_init() == 1)
32-
{
33-
git_openssl_set_locking();
34-
}
35-
}
36-
37-
~LibraryLifetimeObject()
38-
{
39-
git_libgit2_shutdown();
40-
}
41-
}
22+
private static readonly NativeShutdownObject shutdownObject;
4223

4324
static NativeMethods()
4425
{
@@ -53,8 +34,30 @@ static NativeMethods()
5334
String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
5435
}
5536

56-
// See LibraryLifetimeObject description.
57-
lifetimeObject = new LibraryLifetimeObject();
37+
LoadNativeLibrary();
38+
shutdownObject = new NativeShutdownObject();
39+
}
40+
41+
// Avoid inlining this method because otherwise mono's JITter may try
42+
// to load the library _before_ we've configured the path.
43+
[MethodImpl(MethodImplOptions.NoInlining)]
44+
private static void LoadNativeLibrary()
45+
{
46+
// Configure the OpenSSL locking on the true initialization
47+
// of the library.
48+
if (git_libgit2_init() == 1)
49+
{
50+
git_openssl_set_locking();
51+
}
52+
}
53+
54+
// Shutdown the native library in a finalizer.
55+
private sealed class NativeShutdownObject : CriticalFinalizerObject
56+
{
57+
~NativeShutdownObject()
58+
{
59+
git_libgit2_shutdown();
60+
}
5861
}
5962

6063
[DllImport(libgit2)]

0 commit comments

Comments
 (0)