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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Cursor;
use crate::headers::{SMXHeader, SectionEntry};
use crate::v1types::*;
use crate::rtti::{SMXRTTIListTable, RTTIMethod};
use crate::file::SMXFile;
use crate::errors::{Result, Error};

#[derive(Debug, Clone)]
pub struct BaseSection {
    pub header: Rc<SMXHeader>,
    pub section: Rc<SectionEntry>,
}

impl BaseSection {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Self {
        BaseSection {
            header,
            section,
        }
    }

    pub fn get_data(&self) -> Vec<u8> {
        self.header.data[self.section.data_offset as usize..(self.section.data_offset + self.section.size) as usize].to_vec()
    }
}

// The following tables conform to a nametable:
//   .names
//   .dbg.names
#[derive(Debug, Clone)]
pub struct SMXNameTable {
    base: BaseSection,

    names: HashMap<i32, String>,

    extends: Vec<i32>,
}

impl SMXNameTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Self {
        Self {
            base: BaseSection::new(header, section),
            names: HashMap::new(),
            extends: Vec::new(),
        }
    }

    fn compute_extends(&mut self) -> &Self {
        let mut last_index: i32 = 0;

        for i in 0..self.base.section.size {
            if self.base.header.data[(self.base.section.data_offset + i) as usize] == 0 {
                self.extends.push(last_index);
                last_index = i + 1;
            }
        }

        self
    }

    // Returns a list of all root indexes that map to strings.
    pub fn get_extends(&mut self) -> Vec<i32> {
        if self.extends.is_empty() {
            self.compute_extends();
        }

        self.extends.clone()
    }

    pub fn names(&self) -> HashMap<i32, String> {
        self.names.clone()
    }

    // Returns a string at a given index.
    pub fn string_at(&mut self, index: i32) -> Result<String> {
        if self.names.contains_key(&index) {
            return Ok(self.names.get(&index).unwrap().clone())
        }

        if index >= self.base.section.size {
            return Err(Error::InvalidIndex)
        }

        let mut str_vec = Vec::with_capacity(256);

        for i in index..self.base.section.size {
            if self.base.header.data[(self.base.section.data_offset + i) as usize] == 0 {
                break;
            }

            str_vec.push(self.base.header.data[(self.base.section.data_offset + i) as usize]);
        }

        let s = String::from_utf8_lossy(&str_vec[..]).into_owned();

        self.names.insert(index, s.clone());

        Ok(s)
    }
}

// The .natives table.
#[derive(Debug, Clone)]
pub struct SMXNativeTable {
    natives: Vec<NativeEntry>,
}

impl SMXNativeTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let natives = NativeEntry::new(&base.get_data(), section, names)?;

        Ok(Self {
            natives,
        })
    }

    // Return a copy of the natives vector
    pub fn entries(&self) -> Vec<NativeEntry> {
        self.natives.clone()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> NativeEntry {
        self.natives[index].clone()
    }

    pub fn size(&self) -> usize {
        self.natives.len()
    }
}

// The .publics table.
#[derive(Debug, Clone)]
pub struct SMXPublicTable {
    publics: Vec<PublicEntry>,
}

impl SMXPublicTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let publics = PublicEntry::new(base.get_data(), section, names)?;

        Ok(Self {
            publics,
        })
    }

    // Return a copy of the publics vector
    pub fn entries(&self) -> Vec<PublicEntry> {
        self.publics.clone()
    }

    pub fn entries_ref(&self) -> &Vec<PublicEntry> {
        self.publics.as_ref()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> PublicEntry {
        self.publics[index].clone()
    }

    pub fn size(&self) -> usize {
        self.publics.len()
    }
}

#[derive(Debug, Clone, Default)]
pub struct SMXCalledFunctionsTable {
    functions: Vec<CalledFunctionEntry>,
}

impl SMXCalledFunctionsTable{
    pub fn new() -> Self {
        Self {
            functions: Vec::new(),
        }
    }

    pub fn add_function(&mut self, addr: u32) {
        self.functions.push(CalledFunctionEntry {
            address: addr,
            name: format!("sub_{:x}", addr),
        })
    }

    // Return a copy of the publics vector
    pub fn entries(&self) -> Vec<CalledFunctionEntry> {
        self.functions.clone()
    }

    pub fn entries_ref(&self) -> &Vec<CalledFunctionEntry> {
        self.functions.as_ref()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> CalledFunctionEntry {
        self.functions[index].clone()
    }

    pub fn size(&self) -> usize {
        self.functions.len()
    }
}

// The .pubvars table.
#[derive(Debug, Clone)]
pub struct SMXPubvarTable {
    public_variables: Vec<PubvarEntry>,
}

impl SMXPubvarTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let public_variables = PubvarEntry::new(base.get_data(), section, names)?;

        Ok(Self {
            public_variables,
        })
    }

    // Return a copy of the publics vector
    pub fn entries(&self) -> Vec<PubvarEntry> {
        self.public_variables.clone()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> PubvarEntry {
        self.public_variables[index].clone()
    }

    pub fn size(&self) -> usize {
        self.public_variables.len()
    }
}

bitflags! {
    pub struct TagFlags: u32 {
        const FIXED = 0x4000_0000;
        const FUNCTION = 0x2000_0000;
        const OBJECT = 0x1000_0000;
        const ENUM = 0x0800_0000;
        const METHODMAP = 0x0400_0000;
        const STRUCT = 0x0200_0000;
    }
}

#[derive(Debug, Clone)]
pub struct Tag {
    entry: TagEntry,
}

impl Tag {
    pub fn new(entry: TagEntry) -> Self {
        Self {
            entry,
        }
    }

    pub fn id(&self) -> u32 {
        self.entry.tag & !TagEntry::FLAGMASK
    }

    pub fn value(&self) -> u32 {
        self.entry.tag
    }

    pub fn flags(&self) -> u32 {
        self.entry.tag & TagEntry::FLAGMASK
    }

    pub fn name(&self) -> String {
        self.entry.name.clone()
    }

    pub fn entry(&self) -> TagEntry {
        self.entry.clone()
    }
}

// The .tags table.
#[derive(Debug, Clone)]
pub struct SMXTagTable {
    tags: Vec<Tag>,

    cache: HashMap<u16, Tag>,
}

impl SMXTagTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let tags = TagEntry::new(base.get_data(), section, names)?;

        let mut tt = Self {
            tags: Vec::new(),
            cache: HashMap::new(),
        };

        for tag in tags {
            tt.tags.push(Tag::new(tag.to_owned()))
        }

        Ok(tt)
    }

    pub fn find_tag(&mut self, tag: u16) -> Option<Tag> {
        if self.cache.contains_key(&tag) {
            return Some(self.cache.get(&tag).unwrap().clone());
        }

        let mut found: Option<Tag> = None;

        for i in 0..self.tags.len() {
            if self.tags[i].id() as u16 == tag {
                found = Some(self.tags[i].clone());
                break;
            }
        }

        if let Some(v) = &found {
            self.cache.insert(tag, v.clone());
        }

        found
    }


    // Return a copy of the tag vector
    pub fn entries(&self) -> Vec<Tag> {
        self.tags.clone()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> Tag {
        self.tags[index].clone()
    }

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

    pub fn is_empty(&self) -> bool {
        self.tags.is_empty()
    }
}

// The .data section.
#[derive(Debug, Clone)]
pub struct SMXDataSection{
    base: BaseSection,

    data_header: DataHeader,
}

impl SMXDataSection {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let data_header = DataHeader::new(base.get_data())?;

        Ok(Self {
            base,
            data_header,
        })
    }

    pub fn get_data_vec(&self) -> Vec<u8> {
        let start = self.base.section.data_offset as u32 + self.data_header.data_offset;

        Vec::from(&self.base.header.data[start as usize..(start + self.data_header.data_size) as usize])
    }

    pub fn header(&self) -> DataHeader {
        self.data_header.clone()
    }
}

// The .code section.
#[derive(Debug, Clone)]
pub struct SMXCodeV1Section{
    base: BaseSection,

    code_header: CodeV1Header,
}

impl SMXCodeV1Section {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let code_header = CodeV1Header::new(base.get_data())?;

        Ok(Self {
            base,
            code_header,
        })
    }

    pub fn get_data_vec(&self) -> Vec<u8> {
        let start = self.base.section.data_offset + self.code_header.code_offset;

        Vec::from(&self.base.header.data[start as usize..(start + self.code_header.code_size) as usize])
    }

    pub fn header(&self) -> CodeV1Header {
        self.code_header.clone()
    }

    // Compute an absolute offset to where the code stream begins.
    pub fn code_start(&self) -> i32 {
        self.base.section.data_offset + self.code_header.code_offset
    }
}

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

impl SMXDebugInfoSection {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let info = DebugInfoHeader::new(base.get_data())?;

        Ok(Self {
            info,
        })
    }

    pub fn file_count(&self) -> i32 {
        self.info.file_count
    }

    pub fn line_count(&self) -> i32 {
        self.info.line_count
    }

    pub fn symbol_count(&self) -> i32 {
        self.info.symbol_count
    }

    pub fn array_count(&self) -> i32 {
        self.info.array_count
    }
}

// The .dbg.files table.
#[derive(Debug, Clone)]
pub struct SMXDebugFilesTable {
    entries: Vec<DebugFileEntry>,
}

impl SMXDebugFilesTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>, names: Rc<RefCell<SMXNameTable>>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let entries = DebugFileEntry::new(base.get_data(), section, names)?;

        Ok(Self {
            entries,
        })
    }

    pub fn find_file(&self, addr: u32) -> Option<String> {
        let mut high = self.len() as i32;
        let mut low = -1;

        while high - low > 1 {
            let mid = (low + high) / 2;

            if self.entries[mid as usize].address <= addr {
                low = mid;
            } else {
                high = mid;
            }
        }

        if low == -1 {
            return None;
        }

        Some(self.entries[low as usize].name.clone())
    }

    // Return a copy of the tag vector
    pub fn entries(&self) -> Vec<DebugFileEntry> {
        self.entries.clone()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> DebugFileEntry {
        self.entries[index].clone()
    }

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

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// The .dbg.lines table.
#[derive(Debug, Clone)]
pub struct SMXDebugLinesTable {
    entries: Vec<DebugLineEntry>,
}

impl SMXDebugLinesTable {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let entries = DebugLineEntry::new(base.get_data(), section)?;

        Ok(Self {
            entries,
        })
    }

    pub fn find_file(&self, addr: u32) -> Option<u32> {
        let mut high = self.len() as i32;
        let mut low = -1;

        while high - low > 1 {
            let mid = (low + high) / 2;

            if self.entries[mid as usize].address <= addr {
                low = mid;
            } else {
                high = mid;
            }
        }

        if low == -1 {
            return None;
        }

        Some(self.entries[low as usize].line + 1)
    }

    // Return a copy of the tag vector
    pub fn entries(&self) -> Vec<DebugLineEntry> {
        self.entries.clone()
    }

    // Return immutable cloned copy at index
    pub fn get_entry(&self, index: usize) -> DebugLineEntry {
        self.entries[index].clone()
    }

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

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

#[derive(Debug, Clone)]
pub struct SMXDebugMethods {
    entries: Vec<DebugMethodEntry>,
}

impl SMXDebugMethods {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let mut rtti = SMXRTTIListTable::new(header, section);

        let mut data = Cursor::new(base.get_data());

        rtti.init(&mut data)?;

        let mut entries: Vec<DebugMethodEntry> = Vec::with_capacity(rtti.row_count() as usize);

        for _ in 0..rtti.row_count() {
            entries.push(DebugMethodEntry::new(&mut data)?)
        }

        Ok(Self {
            entries,
        })
    }

    pub fn entries(&self) -> Vec<DebugMethodEntry> {
        self.entries.clone()
    }

    pub fn entries_ref(&self) -> &Vec<DebugMethodEntry> {
        self.entries.as_ref()
    }

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

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}


#[derive(Debug, Clone)]
pub struct SMXDebugSymbols {
    entries: Vec<DebugVarEntry>,

    address_sorted: Vec<DebugVarEntry>,
}

impl SMXDebugSymbols {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        let base = BaseSection::new(Rc::clone(&header), Rc::clone(&section));
        let mut rtti = SMXRTTIListTable::new(header, section);

        let mut data = Cursor::new(base.get_data());

        rtti.init(&mut data)?;

        let mut entries: Vec<DebugVarEntry> = Vec::with_capacity(rtti.row_count() as usize);

        for _ in 0..rtti.row_count() {
            entries.push(DebugVarEntry::new(&mut data)?)
        }

        Ok(Self {
            entries,
            address_sorted: Vec::with_capacity(rtti.row_count() as usize),
        })
    }

    pub fn ensure_sorted_addresses(&mut self) -> &Self {
        if !self.address_sorted.is_empty() {
            return self
        }

        self.address_sorted.sort_by(|a, b| b.address.cmp(&a.address));

        self
    }

    pub fn entries(&self) -> Vec<DebugVarEntry> {
        self.entries.clone()
    }

    pub fn entries_ref(&self) -> &Vec<DebugVarEntry> {
        self.entries.as_ref()
    }

    pub fn entries_len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_entry_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn address_sorted(&self) -> Vec<DebugVarEntry> {
        self.address_sorted.clone()
    }
}

#[derive(Debug, Clone)]
pub struct SMXDebugGlobals {
    debug_symbols: SMXDebugSymbols,
}

impl SMXDebugGlobals {
    pub fn new(header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        Ok(Self {
            debug_symbols: SMXDebugSymbols::new(Rc::clone(&header), Rc::clone(&section))?,
        })
    }

    pub fn find_global(&mut self, addr: i32) -> Option<DebugVarEntry> {
        self.debug_symbols.ensure_sorted_addresses();

        for i in 0..self.debug_symbols.address_sorted.len() {
            let sym = &self.debug_symbols.address_sorted[i];

            if sym.address == addr {
                return Some(sym.clone())
            }

            if addr < sym.address {
                break;
            }

            if i == self.debug_symbols.address_sorted.len() -1 {
                break;
            }

            let next_sym = &self.debug_symbols.address_sorted[i + 1];

            if addr > sym.address && addr < next_sym.address {
                return Some(sym.clone())
            }
        }

        None
    }

    pub fn symbol_entries(&self) -> Vec<DebugVarEntry> {
        self.debug_symbols.entries()
    }
}

#[derive(Clone)]
pub struct SMXDebugLocals {
    file: Rc<RefCell<SMXFile>>,
    debug_symbols: SMXDebugSymbols,
}

impl SMXDebugLocals {
    pub fn new(file: Rc<RefCell<SMXFile>>, header: Rc<SMXHeader>, section: Rc<SectionEntry>) -> Result<Self> {
        Ok(Self {
            file,
            debug_symbols: SMXDebugSymbols::new(Rc::clone(&header), Rc::clone(&section))?,
        })
    }

    pub fn find_local(&self, code_addr: i32, addr: i32) -> Option<DebugVarEntry> {
        let mut start_at: i32 = 0;
        let mut stop_at: i32 = self.debug_symbols.entries_len() as i32;

        if self.file.borrow().debug_methods.is_some() && self.file.borrow().rtti_methods.is_some() {
            let mut index: Option<usize> = None;

            for i in 0..self.file.borrow().debug_methods.as_ref().unwrap().len() {
                let f = self.file.borrow();
                let method_index: i32 = f.debug_methods.as_ref().unwrap().entries_ref()[i as usize].method_index;
                let method: &RTTIMethod = &f.rtti_methods.as_ref().unwrap().methods_ref()[method_index as usize];

                if code_addr > method.pcode_start && code_addr < method.pcode_end {
                    index = Some(i as usize);
                    break;
                }
            }

            if let Some(i) = index {
                start_at = self.file.borrow().debug_methods.as_ref().unwrap().entries_ref()[i].first_local;

                if i != self.file.borrow().debug_methods.as_ref().unwrap().len() - 1 {
                    stop_at = self.file.borrow().debug_methods.as_ref().unwrap().entries_ref()[i + 1].first_local;
                }
            }
        }

        for i in start_at..stop_at {
            let sym: DebugVarEntry = self.debug_symbols.entries_ref()[i as usize].clone();

            if code_addr < sym.code_start || code_addr >= sym.code_end {
                continue;
            }

            if sym.address == addr {
                return Some(sym);
            }

            if i == stop_at - 1 {
                break;
            }

            let next_sym: DebugVarEntry = self.debug_symbols.entries_ref()[(i + 1) as usize].clone();

            if addr > sym.address && addr < next_sym.address {
                return Some(sym);
            }
        }

        None
    }

    pub fn symbol_entries(&self) -> Vec<DebugVarEntry> {
        self.debug_symbols.entries()
    }
}