1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
|
import subprocess
import sys
import pytest
from memray import AllocatorType
from memray import FileReader
from memray.commands.attach import debugger_available
from tests.utils import filter_relevant_allocations
PROGRAM = """
import sys
import threading
from memray._test import MemoryAllocator
stop_bg_thread = threading.Event()
def bg_thread_body():
bg_allocator = MemoryAllocator()
while not stop_bg_thread.is_set():
bg_allocator.malloc(1024)
bg_allocator.free()
def foo():
bar()
def bar():
baz()
def baz():
allocator = MemoryAllocator()
allocator.valloc(50 * 1024 * 1024)
allocator.free()
# attach waits for a call to an allocator or deallocator, so we can't just
# block waiting for a signal. Allocate and free in a loop in the background.
bg_thread = threading.Thread(target=bg_thread_body)
bg_thread.start()
print("ready")
for line in sys.stdin:
if not stop_bg_thread.is_set():
stop_bg_thread.set()
bg_thread.join()
foo()
"""
def generate_attach_command(method, output, *args):
cmd = [
sys.executable,
"-m",
"memray",
"attach",
"--verbose",
"--force",
"--method",
method,
"-o",
str(output),
]
if args:
cmd.extend(args)
return cmd
def generate_detach_command(method, *args):
cmd = [
sys.executable,
"-m",
"memray",
"detach",
"--verbose",
"--method",
method,
]
if args:
cmd.extend(args)
return cmd
def run_process(cmd, wait_for_stderr=False):
process_stderr = ""
tracked_process = subprocess.Popen(
[sys.executable, "-uc", PROGRAM],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
# Help the type checker out...
assert tracked_process.stdin is not None
assert tracked_process.stdout is not None
assert tracked_process.stdout.readline() == "ready\n"
cmd.append(str(tracked_process.pid))
# WHEN
try:
subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True)
except subprocess.CalledProcessError as exc:
# The test has failed; we'd just wait forever.
wait_for_stderr = False
if "Couldn't write extended state status" in exc.output:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=898048
pytest.xfail("gdb < 8 does not support this CPU")
else:
print(exc.output)
raise
finally:
print("1", file=tracked_process.stdin, flush=True)
if wait_for_stderr:
process_stderr = tracked_process.stderr.readline()
while "WARNING" in process_stderr:
process_stderr = tracked_process.stderr.readline()
tracked_process.stdin.close()
tracked_process.wait()
# THEN
assert "" == tracked_process.stdout.read()
assert tracked_process.returncode == 0
return process_stderr
def get_call_stack(allocation):
return [f[0] for f in allocation.stack_trace()]
def get_relevant_vallocs(records):
return [
record
for record in filter_relevant_allocations(records)
if record.allocator == AllocatorType.VALLOC
]
@pytest.mark.parametrize("method", ["lldb", "gdb"])
def test_basic_attach(tmp_path, method):
if not debugger_available(method):
pytest.skip(f"a supported {method} debugger isn't installed")
# GIVEN
output = tmp_path / "test.bin"
attach_cmd = generate_attach_command(method, output)
# WHEN
run_process(attach_cmd)
# THEN
reader = FileReader(output)
(valloc,) = get_relevant_vallocs(reader.get_allocation_records())
assert get_call_stack(valloc) == ["valloc", "baz", "bar", "foo", "<module>"]
@pytest.mark.parametrize("method", ["lldb", "gdb"])
def test_aggregated_attach(tmp_path, method):
if not debugger_available(method):
pytest.skip(f"a supported {method} debugger isn't installed")
# GIVEN
output = tmp_path / "test.bin"
attach_cmd = generate_attach_command(method, output, "--aggregate")
# WHEN
run_process(attach_cmd)
# THEN
reader = FileReader(output)
with pytest.raises(
NotImplementedError,
match="Can't get all allocations from a pre-aggregated capture file.",
):
list(reader.get_allocation_records())
(valloc,) = get_relevant_vallocs(reader.get_high_watermark_allocation_records())
assert get_call_stack(valloc) == ["valloc", "baz", "bar", "foo", "<module>"]
@pytest.mark.parametrize("method", ["lldb", "gdb"])
def test_attach_time(tmp_path, method):
if not debugger_available(method):
pytest.skip(f"a supported {method} debugger isn't installed")
# GIVEN
output = tmp_path / "test.bin"
attach_cmd = generate_attach_command(method, output, "--duration", "1")
# WHEN
process_stderr = run_process(attach_cmd, wait_for_stderr=True)
# THEN
assert "memray: Deactivating tracking: 1 seconds have elapsed" in process_stderr
@pytest.mark.parametrize("method", ["lldb", "gdb"])
def test_detach_without_attach(method):
if not debugger_available(method):
pytest.skip(f"a supported {method} debugger isn't installed")
# GIVEN
detach_cmd = generate_detach_command(method)
# WHEN
with pytest.raises(subprocess.CalledProcessError) as exc_info:
run_process(detach_cmd)
# THEN
assert (
"Failed to stop tracking in remote process:"
" no previous `memray attach` call detected"
) in exc_info.value.stdout
|