use facet::Facet;
use hao::dotnet::il::{Instruction, MemberToken, Operand, instruction_offsets};
use hao::prelude::*;
use xur_runtime::registry::ModuleBuilder;
use xur_runtime::{OneOf, OptionalArg};
use super::WellKnownMethodArg;
use super::types::DotnetMethodBody;
#[derive(Facet, Clone)]
pub struct IlInstruction {
pub index: i64,
pub offset: i64,
pub opcode: String,
pub operand: String,
pub token: Option<i64>,
pub target: Option<i64>,
}
pub fn token(table: u32, rid: u32) -> i64 {
i64::from((table << 24) | rid)
}
pub fn member_token(token_: &MemberToken) -> i64 {
match token_ {
MemberToken::TypeRef(e) => token(0x01, e.rid()),
MemberToken::TypeDef(e) => token(0x02, e.rid()),
MemberToken::Field(e) => token(0x04, e.rid()),
MemberToken::Method(e) => token(0x06, e.rid()),
MemberToken::MemberRef(e) => token(0x0a, e.rid()),
MemberToken::TypeSpec(e) => token(0x1b, e.rid()),
MemberToken::MethodSpec(e) => token(0x2b, e.rid()),
}
}
fn member_name(token_: &MemberToken) -> String {
match token_ {
MemberToken::Method(m) => {
let g = m.get();
let ty = g
.declaring_type
.upgrade()
.map(|t| t.get().full_name())
.unwrap_or_default();
format!("{ty}::{}", g.name)
}
MemberToken::Field(f) => {
let g = f.get();
let ty = g
.declaring_type
.upgrade()
.map(|t| t.get().full_name())
.unwrap_or_default();
format!("{ty}::{}", g.name)
}
MemberToken::MemberRef(mr) => {
let g = mr.get();
let class = g
.parent
.as_type()
.map(|t| t.full_name())
.unwrap_or_default();
format!("{class}::{}", g.name)
}
MemberToken::TypeDef(t) => t.get().full_name(),
MemberToken::TypeRef(t) => t.get().full_name(),
MemberToken::TypeSpec(_) => "<typespec>".into(),
MemberToken::MethodSpec(s) => s.get().method.name().to_string(),
}
}
fn label(offsets: &[u32], index: usize) -> String {
format!("IL_{:04x}", offsets.get(index).copied().unwrap_or(0))
}
fn operand_text(op: &Operand, offsets: &[u32]) -> String {
match op {
Operand::None => String::new(),
Operand::Int32(v) => v.to_string(),
Operand::Int64(v) => v.to_string(),
Operand::Float32(v) => v.to_string(),
Operand::Float64(v) => v.to_string(),
Operand::Target(l) => label(offsets, l.0),
Operand::Switch(targets) => {
let labels: Vec<String> = targets.iter().map(|l| label(offsets, l.0)).collect();
format!("({})", labels.join(", "))
}
Operand::Local(idx) => format!("V_{idx}"),
Operand::Arg(idx) => format!("A_{idx}"),
Operand::String(s) => format!("\"{s}\""),
Operand::Sig(_) => "<sig>".into(),
Operand::Token(t) => member_name(t),
}
}
fn info(
body: &hao::dotnet::il::MethodBody,
offsets: &[u32],
index: usize,
) -> Option<IlInstruction> {
let instr = body.instructions.get(index)?;
Some(IlInstruction {
index: index as i64,
offset: i64::from(offsets[index]),
opcode: instr.opcode.to_string(),
operand: operand_text(&instr.operand, offsets),
token: match &instr.operand {
Operand::Token(t) => Some(member_token(t)),
_ => None,
},
target: match &instr.operand {
Operand::Target(l) => offsets.get(l.0).map(|&o| i64::from(o)),
_ => None,
},
})
}
fn take_instructions(
body: &mut hao::dotnet::il::MethodBody,
other: &hao::dotnet::il::MethodBody,
) -> Vec<Instruction> {
let base = body.locals.len() as u16;
body.locals.extend(other.locals.iter().cloned());
other
.instructions
.iter()
.cloned()
.map(|mut i| {
if let Operand::Local(n) = &mut i.operand {
*n += base;
}
i
})
.collect()
}
fn calls(instr: &Instruction, m: WellKnownMethod) -> bool {
let (ns, ty) = m.declaring().full_name();
let full = if ns.is_empty() {
ty.to_string()
} else {
format!("{ns}.{ty}")
};
let (name, sig) = match &instr.operand {
Operand::Token(MemberToken::MemberRef(r)) => {
let g = r.get();
let class = g
.parent
.as_type()
.map(|t| t.full_name())
.unwrap_or_default();
if class != full {
return false;
}
let params = match &g.signature {
hao::dotnet::signature::MemberRefSig::Method(s) => Some(s.params.len()),
_ => None,
};
(g.name.to_string(), params)
}
Operand::Token(MemberToken::Method(md)) => {
let g = md.get();
let class = g
.declaring_type
.upgrade()
.map(|t| t.get().full_name())
.unwrap_or_default();
if class != full {
return false;
}
(g.name.to_string(), Some(g.signature.params.len()))
}
_ => return false,
};
name == m.method_name() && sig.is_none_or(|n| n == m.param_count())
}
pub(super) fn register(dotnet: &mut ModuleBuilder<'_>) {
dotnet.ty::<IlInstruction>("Instruction");
dotnet
.ty::<DotnetMethodBody>("MethodBody")
.method("size", |b: &DotnetMethodBody| b.0.instructions.len() as i64)
.method("instructions", |b: &DotnetMethodBody| -> Vec<String> {
let offsets = instruction_offsets(&b.0.instructions);
(0..b.0.instructions.len())
.filter_map(|i| info(&b.0, &offsets, i))
.map(|i| {
let label = format!("IL_{:04x}", i.offset);
if i.operand.is_empty() {
format!("{label}: {}", i.opcode)
} else {
format!("{label}: {} {}", i.opcode, i.operand)
}
})
.collect()
})
.named_method(
"at",
&["index"],
|b: &DotnetMethodBody, index: i64| -> Option<IlInstruction> {
let offsets = instruction_offsets(&b.0.instructions);
usize::try_from(index)
.ok()
.and_then(|i| info(&b.0, &offsets, i))
},
)
.method("list", |b: &DotnetMethodBody| -> Vec<IlInstruction> {
let offsets = instruction_offsets(&b.0.instructions);
(0..b.0.instructions.len())
.filter_map(|i| info(&b.0, &offsets, i))
.collect()
})
.method("offsets", |b: &DotnetMethodBody| -> Vec<i64> {
instruction_offsets(&b.0.instructions)
.into_iter()
.map(i64::from)
.collect()
})
.named_method(
"find_calls",
&["method"],
|b: &DotnetMethodBody, m: OneOf<WellKnownMethodArg>| -> Vec<i64> {
let m: WellKnownMethod = m.0.into();
b.0.instructions
.iter()
.enumerate()
.filter(|(_, i)| calls(i, m))
.map(|(i, _)| i as i64)
.collect()
},
)
.named_method_mut(
"insert",
&["index", "body"],
|b: &mut DotnetMethodBody, index: i64, other: DotnetMethodBody| -> Result<(), String> {
let index = usize::try_from(index)
.ok()
.filter(|&i| i <= b.0.instructions.len())
.ok_or_else(|| format!("no instruction {index} to insert before"))?;
let added = take_instructions(&mut b.0, &other.0);
b.0.insert(index, added);
Ok(())
},
)
.named_method_mut(
"remove",
&["index", "count"],
|b: &mut DotnetMethodBody, index: i64, count: OptionalArg<i64>| -> Result<(), String> {
let count = count.0.unwrap_or(1).max(0) as usize;
let index = usize::try_from(index)
.ok()
.filter(|&i| i + count <= b.0.instructions.len())
.ok_or_else(|| format!("no {count} instruction(s) at {index}"))?;
for _ in 0..count {
b.0.remove(index);
}
Ok(())
},
)
.named_method_mut(
"replace",
&["index", "count", "body"],
|b: &mut DotnetMethodBody,
index: i64,
count: i64,
other: DotnetMethodBody|
-> Result<(), String> {
let count = count.max(0) as usize;
let at = usize::try_from(index)
.ok()
.filter(|&i| i + count <= b.0.instructions.len())
.ok_or_else(|| format!("no {count} instruction(s) at {index}"))?;
let added = take_instructions(&mut b.0, &other.0);
b.0.insert(at, added.clone());
for _ in 0..count {
b.0.remove(at + added.len());
}
Ok(())
},
);
}
pub(super) fn well_known_method_name(m: OneOf<WellKnownMethodArg>) -> String {
let m: WellKnownMethod = m.0.into();
let (ns, ty) = m.declaring().full_name();
if ns.is_empty() {
format!("{ty}::{}", m.method_name())
} else {
format!("{ns}.{ty}::{}", m.method_name())
}
}