use crate::code_asm::op_state::CodeAsmOpState;
use crate::code_asm::{CodeAssembler, CodeAssemblerOptions, CodeAssemblerResult, CodeLabel, PrefixFlags};
use crate::IcedError;
use crate::{BlockEncoder, BlockEncoderOptions, Code, Instruction, InstructionBlock, MemoryOperand, Register};
use alloc::vec::Vec;
impl CodeAssembler {
const MAX_DB_COUNT: usize = 16;
const MAX_DW_COUNT: usize = CodeAssembler::MAX_DB_COUNT / 2;
const MAX_DD_COUNT: usize = CodeAssembler::MAX_DB_COUNT / 4;
const MAX_DQ_COUNT: usize = CodeAssembler::MAX_DB_COUNT / 8;
#[inline]
pub fn new(bitness: u32) -> Result<CodeAssembler, IcedError> {
match bitness {
16 | 32 | 64 => {}
_ => return Err(IcedError::new("Invalid bitness")),
}
Ok(Self {
bitness,
instructions: Vec::new(),
current_label_id: 0,
current_label: CodeLabel::default(),
current_anon_label: CodeLabel::default(),
next_anon_label: CodeLabel::default(),
defined_anon_label: false,
prefix_flags: PrefixFlags::NONE,
options: CodeAssemblerOptions::PREFER_VEX | CodeAssemblerOptions::PREFER_SHORT_BRANCH,
})
}
#[must_use]
#[inline]
pub fn xacquire(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPNE;
self
}
#[must_use]
#[inline]
pub fn xrelease(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPE;
self
}
#[must_use]
#[inline]
pub fn lock(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::LOCK;
self
}
#[must_use]
#[inline]
pub fn rep(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPE;
self
}
#[must_use]
#[inline]
pub fn repe(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPE;
self
}
#[must_use]
#[inline]
pub fn repz(&mut self) -> &mut Self {
self.repe()
}
#[must_use]
#[inline]
pub fn repne(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPNE;
self
}
#[must_use]
#[inline]
pub fn repnz(&mut self) -> &mut Self {
self.repne()
}
#[must_use]
#[inline]
pub fn bnd(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::REPNE;
self
}
#[must_use]
#[inline]
pub fn notrack(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::NOTRACK;
self
}
#[must_use]
#[inline]
pub fn vex(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::PREFER_VEX;
self
}
#[must_use]
#[inline]
pub fn evex(&mut self) -> &mut Self {
self.prefix_flags |= PrefixFlags::PREFER_EVEX;
self
}
#[must_use]
#[inline]
pub fn instructions(&self) -> &[Instruction] {
&self.instructions
}
#[must_use]
#[inline]
pub fn take_instructions(&mut self) -> Vec<Instruction> {
let instrs = core::mem::take(&mut self.instructions);
self.reset();
instrs
}
#[inline]
pub fn reset(&mut self) {
self.instructions.clear();
self.current_label_id = 0;
self.current_label = CodeLabel::default();
self.current_anon_label = CodeLabel::default();
self.next_anon_label = CodeLabel::default();
self.defined_anon_label = false;
self.prefix_flags = PrefixFlags::NONE;
}
#[must_use]
#[inline]
pub fn create_label(&mut self) -> CodeLabel {
self.current_label_id += 1;
CodeLabel::new(self.current_label_id)
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn set_label(&mut self, label: &mut CodeLabel) -> Result<(), IcedError> {
if label.is_empty() {
return Err(IcedError::new("Invalid label. Must be created by current_label()"));
}
if label.has_instruction_index() {
return Err(IcedError::new("Labels can't be re-used and can only be set once."));
}
if !self.current_label.is_empty() {
return Err(IcedError::new("Only one label per instruction is allowed"));
}
label.instruction_index = self.instructions.len();
self.current_label = *label;
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn anonymous_label(&mut self) -> Result<(), IcedError> {
if self.defined_anon_label {
return Err(IcedError::new("At most one anonymous label per instruction is allowed"));
}
self.current_anon_label = if self.next_anon_label.is_empty() { self.create_label() } else { self.next_anon_label };
self.next_anon_label = CodeLabel::default();
self.defined_anon_label = true;
Ok(())
}
#[inline]
pub fn bwd(&mut self) -> Result<CodeLabel, IcedError> {
if self.current_anon_label.is_empty() {
Err(IcedError::new("No anonymous label has been created yet"))
} else {
Ok(self.current_anon_label)
}
}
#[inline]
pub fn fwd(&mut self) -> Result<CodeLabel, IcedError> {
if self.next_anon_label.is_empty() {
self.next_anon_label = self.create_label();
}
Ok(self.next_anon_label)
}
#[inline]
fn decl_data_verify_no_prefixes(&self) -> Result<(), IcedError> {
if self.prefix_flags != 0 {
Err(IcedError::new("db/dw/dd/dq: No prefixes are allowed"))
} else {
Ok(())
}
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn db(&mut self, data: &[u8]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
for bytes in data.chunks(CodeAssembler::MAX_DB_COUNT) {
self.add_instr(Instruction::with_declare_byte(bytes)?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn db_i(&mut self, data: &[i8]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DB_COUNT];
for bytes in data.chunks(CodeAssembler::MAX_DB_COUNT) {
for (t, b) in tmp.iter_mut().zip(bytes.iter()) {
*t = *b as u8;
}
self.add_instr(Instruction::with_declare_byte(&tmp[0..bytes.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dw(&mut self, data: &[u16]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
for words in data.chunks(CodeAssembler::MAX_DW_COUNT) {
self.add_instr(Instruction::with_declare_word(words)?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dw_i(&mut self, data: &[i16]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DW_COUNT];
for words in data.chunks(CodeAssembler::MAX_DW_COUNT) {
for (t, w) in tmp.iter_mut().zip(words.iter()) {
*t = *w as u16;
}
self.add_instr(Instruction::with_declare_word(&tmp[0..words.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dd(&mut self, data: &[u32]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
for dwords in data.chunks(CodeAssembler::MAX_DD_COUNT) {
self.add_instr(Instruction::with_declare_dword(dwords)?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dd_i(&mut self, data: &[i32]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DD_COUNT];
for dwords in data.chunks(CodeAssembler::MAX_DD_COUNT) {
for (t, d) in tmp.iter_mut().zip(dwords.iter()) {
*t = *d as u32;
}
self.add_instr(Instruction::with_declare_dword(&tmp[0..dwords.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dd_f32(&mut self, data: &[f32]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DD_COUNT];
for dwords in data.chunks(CodeAssembler::MAX_DD_COUNT) {
for (t, d) in tmp.iter_mut().zip(dwords.iter()) {
*t = f32::to_bits(*d);
}
self.add_instr(Instruction::with_declare_dword(&tmp[0..dwords.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dq(&mut self, data: &[u64]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
for qwords in data.chunks(CodeAssembler::MAX_DQ_COUNT) {
self.add_instr(Instruction::with_declare_qword(qwords)?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dq_i(&mut self, data: &[i64]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DQ_COUNT];
for qwords in data.chunks(CodeAssembler::MAX_DQ_COUNT) {
for (t, q) in tmp.iter_mut().zip(qwords.iter()) {
*t = *q as u64;
}
self.add_instr(Instruction::with_declare_qword(&tmp[0..qwords.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn dq_f64(&mut self, data: &[f64]) -> Result<(), IcedError> {
self.decl_data_verify_no_prefixes()?;
let mut tmp = [0; CodeAssembler::MAX_DQ_COUNT];
for qwords in data.chunks(CodeAssembler::MAX_DQ_COUNT) {
for (t, q) in tmp.iter_mut().zip(qwords.iter()) {
*t = f64::to_bits(*q);
}
self.add_instr(Instruction::with_declare_qword(&tmp[0..qwords.len()])?)?;
}
Ok(())
}
#[allow(clippy::missing_inline_in_public_items)]
pub fn nops_with_size(&mut self, size: usize) -> Result<(), IcedError> {
if self.prefix_flags != 0 {
return Err(IcedError::new("No prefixes are allowed"));
}
const MAX_NOP_LEN: usize = 9;
if size >= MAX_NOP_LEN {
let bytes = self.get_nop_bytes(MAX_NOP_LEN);
for _ in 0..size / MAX_NOP_LEN {
self.db(bytes)?;
}
}
match size % MAX_NOP_LEN {
0 => {}
remaining => self.db(self.get_nop_bytes(remaining))?,
}
Ok(())
}
fn get_nop_bytes(&self, size: usize) -> &'static [u8] {
match size {
1 => &[0x90], 2 => &[0x66, 0x90], 3 => &[0x0F, 0x1F, 0x00], 4 => &[0x0F, 0x1F, 0x40, 0x00], 5 => {
if self.bitness() != 16 {
&[0x0F, 0x1F, 0x44, 0x00, 0x00] } else {
&[0x0F, 0x1F, 0x80, 0x00, 0x00] }
}
6 => {
if self.bitness() != 16 {
&[0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00] } else {
&[0x66, 0x0F, 0x1F, 0x80, 0x00, 0x00] }
}
7 => {
if self.bitness() != 16 {
&[0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00] } else {
&[0x67, 0x66, 0x0F, 0x1F, 0x44, 0x00, 0x00] }
}
8 => {
if self.bitness() != 16 {
&[0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00] } else {
&[0x67, 0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00] }
}
9 => {
if self.bitness() != 16 {
&[0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00] } else {
&[0x67, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00] }
}
_ => unreachable!(),
}
}
#[inline]
pub fn add_instruction(&mut self, instruction: Instruction) -> Result<(), IcedError> {
self.add_instr(instruction)
}
pub(crate) fn add_instr_with_state(&mut self, mut instruction: Instruction, state: CodeAsmOpState) -> Result<(), IcedError> {
if !state.is_default() {
if state.is_broadcast() {
instruction.set_is_broadcast(true);
}
if state.zeroing_masking() {
instruction.set_zeroing_masking(true);
}
if state.suppress_all_exceptions() {
instruction.set_suppress_all_exceptions(true);
}
instruction.set_op_mask(state.op_mask());
instruction.set_rounding_control(state.rounding_control());
}
self.add_instr(instruction)
}
pub(crate) fn add_instr(&mut self, mut instruction: Instruction) -> Result<(), IcedError> {
if !self.current_label.is_empty() && self.defined_anon_label {
return Err(IcedError::new("You can't create both an anonymous label and a normal label"));
}
if !self.current_label.is_empty() {
instruction.set_ip(self.current_label.id());
} else if self.defined_anon_label {
instruction.set_ip(self.current_anon_label.id());
}
if self.prefix_flags != 0 {
if (self.prefix_flags & PrefixFlags::LOCK) != 0 {
instruction.set_has_lock_prefix(true);
}
if (self.prefix_flags & PrefixFlags::REPE) != 0 {
instruction.set_has_repe_prefix(true);
} else if (self.prefix_flags & PrefixFlags::REPNE) != 0 {
instruction.set_has_repne_prefix(true);
}
if (self.prefix_flags & PrefixFlags::NOTRACK) != 0 {
instruction.set_segment_prefix(Register::DS);
}
}
self.instructions.push(instruction);
self.current_label = CodeLabel::default();
self.defined_anon_label = false;
self.prefix_flags = PrefixFlags::NONE;
Ok(())
}
#[inline]
pub fn assemble(&mut self, ip: u64) -> Result<Vec<u8>, IcedError> {
Ok(self.assemble_options(ip, BlockEncoderOptions::NONE)?.inner.code_buffer)
}
#[inline]
pub fn assemble_options(&mut self, ip: u64, options: u32) -> Result<CodeAssemblerResult, IcedError> {
if self.prefix_flags != 0 {
return Err(IcedError::new("Unused prefixes. Did you forget to add an instruction?"));
}
if !self.current_label.is_empty() {
return Err(IcedError::new("Unused label. Did you forget to add an instruction?"));
}
if self.defined_anon_label {
return Err(IcedError::new("Unused anonymous label. Did you forget to add an instruction?"));
}
if !self.next_anon_label.is_empty() {
return Err(IcedError::new("Unused anonymous fwd() label. Did you forget to call anonymous_label()?"));
}
let block = InstructionBlock::new(self.instructions(), ip);
let result = BlockEncoder::encode(self.bitness(), block, options)?;
Ok(CodeAssemblerResult { inner: result })
}
#[must_use]
#[inline]
pub fn bitness(&self) -> u32 {
self.bitness
}
#[must_use]
#[inline]
pub fn prefer_vex(&self) -> bool {
(self.options & CodeAssemblerOptions::PREFER_VEX) != 0
}
#[inline]
pub fn set_prefer_vex(&mut self, new_value: bool) {
if new_value {
self.options |= CodeAssemblerOptions::PREFER_VEX;
} else {
self.options &= !CodeAssemblerOptions::PREFER_VEX;
}
}
#[must_use]
#[inline]
pub fn prefer_short_branch(&self) -> bool {
(self.options & CodeAssemblerOptions::PREFER_SHORT_BRANCH) != 0
}
#[inline]
pub fn set_prefer_short_branch(&mut self, new_value: bool) {
if new_value {
self.options |= CodeAssemblerOptions::PREFER_SHORT_BRANCH;
} else {
self.options &= !CodeAssemblerOptions::PREFER_SHORT_BRANCH;
}
}
#[inline]
pub(crate) fn instruction_prefer_vex(&self) -> bool {
if (self.prefix_flags & (PrefixFlags::PREFER_VEX | PrefixFlags::PREFER_EVEX)) != 0 {
(self.prefix_flags & PrefixFlags::PREFER_VEX) != 0
} else {
(self.options & CodeAssemblerOptions::PREFER_VEX) != 0
}
}
#[inline]
pub fn call_far(&mut self, selector: u16, offset: u32) -> Result<(), IcedError> {
let code = if self.bitness() >= 32 { Code::Call_ptr1632 } else { Code::Call_ptr1616 };
self.add_instr(Instruction::with_far_branch(code, selector, offset)?)
}
#[inline]
pub fn jmp_far(&mut self, selector: u16, offset: u32) -> Result<(), IcedError> {
let code = if self.bitness() >= 32 { Code::Jmp_ptr1632 } else { Code::Jmp_ptr1616 };
self.add_instr(Instruction::with_far_branch(code, selector, offset)?)
}
#[inline]
pub fn xlatb(&mut self) -> Result<(), IcedError> {
let base = match self.bitness() {
64 => Register::RBX,
32 => Register::EBX,
16 => Register::BX,
_ => unreachable!(),
};
self.add_instr(Instruction::with1(Code::Xlat_m8, MemoryOperand::with_base_index(base, Register::AL))?)
}
}