# elfparser **Repository Path**: stesen/elfparser ## Basic Information - **Project Name**: elfparser - **Description**: elf文件的解析和反汇编工具,基于rust,caoptone,graphviz,代码全是AI xjbx的 - **Primary Language**: Rust - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-06 - **Last Updated**: 2026-03-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ELF Parser **English Documentation** | [中文文档](README.md) --- ## Project Overview **ELF Parser** is a high-performance ELF file parsing and disassembly tool built with Rust, supporting multi-architecture disassembly, control flow graph generation, DWARF debug info parsing, and AI assistant integration. - **Repository**: https://gitee.com/stesen/elfparser/ - **Version**: 0.10.0 - **License**: Apache License 2.0 - **Language**: Rust (89.3%), Python (5.7%), Shell (4.1%) --- ## Core Features ### 1. ELF File Parsing - **Supported Formats**: 32-bit/64-bit ELF - **Display Info**: Sections, Segments, Program Headers, Section Headers, Relocations, Dynamic Section, Note Sections - **Compatibility**: Provides functionality similar to `readelf -a` ### 2. Multi-Architecture Disassembly - **Supported Architectures**: - ARM64 (AArch64) - x86 (32-bit) - x86_64 (64-bit) - ARM (32-bit) - **Disassembly Engine**: Capstone - **Jump Instructions**: - ARM64: `b`, `b.cond`, `bl`, `blr`, `br`, `cbz`, `cbnz`, `tbz`, `tbnz`, `ret` - x86/x64: `jmp`, `je/jne`, `jz/jnz`, `call`, `ret`, etc. ### 3. Control Flow Graph Generation - **Layout Algorithm**: Sugiyama hierarchical layout algorithm - **Output Formats**: - **DOT**: Graphviz graph description file - **PDF**: Vector graphics format (requires Graphviz) - **Excalidraw**: Hand-drawn style (can be imported to excalidraw.com) - **GUI**: Interactive graphical interface (supports drag and zoom) - **TUI**: Terminal interactive interface (keyboard navigation) - **Features**: - Automatic node position optimization, reducing edge crossings - Smart handling of back edges (loops), using Bezier curves for elegant connections - Color syntax highlighting (Atom Code Dark/Light themes) ### 4. Type Graph Generation - **Function**: Visualize member relationship graphs of C++ classes/structs - **Display Content**: - Member variable offsets and sizes - Inheritance relationships (base classes) - Pointer/reference type relationships - Hierarchical structures of nested types - **Supported Formats**: DOT, PDF, GUI, TUI, Excalidraw ### 5. DWARF Debug Info Parsing - **Supported Tags**: - `DW_TAG_subprogram`: Functions/subroutines - `DW_TAG_class_type`: Class types - `DW_TAG_structure_type`: Struct types - `DW_TAG_union_type`: Union types - `DW_TAG_member`: Member variables - `DW_TAG_inheritance`: Inheritance relationships - `DW_TAG_typedef`: Type definitions - `DW_TAG_enumeration_type`: Enumeration types - `DW_TAG_pointer_type`: Pointer types - `DW_TAG_reference_type`: Reference types - **Source Location**: Display source file paths and line numbers for functions and classes - **Accuracy**: Exactly matches `addr2line` ### 6. Smart Annotations - **Verbose Mode**: `-v` parameter adds natural language explanations for each assembly instruction - **Function Analysis**: Analyze overall function behavior (stack allocation, conditional branches, external calls, etc.) ### 7. MCP Server - **Protocol**: Model Context Protocol (MCP) over stdio - **AI Assistant Integration**: Supports Claude Desktop, Cursor, etc. - **Provided Tools**: - `mcp_elf_analyze_file`: Analyze ELF file basic info - `mcp_elf_list_symbols`: List symbol table - `mcp_elf_resolve_address`: Resolve address to source location - `mcp_elf_find_function`: Find function information - `mcp_elf_disassemble_function`: Disassemble function - **Provided Resources**: Access ELF file data via `elf://` URI protocol --- ## Usage ### Basic Usage ```bash # Show ELF basic info elfparser -a # Disassemble at address elfparser -d 0x1234 elfparser -d 10342380 # Decimal # Verbose mode (with explanations) elfparser -d 0x1234 -v ``` ### Control Flow Graph Generation ```bash # Generate DOT format elfparser -d 0x1234 --dot # Generate PDF (requires Graphviz) elfparser -d 0x1234 --pdf # Recommended: DOT to PDF elfparser -d 0x1234 --dot2pdf # Generate Excalidraw elfparser -d 0x1234 --excalidraw # Launch GUI elfparser -d 0x1234 --gui # Launch TUI elfparser -d 0x1234 --tui ``` ### Symbol Query ```bash # Query function symbol elfparser -s function_name # Query class/struct elfparser -s ClassName # Generate type graph elfparser -s ClassName --dot elfparser -s ClassName --pdf elfparser -s ClassName --gui elfparser -s ClassName --tui ``` ### MCP Server ```bash # Start MCP server elfparser --mcp ``` **Claude Desktop Configuration**: ```json { "mcpServers": { "elfparser": { "command": "/path/to/elfparser", "args": ["--mcp"] } } } ``` **Cursor Configuration** (`.cursor/mcp.json`): ```json { "mcpServers": { "elfparser": { "command": "/path/to/elfparser", "args": ["--mcp"] } } } ``` --- ## Project Structure ``` elfparser/ ├── Cargo.toml # Project configuration ├── src/ │ ├── main.rs # Main entry │ ├── core/ # Core types │ │ ├── mod.rs # Core type definitions │ │ ├── types.rs # VirtualAddress and basic types │ │ ├── address.rs # Address types (Newtype pattern) │ │ └── location.rs # Source locations │ ├── domain/ # Domain layer │ │ ├── dwarf/ # DWARF domain models │ │ │ ├── type_graph.rs # Type graph data structures │ │ │ └── type_graph_builder.rs # Type graph builder │ │ └── elf/ # ELF domain models │ ├── dwarf_parser.rs # DWARF debug info parsing │ ├── disasm.rs # Disassembly module │ ├── instruction.rs # Instruction definitions │ ├── generate_function_graph.rs # Function CFG generation │ ├── layout/ # Layout algorithms │ │ ├── sugiyama.rs # Sugiyama hierarchical layout │ │ └── legacy.rs # Legacy layout algorithms │ ├── gui.rs # GUI interface │ ├── tui.rs # TUI interface │ ├── output/ # Output formats │ │ ├── pdf.rs # PDF generation │ │ ├── dot.rs # DOT format │ │ ├── mermaid.rs # Mermaid format │ │ ├── excalidraw.rs # Excalidraw format │ │ ├── type_pdf.rs # Type graph PDF │ │ └── type_dot.rs # Type graph DOT │ └── mcp/ # MCP server │ ├── mod.rs # MCP server entry │ ├── handlers.rs # Tool and resource handlers │ └── protocol.rs # MCP protocol definitions ├── scripts/ # Build scripts │ ├── build-release.sh # Linux multi-platform build │ ├── build-release.bat # Windows build │ └── build-release.py # Python build script ├── tests/ # Tests └── docs/ # Documentation ``` --- ## Dependencies ### Required Dependencies | Dependency | Version | Purpose | |------------------|----------------|----------------| | capstone | 0.14 | Disassembly engine | | gimli | 0.29 | DWARF parsing library | | object | 0.35 | Object file parsing | | goblin | 0.10 | ELF parsing | | clap | 4.0 | CLI parsing | | memmap2 | 0.9 | Memory mapping | | printpdf | 0.7 | PDF generation | | serde | 1.0 | Serialization | | serde_json | 1.0 | JSON processing | | hex | 0.4 | Hex encoding | | dirs | 5.0 | Directory operations | ### Optional Dependencies | Dependency | Version | Purpose | Feature Flag | Supported Platforms | |------------------|----------------|----------------|------------------------|----------| | iced | 0.13 | GUI | `gui` | Linux, Windows | | clipboard | 0.5 | Clipboard | `gui` | Linux, Windows | | ratatui | 0.29 | TUI | `tui` | All platforms | | crossterm | 0.28 | Terminal control | `tui` | All platforms | ### System Dependencies - **Capstone Library**: Core disassembly engine - **Graphviz** (optional): For DOT to PDF conversion - **X11 dev libraries** (Linux GUI required): libxcb-render0-dev, libxcb-shape0-dev, libxcb-xfixes0-dev ### Platform Support | Platform | GUI | TUI | PDF | CLI | Build Command | |------|-----|-----|-----|-----|----------| | Linux x86_64 | ✅ | ✅ | ✅ | ✅ | `cargo build --release` | | Windows | ✅ | ✅ | ✅ | ✅ | `cargo build --release` | | Android | ❌ | ❌ | ❌ | ✅ | `scripts/mobile-dev build android-aarch64` | | OpenHarmony | ❌ | ❌ | ❌ | ✅ | `scripts/mobile-dev build ohos-aarch64` | **Note**: Android and OpenHarmony only support CLI core features (ELF parsing, disassembly, symbol query, DOT/Excalidraw output). GUI, TUI, and PDF generation are not supported. --- ## Installation ### Build from Source ```bash # Clone repository git clone https://gitee.com/stesen/elfparser.git cd elfparser # Build debug version cargo build # Build release version cargo build --release # Build with specific features cargo build --features "gui tui" # Enable GUI and TUI cargo build --no-default-features # CLI only ``` ### Install Capstone **Ubuntu/Debian**: ```bash sudo apt-get install libcapstone-dev ``` **macOS**: ```bash brew install capstone ``` **Windows**: 1. Download pre-built version: https://github.com/capstone-engine/capstone/releases 2. Copy `capstone.dll` to system or project directory ### Install Graphviz (Optional) **Ubuntu/Debian**: ```bash sudo apt-get install graphviz ``` **macOS**: ```bash brew install graphviz ``` **Windows**: ```bash # Using Chocolatey choco install graphviz ``` --- ## Command Line Arguments ``` Usage: elfparser [OPTIONS] Arguments: ELF file path Options: -a Show all ELF info -d
Disassemble at address -v, --verbose Verbose mode -V, --version Show version --dot Generate DOT format CFG --dot2pdf Generate DOT and auto-convert to PDF --pdf Generate PDF format CFG --excalidraw Generate Excalidraw format --tui Launch TUI --gui Launch GUI --mcp Start MCP server -s Query symbol name -h, --help Show help ``` --- ## Architecture Design ### Layered Architecture ``` ┌─────────────────────────────────────────────────────────────┐ │ Presentation Layer (GUI/TUI/MCP/Output) │ ├─────────────────────────────────────────────────────────────┤ │ Application Layer (Use Cases) │ ├─────────────────────────────────────────────────────────────┤ │ Domain Layer (Business Logic) │ ├─────────────────────────────────────────────────────────────┤ │ Core Layer (Fundamental Types) │ ├─────────────────────────────────────────────────────────────┤ │ Infrastructure Layer (External Systems) │ └─────────────────────────────────────────────────────────────┘ ``` ### Key Design Patterns 1. **Newtype Pattern**: Type-safe address handling - `VirtualAddress`, `PhysicalAddress`, `FileOffset` 2. **Caching**: - `SourceLocationCache`: O(1) address to source location query - `FunctionCache`: Pre-calculated function boundaries 3. **Batch Query**: - `get_source_locations_batch()`: Batch address resolution --- ## Color Themes ### Flat Mode (Default) - **Theme**: Atom Code Dark | Element | Color | RGB | |---------------|-------------|-----| | Address | Orange | #d19a66 | | Jump | Red | #e06c75 | | Instruction | Purple | #c678dd | | Operands | Cyan | #56b6c2 | | Comment | Gray | #5c6370 | ### PDF Mode - **Theme**: Atom Code Light | Element | Color | RGB | |---------------|-------------|-----| | Address | Orange | #986801 | | Jump | Red | #ca1243 | | Instruction | Purple | #a626a4 | | Operands | Green | #50a14f | --- ## Testing ```bash # Run all tests cargo test # Run library tests cargo test --lib # Run specific test cargo test test_name # Run integration tests cargo test -- --ignored # Show output cargo test -- --nocapture ``` --- ## Cross Compilation ### Android **Prerequisites**: Install Android NDK (r21 or higher) ```bash # 1. Download and install Android NDK # https://developer.android.com/ndk/downloads # 2. Set environment variables export NDK_HOME=/path/to/android-ndk-r25c export PATH=$NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH # 3. Build (using script) scripts/mobile-dev build android-aarch64 # Or build manually cargo build --release --target aarch64-linux-android --no-default-features ``` ### OpenHarmony **Prerequisites**: Install musl cross-compilation toolchain ```bash # 1. Download musl cross-compilation toolchain # aarch64: https://musl.cc/aarch64-linux-musl-cross.tgz # x86_64: https://musl.cc/x86_64-linux-musl-cross.tgz # 2. Extract and set environment variables export PATH=/path/to/aarch64-linux-musl-cross/bin:$PATH # 3. Build (using script) scripts/mobile-dev build ohos-aarch64 # Or build manually cargo build --release --target aarch64-unknown-linux-musl --no-default-features ``` **Note**: OpenHarmony build requires musl cross-compiler. Without it, you will get `incompatible with elf_x86_64` error. --- ## Troubleshooting ### Compilation Error: capstone not found ```bash # Ubuntu/Debian sudo apt-get install libcapstone-dev # Set environment variables export CAPSTONE_LIB_DIR=/usr/lib export CAPSTONE_INCLUDE_DIR=/usr/include ``` ### Link Error: xcb library not found ```bash # Error: unable to find library -lxcb-render # This is the X11 library required by GUI features # Solution 1: Install X11 development libraries (if you need GUI) sudo apt-get install libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev # Solution 2: Disable GUI feature (recommended for servers/headless environments) cargo build --release --no-default-features # CLI only cargo build --release --no-default-features --features tui # CLI + TUI ``` ### PDF Generation Failed ```bash # Check Graphviz installation dot -V # Generate PDF manually dot -Tpdf input.dot -o output.pdf ``` ### DWARF Query Failed ```bash # Check DWARF info readelf --debug-dump=info | head -20 readelf --debug-dump=line | head -20 ``` --- ## Comparison with addr2line | Feature | addr2line | elfparser MCP | |---------------|-----------|---------------| | Address Resolution | ✅ | ✅ | | Symbol List | ❌ | ✅ | | Function Lookup | ❌ | ✅ | | AI Integration | ❌ | ✅ | | Batch Query | ❌ | ✅ | | File Caching | ❌ | ✅ | | Disassembly | ❌ | ✅ | | CFG | ❌ | ✅ | **Accuracy Verification**: elfparser address resolution accuracy exactly matches `addr2line`. --- ## Usage Examples ### 1. View ELF Info ```bash elfparser /bin/ls -a ``` ### 2. Disassemble and Generate PDF ```bash elfparser libexample.so -d 0x9db94c --dot2pdf -v ``` ### 3. Query Symbol Info ```bash elfparser libexample.so -s ngtcp2_gaptr_free ``` ### 4. Generate Type Graph ```bash elfparser libexample.so -s grpc::CompletionQueue --pdf ``` ### 5. Launch TUI ```bash elfparser libexample.so -d 0x9db94c --tui ``` --- ## Related Documentation - **Test Report**: [TEST_REPORT.md](TEST_REPORT.md) - **Claude Code Guide**: [CLAUDE.md](CLAUDE.md) - **MCP Design**: [MCP_DESIGN.md](MCP_DESIGN.md) - **Release Guide**: [RELEASE_GUIDE.md](RELEASE_GUIDE.md) --- ## Changelog ### v0.9.9 (2026-03-05) - **New**: Type graph visualization (DOT/PDF/GUI/TUI/Excalidraw) - **New**: C++ class/struct member relationship graph generation - **New**: Separate Chinese and English documentation - **Improved**: Compilation speed optimization - **Fixed**: Multiple compiler warnings and test cases ### v0.9.8 (2026-03-02) - **New**: MCP disassembly tool (`mcp_elf_disassemble_function`) - **New**: MCP test scripts and test suite - **Improved**: CLAUDE.md project architecture documentation ### v0.9.7 (2026-02-24) - **New**: Type graph generation feature - **New**: GUI/TUI support for type graph viewing - **Improved**: Sugiyama layout algorithm ### v0.9.6 (2026-02-18) - **New**: MCP server full implementation - **New**: DWARF debug info parsing enhancement --- ## Contributors - **Author**: [stesen](https://gitee.com/stesen) --- **Note**: All code is AI-generated (xjbx = random writing). --- *Document Generated*: 2026-03-05