Skip to content

Commit 7d849bd

Browse files
authored
Merge pull request #138 from acheron2302/main
Adding I-cache and Memory permission for emulation
2 parents 13dca5b + 6c077e0 commit 7d849bd

File tree

869 files changed

+6444
-5870
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

869 files changed

+6444
-5870
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ members = [
99
[profile.release]
1010
debug = 0
1111
strip = true
12-
opt-level = 2
12+
opt-level = 3
1313
panic = 'unwind'
1414

1515
[profile.dev]

crates/libmwemu/src/banzai.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,4 @@ impl Banzai {
3030
pub fn add(&mut self, name: &str, nparams: i32) {
3131
self.api_params.insert(name.to_string(), nparams);
3232
}
33-
3433
}

crates/libmwemu/src/breakpoint.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ impl Default for Breakpoints {
2222
}
2323
}
2424

25-
2625
impl Breakpoints {
2726
// TODO: implementing clearing breakpoint for console
2827
pub fn new() -> Self {
@@ -109,10 +108,18 @@ impl Breakpoints {
109108
let instruction_str: Vec<String> = self.addr.iter().map(|a| format!("0x{:x}", a)).collect();
110109
log::info!("break on instruction: [{}]", instruction_str.join(", ")); // Uses Debug formatting for the whole vector
111110

112-
let mem_read_str: Vec<String> = self.mem_read_addr.iter().map(|a| format!("0x{:x}", a)).collect();
111+
let mem_read_str: Vec<String> = self
112+
.mem_read_addr
113+
.iter()
114+
.map(|a| format!("0x{:x}", a))
115+
.collect();
113116
log::info!("break on memory read: [{}]", mem_read_str.join(", "));
114117

115-
let mem_write_str: Vec<String> = self.mem_write_addr.iter().map(|a| format!("0x{:x}", a)).collect();
118+
let mem_write_str: Vec<String> = self
119+
.mem_write_addr
120+
.iter()
121+
.map(|a| format!("0x{:x}", a))
122+
.collect();
116123
log::info!("break on memory write: [{}]", mem_write_str.join(", "));
117124
}
118125
}

crates/libmwemu/src/colors.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ pub struct Colors {
2424
pub clear_screen: String,
2525
}
2626

27-
2827
impl Default for Colors {
2928
fn default() -> Self {
3029
Self::new()

crates/libmwemu/src/config.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
use std::collections::HashMap;
22

3-
use serde::{Deserialize, Serialize};
43
use crate::{constants, definitions::Definition};
4+
use serde::{Deserialize, Serialize};
55

66
#[derive(Clone, Serialize, Deserialize)]
77
pub struct Config {
8-
pub filename: String, // filename with full path included
9-
pub trace_mem: bool, // show memory operations in every step.
8+
pub filename: String, // filename with full path included
9+
pub trace_mem: bool, // show memory operations in every step.
1010
pub trace_calls: bool, // trace every call
11-
pub trace_regs: bool, // show all the regs in every step.
12-
pub trace_reg: bool, // show value and content of a reg in every step.
11+
pub trace_regs: bool, // show all the regs in every step.
12+
pub trace_reg: bool, // show value and content of a reg in every step.
1313
pub trace_filename: Option<String>,
1414
pub trace_start: u64,
1515
pub trace_string: bool,
@@ -39,7 +39,7 @@ pub struct Config {
3939
pub skip_unimplemented: bool,
4040
pub stack_addr: u64,
4141
pub arguments: String,
42-
pub enable_threading: bool, // Enable multi-threading support
42+
pub enable_threading: bool, // Enable multi-threading support
4343
pub verbose_at: Option<u64>,
4444
pub command: Option<String>,
4545
pub definitions: HashMap<u64, Definition>,
@@ -89,7 +89,7 @@ impl Config {
8989
skip_unimplemented: false,
9090
stack_addr: 0,
9191
arguments: "".to_string(),
92-
enable_threading: false, // Default to single-threaded for backward compatibility
92+
enable_threading: false, // Default to single-threaded for backward compatibility
9393
verbose_at: None,
9494
command: None,
9595
definitions: HashMap::new(),

crates/libmwemu/src/console.rs

Lines changed: 36 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
use std::io::Write;
2-
use std::num::ParseIntError;
3-
use std::sync::atomic;
41
use crate::emu::Emu;
52
use crate::peb::peb32;
63
use crate::peb::peb64;
@@ -9,11 +6,15 @@ use crate::structures;
96
use crate::to32;
107
use crate::winapi::winapi32;
118
use crate::winapi::winapi64;
9+
use std::io::Write;
10+
use std::num::ParseIntError;
11+
use std::sync::atomic;
1212

1313
// if the user types "r2 0x123" will execute radare2
14-
use std::process::{Command, Stdio};
14+
use crate::maps::mem64::Permission;
1515
use std::fs;
1616
use std::io;
17+
use std::process::{Command, Stdio};
1718

1819
pub struct Console {}
1920

@@ -163,22 +164,25 @@ impl Console {
163164
}
164165

165166
pub fn spawn_radare2(addr: u64, emu: &mut Emu) {
166-
167167
let mem = match emu.maps.get_mem_by_addr(addr) {
168168
Some(m) => m,
169169
None => {
170170
log::info!("address not found on any map");
171-
return
171+
return;
172172
}
173173
};
174174

175175
let tmpfile = format!("/tmp/{}.r2", mem.get_name());
176176
mem.save_all(&tmpfile);
177177

178-
let base = format!("0x{:x}",mem.get_base());
179-
let seek = format!("0x{:x}",addr);
178+
let base = format!("0x{:x}", mem.get_base());
179+
let seek = format!("0x{:x}", addr);
180180
let bits;
181-
if emu.cfg.is_64bits { bits = "64" } else { bits = "32" }
181+
if emu.cfg.is_64bits {
182+
bits = "64"
183+
} else {
184+
bits = "32"
185+
}
182186
let precmd = format!("dr rax={}?; dr rbx={}?; dr rcx={}?; dr rdx={}?; dr rsi={}?;
183187
dr rdi={}?; dr rbp={}?; dr rsp={}?; dr rip={}?; dr r8={}?
184188
dr r9={}?; dr r10={}?; dr r11={}?; dr r12={}?; dr r13={}?;
@@ -189,30 +193,25 @@ impl Console {
189193
emu.regs().r11, emu.regs().r12, emu.regs().r13, emu.regs().r14,
190194
emu.regs().r15);
191195
let r2args = vec![
192-
"-n",
193-
"-a", "x86",
194-
"-b", &bits,
195-
"-m", &base,
196-
"-s", &seek,
197-
"-c", &precmd,
198-
&tmpfile
196+
"-n", "-a", "x86", "-b", &bits, "-m", &base, "-s", &seek, "-c", &precmd, &tmpfile,
199197
];
200198

201199
log::info!("spawning radare2 software.");
202-
200+
203201
match Command::new("radare2")
204202
.args(&r2args)
205203
.stdin(Stdio::inherit())
206204
.stdout(Stdio::inherit())
207205
.stderr(Stdio::inherit())
208-
.spawn() {
209-
Ok(mut child) => {
210-
let _ = child.wait();
211-
}
212-
Err(e) => {
213-
log::error!("Install radare first! {}", e);
214-
return
215-
}
206+
.spawn()
207+
{
208+
Ok(mut child) => {
209+
let _ = child.wait();
210+
}
211+
Err(e) => {
212+
log::error!("Install radare first! {}", e);
213+
return;
214+
}
216215
}
217216

218217
if let Err(e) = fs::remove_file(&tmpfile) {
@@ -222,7 +221,6 @@ impl Console {
222221
}
223222
}
224223

225-
226224
pub fn spawn_console(emu: &mut Emu) {
227225
if !emu.cfg.console_enabled {
228226
return;
@@ -520,7 +518,7 @@ impl Console {
520518
}
521519
};
522520
emu.maps
523-
.create_map(&name, addr, sz)
521+
.create_map(&name, addr, sz, Permission::READ_WRITE_EXECUTE)
524522
.expect("cannot create map from console mc");
525523
log::info!("allocated {} at 0x{:x} sz: {}", name, addr, sz);
526524
}
@@ -546,7 +544,7 @@ impl Console {
546544
};
547545

548546
emu.maps
549-
.create_map(&name, addr, sz)
547+
.create_map(&name, addr, sz, Permission::READ_WRITE_EXECUTE)
550548
.expect("cannot create map from console mca");
551549
log::info!("allocated {} at 0x{:x} sz: {}", name, addr, sz);
552550
}
@@ -578,7 +576,10 @@ impl Console {
578576
}
579577
};
580578

581-
let mem = emu.maps.get_mem_by_addr(addr).expect("address not found on any map");
579+
let mem = emu
580+
.maps
581+
.get_mem_by_addr(addr)
582+
.expect("address not found on any map");
582583
if emu.cfg.is_64bits {
583584
log::info!(
584585
"map: {} 0x{:x}-0x{:x} ({})",
@@ -1033,14 +1034,13 @@ impl Console {
10331034
if parts.len() >= 2 {
10341035
emu.maps.print_maps_keyword(&parts[1]);
10351036
}
1036-
10371037
} else if cmd.starts_with("r2 ") {
1038-
let parts: Vec<&str> = cmd.split_whitespace().collect();
1039-
if parts.len() >= 2 {
1040-
if let Ok(addr) = u64::from_str_radix(parts[1].trim_start_matches("0x"), 16) {
1041-
1038+
let parts: Vec<&str> = cmd.split_whitespace().collect();
1039+
if parts.len() >= 2 {
1040+
if let Ok(addr) =
1041+
u64::from_str_radix(parts[1].trim_start_matches("0x"), 16)
1042+
{
10421043
Console::spawn_radare2(addr, emu);
1043-
10441044
} else {
10451045
println!("wrong hexa parameter");
10461046
}
@@ -1052,11 +1052,10 @@ impl Console {
10521052
}
10531053
}
10541054
} // match commands
1055-
1055+
10561056
if emu.cfg.command.is_some() {
10571057
std::process::exit(1);
10581058
}
1059-
10601059
} // end loop
10611060
} // end commands function
10621061
}

crates/libmwemu/src/constants.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,8 @@ pub const INTERNET_FLAG_SECURE: u64 = 0x00800000;
9898
// exceptions
9999
pub const EXCEPTION_CONTINUE_EXECUTION32: u32 = 0xffffffff;
100100
pub const EXCEPTION_CONTINUE_EXECUTION64: u64 = 0xffffffff_ffffffff;
101-
pub const EXCEPTION_CONTINUE_SEARCH: u32 = 0x00000000;
102-
pub const EXCEPTION_EXECUTE_HANDLER: u32 = 0x00000001;
103-
101+
pub const EXCEPTION_CONTINUE_SEARCH: u32 = 0x00000000;
102+
pub const EXCEPTION_EXECUTE_HANDLER: u32 = 0x00000001;
104103

105104
pub const ERROR_NO_MORE_FILES: u64 = 18;
106105
pub const CREATE_SUSPENDED: u64 = 0x00000004;
@@ -119,7 +118,6 @@ pub const STATUS_READING_XMM_OPERAND: u32 = 0xE000000A;
119118
pub const STATUS_WRITING_XMM_OPERAND: u32 = 0xE000000B;
120119
pub const STATUS_READING_RIP: u32 = 0xE000000C;
121120

122-
123121
pub const PAGE_NOACCESS: u32 = 0x01;
124122
pub const PAGE_EXECUTE: u32 = 0x00;
125123
pub const PAGE_READONLY: u32 = 0x02;

crates/libmwemu/src/crit_state.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::collections::VecDeque;
22

33
#[derive(Debug, Clone)]
44
pub struct CritState {
5-
pub owner_tid: Option<u64>, // Thread ID currently owning the lock
6-
pub recursion_count: usize, // Recursive enter count
7-
pub wait_queue: VecDeque<u64>, // Waiting thread IDs
5+
pub owner_tid: Option<u64>, // Thread ID currently owning the lock
6+
pub recursion_count: usize, // Recursive enter count
7+
pub wait_queue: VecDeque<u64>, // Waiting thread IDs
88
}

crates/libmwemu/src/definitions.rs

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,17 @@ where
4242
{
4343
let s: String = serde::Deserialize::deserialize(deserializer)?;
4444
if s.starts_with("0x") {
45-
u64::from_str_radix(&s[2..], 16)
46-
.map_err(|e| serde::de::Error::custom(e))
45+
u64::from_str_radix(&s[2..], 16).map_err(|e| serde::de::Error::custom(e))
4746
} else {
48-
s.parse::<u64>()
49-
.map_err(|e| serde::de::Error::custom(e))
47+
s.parse::<u64>().map_err(|e| serde::de::Error::custom(e))
5048
}
5149
}
5250

5351
pub fn load_definitions(filename: &str) -> HashMap<u64, Definition> {
54-
let contents = fs::read_to_string(filename)
55-
.expect("Failed to read definitions file");
56-
57-
let definitions: Definitions = serde_yaml::from_str(&contents)
58-
.expect("Failed to parse YAML");
59-
52+
let contents = fs::read_to_string(filename).expect("Failed to read definitions file");
53+
54+
let definitions: Definitions = serde_yaml::from_str(&contents).expect("Failed to parse YAML");
55+
6056
let mut map = HashMap::new();
6157
for def in definitions.events {
6258
map.insert(def.address, def);
@@ -69,18 +65,28 @@ impl Emu {
6965
let rip = self.regs().rip;
7066
let definitions = &self.cfg.definitions;
7167
if let Some(definition) = definitions.get(&rip) {
72-
log::info!("Event: {} (0x{:x}) - {}", definition.name, rip, definition.event_type);
73-
68+
log::info!(
69+
"Event: {} (0x{:x}) - {}",
70+
definition.name,
71+
rip,
72+
definition.event_type
73+
);
74+
7475
// Store context if needed
7576
if let Some(context_name) = &definition.store_context {
7677
let mut context_values = HashMap::new();
7778
for param in &definition.parameters {
7879
let value = self.resolve_source(&param.source);
7980
context_values.insert(param.name.clone(), value);
8081
}
81-
self.stored_contexts.insert(context_name.clone(), StoredContext { values: context_values });
82+
self.stored_contexts.insert(
83+
context_name.clone(),
84+
StoredContext {
85+
values: context_values,
86+
},
87+
);
8288
}
83-
89+
8490
// Display parameters
8591
for param in &definition.parameters {
8692
let value = self.resolve_source(&param.source);
@@ -89,10 +95,10 @@ impl Emu {
8995
}
9096
}
9197
}
92-
98+
9399
fn resolve_source(&self, source: &str) -> u64 {
94100
let parts: Vec<&str> = source.split(':').collect();
95-
101+
96102
match parts[0] {
97103
"deref" => {
98104
// deref:context:context_name:param_name or deref:register
@@ -128,7 +134,7 @@ impl Emu {
128134
}
129135
}
130136
}
131-
137+
132138
fn get_parameter_value(&self, source: &str) -> u64 {
133139
match source {
134140
"rcx" => self.regs().rcx,
@@ -156,7 +162,7 @@ impl Emu {
156162
}
157163
}
158164
}
159-
165+
160166
fn format_parameter_value(&self, value: u64, param_type: &str) -> String {
161167
match param_type {
162168
"pointer" => format!("0x{:x}", value),
@@ -176,4 +182,4 @@ impl Emu {
176182
_ => format!("0x{:x}", value),
177183
}
178184
}
179-
}
185+
}

0 commit comments

Comments
 (0)