VirusTotal / yara-x

A rewrite of YARA in Rust.
https://virustotal.github.io/yara-x/
BSD 3-Clause "New" or "Revised" License
631 stars 50 forks source link

How can I put a Scanner inside a struct, are there any examples to learn from? #139

Closed xvsfekcn closed 3 months ago

xvsfekcn commented 3 months ago

During the development of a detection engine based on yara-x in Rust, I encountered a lifetime issue because the scanner depends on a reference to rules, but I want to put the scanner inside a struct. How should this be implemented? Are there any corresponding examples to learn from?

latonis commented 3 months ago

I am not sure where you're encountering the lifetime issues without seeing the code, but here is an example that places the Scanner into a struct with named lifetime parameters.

use yara_x::Scanner;

struct NestedScanner<'a> {
    inner_scanner: yara_x::Scanner<'a>,
}

fn test_function(scanner_struct: &mut NestedScanner) {
    let result = scanner_struct.inner_scanner.scan(b"test");
    println!("{} rules matched", result.unwrap().matching_rules().len());
}

fn test_function_two(scanner_struct: &mut NestedScanner) {
    let result = scanner_struct.inner_scanner.scan(b"test");
    println!("{} rules not matched", result.unwrap().non_matching_rules().len());
}

fn main() {
    let mut compiler = yara_x::Compiler::new();

    compiler
        .add_source(
            r#"
        rule always_true {
            condition: true
        }"#,
        )
        .expect("Rule should've added without issue")
        .add_source(
            r#"
        rule always_false {
            condition: false
        }"#,
        )
        .expect("Rule should've added without issue");

    let rules = compiler.build();

    let scanner = Scanner::new(&rules);

    let mut ns = NestedScanner {
        inner_scanner: scanner,
    };

    test_function(&mut ns);
    test_function_two(&mut ns);
}
plusvic commented 3 months ago

@xvsfekcn, you may find lifetime issues if you are trying to put both the rules and the scanner inside the same structure, because the scanner references the rules. That's a self-referential struct, and they are problematic in Rust. If that's your problem, you may find more information if you search for "rust self-referential structs" in Google.

plusvic commented 3 months ago

I'm closing the issue because it doesn't look like a real issue, but feel to provide more information about your use case here and I'll try to help you as much as I can.