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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt;
use std::io::{Cursor};
use byteorder::{ReadBytesExt, LittleEndian};
use crate::headers::{SectionEntry};
use crate::sections::{SMXNameTable};
use crate::errors::{Result, Error};

bitflags! {
    pub struct CodeV1Flags: u16 {
        const DEBUG = 0x0000_0001;
    }
}

// The ".code" section.
#[derive(Debug, Clone)]
pub struct CodeV1Header {
    // Size of the code blob.
    pub code_size: i32,

    // Size of a cell in bytes (always 4).
    pub cell_size: u8,

    // Code version (see above constants).
    pub code_version: u8,

    // Flags (see above).
    pub flags: CodeV1Flags,

    // Offset within the code blob to the entry point function.
    pub main_offset: i32,

    // Offset to the code section.
    pub code_offset: i32,

    // This field is only guaranteed to be present when codeversion >= 13 or
    // higher. Note that newer spcomp versions will still include a 0-filled
    // value. This is legal since anything between the end of the code header
    // and the code buffer is undefined. The field should still be ignored.
    pub features: i32,
}

impl CodeV1Header {
    pub const SIZE: i32 = 16;

    pub const VERSION_JIT1: u8 = 9;
    pub const VERSION_JIT2: u8 = 10;

    pub fn new<T>(data: T) -> Result<Self>
    where
        T: AsRef<[u8]>
    {
        let mut cursor = Cursor::new(data);

        let code_size = cursor.read_i32::<LittleEndian>()?;
        let cell_size = cursor.read_u8()?;
        let code_version = cursor.read_u8()?;
        let flags = cursor.read_u16::<LittleEndian>()?;
        let main_offset = cursor.read_i32::<LittleEndian>()?;
        let code_offset = cursor.read_i32::<LittleEndian>()?;

        Ok(Self {
            code_size,
            cell_size,
            code_version,
            flags: CodeV1Flags::from_bits_truncate(flags),
            main_offset,
            code_offset,
            features: {
                if code_version >= 13 {
                    cursor.read_i32::<LittleEndian>()?;
                }

                0
            }
        })
    }
}

// The ".data" section.
#[derive(Debug, Clone)]
pub struct DataHeader {
    // Size of the data blob.
    pub data_size: u32,

    // Amount of memory the plugin runtime requires.
    pub memory_size: u32,

    // Offset within this section to the data blob.
    pub data_offset: u32,
}

impl DataHeader {
    pub const SIZE: i32 = 12;

    pub fn new<T>(data: T) -> Result<Self>
    where
        T: AsRef<[u8]>,
    {
        let mut cursor = Cursor::new(data);

        Ok(Self {
            data_size: cursor.read_u32::<LittleEndian>()?,
            memory_size: cursor.read_u32::<LittleEndian>()?,
            data_offset: cursor.read_u32::<LittleEndian>()?,
        })
    }
}

// The ".publics" section.
#[derive(Debug, Clone)]
pub struct PublicEntry {
    // Offset into the code section.
    pub address: u32,

    // Offset into the .names section.
    pub name_offset: i32,

    // Computed.
    pub name: String,
}

impl PublicEntry {
    pub const SIZE: i32 = 8;

    pub fn new<T>(data: T, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size & Self::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / Self::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let address = cursor.read_u32::<LittleEndian>()?;
            let name_offset = cursor.read_i32::<LittleEndian>()?;

            entries.push(Self {
                address,
                name_offset,
                name: names.borrow_mut().string_at(name_offset)?,
            })
        }

        Ok(entries)
    }
}

#[derive(Debug, Clone)]
pub struct CalledFunctionEntry {
    pub address: u32,

    pub name: String,
}

// The ".natives" section.
#[derive(Debug, Clone)]
pub struct NativeEntry {
    // Offset into the .names section.
    pub name_offset: i32,

    // Computed name.
    pub name: String,
}

impl NativeEntry {
    pub const SIZE: i32 = 4;

    pub fn new<T>(data: T, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size % Self::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / Self::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let name_offset = cursor.read_i32::<LittleEndian>()?;

            entries.push(Self {
                name_offset,
                name: names.borrow_mut().string_at(name_offset)?,
            })
        }

        Ok(entries)
    }
}

// The ".pubvars" section.
#[derive(Debug, Clone)]
pub struct PubvarEntry {
    // Offset into the data section.
    pub address: u32,

    // Offset into the .names section.
    pub name_offset: i32,

    // Computed name.
    pub name: String,
}

impl PubvarEntry {
    pub const SIZE: i32 = 8;

    pub fn new<T>(data: T, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size % Self::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / Self::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let address = cursor.read_u32::<LittleEndian>()?;
            let name_offset = cursor.read_i32::<LittleEndian>()?;

            entries.push(Self {
                address,
                name_offset,
                name: names.borrow_mut().string_at(name_offset)?,
            })
        }

        Ok(entries)
    }
}

// The ".tags" section.
#[derive(Debug, Clone)]
pub struct TagEntry {
    // Tag ID from the compiler.
    pub tag: u32,

    // Offset into the .names section.
    pub name_offset: i32,

    // Computed name.
    pub name: String,
}

impl TagEntry {
    pub const SIZE: i32 = 8;

    // Various tags that can be on a tag id.
    pub const FIXED: u32 = 0x4000_0000;
    pub const FUNC: u32 = 0x2000_0000;
    pub const OBJECT: u32 = 0x1000_0000;
    pub const ENUM: u32 = 0x0800_0000;
    pub const METHODMAP: u32 = 0x0400_0000;
    pub const STRUCT: u32 = 0x0200_0000;
    pub const FLAGMASK: u32 = 
        Self::FIXED |
        Self:: FUNC |
        Self::OBJECT |
        Self::ENUM |
        Self::METHODMAP |
        Self::STRUCT;

    pub fn new<T>(data: T, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size % NativeEntry::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / NativeEntry::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let tag = cursor.read_u32::<LittleEndian>()?;
            let name_offset = cursor.read_i32::<LittleEndian>()?;

            entries.push(Self {
                tag,
                name_offset,
                name: names.borrow_mut().string_at(name_offset)?,
            })
        }

        Ok(entries)
    }
}

// The ".dbg.info" section.
#[derive(Debug, Clone)]
pub struct DebugInfoHeader {
    pub file_count: i32,

    pub line_count: i32,

    pub symbol_count: i32,

    pub array_count: i32,
}

impl DebugInfoHeader {
    pub fn new<T>(data: T) -> Result<Self>
    where
        T: AsRef<[u8]>,
    {
        let mut cursor = Cursor::new(data);

        Ok(Self {
            file_count: cursor.read_i32::<LittleEndian>()?,
            line_count: cursor.read_i32::<LittleEndian>()?,
            symbol_count: cursor.read_i32::<LittleEndian>()?,
            array_count: cursor.read_i32::<LittleEndian>()?,
        })
    }
}

// The ".dbg.files" section.
#[derive(Debug, Clone)]
pub struct DebugFileEntry {
    // Offset into the data section.
    pub address: u32,

    // Offset into the .names section.
    pub name_offset: i32,

    // Computed name.
    pub name: String,
}

impl DebugFileEntry {
    pub const SIZE: i32 = 8;

    pub fn new<T>(data: T, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size % Self::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / Self::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let address = cursor.read_u32::<LittleEndian>()?;
            let name_offset = cursor.read_i32::<LittleEndian>()?;

            entries.push(Self {
                address,
                name_offset,
                name: names.borrow_mut().string_at(name_offset)?,
            })
        }

        Ok(entries)
    }
}

// The ".dbg.lines" section.
#[derive(Debug, Clone)]
pub struct DebugLineEntry {
    // Offset into the data section.
    pub address: u32,

    // Line number.
    pub line: u32,
}

impl DebugLineEntry {
    pub const SIZE: i32 = 8;

    pub fn new<T>(data: T, section: Rc<SectionEntry>) -> Result<Vec<Self>>
    where
        T: AsRef<[u8]>,
    {
        if section.size % Self::SIZE != 0 {
            return Err(Error::InvalidSize)
        }

        let count: usize = (section.size / Self::SIZE) as usize;

        let mut entries: Vec<Self> = Vec::with_capacity(count);

        let mut cursor = Cursor::new(data);

        for _ in 0..count {
            let address = cursor.read_u32::<LittleEndian>()?;
            let line = cursor.read_u32::<LittleEndian>()?;

            entries.push(Self {
                address,
                line,
            })
        }

        Ok(entries)
    }
}

#[derive(Debug, Clone)]
pub enum SymbolScope {
    Global,
    Local,
    Static,
    Arg,
    Unknown,
}

impl From<u8> for SymbolScope {
    fn from(s: u8) -> Self {
        match s {
            0 => Self::Global,
            1 => Self::Local,
            2 => Self::Static,
            3 => Self::Arg,
            _ => Self::Unknown,
        }
    }
}

impl fmt::Display for SymbolScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SymbolScope::Global => writeln!(f, "Global"),
            SymbolScope::Local => writeln!(f, "Local"),
            SymbolScope::Static => writeln!(f, "Static"),
            SymbolScope::Arg => writeln!(f, "Arg"),
            SymbolScope::Unknown => writeln!(f, "Unknown"),
        }
    }
}

// The ".dbg.methods" section.
#[derive(Debug, Clone)]
pub struct DebugMethodEntry {
    pub method_index: i32,

    pub first_local: i32,
}

impl DebugMethodEntry {
    pub fn new(cursor: &mut Cursor<Vec<u8>>) -> Result<Self> {
        Ok(Self {
            method_index: cursor.read_i32::<LittleEndian>()?,
            first_local: cursor.read_i32::<LittleEndian>()?,
        })
    }
}

// The ".dbg.globals"  and ".dbg.locals" section.
#[derive(Debug, Clone)]
pub struct DebugVarEntry {
    pub address: i32,

    pub scope: SymbolScope,

    pub name_offset: i32,

    pub code_start: i32,

    pub code_end: i32,

    pub type_id: i32,
}

impl DebugVarEntry {
    pub fn new(cursor: &mut Cursor<Vec<u8>>) -> Result<Self>
    {
        Ok(Self {
            address: cursor.read_i32::<LittleEndian>()?,
            scope: SymbolScope::from(cursor.read_u8()? & 3),
            name_offset: cursor.read_i32::<LittleEndian>()?,
            code_start: cursor.read_i32::<LittleEndian>()?,
            code_end: cursor.read_i32::<LittleEndian>()?,
            type_id: cursor.read_i32::<LittleEndian>()?,
        })
    }
}