Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created March 29, 2025 17:04
Show Gist options
  • Save rnapier/f7bc0017c09f52108f7abf3ecbd8aed4 to your computer and use it in GitHub Desktop.
Save rnapier/f7bc0017c09f52108f7abf3ecbd8aed4 to your computer and use it in GitHub Desktop.
stack_usage lldb script
import lldb
# put this in ~/.lldb/stack_usage/stack_usage.py.
# Load in .lldbinit with `command script import "~/.lldb/stack_usage/stack_usage.py"`
# At a breakpoint, you can then type `stack_usage` to get the current stats.
@lldb.command("stack_usage")
def _stack_usage(debugger, command, result, internal_dict):
"""Show current stack usage information"""
target = debugger.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetSelectedThread()
# Get stack pointer from current frame
frame = thread.GetSelectedFrame()
sp = frame.GetSP()
# Get stack region info
res = lldb.SBCommandReturnObject()
interpreter = debugger.GetCommandInterpreter()
interpreter.HandleCommand("memory region $sp", res)
# Parse memory region output to get stack bounds
region_info = res.GetOutput().split('\n')[0]
if '[' in region_info and ')' in region_info:
bounds = region_info[region_info.find('[')+1:region_info.find(')')].split('-')
if len(bounds) == 2:
stack_start = int(bounds[0], 16)
stack_end = int(bounds[1], 16)
# Calculate usage
total_size = stack_end - stack_start
used_size = stack_end - sp
free_size = total_size - used_size
usage_percent = (used_size / total_size) * 100
print(f"Stack Usage:")
print(f"Total Size: {total_size:,} bytes")
print(f"Used Size: {used_size:,} bytes")
print(f"Free Size: {free_size:,} bytes")
print(f"Usage: {usage_percent:.1f}%")
return
print("Could not determine stack usage")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment