### Standalone InstructionAnalyzer Workflow Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/InstructionAnalyzer.md Provides a detailed example of setting up and using the InstrAnalyzer independently. It covers context setup, analyzer instantiation, register tracker simulation, and the iterative processing of MIPS instructions to populate the analyzer's state with detected references. ```python import rabbitizer from spimdisasm import common, mips # Setup context = common.Context() context.changeGlobalSegmentRanges(0, 0x100000, 0x80000000, 0x80100000) # Create instruction analyzer analyzer = mips.symbols.analysis.InstrAnalyzer(0x80000000, context) # Create register tracker regs = rabbitizer.RegistersTracker() # Simulate analyzing instructions words = [0x27BDFFE0, 0xAFBF001C, ...] # MIPS instructions instrs = [rabbitizer.Instruction(w) for w in words] prev_instr = None for offset, word in enumerate(words): instr = instrs[offset] instr.vram = 0x80000000 + offset * 4 # Process instruction analyzer.processInstr( regs, instr, offset * 4, instr.vram, prev_instr ) prev_instr = instr # Analyzer state now contains all references found ``` -------------------------------- ### Install spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/00-START-HERE.txt Install the spimdisasm library using pip. ```bash python3 -m pip install spimdisasm ``` -------------------------------- ### Install Spimdisasm Development Version (from GitHub) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/README.md Install the latest development version directly from the GitHub repository without cloning. Use with caution. ```bash python3 -m pip uninstall spimdisasm python3 -m pip install git+https://github.com/Decompollaborate/spimdisasm.git@1.x ``` -------------------------------- ### Install Spimdisasm Development Version (Editable) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/README.md Install the development version of spimdisasm from a local clone of the repository using the editable flag. ```bash python3 -m pip install -e . ``` -------------------------------- ### SymbolFunction Usage Example Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SymbolFunction.md A complete example showing how to set up the context, read binary data, create a SymbolFunction instance, analyze it, and then disassemble its instructions. This covers common use cases for analyzing MIPS code. ```python from spimdisasm import common, mips import rabbitizer # Setup context = common.Context() context.changeGlobalSegmentRanges(0x0, 0x100000, 0x80000000, 0x80100000) # Read and decode instructions with open("game.bin", "rb") as f: binary = f.read() code_bytes = binary[0x1000:0x2000] words = [int.from_bytes(code_bytes[i:i+4], 'big') for i in range(0, len(code_bytes), 4)] instrs = [rabbitizer.Instruction(w) for w in words] # Create function func = mips.symbols.SymbolFunction( context, vromStart=0x1000, vromEnd=0x2000, inFileOffset=0, vram=0x80000000, instrsList=instrs, segmentVromStart=0, overlayCategory=None ) func.setName("main_function") # Analyze func.analyze() print(f"Function: {func.getName()}") print(f"Instructions: {func.nInstr}") print(f"Likely handwritten: {func.isLikelyHandwritten}") # Disassemble asm = func.disassemble() print(asm) # Check for branches if len(func.branchesTaken) > 0: print(f"Branch targets found: {len(func.branchesTaken)}") ``` -------------------------------- ### Get Full Assembly Preamble Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileBase.md Combines all preamble components, including includes, instruction directives, and section start, into a single string. ```python full_prelude = section.getAsmPrelude() ``` -------------------------------- ### Context Class Usage Example Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md Demonstrates how to initialize a Context, configure memory layout, add overlay segments, and check address validity. ```python from spimdisasm import common # Create context for N64 binary context = common.Context() # Configure memory layout context.changeGlobalSegmentRanges(0x0, 0xFFFFFF, 0x80000000, 0x80100000) # Add overlay segments for code overlays overlay1 = context.addOverlaySegment( "code", 0x100000, 0x200000, 0x80100000, 0x80200000, "intro" ) # Check if address is valid if context.isInTotalVramRange(0x80050000): print("Address is in valid VRAM range") # Add special VRAM range for exception table context.addSpecialVramRange(0x80300000, 0x80350000) ``` -------------------------------- ### Install Spimdisasm from PyPI Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/README.md Use this command to install the latest stable release of spimdisasm from the Python Package Index. ```bash python3 -m pip install -U spimdisasm ``` -------------------------------- ### Configure spimdisasm via Command-Line Arguments Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md All spimdisasm tools support configuration through command-line arguments. This example shows how to set compiler, endianness, architecture level, and verbosity. ```bash singleFileDisasm input.bin \ --compiler IDO \ --endian big \ --arch-level MIPS3 \ --verbose ``` -------------------------------- ### Boolean Option Syntax Examples Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Demonstrates the syntax for enabling and disabling boolean options using command-line arguments. ```bash # Enable --option --option true ``` ```bash # Disable --no-option --option false ``` -------------------------------- ### Setup Global Offset Table (GOT) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md Initializes the Global Offset Table (GOT) for position-independent code analysis. Requires the GOT base address and a list of GOT entries. ```python def setupGotTable(self, pltGot: int, table: list[GotEntry]) -> None ``` ```python context = Context() got_entries = [GotEntry(...), ...] context.setupGotTable(0x80000600, got_entries) ``` -------------------------------- ### Minimal Imports for spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Demonstrates the most basic imports required to start using spimdisasm for common tasks. ```python # Minimal imports from spimdisasm import common, mips, elf32 ``` -------------------------------- ### Generic GCC Build Disassembly Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Example command-line arguments for disassembling a generic GCC-compiled executable. ```bash singleFileDisasm executable \ --compiler GCC \ --pic \ --verbose \ --name-vars-by-file ``` -------------------------------- ### Get spimdisasm Version Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Import the spimdisasm library and print its version. This is useful for checking the installed version. ```python import spimdisasm print(spimdisasm.__version__) # e.g., "1.42.2" ``` -------------------------------- ### Zelda 64 Disassembly Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Example command-line arguments for disassembling a Zelda 64 ROM using the IDO compiler. ```bash singleFileDisasm rom.bin \ --compiler IDO \ --abi N64 \ --arch-level MIPS3 \ --endian big \ --filter-low-addresses \ --name-vars-by-type ``` -------------------------------- ### PlayStation 2 Disassembly Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Example command-line arguments for disassembling a PlayStation 2 executable using the EE R5900 architecture. ```bash singleFileDisasm game.elf \ --compiler EEGCC \ --arch-level MIPS3 \ --rodata-string-encoding "ASCII" ``` -------------------------------- ### Basic Python Disassembly Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Disassemble a binary file using the spimdisasm Python API. This example demonstrates setting up context, loading a binary, creating a text section, configuring global settings, analyzing the section, and saving the output. ```python from spimdisasm import common, mips import rabbitizer # 1. Setup context context = common.Context() context.changeGlobalSegmentRanges(0, 0x100000, 0x80000000, 0x80100000) # 2. Load binary with open("game.bin", "rb") as f: binary = f.read() # 3. Create section text_section = mips.sections.SectionText( context, vromStart=0, vromEnd=len(binary), vram=0x80000000, filename="code.s", array_of_bytes=binary, segmentVromStart=0, overlayCategory=None ) # 4. Configure common.GlobalConfig.COMPILER = common.Compiler.IDO common.GlobalConfig.ARCHLEVEL = common.ArchLevel.MIPS3 # 5. Analyze text_section.analyze() # 6. Output text_section.saveToFile("output/code.s") print(f"Found {text_section.nFuncs} functions") ``` -------------------------------- ### PlayStation 1 Disassembly Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Example command-line arguments for disassembling a PlayStation 1 game binary using the PSYQ compiler. ```bash singleFileDisasm game.bin \ --compiler PSYQ \ --arch-level MIPS1 \ --endian little \ --rodata-string-guesser 2 \ --custom-suffix "_ps1" ``` -------------------------------- ### Configure Global Settings for Disassembly Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/GlobalConfig.md Set global configuration options programmatically to customize the disassembly process. Changes persist across the entire disassembly session. This example configures settings for Zelda 64 (IDO compiler, N64 ABI) and adjusts string detection and output labels. ```python from spimdisasm import common # Configure for Zelda 64 (IDO compiler, N64 ABI) common.GlobalConfig.COMPILER = common.Compiler.IDO common.GlobalConfig.ABI = common.Abi.O32 common.GlobalConfig.ENDIAN = common.InputEndian.BIG common.GlobalConfig.ARCHLEVEL = common.ArchLevel.MIPS3 # Enable aggressive string detection common.GlobalConfig.RODATA_STRING_GUESSER_LEVEL = 2 # Customize output common.GlobalConfig.ASM_TEXT_LABEL = "func" common.GlobalConfig.ASM_DATA_LABEL = "data" common.GlobalConfig.VERBOSE = True # Disable uncertain features common.GlobalConfig.SYMBOL_FINDER_FILTER_LOW_ADDRESSES = True ``` -------------------------------- ### getAsmPrelude Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileBase.md Combines all components of the assembly preamble, including includes, directives, and section start information. ```APIDOC ## getAsmPrelude ### Description Combines all preamble components (includes, directives, section start). ### Method ```python def getAsmPrelude(self) -> str ``` ### Returns `str` - Complete assembly preamble ### Example ```python full_prelude = section.getAsmPrelude() ``` ``` -------------------------------- ### Data Flow Analysis Example Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/InstructionAnalyzer.md Illustrates how the InstructionAnalyzer tracks register values across instructions to determine memory addresses. This helps in identifying pointers and references. ```python # Example: Tracking address loading # Instruction 1: lui $t0, 0x8001 # Load upper immediate # Instruction 2: addiu $t0, $t0, 0x234 # Add lower immediate # Result: $t0 = 0x80010000 + 0x234 = 0x80010234 (a pointer!) # RegistersTracker updates $t0's known value # Analyzer records this as a reference ``` -------------------------------- ### Get Assembly Includes Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileBase.md Retrieves the includes section of the assembly preamble, typically containing .include directives. ```python prelude = section.getAsmPrelude_includes() # Output: '.include "macro.inc"\n\n' ``` -------------------------------- ### Accessing and Iterating Instructions Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SymbolFunction.md Demonstrates how to get a specific instruction by its offset and how to iterate through all instructions within a function. Offsets are typically divided by 4 as instructions are word-aligned. ```python # Get instruction at byte offset instr = func.instructions[offset // 4] # Iterate all instructions for instr in func.instructions: print(f"{instr.vram:08X}: {instr.disassemble()}") ``` -------------------------------- ### Get Assembly Section Start Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileBase.md Retrieves the section declaration directive, including alignment and flags. This is crucial for defining the start of a section in assembly. ```python prelude = section.getAsmPrelude_sectionStart() # Output: '.section .text\n\n.align 4\n\n' ``` -------------------------------- ### Context Initialization Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md Initializes the Context class, setting up default memory ranges and symbol segments for N64 binaries. ```APIDOC ## Context() ### Description Initializes the Context class. It sets up default memory ranges and symbol segments, particularly tailored for N64 binaries. ### Method __init__ ### Parameters None ### Request Example ```python context = Context() ``` ### Response Initializes a new Context object with default attributes. ``` -------------------------------- ### setupGotTable Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md Initializes the Global Offset Table (GOT) for position-independent code analysis. This is essential for correctly resolving indirect function calls. ```APIDOC ## setupGotTable ### Description Initializes the Global Offset Table (GOT) for position-independent code analysis. ### Method `setupGotTable` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **pltGot** (`int`) - Required - GOT base address - **table** (`list[GotEntry]`) - Required - List of GOT entries ### Returns `None` ### Example ```python context = Context() got_entries = [GotEntry(...), ...] context.setupGotTable(0x80000600, got_entries) ``` ``` -------------------------------- ### Get Read-Only Data for Function Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md Extracts read-only data associated with a specific function. ```python def getRdataAndLateRodataForFunction( func: symbols.SymbolFunction, rodataFileList: list[sections.SectionBase] ) -> tuple[list[symbols.SymbolBase], list[symbols.SymbolBase], int]: Extracts read-only data associated with a function. **Returns:** Tuple of (rodata symbols, late rodata, late rodata size) ``` -------------------------------- ### Create Empty FileBase Instance Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md Creates a minimal empty `FileBase` instance for manual population. Used internally when no explicit binary data is provided. Requires a symbol tracking context. ```python from spimdisasm import common, mips context = common.Context() empty_file = mips.createEmptyFile(context) # Can be populated manually empty_file.symbolList = [func1, func2, ...] ``` -------------------------------- ### Parse and Analyze Binary File with spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileBase.md Demonstrates how to create a context, read binary data, parse it into words, create a text section, analyze it, and save the disassembly. Use this for basic binary file analysis and disassembly. ```python from spimdisasm import common, mips # Create a context context = common.Context() context.changeGlobalSegmentRanges(0, 0xFFFFFF, 0x80000000, 0x81000000) # Read binary file with open("game.bin", "rb") as f: binary_data = f.read() # Parse binary as words words = common.Utils.bytesToWords(binary_data[0x1000:0x2000], 0) # Create a text section text_section = mips.sections.SectionText( context, vromStart=0x1000, vromEnd=0x2000, vram=0x80000000, filename="code.s", array_of_bytes=binary_data[0x1000:0x2000], segmentVromStart=0, overlayCategory=None ) # Configure and analyze text_section.analyze() # Save disassembly text_section.saveToFile("output/code.s") # Compare against reference text_section2 = mips.sections.SectionText(...) result = text_section.compareToFile(text_section2) if result['equal']: print("Matching disassembly!") ``` -------------------------------- ### AddressRange Data Class Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md Defines a data structure for tracking address ranges with start and end points. ```python import dataclasses @dataclasses.dataclass class AddressRange: start: int end: int ``` -------------------------------- ### Set Application Binary Interface (ABI) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Configure the Application Binary Interface (ABI) using the --abi option. Supported ABIs are O32, N32, O64, N64, EABI32, and EABI64. ```bash --abi ``` -------------------------------- ### Programmatic Configuration for Custom Projects Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Demonstrates how to configure spimdisasm programmatically using the GlobalConfig module for a custom project. Imports necessary enums and classes. ```python from spimdisasm.common import GlobalConfig, Compiler, InputEndian, ArchLevel # Configure for custom project GlobalConfig.COMPILER = Compiler.IDO GlobalConfig.ENDIAN = InputEndian.BIG GlobalConfig.ARCHLEVEL = ArchLevel.MIPS3 GlobalConfig.RODATA_STRING_ENCODING = "ASCII" GlobalConfig.RODATA_STRING_GUESSER_LEVEL = 2 GlobalConfig.ASM_COMMENT = True GlobalConfig.VERBOSE = True # Now create sections/analyze... ``` -------------------------------- ### Import and Use Common Module Components Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Demonstrates importing and instantiating various types, enums, and utility functions from the spimdisasm.common module. This shows how to access core functionalities like context management, configuration, and data type definitions. ```python from spimdisasm import common # Types context = common.Context() config = common.GlobalConfig symbol = common.ContextSymbol(...) segment = common.SymbolsSegment(...) # Enums endian = common.InputEndian.BIG abi = common.Abi.N32 level = common.ArchLevel.MIPS3 compiler = common.Compiler.IDO # Utilities words = common.Utils.bytesToWords(data) encoded = common.Utils.bytesToStr(data, "UTF-8") ``` -------------------------------- ### Spimdisasm Command-Line Entry Points Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Lists the available subcommands and their basic usage for the spimdisasm command-line interface. ```bash # Command spimdisasm [options] singleFileDisasm [options] disasmdis [options] rspDisasm [options] elfObjDisasm [options] ``` -------------------------------- ### wordListToInstructions Static Method Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SectionText.md Converts a list of raw 32-bit words into a list of rabbitizer Instruction objects, with optional VRAM tracking. ```APIDOC ## wordListToInstructions Static Method ### Description Converts raw 32-bit words to rabbitizer Instruction objects with optional VRAM tracking. ### Parameters #### Parameters - **wordList** (`list[int]`) - Required - List of 32-bit instruction words - **currentVram** (`int | None`) - Required - Starting VRAM address (increments by 4 per instruction) - **instrCat** (`rabbitizer.Enum`) - Required - Instruction category (defines ISA) ### Returns - `list[rabbitizer.Instruction]` - Decoded instructions with VRAM addresses ### Example ```python import rabbitizer words = [0x27BDFFE0, 0xAFBF001C, ...] instrs = SectionText.wordListToInstructions( words, currentVram=0x80000000, instrCat=rabbitizer.InstrCategory.CPU ) for instr in instrs: print(f"{instr.vram:08X}: {instr.disassemble()}") ``` ``` -------------------------------- ### Get Function Size in 32-bit Words Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SymbolFunction.md Obtain the size of the function in 32-bit words. This value is equivalent to the number of MIPS instructions. ```python @property def sizew(self) -> int: # Returns the size in 32-bit words (equivalent to nInstr). ``` -------------------------------- ### Full Imports for spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Shows how to import all necessary components for comprehensive usage of spimdisasm, including context, configuration, and specific file/section types. ```python # Full setup from spimdisasm.common import Context, GlobalConfig, InputEndian from spimdisasm.mips import FileSplits, sections, symbols from spimdisasm.elf32 import Elf32File ``` -------------------------------- ### Full Code Analysis with spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SectionText.md Demonstrates a complete workflow for analyzing a binary file using spimdisasm. This includes setting up the context, reading the binary, creating a SectionText object, configuring analysis parameters, performing the analysis, and outputting the disassembly. ```python from spimdisasm import common, mips import rabbitizer # Setup context context = common.Context() context.changeGlobalSegmentRanges(0x0, 0x100000, 0x80000000, 0x80100000) # Read code section with open("game.bin", "rb") as f: binary = f.read() # Create text section text = mips.sections.SectionText( context, vromStart=0x1000, vromEnd=0x5000, vram=0x80000000, filename="code", array_of_bytes=binary[0x1000:0x5000], segmentVromStart=0, overlayCategory=None ) # Configure text.instrCat = rabbitizer.InstrCategory.CPU common.GlobalConfig.ARCHLEVEL = common.ArchLevel.MIPS3 # Analyze functions text.analyze() print(f"Found {text.nFuncs} functions") # Output disassembly text.saveToFile("output/code.s") # Inspect individual functions for func in text.symbolList: if isinstance(func, mips.symbols.SymbolFunction): print(f"Function {func.getName()} at 0x{func.vram:08X}") print(f" Instructions: {func.nInstr}") if func.isLikelyHandwritten: print(" (Likely handwritten)") ``` -------------------------------- ### Get Number of Functions in Section Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SectionText.md Retrieves the total count of functions identified within a section. Useful for understanding the structure of the analyzed code. ```python text_section = SectionText(...) text_section.analyze() print(f"Found {text_section.nFuncs} functions") ``` -------------------------------- ### Get Number of MIPS Instructions Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SymbolFunction.md Retrieve the total count of MIPS instructions within a function. This can be used to calculate the function's byte size. ```python func = SymbolFunction(...) print(f"Function has {func.nInstr} instructions ({func.nInstr * 4} bytes)") ``` -------------------------------- ### Work with ELF Files Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Shows how to parse an ELF file, utilize global configuration derived from ELF headers, extract sections, and access symbols from the symbol table. ```python # 1. Parse ELF elf = elf32.Elf32File(binary_data) # 2. GlobalConfig already set from ELF headers # (endianness, PIC flag, architecture) # 3. Extract sections for name, entry in elf.progbitsExecute.items(): code_data = binary_data[entry.offset:entry.offset + entry.size] section = mips.sections.SectionText(...) # 4. Access symbols if elf.symtab: for sym in elf.symtab.entries: sym_name = elf.strtab[sym.name] ``` -------------------------------- ### Get Effective Size of a ContextSymbol Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ContextSymbol.md Retrieves the effective size of a symbol, prioritizing user-declared size over autodetected size. Useful for determining the memory footprint of a symbol. ```python def getEffectiveSize(sym: common.ContextSymbol) -> int|None: """Get size, preferring user-declared over autodetected.""" if sym.userDeclaredSize is not None: return sym.userDeclaredSize return sym.autodetectedSize # Usage effective_size = getEffectiveSize(sym) if effective_size: end_address = sym.address + effective_size ``` -------------------------------- ### Get Assembly Representation and Save to File Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SymbolFunction.md Obtain the assembly string representation of a function and save it to a file. The `disassemble` method can also be used with `migrate=True` to omit the header. ```python # Get assembly representation asm_str = func.disassemble() # Write to file func.saveToFile("output/function.s") # Get with migration (omits header) asm_migrated = func.disassemble(migrate=True) ``` -------------------------------- ### Initialize Context Class Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/Context.md The Context class is initialized without parameters. It sets up default memory ranges suitable for N64 binaries. ```python class Context: def __init__(self) -> None: ``` -------------------------------- ### Global Configuration Usage Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/GlobalConfig.md Demonstrates how to set various global configuration options for spimdisasm, such as compiler, ABI, endianness, architecture level, string detection, and output labels. Changes to these settings persist throughout the disassembly session. ```APIDOC ## Usage Example ```python from spimdisasm import common # Configure for Zelda 64 (IDO compiler, N64 ABI) common.GlobalConfig.COMPILER = common.Compiler.IDO common.GlobalConfig.ABI = common.Abi.O32 common.GlobalConfig.ENDIAN = common.InputEndian.BIG common.GlobalConfig.ARCHLEVEL = common.ArchLevel.MIPS3 # Enable aggressive string detection common.GlobalConfig.RODATA_STRING_GUESSER_LEVEL = 2 # Customize output common.GlobalConfig.ASM_TEXT_LABEL = "func" common.GlobalConfig.ASM_DATA_LABEL = "data" common.GlobalConfig.VERBOSE = True # Disable uncertain features common.GlobalConfig.SYMBOL_FINDER_FILTER_LOW_ADDRESSES = True ``` ## Notes - All boolean CLI options support `--option` and `--no-option` syntax - Changes to GlobalConfig persist across the entire disassembly session - String guesser levels affect accuracy vs false positives trade-off - Architecture level affects which MIPS instruction variants are recognized - Compiler selection enables/disables specific workarounds for known compiler behavior ``` -------------------------------- ### Get Effective Type of a ContextSymbol Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ContextSymbol.md Retrieves the effective type of a symbol, prioritizing user-declared type over autodetected type. Handles both string types and special symbol types. ```python def getEffectiveType(sym: common.ContextSymbol) -> str|common.SymbolSpecialType|None: """Get type, preferring user-declared over autodetected.""" if sym.userDeclaredType is not None: return sym.userDeclaredType return sym.autodetectedType effective_type = getEffectiveType(sym) if isinstance(effective_type, common.SymbolSpecialType): print(f"Special type: {effective_type.name}") else: print(f"Data type: {effective_type}") ``` -------------------------------- ### Get MIPS Assembly Directives for Text Section Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/SectionText.md Retrieves standard MIPS assembly directives for the preamble of a .text section. These directives help configure the assembler for optimal code generation. ```python directives = text_section.getAsmPrelude_instructionDirectives() # Output: '.set noat\n.set noreorder\n.set gp=64\n\n' ``` -------------------------------- ### Create Multi-Section Binary (FileSplits) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md This snippet shows how to handle multi-section binaries using FileSplits. It defines split points for different sections (Text, Rodata), creates a FileSplits object, analyzes it, and then saves each section to its respective file. ```python # Define split points splits = [ common.FileSplitEntry( offset=0x0, vram=0x80000000, fileName="code", section=common.FileSectionType.Text, nextOffset=0x20000 ), common.FileSplitEntry( offset=0x20000, vram=0x80020000, fileName="rodata", section=common.FileSectionType.Rodata, nextOffset=0x30000 ), ] # Create splits file file_splits = mips.FileSplits( context, vromStart=0, vromEnd=len(binary), vram=0x80000000, filename="game", array_of_bytes=binary, segmentVromStart=0, overlayCategory=None, splitsData=splits ) file_splits.analyze() # Access sections text_sections = file_splits.sectionsDict[common.FileSectionType.Text].values() for text in text_sections: text.saveToFile(f"output/{text.name}.s") ``` -------------------------------- ### Get MIPS Sections by Type and Name Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md Retrieve sections from FileSplits by their type (Text, Data, Rodata, Bss) or by specific name. Useful for isolating and inspecting specific code or data segments. ```python splits = mips.FileSplits(...) splits.analyze() # By section type text_sections = splits.sectionsDict[common.FileSectionType.Text] data_sections = splits.sectionsDict[common.FileSectionType.Data] rodata_sections = splits.sectionsDict[common.FileSectionType.Rodata] bss_sections = splits.sectionsDict[common.FileSectionType.Bss] # By name code = text_sections.get("code") if code: print(f"Code: {code.nFuncs} functions") ``` -------------------------------- ### Automatic ELF Header Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ELF32File.md Demonstrates how ELF headers are automatically parsed to configure global settings like endianness and PIC flag. Shows conditional logic based on detected header properties. ```python # Endianness is auto-detected if elf.header.ident.getDataEncoding() == Elf32HeaderIdentifier.DataEncoding.DATA2MSB: # GlobalConfig.ENDIAN is set to InputEndian.BIG pass elif elf.header.ident.getDataEncoding() == Elf32HeaderIdentifier.DataEncoding.DATA2LSB: # GlobalConfig.ENDIAN is set to InputEndian.LITTLE pass # ELF flags are parsed if Elf32HeaderFlag.PIC in elf.elfFlags: # GlobalConfig.PIC is set to True pass ``` -------------------------------- ### Accessing and Modifying Global Configuration Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/GlobalConfig.md Demonstrates how to import the GlobalConfig and modify its settings. Use this to enable or disable specific disassembly features. ```python from spimdisasm import common config = common.GlobalConfig config.DISASSEMBLE_UNKNOWN_INSTRUCTIONS = True ``` -------------------------------- ### Parallel Section Analysis with Multiprocessing Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Improve analysis performance by processing independent sections in parallel using Python's multiprocessing module. This example demonstrates using a Pool to map an analysis function across multiple sections. ```python from multiprocessing import Pool def analyze_section(section): section.analyze() return section sections = [...] with Pool(4) as p: analyzed = p.map(analyze_section, sections) ``` -------------------------------- ### Analyze a MIPS File Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Demonstrates the process of analyzing a MIPS file by creating a context, loading a text section, configuring compiler settings, analyzing the section, and accessing/saving the results. ```python # 1. Create context context = common.Context() context.changeGlobalSegmentRanges(...) # 2. Load and create section section = mips.sections.SectionText(context, ...) # 3. Configure (before analyze) common.GlobalConfig.COMPILER = ... section.instrCat = ... # 4. Analyze section.analyze() # 5. Access results for func in section.symbolList: print(f"{func.getName()}: {func.nInstr} instructions") # 6. Save section.saveToFile(output_path) ``` -------------------------------- ### Create and Populate ContextSymbol Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ContextSymbol.md Demonstrates creating a ContextSymbol for a function and updating its size after analysis. Convert to an actual SymbolFunction. ```python sym = common.ContextSymbol( address=target_address, segment=segment, autodetectedType=common.SymbolSpecialType.function, isDefined=True, isAutogenerated=True ) # Later, after size analysis: sym.autodetectedSize = calculated_size # Convert to actual SymbolFunction actual_symbol = symbols.SymbolFunction.fromContextSymbol(sym) ``` -------------------------------- ### Process Multiple File Splits Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Illustrates how to define file split points, create FileSplits objects, analyze all defined splits, and access sections by type for output. ```python # 1. Define split points splits = [ common.FileSplitEntry(0x0, 0x80000000, "code", common.FileSectionType.Text, 0x10000), common.FileSplitEntry(0x10000, 0x80010000, "data", common.FileSectionType.Data, 0x20000), ] # 2. Create FileSplits file_splits = mips.FileSplits(context, ..., splitsData=splits) # 3. Analyze all file_splits.analyze() # 4. Access by type for name, section in file_splits.sectionsDict[common.FileSectionType.Text].items(): section.saveToFile(f"output/{name}.s") ``` -------------------------------- ### Add Spimdisasm to requirements.txt Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/README.md Include this line in your requirements.txt file to specify the spimdisasm library and its version range. ```txt spimdisasm>=1.42.2,<2.0.0 ``` -------------------------------- ### Create and Configure a Context Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/INDEX.md Initializes a spimdisasm context and sets global segment ranges. Use this to define the memory layout for disassembly. ```python from spimdisasm import common context = common.Context() context.changeGlobalSegmentRanges( vromStart=0, vromEnd=0x100000, vramStart=0x80000000, vramEnd=0x80100000 ) ``` -------------------------------- ### Create Single-Section Binary Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md This snippet demonstrates how to create a single-section text section from binary data. It sets up the context, reads binary data from a file, creates a SectionText object, analyzes it, and saves the output to a file. ```python from spimdisasm import common, mips # Setup context = common.Context() context.changeGlobalSegmentRanges(0, 0x100000, 0x80000000, 0x80100000) with open("code.bin", "rb") as f: code_bytes = f.read() # Create text section directly text_section = mips.sections.SectionText( context, vromStart=0, vromEnd=len(code_bytes), vram=0x80000000, filename="code.s", array_of_bytes=code_bytes, segmentVromStart=0, overlayCategory=None ) # Analyze and save text_section.analyze() text_section.saveToFile("output/code.s") ``` -------------------------------- ### Track $gp Register Access Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/InstructionAnalyzer.md Demonstrates how to initialize a RegistersTracker and check if the $gp register's value is known after processing. ```python # Example: Track $gp relative access regsTracker = rabbitizer.RegistersTracker() # After processing: regsTracker.isRegValueKnown(rabbitizer.Register.GP) ``` -------------------------------- ### Create MIPS Symbols Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Demonstrates the creation of symbol objects like functions and data. Direct creation is rare; symbols are usually generated during analysis. ```python from spimdisasm.mips import symbols # Create symbols (rarely done directly) func = symbols.SymbolFunction(context, ...) data = symbols.SymbolData(context, ...) # Access symbol methods func.analyze() assembly = func.disassemble() name = func.getName() ``` -------------------------------- ### Enum and Constant Operations in spimdisasm Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/types.md Demonstrates basic operations with enums like InputEndian and ArchLevel, and type conversions for FileSectionType. ```python from spimdisasm.common import InputEndian, ArchLevel, FileSectionType # Enum operations endian = InputEndian.BIG if endian == InputEndian.BIG: print("Big-endian") # ArchLevel comparison if ArchLevel.MIPS3 >= ArchLevel.MIPS2: print("Supports MIPS3+") # Section type conversion section = FileSectionType.Text print(section.toStr()) # ".text" ``` -------------------------------- ### createEmptyFile Function Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/MipsFileBase.md Creates a minimal empty FileBase instance for manual population. Used internally when no explicit binary data is provided. ```APIDOC ## createEmptyFile Function ### Description Creates a minimal empty FileBase instance for manual population. Used internally when no explicit binary data is provided. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method ```python def createEmptyFile(context: common.Context) -> FileBase ``` ### Parameters #### Path Parameters - **context** (`Context`) - Required - Symbol tracking context ### Returns - **FileBase** - Empty file with no symbols or content ### Example ```python from spimdisasm import common, mips context = common.Context() empty_file = mips.createEmptyFile(context) # Can be populated manually empty_file.symbolList = [func1, func2, ...] ``` ``` -------------------------------- ### FileSplits Constructor Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileSplits.md Initializes a new instance of the FileSplits class. This constructor is used to set up the management of MIPS binary files with multiple sections. ```APIDOC ## FileSplits Constructor ### Description Initializes a new instance of the FileSplits class. This constructor is used to set up the management of MIPS binary files with multiple sections. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```python FileSplits(context: common.Context, vromStart: int, vromEnd: int, vram: int, filename: str, array_of_bytes: bytes, segmentVromStart: int, overlayCategory: str|None, splitsData: common.FileSplitFormat|None = None, relocSection: sections.SectionRelocZ64|None = None) ``` ### Parameters Details - **context** (`Context`) - Required - Symbol context - **vromStart** (`int`) - Required - Virtual ROM start - **vromEnd** (`int`) - Required - Virtual ROM end - **vram** (`int`) - Required - Execution address - **filename** (`str`) - Required - Output filename prefix - **array_of_bytes** (`bytes`) - Required - Full binary content - **segmentVromStart** (`int`) - Required - Parent segment start - **overlayCategory** (`str|None`) - Required - Overlay category - **splitsData** (`FileSplitFormat|None`) - Optional - List of split entries - **relocSection** (`SectionRelocZ64|None`) - Optional - Zelda 64 relocation section ``` -------------------------------- ### Configure Compiler for Nintendo 64 (Zelda) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Sets the global configuration for the compiler to IDO, ABI to O32, and endianness to Big for Nintendo 64 targets. ```python common.GlobalConfig.COMPILER = common.Compiler.IDO common.GlobalConfig.ABI = common.Abi.O32 common.GlobalConfig.ENDIAN = common.InputEndian.BIG common.GlobalConfig.ARCHLEVEL = common.ArchLevel.MIPS3 ``` -------------------------------- ### Enable Pascal String Detection in .data Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Activate experimental detection of Pascal-style strings within the .data section using the --pascal-data-string-guesser option. This feature is disabled by default. ```bash --pascal-data-string-guesser ``` -------------------------------- ### Disassemble Binary File (CLI) Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/README.md Use the singleFileDisasm CLI tool to disassemble a binary file. Specify endianness and architecture level. ```bash # Disassemble a binary file singleFileDisasm game.bin --endian big --arch-level MIPS3 ``` -------------------------------- ### Full ELF32 File Parsing and Information Extraction Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ELF32File.md Demonstrates reading an ELF file, parsing it with Elf32File, and accessing various sections like header, symbol tables, code, data, and relocations. It also shows how to access raw section data. ```python from spimdisasm import elf32, common, mips # Read ELF file with open("game.elf", "rb") as f: elf_data = f.read() # Parse ELF elf = elf32.Elf32File(elf_data) print("=== ELF Header ===") print(f"Entry point: 0x{elf.header.entry:08X}") print(f"Machine: {elf.header.machine}") print(f"Flags: 0x{elf.header.flags:08X}") print("\n=== Symbol Tables ===") if elf.symtab: print(f"Static symbols: {len(elf.symtab.entries)}") if elf.dynsym: print(f"Dynamic symbols: {len(elf.dynsym.entries)}") print("\n=== Code Sections ===") for name, entry in elf.progbitsExecute.items(): print(f"{name}: 0x{entry.addr:08X} ({entry.size} bytes)") print("\n=== Data Sections ===") for name, entry in elf.progbitsWrite.items(): print(f"{name}: 0x{entry.addr:08X} ({entry.size} bytes)") for name, entry in elf.progbitsNoWrite.items(): print(f"{name} (RO): 0x{entry.addr:08X} ({entry.size} bytes)") for name, entry in elf.nobitsPerName.items(): print(f"{name} (BSS): 0x{entry.addr:08X}") print("\n=== Relocations ===") for name, relocs in elf.relPerName.items(): print(f"{name}: {len(relocs.entries)} relocations") # Access raw section data if elf.progbitsExecute: text_entry = next(iter(elf.progbitsExecute.values())) text_data = elf_data[text_entry.offset:text_entry.offset + text_entry.size] print(f"\nText section data: {len(text_data)} bytes") ``` -------------------------------- ### Accessing spimdisasm Components via Imported Submodule Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Demonstrates an alternative way to access spimdisasm components by importing a submodule and then accessing its members. This can make code more concise when using multiple components from the same submodule. ```python # Via imported submodule common = spimdisasm.common ctx = common.Context() ``` -------------------------------- ### Enable Pascal String Detection in .rodata Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Enable experimental detection of Pascal-style strings in the .rodata section by setting the --pascal-rodata-string-guesser option. The default value is 0 (disabled). ```bash --pascal-rodata-string-guesser ``` -------------------------------- ### Elf32File Constructor Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ELF32File.md Initializes an Elf32File object by parsing raw ELF file content. This process includes parsing headers, detecting endianness, processing sections, symbol tables, and relocations. ```APIDOC ## Elf32File Constructor ### Description Initializes an Elf32File object by parsing raw ELF file content. This process includes parsing headers, detecting endianness, processing sections, symbol tables, and relocations. ### Method __init__ ### Parameters #### Constructor Parameters - **array_of_bytes** (bytes) - Required - Raw ELF file content ``` -------------------------------- ### InstructionAnalyzer Constructor Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/InstructionAnalyzer.md Initializes the InstructionAnalyzer with a base VRAM address and a symbol context for pointer tracking. ```APIDOC ## InstructionAnalyzer Constructor ### Description Initializes the InstructionAnalyzer with a base VRAM address and a symbol context for pointer tracking. ### Parameters #### Path Parameters - **vram** (int) - Yes - Base VRAM address of function - **context** (Context) - Yes - Symbol context for pointer tracking ``` -------------------------------- ### Register spimdisasm Configuration Options with argparse Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Front-end scripts can integrate spimdisasm configuration options into their argument parsing using the GlobalConfig.addParametersToArgParse method. This requires importing argparse and GlobalConfig. ```python from spimdisasm.common import GlobalConfig import argparse parser = argparse.ArgumentParser() GlobalConfig.addParametersToArgParse(parser) args = parser.parse_args() ``` -------------------------------- ### Register GlobalConfig Parameters with argparse Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/GlobalConfig.md Use this method to register all configuration options as command-line arguments for an argparse parser. This is useful for exposing spimdisasm's configuration settings in CLI tools. ```python from spimdisasm import common import argparse parser = argparse.ArgumentParser() common.GlobalConfig.addParametersToArgParse(parser) args = parser.parse_args() ``` -------------------------------- ### All File Sections List Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/types.md Defines a comprehensive list of all possible file section types, including standard sections and exception tables. Use this when dealing with binaries that may contain advanced section types. ```python FileSections_ListAll: list[FileSectionType] = [ FileSectionType.Text, FileSectionType.Data, FileSectionType.Rodata, FileSectionType.Bss, FileSectionType.GccExceptTable, ] ``` -------------------------------- ### Enable verbose logging Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Enable verbose logging for detailed output. The default is False. Can also be set via the VERBOSE=1 environment variable. ```cli --verbose ``` -------------------------------- ### Accessing spimdisasm Components via Module Path Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/module-overview.md Illustrates how to access spimdisasm functionalities by referencing their full module paths. This is useful when you need to use specific components without importing them directly into the current namespace. ```python # Via module path ctx = spimdisasm.common.Context() section = spimdisasm.mips.sections.SectionText(...) elf = spimdisasm.elf32.Elf32File(data) ``` -------------------------------- ### String Detection Workflow for ContextSymbol Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/ContextSymbol.md Demonstrates the workflow for detecting if a symbol's content might be a string. It involves setting initial detection flags, attempting to decode the string, and updating symbol properties based on the decoding result. ```python # Initial detection sym.isMaybeString = True sym.autodetectedType = "asciz" # Attempt decoding try: decoded = decode_string(sym.address, sym.segment) sym.failedStringDecoding = False print(f"String: {decoded}") except: # Failed to decode sym.failedStringDecoding = True sym.isMaybeString = False # Downgrade confidence ``` -------------------------------- ### Binary Output Option Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/configuration.md Enables writing split binary files. This option is a boolean type. ```bash --write-binary Write split binary files Default: False Type: bool ``` -------------------------------- ### Enable Function Analysis Debug Info Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/InstructionAnalyzer.md Shows how to enable the printing of detailed function analysis debug information, including register state and instruction details. ```python common.GlobalConfig.PRINT_FUNCTION_ANALYSIS_DEBUG_INFO = True ``` -------------------------------- ### File Analysis Workflow Source: https://github.com/decompollaborate/spimdisasm/blob/1.x/_autodocs/api-reference/FileSplits.md Perform a complete analysis of a file's sections, check for unimplemented instructions, save output files, and generate hash comparisons. This is the primary workflow for processing files. ```python splits = mips.FileSplits(...) # 1. Analyze all sections in order splits.analyze() # 2. Check for unimplemented instructions for section in splits.sectionsDict[common.FileSectionType.Text].values(): for func in section.symbolList: if hasattr(func, 'hasUnimplementedIntrs') and func.hasUnimplementedIntrs: print(f"Unimplemented: {func.getName()}") # 3. Write output files for section_type, sections_dict in splits.sectionsDict.items(): for filename, section in sections_dict.items(): output_name = f"{filename}_{section.vram:08X}.s" section.saveToFile(f"output/{output_name}") # 4. Generate comparison report for section_type, sections_dict in splits.sectionsDict.items(): for filename, section in sections_dict.items(): hash_val = section.getHash() print(f"{filename}: {hash_val}") ```