1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
use std::{
alloc::{self, Layout},
fmt::Display,
ptr::NonNull,
};
use super::{
errors::InstructionsError, instruction::Instruction, opcode::OpCode,
};
#[derive(Debug, Clone, PartialEq)]
pub struct Instructions {
/// actual bytes are stored in here
byte: NonNull<u8>,
/// position of next instruction will be written
cursor: *mut u8,
/// capacity of [`Self::byte`] ( bytes )
cap: usize,
/// actual length of whole instructions ( bytes )
len: usize,
}
/// default size of instructions, 2048 (0x800) bytes
const SIZE: usize = 1 << 11;
const SUCCESS: Result<(), InstructionsError> = Ok(());
impl Instructions {
/// create [`Instructions`]
///
/// # Panics
///
/// Panics if OOM (out of memory) and panic_flag is set to true
///
/// # Errors [`InstructionsError::AllocationFailed`]
///
/// This function will return an error if panic_flag is set to false
/// and OOM occured
pub fn create() -> Result<Self, InstructionsError> {
let layout = Layout::array::<u8>(SIZE).unwrap();
let new_ptr = unsafe { alloc::alloc(layout) };
let ptr = match NonNull::new(new_ptr) {
Some(p) => p,
None => {
// HACK: change this to configuration
let panic_flag = false;
if panic_flag {
// May panic here if OOM (Out of memory)
// depending on env_config and if panic_flag is true,
// global configuration, it may either panic (resulting in unwinding or aborting as per
// configuration for all panics), or abort the process (with no unwinding).
alloc::handle_alloc_error(layout);
}
return Err(InstructionsError::AllocationFailed(layout));
}
};
Ok(Self {
byte: ptr,
cursor: ptr.as_ptr(),
cap: SIZE,
len: 0,
})
}
/// Stringify this [`Instructions`]
///
/// * hidx - index of highlight target
pub fn to_string_with_highlight(&self, hidx: usize) -> String {
let mut buf = String::new();
let mut idx = 0;
while idx < self.len {
let res = self.read_instruction(idx);
if res.is_err() {
return format!(
"Error have occured on reading instruction. Error: {:?}",
res.unwrap_err()
);
}
let ins = res.unwrap();
if idx == hidx {
buf += &format!(">>{:0>5}\t\t", idx);
} else {
buf += &format!("{:0>5}\t\t", idx);
}
buf += &ins.to_string();
buf += "\n";
idx += ins.opcode().length();
}
buf
}
/// Add new instruction at the end.
/// return new Instruction's offset
///
/// # Errors [`InstructionsError`]
///
/// This function will return an error if this [`Instructions::grow()`] have failed.
pub fn add_instruction(
&mut self,
ins: Instruction,
) -> Result<usize, InstructionsError> {
if self.len + ins.opcode().length() > self.cap {
self.grow()?;
}
unsafe {
std::ptr::copy(
ins.as_byte().as_ptr(),
self.cursor,
ins.opcode().length(),
);
self.cursor = self.cursor.add(ins.opcode().length());
}
let offset = self.len;
self.len += ins.opcode().length();
Ok(offset)
}
/// Update instruction at `offset` with given `ins`
///
/// # Safety
/// if lengths are different between `ins` and instruction at `offset`,
/// There will be Corruption of this [`Instructions`]
pub unsafe fn update_instruction(
&mut self,
ins: Instruction,
offset: usize,
) {
unsafe {
std::ptr::copy(
ins.as_byte().as_ptr(),
self.byte.as_ptr().add(offset),
ins.opcode().length(),
);
}
}
/// Remove instructions by set [`Self::len`] with `new_len`
///
/// This will move [`Self::cursor`] with new position of next instruction's one
pub fn remove_instruction(&mut self, new_len: usize) {
unsafe {
self.cursor = self.byte.as_ptr().add(new_len);
}
self.len = new_len;
}
/// Read Instruction at given `offset`
///
/// # Errors [`InstructionsError::CannotRead`]
///
/// This function will return an error if failed to read opcode
/// from [`Self::byte`] at `offset` to convert it as [`Instruction`]
pub fn read_instruction(
&self,
offset: usize,
) -> Result<Instruction, InstructionsError> {
unsafe {
let opcode =
std::ptr::read(self.byte.as_ptr().add(offset) as *const OpCode);
let instruction = match opcode {
OpCode::PUSH => Instruction::PUSH,
OpCode::POP => Instruction::POP,
OpCode::ADD => Instruction::ADD,
OpCode::SUB => Instruction::SUB,
OpCode::PRODUCT => Instruction::PRODUCT,
OpCode::DIVIDE => Instruction::DIVIDE,
OpCode::MOD => Instruction::MOD,
OpCode::BANG => Instruction::BANG,
OpCode::NEG => Instruction::NEG,
OpCode::CGT => Instruction::CGT,
OpCode::CGTE => Instruction::CGTE,
OpCode::CLT => Instruction::CLT,
OpCode::CLTE => Instruction::CLTE,
OpCode::CEQ => Instruction::CEQ,
OpCode::CNEQ => Instruction::CNEQ,
OpCode::AND => Instruction::AND,
OpCode::OR => Instruction::OR,
OpCode::BAND => Instruction::BAND,
OpCode::BOR => Instruction::BOR,
OpCode::INDEX => Instruction::INDEX,
OpCode::RETN => Instruction::RETN,
OpCode::RETV => Instruction::RETV,
OpCode::GETCUR => Instruction::GETCUR,
has_argument => {
let arg_1 = std::ptr::read(
self.byte.as_ptr().add(offset + 1) as *const usize,
);
match has_argument {
OpCode::CONST => Instruction::CONST { idx: arg_1 },
OpCode::DEFGLB => Instruction::DEFGLB { idx: arg_1 },
OpCode::GETGLB => Instruction::GETGLB { idx: arg_1 },
OpCode::DEFLCL => Instruction::DEFLCL { idx: arg_1 },
OpCode::GETLCL => Instruction::GETLCL { idx: arg_1 },
OpCode::GETFREE => Instruction::GETFREE { idx: arg_1 },
OpCode::JMP => Instruction::JMP { idx: arg_1 },
OpCode::JIS => Instruction::JIS { idx: arg_1 },
OpCode::JNS => Instruction::JNS { idx: arg_1 },
OpCode::JEQ => Instruction::JEQ { idx: arg_1 },
OpCode::JNEQ => Instruction::JNEQ { idx: arg_1 },
OpCode::ARRAY => Instruction::ARRAY { count: arg_1 },
OpCode::CALL => Instruction::CALL { arg_len: arg_1 },
OpCode::CLOSURE => {
let arg_2 = std::ptr::read(
self.byte.as_ptr().add(offset + 1 + 8)
as *const usize,
);
Instruction::CLOSURE {
idx: arg_1,
free: arg_2,
}
}
_not_matched => {
return Err(InstructionsError::CannotRead {
offset,
});
}
}
}
};
Ok(instruction)
}
}
/// Returns the length of this [`Instructions`].
pub fn length(&self) -> usize {
self.len
}
/// grow size of [`Self::byte`] by twice
///
/// # Panics
///
/// Panics if OOM (out of memory) and panic_flag is set to true
///
/// # Errors [`InstructionsError::AllocationFailed`]
///
/// This function will return an error if panic_flag is set to false
/// and OOM occured
fn grow(&mut self) -> Result<(), InstructionsError> {
let new_cap = 2 * self.cap;
let new_layout = Layout::array::<u8>(new_cap).unwrap();
if new_layout.size() <= isize::MAX as usize {
return Err(InstructionsError::TooLargeToAllocate);
}
let old_layout = Layout::array::<u8>(self.cap).unwrap();
let old_ptr = self.byte.as_ptr();
let new_ptr =
unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) };
self.byte = match NonNull::new(new_ptr) {
Some(p) => p,
None => {
// HACK: change this to configuration
let panic_flag = false;
if panic_flag {
// May panic here if OOM (Out of memory)
// depending on env_config and if panic_flag is true,
// global configuration, it may either panic (resulting in unwinding or aborting as per
// configuration for all panics), or abort the process (with no unwinding).
alloc::handle_alloc_error(new_layout);
}
return Err(InstructionsError::AllocationFailed(new_layout));
}
};
self.cap = new_cap;
SUCCESS
}
/// Returns the manual drop of this [`Instructions`].
///
/// # Safety
/// this is unsafe because of possibility of multiple owner of this
#[allow(dead_code)]
unsafe fn manual_drop(&mut self) {
dbg!("drop...", &self);
unsafe {
alloc::dealloc(
self.byte.as_ptr(),
Layout::array::<u8>(self.cap).unwrap(),
);
}
}
}
impl Display for Instructions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut buf = String::new();
let mut idx = 0;
while idx < self.len {
let res = self.read_instruction(idx);
if res.is_err() {
f.write_fmt(format_args!(
"Error have occured on reading instruction. Error: {:?}",
res.unwrap_err()
))?;
return Ok(());
}
let ins = res.unwrap();
buf += &format!("{:0>5}\t\t", idx);
buf += &ins.to_string();
buf += "\n";
idx += ins.opcode().length();
}
f.write_str(buf.as_str())
}
}