jvmrs 0.1.2

A JVM implementation in Rust with Cranelift JIT, AOT compilation, and WebAssembly support
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! JVM heap for object and array allocation.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::debug::JvmDebugger;
use crate::error::MemoryError;
use crate::security::Sanitizer;

use super::heap_object::{HeapArray, HeapObject};
use super::monitor::Monitor;
use super::Value;

/// JVM heap for object allocation
#[derive(Debug)]
pub struct Heap {
    objects: HashMap<u32, HeapObject>,
    arrays: HashMap<u32, HeapArray>,
    next_addr: u32,
    marked: HashSet<u32>,
    debugger: Option<JvmDebugger>,
    sanitizer: Option<Arc<Sanitizer>>,
}

impl Heap {
    pub fn new() -> Self {
        Heap {
            objects: HashMap::new(),
            arrays: HashMap::new(),
            next_addr: 1,
            marked: HashSet::new(),
            debugger: None,
            sanitizer: None,
        }
    }

    pub fn with_debugger(debugger: JvmDebugger) -> Self {
        Heap {
            objects: HashMap::new(),
            arrays: HashMap::new(),
            next_addr: 1,
            marked: HashSet::new(),
            debugger: Some(debugger),
            sanitizer: None,
        }
    }

    pub fn set_sanitizer(&mut self, sanitizer: Option<Arc<Sanitizer>>) {
        self.sanitizer = sanitizer;
    }

    pub fn allocate(&mut self, class_name: String) -> u32 {
        let addr = self.next_addr;
        self.next_addr += 1;

        if let Some(debugger) = &self.debugger {
            debugger.log_memory_allocation(addr, 0, &class_name);
        }

        self.objects.insert(
            addr,
            HeapObject {
                fields: HashMap::new(),
                class_name,
                marked: false,
                string_data: None,
                monitor: None,
            },
        );
        addr
    }

    pub fn allocate_string(&mut self, data: String) -> u32 {
        let addr = self.next_addr;
        self.next_addr += 1;

        if let Some(debugger) = &self.debugger {
            debugger.log_memory_allocation(addr, data.len(), "java/lang/String");
        }

        self.objects.insert(
            addr,
            HeapObject {
                fields: HashMap::new(),
                class_name: "java/lang/String".to_string(),
                marked: false,
                string_data: Some(data),
                monitor: None,
            },
        );
        addr
    }

    pub fn allocate_array(&mut self, array_type: HeapArray) -> u32 {
        let addr = self.next_addr;
        self.next_addr += 1;
        self.arrays.insert(addr, array_type);
        addr
    }

    pub fn get_object(&self, addr: u32) -> Option<&HeapObject> {
        self.objects.get(&addr)
    }

    pub fn get_object_mut(&mut self, addr: u32) -> Option<&mut HeapObject> {
        self.objects.get_mut(&addr)
    }

    pub fn get_field(&self, addr: u32, field_name: &str) -> Option<Value> {
        self.objects
            .get(&addr)
            .and_then(|obj| obj.fields.get(field_name).cloned())
    }

    pub fn set_field(
        &mut self,
        addr: u32,
        field_name: String,
        value: Value,
    ) -> Result<(), crate::error::MemoryError> {
        let obj = self
            .objects
            .get_mut(&addr)
            .ok_or_else(|| crate::error::MemoryError::InvalidReference(addr))?;
        obj.fields.insert(field_name, value);
        Ok(())
    }

    pub fn get_string_data(&self, addr: u32) -> Option<&String> {
        self.objects.get(&addr).and_then(|obj| {
            if obj.class_name == "java/lang/String" {
                obj.string_data.as_ref()
            } else {
                None
            }
        })
    }

    pub fn is_string(&self, addr: u32) -> bool {
        self.objects
            .get(&addr)
            .map(|obj| obj.class_name == "java/lang/String")
            .unwrap_or(false)
    }

    pub fn get_array(&self, addr: u32) -> Option<&HeapArray> {
        self.arrays.get(&addr)
    }

    pub fn get_array_mut(&mut self, addr: u32) -> Option<&mut HeapArray> {
        self.arrays.get_mut(&addr)
    }

    pub fn mark(&mut self, addr: u32) {
        if let Some(obj) = self.objects.get_mut(&addr) {
            obj.marked = true;
            self.marked.insert(addr);
        }
    }

    pub fn unmark_all(&mut self) {
        for obj in self.objects.values_mut() {
            obj.marked = false;
        }
        self.marked.clear();
    }

    pub fn collect_garbage(&mut self, roots: &[u32]) -> Result<usize, MemoryError> {
        self.unmark_all();
        let mut to_mark: Vec<u32> = roots.to_vec();

        while let Some(addr) = to_mark.pop() {
            if self.marked.contains(&addr) {
                continue;
            }

            self.mark(addr);

            if let Some(obj) = self.objects.get(&addr) {
                for value in obj.fields.values() {
                    if let Some(ref_addr) = value.as_reference() {
                        if !self.marked.contains(&ref_addr) {
                            to_mark.push(ref_addr);
                        }
                    }
                }
            }

            if let Some(array) = self.arrays.get(&addr) {
                if let HeapArray::ReferenceArray(_, refs) = array {
                    for ref_addr in refs {
                        if !self.marked.contains(ref_addr) {
                            to_mark.push(*ref_addr);
                        }
                    }
                }
            }
        }

        let mut freed = 0;
        let objects_to_remove: Vec<_> = self
            .objects
            .iter()
            .filter(|(_, obj)| !obj.marked)
            .map(|(addr, _)| *addr)
            .collect();
        let arrays_to_remove: Vec<_> = self
            .arrays
            .keys()
            .filter(|addr| !self.marked.contains(addr))
            .cloned()
            .collect();

        for addr in objects_to_remove {
            self.objects.remove(&addr);
            freed += 1;
        }
        for addr in arrays_to_remove {
            self.arrays.remove(&addr);
            freed += 1;
        }

        Ok(freed)
    }

    pub fn object_count(&self) -> usize {
        self.objects.len()
    }

    pub fn array_count(&self) -> usize {
        self.arrays.len()
    }

    pub fn memory_used(&self) -> usize {
        let mut total = 0;
        for obj in self.objects.values() {
            total += obj.class_name.len() + obj.fields.len() * 16;
        }
        for array in self.arrays.values() {
            total += match array {
                HeapArray::IntArray(v) => v.len() * 4,
                HeapArray::FloatArray(v) => v.len() * 4,
                HeapArray::LongArray(v) => v.len() * 8,
                HeapArray::DoubleArray(v) => v.len() * 8,
                HeapArray::ReferenceArray(_, v) => v.len() * 4,
                HeapArray::ByteArray(v) => v.len(),
                HeapArray::CharArray(v) => v.len() * 2,
                HeapArray::ShortArray(v) => v.len() * 2,
                HeapArray::BooleanArray(v) => v.len(),
            };
        }
        total
    }

    pub fn array_length(&self, addr: u32) -> Result<usize, MemoryError> {
        if let Some(ref s) = self.sanitizer {
            s.check_null(Some(addr))
                .map_err(MemoryError::InvalidArrayOperation)?;
        }
        self.arrays
            .get(&addr)
            .map(|array| match array {
                HeapArray::IntArray(v) => v.len(),
                HeapArray::FloatArray(v) => v.len(),
                HeapArray::LongArray(v) => v.len(),
                HeapArray::DoubleArray(v) => v.len(),
                HeapArray::ReferenceArray(_, v) => v.len(),
                HeapArray::ByteArray(v) => v.len(),
                HeapArray::CharArray(v) => v.len(),
                HeapArray::ShortArray(v) => v.len(),
                HeapArray::BooleanArray(v) => v.len(),
            })
            .ok_or_else(|| MemoryError::InvalidHeapAddress(addr))
    }

    pub fn array_get(&self, addr: u32, index: usize) -> Result<Value, MemoryError> {
        if let Some(ref s) = self.sanitizer {
            s.check_null(Some(addr))
                .map_err(MemoryError::InvalidArrayOperation)?;
        }
        let array = self
            .arrays
            .get(&addr)
            .ok_or_else(|| MemoryError::InvalidHeapAddress(addr))?;
        let len = match array {
            HeapArray::IntArray(v) => v.len(),
            HeapArray::FloatArray(v) => v.len(),
            HeapArray::LongArray(v) => v.len(),
            HeapArray::DoubleArray(v) => v.len(),
            HeapArray::ReferenceArray(_, v) => v.len(),
            HeapArray::ByteArray(v) => v.len(),
            HeapArray::CharArray(v) => v.len(),
            HeapArray::ShortArray(v) => v.len(),
            HeapArray::BooleanArray(v) => v.len(),
        };
        if let Some(ref s) = self.sanitizer {
            s.check_array_bounds(index, len)
                .map_err(MemoryError::InvalidArrayOperation)?;
        }
        match array {
            HeapArray::IntArray(v) => v
                .get(index)
                .map(|&val| Value::Int(val))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::FloatArray(v) => v
                .get(index)
                .map(|&val| Value::Float(val))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::LongArray(v) => v
                .get(index)
                .map(|&val| Value::Long(val))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::DoubleArray(v) => v
                .get(index)
                .map(|&val| Value::Double(val))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::ReferenceArray(_, v) => v
                .get(index)
                .map(|&val| Value::Reference(val))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::ByteArray(v) => v
                .get(index)
                .map(|&val| Value::Int(val as i8 as i32))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::CharArray(v) => v
                .get(index)
                .map(|&val| Value::Int(val as i32))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::ShortArray(v) => v
                .get(index)
                .map(|&val| Value::Int(val as i32))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
            HeapArray::BooleanArray(v) => v
                .get(index)
                .map(|&val| Value::Int(if val { 1 } else { 0 }))
                .ok_or_else(|| MemoryError::InvalidArrayLength(index)),
        }
    }

    pub fn array_set(&mut self, addr: u32, index: usize, value: Value) -> Result<(), MemoryError> {
        if let Some(ref s) = self.sanitizer {
            s.check_null(Some(addr))
                .map_err(MemoryError::InvalidArrayOperation)?;
        }
        let array = self
            .arrays
            .get_mut(&addr)
            .ok_or_else(|| MemoryError::InvalidHeapAddress(addr))?;
        let len = match array {
            HeapArray::IntArray(v) => v.len(),
            HeapArray::FloatArray(v) => v.len(),
            HeapArray::LongArray(v) => v.len(),
            HeapArray::DoubleArray(v) => v.len(),
            HeapArray::ReferenceArray(_, v) => v.len(),
            HeapArray::ByteArray(v) => v.len(),
            HeapArray::CharArray(v) => v.len(),
            HeapArray::ShortArray(v) => v.len(),
            HeapArray::BooleanArray(v) => v.len(),
        };
        if let Some(ref s) = self.sanitizer {
            s.check_array_bounds(index, len)
                .map_err(MemoryError::InvalidArrayOperation)?;
        }
        match array {
            HeapArray::IntArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_int();
            }
            HeapArray::FloatArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_float();
            }
            HeapArray::LongArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_long();
            }
            HeapArray::DoubleArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_double();
            }
            HeapArray::ReferenceArray(_, v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_reference().ok_or_else(|| {
                    MemoryError::InvalidArrayType("Expected reference".to_string())
                })?;
            }
            HeapArray::ByteArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = (value.as_int() as i8) as u8;
            }
            HeapArray::CharArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_int() as u16;
            }
            HeapArray::ShortArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_int() as i16;
            }
            HeapArray::BooleanArray(v) => {
                if index >= v.len() {
                    return Err(MemoryError::InvalidArrayLength(index));
                }
                v[index] = value.as_int() != 0;
            }
        }

        Ok(())
    }

    pub fn monitor_enter(&mut self, addr: u32, thread_id: u32) -> Result<(), MemoryError> {
        let obj = self
            .get_object_mut(addr)
            .ok_or(MemoryError::InvalidReference(addr))?;

        if obj.monitor.is_none() {
            obj.monitor = Some(Monitor::new());
        }

        let monitor = obj.monitor.as_mut().unwrap();

        if monitor.enter(thread_id) {
            Ok(())
        } else {
            Err(MemoryError::InvalidMonitorState)
        }
    }

    pub fn monitor_exit(&mut self, addr: u32, thread_id: u32) -> Result<(), MemoryError> {
        let obj = self
            .get_object_mut(addr)
            .ok_or(MemoryError::InvalidReference(addr))?;

        if let Some(monitor) = &mut obj.monitor {
            if Monitor::exit(monitor, thread_id) {
                Ok(())
            } else {
                Err(MemoryError::IllegalMonitorState)
            }
        } else {
            Err(MemoryError::IllegalMonitorState)
        }
    }

    pub fn owns_monitor(&self, addr: u32, thread_id: u32) -> bool {
        if let Some(obj) = self.get_object(addr) {
            if let Some(monitor) = &obj.monitor {
                return monitor.is_owned_by(thread_id);
            }
        }
        false
    }
}

impl Default for Heap {
    fn default() -> Self {
        Self::new()
    }
}