Skip to content

Commit 1764878

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 cfbb3fe commit 1764878

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,28 +19,9 @@ 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;
22+
private static readonly NativeShutdownObject shutdownObject;
2323
#pragma warning restore 0414
2424

25-
private sealed class LibraryLifetimeObject : CriticalFinalizerObject
26-
{
27-
[MethodImpl(MethodImplOptions.NoInlining)]
28-
public LibraryLifetimeObject()
29-
{
30-
// Configure the OpenSSL locking on the true initialization
31-
// of the library.
32-
if (git_libgit2_init() == 1)
33-
{
34-
git_openssl_set_locking();
35-
}
36-
}
37-
38-
~LibraryLifetimeObject()
39-
{
40-
git_libgit2_shutdown();
41-
}
42-
}
43-
4425
static NativeMethods()
4526
{
4627
if (Platform.OperatingSystem == OperatingSystemType.Windows)
@@ -54,8 +35,30 @@ static NativeMethods()
5435
String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
5536
}
5637

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

6164
[DllImport(libgit2)]

0 commit comments

Comments
 (0)