r2fas 0.2.1

radare2 core plugin that loads FASM -s symbolic dumps for named labels, source lines, and comments
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
//! Apply [`crate::session::DebugInfo`] to an open radare2 core.

use crate::session::{DebugInfo, SourceExtent, SymbolKind as FasSymbolKind};
use radare2::Core;
use radare2::native::{
    AddrLine as NativeAddrLine, AddrLineSnapshot, BinIdentity, FunctionAdd, FunctionTransaction,
    MapIdentity, Symbol as NativeSymbol, SymbolAdd, SymbolKind as NativeSymbolKind,
    SymbolTransaction, XrefAdd, XrefKind, XrefTransaction, replace_addrlines, resolve_paddr,
    resolve_vaddr,
};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

/// True when active IO maps can represent at least one emitted FAS address.
pub fn maps_ready(core: Core, info: &DebugInfo) -> bool {
    let mut resolver = AddressResolver::new(core, info);
    info.source_locations
        .iter()
        .filter(|location| location.primary)
        .any(|location| {
            resolver
                .resolve(
                    location.address,
                    Some(u64::from(location.output_offset)),
                    false,
                )
                .is_some()
        })
        || info
            .symbols
            .iter()
            .filter(|symbol| symbol.debugger_visible)
            .any(|symbol| {
                resolver
                    .resolve(
                        symbol.value,
                        symbol.output_offset.map(u64::from),
                        symbol.kind == FasSymbolKind::Code,
                    )
                    .is_some()
            })
}

/// True when `om` lists a vaddr range that contains `addr`.
///
/// Kept as a parser helper for compatibility and focused tests. Runtime address
/// resolution itself uses header-backed `RIOMap` APIs.
pub fn maps_cover_addr(om: &str, addr: u64) -> bool {
    om.lines()
        .any(|line| parse_om_vaddr_range(line).is_some_and(|(from, to)| addr >= from && addr <= to))
}

/// Parse the `0xFROM - 0xTO` vaddr span from one `om` line.
fn parse_om_vaddr_range(line: &str) -> Option<(u64, u64)> {
    let dash = line.find(" - 0x")?;
    let from_hex = line[..dash]
        .rsplit("0x")
        .next()?
        .chars()
        .take_while(|c| c.is_ascii_hexdigit())
        .collect::<String>();
    let to_hex = line[dash + 5..]
        .chars()
        .take_while(|c| c.is_ascii_hexdigit())
        .collect::<String>();
    let from = u64::from_str_radix(&from_hex, 16).ok()?;
    let to = u64::from_str_radix(&to_hex, 16).ok()?;
    Some((from, to))
}

#[derive(Debug, Clone, Copy)]
struct RuntimeAddress {
    addr: u64,
}

struct AddressResolver {
    core: Core,
    original_baddr: u64,
    current_baddr: u64,
    debugger: bool,
    maps: BTreeSet<MapIdentity>,
}

impl AddressResolver {
    fn new(core: Core, info: &DebugInfo) -> Self {
        Self {
            core,
            original_baddr: info.original_baddr,
            current_baddr: core.baddr(),
            debugger: radare2::io_uri::ptrace_pid(core.cmd_str("o.").trim()).is_some(),
            maps: BTreeSet::new(),
        }
    }

    fn rebased(&self, original: u64) -> u64 {
        if original != 0 && self.current_baddr != 0 && self.original_baddr != 0 {
            original.wrapping_add(self.current_baddr.wrapping_sub(self.original_baddr))
        } else {
            original
        }
    }

    fn accept(
        &mut self,
        addr: u64,
        map: MapIdentity,
        require_executable: bool,
    ) -> Option<RuntimeAddress> {
        if require_executable && !map.is_executable() {
            return None;
        }
        self.maps.insert(map);
        Some(RuntimeAddress { addr })
    }

    fn resolve(
        &mut self,
        original: u64,
        paddr: Option<u64>,
        require_executable: bool,
    ) -> Option<RuntimeAddress> {
        let rebased = self.rebased(original);

        if let Some(paddr) = paddr
            && let Some((mapped, map)) = resolve_paddr(self.core, paddr)
            && (self.original_baddr == 0 || mapped == original || mapped == rebased)
            && let Some(address) = self.accept(mapped, map, require_executable)
        {
            return Some(address);
        }

        for candidate in [rebased, original] {
            if candidate == 0 {
                continue;
            }
            let Some((mapped_paddr, map)) = resolve_vaddr(self.core, candidate) else {
                continue;
            };
            if paddr.is_some_and(|expected| expected != mapped_paddr) && !self.debugger {
                continue;
            }
            if let Some(address) = self.accept(candidate, map, require_executable) {
                return Some(address);
            }
        }
        None
    }

    fn identities(&self) -> Vec<MapIdentity> {
        self.maps.iter().copied().collect()
    }
}

/// Result of a successful apply, used for log lines and unload.
#[derive(Debug, Clone)]
pub struct Applied {
    /// Flag names that were created (for `fas unload`).
    pub flags: Vec<String>,
    /// How many native binary symbols were inserted.
    pub native_symbol_count: usize,
    /// How many native addrline entries were written.
    pub line_count: usize,
    /// How many real analyzed functions were newly created.
    pub function_count: usize,
    /// How many conservative FAS reference xrefs were newly inserted.
    pub xref_count: usize,
    /// Path of the dump that was applied.
    pub fas_path: String,
    /// Binary object that owns all native mutations.
    pub identity: BinIdentity,
    /// IO maps used to resolve runtime metadata.
    pub maps: Vec<MapIdentity>,
    symbol_transaction: SymbolTransaction,
    addrline_snapshot: AddrLineSnapshot,
    function_transaction: FunctionTransaction,
    xref_transaction: XrefTransaction,
}

impl Applied {
    /// Return whether this transaction still targets the current bin and maps.
    pub fn target_is_current(&self, core: Core) -> bool {
        self.identity.is_current(core) && self.maps.iter().all(|map| map.is_current(core))
    }
}

/// Failure while applying native metadata to radare2.
#[derive(Debug, Clone)]
pub struct ApplyError {
    message: String,
}

impl ApplyError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl std::fmt::Display for ApplyError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ApplyError {}

/// Load FAS debug info into `core`.
pub fn apply(core: Core, info: &DebugInfo) -> Result<Applied, ApplyError> {
    let identity = BinIdentity::current(core)
        .ok_or_else(|| ApplyError::new("fas: no current binary object for native metadata"))?;
    let mut symbol_transaction = SymbolTransaction::begin(core, identity)
        .ok_or_else(|| ApplyError::new("fas: cannot access the current binary symbol vector"))?;
    let addrline_snapshot = AddrLineSnapshot::capture(core, identity)
        .ok_or_else(|| ApplyError::new("fas: cannot snapshot current source lines"))?;

    for symbol in native_symbols(info) {
        match symbol_transaction.add(core, &symbol) {
            SymbolAdd::Added | SymbolAdd::Duplicate => {}
            SymbolAdd::Failed => {
                let _ = symbol_transaction.rollback(core);
                return Err(ApplyError::new(format!(
                    "fas: failed to insert native symbol {}",
                    symbol.name
                )));
            }
        }
    }

    let mut resolver = AddressResolver::new(core, info);
    let resolved_lines = resolved_addrlines(info, &mut resolver);
    if !replace_addrlines(core, identity, &resolved_lines) {
        let _ = symbol_transaction.rollback(core);
        return Err(ApplyError::new(
            "fas: failed to replace native source lines",
        ));
    }

    let want_comments = core.cfg_bool("fas.comments", true);
    let want_analyze = core.cfg_bool("fas.analyze", true);
    let mut script = String::with_capacity(4096);
    script.push_str("e asm.dwarf=true\nfs fas\n");

    let mut flags = Vec::new();
    for symbol in info.symbols.iter().filter(|symbol| symbol.debugger_visible) {
        let Some(name) = symbol.alias.as_deref().map(sanitize_flag) else {
            continue;
        };
        if name.is_empty() {
            continue;
        }
        let Some(runtime) = resolver.resolve(
            symbol.value,
            symbol.output_offset.map(u64::from),
            symbol.kind == FasSymbolKind::Code,
        ) else {
            continue;
        };
        let size = u64::from(symbol.size.max(1));
        script.push_str(&format!("f {name} {size} @ 0x{:x}\n", runtime.addr));
        if symbol.kind == FasSymbolKind::Data && symbol.size > 0 {
            script.push_str(&format!("Cd {} @ 0x{:x}\n", symbol.size, runtime.addr));
        }
        flags.push(name);
    }
    script.push_str("fs *\n");

    if want_comments {
        for location in info
            .source_locations
            .iter()
            .filter(|location| location.primary)
        {
            let Some(text) = location_comment_text(location) else {
                continue;
            };
            if let Some(runtime) = resolver.resolve(
                location.address,
                Some(u64::from(location.output_offset)),
                false,
            ) {
                script.push_str(&format!("CCu {text} @ 0x{:x}\n", runtime.addr));
            }
        }
    }
    core.cmd_lines(&script);

    let mut xref_transaction = XrefTransaction::begin();
    if let Err(error) = apply_xrefs(core, info, &mut resolver, &mut xref_transaction) {
        let _ = xref_transaction.rollback(core);
        let _ = addrline_snapshot.restore(core);
        let _ = symbol_transaction.rollback(core);
        remove_flags(core, &flags);
        return Err(error);
    }

    let mut function_transaction = FunctionTransaction::begin();
    if want_analyze {
        analyze_functions(core, info, &mut resolver, &mut function_transaction);
    }

    Ok(Applied {
        flags,
        native_symbol_count: symbol_transaction.added(),
        line_count: resolved_lines.len(),
        function_count: function_transaction.added(),
        xref_count: xref_transaction.added(),
        fas_path: info.fas_path.display().to_string(),
        identity,
        maps: resolver.identities(),
        symbol_transaction,
        addrline_snapshot,
        function_transaction,
        xref_transaction,
    })
}

/// Remove native and analysis metadata created by this plugin.
pub fn unload(core: Core, applied: &Applied) -> bool {
    if !applied.target_is_current(core)
        || !applied.xref_transaction.can_rollback(core)
        || !applied.function_transaction.can_rollback(core)
        || !applied.symbol_transaction.can_rollback(core)
    {
        return false;
    }

    if !applied.xref_transaction.rollback(core)
        || !applied.function_transaction.rollback(core)
        || !applied.addrline_snapshot.restore(core)
        || !applied.symbol_transaction.rollback(core)
    {
        return false;
    }
    remove_flags(core, &applied.flags);
    true
}

fn remove_flags(core: Core, flags: &[String]) {
    core.cmd("fs fas");
    for name in flags {
        core.cmd(&format!("f- {name}"));
    }
    core.cmd("fs *");
}

fn native_symbols(info: &DebugInfo) -> Vec<NativeSymbol> {
    info.symbols
        .iter()
        .filter(|symbol| symbol.debugger_visible)
        .filter_map(|symbol| {
            let name = symbol.original_name.clone()?;
            let kind = match symbol.kind {
                FasSymbolKind::Data => NativeSymbolKind::Object,
                FasSymbolKind::Code => NativeSymbolKind::Function,
                _ => NativeSymbolKind::NoType,
            };
            Some(NativeSymbol {
                name,
                paddr: symbol.output_offset.map(u64::from),
                vaddr: symbol.value,
                size: u32::from(symbol.size),
                ordinal: symbol.id.0.try_into().unwrap_or(u32::MAX),
                kind,
            })
        })
        .collect()
}

fn resolved_addrlines(info: &DebugInfo, resolver: &mut AddressResolver) -> Vec<NativeAddrLine> {
    info.source_locations
        .iter()
        .filter(|location| location.primary)
        .filter_map(|location| {
            let runtime = resolver.resolve(
                location.address,
                Some(u64::from(location.output_offset)),
                false,
            )?;
            let source = resolve_source(&info.source_dir, &location.file);
            Some(NativeAddrLine {
                addr: runtime.addr,
                file: source.to_string_lossy().into_owned(),
                path: None,
                line: location.line,
                column: 0,
            })
        })
        .collect()
}

fn analyze_functions(
    core: Core,
    info: &DebugInfo,
    resolver: &mut AddressResolver,
    transaction: &mut FunctionTransaction,
) {
    for symbol in info.symbols.iter().filter(|symbol| {
        symbol.debugger_visible
            && symbol.kind == FasSymbolKind::Code
            && symbol.output_offset.is_some()
    }) {
        let Some(name) = symbol.alias.as_deref().map(sanitize_flag) else {
            continue;
        };
        if name.is_empty() {
            continue;
        }
        let Some(runtime) =
            resolver.resolve(symbol.value, symbol.output_offset.map(u64::from), true)
        else {
            continue;
        };
        match transaction.add(core, runtime.addr, &name) {
            FunctionAdd::Added | FunctionAdd::Existing | FunctionAdd::Failed => {}
        }
    }
}

fn apply_xrefs(
    core: Core,
    info: &DebugInfo,
    resolver: &mut AddressResolver,
    transaction: &mut XrefTransaction,
) -> Result<(), ApplyError> {
    let mut seen = BTreeSet::new();
    for reference in &info.references {
        let Some(symbol) = info.symbols.get(reference.symbol.0) else {
            continue;
        };
        if !symbol.debugger_visible
            || matches!(
                symbol.kind,
                FasSymbolKind::Constant
                    | FasSymbolKind::External
                    | FasSymbolKind::Marker
                    | FasSymbolKind::Anonymous
            )
        {
            continue;
        }
        let Some(location) = info
            .source_locations
            .iter()
            .find(|location| location.row == reference.row)
        else {
            continue;
        };
        if !matches!(location.extent, SourceExtent::Emitted(_)) {
            continue;
        }
        let Some(from) = resolver.resolve(
            location.address,
            Some(u64::from(location.output_offset)),
            false,
        ) else {
            continue;
        };
        let Some(to) = resolver.resolve(symbol.value, symbol.output_offset.map(u64::from), false)
        else {
            continue;
        };
        if from.addr == to.addr || !seen.insert((from.addr, to.addr)) {
            continue;
        }
        if transaction.add(core, from.addr, to.addr, XrefKind::Data) == XrefAdd::Failed {
            return Err(ApplyError::new(format!(
                "fas: failed to insert xref 0x{:x} -> 0x{:x}",
                from.addr, to.addr
            )));
        }
    }
    Ok(())
}

/// Make a string safe as an r2 flag / command name.
pub fn sanitize_flag(name: &str) -> String {
    let mut output: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '_' | '.' | ':') {
                character
            } else {
                '_'
            }
        })
        .collect();
    if output
        .chars()
        .next()
        .is_some_and(|character| character.is_ascii_digit())
    {
        output.insert(0, '_');
    }
    output
}

fn resolve_source(directory: &Path, file: &str) -> PathBuf {
    let path = directory.join(file);
    if path.exists() {
        path
    } else {
        PathBuf::from(file)
    }
}

fn location_comment_text(location: &crate::session::SourceLocation) -> Option<String> {
    let macro_name = location
        .macro_frames
        .first()
        .and_then(|frame| frame.macro_name.as_deref())?;
    let source = location.text.as_deref().unwrap_or("").trim();
    let text = if source.is_empty() {
        format!("macro {macro_name}")
    } else {
        format!("macro {macro_name}: {source}")
    };
    Some(sanitize_comment(&text))
}

fn sanitize_comment(value: &str) -> String {
    value
        .chars()
        .map(|character| match character {
            '\n' | '\r' | ';' | '@' | '"' | '\'' => ' ',
            character => character,
        })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn om_range_covers_elf_load_maps_not_file_offsets() {
        let om = "\
* 3 fd: 3 +0x00000000 0x00400000 - 0x00400266 r-x fmap.LOAD0
- 2 fd: 3 +0x00000267 0x00401267 - 0x00401337 r-- fmap.LOAD1
";
        assert!(maps_cover_addr(om, 0x400112));
        assert!(!maps_cover_addr(om, 0x111));
        assert!(!maps_cover_addr("", 0x400112));
        assert_eq!(
            parse_om_vaddr_range("* 3 fd: 3 +0x00000000 0x00400000 - 0x00400266 r-x fmap.LOAD0"),
            Some((0x400000, 0x400266))
        );
    }

    #[test]
    fn om_range_covers_ptrace_whole_as() {
        let om = "* 3 fd: 4 +0x00000000 0x00000000 - 0xffffffffffffffff rwx dbg.ptrace";
        assert!(maps_cover_addr(om, 0x400112));
    }

    #[test]
    fn sanitizers_preserve_names_and_neutralize_commands() {
        assert_eq!(sanitize_flag("12 bad-name"), "_12_bad_name");
        assert_eq!(
            sanitize_comment("macro x: a; b @ \"c\"\n"),
            "macro x: a b c"
        );
    }
}