8000 NativeMethods: setup shutdown handler only when init succeeds · jiangshengair/libgit2sharp@2d05265 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2d05265

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 57662ac commit 2d05265

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
@@ -22,28 +22,9 @@ internal static partial class NativeMethods
2222
// This will handle initialization and shutdown of the underlying
2323
// native library.
2424
#pragma warning disable 0414
25-
private static readonly LibraryLifetimeObject lifetimeObject;
25+
private static readonly NativeShutdownObject shutdownObject;
2626
#pragma warning restore 0414
2727

28-
private sealed class LibraryLifetimeObject : CriticalFinalizerObject
29-
{
30-
[MethodImpl(MethodImplOptions.NoInlining)]
31-
public LibraryLifetimeObject()
32-
{
33-
// Configure the OpenSSL locking on the true initialization
34-
// of the library.
35-
if (git_libgit2_init() == 1)
36-
{
37-
git_openssl_set_locking();
38-
}
39-
}
40-
41-
~LibraryLifetimeObject()
42-
{
43-
git_libgit2_shutdown();
44-
}
45-
}
46-
4728
static NativeMethods()
4829
{
4930
if (Platform.OperatingSystem == OperatingSystemType.Windows)
@@ -57,8 +38,30 @@ static NativeMethods()
5738
String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
5839
}
5940

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

6467
[DllImport(libgit2)]

0 commit comments

Comments
 (0)
0