spimdisasm 2.0.0-alpha.1

MIPS disassembler
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
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
/* SPDX-FileCopyrightText: © 2024-2025 Decompollaborate */
/* SPDX-License-Identifier: MIT */

use alloc::sync::Arc;
use core::{fmt, hash::Hash};
use rabbitizer::access_type::AccessType;

//#[cfg(feature = "pyo3")]
//use pyo3::prelude::*;

use crate::{
    addresses::{Rom, Size, Vram},
    collections::{addended_ordered_map::SizedValue, unordered_map::UnorderedMap},
    config::Compiler,
    section_type::SectionType,
};

use super::{
    ParentSectionMetadata, ReferrerInfo, Referrers, SymbolMetadataNameDisplay,
    SymbolNameGenerationSettings, SymbolType,
};

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub /*(crate)*/ enum GeneratedBy {
    /// This symbol was automatically generated by the disassembler
    Autogenerated,
    /// Declared externally by the user, but it may have not been found yet
    UserDeclared,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct StringInfo {
    is_maybe_string: bool,
    failed_string_decoding: bool,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum GotAccessKind {
    Local,
    Global,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct GotInfo {
    access_kind: GotAccessKind,
    got_index: Option<usize>, // TODO: maybe remove Option?
}

impl GotInfo {
    pub fn access_kind(&self) -> GotAccessKind {
        self.access_kind
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum RodataMigrationBehavior {
    /// Let spimdisasm handle if it should migrate this rodata symbol.
    Default,

    /// Ignore rules for migrating rodata and force migration of this symbol to any
    /// function which references it.
    ForceMigrate,
    /// Ignore rules for migrating rodata and prevent migration of this symbol to
    /// any function which references it.
    ForceNotMigrate,

    /// Force migrating to the function that matches the specified name.
    ///
    /// Overrides all logic for determining if this symbol should be migrated or
    /// not and to which function should be migrated.
    ///
    /// This can be specially useful for unreferenced symbols that should be
    /// defined in-between actually referenced symbols.
    ///
    /// This field is ignored if applied on anything that is not a rodata symbol.
    ///
    /// WARNING: It is undefined behavior if during rodata migration the listed
    /// function does not exists on the given text section. For example this symbol
    /// may get lost in limbo.
    MigrateToSpecificFunction(Arc<str>),
}

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

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum OwnerSegmentKind {
    Global,
    // The string corresponds to the name of the segment.
    Overlay(Arc<str>),
    Unknown,
    User,
}

impl OwnerSegmentKind {
    pub fn is_unknown_segment(&self) -> bool {
        matches!(self, OwnerSegmentKind::Unknown)
    }
}

#[derive(Clone)]
#[allow(dead_code)]
pub struct SymbolMetadata {
    generated_by: GeneratedBy,
    vram: Vram,
    owner_segment_kind: OwnerSegmentKind,
    symbol_name_generation_settings: SymbolNameGenerationSettings,
    rom: Option<Rom>,

    user_declared_name: Option<Arc<str>>,
    user_declared_name_end: Option<Arc<str>>,

    // TODO: Is this still necessary?
    /// Used to register a name of a symbol which may change in the future.
    ///
    /// The only parameter is the ContextSymbol itself, and it should return a string containing the name of the symbol.
    ///
    /// Used by .get_name() instead of using the setted name or the default generated name.
    // name_get_callback: Option<Box<dyn FnOnce(&SymbolMetadata) -> String>>,
    user_declared_size: Option<Size>,
    autodetected_size: Option<Size>,

    user_declared_type: Option<SymbolType>,
    autodetected_type: Option<SymbolType>,

    section_type: Option<SectionType>,

    /// This symbol exists (was found) in any of the analyzed sections
    is_defined: bool,

    // TODO: merge these two
    access_types: UnorderedMap<AccessType, u32>,

    c_string_info: Option<StringInfo>,
    // pascal_string_info: Option<StringInfo>,
    // TODO
    // sym_creators: Referrers,
    sym_referrers: Referrers,

    // TODO: how to reimplement these crossreferences?
    // parentFunction: ContextSymbol|None = None
    // "Parent function for branch labels, jump tables, and jump table labels"
    // branchLabels: SortedDict[ContextSymbol] = dataclasses.field(default_factory=SortedDict)
    // "For functions, the branch and jump table labels which are contained in this function"
    // jumpTables: SortedDict[ContextSymbol] = dataclasses.field(default_factory=SortedDict)
    // "For functions, the jump tables which are contained in this function"

    // parentFileName: str|None = None
    // "Name of the file containing this symbol"
    // inFileOffset: int|None = None
    // "Offset relative to the start of the file"

    //
    got_info: Option<GotInfo>,

    accessed_as_gp_rel: bool,

    // _isStatic: bool = False

    // TODO: These two are kinda redundant
    auto_created_pad_by: Option<Vram>,

    // firstLoAccess: int|None = None

    // isElfNotype: bool = False

    //
    rodata_migration_behavior: RodataMigrationBehavior,

    allow_ref_with_addend: bool,
    /*
    allowedToReferenceAddends: bool = False
    notAllowedToReferenceAddends: bool = False

    allowedToReferenceConstants: bool = False
    notAllowedToReferenceConstants: bool = False

    allowedToReferenceSymbols: bool = True
    """
    Allow or prohibit this symbol to reference other symbols.
    """

    allowedToBeReferenced: bool = True
    """
    Allow or prohibit this symbol to be referenced by other symbols.
    """
    */
    is_mips1_double: bool,

    visibility: Option<Arc<str>>,

    compiler: Option<Compiler>,
    parent_metadata: Option<ParentSectionMetadata>,

    trailing_padding_size: Option<Size>,

    add_gp_to_pointed_data: bool,
}

impl SymbolMetadata {
    pub(crate) fn new(
        generated_by: GeneratedBy,
        vram: Vram,
        owner_segment_kind: OwnerSegmentKind,
        symbol_name_generation_settings: SymbolNameGenerationSettings,
    ) -> Self {
        Self {
            generated_by,
            vram,
            owner_segment_kind,
            symbol_name_generation_settings,

            rom: None,

            user_declared_name: None,
            user_declared_name_end: None,

            user_declared_size: None,
            autodetected_size: None,
            user_declared_type: None,
            autodetected_type: None,

            section_type: None,

            is_defined: false,

            access_types: UnorderedMap::new(),
            c_string_info: None,
            // pascal_string_info: None,
            sym_referrers: Referrers::new(),
            // name_get_callback: None,
            got_info: None,
            accessed_as_gp_rel: false,
            auto_created_pad_by: None,
            rodata_migration_behavior: RodataMigrationBehavior::Default,
            allow_ref_with_addend: true,
            is_mips1_double: false,
            visibility: None,

            compiler: None,
            parent_metadata: None,

            trailing_padding_size: None,

            add_gp_to_pointed_data: false,
        }
    }

    pub fn generated_by(&self) -> GeneratedBy {
        self.generated_by
    }

    pub const fn vram(&self) -> Vram {
        self.vram
    }

    pub fn symbol_name_generation_settings(&self) -> &SymbolNameGenerationSettings {
        &self.symbol_name_generation_settings
    }
    pub(crate) fn symbol_name_generation_settings_mut(
        &mut self,
    ) -> &mut SymbolNameGenerationSettings {
        &mut self.symbol_name_generation_settings
    }

    pub fn rom(&self) -> Option<Rom> {
        self.rom
    }
    pub(crate) fn rom_mut(&mut self) -> &mut Option<Rom> {
        &mut self.rom
    }

    pub fn display_name(&self) -> SymbolMetadataNameDisplay<'_> {
        SymbolMetadataNameDisplay::new(self)
    }

    pub(crate) fn user_declared_name(&self) -> Option<Arc<str>> {
        self.user_declared_name.clone()
    }
    pub(crate) fn set_user_declared_name(&mut self, name: Arc<str>) {
        self.user_declared_name = Some(name);
    }

    pub(crate) fn set_user_declared_name_end(&mut self, name: Arc<str>) {
        self.user_declared_name_end = Some(name);
    }

    pub fn user_declared_size(&self) -> Option<Size> {
        self.user_declared_size
    }
    pub(crate) fn user_declared_size_mut(&mut self) -> &mut Option<Size> {
        &mut self.user_declared_size
    }
    pub fn autodetected_size(&self) -> Option<Size> {
        self.autodetected_size
    }
    pub(crate) fn autodetected_size_mut(&mut self) -> &mut Option<Size> {
        &mut self.autodetected_size
    }
    pub fn size(&self) -> Option<Size> {
        // TODO

        if let Some(siz) = self.user_declared_size {
            return Some(siz);
        }
        if let Some(siz) = self.autodetected_size {
            return Some(siz);
        }

        // TODO: Infer size based on user-declared type

        // TODO: Infer size based on instruction access type

        None
    }

    pub fn sym_type(&self) -> Option<SymbolType> {
        if let Some(t) = self.user_declared_type {
            Some(t)
        } else {
            self.autodetected_type()
        }
    }
    pub fn user_declared_type(&self) -> Option<SymbolType> {
        self.user_declared_type
    }
    pub fn autodetected_type(&self) -> Option<SymbolType> {
        if let Some(t) = self.autodetected_type {
            Some(t)
        } else if self.access_types.len() == 1 {
            SymbolType::from_access_type(
                *self
                    .access_types
                    .iter()
                    .next()
                    .expect("Should not panic since we already checked its length")
                    .0,
            )
        } else {
            None
        }
    }
    pub(crate) fn set_type(&mut self, new_type: SymbolType, generated_by: GeneratedBy) {
        match generated_by {
            GeneratedBy::Autogenerated => self.autodetected_type = Some(new_type),
            GeneratedBy::UserDeclared => self.user_declared_type = Some(new_type),
        }
    }

    pub fn section_type(&self) -> Option<SectionType> {
        self.section_type
    }
    pub(crate) fn section_type_mut(&mut self) -> &mut Option<SectionType> {
        &mut self.section_type
    }

    pub fn is_defined(&self) -> bool {
        self.is_defined
    }
    pub(crate) fn set_defined(&mut self) {
        self.is_defined = true;
    }

    pub fn all_access_types(&self) -> &UnorderedMap<AccessType, u32> {
        &self.access_types
    }
    pub(crate) fn set_access_type(&mut self, access_type: (AccessType, bool)) {
        *self.access_types.entry(access_type.0).or_default() += 1;
    }

    /// How much this symbol is referenced by something else
    pub fn reference_counter(&self) -> usize {
        self.sym_referrers.reference_counter()
    }
    pub fn sym_referrers(&self) -> &Referrers {
        &self.sym_referrers
    }
    pub(crate) fn add_referenced_info(&mut self, referrer: ReferrerInfo) {
        self.sym_referrers.add(referrer);
    }

    pub fn owner_segment_kind(&self) -> &OwnerSegmentKind {
        &self.owner_segment_kind
    }

    pub fn got_info(&self) -> Option<&GotInfo> {
        self.got_info.as_ref()
    }
    pub(crate) fn set_got_access_kind(&mut self, kind: GotAccessKind) {
        if let Some(got_info) = &mut self.got_info {
            got_info.access_kind = kind;
        } else {
            self.got_info = Some(GotInfo {
                access_kind: kind,
                got_index: None,
            });
        }
    }

    pub(crate) fn autogenerated_pad_info(&self) -> Option<AutogeneratedPadInfo> {
        if self.reference_counter() == 0 && self.generated_by == GeneratedBy::Autogenerated {
            match self.auto_created_pad_by {
                None => {
                    if self.owner_segment_kind == OwnerSegmentKind::Global {
                        Some(AutogeneratedPadInfo::Unreferenced)
                    } else {
                        None
                    }
                }
                Some(vram) => Some(AutogeneratedPadInfo::CreatedBy(vram)),
            }
        } else {
            None
        }
    }
    pub(crate) fn set_auto_created_pad_by(&mut self, vram: Vram) {
        self.auto_created_pad_by = Some(vram);
    }

    #[must_use]
    pub fn rodata_migration_behavior(&self) -> &RodataMigrationBehavior {
        &self.rodata_migration_behavior
    }
    #[must_use]
    pub(crate) fn rodata_migration_behavior_mut(&mut self) -> &mut RodataMigrationBehavior {
        &mut self.rodata_migration_behavior
    }

    pub fn allow_ref_with_addend(&self) -> bool {
        self.allow_ref_with_addend
    }
    pub(crate) fn set_allow_ref_with_addend(&mut self, val: bool) {
        self.allow_ref_with_addend = val;
    }

    pub fn visibility(&self) -> Option<Arc<str>> {
        self.visibility.clone()
    }
    pub(crate) fn set_visibility(&mut self, visibility: Arc<str>) {
        self.visibility = Some(visibility)
    }

    pub(crate) fn compiler(&self) -> Option<Compiler> {
        self.compiler
    }
    pub(crate) fn set_compiler(&mut self, compiler: Compiler) {
        self.compiler = Some(compiler);
    }

    pub(crate) fn parent_metadata(&self) -> Option<&ParentSectionMetadata> {
        self.parent_metadata.as_ref()
    }
    pub(crate) fn set_parent_metadata(&mut self, parent_metadata: ParentSectionMetadata) {
        self.parent_metadata = Some(parent_metadata);
    }

    pub fn trailing_padding_size(&self) -> Option<Size> {
        self.trailing_padding_size
    }
    pub(crate) fn set_trailing_padding_size(&mut self, size: Size) {
        self.trailing_padding_size = Some(size);
    }

    #[must_use]
    pub(crate) fn add_gp_to_pointed_data(&self) -> bool {
        self.add_gp_to_pointed_data
    }
    pub(crate) fn set_add_gp_to_pointed_data(&mut self) {
        self.add_gp_to_pointed_data = true;
    }
}

impl SymbolMetadata {
    pub(crate) fn is_trustable_function(&self) -> bool {
        // """Checks if the function symbol should be trusted based on the current disassembler settings"""

        /*
        if self.unknownSegment:
            return False

        if self.isGotLocal:
            return False

        if self.isAutocreatedSymFromOtherSizedSym:
            return True
        */

        match self.sym_type() {
            Some(SymbolType::Function) => true,
            None => {
                // Users may not type the symbol as a function.
                self.generated_by() == GeneratedBy::UserDeclared
            }
            Some(_) => false,
        }
        /*
        currentType = self.getTypeSpecial()

        if self.isUserDeclared:
            if currentType == SymbolSpecialType.branchlabel:
                return False
            return True

        if self.isAutogenerated and currentType == SymbolSpecialType.function:
            return True

        if rsp:
            return True

        return False
        */
    }

    fn is_maybe_const_variable(&self) -> bool {
        if self.section_type != Some(SectionType::Rodata) {
            return false;
        }

        if let Some(sym_type) = self.sym_type() {
            match sym_type {
                SymbolType::Function => false,
                SymbolType::Jumptable => false,
                SymbolType::GccExceptTable => false,
                SymbolType::Byte => true,
                SymbolType::Short => true,
                SymbolType::Word => true,
                SymbolType::DWord => true,
                SymbolType::Float32 => {
                    if let (Some(size), Some(padding)) = (self.size(), self.trailing_padding_size())
                    {
                        // Check if we have more than a single float here. If that's the case, then
                        // let's say it is a const variable instead of a float literal.
                        size != padding + Size::new(4)
                    } else {
                        false
                    }
                }
                SymbolType::Float64 => {
                    if let (Some(size), Some(padding)) = (self.size(), self.trailing_padding_size())
                    {
                        // Check if we have more than a single double here. If that's the case, then
                        // let's say it is a const variable instead of a double literal.
                        size != padding + Size::new(8)
                    } else {
                        false
                    }
                }
                SymbolType::CString => false,
                SymbolType::VirtualTable => true,
                SymbolType::UserCustom => !self.compiler.is_some_and(|x| x.forbids_const_structs()),
            }
        } else {
            true
        }
    }

    pub(crate) fn is_late_rodata(&self) -> bool {
        self.sym_type()
            .is_some_and(|x| x.is_late_rodata(self.compiler))
    }

    pub(crate) fn is_migrable(&self) -> bool {
        match self.rodata_migration_behavior {
            RodataMigrationBehavior::MigrateToSpecificFunction(_) => true,
            RodataMigrationBehavior::ForceMigrate => true,
            RodataMigrationBehavior::ForceNotMigrate => false,
            RodataMigrationBehavior::Default => {
                if self.is_mips1_double {
                    true
                } else if !self.sym_referrers.reference_symbols().is_empty()
                    || self.sym_referrers.reference_functions().len() > 1
                {
                    false
                } else if self.is_maybe_const_variable() {
                    self.compiler.is_some_and(|x| x.allow_rdata_migration())
                } else {
                    true
                }
            }
        }
    }
}

impl PartialEq for SymbolMetadata {
    fn eq(&self, other: &Self) -> bool {
        self.vram == other.vram && self.rom == other.rom
    }
}
impl PartialOrd for SymbolMetadata {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        match self.vram.partial_cmp(&other.vram) {
            Some(core::cmp::Ordering::Equal) => {}
            ord => return ord,
        };
        self.rom.partial_cmp(&other.rom)
    }
}
impl Hash for SymbolMetadata {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.vram.hash(state);
        self.rom.hash(state);
    }
}

impl fmt::Debug for SymbolMetadata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SymbolMetadata {{ vram: 0x{}, name: \"{}\" }}",
            self.vram,
            self.display_name()
        )
    }
}

impl SizedValue for SymbolMetadata {
    fn size(&self) -> Size {
        self.size().unwrap_or(Size::new(1))
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum AutogeneratedPadInfo {
    Unreferenced,
    CreatedBy(Vram),
}