use crate::TrapInformation;
use crate::obj::ELF_WASMTIME_TRAPS;
use crate::prelude::*;
use object::write::{Object, StandardSegment};
use object::{LittleEndian, SectionKind, U32Bytes};
use std::ops::Range;
#[derive(Default)]
pub struct TrapEncodingBuilder {
offsets: Vec<U32Bytes<LittleEndian>>,
traps: Vec<u8>,
last_offset: u32,
}
impl TrapEncodingBuilder {
pub fn push(&mut self, func: Range<u64>, traps: &[TrapInformation]) {
let func_start = u32::try_from(func.start).unwrap();
let func_end = u32::try_from(func.end).unwrap();
assert!(func_start >= self.last_offset);
self.offsets.reserve(traps.len());
self.traps.reserve(traps.len());
for info in traps {
let pos = func_start + info.code_offset;
assert!(pos >= self.last_offset);
self.offsets.push(U32Bytes::new(LittleEndian, pos));
self.traps.push(info.trap_code as u8);
self.last_offset = pos;
}
self.last_offset = func_end;
}
pub fn append_to(self, obj: &mut Object) {
let section = obj.add_section(
obj.segment_name(StandardSegment::Data).to_vec(),
ELF_WASMTIME_TRAPS.as_bytes().to_vec(),
SectionKind::ReadOnlyData,
);
let amt = u32::try_from(self.traps.len()).unwrap();
obj.append_section_data(section, &amt.to_le_bytes(), 1);
obj.append_section_data(section, object::bytes_of_slice(&self.offsets), 1);
obj.append_section_data(section, &self.traps, 1);
}
}