reknife 1.8.0

A reverse engineer's binary Swiss-army knife: parse, triage, and disassemble PE/ELF/Mach-O. Installs as `knife`.
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
//! Reusable listing indexes and disassembly queries for interactive front ends.

/// Query an existing string index without rebuilding or cloning the workspace.
pub fn string_summaries(
    binary: &Binary,
    analysis: &engine::Analysis,
    strings: &BTreeMap<u64, Located>,
    query: &StringQuery,
) -> Vec<StringSummary> {
    let needle = query
        .text_contains
        .as_deref()
        .unwrap_or_default()
        .to_lowercase();
    strings
        .iter()
        .filter_map(|(address, string)| {
            if !needle.is_empty() && !string.text.to_lowercase().contains(&needle) {
                return None;
            }
            let references = analysis.xrefs_to.get(address).map_or(0, Vec::len);
            if query.referenced_only && references == 0 {
                return None;
            }
            Some(StringSummary {
                address: *address,
                file_offset: engine::va_to_off(binary, engine::display_base(binary), *address)
                    .and_then(|offset| u64::try_from(offset).ok())
                    .map(FileOffset),
                text: string.text.clone(),
                wide: string.wide,
                len: string.len,
                references,
            })
        })
        .take(query.limit.unwrap_or(usize::MAX))
        .collect()
}

use crate::address::{FileOffset, StaticVa};
use crate::analysis::engine::{self, Function};
use crate::analysis::strings::Located;
use crate::analysis::{disasm, driver, entropy};
use crate::api::driver_surface::{DriverSurface, DriverSurfaceQuery};
use crate::api::risk_signals::RiskSignal;
use crate::listing::{self, Annot, Line};
use crate::model::{Binary, Format, Section};
use crate::workspace::Session;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PseudocodeLine {
    pub label: bool,
    pub text: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ListingAnnotationKind {
    Note,
    Symbol,
    Local,
    Text,
    Hint,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListingAnnotation {
    pub kind: ListingAnnotationKind,
    pub text: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ListingLine {
    Label {
        address: StaticVa,
        text: String,
    },
    Instruction {
        address: StaticVa,
        mnemonic: String,
        operands: String,
        annotation: Option<ListingAnnotation>,
        target: Option<StaticVa>,
    },
    Data {
        address: StaticVa,
        text: String,
    },
}

impl ListingLine {
    pub const fn address(&self) -> StaticVa {
        match self {
            Self::Label { address, .. }
            | Self::Instruction { address, .. }
            | Self::Data { address, .. } => *address,
        }
    }
}

impl From<Line> for ListingLine {
    fn from(line: Line) -> Self {
        match line {
            Line::Label { addr, text } => Self::Label {
                address: StaticVa(addr),
                text,
            },
            Line::Insn {
                addr,
                mnemonic,
                operands,
                annot,
                target,
            } => Self::Instruction {
                address: StaticVa(addr),
                mnemonic,
                operands,
                annotation: annot.map(ListingAnnotation::from),
                target: target.map(StaticVa),
            },
            Line::Data { addr, text } => Self::Data {
                address: StaticVa(addr),
                text,
            },
        }
    }
}

impl From<Annot> for ListingAnnotation {
    fn from(annotation: Annot) -> Self {
        let (kind, text) = match annotation {
            Annot::Note(text) => (ListingAnnotationKind::Note, text),
            Annot::Symbol(text) => (ListingAnnotationKind::Symbol, text),
            Annot::Local(text) => (ListingAnnotationKind::Local, text),
            Annot::Text(text) => (ListingAnnotationKind::Text, text),
            Annot::Hint(text) => (ListingAnnotationKind::Hint, text),
        };
        Self { kind, text }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StringSummary {
    pub address: u64,
    /// File location of the first encoded byte. Kept distinct from the static
    /// address so front ends cannot visually conflate the two address spaces.
    pub file_offset: Option<FileOffset>,
    pub text: String,
    pub wide: bool,
    pub len: u64,
    pub references: usize,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StringQuery {
    pub text_contains: Option<String>,
    pub referenced_only: bool,
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LinearLocation {
    FileOffset(FileOffset),
    StaticVa(StaticVa),
}

impl LinearLocation {
    pub const fn get(self) -> u64 {
        match self {
            Self::FileOffset(value) => value.get(),
            Self::StaticVa(value) => value.get(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LinearRow {
    Region {
        file_offset: FileOffset,
        end_offset: FileOffset,
        name: String,
        segment: String,
        permissions: Option<String>,
        code: bool,
    },
    Label {
        address: StaticVa,
        text: String,
    },
    Function {
        address: StaticVa,
        name: String,
        basic_blocks: usize,
        byte_size: u64,
    },
    Instruction {
        address: StaticVa,
        mnemonic: String,
        operands: String,
        annotation: Option<String>,
        target: Option<StaticVa>,
        segment: String,
    },
    Data {
        location: LinearLocation,
        text: String,
        segment: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinearQuery {
    pub file_offset: Option<FileOffset>,
    pub address: Option<StaticVa>,
    pub maximum_rows: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinearWindow {
    pub rows: Vec<LinearRow>,
    pub start: FileOffset,
    pub next: Option<FileOffset>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct HexQuery {
    pub address: StaticVa,
    pub length: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HexRowSummary {
    pub file_offset: FileOffset,
    pub address: StaticVa,
    pub byte_length: u64,
    pub hex: String,
    pub ascii: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OverviewBucketSummary {
    pub file_offset: FileOffset,
    pub static_address: Option<StaticVa>,
    pub entropy: f64,
    pub section: Option<String>,
    pub code: bool,
    pub risk_signals: u32,
    pub maximum_severity: u8,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OverviewSummary {
    pub size: u64,
    pub bucket_bytes: u64,
    pub buckets: Vec<OverviewBucketSummary>,
    pub entry_bucket: Option<usize>,
}

/// Name-independent strings and name-dependent driver annotations used to
/// render listings. Build once per session and refresh after recovery changes.
pub struct ListingIndex {
    base: u64,
    strings: BTreeMap<u64, Located>,
    hints: Option<BTreeMap<u64, String>>,
}

impl ListingIndex {
    pub fn from_session(session: &Session) -> Self {
        let base = engine::display_base(&session.bin);
        let strings = listing::string_map(&session.bin, &session.bytes, base);
        let hints = driver::plausibly_a_driver(&session.bin)
            .then(|| driver::listing_hints(&session.bin, &session.bytes, &session.an));
        Self {
            base,
            strings,
            hints,
        }
    }

    /// Refresh facts that can change after analyst names alter recovery.
    pub fn refresh_analysis(&mut self, session: &Session) {
        self.base = engine::display_base(&session.bin);
        self.hints = driver::plausibly_a_driver(&session.bin)
            .then(|| driver::listing_hints(&session.bin, &session.bytes, &session.an));
    }

    pub const fn base(&self) -> u64 {
        self.base
    }

    pub fn strings(&self, session: &Session, query: &StringQuery) -> Vec<StringSummary> {
        string_summaries(&session.bin, &session.an, &self.strings, query)
    }

    pub const fn has_driver_hints(&self) -> bool {
        self.hints.is_some()
    }

    pub fn function_lines(&self, session: &Session, function: &Function) -> Vec<ListingLine> {
        listing::function(
            &session.an,
            function,
            &session.db,
            self.base,
            &self.strings,
            self.hints.as_ref(),
        )
        .into_iter()
        .map(ListingLine::from)
        .collect()
    }

    pub fn function_lines_by_selector(
        &self,
        session: &Session,
        selector: &str,
    ) -> Result<Vec<ListingLine>> {
        let function = resolve_function(session, selector)
            .ok_or_else(|| anyhow!("nothing matches {selector:?}"))?;
        Ok(self.function_lines(session, function))
    }

    pub fn pseudocode(&self, session: &Session, function: &Function) -> Vec<PseudocodeLine> {
        crate::analysis::ir::decompile(
            &session.an,
            &session.bin,
            function,
            &self.strings,
            &session.db,
        )
        .into_iter()
        .map(|line| PseudocodeLine {
            label: line.label,
            text: line.text,
        })
        .collect()
    }

    pub fn pseudocode_by_selector(
        &self,
        session: &Session,
        selector: &str,
    ) -> Result<Vec<PseudocodeLine>> {
        let function = resolve_function(session, selector)
            .ok_or_else(|| anyhow!("nothing matches {selector:?}"))?;
        Ok(self.pseudocode(session, function))
    }

    pub fn driver_surface(&self, session: &Session) -> Option<DriverSurface> {
        driver::plausibly_a_driver(&session.bin)
            .then(|| driver::report(&session.bin, &session.bytes, &session.an, &self.strings))
            .filter(|report| report.is_driver)
            .map(|report| DriverSurface::from_report(&report, DriverSurfaceQuery::default()))
    }

    /// Render a function selected by name/address, or mapped data selected by
    /// address. This preserves the GUI/TUI behavior that every mapped address
    /// is navigable even when it is not recovered code.
    pub fn disassemble(&self, session: &Session, selector: &str) -> Result<Vec<ListingLine>> {
        if let Some(function) = resolve_function(session, selector) {
            return Ok(self.function_lines(session, function));
        }
        let address =
            parse_address(selector).map_err(|_| anyhow!("nothing matches {selector:?}"))?;
        if engine::va_to_off(&session.bin, self.base, address).is_none() {
            return Err(anyhow!("{selector} is not mapped in this image"));
        }
        Ok(
            listing::data_view(&session.bin, self.base, &session.bytes, address)
                .into_iter()
                .map(ListingLine::from)
                .collect(),
        )
    }

    pub fn hex_window(&self, session: &Session, query: HexQuery) -> Result<Vec<HexRowSummary>> {
        let offset = engine::va_to_off(&session.bin, self.base, query.address.get())
            .ok_or_else(|| anyhow!("address is not in any mapped section"))?;
        let length = query.length.clamp(16, 1024);
        let start = offset.min(session.bytes.len());
        let end = start.saturating_add(length).min(session.bytes.len());
        let mut rows = Vec::new();
        let mut cursor = start;
        while cursor < end {
            let relative = u64::try_from(cursor - start)
                .map_err(|_| anyhow!("hex window row offset overflow"))?;
            let expected_address = query
                .address
                .get()
                .checked_add(relative)
                .ok_or_else(|| anyhow!("hex window address overflow"))?;
            let file_offset = u64::try_from(cursor)
                .map(FileOffset)
                .map_err(|_| anyhow!("hex window file offset overflow"))?;
            if engine::off_to_va(&session.bin, self.base, file_offset.get())
                != Some(expected_address)
            {
                break;
            }

            let maximum_row_end = cursor.saturating_add(16).min(end);
            let mut row_end = cursor + 1;
            while row_end < maximum_row_end {
                let byte_relative = u64::try_from(row_end - start)
                    .map_err(|_| anyhow!("hex window byte offset overflow"))?;
                let Some(byte_address) = query.address.get().checked_add(byte_relative) else {
                    break;
                };
                let byte_offset = u64::try_from(row_end)
                    .map_err(|_| anyhow!("hex window file offset overflow"))?;
                if engine::off_to_va(&session.bin, self.base, byte_offset) != Some(byte_address) {
                    break;
                }
                row_end += 1;
            }

            let chunk = &session.bytes[cursor..row_end];
            let address = StaticVa(expected_address);
            let byte_length = u64::try_from(chunk.len())
                .map_err(|_| anyhow!("hex window row length overflow"))?;
            let hex = chunk
                .iter()
                .map(|byte| format!("{byte:02x}"))
                .collect::<Vec<_>>()
                .join(" ");
            let ascii = chunk
                .iter()
                .map(|byte| {
                    if (0x20..=0x7e).contains(byte) {
                        *byte as char
                    } else {
                        '.'
                    }
                })
                .collect();
            rows.push(HexRowSummary {
                file_offset,
                address,
                byte_length,
                hex,
                ascii,
            });
            cursor = row_end;
        }
        if rows.is_empty() {
            return Err(anyhow!(
                "address mapping is ambiguous between virtual and file locations"
            ));
        }
        Ok(rows)
    }

    pub fn linear(&self, session: &Session, query: &LinearQuery) -> Result<LinearWindow> {
        let maximum_rows = query.maximum_rows.clamp(1, 20_000);
        let file_size = u64::try_from(session.bytes.len()).unwrap_or(u64::MAX);
        let mut cursor = match (query.file_offset, query.address) {
            (Some(offset), _) => offset.get(),
            (None, Some(address)) => engine::va_to_off(&session.bin, self.base, address.get())
                .map(|offset| offset as u64)
                .ok_or_else(|| anyhow!("address is not in any mapped section"))?,
            (None, None) => 0,
        };
        let start = FileOffset(cursor);
        if cursor >= file_size {
            return Ok(LinearWindow {
                rows: Vec::new(),
                start,
                next: None,
            });
        }

        let regions = file_regions(&session.bin, file_size);
        let entry_offset = disasm::entry_location(&session.bin, &session.bytes).map(|(off, _)| off);
        let mut rows = Vec::new();
        while rows.len() < maximum_rows && cursor < file_size {
            let Some(region) = regions
                .iter()
                .find(|region| cursor >= region.start && cursor < region.end)
            else {
                break;
            };
            let before = cursor;
            if cursor == region.start || rows.is_empty() {
                rows.push(LinearRow::Region {
                    file_offset: FileOffset(cursor),
                    end_offset: FileOffset(region.end),
                    name: region.name.clone(),
                    segment: region.segment.clone(),
                    permissions: region.permissions.clone(),
                    code: region.code,
                });
            }

            if region.code && disasm::supported(session.bin.arch) {
                let address = engine::off_to_va(&session.bin, self.base, cursor).unwrap_or(cursor);
                let room = maximum_rows.saturating_sub(rows.len()).max(1);
                let instructions = disasm::disassemble(
                    &session.bytes,
                    cursor,
                    address,
                    session.bin.bits,
                    session.bin.arch,
                    room,
                );
                if instructions.is_empty() {
                    cursor = region.end;
                    continue;
                }
                for instruction in &instructions {
                    let instruction_len = instruction.bytes.len() as u64;
                    if cursor + instruction_len > region.end {
                        break;
                    }
                    if Some(cursor) == entry_offset {
                        rows.push(LinearRow::Label {
                            address: StaticVa(instruction.addr),
                            text: "entry point:".into(),
                        });
                    }
                    if let Some(function) = session.an.find_function(instruction.addr) {
                        if function.addr == instruction.addr && Some(cursor) != entry_offset {
                            rows.push(LinearRow::Function {
                                address: StaticVa(instruction.addr),
                                name: function.name.clone(),
                                basic_blocks: function.blocks.len(),
                                byte_size: function.size,
                            });
                        }
                    }
                    let (mnemonic, operands) =
                        match instruction.text.split_once(char::is_whitespace) {
                            Some((mnemonic, rest)) => {
                                (mnemonic.to_string(), rest.trim_start().to_string())
                            }
                            None => (instruction.text.clone(), String::new()),
                        };
                    let target = trailing_address(&operands).filter(|target| {
                        session.an.find_function(*target).is_some()
                            || session.an.imports.contains_key(target)
                    });
                    rows.push(LinearRow::Instruction {
                        address: StaticVa(instruction.addr),
                        mnemonic,
                        operands,
                        annotation: target.map(|target| session.an.label(target)),
                        target: target.map(StaticVa),
                        segment: region.segment.clone(),
                    });
                    cursor += instruction_len;
                }
            } else {
                while rows.len() < maximum_rows && cursor < region.end {
                    let end = (cursor + 16).min(region.end).min(file_size);
                    let chunk = &session.bytes[cursor as usize..end as usize];
                    let hex_bytes = chunk
                        .iter()
                        .map(|byte| format!("{byte:02x} "))
                        .collect::<String>();
                    let ascii = chunk
                        .iter()
                        .map(|byte| {
                            if (0x20..=0x7e).contains(byte) {
                                *byte as char
                            } else {
                                '.'
                            }
                        })
                        .collect::<String>();
                    let location = engine::off_to_va(&session.bin, self.base, cursor)
                        .map(|address| LinearLocation::StaticVa(StaticVa(address)))
                        .unwrap_or(LinearLocation::FileOffset(FileOffset(cursor)));
                    rows.push(LinearRow::Data {
                        location,
                        text: format!("{hex_bytes:<48} {ascii}"),
                        segment: region.segment.clone(),
                    });
                    cursor = end;
                }
            }

            if cursor == before {
                if rows.len() >= maximum_rows {
                    break;
                }
                cursor = region.end;
            }
        }
        Ok(LinearWindow {
            rows,
            start,
            next: (cursor < file_size).then_some(FileOffset(cursor)),
        })
    }

    pub fn overview(
        &self,
        session: &Session,
        requested_buckets: usize,
        signals: &[RiskSignal],
    ) -> OverviewSummary {
        let bytes = &session.bytes;
        if bytes.is_empty() {
            return OverviewSummary {
                size: 0,
                bucket_bytes: 0,
                buckets: Vec::new(),
                entry_bucket: None,
            };
        }
        let count = requested_buckets.clamp(64, 2048);
        let step = bytes.len().div_ceil(count).max(1);
        let mut buckets: Vec<_> = bytes
            .chunks(step)
            .enumerate()
            .map(|(index, chunk)| {
                let offset = (index * step) as u64;
                let section = session.bin.sections.iter().find(|section| {
                    section.file_size > 0
                        && offset >= section.file_off
                        && offset < section.file_off + section.file_size
                });
                OverviewBucketSummary {
                    file_offset: FileOffset(offset),
                    static_address: engine::off_to_va(&session.bin, self.base, offset)
                        .map(StaticVa),
                    entropy: entropy::entropy(chunk),
                    section: section.map(|section| section.name.clone()),
                    code: section.is_some_and(|section| section.exec),
                    risk_signals: 0,
                    maximum_severity: 0,
                }
            })
            .collect();
        let last = buckets.len().saturating_sub(1);
        for signal in signals {
            if let Some(offset) = engine::va_to_off(&session.bin, self.base, signal.address.get()) {
                let bucket = &mut buckets[(offset / step).min(last)];
                bucket.risk_signals += 1;
                bucket.maximum_severity = bucket.maximum_severity.max(signal.severity);
            }
        }
        let entry_bucket = disasm::entry_location(&session.bin, &session.bytes)
            .map(|(offset, _)| (offset as usize / step).min(last));
        OverviewSummary {
            size: bytes.len() as u64,
            bucket_bytes: step as u64,
            buckets,
            entry_bucket,
        }
    }
}

struct FileRegion {
    start: u64,
    end: u64,
    name: String,
    segment: String,
    permissions: Option<String>,
    code: bool,
}

fn section_permissions(section: &Section) -> String {
    let bit = |enabled: bool, marker: char| if enabled { marker } else { '-' };
    format!(
        "{}{}{}",
        bit(section.read, 'R'),
        bit(section.write, 'W'),
        bit(section.exec, 'X')
    )
}

fn file_regions(binary: &Binary, file_size: u64) -> Vec<FileRegion> {
    let mut sections: Vec<_> = binary
        .sections
        .iter()
        .filter(|section| section.file_size > 0)
        .collect();
    sections.sort_by_key(|section| section.file_off);
    let mut regions = Vec::new();
    let mut cursor = 0u64;
    for section in sections {
        if section.file_off > cursor {
            let headers = cursor == 0;
            regions.push(FileRegion {
                start: cursor,
                end: section.file_off.min(file_size),
                name: if headers && binary.format == Format::Pe {
                    "DOS header, stub, and PE headers".into()
                } else if headers {
                    "container headers".into()
                } else {
                    "alignment padding".into()
                },
                segment: if headers { "HEADER" } else { "align" }.into(),
                permissions: None,
                code: false,
            });
        }
        let end = section
            .file_off
            .saturating_add(section.file_size)
            .min(file_size);
        let start = section.file_off.max(cursor);
        if end > start {
            regions.push(FileRegion {
                start,
                end,
                name: section.name.clone(),
                segment: section.name.clone(),
                permissions: Some(section_permissions(section)),
                code: section.exec,
            });
        }
        cursor = cursor.max(end);
    }
    if file_size > cursor {
        regions.push(FileRegion {
            start: cursor,
            end: file_size,
            name: "overlay".into(),
            segment: "overlay".into(),
            permissions: None,
            code: false,
        });
    }
    if regions.is_empty() {
        regions.push(FileRegion {
            start: 0,
            end: file_size,
            name: "file".into(),
            segment: "file".into(),
            permissions: None,
            code: false,
        });
    }
    regions
}

fn trailing_address(operands: &str) -> Option<u64> {
    let at = operands.rfind("0x")?;
    let digits: String = operands[at + 2..]
        .chars()
        .take_while(char::is_ascii_hexdigit)
        .collect();
    if operands[at..].contains(']') {
        return None;
    }
    u64::from_str_radix(&digits, 16).ok()
}

fn resolve_function<'a>(session: &'a Session, selector: &str) -> Option<&'a Function> {
    if let Some(function) = session.an.find_by_name(selector) {
        return Some(function);
    }
    parse_address(selector).ok().and_then(|address| {
        session
            .an
            .find_function(address)
            .or_else(|| session.an.function_at(address))
    })
}

fn parse_address(value: &str) -> Result<u64> {
    let raw = value
        .trim()
        .trim_start_matches("0x")
        .trim_start_matches("0X");
    u64::from_str_radix(raw, 16).map_err(Into::into)
}