capa 0.5.2

File capability extractor.
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
use crate::Result;
use dnfile::{
    DnPe,
    lang::{
        cil::{self, enums::*},
        clr,
    },
    stream::meta_data_tables::mdtables::{codedindex::*, *},
};
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    sync::Arc,
};

use parking_lot::RwLock;

use crate::extractor::Extractor as BaseExtractor;

#[derive(Debug, Clone)]
struct Instruction {
    i: cil::instruction::Instruction,
}

impl super::Instruction for Instruction {
    /// CIL is a stack-based ISA — there is no notion of a "stack
    /// variable" in the x86 sense. Locals are addressed by index
    /// (`ldloc.N` / `stloc.N`), not by frame offset, and the
    /// stack-string heuristic that drives `is_mov_imm_to_stack` on
    /// x86 backends doesn't apply. Python capa makes the same call —
    /// it doesn't define this method on the dnfile extractor at all.
    /// Safe default `false` matches Python's behaviour: the
    /// stack-string detector skips .NET methods.
    ///
    /// 0.4.x: previously `unimplemented!()`. Replaced in 0.5.0 — the
    /// panic was a latent footgun for any caller that held a
    /// `&dyn Instruction` without knowing which extractor produced it.
    fn is_mov_imm_to_stack(&self) -> Result<bool> {
        Ok(false)
    }

    /// CIL string literals come from the `#US` heap via `ldstr`, not
    /// as byte arrays moved to a stack frame, so there are no
    /// "printable bytes" to count on an instruction. Python capa
    /// doesn't define this for the dnfile extractor. Safe default
    /// `0` keeps the stack-string aggregator at 0 contributions for
    /// .NET methods — same outcome as Python.
    ///
    /// 0.4.x: previously `unimplemented!()`.
    fn get_printable_len(&self) -> Result<u64> {
        Ok(0)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[derive(Debug, Clone)]
struct Function {
    f: cil::function::Function,
    /// Python capa convention: `calls_to` = set of CALLERS (incoming
    /// references — addresses of methods that call this one).
    calls_to: HashSet<u64>,
    /// Python capa convention: `calls_from` = set of CALLEES (outgoing
    /// references — addresses of methods this one calls).
    calls_from: HashSet<u64>,
    /// Materialised caller list for the `inrefs` trait method. Same
    /// content as `calls_to`, kept as `Vec` because the trait returns
    /// `&Vec<u64>`. Populated at `get_functions` construction.
    inrefs: Vec<u64>,
    /// Per-block successor map for the `blockrefs` trait method. The
    /// .NET extractor treats each method as a single basic block
    /// (matches `get_blocks` below), so this is always
    /// `{first_insn_offset: vec![]}` — one entry, no successors. A
    /// future CIL CFG split (br/brtrue/brfalse/switch walking) would
    /// expand this; tracked as a follow-up.
    blockrefs: HashMap<u64, Vec<u64>>,
}

impl super::Function for Function {
    /// Callers of this method. 0.4.x: `unimplemented!()`. 0.5.0:
    /// populated from `calls_to` at construction.
    fn inrefs(&self) -> &Vec<u64> {
        &self.inrefs
    }

    /// Per-basic-block successor map. 0.4.x: `unimplemented!()`.
    /// 0.5.0: returns a single-entry map matching `get_blocks`'
    /// single-block-per-method shape. Proper CIL CFG split is a
    /// follow-up — it requires walking br/brtrue/brfalse/switch
    /// targets and re-segmenting the instruction list.
    fn blockrefs(&self) -> &HashMap<u64, Vec<u64>> {
        &self.blockrefs
    }

    fn offset(&self) -> u64 {
        self.f.offset as u64
    }

    fn get_blocks(&self) -> Result<BTreeMap<u64, Vec<Box<dyn super::Instruction>>>> {
        let mut res = BTreeMap::<u64, Vec<Box<dyn super::Instruction>>>::new();
        let mut insts: Vec<Box<dyn super::Instruction>> = vec![];
        for i in &self.f.instructions {
            insts.push(Box::new(Instruction { i: i.clone() }));
        }
        res.insert(self.f.instructions[0].offset as u64, insts);
        Ok(res)
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[derive(Debug, Clone)]
pub struct DnMethod {
    name: String,
    namespace: String,
    class_name: String,
    token: u64,
    access: Option<crate::rules::features::FeatureAccess>,
}

impl DnMethod {
    pub fn new(
        token: u64,
        namespace: &str,
        class_name: &str,
        method_name: &str,
        access: Option<crate::rules::features::FeatureAccess>,
    ) -> Self {
        Self {
            token,
            namespace: namespace.to_string(),
            class_name: class_name.to_string(),
            name: match method_name {
                ".ctor" => "ctor".to_string(),
                ".cctor" => "cctor".to_string(),
                _ => method_name.to_string(),
            },
            access,
        }
    }
}

impl std::fmt::Display for DnMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}::{}", self.namespace, self.class_name, self.name)
    }
}

enum Callee {
    Str(String),
    Method(DnMethod),
}

/// 0.4.0: full zero-copy. `Extractor<'a>` borrows the input bytes
/// from the caller for the lifetime `'a`. `DnPe<'a>` lives directly
/// on the struct — no `ouroboros` self-referential wrapper, no extra
/// `Vec<u8>` clone inside capa-rs.
///
/// Caller (typically `FileCapabilities::from_file`) reads the file
/// once and passes `&buf` into `Extractor::new`. The borrow lives as
/// long as the buffer.
pub struct Extractor<'a> {
    pe: DnPe<'a>,
    properties_cache: Arc<RwLock<Option<HashMap<u64, DnMethod>>>>,
    fields_cache: Arc<RwLock<Option<HashMap<u64, DnMethod>>>>,
}

impl std::fmt::Debug for Extractor<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Extractor").finish_non_exhaustive()
    }
}

// 0.4.0: same lifetime-shadow workaround as the smda extractor. The
// trait method `get_instructions<'a>` redeclares `'a`; we name the
// impl's parameter `'data` to avoid the shadow error.
impl<'data> super::Extractor for Extractor<'data> {
    fn is_dot_net(&self) -> bool {
        true
    }

    fn get_base_address(&self) -> Result<u64> {
        Ok(0)
    }

    fn arch(&self) -> Result<crate::FileArchitecture> {
        // .NET assemblies surface the CIL bitness via the existing
        // `extract_arch()` (CorFlags.32BIT_REQUIRED → I386, otherwise
        // AMD64). No AArch64 path — .NET assemblies are bitness-
        // agnostic at the CIL level and capa rules don't distinguish.
        self.extract_arch()
    }

    fn format(&self) -> super::FileFormat {
        super::FileFormat::DOTNET
    }

    fn bitness(&self) -> u32 {
        match self.extract_arch() {
            Ok(crate::FileArchitecture::AMD64) => 64,
            _ => 32,
        }
    }

    fn extract_global_features(&self) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        Ok(vec![
            (
                crate::rules::features::Feature::Os(crate::rules::features::OsFeature::new(
                    &crate::consts::Os::WINDOWS.to_string(),
                    "",
                )?),
                0,
            ),
            (
                crate::rules::features::Feature::Arch(crate::rules::features::ArchFeature::new(
                    &self.extract_arch()?.to_string(),
                    "",
                )?),
                0,
            ),
        ])
    }

    fn extract_file_features(&self) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut ss = self.extract_file_import_names()?;
        ss.extend(self.extract_file_function_names()?);
        ss.extend(self.extract_file_format()?);
        ss.extend(self.extract_file_mixed_mode_characteristic_features()?);
        ss.extend(self.extract_file_namespace_and_class_features()?);
        Ok(ss)
    }

    fn get_functions(&self) -> Result<std::collections::BTreeMap<u64, Box<dyn super::Function>>> {
        // 0.5.0: rebuilt to match Python capa's `calls_to` (callers,
        // incoming) / `calls_from` (callees, outgoing) convention.
        // Pre-0.5.0 had two bugs that compounded into a silently-wrong
        // call graph for every .NET assembly:
        //   1. `calls_to` was initialised empty and never populated.
        //   2. The reverse-index loop overwrote `f.calls_from` with the
        //      caller set instead of populating `f.calls_to`, which
        //      both inverted the `calls from` characteristic feature
        //      and broke the `recursive call` detector (it checked
        //      `f.calls_to`, which was always empty).
        //
        // First pass builds `callers_of[target] = {caller, ...}` and
        // records each function's outgoing callee set. Second pass
        // assembles the `Function` values with both fields filled in
        // the correct direction.
        let mut callers_of: HashMap<u64, HashSet<u64>> = HashMap::new();
        let mut callees_of: HashMap<u64, HashSet<u64>> = HashMap::new();

        for f in self.pe().net()?.functions() {
            let caller_addr = f.offset as u64;
            let mut my_callees: HashSet<u64> = HashSet::new();
            for insn in &f.instructions {
                if ![
                    OpCodeValue::Call,
                    OpCodeValue::Callvirt,
                    OpCodeValue::Jmp,
                    OpCodeValue::Newobj,
                ]
                .contains(&insn.opcode.value)
                {
                    continue;
                }
                let target = insn.operand.value()? as u64;
                my_callees.insert(target);
                callers_of.entry(target).or_default().insert(caller_addr);
            }
            callees_of.insert(caller_addr, my_callees);
        }

        let mut methods: HashMap<u64, Function> = HashMap::new();
        for f in self.pe().net()?.functions() {
            let addr = f.offset as u64;
            let calls_to = callers_of.remove(&addr).unwrap_or_default();
            let calls_from = callees_of.remove(&addr).unwrap_or_default();
            // `inrefs` is just the materialised caller list (the trait
            // returns `&Vec<u64>`; `calls_to` is a `HashSet`).
            let inrefs: Vec<u64> = calls_to.iter().copied().collect();
            // Single-block-per-method shape matches `get_blocks`.
            // First instruction's offset is the block key; no
            // intra-function successors at this granularity.
            let mut blockrefs: HashMap<u64, Vec<u64>> = HashMap::new();
            if let Some(first) = f.instructions.first() {
                blockrefs.insert(first.offset as u64, Vec::new());
            }
            methods.insert(
                addr,
                Function {
                    f: f.clone(),
                    calls_to,
                    calls_from,
                    inrefs,
                    blockrefs,
                },
            );
        }

        Ok(methods
            .into_iter()
            .map(|(a, b)| (a, Box::new(b) as Box<dyn super::Function>))
            .collect::<BTreeMap<u64, Box<dyn super::Function>>>())
    }

    fn extract_function_features(
        &self,
        f: &Box<dyn super::Function>,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let f: &Function = f.as_any().downcast_ref::<Function>().unwrap();
        Ok([
            self.extract_function_call_to_features(f)?,
            self.extract_function_call_from_features(f)?,
            self.extract_recurcive_call_features(f)?,
        ]
        .into_iter()
        .fold(Vec::new(), |mut acc, f| {
            acc.extend(f);
            acc
        }))
    }

    fn get_basic_blocks(
        &self,
        f: &Box<dyn super::Function>,
    ) -> Result<std::collections::BTreeMap<u64, Vec<Box<dyn super::Instruction>>>> {
        f.get_blocks()
    }

    fn get_instructions<'a>(
        &self,
        _f: &Box<dyn super::Function>,
        bb: &'a (&u64, &Vec<Box<dyn super::Instruction>>),
    ) -> Result<&'a Vec<Box<dyn super::Instruction>>> {
        Ok(bb.1)
    }

    fn extract_basic_block_features(
        &self,
        _f: &Box<dyn super::Function>,
        _bb: &(&u64, &Vec<Box<dyn super::Instruction>>),
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        Ok(vec![])
    }

    fn extract_insn_features(
        &self,
        f: &Box<dyn super::Function>,
        insn: &Box<dyn super::Instruction>,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let f: &Function = f.as_any().downcast_ref::<Function>().unwrap();
        let insn: &Instruction = insn.as_any().downcast_ref::<Instruction>().unwrap();
        let mut ss = self.extract_insn_api_features(&f.f, &insn.i)?;
        ss.extend(self.extract_insn_propery_features(&f.f, &insn.i)?);
        ss.extend(self.extract_insn_number_features(&f.f, &insn.i)?);
        ss.extend(self.extract_insn_string_features(&f.f, &insn.i)?);
        ss.extend(self.extract_insn_namespace_features(&f.f, &insn.i)?);
        ss.extend(self.extract_insn_class_features(&f.f, &insn.i)?);
        ss.extend(self.extract_unmanaged_call_characteristic_features(&f.f, &insn.i)?);
        ss.extend(self.extract_file_format()?);
        ss.extend(self.extract_global_features()?);
        Ok(ss)
    }
}

impl<'data> Extractor<'data> {
    /// 0.4.0: parse a CLR/.NET PE from a borrowed byte slice.
    ///
    /// Pre-0.4.0 this read the file internally and held the bytes via
    /// an `ouroboros` self-referential wrapper. The new API matches
    /// the smda extractor — caller owns the buffer, we borrow.
    pub fn new(data: &'data [u8]) -> Result<Extractor<'data>> {
        let pe = DnPe::parse(data)?;
        Ok(Extractor {
            pe,
            fields_cache: Arc::new(RwLock::new(None)),
            properties_cache: Arc::new(RwLock::new(None)),
        })
    }

    /// Borrowed view onto the parsed `DnPe`.
    pub(crate) fn pe(&self) -> &DnPe<'data> {
        &self.pe
    }

    pub fn extract_arch(&self) -> Result<crate::FileArchitecture> {
        if let Some(oh) = self.pe().pe()?.header.optional_header {
            if self
                .pe()
                .net()?
                .flags
                .contains(&dnfile::ClrHeaderFlags::BitRequired32)
                && oh.standard_fields.magic == goblin::pe::optional_header::MAGIC_32
            {
                Ok(crate::FileArchitecture::I386)
            } else {
                Ok(crate::FileArchitecture::AMD64)
            }
        } else {
            Err(crate::Error::UnsupportedArchError)
        }
    }

    pub fn extract_file_format(&self) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        Ok(vec![(
            crate::rules::features::Feature::Format(crate::rules::features::FormatFeature::new(
                "dotnet", "",
            )?),
            0,
        )])
    }

    pub fn extract_file_import_names(&self) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        for (token, imp) in self
            .get_dotnet_managed_imports()?
            .iter()
            .chain(self.get_dotnet_unmanaged_imports()?.iter())
        {
            if imp.contains("::") {
                res.push((
                    crate::rules::features::Feature::Import(
                        crate::rules::features::ImportFeature::new(imp, "")?,
                    ),
                    *token,
                ));
                //split :: get last part and add stringFeature
                let ss = imp.split("::").collect::<Vec<&str>>();
                let trimmed = ss[1].trim();
                if !trimmed.is_empty() {
                    res.push((
                        crate::rules::features::Feature::String(
                            crate::rules::features::StringFeature::new(trimmed, "")?,
                        ),
                        *token,
                    ));
                }
            } else {
                let ss = imp.split('.').collect::<Vec<&str>>();
                for symbol_variant in crate::extractor::smda::generate_symbols(
                    &Some(ss[0].to_string()),
                    &Some(ss[1].to_string()),
                )? {
                    res.push((
                        crate::rules::features::Feature::Import(
                            crate::rules::features::ImportFeature::new(&symbol_variant, "")?,
                        ),
                        *token,
                    ));
                }
            }
        }
        Ok(res)
    }

    ///emit namespace features from TypeRef and TypeDef tables
    pub fn extract_file_namespace_and_class_features(
        &self,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        // namespaces may be referenced multiple times, so we need to filter
        let mut namespaces = std::collections::HashSet::new();
        let typedef = self.pe().net()?.md_table("TypeDef")?;
        for rid in 0..typedef.row_count() {
            let row = typedef.row::<TypeDef>(rid)?;
            namespaces.insert(row.type_namespace.clone());
            let token = calculate_dotnet_token_value("TypeDef", rid + 1)?;
            res.push((
                crate::rules::features::Feature::Class(crate::rules::features::ClassFeature::new(
                    &format!("{}.{}", row.type_namespace, row.type_name),
                    "",
                )?),
                token,
            ))
        }
        let typedef = self.pe().net()?.md_table("TypeRef")?;
        for rid in 0..typedef.row_count() {
            let row = typedef.row::<TypeRef>(rid)?;
            namespaces.insert(row.type_namespace.clone());
            let token = calculate_dotnet_token_value("TypeRef", rid + 1)?;
            res.push((
                crate::rules::features::Feature::Class(crate::rules::features::ClassFeature::new(
                    &format!("{}.{}", row.type_namespace, row.type_name),
                    "",
                )?),
                token,
            ))
        }
        for ns in namespaces {
            if !ns.is_empty() {
                res.push((
                    crate::rules::features::Feature::Namespace(
                        crate::rules::features::NamespaceFeature::new(&ns, "")?,
                    ),
                    0,
                ))
            }
        }
        Ok(res)
    }

    pub fn extract_file_function_names(
        &self,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        for (_, method) in self.get_dotnet_managed_methods()? {
            res.push((
                crate::rules::features::Feature::FunctionName(
                    crate::rules::features::FunctionNameFeature::new(&method.to_string(), "")?,
                ),
                method.token,
            ));
        }
        Ok(res)
    }

    pub fn get_dotnet_managed_methods(&self) -> Result<HashMap<u64, DnMethod>> {
        let mut res = HashMap::new();
        let typedef = self.pe().net()?.md_table("TypeDef")?;
        for rid in 0..typedef.row_count() {
            let row = typedef.row::<TypeDef>(rid)?;
            for metdef in &row.method_list {
                let token = calculate_dotnet_token_value("MemberRef", rid + 1)?;
                res.insert(
                    token,
                    DnMethod::new(
                        token,
                        &row.type_namespace,
                        &row.type_name,
                        &self
                            .pe()
                            .net()?
                            .resolve_coded_index::<MethodDef>(metdef)?
                            .name,
                        None,
                    ),
                );
            }
        }
        Ok(res)
    }

    pub fn get_dotnet_property_map(&self, property_row: &Property) -> Result<Option<TypeDef>> {
        let property_map = self.pe().net()?.md_table("PropertyMap")?;
        for rid in 0..property_map.row_count() {
            let row = property_map.row::<PropertyMap>(rid)?;
            for i in &row.property_list {
                if i.name == property_row.name {
                    return Ok(Some(
                        self.pe()
                            .net()?
                            .resolve_coded_index::<TypeDef>(&row.parent)?
                            .clone(),
                    ));
                }
            }
        }
        Ok(None)
    }

    pub fn get_properties(&self) -> Result<Arc<RwLock<Option<HashMap<u64, DnMethod>>>>> {
        {
            let properties_read = self.properties_cache.read();
            if properties_read.is_some() {
                return Ok(self.properties_cache.clone());
            }
        }

        let mut properties_write = self.properties_cache.write();
        if properties_write.is_none() {
            let dotnet_properties = self.get_dotnet_properties()?;
            *properties_write = Some(dotnet_properties);
        }
        Ok(self.properties_cache.clone())
    }

    pub fn get_dotnet_properties(&self) -> Result<HashMap<u64, DnMethod>> {
        let mut res = HashMap::new();
        let method_semantics = if let Ok(s) = self.pe().net()?.md_table("MethodSemantics") {
            s
        } else {
            return Ok(res);
        };
        for rid in 0..method_semantics.row_count() {
            let row = method_semantics.row::<MethodSemantics>(rid)?;
            let typedef_row = match self.get_dotnet_property_map(
                self.pe()
                    .net()?
                    .resolve_coded_index::<Property>(&row.association)?,
            )? {
                Some(s) => s,
                None => continue,
            };
            let token = calculate_dotnet_token_value("MethodSemantics", rid + 1)?;
            let access = if row
                .semantics
                .contains(&enums::ClrMethodSemanticsAttr::Setter)
            {
                Some(crate::rules::features::FeatureAccess::Write)
            } else if row
                .semantics
                .contains(&enums::ClrMethodSemanticsAttr::Getter)
            {
                Some(crate::rules::features::FeatureAccess::Read)
            } else {
                None
            };
            res.insert(
                token,
                DnMethod::new(
                    token,
                    &typedef_row.type_namespace,
                    &typedef_row.type_name,
                    &self
                        .pe()
                        .net()?
                        .resolve_coded_index::<Property>(&row.association)?
                        .name,
                    access,
                ),
            );
        }
        Ok(res)
    }

    pub fn get_fields(&self) -> Result<&RwLock<Option<HashMap<u64, DnMethod>>>> {
        {
            let fields_read = self.fields_cache.read();
            if fields_read.is_some() {
                return Ok(&self.fields_cache);
            }
        }

        let mut fields_write = self.fields_cache.write();
        if fields_write.is_none() {
            let dotnet_fields = self.get_dotnet_fields()?;
            *fields_write = Some(dotnet_fields);
        }
        Ok(&self.fields_cache)
    }

    /// get fields from TypeDef table
    pub fn get_dotnet_fields(&self) -> Result<HashMap<u64, DnMethod>> {
        let mut res = HashMap::new();
        let type_defs = self.pe().net()?.md_table("TypeDef")?;
        for rid in 0..type_defs.row_count() {
            let row = type_defs.row::<TypeDef>(rid)?;
            for index in &row.field_list {
                let ss = self.pe().net()?.resolve_coded_index::<Field>(index)?;
                let token = calculate_dotnet_token_value("TypeDef", rid + 1)?;
                res.insert(
                    token,
                    DnMethod::new(token, &row.type_namespace, &row.type_name, &ss.name, None),
                );
            }
        }
        Ok(res)
    }

    pub fn get_dotnet_managed_imports(&self) -> Result<HashMap<u64, String>> {
        let mut res = HashMap::new();
        let memref = self.pe().net()?.md_table("MemberRef")?;
        let typeref = self.pe().net()?.md_table("TypeRef")?;
        for rid in 0..memref.row_count() {
            let row = memref.row::<MemberRef>(rid)?;
            if row.class.table != "TypeRef" {
                continue;
            }
            let typeref_row = typeref.row::<TypeRef>(row.class.row_index - 1)?;
            let token = calculate_dotnet_token_value("MemberRef", rid + 1)?;
            let imp = format!(
                "{}.{}::{}",
                typeref_row.type_namespace, typeref_row.type_name, row.name
            );
            res.insert(token, imp);
        }
        Ok(res)
    }

    pub fn get_dotnet_unmanaged_imports(&self) -> Result<HashMap<u64, String>> {
        let mut res = HashMap::new();
        if let Ok(implmap) = self.pe().net()?.md_table("ImplMap") {
            for rid in 0..implmap.row_count() {
                let row = implmap.row::<ImplMap>(rid)?;
                let import_scope = self
                    .pe()
                    .net()?
                    .resolve_coded_index::<ModuleRef>(&row.import_scope)?;
                let mut dll = import_scope.name.clone();
                let symbol = row.import_name.clone();
                let token = calculate_dotnet_token_value(
                    row.member_forwarded.table(),
                    row.member_forwarded.row_index(),
                )?;
                if !dll.is_empty() && dll.contains('.') {
                    dll = dll.split('.').collect::<Vec<&str>>()[0].to_string();
                }
                res.insert(token, format!("{}.{}", dll, symbol));
            }
        }
        Ok(res)
    }

    pub fn extract_file_mixed_mode_characteristic_features(
        &self,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        if is_dotnet_mixed_mode(self.pe())? {
            Ok(vec![(
                crate::rules::features::Feature::Characteristic(
                    crate::rules::features::CharacteristicFeature::new("mixed mode", "")?,
                ),
                0,
            )])
        } else {
            Ok(vec![])
        }
    }

    fn extract_function_call_to_features(
        &self,
        f: &Function,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        Ok(f.calls_to
            .iter()
            .map(|a| {
                (
                    crate::rules::features::Feature::Characteristic(
                        crate::rules::features::CharacteristicFeature::new("calls to", "").unwrap(),
                    ),
                    *a,
                )
            })
            .collect())
    }

    fn extract_function_call_from_features(
        &self,
        f: &Function,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        // 0.5.0: read `calls_from` (callees) not `calls_to` (callers).
        // Pre-0.5.0 this was a copy-paste from
        // `extract_function_call_to_features` that silently emitted the
        // caller set for every `characteristic: calls from` rule on
        // .NET assemblies. Matches Python capa's
        // `extract_function_calls_from` in dnfile/function.py.
        Ok(f.calls_from
            .iter()
            .map(|a| {
                (
                    crate::rules::features::Feature::Characteristic(
                        crate::rules::features::CharacteristicFeature::new("calls from", "")
                            .unwrap(),
                    ),
                    *a,
                )
            })
            .collect())
    }

    fn extract_recurcive_call_features(
        &self,
        f: &Function,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        if f.calls_to.contains(&(f.f.offset as u64)) {
            Ok(vec![(
                crate::rules::features::Feature::Characteristic(
                    crate::rules::features::CharacteristicFeature::new("recursive call", "")?,
                ),
                f.f.offset as u64,
            )])
        } else {
            Ok(vec![])
        }
    }

    fn get_callee(&self, token: u64) -> Result<Option<Callee>> {
        // map dotnet token to un/managed method
        match self.get_dotnet_managed_imports()?.get(&token) {
            None => {
                // we must check unmanaged imports before managed methods because we map forwarded managed methods
                // to their unmanaged imports; we prefer a forwarded managed method be mapped to its unmanaged import for analysis
                match self.get_dotnet_unmanaged_imports()?.get(&token) {
                    None => match self.get_dotnet_managed_methods()?.get(&token) {
                        None => Ok(None),
                        Some(s) => Ok(Some(Callee::Method(s.clone()))),
                    },
                    Some(s) => Ok(Some(Callee::Str(s.clone()))),
                }
            }
            Some(s) => Ok(Some(Callee::Str(s.clone()))),
        }
    }

    pub fn extract_insn_api_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        if ![
            OpCodeValue::Call,
            OpCodeValue::Callvirt,
            OpCodeValue::Jmp,
            OpCodeValue::Calli,
            OpCodeValue::Newobj,
        ]
        .contains(&insn.opcode.value)
        {
            return Ok(vec![]);
        }

        match self.get_callee(insn.operand.value()? as u64)? {
            None => {}
            Some(Callee::Str(s)) => {
                let ss = s.split('.').collect::<Vec<&str>>();
                for symbol_variant in crate::extractor::smda::generate_symbols(
                    &Some(ss[0].to_string()),
                    &Some(ss[1].to_string()),
                )? {
                    res.push((
                        crate::rules::features::Feature::Api(
                            crate::rules::features::ApiFeature::new(&symbol_variant, "")?,
                        ),
                        insn.offset as u64,
                    ));
                }
                //same for ::
                if s.contains("::") {
                    let ss = s.split("::").collect::<Vec<&str>>();
                    for symbol_variant in crate::extractor::smda::generate_symbols(
                        &Some(ss[0].to_string()),
                        &Some(ss[1].to_string()),
                    )? {
                        res.push((
                            crate::rules::features::Feature::Api(
                                crate::rules::features::ApiFeature::new(&symbol_variant, "")?,
                            ),
                            insn.offset as u64,
                        ));
                    }
                }
            }
            Some(Callee::Method(m)) => {
                if m.name.starts_with("get_") || m.name.starts_with("set_") {
                    let row = resolve_dotnet_token(
                        self.pe(),
                        &cil::instruction::Operand::Token(clr::token::Token::new(
                            insn.operand.value()?,
                        )),
                    )?;
                    if row.downcast_ref::<MethodDef>().is_some() {
                        if self
                            .get_properties()?
                            .read()
                            .as_ref()
                            .unwrap()
                            .get(&(insn.operand.value()? as u64))
                            .is_some()
                        {
                            return Ok(res);
                        }
                    } else if row.downcast_ref::<MemberRef>().is_some() {
                        return Ok(res);
                    }
                    res.push((
                        crate::rules::features::Feature::Api(
                            crate::rules::features::ApiFeature::new(&m.to_string(), "")?,
                        ),
                        insn.offset as u64,
                    ));
                }
            }
        }
        Ok(res)
    }

    /// parse instruction property features
    pub fn extract_insn_propery_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = Vec::new();
        if [
            OpCodeValue::Call,
            OpCodeValue::Callvirt,
            OpCodeValue::Jmp,
            OpCodeValue::Calli,
        ]
        .contains(&insn.opcode.value)
        {
            let operand_result = resolve_dotnet_token(
                self.pe(),
                &cil::instruction::Operand::Token(clr::token::Token::new(insn.operand.value()?)),
            );

            if let Ok(operand) = operand_result {
                if operand.downcast_ref::<MethodDef>().is_some() {
                    if let Ok(properties_lock) = self.get_properties() {
                        if let Some(properties) = properties_lock.read().as_ref() {
                            if let Some(prop) = properties.get(&(insn.operand.value()? as u64)) {
                                res.push((
                                    crate::rules::features::Feature::Property(
                                        crate::rules::features::PropertyFeature::new(
                                            &prop.to_string(),
                                            prop.access.clone(),
                                            "",
                                        )?,
                                    ),
                                    insn.offset as u64,
                                ));
                            }
                        }
                    }
                } else if let Some(operand) = operand.downcast_ref::<MemberRef>() {
                    // Verifica si el nombre del método indica un acceso a una propiedad (get o set).
                    if operand.name.starts_with("get_") || operand.name.starts_with("set_") {
                        // Obtiene el namespace y el nombre de la clase a la que pertenece el MemberRef.
                        let (operand_class_type_namespace, operand_class_type_name) =
                            match operand.class.table() {
                                "TypeRef" => {
                                    if let Ok(rr) = self
                                        .pe()
                                        .net()?
                                        .resolve_coded_index::<TypeRef>(&operand.class)
                                    {
                                        (rr.type_namespace.clone(), rr.type_name.clone())
                                    } else {
                                        return Ok(vec![]);
                                    }
                                }
                                "TypeDef" => {
                                    if let Ok(rr) = self
                                        .pe()
                                        .net()?
                                        .resolve_coded_index::<TypeDef>(&operand.class)
                                    {
                                        (rr.type_namespace.clone(), rr.type_name.clone())
                                    } else {
                                        return Ok(vec![]);
                                    }
                                }
                                _ => return Ok(vec![]),
                            };

                        // Construye el nombre completo de la propiedad accedida.
                        let property_name = format!(
                            "{}.{}::{}",
                            operand_class_type_namespace,
                            operand_class_type_name,
                            &operand.name[4..] // Remueve "get_" o "set_" del nombre.
                        );

                        // Determina el tipo de acceso (lectura o escritura) basado en el prefijo del nombre del método.
                        let access = if operand.name.starts_with("get_") {
                            Some(crate::rules::features::FeatureAccess::Read)
                        } else {
                            Some(crate::rules::features::FeatureAccess::Write)
                        };

                        // Retorna la información de la propiedad como una característica.
                        return Ok(vec![(
                            crate::rules::features::Feature::Property(
                                crate::rules::features::PropertyFeature::new(
                                    &property_name,
                                    access,
                                    "", // Aquí puedes agregar una descripción adicional si es necesario.
                                )?,
                            ),
                            insn.offset as u64,
                        )]);
                    }
                }
            }
        } else if [
            OpCodeValue::Ldfld,
            OpCodeValue::Ldflda,
            OpCodeValue::Ldsfld,
            OpCodeValue::Ldsflda,
            OpCodeValue::Stfld,
            OpCodeValue::Stsfld,
        ]
        .contains(&insn.opcode.value)
        {
            if let Ok(fields_lock) = self.get_fields() {
                if let Some(fields) = fields_lock.read().as_ref() {
                    if let Some(field) = fields.get(&(insn.operand.value()? as u64)) {
                        let access = if [OpCodeValue::Stfld, OpCodeValue::Stsfld]
                            .contains(&insn.opcode.value)
                        {
                            Some(crate::rules::features::FeatureAccess::Write)
                        } else {
                            Some(crate::rules::features::FeatureAccess::Read)
                        };
                        res.push((
                            crate::rules::features::Feature::Property(
                                crate::rules::features::PropertyFeature::new(
                                    &field.to_string(),
                                    access,
                                    "",
                                )?,
                            ),
                            insn.offset as u64,
                        ));
                    }
                }
            }
        }

        Ok(res)
    }

    pub fn extract_insn_number_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        if insn.is_ldc() {
            res.push((
                crate::rules::features::Feature::Number(
                    crate::rules::features::NumberFeature::new(
                        self.bitness(),
                        &(insn.get_ldc().unwrap() as i128),
                        "",
                    )?,
                ),
                insn.offset as u64,
            ));
        }
        Ok(res)
    }

    pub fn extract_insn_string_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        let mut res = vec![];
        if !insn.is_ldstr() {
            return Ok(res);
        }
        if let cil::instruction::Operand::StringToken(t) = &insn.operand {
            match self.pe().net()?.get_us(t.rid()) {
                Err(_) => Ok(res),
                Ok(s) => {
                    let trimmed = s.trim();
                    if !trimmed.is_empty() {
                        res.push((
                            crate::rules::features::Feature::String(
                                crate::rules::features::StringFeature::new(trimmed, "")?,
                            ),
                            insn.offset as u64,
                        ));
                    }
                    Ok(res)
                }
            }
        } else {
            Ok(res)
        }
    }

    ///parse instruction namespace features
    pub fn extract_insn_namespace_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        if self.check_contains_opcode(insn) {
            return Ok(vec![]);
        }
        let mut res = vec![];
        let operand = resolve_dotnet_token(
            self.pe(),
            &cil::instruction::Operand::Token(clr::token::Token::new(insn.operand.value()?)),
        )?;
        if let Some(s) = operand.downcast_ref::<MemberRef>() {
            if let Ok(ss) = &self.pe().net()?.resolve_coded_index::<TypeDef>(&s.class) {
                if !ss.type_namespace.is_empty() {
                    res.push((
                        crate::rules::features::Feature::Namespace(
                            crate::rules::features::NamespaceFeature::new(&ss.type_namespace, "")?,
                        ),
                        insn.offset as u64,
                    ))
                }
            } else if let Ok(ss) = &self.pe().net()?.resolve_coded_index::<TypeRef>(&s.class) {
                if !ss.type_namespace.is_empty() {
                    res.push((
                        crate::rules::features::Feature::Namespace(
                            crate::rules::features::NamespaceFeature::new(&ss.type_namespace, "")?,
                        ),
                        insn.offset as u64,
                    ));
                }
            }
        } else if operand.downcast_ref::<MethodDef>().is_some() {
            if let Some(Callee::Method(dm)) = self.get_callee(insn.operand.value()? as u64)? {
                if !dm.namespace.is_empty() {
                    res.push((
                        crate::rules::features::Feature::Namespace(
                            crate::rules::features::NamespaceFeature::new(&dm.namespace, "")?,
                        ),
                        insn.offset as u64,
                    ));
                }
            }
        } else if operand.downcast_ref::<Field>().is_some() {
            let fields_lock = self.get_fields()?.read();

            if let Some(fields) = &*fields_lock {
                if let Some(field) = fields.clone().get(&(insn.operand.value()? as u64)) {
                    if !field.namespace.is_empty() {
                        res.push((
                            crate::rules::features::Feature::Namespace(
                                crate::rules::features::NamespaceFeature::new(
                                    &field.namespace,
                                    "",
                                )?,
                            ),
                            insn.offset as u64,
                        ));
                    }
                }
            }
        }
        Ok(res)
    }

    fn check_contains_opcode(&self, insn: &cil::instruction::Instruction) -> bool {
        if ![
            OpCodeValue::Call,
            OpCodeValue::Callvirt,
            OpCodeValue::Jmp,
            OpCodeValue::Calli,
            OpCodeValue::Ldfld,
            OpCodeValue::Ldflda,
            OpCodeValue::Ldsfld,
            OpCodeValue::Ldsflda,
            OpCodeValue::Stfld,
            OpCodeValue::Stsfld,
            OpCodeValue::Newobj,
        ]
        .contains(&insn.opcode.value)
        {
            return true;
        }
        false
    }
    ///parse instruction class features
    pub fn extract_insn_class_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        if self.check_contains_opcode(insn) {
            return Ok(vec![]);
        }

        let mut res = vec![];
        let operand = resolve_dotnet_token(
            self.pe(),
            &cil::instruction::Operand::Token(clr::token::Token::new(insn.operand.value()?)),
        )?;
        if let Some(s) = operand.downcast_ref::<MemberRef>() {
            if let Ok(ss) = &self.pe().net()?.resolve_coded_index::<TypeDef>(&s.class) {
                res.push((
                    crate::rules::features::Feature::Class(
                        crate::rules::features::ClassFeature::new(
                            &format!("{}.{}", ss.type_namespace, ss.type_name),
                            "",
                        )?,
                    ),
                    insn.offset as u64,
                ))
            } else if let Ok(ss) = &self.pe().net()?.resolve_coded_index::<TypeRef>(&s.class) {
                res.push((
                    crate::rules::features::Feature::Class(
                        crate::rules::features::ClassFeature::new(
                            &format!("{}.{}", ss.type_namespace, ss.type_name),
                            "",
                        )?,
                    ),
                    insn.offset as u64,
                ));
            }
        } else if operand.downcast_ref::<MethodDef>().is_some() {
            if let Some(Callee::Method(dm)) = self.get_callee(insn.operand.value()? as u64)? {
                res.push((
                    crate::rules::features::Feature::Class(
                        crate::rules::features::ClassFeature::new(
                            &format!("{}.{}", dm.namespace, dm.class_name),
                            "",
                        )?,
                    ),
                    insn.offset as u64,
                ));
            }
        } else if operand.downcast_ref::<Field>().is_some() {
            let fields_lock = self.get_fields()?.read();
            if let Some(fields) = &*fields_lock {
                if let Some(field) = fields.get(&(insn.operand.value()? as u64)) {
                    res.push((
                        crate::rules::features::Feature::Class(
                            crate::rules::features::ClassFeature::new(
                                &format!("{}.{}", field.namespace, field.class_name),
                                "",
                            )?,
                        ),
                        insn.offset as u64,
                    ));
                }
            }
        }

        Ok(res)
    }

    pub fn extract_unmanaged_call_characteristic_features(
        &self,
        _f: &cil::function::Function,
        insn: &cil::instruction::Instruction,
    ) -> Result<Vec<(crate::rules::features::Feature, u64)>> {
        if ![
            OpCodeValue::Call,
            OpCodeValue::Callvirt,
            OpCodeValue::Jmp,
            OpCodeValue::Calli,
        ]
        .contains(&insn.opcode.value)
        {
            return Ok(vec![]);
        }
        let mut res = vec![];
        let token = resolve_dotnet_token(self.pe(), &insn.operand)?;
        if let Some(s) = token.downcast_ref::<MethodDef>() {
            if s.flags.contains(&dnfile::stream::meta_data_tables::mdtables::enums::ClrMethodAttr::AttrFlag(dnfile::stream::meta_data_tables::mdtables::enums::CorMethodAttrFlag::PinvokeImpl))
                || s.impl_flags.contains(&dnfile::stream::meta_data_tables::mdtables::enums::ClrMethodImpl::MethodManaged(dnfile::stream::meta_data_tables::mdtables::enums::CorMethodManaged::Unmanaged))
                || s.impl_flags.contains(&dnfile::stream::meta_data_tables::mdtables::enums::ClrMethodImpl::MethodCodeType(dnfile::stream::meta_data_tables::mdtables::enums::CorMethodCodeType::Native)){
                res.push((crate::rules::features::Feature::Characteristic(crate::rules::features::CharacteristicFeature::new("unmanaged call", "")?),
                          insn.offset as u64,
                ));
            }
        }
        Ok(res)
    }
}

pub fn calculate_dotnet_token_value(table: &'static str, rid: usize) -> Result<u64> {
    let table_number = table_name_2_index(table)?;
    Ok((((table_number & 0xFF) << clr::token::TABLE_SHIFT) | (rid & clr::token::RID_MASK)) as u64)
}

pub fn is_dotnet_mixed_mode(pe: &dnfile::DnPe) -> Result<bool> {
    Ok(!pe.net()?.flags.contains(&dnfile::ClrHeaderFlags::IlOnly))
}

///map generic token to string or table row
pub fn resolve_dotnet_token<'a>(
    pe: &'a dnfile::DnPe,
    token: &cil::instruction::Operand,
) -> Result<&'a dyn std::any::Any> {
    //    if let cil::instruction::Operand::StringToken(t) = token{
    //        let user_string = read_dotnet_user_string(pe, t);
    //        if let Ok(s) = user_string{
    //            return Ok(s);
    //        } else {
    //            return Err(crate::Error::InvalidToken(format!("{:?}", token)));
    //        }
    //    }
    if let cil::instruction::Operand::Token(t) = token {
        let table = pe.net()?.md_table_by_index(&t.table())?;
        return Ok(table.get_row(t.rid() - 1)?.get_row().as_any());
    }
    Err(crate::Error::InvalidToken(format!("{:?}", token)))
}

///read user string from #US stream
pub fn _read_dotnet_user_string(pe: &dnfile::DnPe, token: &clr::token::Token) -> Result<String> {
    Ok(pe.net()?.metadata.get_us(token.rid())?)
}