Skip to content

Commit 2f819ce

Browse files
committed
Major code refactoring with clippy.
1 parent 1b3cb03 commit 2f819ce

13 files changed

+301
-314
lines changed

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
name = "deoptimizer"
33
version = "0.1.0"
44
edition = "2021"
5-
license = "MIT OR Apache-2.0"
6-
license-file = "LICENSE"
5+
license = "MIT"
6+
# license-file = "LICENSE"
77
readme = "README.md"
88
repository = "https://github.com/EgeBalci/deoptimizer"
99
authors = ["Ege BALCI <[email protected]>"]

src/options.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ pub fn parse_options() -> Result<Options, ArgParseError> {
9191
// let mut opts: Options = argh::from_env();
9292
let mut opts = Options::parse();
9393
if opts.file.is_empty() {
94-
print!("\n");
94+
println!();
9595
error!("The '-f' parameter is mandatory.\n");
9696
Options::command().print_help()?;
9797
process::exit(0x01);
@@ -120,11 +120,11 @@ pub fn parse_options() -> Result<Options, ArgParseError> {
120120
}
121121

122122
pub fn parse_offset(offsets: &str) -> Result<(u32, u32), ArgParseError> {
123-
if offsets.matches("-").count() != 1 {
123+
if offsets.matches('-').count() != 1 {
124124
return Err(ArgParseError::InvalidOffsetValues);
125125
}
126126
let mut off: Vec<u32> = Vec::new();
127-
for part in offsets.split("-") {
127+
for part in offsets.split('-') {
128128
if part.starts_with("0x") {
129129
off.push(u32::from_str_radix(part.trim_start_matches("0x"), 16)?)
130130
} else {
@@ -201,5 +201,5 @@ pub fn print_summary(opts: &Options) {
201201
opts.transforms,
202202
" ".repeat(wspace - opts.transforms.len())
203203
);
204-
print!("\n");
204+
println!();
205205
}

src/x86_64/deoptimizer.rs

+22-28
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,31 @@ use crate::x86_64::*;
22
use bitflags::bitflags;
33
use iced_x86::code_asm::*;
44
use iced_x86::*;
5-
use log::{debug, error, info, trace, warn};
6-
use rand::{seq::SliceRandom, Rng};
5+
use log::{error, info, trace, warn};
6+
use rand::Rng;
77
use std::collections::HashMap;
88
use thiserror::Error;
99

1010
#[derive(Error, Debug)]
1111
pub enum DeoptimizerError {
12+
// #[error("Instruction with unexpected operand count.")]
13+
// UnexpectedOperandCount,
14+
// #[error("Given instruction not found in code map.")]
15+
// InstructionNotFound,
16+
// #[error("Code analysis results are not found.")]
17+
// MissingCodeAnalysis,
18+
// #[error("Near branch value too large.")]
19+
// NearBranchTooBig,
20+
// #[error("Unexpected memory size given.")]
21+
// UnexpectedMemorySize,
22+
// #[error("Offset skipping failed!")]
23+
// OffsetSkipFail,
1224
#[error("Invalid formatter syntax.")]
1325
InvalidSyntax,
1426
#[error("Invalid processor mode(bitness). (16/32/64 accepted)")]
1527
InvalidProcessorMode,
16-
#[error("Instruction with unexpected operand count.")]
17-
UnexpectedOperandCount,
1828
#[error("All available instruction transform gadgets failed.")]
1929
AllTransformsFailed,
20-
#[error("Given instruction not found in code map.")]
21-
InstructionNotFound,
22-
#[error("Code analysis results are not found.")]
23-
MissingCodeAnalysis,
24-
#[error("Near branch value too large.")]
25-
NearBranchTooBig,
2630
#[error("Far branch value too large.")]
2731
FarBranchTooBig,
2832
#[error("Found invalid instruction.")]
@@ -31,8 +35,6 @@ pub enum DeoptimizerError {
3135
BracnhTargetNotFound,
3236
#[error("This transform not possible for given instruction.")]
3337
TransformNotPossible,
34-
#[error("Unexpected memory size given.")]
35-
UnexpectedMemorySize,
3638
#[error("Unexpected register size given.")]
3739
UnexpectedRegisterSize,
3840
#[error("Unexpected operand type encountered.")]
@@ -45,8 +47,6 @@ pub enum DeoptimizerError {
4547
TransposeFailed,
4648
#[error("Invalid transform gadget.")]
4749
InvalidTransformGadget,
48-
#[error("Offset skipping failed!")]
49-
OffsetSkipFail,
5050
#[error("Instruction encoding failed: {0}")]
5151
EncodingFail(#[from] IcedError),
5252
}
@@ -58,6 +58,7 @@ enum AssemblySyntax {
5858
Intel,
5959
Gas,
6060
}
61+
6162
bitflags! {
6263
#[derive(Clone, Copy, Debug,PartialEq,Eq, Hash)]
6364
pub struct AvailableTransforms: u8 {
@@ -154,8 +155,8 @@ impl Deoptimizer {
154155

155156
pub fn set_transform_gadgets(&mut self, transforms: String) -> Result<(), DeoptimizerError> {
156157
let mut selected_transforms = AvailableTransforms::None;
157-
let trs = transforms.split(",");
158-
for (_i, t) in trs.enumerate() {
158+
let trs = transforms.split(',');
159+
for t in trs {
159160
match t.to_uppercase().as_str() {
160161
"AP" => selected_transforms |= AvailableTransforms::ArithmeticPartitioning,
161162
"LI" => selected_transforms |= AvailableTransforms::LogicalInverse,
@@ -182,9 +183,7 @@ impl Deoptimizer {
182183
}
183184

184185
pub fn set_skipped_offsets(&mut self, skipped: Vec<(u32, u32)>) {
185-
if skipped.len() > 0 {
186-
self.skipped_offsets = Some(skipped);
187-
}
186+
self.skipped_offsets = Some(skipped);
188187
}
189188

190189
fn is_offset_skipped(&self, offset: u32) -> bool {
@@ -234,7 +233,7 @@ impl Deoptimizer {
234233
let mut decoder = Decoder::with_ip(bitness, bytes, start_addr, DecoderOptions::NONE);
235234
let replaced_bytes: Vec<u8>;
236235
if self.skipped_offsets.is_some() {
237-
replaced_bytes = self.replace_skipped_offsets(&bytes, 0x90)?;
236+
replaced_bytes = self.replace_skipped_offsets(bytes, 0x90)?;
238237
decoder = Decoder::with_ip(bitness, &replaced_bytes, start_addr, DecoderOptions::NONE);
239238
}
240239

@@ -285,7 +284,7 @@ impl Deoptimizer {
285284
}
286285

287286
for bt in branch_targets.iter() {
288-
if !known_addr_table.contains(&bt) {
287+
if !known_addr_table.contains(bt) {
289288
warn!(
290289
"Branch target 0x{:016X} is outside the known address sapce!",
291290
bt
@@ -461,12 +460,7 @@ impl Deoptimizer {
461460
if acode.is_branch_target(inst.ip()) {
462461
ip_to_index_table.insert(inst.ip(), result.len());
463462
}
464-
match Deoptimizer::apply_transform(
465-
acode.bitness,
466-
&inst,
467-
self.freq,
468-
self.transforms.clone(),
469-
) {
463+
match Deoptimizer::apply_transform(acode.bitness, &inst, self.freq, self.transforms) {
470464
Ok(dinst) => {
471465
result = [result, dinst.clone()].concat();
472466
print_inst_diff(&inst, dinst);
@@ -507,7 +501,7 @@ impl Deoptimizer {
507501
result[*idx]
508502
);
509503
result[i] = set_branch_target(
510-
&mut result[i].clone(),
504+
&result[i].clone(),
511505
result[*idx].ip(),
512506
acode.bitness,
513507
)?;

src/x86_64/helpers.rs

+68-75
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pub fn random_immediate_value(kind: OpKind) -> Result<u64, DeoptimizerError> {
2020
})
2121
}
2222

23-
pub fn adjust_instruction_addrs(code: &mut Vec<Instruction>, start_addr: u64) {
23+
pub fn adjust_instruction_addrs(code: &mut [Instruction], start_addr: u64) {
2424
let mut new_ip = start_addr;
2525
for inst in code.iter_mut() {
2626
inst.set_ip(new_ip);
@@ -61,35 +61,35 @@ pub fn get_instruction_bytes(bitness: u32, insts: Vec<Instruction>) -> Result<Ve
6161
Ok(buffer)
6262
}
6363

64-
pub fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
65-
haystack
66-
.windows(needle.len())
67-
.position(|window| window == needle)
68-
}
69-
70-
pub fn generate_random_instructions(size: usize) -> Vec<u8> {
71-
let small_mnemonics = [
72-
0x90, // nop
73-
0xc3, // ret
74-
0xf1, // int1
75-
0xf4, // hlt
76-
0xf5, // cmc
77-
0xf8, // clc
78-
0xfa, // cli
79-
0xf9, // stc
80-
0xfb, // sti
81-
0xfc, // cld
82-
]
83-
.to_vec();
84-
let mut output = Vec::new();
85-
for _ in 0..size {
86-
output.push(*small_mnemonics.choose(&mut rand::thread_rng()).unwrap() as u8)
87-
}
88-
output
89-
}
64+
// pub fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
65+
// haystack
66+
// .windows(needle.len())
67+
// .position(|window| window == needle)
68+
// }
69+
//
70+
// pub fn generate_random_instructions(size: usize) -> Vec<u8> {
71+
// let small_mnemonics = [
72+
// 0x90, // nop
73+
// 0xc3, // ret
74+
// 0xf1, // int1
75+
// 0xf4, // hlt
76+
// 0xf5, // cmc
77+
// 0xf8, // clc
78+
// 0xfa, // cli
79+
// 0xf9, // stc
80+
// 0xfb, // sti
81+
// 0xfc, // cld
82+
// ]
83+
// .to_vec();
84+
// let mut output = Vec::new();
85+
// for _ in 0..size {
86+
// output.push(*small_mnemonics.choose(&mut rand::thread_rng()).unwrap() as u8)
87+
// }
88+
// output
89+
// }
9090

9191
pub fn print_inst_diff(inst: &Instruction, dinst: Vec<Instruction>) {
92-
if log::max_level() <= log::Level::Info || dinst.len() == 0 {
92+
if log::max_level() <= log::Level::Info || dinst.is_empty() {
9393
return;
9494
}
9595
let inst_column_len = 48;
@@ -119,18 +119,12 @@ pub fn print_inst_diff(inst: &Instruction, dinst: Vec<Instruction>) {
119119
}
120120
} else {
121121
println!(
122-
"{:016X}:\t{}|\t{}",
122+
"{:016X}:\t{}{}|\t{}{}",
123123
inst.ip(),
124-
format!(
125-
"{}{}",
126-
inst_str.blue(),
127-
" ".repeat(inst_column_len - inst_str.len())
128-
),
129-
format!(
130-
"{}{}",
131-
inst_str.blue(),
132-
" ".repeat(inst_column_len - inst_str.len())
133-
),
124+
inst_str.blue(),
125+
" ".repeat(inst_column_len - inst_str.len()),
126+
inst_str.blue(),
127+
" ".repeat(inst_column_len - inst_str.len()),
134128
);
135129
}
136130
}
@@ -189,18 +183,18 @@ pub fn transpose_fixed_register_operand(inst: &mut Instruction) -> Result<(), De
189183
// }
190184
// }
191185

192-
pub fn get_immediate_indexes(inst: &Instruction) -> Option<Vec<u32>> {
193-
let mut indexes = Vec::new();
194-
for i in 0..inst.op_count() {
195-
if is_immediate_operand(inst.op_kind(i)) {
196-
indexes.push(i);
197-
}
198-
}
199-
if indexes.len() == 0 {
200-
return None;
201-
}
202-
Some(indexes)
203-
}
186+
// pub fn get_immediate_indexes(inst: &Instruction) -> Option<Vec<u32>> {
187+
// let mut indexes = Vec::new();
188+
// for i in 0..inst.op_count() {
189+
// if is_immediate_operand(inst.op_kind(i)) {
190+
// indexes.push(i);
191+
// }
192+
// }
193+
// if indexes.len() == 0 {
194+
// return None;
195+
// }
196+
// Some(indexes)
197+
// }
204198

205199
pub fn get_stack_pointer_register(bitness: u32) -> Result<Register, DeoptimizerError> {
206200
Ok(match bitness {
@@ -234,25 +228,25 @@ pub fn to_db_mnemonic(bytes: &[u8]) -> String {
234228
db_inst.trim_end_matches(", ").to_string()
235229
}
236230

237-
pub fn get_register_save_seq(
238-
bitness: u32,
239-
reg: Register,
240-
) -> Result<(Instruction, Instruction), DeoptimizerError> {
241-
let mut full_reg = reg.full_register();
242-
if bitness != 64 {
243-
full_reg = reg.full_register32();
244-
}
245-
let (c1, c2) = match bitness {
246-
16 => (Code::Push_r16, Code::Pop_r16),
247-
32 => (Code::Push_r32, Code::Pop_r32),
248-
64 => (Code::Push_r64, Code::Pop_r64),
249-
_ => return Err(DeoptimizerError::InvalidProcessorMode),
250-
};
251-
Ok((
252-
Instruction::with1(c1, full_reg)?,
253-
Instruction::with1(c2, full_reg)?,
254-
))
255-
}
231+
// pub fn get_register_save_seq(
232+
// bitness: u32,
233+
// reg: Register,
234+
// ) -> Result<(Instruction, Instruction), DeoptimizerError> {
235+
// let mut full_reg = reg.full_register();
236+
// if bitness != 64 {
237+
// full_reg = reg.full_register32();
238+
// }
239+
// let (c1, c2) = match bitness {
240+
// 16 => (Code::Push_r16, Code::Pop_r16),
241+
// 32 => (Code::Push_r32, Code::Pop_r32),
242+
// 64 => (Code::Push_r64, Code::Pop_r64),
243+
// _ => return Err(DeoptimizerError::InvalidProcessorMode),
244+
// };
245+
// Ok((
246+
// Instruction::with1(c1, full_reg)?,
247+
// Instruction::with1(c2, full_reg)?,
248+
// ))
249+
// }
256250

257251
pub fn get_random_register_value(reg: Register) -> u64 {
258252
let mut rng = rand::thread_rng();
@@ -288,8 +282,7 @@ pub fn set_branch_target(
288282
bt: u64,
289283
bitness: u32,
290284
) -> Result<Instruction, DeoptimizerError> {
291-
let mut my_inst = inst.clone();
292-
285+
let mut my_inst = *inst;
293286
if matches!(inst.op0_kind(), OpKind::FarBranch16 | OpKind::FarBranch32) {
294287
if bt < u16::MAX as u64 {
295288
my_inst.set_op0_kind(OpKind::FarBranch16);
@@ -407,15 +400,15 @@ pub fn get_random_gp_register(
407400
let index = shuffed_regs.iter().position(|x| {
408401
x.full_register() == ex.register().full_register() || x == &ex.register()
409402
});
410-
if index.is_some() {
411-
shuffed_regs.remove(index.unwrap());
403+
if let Some(idx) = index {
404+
shuffed_regs.remove(idx);
412405
}
413406
}
414407
}
415408

416409
for reg in shuffed_regs {
417410
let reg_str = format!("{:?}", reg);
418-
let is_extended = reg_str.contains("R") || reg_str.contains("IL") || reg_str.contains("PL");
411+
let is_extended = reg_str.contains('R') || reg_str.contains("IL") || reg_str.contains("PL");
419412
if is_extended == extended {
420413
return Ok(reg);
421414
}

0 commit comments

Comments
 (0)