-
Notifications
You must be signed in to change notification settings - Fork 5k
Add hooks to debug OpenSSL memory allocations #111539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
61d9b38
add hooks to debug OpenSSL memory
wfurt ae0b47b
opensslshim
wfurt 3de18d1
1.x
wfurt 32b5b22
1.0.1
wfurt a5ceb86
android
wfurt 04819ad
Collections
wfurt a810556
unsafe
wfurt 83795f2
build
wfurt 04f5bde
feedback
wfurt d9bc610
update
wfurt de0ef7d
feedback
wfurt c0d8f2d
feedback
wfurt 250822d
feedback
wfurt 607b4d7
fix build
wfurt e29aeb1
gcc
wfurt 518446c
gcc
wfurt 860490a
Update src/native/libs/System.Security.Cryptography.Native/openssl.c
wfurt ebcb3d8
Move init to Interop.Crypto
rzikm 918d337
Fix data race on GetIncrementalAllocations
rzikm 23af46f
Use modern tuple type
rzikm 36cd612
Fix typo
rzikm b5e2208
Merge remote-tracking branch 'upstream/main' into openssl-mallloc-deb…
rzikm d310a31
Move functionality to separate file
rzikm 03e0b9c
Revert unnecessary changes
rzikm 051f01c
WIP tracking in native code
rzikm d972e43
Improvements
rzikm 8af851e
Reintroduce rw lock
rzikm ea5cce4
Add readme
rzikm 3924367
Fix build
rzikm 12e2a39
Code review feedback
rzikm efeee1f
code review changes - cont.
rzikm a997064
More code review feedback
rzikm d8c6c71
Expose the "API" via system.security.cryptography
rzikm 2ee91f8
Fix infinite link list traversal
rzikm 938ada9
Fix memory accounting for realloc
rzikm e659676
Refactoring
rzikm f619b76
Improve comments
rzikm 4ef5e7d
Improve Readme
rzikm e64df06
Simplify implementation
rzikm e9cb00d
Don't use CRYPTO_atomic_add
rzikm 1add544
Readme fixes
rzikm 61f7b66
Fix build
rzikm 7b650ee
Fix compilation, attempt 2
rzikm 7cf2283
Fix build - attemt no 3
rzikm 201f945
Apply suggestions from code review
rzikm 86f543b
Feedback
rzikm 7dbede7
Merge branch 'main' into openssl-mallloc-debug-hooks
rzikm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
...libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
# System.Security.Cryptography.Native | ||
|
||
This folder contains C# bindings for native shim (libSystem.Security.Cryptography.Native.OpenSsl.so), shimming functionality provided by the OpenSSL library. | ||
|
||
## Memory allocation hooks | ||
|
||
One extra feature exposed by the native shim is tracking of memory used by | ||
OpenSSL by hooking the memory allocation routines via | ||
`CRYPTO_set_mem_functions`. | ||
|
||
The functionality is enabled by setting | ||
`DOTNET_OPENSSL_MEMORY_DEBUG` to 1. This environment | ||
variable must be set before launching the program (calling | ||
`Environment.SetEnvironmentVariable` at the start of the program is not | ||
sufficient). The diagnostic API is not officially exposed and needs to be | ||
accessed via private reflection on the `Interop.Crypto` type located in the | ||
`System.Security.Cryptography` assembly. On this type, you can use following static | ||
methods: | ||
|
||
- `int GetOpenSslAllocatedMemory()` | ||
- Gets the total amount of memory allocated by OpenSSL | ||
- `int GetOpenSslAllocationCount()` | ||
- Gets the number of allocations made by OpenSSL | ||
- `void EnableMemoryTracking()`/`void DisableMemoryTracking()` | ||
- toggles tracking of individual live allocations via internal data | ||
structures. I.e. will keep track of live memory allocated since the start of | ||
tracking. | ||
- `void ForEachTrackedAllocation(Action<IntPtr, ulong, IntPtr, int> callback)` | ||
- Accepts an callback and calls it for each allocation performed since the | ||
last `EnableMemoryTracking` call. The order of reported information does not | ||
correspond to the order of allocation. This method holds an internal lock | ||
which prevents other threads from allocating any memory from OpenSSL. | ||
- Callback parameters are | ||
- IntPtr - The pointer to the allocated object | ||
- ulong - size of the allocation in bytes | ||
- IntPtr - Pointer to a null-terminated string (`const char*`) containing the name of the file from which the allocation was made. | ||
- int - line number within the file specified by the previous parameter where the allocation was called from. | ||
|
||
The debug functionality brings some overhead (header for each allocation, | ||
locks/synchronization during each allocation) and may cause performance penalty. | ||
|
||
### Example usage | ||
|
||
```cs | ||
// all above mentioned APIs are accessible via "private reflection" | ||
BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static; | ||
var cryptoInterop = typeof(RandomNumberGenerator).Assembly.GetTypes().First(t => t.Name == "Crypto"); | ||
|
||
// enable tracking, this clears up any previously tracked allocations | ||
cryptoInterop.InvokeMember("EnableMemoryTracking", flags, null, null, null); | ||
|
||
// do some work that includes OpenSSL | ||
HttpClient client = new HttpClient(); | ||
await client.GetAsync("https://www.microsoft.com"); | ||
|
||
// stop tracking (this step is optional) | ||
cryptoInterop.InvokeMember("DisableMemoryTracking", flags, null, null, null); | ||
|
||
using var process = Process.GetCurrentProcess(); | ||
Console.WriteLine($"Bytes known to GC [{GC.GetTotalMemory(false)}], process working set [{process.WorkingSet64}]"); | ||
Console.WriteLine("OpenSSL - currently allocated memory: {0} B", cryptoInterop.InvokeMember("GetOpenSslAllocatedMemory", flags, null, null, null)); | ||
Console.WriteLine("OpenSSL - total allocations since start: {0}", cryptoInterop.InvokeMember("GetOpenSslAllocationCount", flags, null, null, null)); | ||
|
||
Dictionary<(IntPtr file, int line), ulong> allAllocations = new(); | ||
Action<IntPtr, ulong, IntPtr, int> callback = (ptr, size, namePtr, line) => | ||
{ | ||
CollectionsMarshal.GetValueRefOrAddDefault(allAllocations, (namePtr, line), out _) += size; | ||
}; | ||
cryptoInterop.InvokeMember("ForEachTrackedAllocation", flags, null, null, [callback]); | ||
|
||
Console.WriteLine("Total allocated OpenSSL memory by location"); | ||
foreach (var ((filenameptr, line), total) in allAllocations.OrderByDescending(kvp => kvp.Value).Take(10)) | ||
{ | ||
string filename = Marshal.PtrToStringUTF8(filenameptr); | ||
Console.WriteLine($"{total:N0} B from {filename}:{line}"); | ||
} | ||
``` |
12 changes: 12 additions & 0 deletions
12
src/libraries/System.Security.Cryptography/src/ILLink/ILLink.Descriptors.LibraryBuild.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<linker> | ||
<assembly fullname="System.Security.Cryptography"> | ||
<type fullname="Interop/Crypto"> | ||
<!-- Debug only APIs to be reachable only via private reflection --> | ||
<method name="GetOpenSslAllocationCount" /> | ||
<method name="GetOpenSslAllocatedMemory" /> | ||
<method name="ForEachTrackedAllocation" /> | ||
<method name="EnableMemoryTracking" /> | ||
<method name="DisableMemoryTracking" /> | ||
</type> | ||
</assembly> | ||
</linker> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.