use core::fmt::{self, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use crate::Decoded;
use crate::tokens::{OperandIndex, TokenKind, TokenSink};
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Ok = 0,
Unallocated = 1,
Undefined = 2,
Nop = 3,
Failed = 4,
Unpredictable = 5,
ReservedHint = 6,
}
impl From<crate::DecodeError> for Status {
fn from(error: crate::DecodeError) -> Self {
match error {
crate::DecodeError::Unallocated => Status::Unallocated,
crate::DecodeError::UNDEF => Status::Undefined,
crate::DecodeError::NOP => Status::Nop,
crate::DecodeError::Unpredictable => Status::Unpredictable,
crate::DecodeError::ReservedHint => Status::ReservedHint,
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Str {
pub data: *const u8,
pub length: usize,
}
unsafe impl Send for Str {}
unsafe impl Sync for Str {}
impl Str {
pub const fn of(s: &'static str) -> Self {
Str {
data: s.as_ptr(),
length: s.len(),
}
}
pub const EMPTY: Str = Str::of("");
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Token {
pub kind: u32,
pub offset: u32,
pub length: u32,
pub operand: u8,
pub value: u64,
}
impl Token {
pub const NO_OPERAND: u8 = 0xFF;
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextSize {
pub tokens: usize,
pub length: usize,
}
impl TextSize {
pub const NONE: TextSize = TextSize {
tokens: 0,
length: 0,
};
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FlagEffect {
pub writes: u8,
pub reads: u8,
pub float_compare: bool,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Branch {
pub kind: u8,
pub conditional: bool,
pub has_target: bool,
pub target: u64,
}
impl Branch {
pub const NONE: Branch = Branch {
kind: crate::branch::BranchKind::None as u8,
conditional: false,
has_target: false,
target: 0,
};
}
impl From<crate::branch::Branch> for Branch {
fn from(branch: crate::branch::Branch) -> Self {
Branch {
kind: branch.kind as u8,
conditional: branch.conditional,
has_target: branch.target.is_some(),
target: branch.target.unwrap_or(0),
}
}
}
impl From<crate::flags::FlagEffect> for FlagEffect {
fn from(effect: crate::flags::FlagEffect) -> Self {
FlagEffect {
writes: effect.writes.0,
reads: effect.reads.0,
float_compare: effect.float_compare,
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Symbol {
pub bits: u16,
pub name: Str,
}
impl From<crate::view::Symbol> for Symbol {
fn from(s: crate::view::Symbol) -> Self {
Symbol {
bits: s.bits,
name: Str::of(s.name),
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Label {
pub offset: i64,
pub pc_ahead: u8,
pub pc_align: u32,
}
impl Label {
pub fn of(offset: i64, pc: crate::address::PcRead) -> Self {
Label {
offset,
pc_ahead: pc.ahead,
pc_align: pc.align,
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct CFpImm {
pub value: f64,
pub bits: u64,
pub width: u8,
}
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Writeback {
None = 0,
Pre = 1,
Post = 2,
}
impl From<crate::view::Writeback> for Writeback {
fn from(writeback: crate::view::Writeback) -> Self {
match writeback {
crate::view::Writeback::None => Writeback::None,
crate::view::Writeback::Pre => Writeback::Pre,
crate::view::Writeback::Post => Writeback::Post,
}
}
}
pub fn guarded<T>(fallback: T, f: impl FnOnce() -> T) -> T {
catch_unwind(AssertUnwindSafe(f)).unwrap_or(fallback)
}
pub unsafe trait Storage {
type Instruction: crate::Decoded + Copy;
}
pub unsafe fn held<'a, C: Storage>(inst: *const C) -> Option<&'a C::Instruction> {
if inst.is_null() {
None
} else {
Some(unsafe { &*inst.cast::<C::Instruction>() })
}
}
pub unsafe fn with_held<C: Storage, T>(
inst: *const C,
none: T,
ask: impl FnOnce(&C::Instruction) -> T,
) -> T {
match unsafe { held(inst) } {
Some(inst) => guarded(none, || ask(inst)),
None => none,
}
}
pub unsafe fn fill<T>(
out: *mut T,
capacity: usize,
items: impl ExactSizeIterator<Item = T>,
) -> usize {
let count = items.len();
for (slot, item) in unsafe { buffer(out, capacity) }.iter_mut().zip(items) {
*slot = item;
}
count
}
pub unsafe fn write_tokens<C: Storage>(
inst: *const C,
address: u64,
text: *mut u8,
text_capacity: usize,
tokens: *mut Token,
token_capacity: usize,
) -> TextSize {
let text = unsafe { buffer(text, text_capacity) };
let tokens = unsafe { buffer(tokens, token_capacity) };
let write = |inst: &C::Instruction| {
let mut spans = Spans::new(text, tokens);
match inst.write_tokens_at(address, &mut spans) {
Ok(()) => spans.finish(),
Err(_) => TextSize::NONE,
}
};
unsafe { with_held(inst, TextSize::NONE, write) }
}
pub unsafe fn deliver<C: Storage>(
decoded: impl FnOnce() -> Result<C::Instruction, crate::DecodeError>,
out: *mut C,
) -> Status {
guarded(Status::Failed, || match decoded() {
Ok(inst) => {
unsafe { out.cast::<C::Instruction>().write(inst) };
Status::Ok
}
Err(error) => Status::from(error),
})
}
pub unsafe fn buffer<'a, T>(ptr: *mut T, capacity: usize) -> &'a mut [T] {
if ptr.is_null() || capacity == 0 {
&mut []
} else {
unsafe { std::slice::from_raw_parts_mut(ptr, capacity) }
}
}
pub struct Spans<'a> {
text: &'a mut [u8],
length: usize,
tokens: &'a mut [Token],
count: usize,
}
impl<'a> Spans<'a> {
pub fn new(text: &'a mut [u8], tokens: &'a mut [Token]) -> Self {
Spans {
text,
length: 0,
tokens,
count: 0,
}
}
fn record(&mut self, kind: TokenKind, operand: OperandIndex, start: usize) {
if let Some(slot) = self.tokens.get_mut(self.count) {
let (kind, value) = match kind {
TokenKind::Mnemonic => (0, 0),
TokenKind::Text => (1, 0),
TokenKind::Separator => (2, 0),
TokenKind::Bracket => (3, 0),
TokenKind::Register => (4, 0),
TokenKind::Symbol => (5, 0),
TokenKind::Immediate(value) => (6, value as u64),
TokenKind::Integer(value) => (7, value),
TokenKind::Address(address) => (8, address),
TokenKind::Float => (9, 0),
};
*slot = Token {
kind,
operand: operand.unwrap_or(Token::NO_OPERAND),
offset: start as u32,
length: (self.length - start) as u32,
value,
};
}
self.count += 1;
}
pub fn finish(self) -> TextSize {
if let Some(last) = self.text.len().checked_sub(1) {
self.text[self.length.min(last)] = 0;
}
TextSize {
tokens: self.count,
length: self.length,
}
}
}
impl Write for Spans<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let room = self.text.len().saturating_sub(1);
if self.length < room {
let n = s.len().min(room - self.length);
self.text[self.length..self.length + n].copy_from_slice(&s.as_bytes()[..n]);
}
self.length += s.len();
Ok(())
}
}
impl TokenSink for Spans<'_> {
fn text(&mut self, kind: TokenKind, operand: OperandIndex, text: &str) -> fmt::Result {
let start = self.length;
self.write_str(text)?;
self.record(kind, operand, start);
Ok(())
}
fn value(
&mut self,
kind: TokenKind,
operand: OperandIndex,
value: &dyn fmt::Display,
) -> fmt::Result {
let start = self.length;
write!(self, "{value}")?;
self.record(kind, operand, start);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panic_is_reported_not_propagated() {
assert_eq!(guarded(7, || panic!("inside")), 7);
assert_eq!(guarded(7, || 1), 1);
}
#[test]
fn a_text_buffer_is_cut_at_its_capacity_and_terminated() {
let mut text = [0xAAu8; 5];
let mut spans = Spans::new(&mut text, &mut []);
spans.text(TokenKind::Mnemonic, None, "ldr").unwrap();
spans.text(TokenKind::Text, None, "\t").unwrap();
spans.value(TokenKind::Register, Some(0), &"x0").unwrap();
let size = spans.finish();
assert_eq!((size.tokens, size.length), (3, 6));
assert_eq!(&text, b"ldr\t\0");
}
}