yara-x 1.15.0

A pure Rust implementation of YARA.
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
/*! WASM runtime

During the compilation process the condition associated to each YARA rule is
translated into WebAssembly (WASM) code. Depending on the selected target, this
code is later executed either by embedded [wasmtime](https://wasmtime.dev/) or
by YARA-X's browser-oriented custom WASM runtime shim.

For each instance of [`crate::compiler::Rules`] the compiler creates a WASM
module. This WASM module works in close collaboration with YARA's Rust code for
evaluating the rule's conditions. For example, the WASM module exports a
function called `main`, which contains the code that evaluates the conditions
of all the compiled rules. This WASM function is called by YARA at scan time,
and the WASM code calls back the Rust [`rule_match`] function for notifying
YARA about matching rules. The WASM module calls Rust functions in many other
cases, for example when it needs to call YARA built-in functions like
`uint8(...)`, or functions implemented by YARA modules.

WASM and Rust code also share information via WASM global variables and by
sharing memory. For example, the value for YARA's `filesize` keyword is
stored in a WASM global variable that is initialized by Rust code, and read
by WASM code when `filesize` is used in the condition.

# Memory layout

The memory of these WASM modules is organized as follows.

```text
  ┌──────────────────────────┐ 0
  │ Variable undefined flags │
  ├──────────────────────────┤ VARS_STACK_START
  │ Variable #0              │
  │ Variable #1              │
  : ...                      :
  │ Variable #n              │
  : ...                      :
  │                          │
  ├──────────────────────────┤ LOOKUP_INDEXES_START
  │ Field lookup indexes     │
  ├──────────────────────────┤ MATCHING_RULES_BITMAP_BASE
  │ Matching rules bitmap    │
  │                          │
  :                          :
  │                          │
  ├──────────────────────────┤
  │ Matching patterns bitmap │
  │                          │
  :                          :
  │                          │
  └──────────────────────────┘
```

# Variable undefined flags

The first few bytes in WASM memory contains a bitmap where each bit indicates
whether one of the variables is undefined or not. The bitmap is 128-bits long,
which is also the number of variable that follow the bitmap in memory. When
some variable is flagged as undefined (the corresponding bit in the bitmap is
set) the value of the variable is ignored.

# Field lookup

While evaluating rule condition's, the WASM code needs to obtain from YARA the
values stored in structures, maps and arrays. In order to minimize the number
of calls from WASM to Rust, these field lookups are performed in bulk. For
example, suppose that a YARA module named `some_module` exports a structure
named `some_struct` that has an integer field named `some_int`. For accessing,
that field in a YARA rule you would write `some_module.some_struct.some_int`.
The WASM code for obtaining the value of `some_int` consists in a single call
to the [`lookup_integer`] function. This functions receives a series of field
indexes: the index of `some_module` within the global structure, the index
of `some_struct` within `some_module`, and finally the index of `some_int`,
within `some_struct`. These indexes are stored starting at offset 1024 in
the WASM module's main memory (see "Memory layout") before calling
[`lookup_integer`], while the global variable `lookup_num_lookup_indexes` says
how many indexes to lookup.

See the [`lookup_field`] function.

 */
use std::any::{TypeId, type_name};
use std::borrow::Cow;
use std::mem;
use std::ops::RangeInclusive;
use std::rc::Rc;
use std::sync::{LazyLock, OnceLock};

use bstr::{BString, ByteSlice};
#[cfg(not(feature = "inventory"))]
use linkme::distributed_slice;
use rustc_hash::FxHashMap;
use smallvec::{SmallVec, smallvec};
use yara_x_macros::wasm_export;

use crate::compiler::{LiteralId, PatternId, RegexpId, RuleId};
use crate::modules::BUILTIN_MODULES;
use crate::scanner::{RuntimeObjectHandle, ScanContext};
use crate::types::{
    Array, Func, FuncSignature, Map, Struct, TypeValue, Value,
};
use crate::wasm::integer::RangedInteger;
use crate::wasm::runtime::{
    AsContext, AsContextMut, Caller, Config, Engine, FuncType, Linker, ValRaw,
    ValType,
};
use crate::wasm::string::RuntimeString;
use crate::wasm::string::String as _;
use crate::{ScanError, wasm};

pub(crate) mod builder;
pub(crate) mod integer;
pub(crate) mod runtime;
pub(crate) mod string;

/// Maximum number of variables.
pub(crate) const MAX_VARS: i32 = 2048;
/// Offset in module's main memory where the space for variables start.
/// The space that goes from 0 to VARS_STACK_START is dedicated to the flags
/// that indicate whether a variable is undefined. That's why this space
/// is MAX_VARS / 8 bytes, we only need a bit per variable.
pub(crate) const VARS_STACK_START: i32 = MAX_VARS / 8;
/// Offset in module's main memory where the space for variables end.
pub(crate) const VARS_STACK_END: i32 = VARS_STACK_START + MAX_VARS * 8;

/// Offset in module's main memory where the space for lookup indexes start.
pub(crate) const LOOKUP_INDEXES_START: i32 = VARS_STACK_END;
/// Offset in module's main memory where the space for lookup indexes end.
pub(crate) const LOOKUP_INDEXES_END: i32 = LOOKUP_INDEXES_START + 1024;

/// Offset in module's main memory where resides the bitmap that tells if a
/// rule matches or not. This bitmap contains one bit per rule, if the N-th
/// bit is set, it indicates that the rule with RuleId = N matched.
pub(crate) const MATCHING_RULES_BITMAP_BASE: i32 = LOOKUP_INDEXES_END;

/// Global slice that contains an entry for each function that is callable from
/// WASM code. Functions with attributes `#[wasm_export]` and `#[module_export]`
/// are automatically added to this slice. See https://github.com/dtolnay/linkme
/// for details about how `#[distributed_slice]` works.
///
/// When the `inventory` feature is enabled, this vector is not used.
#[cfg(not(feature = "inventory"))]
#[distributed_slice]
pub(crate) static WASM_EXPORTS: [WasmExport] = [..];

#[cfg(feature = "inventory")]
inventory::collect!(WasmExport);

/// Returns an iterator of [`WasmExport`] structs that describes the functions
/// that are callable from WASM code.
pub(crate) fn wasm_exports() -> impl Iterator<Item = &'static WasmExport> {
    #[cfg(feature = "inventory")]
    return inventory::iter::<WasmExport>();

    // Rely on the `WASM_EXPORTS` slice when not using the `inventory` crate.
    #[cfg(not(feature = "inventory"))]
    WASM_EXPORTS.iter()
}

/// Type of each entry in [`WASM_EXPORTS`].
pub(crate) struct WasmExport {
    /// Function's name.
    pub name: &'static str,
    /// Function's mangled name. The mangled name contains information about
    /// the function's arguments and return type. For additional details see
    /// [`crate::types::MangledFnName`].
    pub mangled_name: &'static str,
    /// True if the function is visible from YARA rules. Functions exported by
    /// modules, as well as built-in functions like uint8, uint16, etc, are
    /// public, but many other functions callable from WASM are for internal
    /// use only and therefore are not public.
    pub public: bool,
    /// Path of the module where the function resides. This an absolute path
    /// that includes the crate name (e.g: yara_x::modules::test_proto2)
    pub rust_module_path: &'static str,
    /// If the function is a method of some type, this contains the name of
    /// the type (i.e: `my_module.my_struct`).
    pub method_of: Option<&'static str>,
    /// Controls whether imported module state must be synchronized before
    /// and/or after invoking the callback from generated WASM code.
    pub sync_flags: u32,
    /// Reference to some type that implements the WasmExportedFn trait.
    pub func: &'static (dyn WasmExportedFn + Send + Sync),
    /// Function's documentation description.
    pub description: Option<Cow<'static, str>>,
}

impl WasmExport {
    /// Returns the fully qualified name for a #[wasm_export] function.
    ///
    /// The fully qualified name includes not only the function's name, but
    /// also the module's name (e.g: `my_module.my_struct.my_func@ii@i`)
    pub fn fully_qualified_mangled_name(&self) -> String {
        if self.method_of.is_some() {
            return self.mangled_name.to_string();
        }
        for (module_name, module) in BUILTIN_MODULES.iter() {
            if let Some(rust_module_name) = module.rust_module_name
                && self.rust_module_path.contains(rust_module_name)
            {
                return format!("{}.{}", module_name, self.mangled_name);
            }
        }
        self.mangled_name.to_owned()
    }

    /// Returns true if this export comes from YARA itself, not for a YARA
    /// module.
    pub fn builtin(&self) -> bool {
        self.rust_module_path.strip_prefix("yara_x::modules::").is_none()
    }

    /// Returns a hash map with all function exported to WASM that match the
    /// given predicate.
    ///
    /// Keys are function names and values are [`Func`] structures. Overloaded
    /// functions appear in the map as a single entry where the [`Func`] has
    /// multiple signatures.
    pub fn get_functions<P>(predicate: P) -> FxHashMap<&'static str, Func>
    where
        P: FnMut(&&WasmExport) -> bool,
    {
        let mut functions: FxHashMap<&'static str, Func> =
            FxHashMap::default();

        // Iterate over the WASM exports looking for those that match the
        // predicate. Add them to `functions` map, or update the `Func`
        // object with an additional signature if the function is
        // overloaded.
        for export in wasm_exports().filter(predicate) {
            let mangled_name = export.fully_qualified_mangled_name();
            let description = export.description.clone();
            // If the function was already present in the map is because it has
            // multiple signatures. If that's the case, add more signatures to
            // the existing `Func` object.
            if let Some(function) = functions.get_mut(export.name) {
                let mut signature = FuncSignature::from(mangled_name);
                signature.doc = description;
                function.add_signature(signature);
            } else {
                let mut func = Func::from(mangled_name);
                // Update the description for the first and only signature in
                // the function.
                let signature = func.signatures_mut().get_mut(0).unwrap();
                // It's safe to get a mutable reference to the signature with
                // Rc::get_mut because the Rc was just crated and there's a
                // single reference to it.
                let signature = Rc::get_mut(signature).unwrap();
                signature.doc = description;
                functions.insert(export.name, func);
            }
        }

        functions
    }

    /// Returns the methods implemented for the type with the given name.
    ///
    /// `type_name` is one of the strings passed in the `method_of` field to
    /// the `module_export` macro. For instance, in the example below we
    /// specify that `some_method` is a method of `my_module.MyStructure`. If
    /// we call `get_methods` with `"my_module.MyStructure"` it returns
    /// a hash map that contains a [`Func`] describing `some_method`.
    ///
    /// ```text
    /// #[module_export(method_of = "my_module.MyStructure")]
    /// fn some_method(...) { ... }
    /// ```
    pub fn get_methods(type_name: &str) -> FxHashMap<&'static str, Func> {
        WasmExport::get_functions(|export| {
            export.method_of.is_some_and(|name| name == type_name)
        })
    }
}

/// Trait implemented for all types that represent a function exported to WASM.
///
/// Implementors of this trait are [`WasmExportedFn0`], [`WasmExportedFn1`],
/// [`WasmExportedFn2`], etc. Each of these types is a generic type that
/// represents all functions with 0, 1, and 2 arguments respectively.
pub(crate) trait WasmExportedFn {
    /// Returns the function that will be passed to the selected runtime linker
    /// while linking the WASM code to this function.
    fn trampoline(&'static self) -> TrampolineFn;

    /// Returns a [`Vec<ValType>`] with the types of the function's
    /// arguments
    fn wasmtime_args(&'static self) -> Vec<ValType>;

    /// Returns a [`Vec<ValType>`] with the types of the function's
    /// return values.
    fn wasmtime_results(&'static self) -> WasmResultArray<ValType>;

    /// Returns a [`Vec<walrus::ValType>`] with the types of the function's
    /// arguments
    fn walrus_args(&'static self) -> Vec<walrus::ValType> {
        self.wasmtime_args().iter().map(wasmtime_to_walrus).collect()
    }

    /// Returns a [`Vec<walrus::ValType>`] with the types of the function's
    /// return values.
    fn walrus_results(&'static self) -> WasmResultArray<walrus::ValType> {
        self.wasmtime_results().iter().map(wasmtime_to_walrus).collect()
    }
}

type TrampolineFn = Box<
    dyn Fn(Caller<'_, ScanContext>, &mut [ValRaw]) -> anyhow::Result<()>
        + Send
        + Sync
        + 'static,
>;

const MAX_RESULTS: usize = 4;
type WasmResultArray<T> = SmallVec<[T; MAX_RESULTS]>;

/// A trait for converting raw values received from WASM code into Rust types.
///
/// Functions decorated with `#[wasm_export]` must have arguments of some type
/// `T` so that [`WasmArg<T>`] is implemented for [`ValRaw`].
///
/// By implementing [`WasmArg<T>`] for [`ValRaw`], the raw values received from
/// WASM code can be converted into Rust type `T`.
trait WasmArg<T> {
    fn raw_into(self, _: &mut ScanContext) -> T;
}

impl WasmArg<i64> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> i64 {
        self.get_i64()
    }
}

impl WasmArg<i32> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> i32 {
        self.get_i32()
    }
}

impl WasmArg<f64> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> f64 {
        f64::from_bits(self.get_f64())
    }
}

impl WasmArg<f32> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> f32 {
        f32::from_bits(self.get_f32())
    }
}

impl WasmArg<bool> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> bool {
        self.get_i32() == 1
    }
}

impl WasmArg<RuleId> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> RuleId {
        RuleId::from(self.get_i32())
    }
}

impl WasmArg<PatternId> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> PatternId {
        PatternId::from(self.get_i32())
    }
}

impl WasmArg<LiteralId> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> LiteralId {
        LiteralId::from(self.get_i32())
    }
}

impl WasmArg<RegexpId> for ValRaw {
    #[inline]
    fn raw_into(self, _: &mut ScanContext) -> RegexpId {
        RegexpId::from(self.get_i32())
    }
}

impl WasmArg<RuntimeString> for ValRaw {
    #[inline]
    fn raw_into(self, ctx: &mut ScanContext) -> RuntimeString {
        RuntimeString::from_wasm(ctx, self.get_i64())
    }
}

impl WasmArg<Rc<Array>> for ValRaw {
    #[inline]
    fn raw_into(self, ctx: &mut ScanContext) -> Rc<Array> {
        let handle = RuntimeObjectHandle::from(self.get_i64());
        ctx.runtime_objects.get(&handle).unwrap().as_array()
    }
}

impl WasmArg<Rc<Map>> for ValRaw {
    #[inline]
    fn raw_into(self, ctx: &mut ScanContext) -> Rc<Map> {
        let handle = RuntimeObjectHandle::from(self.get_i64());
        ctx.runtime_objects.get(&handle).unwrap().as_map()
    }
}

impl WasmArg<Rc<Struct>> for ValRaw {
    #[inline]
    fn raw_into(self, ctx: &mut ScanContext) -> Rc<Struct> {
        let handle = RuntimeObjectHandle::from(self.get_i64());
        ctx.runtime_objects.get(&handle).unwrap().as_struct()
    }
}

impl WasmArg<Option<Rc<Struct>>> for ValRaw {
    #[inline]
    fn raw_into(self, ctx: &mut ScanContext) -> Option<Rc<Struct>> {
        let handle = RuntimeObjectHandle::from(self.get_i64());
        if handle == RuntimeObjectHandle::NULL {
            return None;
        }
        Some(ctx.runtime_objects.get(&handle).unwrap().as_struct())
    }
}

/// A trait for converting a function result into an array of [`ValRaw`] values
/// suitable to be passed to WASM code.
///
/// Functions with the `#[wasm_export]` attribute must return a type that
/// implements this trait.
pub(crate) trait WasmResult {
    /// Returns the WASM values representing this result.
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw>;

    /// Returns the WASM types that conform this result.
    fn types() -> WasmResultArray<ValType>;
}

impl WasmResult for () {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![]
    }
}

impl WasmResult for i32 {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i32(self)]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I32]
    }
}

impl WasmResult for i64 {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i64(self)]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl<const MIN: i64, const MAX: i64> WasmResult for RangedInteger<MIN, MAX> {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i64(self.value())]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl WasmResult for f32 {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::f32(f32::to_bits(self))]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::F32]
    }
}

impl WasmResult for f64 {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::f64(f64::to_bits(self))]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::F64]
    }
}

impl WasmResult for bool {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i32(self as i32)]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I32]
    }
}

impl<S: wasm::string::String> WasmResult for S {
    fn values(self, ctx: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i64(self.into_wasm_with_ctx(ctx))]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl WasmResult for RuntimeObjectHandle {
    fn values(self, _: &mut ScanContext) -> WasmResultArray<ValRaw> {
        smallvec![ValRaw::i64(self.into())]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl WasmResult for Rc<BString> {
    fn values(self, ctx: &mut ScanContext) -> WasmResultArray<ValRaw> {
        let s = RuntimeString::Rc(self);
        smallvec![ValRaw::i64(s.into_wasm_with_ctx(ctx))]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl WasmResult for Rc<Struct> {
    fn values(self, ctx: &mut ScanContext) -> WasmResultArray<ValRaw> {
        let handle = ctx.store_struct(self);
        smallvec![ValRaw::i64(handle.into())]
    }

    fn types() -> WasmResultArray<ValType> {
        smallvec![ValType::I64]
    }
}

impl<A, B> WasmResult for (A, B)
where
    A: WasmResult,
    B: WasmResult,
{
    fn values(self, ctx: &mut ScanContext) -> WasmResultArray<ValRaw> {
        let mut result = self.0.values(ctx);
        result.extend(self.1.values(ctx));
        result
    }

    fn types() -> WasmResultArray<ValType> {
        let mut result = A::types();
        result.extend(B::types());
        result
    }
}

impl<T> WasmResult for Option<T>
where
    T: WasmResult + Default,
{
    fn values(self, ctx: &mut ScanContext) -> WasmResultArray<ValRaw> {
        match self {
            Some(value) => {
                let mut result = value.values(ctx);
                result.push(ValRaw::i32(0));
                result
            }
            None => {
                let mut result = T::default().values(ctx);
                result.push(ValRaw::i32(1));
                result
            }
        }
    }

    fn types() -> WasmResultArray<ValType> {
        let mut result = T::types();
        result.push(ValType::I32);
        result
    }
}

pub fn wasmtime_to_walrus(ty: &ValType) -> walrus::ValType {
    #[allow(unreachable_patterns)]
    match ty {
        ValType::I64 => walrus::ValType::I64,
        ValType::I32 => walrus::ValType::I32,
        ValType::F64 => walrus::ValType::F64,
        ValType::F32 => walrus::ValType::F32,
        _ => unreachable!(),
    }
}

#[allow(clippy::if_same_then_else)]
fn type_id_to_wasmtime(
    type_id: TypeId,
    type_name: &'static str,
) -> &'static [ValType] {
    if type_id == TypeId::of::<i64>() {
        return &[ValType::I64];
    } else if type_id == TypeId::of::<i32>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<f64>() {
        return &[ValType::F64];
    } else if type_id == TypeId::of::<f32>() {
        return &[ValType::F32];
    } else if type_id == TypeId::of::<bool>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<LiteralId>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<PatternId>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<RuleId>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<RegexpId>() {
        return &[ValType::I32];
    } else if type_id == TypeId::of::<()>() {
        return &[];
    } else if type_id == TypeId::of::<RuntimeString>() {
        return &[ValType::I64];
    } else if type_id == TypeId::of::<Option<Rc<Struct>>>() {
        return &[ValType::I64];
    } else if type_id == TypeId::of::<Rc<Struct>>() {
        return &[ValType::I64];
    } else if type_id == TypeId::of::<Rc<Array>>() {
        return &[ValType::I64];
    } else if type_id == TypeId::of::<Rc<Map>>() {
        return &[ValType::I64];
    }
    panic!("type `{type_name}` can't be an argument")
}

/// Macro that creates types [`WasmExportedFn0`], [`WasmExportedFn1`], etc,
/// and implements the [`WasmExportedFn`] trait for them.
macro_rules! impl_wasm_exported_fn {
    ($name:ident $($args:ident)*) => {
        #[allow(dead_code)]
        pub(super) struct $name <$($args,)* R>
        where
            $($args: 'static,)*
            R: 'static,
        {
            pub target_fn: &'static (dyn Fn(&mut Caller<'_, ScanContext>, $($args),*) -> R
                          + Send
                          + Sync
                          + 'static),
        }

        #[allow(dead_code)]
        impl<$($args,)* R> WasmExportedFn for $name<$($args,)* R>
        where
            $(ValRaw: WasmArg<$args>,)*
            R: WasmResult,
        {
            #[allow(unused_mut)]
            fn wasmtime_args(&'static self) -> Vec<ValType> {
                let mut result = Vec::new();
                $(
                    result.extend_from_slice(type_id_to_wasmtime(
                        TypeId::of::<$args>(),
                        type_name::<$args>(),
                    ));
                )*
                result
            }

            fn wasmtime_results(&'static self) -> WasmResultArray<ValType> {
                R::types()
            }

            #[allow(unused_assignments)]
            #[allow(unused_variables)]
            #[allow(non_snake_case)]
            #[allow(unused_mut)]
            fn trampoline(&'static self) -> TrampolineFn {
                Box::new(
                    |mut caller: Caller<'_, ScanContext>,
                     args_and_results: &mut [ValRaw]|
                     -> anyhow::Result<()> {
                        let mut i = 0;
                        $(
                            let $args = args_and_results[i].raw_into(caller.data_mut());
                            i += 1;
                        )*

                        let result = (self.target_fn)(&mut caller, $($args),*);
                        let result = result.values(caller.data_mut());

                        let result_slice = result.as_slice();
                        let num_results = result_slice.len();

                        args_and_results[0..num_results].clone_from_slice(result_slice);
                        anyhow::Ok(())
                    },
                )
            }
        }
    };
}

// Generate multiple structures implementing the WasmExportedFn trait,
// each for a different number of arguments. The WasmExportedFn0 is a generic
// type that represents all exported functions that have no arguments,
// WasmExportedFn1 represents functions with 1 argument, and so on.
impl_wasm_exported_fn!(WasmExportedFn0);
impl_wasm_exported_fn!(WasmExportedFn1 A1);
impl_wasm_exported_fn!(WasmExportedFn2 A1 A2);
impl_wasm_exported_fn!(WasmExportedFn3 A1 A2 A3);
impl_wasm_exported_fn!(WasmExportedFn4 A1 A2 A3 A4);

/// Table with identifiers of variables and memories shared by the WASM
/// module with the host.
#[derive(Clone)]
pub(crate) struct WasmSymbols {
    /// The WASM module's main memory.
    pub main_memory: walrus::MemoryId,

    /// Function that checks if a pattern matched or not. This function
    /// receives the pattern ID and returns a boolean.
    pub check_for_pattern_match: walrus::FunctionId,

    /// Global variable that contains the value for `filesize`.
    pub filesize: walrus::GlobalId,

    /// Global variable that is set to true after the pattern search phase
    /// has been executed. In this phase the data is scanned looking for
    /// all the patterns at the same time using the Aho-Corasick algorithm.
    /// However, this phase is executed lazily, when rule conditions are
    /// evaluated and some of them needs to know if a pattern matched or not.
    pub pattern_search_done: walrus::GlobalId,

    /// Local variables used for temporary storage.
    pub i64_tmp_a: walrus::LocalId,
    pub i64_tmp_b: walrus::LocalId,
    pub i32_tmp: walrus::LocalId,
    pub f64_tmp: walrus::LocalId,
}

pub(crate) static CONFIG: LazyLock<Config> = LazyLock::new(|| {
    let mut config = Config::default();
    // Wasmtime produces a nasty warning when linked against musl. The
    // warning can be fixed by disabling native unwind information.
    //
    // More details:
    //
    // https://github.com/bytecodealliance/wasmtime/issues/8897
    // https://github.com/VirusTotal/yara-x/issues/181
    //
    #[cfg(target_env = "musl")]
    config.native_unwind_info(false);

    config.cranelift_opt_level(runtime::OptLevel::SpeedAndSize);
    config.epoch_interruption(true);

    // 16MB should be enough for each WASM module. Each module needs a
    // fixed amount of memory that is only a few KB long, plus a variable
    // amount that depends on the number of rules and patterns (1 bit per
    // rule and 1 bit per pattern). With 16MB there's enough space for
    // millions of rules and patterns. By default, this is 4GB in 64-bits
    // systems, which causes a reservation of 4GB of virtual address space
    // (not physical RAM) per module (and therefore per Scanner). In some
    // scenarios where virtual address space is limited (i.e: Docker
    // instances) this is problematic. See:
    // https://github.com/VirusTotal/yara-x/issues/292
    config.memory_reservation(0x1000000);

    // WASM memory won't grow, there's no need to allocate space for
    // future grow.
    config.memory_reservation_for_growth(0);

    // As the memory can't grow, it won't move. By explicitly indicating
    // this, modules can be compiled with static knowledge the base pointer
    // of linear memory never changes to enable optimizations.
    config.memory_may_move(false);

    config
});

/// The global WASM engine used everywhere.
///
/// The engine is initialized once, the first time that it is used,
/// and then reused. It needs to be mutable so that the [`free_engine`]
/// can destroy it.
static mut ENGINE: OnceLock<Engine> = OnceLock::new();

/// Returns the global WASM engine used everywhere.
pub(crate) fn get_engine<'a>() -> &'a Engine {
    unsafe {
        // Static mutable references are dangerous and should be used
        // with care, that's why the compiler has the static_mut_refs
        // warning. Here it's safe to have a mutable static reference
        // to the engine, because this reference is mutated only once
        // when the engine is initialized, and then again if `free_engine`
        // is called.
        #[allow(static_mut_refs)]
        ENGINE.get_or_init(|| Engine::new(&CONFIG).unwrap())
    }
}

/// Frees the global WASM engine.
///
/// This function only needs to be called in a very specific scenario:
/// when YARA-X is used as a dynamically loaded library (`.so`, `.dll`,
/// `.dylib`) **and** that library must be unloaded at runtime.
///
/// Its primary purpose is to remove the process-wide signal handlers
/// installed by the WASM engine.
///
/// # Safety
///
/// This function is **unsafe** to call under normal circumstances. It has
/// strict preconditions that must be met:
///
/// - There must be no other active `wasmtime` engines in the process. This
///   applies not only to clones of this engine (which should not exist),
///   but to *any* `wasmtime` engine, since global state shared by all
///   engines is torn down.
///
/// - On Unix platforms, no other signal handlers may have been installed
///   for signals intercepted by `wasmtime`. If other handlers have been set,
///   `wasmtime` cannot reliably restore the original state, which may lead
///   to undefined behavior.
pub(crate) unsafe fn free_engine() {
    // `unload_process_handlers` is called only in the platforms where
    // wasmtime actually installs signal handlers. See:
    // https://github.com/bytecodealliance/wasmtime/blob/9362e47987363c350a8d9d09aa56677425496fb7/crates/wasmtime/build.rs#L20
    #[cfg(any(
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "riscv64",
        target_arch = "s390x",
    ))]
    {
        #[allow(static_mut_refs)]
        unsafe {
            ENGINE.take().unwrap().unload_process_handlers()
        }
    }
}

pub(crate) fn new_linker() -> Linker<ScanContext<'static, 'static>> {
    let engine = get_engine();
    let mut linker = Linker::<ScanContext<'static, 'static>>::new(engine);

    for export in wasm_exports() {
        let func_type = FuncType::new(
            engine,
            export.func.wasmtime_args(),
            export.func.wasmtime_results(),
        );
        // Using `func_new_unchecked` instead of `func_new` makes function
        // calls from WASM to Rust around 3x faster.
        unsafe {
            linker
                .func_new_unchecked(
                    export.rust_module_path,
                    export.fully_qualified_mangled_name().as_str(),
                    func_type,
                    export.sync_flags,
                    export.func.trampoline(),
                )
                .unwrap();
        }
    }

    linker
}

/// Invoked from WASM for triggering the pattern search phase.
#[wasm_export(sync = "both")]
pub(crate) fn search_for_patterns(caller: &mut Caller<'_, ScanContext>) {
    // The WASM runtime and `search_for_patterns` each track timeouts
    // independently: the runtime uses epoch deadlines, while
    // `search_for_patterns` relies on the global HEARTBEAT_COUNTER.
    // This means `search_for_patterns` may time out first, while the
    // WASM runtime has not yet hit its own deadline (though it soon
    // will).
    //
    // If a timeout occurred during `search_for_patterns`, force the
    // WASM runtime to raise its own timeout by setting the epoch
    // deadline to 0 (immediate expiry). This forces the WASM runtime
    // to abort the execution of rule conditions as soon as possible
    // after the timeout was detected by `search_for_patterns`.
    if matches!(
        caller.data_mut().search_for_patterns(),
        Err(ScanError::Timeout)
    ) {
        caller.as_context_mut().set_epoch_deadline(0);
    }
}

/// Invoked from WASM to notify when a rule matches.
#[wasm_export(sync = "both")]
pub(crate) fn rule_match(
    caller: &mut Caller<'_, ScanContext>,
    rule_id: RuleId,
) {
    caller.data_mut().track_rule_match(rule_id);
}

/// Invoked from WASM to notify when a rule doesn't match.
#[wasm_export(sync = "both")]
pub(crate) fn rule_no_match(
    caller: &mut Caller<'_, ScanContext>,
    rule_id: RuleId,
) {
    caller.data_mut().track_rule_no_match(rule_id);
}

/// Invoked from WASM to ask whether a pattern matches at a given file
/// offset.
///
/// Returns true if the pattern identified by `pattern_id` matches at `offset`,
/// or false if otherwise.
#[wasm_export(sync = "none")]
pub(crate) fn is_pat_match_at(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
    offset: i64,
) -> bool {
    // Matches can't occur at negative offsets.
    if offset < 0 {
        return false;
    }
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        matches.search(offset.try_into().unwrap()).is_ok()
    } else {
        false
    }
}

/// Invoked from WASM to ask whether a pattern matches at some offset within
/// a given range.
///
/// Returns true if the pattern identified by `pattern_id` matches at some
/// offset in the range [`lower_bound`, `upper_bound`], both inclusive.
#[wasm_export(sync = "none")]
pub(crate) fn is_pat_match_in(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
    lower_bound: i64,
    upper_bound: i64,
) -> bool {
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        matches
            .matches_in_range(lower_bound as isize..=upper_bound as isize)
            .is_positive()
    } else {
        false
    }
}

/// Invoked from WASM to ask if at least `required` of the patterns in the
/// range `pattern_id_start..=pattern_id_end` (inclusive) match.
#[wasm_export(sync = "none")]
pub(crate) fn pat_range_match(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id_start: PatternId,
    pattern_id_end: PatternId,
    required: i64,
) -> bool {
    assert!(pattern_id_start <= pattern_id_end);

    // TODO: We could use RangeInclusive<PatternId>, but iterating over it
    // requires that PatternId implements `iter::Step` which is currently a
    // nightly-only experimental API:
    // https://doc.rust-lang.org/std/iter/trait.Step.html
    let range: RangeInclusive<usize> =
        pattern_id_start.into()..=pattern_id_end.into();

    let required = required.try_into().unwrap();

    let ctx = caller.data();
    let mut num_matches = 0;

    for pattern_id in range {
        let match_found = ctx
            .pattern_matches
            .get(pattern_id.into())
            .is_some_and(|matches| matches.len() > 0);

        if match_found {
            num_matches += 1;
        }
    }

    num_matches >= required
}

/// Invoked from WASM to ask for the number of matches for a pattern.
#[wasm_export(sync = "none")]
pub(crate) fn pat_matches(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
) -> i64 {
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        matches.len().try_into().unwrap()
    } else {
        0
    }
}

/// Invoked from WASM to ask for the number of matches of a given pattern
/// within some offset range.
///
/// Returns the number of matches for the pattern identified by `pattern_id`
/// that start in the range [`lower_bound`, `upper_bound`], both inclusive.
#[wasm_export(sync = "none")]
pub(crate) fn pat_matches_in(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
    lower_bound: i64,
    upper_bound: i64,
) -> i64 {
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        matches.matches_in_range(lower_bound as isize..=upper_bound as isize)
    } else {
        0
    }
}

/// Invoked from WASM to ask for the offset where a pattern matched
///
/// Returns the length for the index-th occurrence of the pattern identified
/// by `pattern_id`. The index is 1-based. Returns `None` if the pattern
/// has not matched or there are less than `index` matches.
#[wasm_export(sync = "none")]
pub(crate) fn pat_length(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
    index: i64,
) -> Option<i64> {
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        let index: usize = index.try_into().ok()?;
        // Index is 1-based, convert it to 0-based before calling `matches.get`
        let m = matches.get(index.checked_sub(1)?)?;
        Some(ExactSizeIterator::len(&m.range) as i64)
    } else {
        None
    }
}

/// Invoked from WASM to ask for the length of some pattern match
///
/// Returns the offset for the index-th occurrence of the pattern identified
/// by `pattern_id`. The index is 1-based. Returns `None` if the pattern
/// has not matched or there are less than `index` matches.
#[wasm_export(sync = "none")]
pub(crate) fn pat_offset(
    caller: &mut Caller<'_, ScanContext>,
    pattern_id: PatternId,
    index: i64,
) -> Option<i64> {
    if let Some(matches) = caller.data().pattern_matches.get(pattern_id) {
        let index: usize = index.try_into().ok()?;
        // Index is 1-based, convert it to 0-based before calling `matches.get`
        let m = matches.get(index.checked_sub(1)?)?;
        Some(m.range.start as i64)
    } else {
        None
    }
}

/// Called from WASM to obtain the length of a string.
#[wasm_export(name = "len", method_of = "RuntimeString", sync = "none")]
pub(crate) fn string_len(
    caller: &mut Caller<'_, ScanContext>,
    string: RuntimeString,
) -> i64 {
    string.as_bstr(caller.as_context().data()).len() as i64
}

/// Called from WASM to obtain the length of an array.
#[wasm_export(name = "len", method_of = "Array", sync = "none")]
pub(crate) fn array_len(
    _: &mut Caller<'_, ScanContext>,
    array: Rc<Array>,
) -> i64 {
    array.len() as i64
}

/// Called from WASM to obtain the length of a map.
#[wasm_export(name = "len", method_of = "Map", sync = "none")]
pub(crate) fn map_len(_: &mut Caller<'_, ScanContext>, map: Rc<Map>) -> i64 {
    map.len() as i64
}

/// Given a structure and a series of fields indexes, walks the structure
/// looking for the final field.
///
/// For example, suppose that we have a structure that has two fields, the
/// first one is an integer and the second one is another struct, which in
/// turns have another integer field:
///
/// {
///   integer_field,
///   struct_field: {
///      integer_field
///   }
/// }
///
/// For locating the integer field in the inner structure, we can start at the
/// outer structure and pass the following sequence of field indexes: 1, 0. The
/// first value (1) is the index of `struct_field` within the outer structure,
/// as this field is another structure, we can continue looking for fields, and
/// the next value (0) is the index of `integer_field` within the inner
/// structure. So starting at the outer structure and following the path: 1,0 we
/// reach the inner `integer_field`.
///
/// The initial structure is the one passed in the `structure` argument, or the
/// root structure if this argument is `None`.
///
/// The sequence of indexes is stored in WASM main memory, starting at
/// `LOOKUP_INDEXES_START`, and the number of indexes is indicated by the
/// argument `num_lookup_indexes`.
fn lookup_field(
    caller: &mut Caller<'_, ScanContext>,
    structure: Option<Rc<Struct>>,
    num_lookup_indexes: i32,
) -> TypeValue /* TODO: make this a &TypeValue? */ {
    assert!(num_lookup_indexes > 0);

    let mut store_ctx = caller.as_context_mut();

    let mem_ptr = store_ctx
        .data_mut()
        .wasm_main_memory
        .unwrap()
        .data_ptr(&mut store_ctx);

    let lookup_indexes_ptr =
        unsafe { mem_ptr.offset(LOOKUP_INDEXES_START as isize) };

    let lookup_indexes = unsafe {
        std::slice::from_raw_parts::<i32>(
            lookup_indexes_ptr as *const i32,
            num_lookup_indexes as usize,
        )
    };

    // If the passed structure is None, it means that we should start the
    // at the root structure.
    let mut structure =
        structure.as_deref().unwrap_or(&store_ctx.data().root_struct);

    let mut final_field = None;

    for field_index in lookup_indexes {
        // Integers in WASM memory are always stored as little-endian
        // regardless of the endianness of the host platform. If we
        // are in a big-endian platform the integers needs to be swapped
        // for obtaining the original value.
        let field_index = if cfg!(target_endian = "big") {
            field_index.swap_bytes()
        } else {
            *field_index
        };

        let field = structure
            .field_by_index(field_index as usize)
            .unwrap_or_else(|| {
                panic!(
                    "expecting field with index {field_index} in {structure:#?}"
                )
            });

        final_field = Some(field);

        if let TypeValue::Struct(s) = &field.type_value {
            structure = s
        }
    }

    final_field.unwrap().type_value.clone()
}

/// Lookup a field of string type and returns its value.
///
/// See [`lookup_field`].
#[wasm_export(sync = "before")]
pub(crate) fn lookup_string(
    caller: &mut Caller<'_, ScanContext>,
    structure: Option<Rc<Struct>>,
    num_lookup_indexes: i32,
) -> Option<RuntimeString> {
    match lookup_field(caller, structure, num_lookup_indexes) {
        TypeValue::String { value: Value::Var(s), .. } => {
            Some(RuntimeString::Rc(s))
        }
        TypeValue::String { value: Value::Const(s), .. } => {
            Some(RuntimeString::Rc(s))
        }
        TypeValue::String { value: Value::Unknown, .. } => None,
        _ => unreachable!(),
    }
}

/// Lookup a value in a struct, and put its value in a variable.
///
/// See [`lookup_field`].
#[wasm_export(sync = "before")]
pub(crate) fn lookup_object(
    caller: &mut Caller<'_, ScanContext>,
    structure: Option<Rc<Struct>>,
    num_lookup_indexes: i32,
) -> RuntimeObjectHandle {
    let type_value = lookup_field(caller, structure, num_lookup_indexes);
    let ctx = caller.data_mut();
    match type_value {
        TypeValue::Struct(s) => ctx.store_struct(s),
        TypeValue::Array(a) => ctx.store_array(a),
        TypeValue::Map(m) => ctx.store_map(m),
        _ => unreachable!(),
    }
}

macro_rules! gen_lookup_fn {
    ($name:ident, $return_type:ty, $type:path) => {
        #[wasm_export(sync = "before")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            structure: Option<Rc<Struct>>,
            num_lookup_indexes: i32,
        ) -> Option<$return_type> {
            if let $type { value, .. } =
                lookup_field(caller, structure, num_lookup_indexes)
            {
                value.extract().cloned()
            } else {
                None
            }
        }
    };
}

gen_lookup_fn!(lookup_integer, i64, TypeValue::Integer);
gen_lookup_fn!(lookup_float, f64, TypeValue::Float);
gen_lookup_fn!(lookup_bool, bool, TypeValue::Bool);

macro_rules! gen_array_indexing_fn {
    ($name:ident, $fn:ident, $return_type:ty) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            _: &mut Caller<'_, ScanContext>,
            array: Rc<Array>,
            index: i64,
        ) -> Option<$return_type> {
            array.$fn().get(index as usize).map(|value| *value)
        }
    };
}

gen_array_indexing_fn!(array_indexing_integer, as_integer_array, i64);
gen_array_indexing_fn!(array_indexing_float, as_float_array, f64);
gen_array_indexing_fn!(array_indexing_bool, as_bool_array, bool);

#[wasm_export(sync = "none")]
#[rustfmt::skip]
pub(crate) fn array_indexing_string(
    _: &mut Caller<'_, ScanContext>,
    array: Rc<Array>,
    index: i64,
) -> Option<Rc<BString>> {
    array
        .as_string_array()
        .get(index as usize)
        .cloned()
}

#[wasm_export(sync = "none")]
#[rustfmt::skip]
pub(crate) fn array_indexing_struct(
    _: &mut Caller<'_, ScanContext>,
    array: Rc<Array>,
    index: i64,
) -> Option<Rc<Struct>> {
    array
        .as_struct_array()
        .get(index as usize)
        .cloned()
}

macro_rules! gen_map_lookup_fn {
    ($name:ident, i64, i64) => {
        gen_map_lookup_fn!($name, i64, i64, with_integer_keys, as_integer);
    };
    ($name:ident, i64, f64) => {
        gen_map_lookup_fn!($name, i64, f64, with_integer_keys, as_float);
    };
    ($name:ident, i64, bool) => {
        gen_map_lookup_fn!($name, i64, bool, with_integer_keys, as_bool);
    };
    ($name:ident, RuntimeString, i64) => {
        gen_map_lookup_fn!(
            $name,
            RuntimeString,
            i64,
            with_string_keys,
            as_integer
        );
    };
    ($name:ident, RuntimeString, f64) => {
        gen_map_lookup_fn!(
            $name,
            RuntimeString,
            f64,
            with_string_keys,
            as_float
        );
    };
    ($name:ident, RuntimeString, bool) => {
        gen_map_lookup_fn!(
            $name,
            RuntimeString,
            bool,
            with_string_keys,
            as_bool
        );
    };
    ($name:ident, i64, $return_type:ty, $with:ident, $as:ident) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            _: &mut Caller<'_, ScanContext>,
            map: Rc<Map>,
            key: i64,
        ) -> Option<$return_type> {
            map.$with().get(&key).map(|v| v.$as())
        }
    };
    ($name:ident, RuntimeString, $return_type:ty, $with:ident, $as:ident) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            map: Rc<Map>,
            key: RuntimeString,
        ) -> Option<$return_type> {
            let key = key.as_bstr(caller.data());
            map.$with().get(key).map(|v| v.$as())
        }
    };
}

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_string_integer,
    RuntimeString,
    i64
);

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_string_float,
    RuntimeString,
    f64
);

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_string_bool,
    RuntimeString,
    bool
);

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_integer_integer,
    i64,
    i64
);

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_integer_float,
    i64,
    f64
);

#[rustfmt::skip]
gen_map_lookup_fn!(
    map_lookup_integer_bool,
    i64,
    bool
);

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_integer_string(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    key: i64,
) -> Option<Rc<BString>> {
    map.with_integer_keys().get(&key).map(|s| s.as_string())
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_string_string(
    caller: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    key: RuntimeString,
) -> Option<Rc<BString>> {
    let key = key.as_bstr(caller.data());
    map.with_string_keys().get(key).map(|s| s.as_string())
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_integer_struct(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    key: i64,
) -> Option<Rc<Struct>> {
    map.with_integer_keys().get(&key).map(|v| v.as_struct())
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_string_struct(
    caller: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    key: RuntimeString,
) -> Option<Rc<Struct>> {
    let key = key.as_bstr(caller.data());
    map.with_string_keys().get(key).map(|v| v.as_struct())
}

macro_rules! gen_map_lookup_by_index_fn {
    ($name:ident, RuntimeString, $val:ty, $with:ident, $as:ident) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            _: &mut Caller<'_, ScanContext>,
            map: Rc<Map>,
            index: i64,
        ) -> (Rc<BString>, $val) {
            map.with_string_keys()
                .get_index(index as usize)
                .map(|(key, value)| (Rc::new(key.clone()), value.$as()))
                .unwrap()
        }
    };
    ($name:ident, $key:ty, $val:ty, $with:ident, $as:ident) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            _: &mut Caller<'_, ScanContext>,
            map: Rc<Map>,
            index: i64,
        ) -> ($key, $val) {
            map.$with()
                .get_index(index as usize)
                .map(|(key, value)| (*key, value.$as()))
                .unwrap()
        }
    };
}

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_integer_integer,
    i64,
    i64,
    with_integer_keys,
    as_integer
);

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_integer_float,
    i64,
    f64,
    with_integer_keys,
    as_float
);

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_integer_bool,
    i64,
    bool,
    with_integer_keys,
    as_bool
);

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_string_integer,
    RuntimeString,
    i64,
    with_string_keys,
    as_integer
);

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_string_float,
    RuntimeString,
    f64,
    with_string_keys,
    as_float
);

#[rustfmt::skip]
gen_map_lookup_by_index_fn!(
    map_lookup_by_index_string_bool,
    RuntimeString,
    bool,
    with_string_keys,
    as_bool
);

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_by_index_integer_string(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    index: i64,
) -> (i64, Rc<BString>) {
    map.with_integer_keys()
        .get_index(index as usize)
        .map(|(key, value)| (*key, value.as_string()))
        .unwrap()
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_by_index_string_string(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    index: i64,
) -> (Rc<BString>, Rc<BString>) {
    map.with_string_keys()
        .get_index(index as usize)
        .map(|(key, value)| {
            (Rc::new(key.as_bstr().to_owned()), value.as_string())
        })
        .unwrap()
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_by_index_integer_struct(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    index: i64,
) -> (i64, Rc<Struct>) {
    map.with_integer_keys()
        .get_index(index as usize)
        .map(|(key, value)| (*key, value.as_struct()))
        .unwrap()
}

#[wasm_export(sync = "none")]
pub(crate) fn map_lookup_by_index_string_struct(
    _: &mut Caller<'_, ScanContext>,
    map: Rc<Map>,
    index: i64,
) -> (Rc<BString>, Rc<Struct>) {
    map.with_string_keys()
        .get_index(index as usize)
        .map(|(key, value)| {
            (Rc::new(key.as_bstr().to_owned()), value.as_struct())
        })
        .unwrap()
}

macro_rules! gen_str_cmp_fn {
    ($name:ident, $op:tt) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            lhs: RuntimeString,
            rhs: RuntimeString,
        ) -> bool {
            lhs.$op(&rhs, caller.data())
        }
    };
}

gen_str_cmp_fn!(str_eq, eq);
gen_str_cmp_fn!(str_ne, ne);
gen_str_cmp_fn!(str_lt, lt);
gen_str_cmp_fn!(str_gt, gt);
gen_str_cmp_fn!(str_le, le);
gen_str_cmp_fn!(str_ge, ge);

macro_rules! gen_str_op_fn {
    ($name:ident, $op:tt, $case_insensitive:literal) => {
        #[wasm_export(sync = "none")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            lhs: RuntimeString,
            rhs: RuntimeString,
        ) -> bool {
            lhs.$op(&rhs, caller.data(), $case_insensitive)
        }
    };
}

gen_str_op_fn!(str_contains, contains, false);
gen_str_op_fn!(str_startswith, starts_with, false);
gen_str_op_fn!(str_endswith, ends_with, false);
gen_str_op_fn!(str_icontains, contains, true);
gen_str_op_fn!(str_istartswith, starts_with, true);
gen_str_op_fn!(str_iendswith, ends_with, true);
gen_str_op_fn!(str_iequals, equals, true);

#[wasm_export(sync = "none")]
pub(crate) fn str_len(
    caller: &mut Caller<'_, ScanContext>,
    s: RuntimeString,
) -> i64 {
    s.len(caller.data()) as i64
}

#[wasm_export(sync = "none")]
pub(crate) fn str_matches(
    caller: &mut Caller<'_, ScanContext>,
    lhs: RuntimeString,
    rhs: RegexpId,
) -> bool {
    let ctx = caller.data();
    ctx.regexp_matches(rhs, lhs.as_bstr(ctx))
}

macro_rules! gen_int_fn {
    ($name:ident, $return_type:ty, $from_fn:ident, $min:expr, $max:expr) => {
        #[wasm_export(public = true, sync = "none")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            offset: i64,
        ) -> Option<RangedInteger<$min, $max>> {
            let offset = usize::try_from(offset).ok()?;
            caller
                .data()
                .scanned_data()?
                .get(offset..offset + mem::size_of::<$return_type>())
                .map(|bytes| {
                    <$return_type>::$from_fn(bytes.try_into().unwrap()) as i64
                })
                .map(|i| RangedInteger::<$min, $max>::new(i))
        }
    };
}

gen_int_fn!(uint8, u8, from_le_bytes, 0, 255);
gen_int_fn!(uint16, u16, from_le_bytes, 0, 65_535);
gen_int_fn!(uint32, u32, from_le_bytes, 0, 4_294_967_295);
gen_int_fn!(uint8be, u8, from_be_bytes, 0, 255);
gen_int_fn!(uint16be, u16, from_be_bytes, 0, 65_535);
gen_int_fn!(uint32be, u32, from_be_bytes, 0, 4_294_967_295);

gen_int_fn!(int8, i8, from_le_bytes, -128, 127);
gen_int_fn!(int16, i16, from_le_bytes, -32_768, 32_767);
gen_int_fn!(int32, i32, from_le_bytes, -2_147_483_648, 2_147_483_647);
gen_int_fn!(int8be, i8, from_be_bytes, -128, 127);
gen_int_fn!(int16be, i16, from_be_bytes, -32_768, 32_767);
gen_int_fn!(int32be, i32, from_be_bytes, -2_147_483_648, 2_147_483_647);

macro_rules! gen_float_fn {
    ($name:ident, $return_type:ty, $from_fn:ident) => {
        #[wasm_export(public = true, sync = "none")]
        pub(crate) fn $name(
            caller: &mut Caller<'_, ScanContext>,
            offset: i64,
        ) -> Option<f64> {
            let offset = usize::try_from(offset).ok()?;
            caller
                .data()
                .scanned_data()?
                .get(offset..offset + mem::size_of::<$return_type>())
                .map(|bytes| {
                    <$return_type>::$from_fn(bytes.try_into().unwrap()) as f64
                })
        }
    };
}

gen_float_fn!(float32, f32, from_le_bytes);
gen_float_fn!(float64, f64, from_le_bytes);
gen_float_fn!(float32be, f32, from_be_bytes);
gen_float_fn!(float64be, f64, from_be_bytes);