Enhance YaraContext management with Singleton pattern and exception handling #11
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.
Purpose
This PR addresses an issue related to memory access errors in the dnYara library when used in a C# environment. These errors were due to premature garbage collection of the YaraContext ctx object.
This address issue #10.
Why
The issue arose because the YaraContext object was being collected by the .NET garbage collector before its usage was completed, especially in the Release build where garbage collection can be more aggressive.
What was changed
The YaraContext implementation was restructured to use the Singleton pattern, ensuring a single instance of the Yara context across the application. This change allows the application to maintain a reference to the context, preventing it from being prematurely collected by the GC. Additionally, an EnsureInitialized method was introduced to throw an exception if the context was cleaned up before a native Yara function was called. A Reinitialize method was also added to reopen the Yara context if it has been cleaned up.
Changes made:
Mentions
Special thanks to @lld1995 for giving more context to this issue.