Skip to content

Instantly share code, notes, and snippets.

@tqinli
Last active March 23, 2022 16:37
Show Gist options
  • Save tqinli/78a5ddc3c60d18079c003ba189a991e2 to your computer and use it in GitHub Desktop.
Save tqinli/78a5ddc3c60d18079c003ba189a991e2 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import ctypes
import sys
import os
import time
PTRACE_ATTACH = 16
PTRACE_DETACH = 17
try:
pid = int(sys.argv[1])
except:
print("Usage: prog <pid>")
exit()
libc = ctypes.CDLL('/lib/x86_64-linux-gnu/libc.so.6')
libc.ptrace.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_void_p]
libc.ptrace.restype = ctypes.c_uint64
def logstat(tid, stat):
if os.WIFSTOPPED(stat[1]):
if os.WSTOPSIG(stat[1]) == 19:
pass
else:
print("ERROR: tid [{}] - stopped for some other signal? {}".format(tid, os.WSTOPSIG(stat[1])))
else:
print("ERROR: tid [{}] - unknown results: {}".format(tid, stat[1]))
def suspend(tid):
ret = libc.ptrace(PTRACE_ATTACH, tid, None, None)
if -1 != ret:
stat = os.waitpid(tid, 0)
logstat(tid, stat)
else:
print('ERROR: ptrace(PTRACE_ATTACH, {}) returned {}'.format(tid, ret))
def resume(tid):
ret = libc.ptrace(PTRACE_DETACH, tid, None, None)
if -1 != ret:
try:
stat = os.waitpid(tid, 0)
except ChildProcessError as e:
if 10 != e.errno:
print('ERROR: waitpid after PTRACE_DETACH threw {}'.format(tid, e))
else:
print('ERROR: ptrace(PTRACE_DETACH, {}) returned {}'.format(tid, ret))
taskDir = '/proc/{}/task'.format(pid)
tids = list(os.listdir(taskDir))
for f in tids:
tid = int(f)
suspend(tid)
resume(tid)
print('INFO: signaled {} threads...'.format(len(tids)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment