dz6 0.8.0

Fast Vim-inspired hex editor for the terminal
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
use std::{
    collections::HashSet,
    fs::{File, OpenOptions},
    io::{self, Seek, SeekFrom, Write},
    path::Path,
    string::FromUtf8Error,
};

use arboard::Clipboard;
use goblin::Object;
use goblin::error;
use mmap_io::{MemoryMappedFile, MmapMode};
use ratatui::{Frame, layout::Rect, widgets::ListState};

use crate::{
    config::*,
    editor::*,
    global::calculator::Calculator,
    header::header_view::{Elf, HeaderView, Pe},
    hex::{hex_view::HexView, strings::FoundString},
    input_history::InputHistory,
    reader::Reader,
    themes::*,
};

#[derive(Default)]
pub struct FileInfo {
    pub file: Option<File>,
    pub path: String,
    pub is_read_only: bool,
    pub name: String,
    pub r#type: &'static str,
    pub size: usize,
    pub mmap: Option<MemoryMappedFile>,
}

impl FileInfo {
    /// Get memory mapped file buffer.
    ///
    /// This slice appears to have all file, but beware it is just a mapping from it and every
    /// time you access a page that is not mapped it will load from disk to memory by the OS,
    /// which also takes care of unloading it if memory constrained.
    pub fn get_buffer(&mut self) -> &[u8] {
        if let Some(mmap) = self.mmap.as_mut() {
            return mmap.as_slice_bytes(0, self.size as u64).unwrap();
        }

        &[]
    }
}

#[derive(Debug)]
pub struct TextView {
    pub area_height: u16,
    pub lines_to_show: usize,
    pub scroll_offset: (u16, u16), // order is (y, x)
    pub table: &'static encoding_rs::Encoding,
}

pub struct Dz6Error {
    // pub code: u16,
    pub message: String,
}

pub struct App {
    pub calculator: Calculator,
    pub clipboard: Result<Clipboard, arboard::Error>,
    pub command_area: Rect,
    pub command_input: InputHistory,
    pub config: Config,
    pub dialog_2nd_renderer: Option<fn(&mut App, &mut Frame)>,
    pub dialog_renderer: Option<fn(&mut App, &mut Frame)>,
    pub editor_view: AppView,
    pub file_info: FileInfo,
    pub header_view: HeaderView,
    pub hex_view: HexView,
    pub last_error: Dz6Error,
    pub list_state: ListState,
    pub log_scroll_offset: (u16, u16),
    pub logs: Vec<String>,
    pub reader: Reader,
    pub running: bool,
    pub screen: Rect,
    pub state: UIState,
    pub string_regex: String,
    pub strings: Vec<FoundString>,
    pub text_view: TextView,
}

impl App {
    pub fn new() -> Self {
        App {
            calculator: Calculator::default(),
            clipboard: Clipboard::new(),
            command_area: Rect::default(),
            command_input: InputHistory::default(),
            config: Config {
                database: true,
                dim_control_chars: false,
                dim_zeroes: true,
                header_base: 16,
                hex_mode_bytes_per_line: 16,
                hex_mode_bytes_per_line_auto: false,
                hex_mode_non_graphic_char: '.',
                maximum_strings_to_show: 3000,
                minimum_string_length: 4,
                search_wrapscan: false,
                search_ignorecase: false,
                search_smartcase: false,
                theme: DARK,
                // hex_mode_dword_separator: '-',
                // text_mode_tab_spaces: 4,
            },
            dialog_renderer: None,
            dialog_2nd_renderer: None,
            editor_view: AppView::Hex,
            file_info: FileInfo::default(),
            header_view: HeaderView {
                // elf_header_table_state: TableState::new().with_selected_cell(Some((0, 1))),
                ..Default::default()
            },
            hex_view: HexView {
                editing_hex: true,
                highlights: HashSet::with_capacity(8),
                ..Default::default()
            },
            list_state: ListState::default(),
            log_scroll_offset: (0, 0),
            logs: Vec::with_capacity(100),
            reader: Reader::new(),
            running: true,
            screen: Rect::default(),
            state: UIState::Normal,
            string_regex: String::new(),
            strings: Vec::new(),
            text_view: TextView {
                area_height: 0,
                lines_to_show: 0,
                scroll_offset: (0, 0),
                table: encoding_rs::UTF_8,
            },
            last_error: Dz6Error {
                message: "Success".to_string(),
            },
        }
    }

    /// this function tries to identify a file type; this is a boilerplate implementation.
    fn id_file(&mut self) -> error::Result<()> {
        let buffer = self.file_info.get_buffer();

        self.file_info.r#type = match Object::parse(buffer)? {
            Object::COFF(_coff) => "COFF",
            Object::Elf(elf) => {
                self.header_view.elf = Some(Elf {
                    header: elf.header,
                    phdrs: elf.program_headers.clone(),
                    sections: elf.section_headers.clone(),
                    dynsymtab: elf.dynsyms.to_vec(),
                    dynstrtab: elf
                        .dynsyms
                        .iter()
                        .map(|s| s.st_name)
                        .filter_map(|idx| {
                            elf.dynstrtab.get_at(idx).map(|name| (idx, name.to_owned()))
                        })
                        .collect(),
                    symtab: elf.syms.to_vec(),
                    strtab: elf
                        .syms
                        .iter()
                        .map(|s| s.st_name)
                        .filter_map(|idx| elf.strtab.get_at(idx).map(|name| (idx, name.to_owned())))
                        .collect(),
                    // for now we'll just create a single vector containing all relocations as generic ones
                    relocs: [
                        elf.pltrelocs.to_vec(),
                        elf.dynrelas.to_vec(),
                        elf.dynrels.to_vec(),
                    ]
                    .concat(),
                });
                "ELF"
            }
            Object::Mach(_mach) => "Mach-O",
            Object::PE(pe) => {
                let mut imports = Vec::new();
                for imp in pe.imports {
                    imports.push(crate::header::header_view::PEImport {
                        dll: imp.dll.to_string(),
                        name: imp.name.to_string(),
                        offset: imp.offset,
                        ordinal: imp.ordinal,
                        rva: imp.rva,
                        _size: imp.size,
                    });
                }

                let mut exports = Vec::new();
                for exp in pe.exports {
                    exports.push(crate::header::header_view::PEExport {
                        name: exp.name.unwrap_or_default().to_string(),
                        offset: exp.offset.unwrap_or_default(),
                        rva: exp.rva,
                        size: exp.size,
                    });
                }

                self.header_view.pe = Some(Pe {
                    dos_header: pe.header.dos_header,
                    coff_header: pe.header.coff_header,
                    optional_header: pe.header.optional_header,
                    sections: pe.sections,
                    imports,
                    exports,
                });

                "PE"
            }
            Object::TE(_magic) => "TE",
            _ => "",
        };

        Ok(())
    }

    /// load a file
    pub fn load_file(
        &mut self,
        filepath: &str,
        initial_offset: usize,
        read_only: bool,
    ) -> io::Result<()> {
        let path = Path::new(&filepath);

        if let Some(f) = path.file_name()
            && let Some(fname) = f.to_str()
        {
            self.file_info.name = String::from(fname);
            self.file_info.path = String::from(filepath);
        }

        let meta = path.metadata()?;

        // We try to open file readwrite to use this later for saving
        if !read_only && let Ok(file) = OpenOptions::new().read(true).write(true).open(path) {
            self.file_info.file = Some(file);
        } else {
            self.file_info.is_read_only = true;
        }

        // We map it on memory readonly as changed to mapped memory also changes it on disk
        if let Ok(mmap) = MemoryMappedFile::builder(path)
            .mode(MmapMode::ReadOnly)
            .open()
        {
            self.file_info.mmap = Some(mmap);
        } else {
            return Err(std::io::Error::other("could not open file"));
        }

        self.file_info.size = meta.len() as usize;

        if self.file_info.size > 0 {
            _ = self.id_file();
        }

        self.log(format!(
            "filesize: {} (0x{:x})",
            self.file_info.size, self.file_info.size
        ));

        if initial_offset != 0 {
            self.goto(0);
        }
        self.goto(initial_offset);

        // try to load a database for this file, but continue otherwise
        if self.config.database {
            let _ = self.load_database();
        }

        Ok(())
    }

    pub fn reload_file(&mut self) {
        let fp = self.file_info.path.clone();
        self.load_file(&fp, self.hex_view.offset, self.file_info.is_read_only)
            .expect("could not reload the file");
    }

    /// write what's cached to the actual file
    pub fn write_to_file(&mut self) -> io::Result<()> {
        if self.file_info.file.is_none() {
            return Err(io::Error::other("file not open"));
        }

        let mut total_written = 0;

        if let Some(f) = &mut self.file_info.file {
            // changed bytes are not necessairily contiguous, so we
            // loop through them when writing to file
            for (k, v) in &self.hex_view.changed_bytes {
                f.seek(SeekFrom::Start(*k as u64))?;
                if let Ok(b) = u8::from_str_radix(v, 16) {
                    let buf = vec![b];
                    let written = f.write(&buf)?;
                    if written != 1 {
                        return Err(io::Error::other("could not write to file"));
                    }
                    total_written += written;
                }
            }
        }

        App::log(self, format!("{} bytes written to file", total_written));
        self.hex_view.changed_bytes.clear();
        Ok(())
    }

    pub fn read_u8(&mut self, offset: usize) -> Option<u8> {
        if offset >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        Some(buffer[offset])
    }

    pub fn read_i8(&mut self, offset: usize) -> Option<i8> {
        if offset >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        Some(buffer[offset] as i8)
    }

    pub fn read_u16(&mut self, offset: usize) -> Option<u16> {
        if offset + 1 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];

        Some(u16::from_le_bytes([b1, b2]))
    }

    pub fn read_i16(&mut self, offset: usize) -> Option<i16> {
        if offset + 1 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];

        Some(i16::from_le_bytes([b1, b2]))
    }

    pub fn read_u32(&mut self, offset: usize) -> Option<u32> {
        if offset + 3 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];
        let b3 = buffer[offset + 2];
        let b4 = buffer[offset + 3];

        Some(u32::from_le_bytes([b1, b2, b3, b4]))
    }

    pub fn read_i32(&mut self, offset: usize) -> Option<i32> {
        if offset + 3 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];
        let b3 = buffer[offset + 2];
        let b4 = buffer[offset + 3];

        Some(i32::from_le_bytes([b1, b2, b3, b4]))
    }

    pub fn read_u64(&mut self, offset: usize) -> Option<u64> {
        if offset + 7 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];
        let b3 = buffer[offset + 2];
        let b4 = buffer[offset + 3];
        let b5 = buffer[offset + 4];
        let b6 = buffer[offset + 5];
        let b7 = buffer[offset + 6];
        let b8 = buffer[offset + 7];

        Some(u64::from_le_bytes([b1, b2, b3, b4, b5, b6, b7, b8]))
    }

    pub fn read_i64(&mut self, offset: usize) -> Option<i64> {
        if offset + 7 >= self.file_info.size {
            return None;
        }

        let buffer = self.file_info.get_buffer();
        let b1 = buffer[offset];
        let b2 = buffer[offset + 1];
        let b3 = buffer[offset + 2];
        let b4 = buffer[offset + 3];
        let b5 = buffer[offset + 4];
        let b6 = buffer[offset + 5];
        let b7 = buffer[offset + 6];
        let b8 = buffer[offset + 7];

        Some(i64::from_le_bytes([b1, b2, b3, b4, b5, b6, b7, b8]))
    }

    pub fn _read_string(&mut self, offset: usize) -> Result<String, FromUtf8Error> {
        let buffer = self.file_info.get_buffer();

        let it = buffer.iter().skip(offset);

        let mut v = Vec::new();
        for e in it {
            v.push(*e);
        }

        String::from_utf8(v)
    }
}