Skip to content
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

Enhance YaraContext management with Singleton pattern and exception handling #11

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

sbruyere
Copy link
Contributor

@sbruyere sbruyere commented Jun 30, 2023

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:

  • Implemented Singleton pattern in YaraContext.
  • Added EnsureInitialized method to YaraContext.
  • Added Reinitialize method to YaraContext.

Mentions

Special thanks to @lld1995 for giving more context to this issue.

sbruyere added 2 commits June 30, 2023 14:37
…tance of Yara context is created and used across the application. This prevents multiple initializations and finalizations of the Yara library.

- Added EnsureInitialized method that throws a custom YaraContextNotInitializedException if the Yara context has been cleaned up. This provides a mechanism to check the initialization status of the Yara context before calling native Yara functions.

- Introduced a Reinitialize method to allow reopening of the Yara context if it has been cleaned up.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant