source_viewer 0.4.3

A CLI tool to inspect and analyze binary sources using DWARF debugging information.
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
use crate::config::get_walk_config_path;
use crate::program_context::map_funcs;
use crate::walk;
use crate::file_parser::InstructionDetail;
use fallible_iterator::FallibleIterator;
use crate::args::FileSelection;
use crate::program_context::find_func_name;
use crate::program_context::CodeRegistry;
use crate::walk::FileResult;
use crate::walk::GlobalState;
use crate::walk::TerminalSession;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

use crate::file_parser::create_capstone;
use crate::file_parser::MachineFile;
use crate::file_parser::Section;
use crate::program_context::resolve_func_name;
use crate::program_context::FileRegistry;
// use crate::program_context::format_inst_debug;
use colored::*;
use std::collections::HashSet;
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use typed_arena::Arena;

use crate::println;

// use crate::program_context::AddressFileMapping;

pub fn walk_command(obj_file: Arc<Path>,file:Option<PathBuf>,line:Option<usize>) -> Result<(), Box<dyn std::error::Error>> {
    let asm_arena = Arena::new();
    let code_arena = Arena::new();
    let mut registry = FileRegistry::new(&asm_arena);
    let mut code_files = CodeRegistry::new(&mut registry, &code_arena);

    println!("visiting file {:?}", &*obj_file);
    let machine_file = code_files.visit_machine_file(obj_file.clone())?;
    machine_file.get_lines_map()?;
    machine_file.get_capstone()?;

    // let mut terminal = create_terminal()?;
    // let _cleanup = TerminalCleanup;
    let mut state = GlobalState::start()?;
    let mut session = TerminalSession::new(&mut state)?;

    if let Some(path) = file {
        let path:Arc<Path> = fs::canonicalize(path)?.into();
        let code_file = code_files
            .get_source_file(path.clone(), true)
            .map_err(|e| format!("Failed to load source {:?}: {}", path, e))?;

        let mut file_state = walk::load_file(session.state, &path, code_file)?;
        if let Some(line) = line {
            file_state.file_scroll = line.saturating_sub(1);
            file_state.cursor = line.saturating_sub(1);
        }

        let mut last_frame = Instant::now();
        match TerminalSession::walk_file_loop(
            &mut last_frame,
            &mut session.terminal,
            &mut file_state,
            &mut code_files,
            code_file,
            obj_file.clone(),
        )? {
            FileResult::Exit => return Ok(()),
            FileResult::Dir => {} // fallthrough to directory walker
            FileResult::KeepGoing => unreachable!(),
        }
    }

    session.walk_directory_loop(&mut code_files, obj_file)
}

pub fn lines_command(file_paths: Vec<PathBuf>, ignore_unknown: bool) -> Result<(), Box<dyn Error>> {
    let arena = Arena::new();
    let mut registry = FileRegistry::new(&arena);
    // Iterate over each file path and process it
    for file_path in file_paths {
        println!("{}", format!("Loading file {:?}", file_path).green().bold());
        let machine_file = registry.get_machine(file_path.into())?;
        let ctx = machine_file.get_addr2line()?;
        let cs = create_capstone(machine_file.obj.architecture())?;

        for section in &machine_file.sections.clone() {
            if let Section::Code(code_section) = section {
                println!("{}", section.name());

                code_section.map_asm(&cs,&mut |ins| {
                    let (file, line) = match ctx.find_location(ins.address)? {
                        Some(loc) => {
                            if ignore_unknown && (loc.file.is_none()||loc.line.is_none()){
                                return Ok(());//closure
                            }
                            let file = loc.file.unwrap_or("<unknown>").to_string();
                            let line = loc.line.map(|i| {i.to_string()}).unwrap_or("<unknown>".to_string());
                            (file, line)
                        },
                        None => {
                            if ignore_unknown {
                                return Ok(());//closure
                            }
                            ("<unknown>".to_string(), "<unknown>".to_string())
                        }
                    };
                    let asm = format!(
                        "{:#010x}: {:<6} {:<15}",
                        ins.address,
                        ins.mnemonic,
                        ins.op_str, //this needs a fixup
                    );

                    let func = find_func_name(&ctx, &mut registry, ins.address)
                        .unwrap_or("<unknown>".to_string());

                    println!(
                        "{} {} {}:{}",
                        asm.bold(),
                        func.cyan(),
                        file.to_string().yellow(),
                        line.to_string().blue()
                    );
                    Ok(())
                })?;
            }
        }
    }

    Ok(())
}

use object::{File, Object, ObjectSection};
fn list_dwarf_sections<'a>(obj_file: &'a File<'a>) -> Result<(), Box<dyn std::error::Error>> {
    let sections = [
        ".debug_abbrev",
        ".debug_addr",
        ".debug_aranges",
        ".debug_info",
        ".debug_line",
        ".debug_line_str",
        ".debug_str",
        ".debug_str_offsets",
        ".debug_types",
        ".debug_loc",
        ".debug_ranges",
    ];

    for section_name in &sections {
        // Find the section by name, get the data if available, or return an empty slice
        let section_data = obj_file
            .section_by_name(section_name)
            .and_then(|x| x.data().ok())
            .unwrap_or(&[]);

        // Print the section name and content as UTF-8 (if possible)
        println!(
            "{}:\n{}",
            section_name.blue(),
            String::from_utf8_lossy(section_data)
        );
    }
    Ok(())
}

pub fn dwarf_dump_command(file_paths: Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
    let message = "NOTE: this comand is not finised".to_string().red();
    println!("{}", message);
    // Iterate over each file path and process it
    for file_path in file_paths {
        println!("{}", format!("Loading file {:?}", file_path).green().bold());
        let buffer = fs::read(file_path)?;
        let machine_file = MachineFile::parse(&buffer)?;
        // let dwarf = machine_file.load_dwarf()?;
        // println!("{:#?}",dwarf );
        list_dwarf_sections(&machine_file.obj)?;
    }
    println!("{}", message);

    Ok(())
}

pub fn sections_command(file_paths: Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
    // Iterate over each file path and process it
    for file_path in file_paths {
        println!("{}", format!("Loading file {:?}", file_path).green().bold());
        let buffer = fs::read(file_path)?;
        let mut machine_file = MachineFile::parse(&buffer)?;
        let debug = machine_file.get_addr2line().ok();
        let cs = create_capstone(machine_file.obj.architecture())?;

        for section in &mut machine_file.sections {
            match section {
                Section::Code(code_section) => {
                    // lazy.disasm(&machine_file.obj.architecture())?;
                    println!(
                        "Code Section: {} ({} bytes)",
                        code_section.name.blue(),
                        code_section.data.len()
                    );

                    code_section.map_asm(&cs,&mut |instruction:&InstructionDetail|{
                        let func_name = match &debug {
                            None => None,
                            Some(ctx) => resolve_func_name(ctx, instruction.address),
                        };
                        // func_name.as_mut().map(|x| x.push_str(" "));
                        // println!("  {}", instruction);
                        println!(
                            "  {:#010x}: {:<6} {:<30} {}",
                            instruction.address,
                            instruction.mnemonic,
                            instruction.op_str,
                            func_name.as_deref().unwrap_or("")
                        );
                        Ok(())
                    })?;
                }
                Section::Info(non_exec) => {
                    println!(
                        "Non-Executable Section: {} ({} bytes)",
                        non_exec.name.blue(),
                        non_exec.data.len()
                    );

                    // println!("{}", String::from_utf8_lossy(non_exec.data) );
                }
            }
        }
    }

    Ok(())
}


pub fn view_sources_command(file_paths: Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
    let mut source_files: HashSet<Box<str>> = HashSet::new();
    for file_path in file_paths {
        println!("{}", format!("Loading file {:?}", file_path).green().bold());
        let buffer = fs::read(file_path)?;
        let machine_file = MachineFile::parse(&buffer)?;
        let ctx = machine_file.get_addr2line()?;
        for section in machine_file.sections.iter(){
            let Section::Code(code) = section else{
                continue;
            };

            let mut locs = ctx.find_location_range(code.address,code.get_high())?;
            while let Some((_,_,loc)) =FallibleIterator::next(&mut locs)?{
                if let Some(file) = loc.file{
                    source_files.insert(file.into());
                }
            }

        }
    }


    let mut source_files: Vec<_> = source_files.into_iter().collect();
    source_files.sort();

    println!("Source files:");
    for (index, file) in source_files.iter().enumerate() {
        println!("{}: {:?}", index, file);
    }
    Ok(())
}

pub fn view_source_command(
    file_path: &Path,
    look_all: bool,
    walk: bool,
    selections: Vec<FileSelection>,
) -> Result<(), Box<dyn Error>> {
    //we allow look_all and selections at the same time we simply ignore selctions

    //removing this just for dev
    // if walk && (look_all || selections.len() > 1) {
    //     return Err("Can only walk in 1 file at a time".into());
    // }

    if walk && selections.len() == 0 {
        return Err("No walk selection provided".into());
    }

    // Load and parse the binary
    let obj_file: Arc<Path> = file_path.into();
    let asm_arena = Arena::new();
    let code_arena = Arena::new();
    let mut registry = FileRegistry::new(&asm_arena);
    let mut code_files = CodeRegistry::new(&mut registry, &code_arena);
    let machine_file = code_files.visit_machine_file(obj_file.clone())?;
    let ctx = machine_file.get_addr2line()?;

    // Populate a unique list of source files in the order they appear
    let mut source_files_set: HashSet<PathBuf> = HashSet::new();
    for section in machine_file.sections.iter(){
        let Section::Code(code) = section else{
            continue;
        };

        let mut locs = ctx.find_location_range(code.address,code.get_high())?;
        while let Some((_,_,loc)) =FallibleIterator::next(&mut locs)?{
            if let Some(file) = loc.file{
                source_files_set.insert(file.into());
            }
        }

    }

    let mut source_files: Vec<&Path> = source_files_set.iter().map(|p| p.as_path()).collect();
    source_files.sort();

    if walk {
        machine_file.get_lines_map()?;
        machine_file.get_capstone()?;

        let file_path = match &selections[0] {
            FileSelection::Index(i) => {
                if let Some(file) = source_files.get(*i) {
                    *file
                } else {
                    println!("{}", format!("Index {} is out of bounds", i).red());
                    return Ok(());
                }
            }
            FileSelection::Path(path) => {
                if let Some(ans) = source_files_set.get(path) {
                    ans
                } else {
                    println!(
                        "{}",
                        format!("Path {:?} is not included in the binary", path).red()
                    );
                    return Ok(());
                }
            }
        };
        let file_path = Path::new(file_path.into());
        let parent = file_path
            .parent()
            .ok_or("No parent dir to path")?
            .to_path_buf();

        let mut state = GlobalState::start_from(parent.into())?;
        let mut session = TerminalSession::new(&mut state)?;

        let code_file = code_files.get_source_file(file_path.into(),true)?;

        //file
        {
            let mut file_state = crate::walk::load_file(session.state, file_path,code_file)?;
            if let Some(FileSelection::Index(i)) = selections.get(1) {
                file_state.file_scroll = i.saturating_sub(1);
                file_state.cursor = i.saturating_sub(1);
            };
            let mut last_frame = Instant::now();
            let res = TerminalSession::walk_file_loop(
                &mut last_frame,
                &mut session.terminal,
                &mut file_state,
                &mut code_files,
                code_file,
                obj_file.clone(),
            )?;

            match res {
                FileResult::Exit => return Ok(()),
                FileResult::Dir => {}
                FileResult::KeepGoing => unreachable!(),
            }
        }

        return session.walk_directory_loop(&mut code_files, obj_file);
    }

    // Display source files with their indices
    println!("Source files:");
    for (index, file) in source_files.iter().enumerate() {
        println!("{}: {:?}", index, file);
    }

    // Collect files to display based on the selections or `-a` flag
    let mut files_to_display: Vec<&Path> = Vec::new();

    if look_all {
        // Add all files if `-a` is set
        files_to_display.extend(source_files.iter());
    } else {
        // Add files based on selections
        for selection in selections {
            match selection {
                FileSelection::Index(i) => {
                    if let Some(file) = source_files.get(i) {
                        files_to_display.push(file);
                    } else {
                        println!("{}", format!("Index {} is out of bounds", i).red());
                    }
                }
                FileSelection::Path(path) => {
                    if let Some(file) = source_files_set.get(&path) {
                        files_to_display.push(file);
                    } else {
                        println!(
                            "{}",
                            format!("Path {:?} is not included in the binary", path).red()
                        );
                    }
                }
            }
        }
    }

    // Display the contents of each file in `files_to_display`
    for file in files_to_display {
        display_file_contents(file)?;
    }

    Ok(())
}

// Helper function to display the contents of a file with line numbers
fn display_file_contents(file_path: &Path) -> Result<(), Box<dyn Error>> {
    match fs::canonicalize(file_path) {
        Ok(file) => match fs::read_to_string(&file) {
            Ok(source_text) => {
                println!("Contents of {:?}:", file);
                for (i, line) in source_text.lines().enumerate() {
                    println!("{:4} {}", i + 1, line);
                }
            }
            Err(e) => {
                println!("{} reading {:?}: {}", "FAILED".red(), file, e);
            }
        },
        Err(_) => {
            println!("{}", format!("{:?} does not exist", file_path).red());
        }
    }
    Ok(())
}

pub fn functions_command(file_paths: Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
    let arena = Arena::new();
    let mut registry = FileRegistry::new(&arena);

    // Iterate over each file path and process it
    for file_path in file_paths {
        let mut seen = HashSet::new();

        println!("{}", format!("functions in {:?}", file_path).green().bold());
        let machine_file = registry.get_machine(file_path.into())?;
        let ctx = machine_file.get_addr2line()?;
        let cs = create_capstone(machine_file.obj.architecture())?;

        for section in &machine_file.sections.clone() {
            if let Section::Code(code_section) = section {

                code_section.map_asm(&cs,&mut |ins| {
                    map_funcs(&ctx, &mut registry, ins.address,|func|{
                        if seen.insert(func.to_string()){
                            println!("{} {}",seen.len().to_string().blue(),func);
                        }
                        Ok(())

                    })
                })?;
            }
        }
    }

    Ok(())
}

pub fn config_paths_command() -> Result<(), Box<dyn Error>> {
    let w = get_walk_config_path();
    let walk_path = match w {
        Some(ref p)=>p.to_string_lossy(),
        None=>"<does not exist>".into()
    };
    println!("  walk confing {}",walk_path);
    Ok(())
}