yara-x-capi 1.17.0

A C API for the YARA-X library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
use std::collections::HashMap;
use std::ffi::CString;
use std::ffi::{CStr, c_char, c_void};
use std::mem;
use std::time::Duration;

#[cfg(feature = "rules-profiling")]
use yara_x::ProfilingData;

use yara_x::ScanOptions;
use yara_x::errors::ScanError;

use crate::{
    _yrx_set_last_error, YRX_RESULT, YRX_RULE, YRX_RULE_CALLBACK, YRX_RULES,
};

enum InnerScanner<'r> {
    None,
    SingleBlock(yara_x::Scanner<'r>),
    MultiBlock(yara_x::blocks::Scanner<'r>),
}

impl<'r> InnerScanner<'r> {
    fn set_timeout(&mut self, duration: Duration) -> &mut Self {
        match self {
            InnerScanner::SingleBlock(s) => {
                s.set_timeout(duration);
            }
            InnerScanner::MultiBlock(s) => {
                s.set_timeout(duration);
            }
            InnerScanner::None => unreachable!(),
        }
        self
    }

    fn fast_scan(&mut self, yes: bool) -> &mut Self {
        match self {
            InnerScanner::SingleBlock(s) => {
                s.fast_scan(yes);
            }
            InnerScanner::MultiBlock(s) => {
                s.fast_scan(yes);
            }
            InnerScanner::None => unreachable!(),
        }
        self
    }

    fn make_multi_block(&mut self) -> &mut yara_x::blocks::Scanner<'r> {
        // Already a multi-block scanner, nothing else to do.
        if let Self::MultiBlock(s) = self {
            return s;
        }
        // It's currently a single-block scanner, replace it with a multi-block
        // scanner.
        if let Self::SingleBlock(s) = mem::replace(self, InnerScanner::None) {
            *self = InnerScanner::MultiBlock(s.into());
        }
        // At this point it must be a multi-block scanner.
        match self {
            InnerScanner::MultiBlock(s) => s,
            _ => unreachable!(),
        }
    }

    fn set_global<T>(
        &mut self,
        ident: &str,
        value: T,
    ) -> Result<&mut Self, yara_x::errors::VariableError>
    where
        T: TryInto<yara_x::Variable, Error = yara_x::errors::VariableError>,
    {
        match self {
            InnerScanner::SingleBlock(s) => {
                s.set_global(ident, value)?;
            }
            InnerScanner::MultiBlock(s) => {
                s.set_global(ident, value)?;
            }
            InnerScanner::None => unreachable!(),
        }
        Ok(self)
    }

    #[cfg(feature = "rules-profiling")]
    fn slowest_rules(&self, n: usize) -> Vec<ProfilingData<'_>> {
        match self {
            InnerScanner::SingleBlock(s) => s.slowest_rules(n),
            InnerScanner::MultiBlock(s) => s.slowest_rules(n),
            InnerScanner::None => unreachable!(),
        }
    }

    #[cfg(feature = "rules-profiling")]
    fn clear_profiling_data(&mut self) {
        match self {
            InnerScanner::SingleBlock(s) => s.clear_profiling_data(),
            InnerScanner::MultiBlock(s) => s.clear_profiling_data(),
            InnerScanner::None => unreachable!(),
        }
    }
}

/// A scanner that scans data with a set of compiled YARA rules.
pub struct YRX_SCANNER<'r, 'm> {
    inner: InnerScanner<'r>,
    on_matching_rule: Option<(YRX_RULE_CALLBACK, *mut c_void)>,
    module_data: HashMap<&'m str, &'m [u8]>,
}

/// Creates a [`YRX_SCANNER`] object that can be used for scanning data with
/// the provided [`YRX_RULES`].
///
/// It's ok to pass the same [`YRX_RULES`] to multiple scanners, and use each
/// scanner from a different thread. The scanner can be used as many times as
/// you want, and it must be destroyed with [`yrx_scanner_destroy`]. Also, the
/// scanner is valid as long as the rules are not destroyed, so, always destroy
/// the [`YRX_SCANNER`] object before the [`YRX_RULES`] object.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_create(
    rules: *const YRX_RULES,
    scanner: &mut *mut YRX_SCANNER,
) -> YRX_RESULT {
    let rules = if let Some(rules) = rules.as_ref() {
        rules
    } else {
        return YRX_RESULT::YRX_INVALID_ARGUMENT;
    };

    *scanner = Box::into_raw(Box::new(YRX_SCANNER {
        inner: InnerScanner::SingleBlock(yara_x::Scanner::new(rules.inner())),
        on_matching_rule: None,
        module_data: HashMap::new(),
    }));

    YRX_RESULT::YRX_SUCCESS
}

/// Destroys a [`YRX_SCANNER`] object.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_destroy(scanner: *mut YRX_SCANNER) {
    drop(Box::from_raw(scanner))
}

/// Sets a timeout (in seconds) for scan operations.
///
/// The scan functions will return a timeout error once the provided timeout
/// duration has elapsed. The scanner will make every effort to stop promptly
/// after the designated timeout duration. However, in some cases, particularly
/// with rules containing only a few patterns, the scanner could potentially
/// continue running for a longer period than the specified timeout.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_timeout(
    scanner: *mut YRX_SCANNER,
    timeout: u64,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    scanner.inner.set_timeout(Duration::from_secs(timeout));

    YRX_RESULT::YRX_SUCCESS
}

/// Enables or disables fast scan mode for the scanner.
///
/// In fast scan mode, the scanner avoids tracking matches for patterns when it
/// is not necessary (e.g. when a rule condition only performs a simple boolean
/// check `$a`).
///
/// Note that using fast scan mode implies that not all matches will be
/// reported. For instance, when iterating matches using [`ScanResults`],
/// you won't get all occurrences of the pattern in the file, only the first
/// one.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_fast_scan(
    scanner: *mut YRX_SCANNER,
    yes: bool,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    scanner.inner.fast_scan(yes);

    YRX_RESULT::YRX_SUCCESS
}

/// Scans a data buffer.
///
/// `data` can be null as long as `len` is 0. In such cases its handled as
/// empty data. Some YARA rules (i.e: `rule dummy { condition: true }`) can
/// match even with empty data.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_scan(
    scanner: *mut YRX_SCANNER,
    data: *const u8,
    len: usize,
) -> YRX_RESULT {
    _yrx_set_last_error::<ScanError>(None);

    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let data = match slice_from_ptr_and_len(data, len) {
        Some(data) => data,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let options = scanner
        .module_data
        .drain()
        .fold(ScanOptions::new(), |acc, (module_name, meta)| {
            acc.set_module_metadata(module_name, meta)
        });

    let scan_results = match &mut scanner.inner {
        InnerScanner::SingleBlock(s) => s.scan_with_options(data, options),
        InnerScanner::MultiBlock(_) => return YRX_RESULT::YRX_INVALID_STATE,
        InnerScanner::None => unreachable!(),
    };

    match scan_results {
        Ok(results) => {
            if let Some((callback, user_data)) = scanner.on_matching_rule {
                for r in results.matching_rules() {
                    callback(&YRX_RULE::new(r), user_data);
                }
            }
            YRX_RESULT::YRX_SUCCESS
        }
        Err(ScanError::Timeout) => {
            _yrx_set_last_error(Some(ScanError::Timeout));
            YRX_RESULT::YRX_SCAN_TIMEOUT
        }
        Err(err) => {
            _yrx_set_last_error(Some(err));
            YRX_RESULT::YRX_SCAN_ERROR
        }
    }
}

/// Scans a file.
///
/// This function is similar to `yrx_scanner_scan`, but it receives a file
/// path instead of data to be scanned.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_scan_file(
    scanner: *mut YRX_SCANNER,
    path: *const c_char,
) -> YRX_RESULT {
    _yrx_set_last_error::<ScanError>(None);

    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let path = match str_from_ptr(path) {
        Ok(path) => path,
        Err(err) => return err,
    };

    let options = scanner
        .module_data
        .drain()
        .fold(ScanOptions::new(), |acc, (module_name, meta)| {
            acc.set_module_metadata(module_name, meta)
        });

    let scan_results = match &mut scanner.inner {
        InnerScanner::SingleBlock(s) => {
            s.scan_file_with_options(path, options)
        }
        InnerScanner::MultiBlock(_) => return YRX_RESULT::YRX_INVALID_STATE,
        InnerScanner::None => unreachable!(),
    };

    match scan_results {
        Ok(results) => {
            if let Some((callback, user_data)) = scanner.on_matching_rule {
                for r in results.matching_rules() {
                    callback(&YRX_RULE::new(r), user_data);
                }
            }
            YRX_RESULT::YRX_SUCCESS
        }
        Err(ScanError::Timeout) => {
            _yrx_set_last_error(Some(ScanError::Timeout));
            YRX_RESULT::YRX_SCAN_TIMEOUT
        }
        Err(err) => {
            _yrx_set_last_error(Some(err));
            YRX_RESULT::YRX_SCAN_ERROR
        }
    }
}

/// Scans a block of data.
///
/// This function is designed for scenarios where the data to be scanned is not
/// available as a single contiguous block of memory, but rather arrives in
/// smaller, discrete blocks, allowing for incremental scanning.
///
/// Each call to this function scans a block of data. The `base` argument
/// specifies the offset of the current block within the overall data being
/// scanned. In most cases you will want to call this function multiple times,
/// providing a different block on each call.
///
/// Once this function is called for a scanner, it enters block scanning mode
/// and any subsequent call to [`yrx_scanner_scan`] will fail with
/// [`YRX_RESULT::YRX_INVALID_STATE`]. Once the scanner is in block scanning
/// mode it can be used in that mode only.
///
/// When all blocks have been scanned, you must call [`yrx_scanner_finish`].
///
/// # Limitations of Block Scanning
///
/// Block scanning works by analyzing data in chunks rather than as a whole
/// file. This makes it useful for streaming or memory-constrained scenarios,
/// but it comes with important limitations compared to standard scanning:
///
/// 1) Modules won't work. Parsers for structured formats (e.g., PE, ELF)
///    require access to the entire file and cannot be applied in block
///    scanning mode.
/// 2) Other modules like `hash` won't work either, as they require access to
///    all the scanned data during the evaluation of the rule's condition,
///    something that can't be guaranteed in block scanning mode. The hash
///    functions will return `undefined` when used in a multi-block context.
/// 3) Built-in functions like `uint8`, `uint16`, `uint32`, etc., have the
///    same limitation. They also return `undefined` in block scanning mode.
/// 4) The `filesize` keyword returns `undefined` in block scanning mode.
/// 5) Patterns won't match across block boundaries. Every match will be
///    completely contained within one of the blocks.
///
/// All these limitations imply that in block scanning mode you should only
/// use rules that rely on text, hex or regex patterns.
///
/// # Data Consistency in Overlapping Blocks
///
/// When [`yrx_scanner_scan_block`] is invoked multiple times with different
/// blocks that may overlap, the user is responsible for ensuring data
/// consistency. This means that if the same region of the original data is
/// present in two or more overlapping blocks, the content of that region must
/// be identical across all calls to `scan`.
///
/// Generally speaking, the scanner does not verify this consistency and
/// assumes the user provides accurate and consistent data. In debug releases
/// the scanner may try to verify this consistency, but only when some pattern
/// matches in the overlapping region.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_scan_block(
    scanner: *mut YRX_SCANNER,
    base: usize,
    data: *const u8,
    len: usize,
) -> YRX_RESULT {
    _yrx_set_last_error::<ScanError>(None);

    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let data = match slice_from_ptr_and_len(data, len) {
        Some(data) => data,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    match scanner.inner.make_multi_block().scan(base, data) {
        Ok(_) => YRX_RESULT::YRX_SUCCESS,
        Err(ScanError::Timeout) => {
            _yrx_set_last_error(Some(ScanError::Timeout));
            YRX_RESULT::YRX_SCAN_TIMEOUT
        }
        Err(err) => {
            _yrx_set_last_error(Some(err));
            YRX_RESULT::YRX_SCAN_ERROR
        }
    }
}

/// Finalizes the scan of a set of memory blocks.
///
/// This function must be used in conjunction with [`yrx_scanner_scan_block`]
/// when scanning data in blocks. After all data blocks have been scanned, this
/// functions evaluates the conditions of the YARA rules and produces the final
/// scan results.
///
/// After this function returns, the scanner is ready to be used again for
/// scanning a new set of memory blocks. However, the scanner remains in block
/// scanning mode and can't be used for normal scanning.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_finish(
    scanner: *mut YRX_SCANNER,
) -> YRX_RESULT {
    _yrx_set_last_error::<ScanError>(None);

    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    match scanner.inner.make_multi_block().finish() {
        Ok(results) => {
            if let Some((callback, user_data)) = scanner.on_matching_rule {
                for r in results.matching_rules() {
                    callback(&YRX_RULE::new(r), user_data);
                }
            }
            YRX_RESULT::YRX_SUCCESS
        }
        Err(ScanError::Timeout) => {
            _yrx_set_last_error(Some(ScanError::Timeout));
            YRX_RESULT::YRX_SCAN_TIMEOUT
        }
        Err(err) => {
            _yrx_set_last_error(Some(err));
            YRX_RESULT::YRX_SCAN_ERROR
        }
    }
}

/// Sets a callback function that is called by the scanner for each rule that
/// matched during a scan.
///
/// The `user_data` pointer can be used to provide additional context to your
/// callback function. If the callback is not set, the scanner doesn't notify
/// about matching rules.
///
/// See [`YRX_RULE_CALLBACK`] for more details.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_on_matching_rule(
    scanner: *mut YRX_SCANNER,
    callback: YRX_RULE_CALLBACK,
    user_data: *mut std::ffi::c_void,
) -> YRX_RESULT {
    if let Some(scanner) = scanner.as_mut() {
        scanner.on_matching_rule = Some((callback, user_data));
        YRX_RESULT::YRX_SUCCESS
    } else {
        YRX_RESULT::YRX_INVALID_ARGUMENT
    }
}

/// Specifies the output data structure for a module.
///
/// Each YARA module generates an output consisting of a data structure that
/// contains information about the scanned file. This data structure is represented
/// by a Protocol Buffer. Typically, you won't need to provide this output data
/// yourself, as the YARA module automatically generates different outputs for
/// each file it scans.
///
/// However, there are two scenarios in which you may want to provide the output
/// for a module yourself:
///
/// 1) When the module does not produce any output on its own.
/// 2) When you already know the output of the module for the upcoming file to
///    be scanned, and you prefer to reuse this data instead of generating it
///    again.
///
/// Case 1) applies to certain modules lacking a main function, thus incapable of
/// producing any output on their own. For such modules, you must set the output
/// before scanning the associated data. Since the module's output typically varies
/// with each scanned file, you need to call [yrx_scanner_set_module_output] prior
/// to each invocation of [yrx_scanner_scan]. Once [yrx_scanner_scan] is executed,
/// the module's output is consumed and will be empty unless set again before the
/// subsequent call.
///
/// Case 2) applies when you have previously stored the module's output for certain
/// scanned data. In such cases, when rescanning the data, you can utilize this
/// function to supply the module's output, thereby preventing redundant computation
/// by the module. This optimization enhances performance by eliminating the need
/// for the module to reparse the scanned data.
///
/// The `name` argument is either a YARA module name (i.e: "pe", "elf", "dotnet",
/// etc.) or the fully-qualified name of the protobuf message associated to
/// the module. It must be a valid UTF-8 string.
///
/// If the scanner is in block scanning mode this function returns `YRX_INVALID_STATE`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_module_output(
    scanner: *mut YRX_SCANNER,
    name: *const c_char,
    data: *const u8,
    len: usize,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let module_name = match str_from_ptr(name) {
        Ok(module_name) => module_name,
        Err(err) => return err,
    };

    let data = match slice_from_ptr_and_len(data, len) {
        Some(data) => data,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    match &mut scanner.inner {
        InnerScanner::SingleBlock(scanner) => {
            match scanner.set_module_output_raw(module_name, data) {
                Ok(_) => {
                    _yrx_set_last_error::<ScanError>(None);
                    YRX_RESULT::YRX_SUCCESS
                }
                Err(err) => {
                    _yrx_set_last_error(Some(err));
                    YRX_RESULT::YRX_SCAN_ERROR
                }
            }
        }
        // This function produces an error if invoked while the scanner
        // is in block scanning mode.
        InnerScanner::MultiBlock(_) => YRX_RESULT::YRX_INVALID_STATE,
        InnerScanner::None => unreachable!(),
    }
}

/// Specifies metadata for a module.
///
/// Since the module's output typically varies with each scanned file, you need to
/// call [yrx_scanner_set_module_data] prior to each invocation of
/// [yrx_scanner_scan]. Once [yrx_scanner_scan] is executed, the module's metadata
/// is consumed and will be empty unless set again before the subsequent call.
///
/// The `name` argument is the name of a YARA module. It must be a valid UTF-8 string.
///
/// The `name` as well as `data` must be valid from the time they are used as arguments
/// of this function until the scan is executed.
///
/// If the scanner is in block scanning mode this function returns `YRX_INVALID_STATE`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_module_data(
    scanner: *mut YRX_SCANNER,
    name: *const c_char,
    data: *const u8,
    len: usize,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let name = match str_from_ptr(name) {
        Ok(name) => name,
        Err(err) => return err,
    };

    let data = match slice_from_ptr_and_len(data, len) {
        Some(data) => data,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    if matches!(scanner.inner, InnerScanner::MultiBlock(_)) {
        return YRX_RESULT::YRX_INVALID_STATE;
    }

    scanner.module_data.insert(name, data);

    YRX_RESULT::YRX_SUCCESS
}

unsafe extern "C" fn yrx_scanner_set_global<
    T: TryInto<yara_x::Variable, Error = yara_x::errors::VariableError>,
>(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: T,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let ident = match str_from_ptr(ident) {
        Ok(ident) => ident,
        Err(err) => return err,
    };

    match scanner.inner.set_global(ident, value) {
        Ok(_) => {
            _yrx_set_last_error::<ScanError>(None);
            YRX_RESULT::YRX_SUCCESS
        }
        Err(err) => {
            _yrx_set_last_error(Some(err));
            YRX_RESULT::YRX_VARIABLE_ERROR
        }
    }
}

/// Sets the value of a global variable of type string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_global_str(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: *const c_char,
) -> YRX_RESULT {
    match str_from_ptr(value) {
        Ok(value) => yrx_scanner_set_global(scanner, ident, value),
        Err(err) => err,
    }
}

/// Sets the value of a global variable of type bool.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_global_bool(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: bool,
) -> YRX_RESULT {
    yrx_scanner_set_global(scanner, ident, value)
}

/// Sets the value of a global variable of type int.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_global_int(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: i64,
) -> YRX_RESULT {
    yrx_scanner_set_global(scanner, ident, value)
}

/// Sets the value of a global variable of type float.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_global_float(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: f64,
) -> YRX_RESULT {
    yrx_scanner_set_global(scanner, ident, value)
}

/// Sets the value of a global variable from a JSON-encoded string.
///
/// This is best for complex types like maps and arrays. For simple types
/// (e.g., booleans, integers, strings), prefer dedicated functions to avoid
/// the overhead of JSON deserialization.
///
/// The type of the JSON-encoded value must match the type of the variable
/// as it was defined.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_set_global_json(
    scanner: *mut YRX_SCANNER,
    ident: *const c_char,
    value: *const c_char,
) -> YRX_RESULT {
    let value = match str_from_ptr(value) {
        Ok(value) => value,
        Err(err) => return err,
    };

    let value: serde_json::Value = match serde_json::from_str(value) {
        Ok(json_value) => json_value,
        Err(_) => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    yrx_scanner_set_global(scanner, ident, value)
}

/// Callback function used when a YARA rule calls the console module.
///
/// The callback function is invoked with a string representing the message
/// being logged. The function can print the message to stdout, append it to a
/// file, etc. If no callback is set these messages are ignored.
pub type YRX_CONSOLE_CALLBACK = extern "C" fn(message: *const c_char) -> ();

/// Sets the callback for console module.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn yrx_scanner_on_console_log(
    scanner: *mut YRX_SCANNER,
    callback: YRX_CONSOLE_CALLBACK,
) -> YRX_RESULT {
    let scanner = match scanner.as_mut() {
        Some(s) => s,
        None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
    };

    let wrapper = move |message: String| {
        let msg = CString::new(message).unwrap();
        callback(msg.as_ptr());
    };

    match &mut scanner.inner {
        InnerScanner::SingleBlock(s) => {
            s.console_log(wrapper);
        }
        InnerScanner::MultiBlock(s) => {
            s.console_log(wrapper);
        }
        InnerScanner::None => unreachable!(),
    }

    YRX_RESULT::YRX_SUCCESS
}

/// Callback function passed to [`yrx_scanner_iter_slowest_rules`].
///
/// The callback function receives pointers to the namespace and rule name,
/// and two float numbers with the time spent by the rule matching patterns
/// and executing its condition. The pointers are valid as long as the callback
/// function is being executed, but will be freed after the callback returns.
///
/// The callback also receives a `user_data` pointer that can point to arbitrary
/// data owned by the user.
///
/// Requires the `rules-profiling` feature.
pub type YRX_SLOWEST_RULES_CALLBACK = extern "C" fn(
    namespace_: *const c_char,
    rule: *const c_char,
    pattern_matching_time: f64,
    condition_exec_time: f64,
    user_data: *mut c_void,
) -> ();

/// Iterates over the slowest N rules, calling the callback for each rule.
///
/// Requires the `rules-profiling` feature, otherwise returns
/// `YRX_RESULT::NOT_SUPPORTED`.
///
/// See [`YRX_SLOWEST_RULES_CALLBACK`] for more details.
#[unsafe(no_mangle)]
#[allow(unused_variables)]
pub unsafe extern "C" fn yrx_scanner_iter_slowest_rules(
    scanner: *mut YRX_SCANNER,
    n: usize,
    callback: YRX_SLOWEST_RULES_CALLBACK,
    user_data: *mut c_void,
) -> YRX_RESULT {
    #[cfg(not(feature = "rules-profiling"))]
    return YRX_RESULT::YRX_NOT_SUPPORTED;

    #[cfg(feature = "rules-profiling")]
    {
        let scanner = match scanner.as_ref() {
            Some(s) => s,
            None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
        };

        for profiling_info in scanner.inner.slowest_rules(n) {
            let namespace = CString::new(profiling_info.namespace).unwrap();
            let rule = CString::new(profiling_info.rule).unwrap();

            callback(
                namespace.as_ptr(),
                rule.as_ptr(),
                profiling_info.pattern_matching_time.as_secs_f64(),
                profiling_info.condition_exec_time.as_secs_f64(),
                user_data,
            );
        }

        YRX_RESULT::YRX_SUCCESS
    }
}

/// Clears all accumulated profiling data.
///
/// This resets the profiling data collected during rule execution across
/// scanned files. Use this to start a new profiling session, ensuring the
/// results reflect only the data gathered after this method is called.
///
/// Requires the `rules-profiling` feature, otherwise returns
/// `YRX_RESULT::NOT_SUPPORTED`.
///
#[unsafe(no_mangle)]
#[allow(unused_variables)]
pub unsafe extern "C" fn yrx_scanner_clear_profiling_data(
    scanner: *mut YRX_SCANNER,
) -> YRX_RESULT {
    #[cfg(not(feature = "rules-profiling"))]
    return YRX_RESULT::YRX_NOT_SUPPORTED;

    #[cfg(feature = "rules-profiling")]
    {
        match scanner.as_mut() {
            Some(s) => s.inner.clear_profiling_data(),
            None => return YRX_RESULT::YRX_INVALID_ARGUMENT,
        };

        YRX_RESULT::YRX_SUCCESS
    }
}

unsafe fn slice_from_ptr_and_len<'a>(
    data: *const u8,
    len: usize,
) -> Option<&'a [u8]> {
    // `data` is allowed to be null as long as `len` is 0. That's equivalent
    // to an empty slice.
    if data.is_null() && len > 0 {
        return None;
    }
    let data = if data.is_null() || len == 0 {
        &[]
    } else {
        std::slice::from_raw_parts(data, len)
    };
    Some(data)
}

unsafe fn str_from_ptr<'a>(s: *const c_char) -> Result<&'a str, YRX_RESULT> {
    match CStr::from_ptr(s).to_str() {
        Ok(s) => Ok(s),
        Err(err) => {
            _yrx_set_last_error(Some(err));
            Err(YRX_RESULT::YRX_INVALID_UTF8)
        }
    }
}