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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//! Array type operations for the managed heap.
//!
//! This module provides operations for single-dimensional arrays, multi-dimensional
//! arrays, and byte array convenience methods on [`ManagedHeap`].
use crate::{
emulation::{
engine::EmulationError,
memory::heap::{HeapObject, ManagedHeap},
EmValue, HeapRef,
},
metadata::typesystem::{CilFlavor, PointerSize},
Result,
};
impl ManagedHeap {
/// Allocates a single-dimensional array on the heap.
///
/// # Arguments
///
/// * `element_type` - Type of array elements
/// * `length` - Number of elements
///
/// # Errors
///
/// Returns [`EmulationError::HeapMemoryLimitExceeded`] if heap is out of memory.
pub fn alloc_array(&self, element_type: CilFlavor, length: usize) -> Result<HeapRef> {
let elements = vec![EmValue::default_for_flavor(&element_type); length];
self.alloc_object_internal(
HeapObject::Array {
element_type,
elements,
},
None,
)
}
/// Allocates an array with explicit initial values.
///
/// # Errors
///
/// Returns [`EmulationError::HeapMemoryLimitExceeded`] if heap is out of memory.
pub fn alloc_array_with_values(
&self,
element_type: CilFlavor,
elements: Vec<EmValue>,
) -> Result<HeapRef> {
self.alloc_object_internal(
HeapObject::Array {
element_type,
elements,
},
None,
)
}
/// Allocates a multi-dimensional array on the heap.
///
/// # Errors
///
/// Returns [`EmulationError::HeapMemoryLimitExceeded`] if heap is out of memory.
pub fn alloc_multi_array(
&self,
element_type: CilFlavor,
dimensions: Vec<usize>,
) -> Result<HeapRef> {
let total_elements: usize = dimensions.iter().product();
let elements = vec![EmValue::default_for_flavor(&element_type); total_elements];
self.alloc_object_internal(
HeapObject::MultiArray {
element_type,
dimensions,
elements,
},
None,
)
}
/// Gets an array element (cloned).
///
/// # Panics
///
/// Panics if the internal `RwLock` is poisoned.
///
/// # Errors
///
/// Returns error if the reference is invalid, not an array, or index out of bounds.
pub fn get_array_element(&self, heap_ref: HeapRef, index: usize) -> Result<EmValue> {
let state = self
.state
.read()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
match state.objects.get(&heap_ref.id()) {
Some(HeapObject::Array { elements, .. }) => {
if index >= elements.len() {
Err(EmulationError::ArrayIndexOutOfBounds {
index: i64::try_from(index).unwrap_or(i64::MAX),
length: elements.len(),
}
.into())
} else {
Ok(elements[index].clone())
}
}
Some(other) => Err(EmulationError::HeapTypeMismatch {
expected: "array",
found: other.kind(),
}
.into()),
None => Err(EmulationError::InvalidHeapReference {
reference_id: heap_ref.id(),
}
.into()),
}
}
/// Sets an array element.
///
/// # Panics
///
/// Panics if the internal `RwLock` is poisoned.
///
/// # Errors
///
/// Returns error if the reference is invalid, not an array, or index out of bounds.
pub fn set_array_element(&self, heap_ref: HeapRef, index: usize, value: EmValue) -> Result<()> {
let mut state = self
.state
.write()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
match state.objects.get_mut(&heap_ref.id()) {
Some(HeapObject::Array { elements, .. }) => {
if index >= elements.len() {
Err(EmulationError::ArrayIndexOutOfBounds {
index: i64::try_from(index).unwrap_or(i64::MAX),
length: elements.len(),
}
.into())
} else {
elements[index] = value;
Ok(())
}
}
Some(other) => Err(EmulationError::HeapTypeMismatch {
expected: "array",
found: other.kind(),
}
.into()),
None => Err(EmulationError::InvalidHeapReference {
reference_id: heap_ref.id(),
}
.into()),
}
}
/// Gets the length of an array.
///
/// # Panics
///
/// Panics if the internal `RwLock` is poisoned.
///
/// # Errors
///
/// Returns error if the reference is invalid or not an array.
pub fn get_array_length(&self, heap_ref: HeapRef) -> Result<usize> {
let state = self
.state
.read()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
match state.objects.get(&heap_ref.id()) {
Some(HeapObject::Array { elements, .. }) => Ok(elements.len()),
Some(HeapObject::MultiArray { dimensions, .. }) => Ok(dimensions.iter().product()),
Some(other) => Err(EmulationError::HeapTypeMismatch {
expected: "array",
found: other.kind(),
}
.into()),
None => Err(EmulationError::InvalidHeapReference {
reference_id: heap_ref.id(),
}
.into()),
}
}
/// Gets the element type of an array.
///
/// # Panics
///
/// Panics if the internal `RwLock` is poisoned.
///
/// # Errors
///
/// Returns error if the reference is invalid or not an array.
pub fn get_array_element_type(&self, heap_ref: HeapRef) -> Result<CilFlavor> {
let state = self
.state
.read()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
match state.objects.get(&heap_ref.id()) {
Some(
HeapObject::Array { element_type, .. }
| HeapObject::MultiArray { element_type, .. },
) => Ok(element_type.clone()),
Some(other) => Err(EmulationError::HeapTypeMismatch {
expected: "array",
found: other.kind(),
}
.into()),
None => Err(EmulationError::InvalidHeapReference {
reference_id: heap_ref.id(),
}
.into()),
}
}
/// Allocates a byte array on the heap.
///
/// # Errors
///
/// Returns [`EmulationError::HeapMemoryLimitExceeded`] if heap is out of memory.
pub fn alloc_byte_array(&self, data: &[u8]) -> Result<HeapRef> {
let elements: Vec<EmValue> = data.iter().map(|&b| EmValue::I32(i32::from(b))).collect();
self.alloc_array_with_values(CilFlavor::U1, elements)
}
/// Gets a byte array from the heap.
///
/// Returns `Ok(None)` if the reference is invalid, not a byte array, or contains
/// any non-I32 elements (including Symbolic values). This fail-fast behavior
/// ensures callers don't silently receive partial/corrupted data.
///
/// # Errors
///
/// Returns [`EmulationError::LockPoisoned`] if the internal `RwLock` is poisoned.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn get_byte_array(&self, heap_ref: HeapRef) -> Result<Option<Vec<u8>>> {
let state = self
.state
.read()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
Ok(match state.objects.get(&heap_ref.id()) {
Some(HeapObject::Array { elements, .. }) => {
let mut bytes = Vec::with_capacity(elements.len());
for e in elements {
match e {
EmValue::I32(n) => bytes.push(*n as u8),
_ => return Ok(None),
}
}
Some(bytes)
}
_ => None,
})
}
/// Converts an array's elements to a byte vector, respecting element type.
///
/// Unlike `get_byte_array` which only takes the low byte, this method
/// properly serializes multi-byte elements (uint32, int64, etc.) to bytes
/// in little-endian order.
///
/// Returns `Ok(None)` if the reference is invalid, not an array, or contains
/// non-numeric types.
///
/// # Errors
///
/// Returns [`EmulationError::LockPoisoned`] if the internal `RwLock` is poisoned.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn get_array_as_bytes(
&self,
heap_ref: HeapRef,
ptr_size: PointerSize,
) -> Result<Option<Vec<u8>>> {
let state = self
.state
.read()
.map_err(|_| EmulationError::LockPoisoned {
description: "managed heap",
})?;
Ok(match state.objects.get(&heap_ref.id()) {
Some(HeapObject::Array {
elements,
element_type,
}) => {
let element_size = element_type.element_size(ptr_size);
match element_size {
Some(element_size) => {
let mut bytes = Vec::with_capacity(elements.len() * element_size);
let mut valid = true;
for e in elements {
match e {
EmValue::I32(n) => match element_size {
2 => bytes.extend_from_slice(&(*n as i16).to_le_bytes()),
4 => bytes.extend_from_slice(&n.to_le_bytes()),
_ => bytes.push(*n as u8),
},
EmValue::I64(n) => {
bytes.extend_from_slice(&n.to_le_bytes());
}
EmValue::F32(f) => {
bytes.extend_from_slice(&f.to_le_bytes());
}
EmValue::F64(f) => {
bytes.extend_from_slice(&f.to_le_bytes());
}
_ => {
valid = false;
break;
}
}
}
if valid {
Some(bytes)
} else {
None
}
}
None => None,
}
}
_ => None,
})
}
}
#[cfg(test)]
mod tests {
use crate::{
emulation::{memory::heap::ManagedHeap, EmValue},
metadata::typesystem::CilFlavor,
};
#[test]
fn test_heap_alloc_array() {
let heap = ManagedHeap::new(1024 * 1024);
let array_ref = heap.alloc_array(CilFlavor::I4, 10).unwrap();
assert!(heap.contains(array_ref).unwrap());
let length = heap.get_array_length(array_ref).unwrap();
assert_eq!(length, 10);
// Elements should be default initialized
let elem = heap.get_array_element(array_ref, 0).unwrap();
assert_eq!(elem, EmValue::I32(0));
}
#[test]
fn test_heap_array_operations() {
let heap = ManagedHeap::new(1024 * 1024);
let array_ref = heap.alloc_array(CilFlavor::I4, 5).unwrap();
heap.set_array_element(array_ref, 2, EmValue::I32(42))
.unwrap();
let elem = heap.get_array_element(array_ref, 2).unwrap();
assert_eq!(elem, EmValue::I32(42));
// Out of bounds
assert!(heap.get_array_element(array_ref, 10).is_err());
assert!(heap
.set_array_element(array_ref, 10, EmValue::I32(0))
.is_err());
}
}