To create a custom LLDB command that retrieves the image base address of the current debugged program and load it via .lldbinit, follow these steps:
1. Create the Python Script
Create a Python script that defines the custom LLDB command. Here's an example:
python
# File: ~/.lldb/commands/get_image_base.py
import lldb
def __lldb_init_module(debugger, internal_dict):
# Register the command with LLDB
debugger.HandleCommand('command script add -f get_image_base.get_image_base get_image_base')
print('The "get_image_base" command has been loaded.')
def get_image_base(debugger, command, result, internal_dict):
target = debugger.GetSelectedTarget()
if not target:
result.AppendWarning("No target selected.")
return
module = target.GetModuleAtIndex(0)
if not module:
result.AppendWarning("No modules loaded.")
return
header_addr = module.GetObjectFileHeaderAddress()
image_base = header_addr.GetLoadAddress(target)
if image_base == lldb.LLDB_INVALID_ADDRESS:
result.AppendError("Failed to get image base address.")
return
result.AppendMessage(f"Image base address: 0x{image_base:x}")
2. Load the Script in .lldbinit
Add the following line to your ~/.lldbinit file to load the script automatically when LLDB starts:
bash
# ~/.lldbinit
command script import ~/.lldb/commands/get_image_base.py
If you're using a different path for the script, adjust it accordingly.
3. Use the Command in LLDB
Start LLDB or reload the .lldbinit file:
bash
(lldb) get_image_base
Image base address: 0x100000000
Explanation
- The
__lldb_init_module function registers the command get_image_base with LLDB.
- The
get_image_base function performs the same logic as in your earlier Python code:
- Gets the selected target.
- Retrieves the first module (main executable).
- Gets the load address of the module's object file header.
- The result is printed directly in the LLDB console.
Optional: Manual Import Without .lldbinit
To test the script without editing .lldbinit, run this in LLDB:
bash
(lldb) command script import /path/to/get_image_base.py
Troubleshooting
- Ensure the script path in
.lldbinit is correct.
- Check file permissions (the script must be readable).
- If LLDB fails to load the script, check for Python syntax errors.