1use core::fmt::{self, Write};
6use std::panic::{AssertUnwindSafe, catch_unwind};
7
8use crate::Decoded;
9use crate::tokens::{OperandIndex, TokenKind, TokenSink};
10
11#[repr(u32)]
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Status {
18 Ok = 0,
20 Unallocated = 1,
22 Undefined = 2,
24 Nop = 3,
26 Failed = 4,
28 Unpredictable = 5,
30 ReservedHint = 6,
33 Truncated = 7,
35}
36
37impl From<crate::DecodeError> for Status {
38 fn from(error: crate::DecodeError) -> Self {
39 match error {
40 crate::DecodeError::Unallocated => Status::Unallocated,
41 crate::DecodeError::UNDEF => Status::Undefined,
42 crate::DecodeError::NOP => Status::Nop,
43 crate::DecodeError::Unpredictable => Status::Unpredictable,
44 crate::DecodeError::ReservedHint => Status::ReservedHint,
45 crate::DecodeError::Truncated => Status::Truncated,
46 }
47 }
48}
49
50#[repr(C)]
52#[derive(Clone, Copy, Debug)]
53pub struct Str {
54 pub data: *const u8,
56 pub length: usize,
58}
59
60unsafe impl Send for Str {}
63unsafe impl Sync for Str {}
64
65impl Str {
66 pub const fn of(s: &'static str) -> Self {
68 Str {
69 data: s.as_ptr(),
70 length: s.len(),
71 }
72 }
73
74 pub const EMPTY: Str = Str::of("");
76}
77
78#[repr(C)]
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct Token {
83 pub kind: u32,
85 pub offset: u32,
87 pub length: u32,
89 pub operand: u8,
95 pub value: u64,
98}
99
100impl Token {
101 pub const NO_OPERAND: u8 = 0xFF;
105}
106
107#[repr(C)]
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub struct TextSize {
111 pub tokens: usize,
113 pub length: usize,
115}
116
117impl TextSize {
118 pub const NONE: TextSize = TextSize {
120 tokens: 0,
121 length: 0,
122 };
123}
124
125#[repr(C)]
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub struct FlagEffect {
129 pub writes: u8,
131 pub reads: u8,
133 pub float_compare: bool,
135}
136
137#[repr(C)]
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct Branch {
143 pub kind: u8,
145 pub conditional: bool,
147 pub has_target: bool,
149 pub target: u64,
151}
152
153impl Branch {
154 pub const NONE: Branch = Branch {
157 kind: crate::branch::BranchKind::None as u8,
158 conditional: false,
159 has_target: false,
160 target: 0,
161 };
162}
163
164impl From<crate::branch::Branch> for Branch {
165 fn from(branch: crate::branch::Branch) -> Self {
166 Branch {
167 kind: branch.kind as u8,
168 conditional: branch.conditional,
169 has_target: branch.target.is_some(),
170 target: branch.target.unwrap_or(0),
171 }
172 }
173}
174
175impl From<crate::flags::FlagEffect> for FlagEffect {
176 fn from(effect: crate::flags::FlagEffect) -> Self {
177 FlagEffect {
178 writes: effect.writes.0,
179 reads: effect.reads.0,
180 float_compare: effect.float_compare,
181 }
182 }
183}
184
185#[repr(C)]
187#[derive(Clone, Copy, Debug)]
188pub struct Symbol {
189 pub bits: u16,
191 pub name: Str,
193}
194
195impl From<crate::view::Symbol> for Symbol {
196 fn from(s: crate::view::Symbol) -> Self {
197 Symbol {
198 bits: s.bits,
199 name: Str::of(s.name),
200 }
201 }
202}
203
204#[repr(C)]
206#[derive(Clone, Copy, Debug)]
207pub struct Label {
208 pub offset: i64,
211 pub pc_ahead: u8,
213 pub pc_align: u32,
216}
217
218impl Label {
219 pub fn of(offset: i64, pc: crate::address::PcRead) -> Self {
221 Label {
222 offset,
223 pc_ahead: pc.ahead,
224 pc_align: pc.align,
225 }
226 }
227}
228
229#[repr(C)]
231#[derive(Clone, Copy, Debug)]
232pub struct CFpImm {
233 pub value: f64,
235 pub bits: u64,
237 pub width: u8,
239}
240
241#[repr(u32)]
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum Writeback {
245 None = 0,
247 Pre = 1,
249 Post = 2,
251}
252
253impl From<crate::view::Writeback> for Writeback {
254 fn from(writeback: crate::view::Writeback) -> Self {
255 match writeback {
256 crate::view::Writeback::None => Writeback::None,
257 crate::view::Writeback::Pre => Writeback::Pre,
258 crate::view::Writeback::Post => Writeback::Post,
259 }
260 }
261}
262
263pub fn guarded<T>(fallback: T, f: impl FnOnce() -> T) -> T {
265 catch_unwind(AssertUnwindSafe(f)).unwrap_or(fallback)
266}
267
268pub unsafe trait Storage {
283 type Instruction: crate::Decoded + Copy;
285}
286
287pub unsafe fn held<'a, C: Storage>(inst: *const C) -> Option<&'a C::Instruction> {
293 if inst.is_null() {
294 None
295 } else {
296 Some(unsafe { &*inst.cast::<C::Instruction>() })
297 }
298}
299
300pub unsafe fn with_held<C: Storage, T>(
307 inst: *const C,
308 none: T,
309 ask: impl FnOnce(&C::Instruction) -> T,
310) -> T {
311 match unsafe { held(inst) } {
312 Some(inst) => guarded(none, || ask(inst)),
313 None => none,
314 }
315}
316
317pub unsafe fn fill<T>(
325 out: *mut T,
326 capacity: usize,
327 items: impl ExactSizeIterator<Item = T>,
328) -> usize {
329 let count = items.len();
330 for (slot, item) in unsafe { buffer(out, capacity) }.iter_mut().zip(items) {
331 *slot = item;
332 }
333 count
334}
335
336pub unsafe fn write_tokens<C: Storage>(
344 inst: *const C,
345 address: u64,
346 text: *mut u8,
347 text_capacity: usize,
348 tokens: *mut Token,
349 token_capacity: usize,
350) -> TextSize {
351 let text = unsafe { buffer(text, text_capacity) };
352 let tokens = unsafe { buffer(tokens, token_capacity) };
353 let write = |inst: &C::Instruction| {
354 let mut spans = Spans::new(text, tokens);
355 match inst.write_tokens_at(address, &mut spans) {
356 Ok(()) => spans.finish(),
357 Err(_) => TextSize::NONE,
358 }
359 };
360 unsafe { with_held(inst, TextSize::NONE, write) }
361}
362
363pub unsafe fn deliver<C: Storage>(
373 decoded: impl FnOnce() -> Result<C::Instruction, crate::DecodeError>,
374 out: *mut C,
375) -> Status {
376 guarded(Status::Failed, || match decoded() {
377 Ok(inst) => {
378 unsafe { out.cast::<C::Instruction>().write(inst) };
382 Status::Ok
383 }
384 Err(error) => Status::from(error),
385 })
386}
387
388pub unsafe fn buffer<'a, T>(ptr: *mut T, capacity: usize) -> &'a mut [T] {
395 if ptr.is_null() || capacity == 0 {
396 &mut []
397 } else {
398 unsafe { std::slice::from_raw_parts_mut(ptr, capacity) }
399 }
400}
401
402pub unsafe fn bytes<'a>(ptr: *const u8, len: usize) -> Option<&'a [u8]> {
409 match (ptr.is_null(), len) {
410 (_, 0) => Some(&[]),
411 (true, _) => None,
412 (false, _) => Some(unsafe { std::slice::from_raw_parts(ptr, len) }),
413 }
414}
415
416pub struct Spans<'a> {
420 text: &'a mut [u8],
421 length: usize,
422 tokens: &'a mut [Token],
423 count: usize,
424}
425
426impl<'a> Spans<'a> {
427 pub fn new(text: &'a mut [u8], tokens: &'a mut [Token]) -> Self {
430 Spans {
431 text,
432 length: 0,
433 tokens,
434 count: 0,
435 }
436 }
437
438 fn record(&mut self, kind: TokenKind, operand: OperandIndex, start: usize) {
439 if let Some(slot) = self.tokens.get_mut(self.count) {
440 let (kind, value) = match kind {
441 TokenKind::Mnemonic => (0, 0),
442 TokenKind::Text => (1, 0),
443 TokenKind::Separator => (2, 0),
444 TokenKind::Bracket => (3, 0),
445 TokenKind::Register => (4, 0),
446 TokenKind::Symbol => (5, 0),
447 TokenKind::Immediate(value) => (6, value as u64),
448 TokenKind::Integer(value) => (7, value),
449 TokenKind::Address(address) => (8, address),
450 TokenKind::Float => (9, 0),
451 };
452 *slot = Token {
453 kind,
454 operand: operand.unwrap_or(Token::NO_OPERAND),
455 offset: start as u32,
456 length: (self.length - start) as u32,
457 value,
458 };
459 }
460 self.count += 1;
461 }
462
463 pub fn finish(self) -> TextSize {
465 if let Some(last) = self.text.len().checked_sub(1) {
466 self.text[self.length.min(last)] = 0;
467 }
468 TextSize {
469 tokens: self.count,
470 length: self.length,
471 }
472 }
473}
474
475impl Write for Spans<'_> {
476 fn write_str(&mut self, s: &str) -> fmt::Result {
477 let room = self.text.len().saturating_sub(1);
478 if self.length < room {
479 let n = s.len().min(room - self.length);
480 self.text[self.length..self.length + n].copy_from_slice(&s.as_bytes()[..n]);
481 }
482 self.length += s.len();
483 Ok(())
484 }
485}
486
487impl TokenSink for Spans<'_> {
488 fn text(&mut self, kind: TokenKind, operand: OperandIndex, text: &str) -> fmt::Result {
489 let start = self.length;
490 self.write_str(text)?;
491 self.record(kind, operand, start);
492 Ok(())
493 }
494
495 fn value(
496 &mut self,
497 kind: TokenKind,
498 operand: OperandIndex,
499 value: &dyn fmt::Display,
500 ) -> fmt::Result {
501 let start = self.length;
502 write!(self, "{value}")?;
503 self.record(kind, operand, start);
504 Ok(())
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 #[test]
513 fn a_panic_is_reported_not_propagated() {
514 assert_eq!(guarded(7, || panic!("inside")), 7);
515 assert_eq!(guarded(7, || 1), 1);
516 }
517
518 #[test]
519 fn a_text_buffer_is_cut_at_its_capacity_and_terminated() {
520 let mut text = [0xAAu8; 5];
521 let mut spans = Spans::new(&mut text, &mut []);
522 spans.text(TokenKind::Mnemonic, None, "ldr").unwrap();
523 spans.text(TokenKind::Text, None, "\t").unwrap();
524 spans.value(TokenKind::Register, Some(0), &"x0").unwrap();
525 let size = spans.finish();
526 assert_eq!((size.tokens, size.length), (3, 6));
527 assert_eq!(&text, b"ldr\t\0");
528 }
529}