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
use byteorder::{BigEndian, ReadBytesExt};
use std::fmt;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

/// Magic number for Java class files (0xCAFEBABE)
const CLASS_MAGIC: u32 = 0xCAFEBABE;

/// Represents a parsed Java class file
#[derive(Debug, Clone)]
pub struct ClassFile {
    pub magic: u32,
    pub minor_version: u16,
    pub major_version: u16,
    pub constant_pool: Vec<ConstantPoolEntry>,
    pub access_flags: u16,
    pub this_class: u16,
    pub super_class: u16,
    pub interfaces: Vec<u16>,
    pub fields: Vec<FieldInfo>,
    pub methods: Vec<MethodInfo>,
    pub attributes: Vec<AttributeInfo>,
}

/// Constant pool entry types
#[derive(Debug, Clone)]
pub enum ConstantPoolEntry {
    ConstantClass {
        name_index: u16,
    },
    ConstantFieldref {
        class_index: u16,
        name_and_type_index: u16,
    },
    ConstantMethodref {
        class_index: u16,
        name_and_type_index: u16,
    },
    ConstantInterfaceMethodref {
        class_index: u16,
        name_and_type_index: u16,
    },
    ConstantString {
        string_index: u16,
    },
    ConstantInteger {
        bytes: i32,
    },
    ConstantFloat {
        bytes: f32,
    },
    ConstantLong {
        bytes: i64,
    },
    ConstantDouble {
        bytes: f64,
    },
    ConstantNameAndType {
        name_index: u16,
        descriptor_index: u16,
    },
    ConstantUtf8 {
        bytes: Vec<u8>,
    },
    ConstantMethodHandle {
        reference_kind: u8,
        reference_index: u16,
    },
    ConstantMethodType {
        descriptor_index: u16,
    },
    ConstantInvokeDynamic {
        bootstrap_method_attr_index: u16,
        name_and_type_index: u16,
    },
}

/// Field information
#[derive(Debug, Clone)]
pub struct FieldInfo {
    pub access_flags: u16,
    pub name_index: u16,
    pub descriptor_index: u16,
    pub attributes: Vec<AttributeInfo>,
}

/// Method information
#[derive(Debug, Clone)]
pub struct MethodInfo {
    pub access_flags: u16,
    pub name_index: u16,
    pub descriptor_index: u16,
    pub attributes: Vec<AttributeInfo>,
}

/// Attribute information
#[derive(Debug, Clone)]
pub struct AttributeInfo {
    pub attribute_name_index: u16,
    pub info: Vec<u8>,
}

/// Errors that can occur during class file parsing
#[derive(Debug)]
pub enum ParseError {
    IoError(io::Error),
    InvalidMagic(u32),
    InvalidConstantPoolTag(u8),
    InvalidAttributeLength,
}

impl From<io::Error> for ParseError {
    fn from(err: io::Error) -> Self {
        ParseError::IoError(err)
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::IoError(e) => write!(f, "IO error: {}", e),
            ParseError::InvalidMagic(magic) => write!(
                f,
                "Invalid magic number: 0x{:08X} (expected 0xCAFEBABE)",
                magic
            ),
            ParseError::InvalidConstantPoolTag(tag) => {
                write!(f, "Invalid constant pool tag: {}", tag)
            }
            ParseError::InvalidAttributeLength => write!(f, "Invalid attribute length"),
        }
    }
}

impl ClassFile {
    /// Parse a class file from the given path
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ParseError> {
        let mut file = File::open(path)?;
        let mut data = Vec::new();
        file.read_to_end(&mut data)?;
        Self::parse(&data)
    }

    /// Parse a class file from a byte slice
    pub fn parse(data: &[u8]) -> Result<Self, ParseError> {
        let mut cursor = io::Cursor::new(data);

        // Read magic number
        let magic = cursor.read_u32::<BigEndian>()?;
        if magic != CLASS_MAGIC {
            return Err(ParseError::InvalidMagic(magic));
        }

        // Read version
        let minor_version = cursor.read_u16::<BigEndian>()?;
        let major_version = cursor.read_u16::<BigEndian>()?;

        // Read constant pool count
        let constant_pool_count = cursor.read_u16::<BigEndian>()?;
        let mut constant_pool = Vec::with_capacity(constant_pool_count as usize);
        constant_pool.push(ConstantPoolEntry::ConstantUtf8 { bytes: Vec::new() }); // Index 0 is invalid

        // Read constant pool entries
        for _ in 1..constant_pool_count {
            let tag = cursor.read_u8()?;
            let entry = Self::read_constant_pool_entry(&mut cursor, tag)?;
            constant_pool.push(entry);

            // Long and Double take two constant pool slots
            if matches!(tag, 5 | 6) {
                constant_pool.push(ConstantPoolEntry::ConstantUtf8 { bytes: Vec::new() });
            }
        }

        // Read access flags
        let access_flags = cursor.read_u16::<BigEndian>()?;

        // Read this class and super class
        let this_class = cursor.read_u16::<BigEndian>()?;
        let super_class = cursor.read_u16::<BigEndian>()?;

        // Read interfaces
        let interfaces_count = cursor.read_u16::<BigEndian>()?;
        let mut interfaces = Vec::with_capacity(interfaces_count as usize);
        for _ in 0..interfaces_count {
            interfaces.push(cursor.read_u16::<BigEndian>()?);
        }

        // Read fields
        let fields_count = cursor.read_u16::<BigEndian>()?;
        let mut fields = Vec::with_capacity(fields_count as usize);
        for _ in 0..fields_count {
            fields.push(Self::read_field_info(&mut cursor)?);
        }

        // Read methods
        let methods_count = cursor.read_u16::<BigEndian>()?;
        let mut methods = Vec::with_capacity(methods_count as usize);
        for _ in 0..methods_count {
            methods.push(Self::read_method_info(&mut cursor)?);
        }

        // Read attributes
        let attributes_count = cursor.read_u16::<BigEndian>()?;
        let mut attributes = Vec::with_capacity(attributes_count as usize);
        for _ in 0..attributes_count {
            attributes.push(Self::read_attribute_info(&mut cursor)?);
        }

        Ok(ClassFile {
            magic,
            minor_version,
            major_version,
            constant_pool,
            access_flags,
            this_class,
            super_class,
            interfaces,
            fields,
            methods,
            attributes,
        })
    }

    fn read_constant_pool_entry(
        cursor: &mut io::Cursor<&[u8]>,
        tag: u8,
    ) -> Result<ConstantPoolEntry, ParseError> {
        match tag {
            1 => {
                // CONSTANT_Utf8
                let len = cursor.read_u16::<BigEndian>()? as usize;
                let mut bytes = vec![0u8; len];
                cursor.read_exact(&mut bytes)?;
                Ok(ConstantPoolEntry::ConstantUtf8 { bytes })
            }
            3 => {
                // CONSTANT_Integer
                let bytes = cursor.read_i32::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantInteger { bytes })
            }
            4 => {
                // CONSTANT_Float
                let bytes = cursor.read_u32::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantFloat {
                    bytes: f32::from_bits(bytes),
                })
            }
            5 => {
                // CONSTANT_Long
                let bytes = cursor.read_i64::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantLong { bytes })
            }
            6 => {
                // CONSTANT_Double
                let bytes = cursor.read_u64::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantDouble {
                    bytes: f64::from_bits(bytes),
                })
            }
            7 => {
                // CONSTANT_Class
                let name_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantClass { name_index })
            }
            8 => {
                // CONSTANT_String
                let string_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantString { string_index })
            }
            9 => {
                // CONSTANT_Fieldref
                let class_index = cursor.read_u16::<BigEndian>()?;
                let name_and_type_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantFieldref {
                    class_index,
                    name_and_type_index,
                })
            }
            10 => {
                // CONSTANT_Methodref
                let class_index = cursor.read_u16::<BigEndian>()?;
                let name_and_type_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantMethodref {
                    class_index,
                    name_and_type_index,
                })
            }
            11 => {
                // CONSTANT_InterfaceMethodref
                let class_index = cursor.read_u16::<BigEndian>()?;
                let name_and_type_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantInterfaceMethodref {
                    class_index,
                    name_and_type_index,
                })
            }
            12 => {
                // CONSTANT_NameAndType
                let name_index = cursor.read_u16::<BigEndian>()?;
                let descriptor_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantNameAndType {
                    name_index,
                    descriptor_index,
                })
            }
            15 => {
                // CONSTANT_MethodHandle
                let reference_kind = cursor.read_u8()?;
                let reference_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantMethodHandle {
                    reference_kind,
                    reference_index,
                })
            }
            16 => {
                // CONSTANT_MethodType
                let descriptor_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantMethodType { descriptor_index })
            }
            18 => {
                // CONSTANT_InvokeDynamic
                let bootstrap_method_attr_index = cursor.read_u16::<BigEndian>()?;
                let name_and_type_index = cursor.read_u16::<BigEndian>()?;
                Ok(ConstantPoolEntry::ConstantInvokeDynamic {
                    bootstrap_method_attr_index,
                    name_and_type_index,
                })
            }
            _ => Err(ParseError::InvalidConstantPoolTag(tag)),
        }
    }

    fn read_field_info(cursor: &mut io::Cursor<&[u8]>) -> Result<FieldInfo, ParseError> {
        let access_flags = cursor.read_u16::<BigEndian>()?;
        let name_index = cursor.read_u16::<BigEndian>()?;
        let descriptor_index = cursor.read_u16::<BigEndian>()?;

        let attributes_count = cursor.read_u16::<BigEndian>()?;
        let mut attributes = Vec::with_capacity(attributes_count as usize);
        for _ in 0..attributes_count {
            attributes.push(Self::read_attribute_info(cursor)?);
        }

        Ok(FieldInfo {
            access_flags,
            name_index,
            descriptor_index,
            attributes,
        })
    }

    fn read_method_info(cursor: &mut io::Cursor<&[u8]>) -> Result<MethodInfo, ParseError> {
        let access_flags = cursor.read_u16::<BigEndian>()?;
        let name_index = cursor.read_u16::<BigEndian>()?;
        let descriptor_index = cursor.read_u16::<BigEndian>()?;

        let attributes_count = cursor.read_u16::<BigEndian>()?;
        let mut attributes = Vec::with_capacity(attributes_count as usize);
        for _ in 0..attributes_count {
            attributes.push(Self::read_attribute_info(cursor)?);
        }

        Ok(MethodInfo {
            access_flags,
            name_index,
            descriptor_index,
            attributes,
        })
    }

    fn read_attribute_info(cursor: &mut io::Cursor<&[u8]>) -> Result<AttributeInfo, ParseError> {
        let attribute_name_index = cursor.read_u16::<BigEndian>()?;
        let length = cursor.read_u32::<BigEndian>()? as usize;
        let mut info = vec![0u8; length];
        cursor.read_exact(&mut info)?;
        Ok(AttributeInfo {
            attribute_name_index,
            info,
        })
    }

    /// Get a string from the constant pool by index
    pub fn get_string(&self, index: u16) -> Option<String> {
        let entry = self.constant_pool.get(index as usize)?;
        match entry {
            ConstantPoolEntry::ConstantUtf8 { bytes } => String::from_utf8(bytes.clone()).ok(),
            _ => None,
        }
    }

    /// Get the class name
    pub fn get_class_name(&self) -> Option<String> {
        let class_entry = self.constant_pool.get(self.this_class as usize)?;
        match class_entry {
            ConstantPoolEntry::ConstantClass { name_index } => self.get_string(*name_index),
            _ => None,
        }
    }

    /// Get the super class name
    pub fn get_super_class_name(&self) -> Option<String> {
        if self.super_class == 0 {
            return None; // java/lang/Object has no super class
        }
        let class_entry = self.constant_pool.get(self.super_class as usize)?;
        match class_entry {
            ConstantPoolEntry::ConstantClass { name_index } => self.get_string(*name_index),
            _ => None,
        }
    }

    /// Get class name from a constant pool index (must point to CONSTANT_Class)
    pub fn get_class_name_from_index(&self, index: u16) -> Option<String> {
        let entry = self.constant_pool.get(index as usize)?;
        match entry {
            ConstantPoolEntry::ConstantClass { name_index } => self.get_string(*name_index),
            _ => None,
        }
    }

    /// Find a method by name and descriptor
    pub fn find_method(&self, name: &str, descriptor: &str) -> Option<&MethodInfo> {
        self.methods.iter().find(|m| {
            let method_name = self.get_string(m.name_index).unwrap_or_default();
            let method_desc = self.get_string(m.descriptor_index).unwrap_or_default();
            method_name == name && method_desc == descriptor
        })
    }
}