Skip to main content

Compiler

Struct Compiler 

Source
pub struct Compiler<'a> { /* private fields */ }
Expand description

Compiles YARA source code producing a set of compiled Rules.

The two most important methods in this type are Compiler::add_source and Compiler::build. The former tells the compiler which YARA source code must be compiled, and can be called multiple times with different set of rules. The latter consumes the compiler and produces a set of compiled Rules.

§Example

let mut compiler = yara_x::Compiler::new();

compiler
    .add_source(r#"
        rule always_true {
            condition: true
        }"#)?
    .add_source(r#"
        rule always_false {
            condition: false
        }"#)?;

let rules = compiler.build();

Implementations§

Source§

impl<'a> Compiler<'a>

Source

pub fn new() -> Self

Creates a new YARA compiler.

Source

pub fn add_include_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self

Adds a directory to the list of directories where the compiler should look for included files.

When an include statement is found, the compiler looks for the included file in the directories added with this function, in the order they were added.

If this function is not called, the compiler will only look for included files in the current directory.

Use Compiler::enable_includes for controlling whether include statements are allowed or not.

§Example
let mut compiler = Compiler::new();
compiler.add_include_dir("/path/to/rules")
        .add_include_dir("/another/path");
Source

pub fn add_source<'src, S>(&mut self, src: S) -> Result<&mut Self, CompileError>
where S: Into<SourceCode<'src>>,

Adds some YARA source code to be compiled.

The src parameter accepts any type that implements Into<SourceCode>, such as &str, &[u8], or an instance of SourceCode itself. The source code may include one or more YARA rules.

You can call this function multiple times to add different sets of rules. If the provided source code contains syntax or semantic errors that prevent compilation, the function returns the first encountered error. All errors found during compilation are also recorded and can be retrieved using Compiler::errors.

Even if previous calls to this function resulted in compilation errors, you may continue adding additional rules. Only successfully compiled rules will be included in the final rule set.

Source

pub fn define_global<T: TryInto<Variable>>( &mut self, ident: &str, value: T, ) -> Result<&mut Self, VariableError>

Defines a global variable and sets its initial value.

Global variables must be defined before adding any YARA source code that references them via Compiler::add_source. Once defined, the variable’s initial value is preserved in the compiled Rules and will be used unless overridden.

When scanning, each scanner instance can modify the initial value of the variable using crate::Scanner::set_global.

T can be any type that implements TryInto<Variable>, including: i64, i32, i16, i8, u32, u16, u8, f64, f32, bool, &str, String and serde_json::Value.

When using a serde_json::Value there are certain limitations: keys in maps must be valid YARA identifiers (the first character must be _ or a letter, the remaining ones must be _, a letter or a digit), because these maps are translated into YARA structures. Also, all items in an array must have the same type.

assert!(Compiler::new()
    .define_global("some_int", 1)?
    .add_source("rule some_int_not_zero {condition: some_int != 0}")
    .is_ok());
Source

pub fn new_namespace(&mut self, namespace: &str) -> &mut Self

Creates a new namespace.

Further calls to Compiler::add_source will put the rules under the newly created namespace. If the new namespace is named as the current one, no new namespace is created.

In the example below both rules foo and bar are put into the same namespace (the default namespace), therefore bar can use foo as part of its condition, and everything is ok.

assert!(Compiler::new()
    .add_source("rule foo {condition: true}")?
    .add_source("rule bar {condition: foo}")
    .is_ok());

In this other example the rule foo is put in the default namespace, but the rule bar is put under the bar namespace. This implies that foo is not visible to bar, and the second call to add_source fails.

assert!(Compiler::new()
    .add_source("rule foo {condition: true}")?
    .new_namespace("bar")
    .add_source("rule bar {condition: foo}")
    .is_err());
Source

pub fn build(self) -> Rules

Builds the source code previously added to the compiler.

This function consumes the compiler and returns an instance of Rules.

Source

pub fn add_linter<L: Linter + 'a>(&mut self, linter: L) -> &mut Self

Adds a linter to the compiler.

Linters perform additional checks to each YARA rule, generating warnings when a rule does not meet the linter’s requirements. See crate::linters for a list of available linters.

Source

pub fn ignore_module<M: Into<String>>(&mut self, module: M) -> &mut Self

Tell the compiler that a YARA module is not supported.

Import statements for ignored modules will be ignored without errors, but a warning will be issued. Any rule that makes use of an ignored module will be also ignored, while the rest of the rules that don’t rely on that module will be correctly compiled.

Source

pub fn ban_module<M: Into<String>, T: Into<String>, E: Into<String>>( &mut self, module: M, error_title: T, error_message: E, ) -> &mut Self

Tell the compiler that a YARA module can’t be used.

Import statements for the banned module will cause an error. The error message can be customized by using the given error title and message.

If this function is called multiple times with the same module name, the error title and message will be updated.

Source

pub fn colorize_errors(&mut self, yes: bool) -> &mut Self

Specifies whether the compiler should produce colorful error messages.

Colorized error messages contain ANSI escape sequences that make them look nicer on compatible consoles.

The default setting is false.

Source

pub fn errors_max_width(&mut self, width: usize) -> &mut Self

Sets the maximum number of columns in error messages.

The default value is 140.

Source

pub fn switch_warning( &mut self, code: &str, enabled: bool, ) -> Result<&mut Self, InvalidWarningCode>

Enables or disables a specific type of warning.

Each warning type has a description code (i.e: slow_pattern, unsupported_module, etc.). This function allows to enable or disable a specific type of warning identified by the given code.

Returns an error if the given warning code doesn’t exist.

Source

pub fn switch_all_warnings(&mut self, enabled: bool) -> &mut Self

Enables or disables all warnings.

Source

pub fn relaxed_re_syntax(&mut self, yes: bool) -> &mut Self

Enables a more relaxed syntax check for regular expressions.

YARA-X enforces stricter regular expression syntax compared to YARA. For instance, YARA accepts invalid escape sequences and treats them as literal characters (e.g., \R is interpreted as a literal ‘R’). It also allows some special characters to appear unescaped, inferring their meaning from the context (e.g., { and } in /foo{}bar/ are literal, but in /foo{0,1}bar/ they form the repetition operator {0,1}).

This setting controls whether the compiler should mimic YARA’s behavior, allowing constructs that YARA-X doesn’t accept by default.

This should be called before any rule is added to the compiler.

§Panics

If called after adding rules to the compiler.

Source

pub fn error_on_slow_pattern(&mut self, yes: bool) -> &mut Self

When enabled, slow patterns produce an error instead of a warning.

This is disabled by default.

Source

pub fn error_on_slow_loop(&mut self, yes: bool) -> &mut Self

When enabled, potentially slow loops produce an error instead of a warning.

This is disabled by default.

Source

pub fn enable_includes(&mut self, yes: bool) -> &mut Self

Controls whether include statements are allowed.

By default, the compiler allows the use of include statements, which include the content of other files. When includes are disabled, any attempt to use an include statement will result in a compile error.

let mut compiler = Compiler::new();
compiler.enable_includes(false);  // Disable includes
Source

pub fn errors(&self) -> &[CompileError]

Retrieves all errors generated by the compiler.

This method returns every error encountered during the compilation, across all invocations of Compiler::add_source.

Source

pub fn warnings(&self) -> &[Warning]

Returns the warnings emitted by the compiler.

This method returns every warning issued during the compilation, across all invocations of Compiler::add_source.

Source

pub fn emit_wasm_file<P>(self, path: P) -> Result<(), EmitWasmError>
where P: AsRef<Path>,

Emits a .wasm file with the WASM module generated by the compiler.

This file can be inspected and converted to WASM text format by using third-party tooling. This is useful for debugging issues with incorrectly emitted WASM code.

Trait Implementations§

Source§

impl Debug for Compiler<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Compiler<'_>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<'a> !Freeze for Compiler<'a>

§

impl<'a> !RefUnwindSafe for Compiler<'a>

§

impl<'a> !Send for Compiler<'a>

§

impl<'a> !Sync for Compiler<'a>

§

impl<'a> Unpin for Compiler<'a>

§

impl<'a> UnsafeUnpin for Compiler<'a>

§

impl<'a> !UnwindSafe for Compiler<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V