Of course. Here is a complete guide on how to create a custom LLDB command in Python to get the image base address, and then how to load it automatically using your .lldbinit file.
Step 1: Create the Python Script for the Custom Command
First, we will create a Python file that defines our new command. Let's call the command baseaddr. The script needs to contain two main parts:
- A function that implements the logic of the command.
- An
__lldb_init_module function that LLDB calls to register the command when the script is imported.
Create a file named baseaddr.py and place the following code inside it. It's good practice to keep your LLDB scripts in a dedicated directory, for example, ~/lldb/scripts/.
File: ~/lldb/scripts/baseaddr.py
import lldb
import optparse
def get_base_address(debugger, command, result, internal_dict):
"""
LLDB command to print the base address of the main executable.
Usage: baseaddr
"""
# Get the current target from the debugger
target = debugger.GetSelectedTarget()
# Check if we have a valid target
if not target or not target.IsValid():
result.SetError("Error: Invalid target. Start a debug session first (e.g., 'run').")
return
# The main executable is usually the first module (at index 0)
main_module = target.GetModuleAtIndex(0)
# Check if we have a valid module
if not main_module or not main_module.IsValid():
result.SetError("Error: Could not find the main module for the current target.")
return
# Get the address of the module's header, which represents the base address
header_addr = main_module.GetObjectFileHeaderAddress()
# Get the actual address where it was loaded into memory by the OS
# This accounts for ASLR (Address Space Layout Randomization)
load_addr = header_addr.GetLoadAddress(target)
# Check if the address is valid
if load_addr == lldb.LLDB_INVALID_ADDRESS:
result.SetError("Error: Could not determine the load address for the main module.")
return
# Get the module name for a more descriptive output
module_name = main_module.GetFileSpec().GetFilename()
# Append the successful result to the 'result' object to be printed in the console
result.AppendMessage(f"Image base address for '{module_name}': 0x{load_addr:x}")
def __lldb_init_module(debugger, internal_dict):
"""
This function is called by LLDB when this script is imported.
It registers the 'baseaddr' command.
"""
# This adds the 'baseaddr' command to lldb.
# -f <module>.<function>: specifies the function to execute.
# The 'baseaddr.get_base_address' means it will call the 'get_base_address'
# function from this script file, which lldb names 'baseaddr'.
debugger.HandleCommand(
'command script add -f baseaddr.get_base_address baseaddr'
)
# Optional: Print a confirmation message to the console when lldb starts
print("The 'baseaddr' command has been loaded.")
Step 2: Load the Script in your .lldbinit File
Now, you need to tell LLDB to load this Python script every time it starts. You do this by adding a command to your ~/.lldbinit file.
- Open (or create) the file
~/.lldbinit in your home directory.
- Add the following line to the file. Make sure to replace the path with the actual path to where you saved
baseaddr.py.
File: ~/.lldbinit
# Import custom lldb scripts
command script import ~/lldb/scripts/baseaddr.py
- Using
~ works because it is automatically expanded to your home directory.
- If you placed the script elsewhere, use the full, absolute path.
Step 3: Run LLDB and Use the New Command
That's it! The next time you start LLDB, the script will be loaded automatically, and the baseaddr command will be available.
Example Usage:
-
Start a debug session with an executable.
$ lldb ./my_program
(lldb) target create "./my_program"
Current executable set to '/path/to/my_program' (x86_64).
-
Set a breakpoint and run the program. The base address is only determined once the program is loaded into memory.
(lldb) b main
Breakpoint 1: where = my_program`main, address = 0x0000000100003f50
(lldb) run
Process 12345 launched: '/path/to/my_program' (x86_64)
The 'baseaddr' command has been loaded. # <-- Confirmation from our script
Process 12345 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000100003f50 my_program`main
-> 0x100003f50 <+0>: push rbp
...
-
Now, use your custom command.
(lldb) baseaddr
Image base address for 'my_program': 0x100000000
You have now successfully created a reusable, custom LLDB command using the Python API and configured LLDB to load it on startup.