smda 0.5.2

Recursive x86/x64 disassembler library for control-flow recovery from memory dumps. Iced-x86-backed; zero-copy.
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
use crate::function::DecodedInsn;
use crate::{
    DisassemblyResult, FunctionAnalysisState, Result, error::Error,
    function_candidate::FunctionCandidate,
};
use iced_x86::{Decoder, DecoderOptions, Mnemonic};
use itertools::Itertools;
use regex::bytes::Regex as BytesRegex;
use std::sync::LazyLock;
use std::{collections::BTreeMap, collections::HashMap, convert::TryInto};

/// Default function-prologue byte patterns scanned across each section.
///
/// Sources:
/// - The first four are classic MSVC: `mov edi, edi; push ebp; mov ebp, esp`
///   (the `8B FF` "hotpatch NOP"), plain `push ebp; mov ebp, esp`, and
///   the AT&T-syntax variant `push ebp; mov ebp, esp` (`55 89 E5`).
/// - 0.4.1 adds:
///   - `F3 0F 1E FA` — `endbr64`, the Intel CET indirect-branch landing
///     pad emitted by GCC / clang with `-fcf-protection` (default on
///     modern Ubuntu, Fedora, RHEL, Debian). Almost every function in a
///     modern dynamically-linked ELF starts with this.
///   - `F3 0F 1E FB` — `endbr32`, the 32-bit equivalent.
///   - `48 89 5C 24 ??` — `mov [rsp+disp8], rbx`, a very common GCC
///     callee-saved-register save in the function preamble.
///   - `48 83 EC ??` — `sub rsp, imm8`, the canonical Sys V AMD64 stack
///     frame setup when no `rbp` chain is used.
///   - `41 57 41 56` — `push r15; push r14`, the start of a typical
///     GCC-emitted register save sequence for functions that touch the
///     extended registers.
static DEFAULT_PROLOGUES: LazyLock<Vec<BytesRegex>> = LazyLock::new(|| {
    vec![
        // MSVC family (32 / 64 bit)
        BytesRegex::new(r"(?-u)\x8B\xFF\x55\x8B\xEC").unwrap(),
        BytesRegex::new(r"(?-u)\x89\xFF\x55\x8B\xEC").unwrap(),
        BytesRegex::new(r"(?-u)\x55\x8B\xEC").unwrap(),
        BytesRegex::new(r"(?-u)\x55\x89\xE5").unwrap(),
        // Intel CET landing pads — used by GCC / clang with -fcf-protection
        BytesRegex::new(r"(?-u)\xF3\x0F\x1E\xFA").unwrap(), // endbr64
        BytesRegex::new(r"(?-u)\xF3\x0F\x1E\xFB").unwrap(), // endbr32
        // GCC / clang Sys V AMD64 prologue families. The `[\S\s]` matches
        // any single byte for the imm8 displacement.
        BytesRegex::new(r"(?-u)\x48\x89\x5C\x24[\S\s]").unwrap(), // mov [rsp+disp8], rbx
        BytesRegex::new(r"(?-u)\x48\x83\xEC[\S\s]").unwrap(),     // sub rsp, imm8
        BytesRegex::new(r"(?-u)\x41\x57\x41\x56").unwrap(),       // push r15; push r14
        // 0.5.2 — Apple-clang x86_64 patterns that previously slipped
        // through (smda-rs missed most /bin/ls-style binaries because of
        // these absences). All very specific multi-byte sequences so the
        // false-positive rate stays low.
        BytesRegex::new(r"(?-u)\x55\x48\x89\xE5").unwrap(), // push rbp; mov rbp, rsp
        BytesRegex::new(r"(?-u)\x48\x81\xEC[\S\s]{4}").unwrap(), // sub rsp, imm32 (large frame)
        BytesRegex::new(r"(?-u)\x48\x89\x6C\x24[\S\s]").unwrap(), // mov [rsp+disp8], rbp
        BytesRegex::new(r"(?-u)\x41\x56\x53").unwrap(),     // push r14; push rbx
        BytesRegex::new(r"(?-u)\x41\x55\x41\x54").unwrap(), // push r13; push r12
        BytesRegex::new(r"(?-u)\x53\x48\x83\xEC").unwrap(), // push rbx; sub rsp, ...
    ]
});
static REF_CANDIDATE: LazyLock<BytesRegex> =
    LazyLock::new(|| BytesRegex::new(r"(?-u)\xE8").unwrap());
static BITNESS: LazyLock<BytesRegex> = LazyLock::new(|| BytesRegex::new(r"(?-u)\xFF\x25").unwrap());
static STUB_CHAIN: LazyLock<BytesRegex> =
    LazyLock::new(|| BytesRegex::new(r"(?-u)(?P<block>(\xFF\x25[\S\s]{4}){2,})").unwrap());
static STUB_CHAIN_FUNC: LazyLock<BytesRegex> =
    LazyLock::new(|| BytesRegex::new(r"(?-u)\xFF\x25(?P<function>[\S\s]{4})").unwrap());
static STUB_CHAIN_BLOCK: LazyLock<BytesRegex> = LazyLock::new(|| {
    BytesRegex::new(r"(?-u)(?P<block>(\xFF\x25[\S\s]{4}\x68[\S\s]{4}\xE9[\S\s]{4}){2,})").unwrap()
});
static STUB_CHAIN_BLOCK_FUNC: LazyLock<BytesRegex> =
    LazyLock::new(|| BytesRegex::new(r"(?-u)\xFF\x25(?P<function>[\S\s]{4})").unwrap());
static CELL_MATCH: LazyLock<BytesRegex> =
    LazyLock::new(|| BytesRegex::new(r"(?-u)\xFF\x15").unwrap());

#[derive(Debug)]
struct GapSequences {
    gs: HashMap<usize, Vec<Vec<u8>>>,
}

impl GapSequences {
    pub fn new() -> GapSequences {
        let mut gs = GapSequences { gs: HashMap::new() };
        gs.gs.insert(
            1,
            vec![
                b"\x90".to_vec(), //NOP1_OVERRIDE_NOP - AMD / nop - INTEL
                b"\xCC".to_vec(), //int3
                b"\x00".to_vec(), //pass over sequences of null bytes
            ],
        );
        gs.gs.insert(
            2,
            vec![
                b"\x66\x90".to_vec(), //NOP2_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x8b\xc0".to_vec(),
                b"\x8b\xff".to_vec(), //mov edi, edi
                b"\x8d\x00".to_vec(), //lea eax, dword ptr [eax]
                b"\x86\xc0".to_vec(), //xchg al, al
                b"\x66\x2e".to_vec(), //NOP2_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x89\xf6".to_vec(), //mov esi, esi
            ],
        );
        gs.gs.insert(
            3,
            vec![
                b"\x0f\x1f\x00".to_vec(), // NOP3_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x8d\x40\x00".to_vec(), // lea eax, dword ptr [eax]
                b"\x8d\x00\x00".to_vec(), // lea eax, dword ptr [eax]
                b"\x8d\x49\x00".to_vec(), // lea ecx, dword ptr [ecx]
                b"\x8d\x64\x24".to_vec(), // lea esp, dword ptr [esp]
                b"\x8d\x76\x00".to_vec(),
                b"\x66\x66\x90".to_vec(),
            ],
        );
        gs.gs.insert(
            4,
            vec![
                b"\x0f\x1f\x40\x00".to_vec(), // NOP4_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x8d\x74\x26\x00".to_vec(),
                b"\x66\x66\x66\x90".to_vec(),
            ],
        );
        gs.gs.insert(
            5,
            vec![
                b"\x0f\x1f\x44\x00\x00".to_vec(), //NOP5_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x90\x8d\x74\x26\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            6,
            vec![
                b"\x66\x0f\x1f\x44\x00\x00".to_vec(), // NOP6_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x8d\xb6\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            7,
            vec![
                b"\x0f\x1f\x80\x00\x00\x00\x00".to_vec(), // NOP7_OVERRIDE_NOP - AMD / nop - INTEL,
                b"\x8d\xb4\x26\x00\x00\x00\x00".to_vec(),
                b"\x8D\xBC\x27\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            8,
            vec![
                b"\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(), // NOP8_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x90\x8d\xb4\x26\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            9,
            vec![
                b"\x66\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(), // NOP9_OVERRIDE_NOP - AMD / nop - INTEL
                b"\x89\xf6\x8d\xbc\x27\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            10,
            vec![
                b"\x66\x66\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(), // NOP10_OVERRIDE_NOP - AMD
                b"\x8d\x76\x00\x8d\xbc\x27\x00\x00\x00\x00".to_vec(),
                b"\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            11,
            vec![
                b"\x66\x66\x66\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(), // NOP11_OVERRIDE_NOP - AMD
                b"\x8d\x74\x26\x00\x8d\xbc\x27\x00\x00\x00\x00".to_vec(),
                b"\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            12,
            vec![
                b"\x8d\xb6\x00\x00\x00\x00\x8d\xbf\x00\x00\x00\x00".to_vec(),
                b"\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            13,
            vec![
                b"\x8d\xb6\x00\x00\x00\x00\x8d\xbc\x27\x00\x00\x00\x00".to_vec(),
                b"\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            14,
            vec![
                b"\x8d\xb4\x26\x00\x00\x00\x00\x8d\xbc\x27\x00\x00\x00\x00".to_vec(),
                b"\x66\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec(),
            ],
        );
        gs.gs.insert(
            15,
            vec![b"\x66\x66\x66\x66\x66\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00".to_vec()],
        );
        gs
    }
}

#[derive(Debug)]
pub struct FunctionCandidateManager {
    pub bitness: u32,
    identified_alignment: u32,
    code_areas: Vec<(u64, u64)>,
    all_call_refs: HashMap<u64, u64>,
    pub symbol_addresses: Vec<u64>,
    pub candidates: BTreeMap<u64, FunctionCandidate>,
    candidate_offsets: Vec<u64>,
    gs: GapSequences,
    candidate_queue: Vec<u64>,
    gap_pointer: u64,
    previously_analyzed_gap: u64,
    function_gaps: Vec<(u64, u64, u64)>,
}

impl FunctionCandidateManager {
    pub fn new() -> FunctionCandidateManager {
        FunctionCandidateManager {
            bitness: 0,
            identified_alignment: 0,
            code_areas: vec![],
            all_call_refs: HashMap::new(),
            symbol_addresses: vec![],
            candidates: BTreeMap::<u64, FunctionCandidate>::new(),
            candidate_offsets: vec![],
            gs: GapSequences::new(),
            candidate_queue: vec![],
            gap_pointer: 0,
            previously_analyzed_gap: 0,
            function_gaps: vec![],
        }
    }

    pub fn init(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        self.bitness = disassembly.binary_info.bitness;
        self.identified_alignment = 0;
        self.code_areas = disassembly.binary_info.code_areas.clone();
        self.locate_candidates(disassembly)?;
        Ok(())
    }

    fn locate_candidates(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        self.locate_symbol_candidates(disassembly)?;
        self.locate_reference_candidates(disassembly)?;
        self.locate_prologue_candidates(disassembly)?;
        //       self.locateLangSpecCandidates()?;
        self.locate_stub_chain_candidates(disassembly)?;
        self.locate_exception_handler_candidates(disassembly)?;
        self.identified_alignment = self.identify_alignment()?;
        Ok(())
    }

    fn locate_symbol_candidates(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        let s = self.symbol_addresses.clone();
        for symbol_addr in s {
            self.add_symbol_candidate(&symbol_addr, disassembly)?;
        }
        Ok(())
    }

    fn add_symbol_candidate(
        &mut self,
        addr: &u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(*addr))? {
            return Ok(false);
        }
        self.ensure_candidate(*addr, disassembly)?;
        if let Some(s) = self.candidates.get_mut(addr) {
            s.set_is_symbol(true)?;
            s.set_initial_candidate();
        }
        Ok(true)
    }

    fn identify_alignment(&self) -> Result<u32> {
        let mut identified_alignment = 0;
        //        if self.config.USE_ALIGNMENT:
        let mut num_candidates = 0;
        for candidate in self.candidates.values() {
            if candidate.call_ref_sources.len() > 1 {
                num_candidates += 1;
            }
        }
        let mut num_aligned_16_candidates = 0;
        for candidate in self.candidates.values() {
            if candidate.call_ref_sources.len() > 1 && candidate.alignment == 16 {
                num_aligned_16_candidates += 1;
            }
        }
        let mut num_aligned_4_candidates = 0;
        for candidate in self.candidates.values() {
            if candidate.call_ref_sources.len() > 1 && candidate.alignment == 4 {
                num_aligned_4_candidates += 1;
            }
        }
        if num_candidates > 0 {
            let alignment_16_ratio = 1.0 * num_aligned_16_candidates as f32 / num_candidates as f32;
            let alignment_4_ratio = 1.0 * num_aligned_4_candidates as f32 / num_candidates as f32;
            if num_candidates > 20 && alignment_4_ratio > 0.95 {
                identified_alignment = 4;
            }
            if num_candidates > 20 && alignment_16_ratio > 0.95 {
                identified_alignment = 16;
            }
        }
        Ok(identified_alignment)
    }

    /// PE x64 `.pdata` sweep — seeds the candidate scanner with function
    /// starts published by the exception-handler runtime.
    ///
    /// 0.4.2 (M3) tightens validation: each `RUNTIME_FUNCTION` entry now
    /// has its `EndAddress`, `UnwindInfoAddress`, and the pointed-at
    /// `UNWIND_INFO` header checked before the `BeginAddress` is accepted
    /// as a candidate. Drops false-positive seeds from packed or
    /// partially-overwritten `.pdata` sections that the 0.4.1 blind sweep
    /// accepted unconditionally.
    ///
    /// Validation rules (all must hold):
    /// - `EndAddress > BeginAddress`
    /// - `EndAddress - BeginAddress < 16 MiB` (anything larger is almost
    ///   certainly a junk entry rather than a real function range)
    /// - `UnwindInfoAddress` resolves to a VA inside the image
    /// - The `UNWIND_INFO` first byte's low 3 bits (Version) is 1 or 2
    /// - The implied UNWIND_INFO record (4-byte header + `2 * CountOfCodes`
    ///   bytes) fits inside the image
    fn locate_exception_handler_candidates(
        &mut self,
        disassembly: &DisassemblyResult,
    ) -> Result<()> {
        if self.bitness != 64 {
            return Ok(());
        }
        let base_addr = disassembly.binary_info.base_addr;
        let bi = &disassembly.binary_info;
        const MAX_FUNC_SPAN: u64 = 16 * 1024 * 1024; // 16 MiB
        for (section_name, section_va_start, section_va_end) in bi.get_sections()? {
            if section_name != ".pdata" {
                continue;
            }
            let mut va = section_va_start;
            while va.checked_add(12).is_some_and(|e| e <= section_va_end) {
                let Ok(packed) = bi.bytes_at(va, 12) else {
                    break;
                };
                let begin_rva =
                    u32::from_le_bytes(packed[0..4].try_into().unwrap_or([0; 4])) as u64;
                let end_rva = u32::from_le_bytes(packed[4..8].try_into().unwrap_or([0; 4])) as u64;
                let unwind_rva =
                    u32::from_le_bytes(packed[8..12].try_into().unwrap_or([0; 4])) as u64;

                // Advance for the next iteration before any continue so we
                // make progress even when validation rejects this entry.
                let Some(next) = va.checked_add(12) else {
                    break;
                };
                va = next;

                if begin_rva == 0 {
                    // All-zero terminator entries are common at the end of .pdata.
                    continue;
                }
                if end_rva <= begin_rva || (end_rva - begin_rva) > MAX_FUNC_SPAN {
                    continue;
                }
                let Some(unwind_va) = base_addr.checked_add(unwind_rva) else {
                    continue;
                };
                let Ok(unwind_hdr) = bi.bytes_at(unwind_va, 4) else {
                    continue;
                };
                let version = unwind_hdr[0] & 0x07;
                if version != 1 && version != 2 {
                    continue;
                }
                // CountOfCodes is a u8, so unwind_total fits in u32
                // trivially: max 4 + 255 * 2 = 514 bytes.
                let count_of_codes = unwind_hdr[2] as u32;
                let unwind_total = 4u32.saturating_add(count_of_codes.saturating_mul(2));
                if bi.bytes_at(unwind_va, unwind_total).is_err() {
                    continue;
                }
                if let Some(addr) = base_addr.checked_add(begin_rva) {
                    self.add_exception_candidate(addr, disassembly)?;
                }
            }
        }
        Ok(())
    }

    fn locate_stub_chain_candidates(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        let base_addr = disassembly.binary_info.base_addr;
        for (section_va, section_bytes) in disassembly.binary_info.section_slices() {
            for block in STUB_CHAIN.find_iter(section_bytes) {
                for call_match in
                    STUB_CHAIN_FUNC.find_iter(&section_bytes[block.start()..block.end()])
                {
                    let stub_addr = section_va + block.start() as u64 + call_match.start() as u64;
                    if !self.passes_code_filter(Some(stub_addr))? {
                        continue;
                    }
                    if self.add_prologue_candidate(stub_addr & self.get_bitmask(), disassembly)? {
                        self.set_initial_candidate(stub_addr & self.get_bitmask())?;
                        self.candidates
                            .get_mut(&stub_addr)
                            .ok_or(Error::LogicError(file!(), line!()))?
                            .set_is_stub();
                    }
                }
            }
            for block in STUB_CHAIN_BLOCK.find_iter(section_bytes) {
                for call_match in
                    STUB_CHAIN_BLOCK_FUNC.find_iter(&section_bytes[block.start()..block.end()])
                {
                    let stub_addr = section_va + block.start() as u64 + call_match.start() as u64;
                    if !self.passes_code_filter(Some(stub_addr))? {
                        continue;
                    }
                    if self.add_prologue_candidate(stub_addr & self.get_bitmask(), disassembly)? {
                        self.set_initial_candidate(stub_addr & self.get_bitmask())?;
                        self.candidates
                            .get_mut(&stub_addr)
                            .ok_or(Error::LogicError(file!(), line!()))?
                            .set_is_stub();
                    }
                }
            }
        }
        let _ = base_addr; // keep for symmetry with prior version
        Ok(())
    }

    fn locate_prologue_candidates(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        for re_prologue in DEFAULT_PROLOGUES.iter() {
            for (section_va, section_bytes) in disassembly.binary_info.section_slices() {
                for prologue_match in re_prologue.find_iter(section_bytes) {
                    let va = section_va + prologue_match.start() as u64;
                    if !self.passes_code_filter(Some(va))? {
                        continue;
                    }
                    self.add_prologue_candidate(va & self.get_bitmask(), disassembly)?;
                    self.set_initial_candidate(va & self.get_bitmask())?;
                }
            }
        }
        Ok(())
    }

    fn locate_reference_candidates(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        let base_addr = disassembly.binary_info.base_addr;
        for (section_va, section_bytes) in disassembly.binary_info.section_slices() {
            for call_match in REF_CANDIDATE.find_iter(section_bytes) {
                let va = section_va + call_match.start() as u64;
                if !self.passes_code_filter(Some(va))? {
                    continue;
                }
                if section_bytes.len() - call_match.start() > 5 {
                    let packed_call: &[u8; 4] = &section_bytes
                        [call_match.start() + 1..call_match.start() + 5]
                        .try_into()?;
                    let rel_call_offset = i32::from_le_bytes(*packed_call) as i64;
                    if rel_call_offset == 0 {
                        continue;
                    }
                    let call_destination =
                        ((va as i64 + rel_call_offset + 5) & self.get_bitmask() as i64) as u64;
                    if disassembly.is_addr_within_memory_image(call_destination)?
                        && self.add_reference_candidate(call_destination, va, disassembly)?
                    {
                        self.set_initial_candidate(call_destination)?;
                    }
                }
            }
        }

        if self.bitness == 32 {
            for (section_va, section_bytes) in disassembly.binary_info.section_slices() {
                for call_match in BITNESS.find_iter(section_bytes) {
                    let va = section_va + call_match.start() as u64;
                    // resolve_pointer_reference takes a base-relative
                    // offset (VA - base_addr) — translate.
                    let Some(rel) = va.checked_sub(base_addr) else {
                        continue;
                    };
                    let function_addr = self.resolve_pointer_reference(rel, disassembly).ok();
                    if !self.passes_code_filter(function_addr)? {
                        continue;
                    }
                    let function_addr = function_addr.unwrap();
                    if disassembly.is_addr_within_memory_image(function_addr)?
                        && self.add_reference_candidate(function_addr, va, disassembly)?
                    {
                        self.set_initial_candidate(function_addr)?;
                    }
                }
            }

            for (section_va, section_bytes) in disassembly.binary_info.section_slices() {
                for call_match in CELL_MATCH.find_iter(section_bytes) {
                    let va = section_va + call_match.start() as u64;
                    let Some(rel) = va.checked_sub(base_addr) else {
                        continue;
                    };
                    let function_addr = self.resolve_pointer_reference(rel, disassembly).ok();
                    if !self.passes_code_filter(function_addr)? {
                        continue;
                    }
                    let function_addr = function_addr.unwrap();
                    if disassembly.is_addr_within_memory_image(function_addr)?
                        && self.add_reference_candidate(function_addr, va, disassembly)?
                    {
                        self.set_initial_candidate(function_addr)?;
                    }
                }
            }
        }
        Ok(())
    }

    fn resolve_pointer_reference(
        &self,
        offset: u64,
        disassembly: &DisassemblyResult,
    ) -> Result<u64> {
        let addr_offset = offset.checked_add(2).ok_or(Error::IntegerOverflow(
            "resolve_pointer_reference offset+2",
            offset,
            2,
        ))?;
        if self.bitness == 32 {
            let addr_block: &[u8; 4] = disassembly.get_raw_bytes(addr_offset, 4)?.try_into()?;
            let function_pointer = u32::from_le_bytes(*addr_block) as u64;
            return disassembly.dereference_dword(function_pointer);
        }
        if self.bitness == 64 {
            let addr_block: &[u8; 4] = disassembly.get_raw_bytes(addr_offset, 4)?.try_into()?;
            let mut function_pointer = u32::from_le_bytes(*addr_block) as u64;
            // RIP-relative; the instruction is 6 (`FF 15`) or 7 (`FF 25`)
            // bytes long depending on the opcode. wrapping_add matches the
            // x86 semantics — if the RIP target wraps around the address
            // space it's still a deterministic value, which the caller
            // gates with `is_addr_within_memory_image`.
            let prefix = disassembly.get_raw_bytes(offset, 2)?;
            if prefix == b"\xFF\x25" {
                function_pointer = function_pointer.wrapping_add(offset).wrapping_add(7);
            } else if prefix == b"\xFF\x15" {
                function_pointer = function_pointer.wrapping_add(offset).wrapping_add(6);
            } else {
                return Err(Error::LogicError(file!(), line!()));
            }
            let absolute = disassembly
                .binary_info
                .base_addr
                .checked_add(function_pointer)
                .ok_or(Error::IntegerOverflow(
                    "resolve_pointer_reference base+ptr",
                    disassembly.binary_info.base_addr,
                    function_pointer,
                ))?;
            return Ok(absolute);
        }
        Err(Error::LogicError(file!(), line!()))
    }

    fn get_bitmask(&self) -> u64 {
        //        if self.bitness == 64{
        0xFFFFFFFFFFFFFFFF
        //        }
        //        0xFFFFFFFF
    }

    fn passes_code_filter(&self, address: Option<u64>) -> Result<bool> {
        match address {
            Some(addr) => {
                for (start, end) in &self.code_areas {
                    if *start <= addr && *end > addr {
                        return Ok(true);
                    }
                }
                Ok(false)
            }
            _ => Ok(false),
        }
    }

    fn ensure_candidate(&mut self, addr: u64, disassembly: &DisassemblyResult) -> Result<bool> {
        if let std::collections::btree_map::Entry::Vacant(e) = self.candidates.entry(addr) {
            e.insert(FunctionCandidate::new(&disassembly.binary_info, addr)?);
            return Ok(true);
        }
        Ok(true)
    }

    pub fn add_reference_candidate(
        &mut self,
        addr: u64,
        source_ref: u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(addr))? {
            return Ok(false);
        }
        if self.ensure_candidate(addr, disassembly)? {
            self.all_call_refs.insert(source_ref, addr);
        }
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .add_call_ref(source_ref)?;
        Ok(true)
    }

    fn add_prologue_candidate(
        &mut self,
        addr: u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(addr))? {
            return Ok(false);
        }
        self.ensure_candidate(addr, disassembly)?;
        Ok(true)
    }

    fn set_initial_candidate(&mut self, addr: u64) -> Result<()> {
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_initial_candidate();
        Ok(())
    }

    fn add_exception_candidate(
        &mut self,
        addr: u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(addr))? {
            return Ok(false);
        }
        self.ensure_candidate(addr, disassembly)?;
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_is_exception_handler();
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_initial_candidate();
        Ok(true)
    }

    pub fn get_queue(&self) -> Result<Vec<u64>> {
        let mut res = vec![];
        for addr in self.candidates.keys() {
            res.push(*addr);
        }
        Ok(res)
    }

    //    pub fn get_candidate(&self, addr: &u64) -> Result<&FunctionCandidate>{
    //        Ok(self.candidates.get(addr).ok_or(Error::LogicError(file!(), line!()))?)
    //    }

    pub fn get_function_start_candidates(&self) -> Result<Vec<u64>> {
        Ok(self.candidate_offsets.clone())
    }

    pub fn is_alignment_sequence(
        &self,
        instruction_sequence: &[DecodedInsn],
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        let mut is_alignment_sequence = false;
        if !instruction_sequence.is_empty() {
            let mut current_offset = instruction_sequence[0].offset;
            for instruction in instruction_sequence {
                let len = instruction.length as usize;
                // 0.4.0: bytes are looked up on demand from BinaryInfo
                // instead of being owned by the DecodedInsn.
                let Ok(bytes) = instruction.bytes_in(&disassembly.binary_info) else {
                    break;
                };
                if self
                    .gs
                    .gs
                    .get(&len)
                    .is_some_and(|set| set.contains(&bytes.to_vec()))
                {
                    current_offset += len as u64;
                    if current_offset.is_multiple_of(16) {
                        is_alignment_sequence = true;
                        break;
                    }
                } else {
                    break;
                }
            }
        }
        Ok(is_alignment_sequence)
    }

    pub fn is_function_candidate(&self, addr: u64) -> Result<bool> {
        Ok(self.candidates.contains_key(&addr))
    }

    pub fn add_candidate(
        &mut self,
        addr: u64,
        is_gap: bool,                  /*False*/
        reference_source: Option<u64>, /*None*/
        disassembly: &DisassemblyResult,
    ) -> Result<()> {
        if !self.passes_code_filter(Some(addr))? {
            return Err(Error::LogicError(file!(), line!()));
        }
        self.ensure_candidate(addr, disassembly)?;
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_is_gap_candidate(is_gap)?;
        if let Some(reference_source) = reference_source {
            self.candidates
                .get_mut(&addr)
                .ok_or(Error::LogicError(file!(), line!()))?
                .add_call_ref(reference_source)?;
        }
        self.candidate_queue.push(addr);
        //        self.candidate_queue.update()?;
        Ok(())
    }

    pub fn update_analysis_aborted(&mut self, addr: &u64, reason: &str) -> Result<()> {
        //LOGGER.debug("function analysis of 0x%08x aborted: %s", addr, reason)
        if let Some(mm) = self.candidates.get_mut(addr) {
            mm.set_analysis_aborted(reason)?;
        }
        Ok(())
    }

    pub fn update_analysis_finished(&mut self, addr: &u64) -> Result<()> {
        //LOGGER.debug("function analysis of 0x%08x successfully completed.", addr)
        if let Some(mm) = self.candidates.get_mut(addr) {
            mm.set_analysis_completed()?;
        }
        Ok(())
    }

    pub fn update_candidates(&mut self, state: &FunctionAnalysisState) -> Result<()> {
        // if let Ok(_s) = std::env::var("HIGH_ACCURACY") {
        if let Ok(conflicts) = state.identify_call_conflicts(&self.all_call_refs) {
            for (candidate_addr, conflict) in conflicts {
                if let Some(c) = self.candidates.get_mut(&candidate_addr) {
                    c.remove_call_refs(conflict)?;
                }
            }

            // self.candidate_queue.update();
        }
        Ok(())
    }

    pub fn next_gap_candidate(
        &mut self,
        start_gap_pointer: Option<u64>,
        disassembly: &DisassemblyResult,
    ) -> Result<u64> {
        if let Some(s) = start_gap_pointer {
            self.gap_pointer = s;
        }
        if self.gap_pointer == 0 {
            self.init_gap_search(disassembly)?;
        }
        //LOGGER.debug("nextGapCandidate() finding new gap
        //candidate, current gap_ptr: 0x%08x", self.gap_pointer)
        loop {
            if disassembly.binary_info.base_addr + disassembly.binary_info.binary_size
                < self.gap_pointer
            {
                //LOGGER.debug("nextGapCandidate() gap_ptr: 0x%08x - finishing", self.gap_pointer)
                return Err(Error::LogicError(file!(), line!()));
            }
            let gap_offset = self.gap_pointer - disassembly.binary_info.base_addr;
            if gap_offset >= disassembly.binary_info.binary_size {
                return Err(Error::LogicError(file!(), line!()));
            }
            //compatibility with python2/3...
            let byte = disassembly.get_raw_byte(gap_offset)?;
            if self.gs.gs[&1].contains(&vec![byte]) {
                //LOGGER.debug("nextGapCandidate() found 0xCC / 0x00 - gap_ptr += 1: 0x%08x", self.gap_pointer)
                self.gap_pointer += 1;
                continue;
            }
            // Try to find a single instruction at the current gap that's a
            // NOP encoding; if so, skip it and continue looking.
            {
                let buf = disassembly.get_raw_bytes(gap_offset, 15)?;
                let mut decoder =
                    Decoder::with_ip(self.bitness, buf, gap_offset, DecoderOptions::NONE);
                if decoder.can_decode() {
                    let insn = decoder.decode();
                    if !insn.is_invalid() && matches!(insn.mnemonic(), Mnemonic::Nop) {
                        self.gap_pointer += decoder.position() as u64;
                        continue;
                    }
                }
                //# try to find effective NOPs and skip them.
                let mut found_multi_byte_nop = false;
                // Iterate widest → narrowest so we match the longest
                // multi-byte NOP first. The previous `15u32..1` range was
                // empty (typo from the iced rewrite) and silently disabled
                // multi-byte NOP gap detection.
                let max_gap = *self
                    .gs
                    .gs
                    .keys()
                    .max()
                    .ok_or(Error::LogicError(file!(), line!()))?
                    as u32;
                for gap_length in (2..=max_gap).rev() {
                    if self.gs.gs[&(gap_length as usize)].contains(
                        &disassembly
                            .get_raw_bytes(gap_offset, gap_length as u64)?
                            .to_vec(),
                    ) {
                        //LOGGER.debug("nextGapCandidate() found %d byte effective nop - gap_ptr += %d: 0x%08x", gap_length, gap_length, self.gap_pointer)
                        self.gap_pointer += gap_length as u64;
                        found_multi_byte_nop = true;
                        break;
                    }
                }
                if found_multi_byte_nop {
                    continue;
                }
                //# we know this place from data already
                if disassembly.data_map.contains(&self.gap_pointer) {
                    //LOGGER.debug("nextGapCandidate() gap_ptr is already inside data map: 0x%08x", self.gap_pointer)
                    self.gap_pointer += 1;
                    continue;
                }
                if disassembly.code_map.contains_key(&self.gap_pointer) {
                    //LOGGER.debug("nextGapCandidate() gap_ptr is already inside code map: 0x%08x", self.gap_pointer)
                    self.gap_pointer = self.get_next_gap(false, disassembly)?;
                    continue;
                }
                //# we may have a candidate here
                //LOGGER.debug("nextGapCandidate() using 0x%08x as candidate", self.gap_pointer)
                let _start_byte = disassembly.get_raw_byte(gap_offset)?;
            }
            let has_common_prologue = true; //start_byte in
            // FunctionCandidate(self.gap_pointer, start_byte,
            // self.bitness).common_gap_starts[self.bitness]
            if (self.previously_analyzed_gap == self.gap_pointer) || !has_common_prologue {
                //LOGGER.debug("--- HRM, nextGapCandidate() gap_ptr at: 0x%08x was previously analyzed", self.gap_pointer)
                self.gap_pointer = self.get_next_gap(true, disassembly)?;
            // } else if !has_common_prologue {
            //     //LOGGER.debug("--- HRM, nextGapCandidate() gap_ptr at: 0x%08x has no common prologue (0x%08x)", self.gap_pointer, ord(start_byte))
            //     self.gap_pointer = self.get_next_gap(true, disassembly)?;
            } else {
                self.previously_analyzed_gap = self.gap_pointer;
                self.add_gap_candidate(self.gap_pointer, disassembly)?;
                return Ok(self.gap_pointer);
            }
        }
    }

    pub fn get_next_gap(&self, dont_skip: bool, disassembly: &DisassemblyResult) -> Result<u64> {
        let mut next_gap = self.get_bitmask();
        for gap in &self.function_gaps {
            if gap.0 > self.gap_pointer {
                next_gap = gap.0;
                break;
            }
        }
        //LOGGER.debug("getNextGap(%s) for 0x%08x based on gap_map: 0x%08x", dont_skip, self.gap_pointer, next_gap)
        //# we potentially just disassembled a function and want to continue directly behind it in case we would otherwise miss more
        if dont_skip && disassembly.code_map.contains_key(&self.gap_pointer) {
            let function = disassembly.ins2fn[&self.gap_pointer];
            if next_gap > disassembly.function_borders[&function].1 {
                next_gap = disassembly.function_borders[&function].1;
            }
            //LOGGER.debug("getNextGap(%s) without skip => after checking versus code map: 0x%08x", dont_skip, next_gap)
        }
        //LOGGER.debug("getNextGap(%s) final gap_ptr: 0x%08x", dont_skip, next_gap)
        Ok(next_gap)
    }

    pub fn add_tailcall_candidate(
        &mut self,
        addr: &u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(*addr))? {
            return Ok(false);
        }
        self.ensure_candidate(*addr, disassembly)?;
        self.candidates
            .get_mut(addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_is_tailcall_candidate(true)?;
        Ok(true)
    }

    pub fn get_aborted_candidates(&self) -> Result<Vec<u64>> {
        let mut aborted = vec![];
        for (addr, candidate) in &self.candidates {
            if candidate.analysis_aborted {
                aborted.push(*addr);
            }
        }
        Ok(aborted)
    }

    pub fn init_gap_search(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        if self.gap_pointer == 0 {
            //LOGGER.debug("initGapSearch()")
            self.gap_pointer = self.get_bitmask();
            self.update_function_gaps(disassembly)?;
            if !self.function_gaps.is_empty() {
                self.gap_pointer = self.function_gaps[0].0;
            }
        }
        // sort gaps by start address
        self.function_gaps.sort_by_key(|gap| gap.0);
        //LOGGER.debug("initGapSearch() gaps are:")
        for _gap in &self.function_gaps {
            //LOGGER.debug("initGapSearch() 0x%08x - 0x%08x == %d",
            // gap[0], gap[1], gap[2])
        }
        Ok(())
    }

    pub fn add_gap_candidate(
        &mut self,
        addr: u64,
        disassembly: &DisassemblyResult,
    ) -> Result<bool> {
        if !self.passes_code_filter(Some(addr))? {
            return Ok(false);
        }
        self.ensure_candidate(addr, disassembly)?;
        self.candidates
            .get_mut(&addr)
            .ok_or(Error::LogicError(file!(), line!()))?
            .set_is_gap_candidate(true)?;
        Ok(true)
    }

    pub fn update_function_gaps(&mut self, disassembly: &DisassemblyResult) -> Result<()> {
        let mut gaps = vec![];
        let mut prev_ins = 0;
        let mut min_code = self.get_bitmask();
        let mut max_code = 0;
        for f in disassembly.code_map.keys() {
            if min_code > *f {
                min_code = *f;
            }
            if max_code < *f {
                max_code = *f;
            }
        }
        for code_area in &self.code_areas {
            if code_area.0 < min_code && min_code < code_area.1 && min_code != code_area.0 {
                gaps.push((code_area.0, min_code, min_code - code_area.0));
            }
            if code_area.0 < max_code && max_code < code_area.1 && max_code != code_area.1 {
                gaps.push((max_code, code_area.1, code_area.1 - max_code));
            }
        }
        for (ins, _) in disassembly.code_map.iter().sorted() {
            if prev_ins != 0 && ins - prev_ins > 1 {
                gaps.push((prev_ins + 1, *ins, ins - prev_ins))
            }
            prev_ins = *ins
        }
        self.function_gaps = gaps;
        Ok(())
    }
}