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
use std::io;
use std::io::{Error, ErrorKind, Read};
use std::str;

use attribute::*;
use class_access::*;
use class_file::ClassFile;
use constant_pool::*;
use field::*;
use field_access::*;
use method::*;
use util::{Contextable, promote_result_to_io};

const EXPECTED_MAGIC: u32 = 0xCAFE_BABE;

const CONSTANT_TAG_UTF8: u8 = 1;
const CONSTANT_TAG_CLASS: u8 = 7;
const CONSTANT_TAG_STRING: u8 = 8;
const CONSTANT_TAG_FIELDREF: u8 = 9;
const CONSTANT_TAG_METHODREF: u8 = 10;
const CONSTANT_TAG_NAME_AND_TYPE: u8 = 12;

const READ_MINOR_VERSION: &str = "Failed to read minor version.";
const READ_MAJOR_VERSION: &str = "Failed to read major version.";
const READ_CONSTANT_POOL: &str = "Failed to read constant pool.";
const READ_ACCESS_FLAGS: &str = "Failed to read access flags.";
const READ_THIS_CLASS: &str = "Failed to read the 'this class' index.";
const READ_SUPER_CLASS: &str = "Failed to read the 'super class' index.";
const READ_INTERFACES: &str = "Failed to read interfaces.";
const READ_FIELDS: &str = "Failed to read fields.";
const READ_METHODS: &str = "Failed to read methods.";
const READ_ATTRIBUTES: &str = "Failed to read attributes.";

pub fn read_class_file<R: Read>(file: &mut R) -> io::Result<ClassFile> {
    let magic = read_u32(file)?;

    if magic != EXPECTED_MAGIC {
        let error_msg = format!("The given file does not appear to be a valid JVM class file. JVM class files must start with the magic bytes \"CAFEBABE\", but this file started with \"{:x}\"", magic);

        return Err(Error::new(ErrorKind::Other, error_msg))
    }

    let minor_version = read_u16(file).context(READ_MINOR_VERSION)?;
    let major_version = read_u16(file).context(READ_MAJOR_VERSION)?;

    let constant_pool = read_constant_pool(file).context(READ_CONSTANT_POOL)?;

    let access_flags  = read_u16(file).context(READ_ACCESS_FLAGS)?;
    let this_class    = read_u16(file).context(READ_THIS_CLASS)?;
    let super_class   = read_u16(file).context(READ_SUPER_CLASS)?;

    let interfaces    = read_interfaces(file).context(READ_INTERFACES)?;
    let fields        = read_fields(file).context(READ_FIELDS)?;
    let methods       = read_methods(file).context(READ_METHODS)?;
    let attributes    = read_attributes(file).context(READ_ATTRIBUTES)?;

    let access_flags = promote_result_to_io(
        ClassAccess::from_access_flags(access_flags)
    )?;

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

fn read_u8<R: Read>(file: &mut R) -> io::Result<u8> {
    let mut buffer = [0; 1];

    file.read_exact(&mut buffer)?;

    Ok(u8::from_be_bytes(buffer))
}

fn read_u16<R: Read>(file: &mut R) -> io::Result<u16> {
    let mut buffer = [0; 2];

    file.read_exact(&mut buffer)?;

    Ok(u16::from_be_bytes(buffer))
}

fn read_u32<R: Read>(file: &mut R) -> io::Result<u32> {
    let mut buffer = [0; 4];

    file.read_exact(&mut buffer)?;

    Ok(u32::from_be_bytes(buffer))
}

fn read_n_bytes<R: Read>(file: &mut R, length: usize) -> io::Result<Vec<u8>> {
    let mut bytes = vec![0u8; length as usize];

    file.read_exact(&mut bytes)?;

    Ok(bytes)
}

#[allow(clippy::vec_box)]
fn read_constant_pool<R: Read>(file: &mut R) -> io::Result<Vec<Box<ConstantPoolEntry>>> {
    let constant_pool_count = i32::from(read_u16(file)?);

    let mut constant_pool = Vec::<Box<ConstantPoolEntry>>::new();

    for _ in 0..(constant_pool_count - 1) {
        let entry = read_constant_pool_entry(file)?;

        constant_pool.push(entry);
    }

    Ok(constant_pool)
}

fn read_constant_pool_entry<R: Read>(file: &mut R) -> io::Result<Box<ConstantPoolEntry>> {
    let tag = read_u8(file)?;

    let entry: Box<ConstantPoolEntry> = match tag {
        CONSTANT_TAG_UTF8 =>
            Box::new(read_constant_utf8(file)?),
        CONSTANT_TAG_CLASS =>
            Box::new(read_constant_class(file)?),
        CONSTANT_TAG_STRING =>
            Box::new(read_constant_string(file)?),
        CONSTANT_TAG_FIELDREF =>
            Box::new(read_constant_fieldref(file)?),
        CONSTANT_TAG_METHODREF =>
            Box::new(read_constant_methodref(file)?),
        CONSTANT_TAG_NAME_AND_TYPE =>
            Box::new(read_constant_name_and_type(file)?),
        _ => panic!("Encountered unknown type of constant pool entry with a tag of: {}", tag),
    };

    Ok(entry)
}

fn read_constant_utf8<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let length = read_u16(file)?;

    let bytes = read_n_bytes(file, length as usize)?;

    let string = str::from_utf8(&bytes).unwrap()
        .to_string();

    Ok(ConstantPoolEntry::ConstantUtf8 {
        string,
    })
}

fn read_constant_class<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let name_index = read_u16(file)?;

    Ok(ConstantPoolEntry::ConstantClass {
        name_index,
    })
}

fn read_constant_string<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let string_index = read_u16(file)?;

    Ok(ConstantPoolEntry::ConstantString {
        string_index,
    })
}

fn read_constant_fieldref<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let class_index = read_u16(file)?;
    let name_and_type_index = read_u16(file)?;

    Ok(ConstantPoolEntry::ConstantFieldref {
        class_index,
        name_and_type_index,
    })
}

fn read_constant_methodref<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let class_index = read_u16(file)?;
    let name_and_type_index = read_u16(file)?;

    Ok(ConstantPoolEntry::ConstantMethodref {
        class_index,
        name_and_type_index,
    })
}

fn read_constant_name_and_type<R: Read>(file: &mut R) -> io::Result<ConstantPoolEntry> {
    let name_index = read_u16(file)?;
    let descriptor_index = read_u16(file)?;

    Ok(ConstantPoolEntry::ConstantNameAndType {
        name_index,
        descriptor_index,
    })
}

fn read_interfaces<R: Read>(file: &mut R) -> io::Result<Vec<u16>> {
    let interfaces_count = i32::from(read_u16(file)?);

    let mut interfaces = Vec::<u16>::new();

    for _ in 0..interfaces_count {
        let entry = read_u16(file)?;

        interfaces.push(entry);
    }

    Ok(interfaces)
}

fn read_fields<R: Read>(file: &mut R) -> io::Result<Vec<Field>> {
    let fields_count = i32::from(read_u16(file)?);

    let mut fields = Vec::<Field>::new();

    for _ in 0..fields_count {
        let entry = read_field(file)?;

        fields.push(entry);
    }

    Ok(fields)
}

fn read_field<R: Read>(file: &mut R) -> io::Result<Field> {
    let access_flags = read_u16(file)?;
    let name_index = read_u16(file)?;
    let descriptor_index = read_u16(file)?;

    let attributes = read_attributes(file)?;

    let access_flags = promote_result_to_io(
        FieldAccess::from_access_flags(access_flags)
    )?;

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

fn read_methods<R: Read>(file: &mut R) -> io::Result<Vec<Method>> {
    let methods_count = i32::from(read_u16(file)?);

    let mut methods = Vec::<Method>::new();

    for _ in 0..methods_count {
        let entry = read_method(file)?;

        methods.push(entry);
    }

    Ok(methods)
}

fn read_method<R: Read>(file: &mut R) -> io::Result<Method> {
    let access_flags = read_u16(file)?;
    let name_index = read_u16(file)?;
    let descriptor_index = read_u16(file)?;

    let attributes = read_attributes(file)?;

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

pub fn read_attributes<R: Read>(file: &mut R) -> io::Result<Vec<Attribute>> {
    let attributes_count = read_u16(file)?;

    let mut attributes = Vec::<Attribute>::new();

    for _ in 0..attributes_count {
        let entry = read_attribute(file)?;

        attributes.push(entry);
    }

    Ok(attributes)
}

fn read_attribute<R: Read>(file: &mut R) -> io::Result<Attribute> {
    let attribute_name_index = read_u16(file)?;
    let attribute_length = read_u32(file)?;

    let info = read_n_bytes(file, attribute_length as usize)?;

    Ok(Attribute {
        attribute_name_index,
        info,
    })
}