Skip to content

Instantly share code, notes, and snippets.

@Mikael-Lovqvist
Last active October 7, 2021 22:57
Show Gist options
  • Save Mikael-Lovqvist/b780f2adf0f430558d9bb690000973c8 to your computer and use it in GitHub Desktop.
Save Mikael-Lovqvist/b780f2adf0f430558d9bb690000973c8 to your computer and use it in GitHub Desktop.
Python script for gdb, uses procfs to monitor task state then stores timestamp and backtrace to file
import pathlib, re, time
line_pattern = re.compile(r'(.*?):\s+(.*)')
'''
Example usage, note that MODULE is this file and is in the directory you run gdb from
Note that gdb needs root privs
# gdb /bin/subl3 -p $(pidof subl3)
pi
>>> import sys
>>> sys.path.append('.')
>>> import MODULE as A
>>> A.experiment('this_file_will_be_overwritten.txt')
'''
def wait_for_task_state(proc_id, task_id, target_state, polling_interval=0.01):
task_dir = pathlib.Path(f'/proc/{proc_id}/task')
while True:
info = dict(match.groups() for match in line_pattern.finditer((task_dir / f'{task_id}/status').read_text()))
if info['State'][0] == target_state:
break
time.sleep(polling_interval)
def info_file_to_dict(path):
return dict(match.groups() for match in line_pattern.finditer((path).read_text()))
def find_task(proc_id, task_name):
task_dir = pathlib.Path(f'/proc/{proc_id}/task')
for task in task_dir.iterdir():
info = info_file_to_dict(task / 'status')
if info['Name'] == task_name:
return task.name
def enumerate_pid_matching_name(proc_name):
results = list()
for proc in pathlib.Path(f'/proc').iterdir():
if proc.name.isdigit():
info = info_file_to_dict(proc / 'status')
if info['Name'] == proc_name:
results.append(proc.name)
return results
def get_backtrace(frame):
result = list()
while frame:
result.append(frame)
frame = frame.older()
return result
def experiment(target_file):
import signal, gdb, threading
s3pid, = enumerate_pid_matching_name('subl3')
s3tid = find_task(s3pid, 'subl3')
def wait():
wait_for_task_state(s3pid, s3tid, 'R')
signal.raise_signal(signal.SIGINT)
gdb.execute("set pagination off") #This prevents things to stop when there is long output since gdb will output a summary automatically
#Of course this hook could be modified to not do that but pagination off is probably still a good idea
with open(target_file, 'w') as outfile:
while True:
threading.Thread(target=wait).start()
gdb.execute('c')
bt = get_backtrace(gdb.newest_frame())
print(time.time(), ' → '.join(f'{f.name() or "??"}[0x{f.pc():x}]' for f in bt), file=outfile, flush=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment