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

use core::fmt;

use alloc::sync::Arc;

use crate::{
    addresses::{Rom, Vram},
    config::{Compiler, GlobalConfig},
    metadata::{
        AutogeneratedPadInfo, LabelMetadata, LabelType, SegmentMetadata, SymbolMetadata, SymbolType,
    },
    section_type::SectionType,
};

pub(crate) enum WordComment {
    No,
    U32([u8; 4]),
    U64([u8; 8]),
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct SymCommonDisplaySettings {
    line_end: Option<Arc<str>>,

    emit_asm_comment: bool,

    asm_indentation: u8,
    rom_comment_width: u8,
}

impl SymCommonDisplaySettings {
    #[must_use]
    pub fn new() -> Self {
        Self {
            line_end: None,
            emit_asm_comment: true,
            asm_indentation: 4,
            rom_comment_width: 6,
        }
    }

    #[must_use]
    pub fn line_end(&self) -> &str {
        if let Some(line_end) = &self.line_end {
            line_end
        } else {
            "\n"
        }
    }
}

impl SymCommonDisplaySettings {
    pub fn set_rom_comment_width(&mut self, rom_comment_width: u8) {
        self.rom_comment_width = rom_comment_width;
    }
}

impl SymCommonDisplaySettings {
    pub fn display_sym_property_comments(
        &self,
        f: &mut fmt::Formatter<'_>,
        metadata: &SymbolMetadata,
        _owned_segment: &SegmentMetadata,
    ) -> fmt::Result {
        if !self.emit_asm_comment {
            return Ok(());
        }

        if false {
            write!(
                f,
                "/* all_access_types: {:?} */{}",
                metadata.all_access_types(),
                self.line_end()
            )?;
            write!(
                f,
                "/* user_declared_type: {:?} */{}",
                metadata.user_declared_type(),
                self.line_end()
            )?;
            write!(
                f,
                "/* autodetected_type: {:?} */{}",
                metadata.autodetected_type(),
                self.line_end()
            )?;
            write!(
                f,
                "/* generated_by: {:?} */{}",
                metadata.generated_by(),
                self.line_end()
            )?;
            write!(
                f,
                "/* sym_referrers: {:?} */{}",
                metadata.sym_referrers(),
                self.line_end()
            )?;
            write!(
                f,
                "/* autogenerated_pad_info: {:?} */{}",
                metadata.autogenerated_pad_info(),
                self.line_end()
            )?;
        }

        // TODO
        // if self.isStatic():
        if false {
            write!(f, "/* static variable */{}", self.line_end())?;
        }
        if let Some(info) = metadata.autogenerated_pad_info() {
            write!(f, "/* Automatically generated and unreferenced pad ",)?;
            if false {
                // This block currently exists for debugging only.
                // Maybe convert into a proper feature in the future?
                match info {
                    AutogeneratedPadInfo::Unreferenced => {}
                    AutogeneratedPadInfo::CreatedBy(vram) => {
                        write!(f, "(generated by {vram}) ")?;
                    }
                }
            }
            write!(f, "*/{}", self.line_end())?;
        }

        Ok(())
    }

    pub fn display_symbol_name(
        &self,
        f: &mut fmt::Formatter<'_>,
        global_config: &GlobalConfig,
        metadata: &SymbolMetadata,
        in_middle: bool,
        section_type: Option<SectionType>,
    ) -> fmt::Result {
        let sym_name = metadata.display_name();

        if let Some(macro_labels) = global_config.macro_labels() {
            // Write the label, ie `glabel`, `dlabel`, etc
            match metadata.sym_type() {
                Some(SymbolType::Function) => {
                    if in_middle {
                        write!(f, "{}", macro_labels.alt_func())?;
                    } else {
                        write!(f, "{}", macro_labels.func())?;
                    }
                }
                Some(
                    SymbolType::Jumptable
                    | SymbolType::GccExceptTable
                    | SymbolType::Byte
                    | SymbolType::Short
                    | SymbolType::Word
                    | SymbolType::DWord
                    | SymbolType::Float32
                    | SymbolType::Float64
                    | SymbolType::CString
                    | SymbolType::VirtualTable
                    | SymbolType::UserCustom,
                )
                | None => match section_type {
                    Some(SectionType::Text) if in_middle => {
                        write!(f, "{}", macro_labels.alt_func())?
                    }
                    _ => write!(f, "{}", macro_labels.data())?,
                },
            }

            write!(f, " {sym_name}")?;

            match metadata.visibility().as_deref() {
                None | Some("global") | Some("globl") => {}
                Some(vis) => write!(f, ", {vis}")?,
            }
        } else {
            /*
            .globl func_80045DD0
            .type func_80045DD0,@function
            .ent func_80045DD0
            func_80045DD0:
            */
            let visibility = metadata.visibility();
            let vis = match visibility.as_deref() {
                None | Some("globl") => "globl",
                Some(vis) => vis,
            };
            write!(f, ".{} {}{}", vis, sym_name, self.line_end())?;

            match metadata.sym_type() {
                Some(SymbolType::Function) => {
                    write!(f, ".type {}, @function{}", sym_name, self.line_end())?;
                    if in_middle {
                        write!(f, ".aent {}{}", sym_name, self.line_end())?;
                    } else {
                        write!(f, ".ent {}{}", sym_name, self.line_end())?;
                    }
                }

                Some(SymbolType::Jumptable | SymbolType::GccExceptTable) => {}
                Some(
                    SymbolType::Byte
                    | SymbolType::Short
                    | SymbolType::Word
                    | SymbolType::DWord
                    | SymbolType::Float32
                    | SymbolType::Float64
                    | SymbolType::CString
                    | SymbolType::VirtualTable
                    | SymbolType::UserCustom,
                )
                | None => match section_type {
                    Some(SectionType::Text) if in_middle => {
                        write!(f, ".aent {}{}", sym_name, self.line_end())?
                    }
                    _ => write!(f, ".type {}, @object{}", sym_name, self.line_end())?,
                },
            }

            write!(f, "{sym_name}:")?;
        }

        /*
        if GlobalConfig.GLABEL_ASM_COUNT:
            if self.index is not None:
                label += f" # {self.index}"
        */

        write!(f, "{}", self.line_end())
    }

    pub fn display_label(
        &self,
        f: &mut fmt::Formatter<'_>,
        global_config: &GlobalConfig,
        metadata: &LabelMetadata,
    ) -> fmt::Result {
        let sym_name = metadata.display_name();

        if let Some(macro_labels) = global_config.macro_labels() {
            // Write the label, ie `jlabel`, `ehlabel`, etc
            match metadata.label_type() {
                LabelType::Jumptable => write!(f, "{}", macro_labels.jtbl_label())?,
                LabelType::GccExceptTable => write!(f, "{}", macro_labels.ehtbl_label())?,
                LabelType::AlternativeEntry => write!(f, "{}", macro_labels.alt_func())?,
                // TODO: use an specific macro for branches
                LabelType::Branch => write!(f, "{}", macro_labels.data())?,
            }

            write!(f, " {sym_name}")?;

            match metadata.visibility().as_deref() {
                None | Some("global") | Some("globl") => {}
                Some(vis) => write!(f, ", {vis}")?,
            }
        } else {
            /*
            .globl func_80045DD0
            func_80045DD0:
            */
            let visibility = metadata.visibility();
            let vis = match visibility.as_deref() {
                Some(vis) => Some(vis),
                None => match metadata.label_type() {
                    LabelType::Jumptable
                    | LabelType::GccExceptTable
                    | LabelType::AlternativeEntry => Some("globl"),
                    LabelType::Branch => None,
                },
            };
            if let Some(vis) = vis {
                write!(f, ".{} {}{}", vis, sym_name, self.line_end())?;
            }

            write!(f, "{sym_name}:")?;
        }

        /*
        if GlobalConfig.GLABEL_ASM_COUNT:
            if self.index is not None:
                label += f" # {self.index}"
        */

        write!(f, "{}", self.line_end())
    }

    /*
    pub fn display_symbol_start(&self, f: &mut fmt::Formatter<'_>, sym_name: &SymbolMetadataNameDisplay) -> fmt::Result {
        /*
        output = self.contextSym.getreferenceSymbols()
        output += self.getPrevAlignDirective(0)

        symName = self.getName()
        output += self.getSymbolAsmDeclaration(symName, useGlobalLabel)
        */

        Ok(())
    }
    */

    pub(crate) fn display_alignment_directive(
        &self,
        f: &mut fmt::Formatter<'_>,
        metadata: &SymbolMetadata,
        compiler: Compiler,
        shift_value: Option<u8>,
    ) -> fmt::Result {
        let shift_value = if let Some(shift_value) = shift_value {
            shift_value
        } else {
            return Ok(());
        };

        let parent_metadata = if let Some(parent_metadata) = metadata.parent_metadata() {
            parent_metadata
        } else {
            // Can't emit alignment directives if we don't have info about the parent.
            return Ok(());
        };

        let shifted_val = 1u32 << shift_value;

        let sub_ram = if compiler.symbol_alignment_requires_aligned_section() {
            if parent_metadata.vram().inner() % shifted_val != 0 {
                // Can't emit alignment directives if the parent file isn't properly aligned.
                return Ok(());
            }

            metadata.vram().inner()
        } else {
            // Check if alignment is relative to the file or to the full binary.
            (metadata.vram() - parent_metadata.vram()).inner() as u32
        };

        if sub_ram % shifted_val != 0 {
            // Emitting an alignment directive when the symbol is not already aligned to the desired
            // alignment would break matching.
            return Ok(());
        }

        write!(f, ".align {}{}", shift_value, self.line_end())
    }

    pub fn display_sym_prev_alignment(
        &self,
        f: &mut fmt::Formatter<'_>,
        metadata: &SymbolMetadata,
    ) -> fmt::Result {
        if let Some(compiler) = metadata.compiler() {
            if let Some(sym_type) = metadata.sym_type() {
                self.display_alignment_directive(
                    f,
                    metadata,
                    compiler,
                    compiler.prev_align_for_type(sym_type),
                )?;
            }
        }

        Ok(())
    }

    pub fn display_sym_end(
        &self,
        f: &mut fmt::Formatter<'_>,
        global_config: &GlobalConfig,
        metadata: &SymbolMetadata,
    ) -> fmt::Result {
        let sym_name = metadata.display_name();

        if let Some(macro_labels) = global_config.macro_labels() {
            if let Some(sym_type) = metadata.sym_type() {
                match sym_type {
                    SymbolType::Function => {
                        if let Some(func_end) = macro_labels.func_end() {
                            write!(f, "{} {}{}", func_end, sym_name, self.line_end())?;
                        }
                    }

                    SymbolType::Jumptable
                    | SymbolType::GccExceptTable
                    | SymbolType::Byte
                    | SymbolType::Short
                    | SymbolType::Word
                    | SymbolType::DWord
                    | SymbolType::Float32
                    | SymbolType::Float64
                    | SymbolType::CString
                    | SymbolType::VirtualTable
                    | SymbolType::UserCustom => {
                        if let Some(data_end) = macro_labels.data_end() {
                            write!(f, "{} {}{}", data_end, sym_name, self.line_end())?;
                        }
                    }
                }
            } else if let Some(data_end) = macro_labels.data_end() {
                write!(f, "{} {}{}", data_end, sym_name, self.line_end())?;
            }
        } else if let Some(SymbolType::Function) = metadata.sym_type() {
            write!(f, ".end {}{}", sym_name, self.line_end())?;
        }

        if global_config.emit_size_directive() {
            write!(f, ".size {}, . - {}{}", sym_name, sym_name, self.line_end())?;
        }

        Ok(())
    }

    pub fn display_asm_indendation(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.asm_indentation > 0 {
            write!(f, "{:width$}", " ", width = self.asm_indentation as usize)
        } else {
            Ok(())
        }
    }

    pub fn display_asm_comment(
        &self,
        f: &mut fmt::Formatter<'_>,
        rom: Option<Rom>,
        vram: Vram,
        word_comment: WordComment,
    ) -> fmt::Result {
        self.display_asm_indendation(f)?;

        if !self.emit_asm_comment {
            return Ok(());
        }

        write!(f, "/* ")?;
        if let Some(rom) = rom {
            // TODO: implement display for Rom
            write!(
                f,
                "{:0width$X} ",
                rom.inner(),
                width = self.rom_comment_width as usize
            )?;
        }
        write!(f, "{vram} ")?;

        match word_comment {
            WordComment::No => {}
            WordComment::U32(arr) => Self::display_byte_array(f, arr)?,
            WordComment::U64(arr) => Self::display_byte_array(f, arr)?,
        }

        write!(f, "*/ ")
    }

    fn display_byte_array<const LENGTH: usize>(
        f: &mut fmt::Formatter<'_>,
        arr: [u8; LENGTH],
    ) -> fmt::Result {
        for x in arr {
            write!(f, "{x:02X}")?;
        }
        write!(f, " ")?;
        Ok(())
    }
}