Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
hugsy committed Jan 9, 2024
1 parent 6b17dfe commit 3527392
Showing 1 changed file with 0 additions and 165 deletions.
165 changes: 0 additions & 165 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,171 +124,6 @@ def is_32b() -> bool:
return ARCH in CI_VALID_ARCHITECTURES_32B


def ansi_clean(s: str) -> str:
ansi_escape = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]")
return ansi_escape.sub("", s)


def gdb_run_cmd(
cmd: CommandType,
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
) -> str:
"""Execute a command inside GDB. `before` and `after` are lists of commands to be executed
before (resp. after) the command to test."""

def _add_command(commands: CommandType) -> List[str]:
if isinstance(commands, str):
commands = [commands]
return [_str for cmd in commands for _str in ["-ex", cmd]]

command = ["gdb", "-q", "-nx"]
if COVERAGE_DIR:
coverage_file = pathlib.Path(COVERAGE_DIR) / os.getenv(
"PYTEST_XDIST_WORKER", "gw0"
)
command += _add_command(
[
"pi from coverage import Coverage",
f'pi cov = Coverage(data_file="{coverage_file}",'
"auto_data=True, branch=True)",
"pi cov.start()",
]
)
command += _add_command(
[
f"source {GEF_PATH}",
"gef config gef.debug True",
]
)
command += _add_command(before)
command += _add_command(cmd)
command += _add_command(after)
if COVERAGE_DIR:
command += _add_command(["pi cov.stop()", "pi cov.save()"])
command += ["-ex", "quit", "--", str(target)]

lines = (
subprocess.check_output(command, stderr=subprocess.STDOUT).strip().splitlines()
)
output = b"\n".join(lines)
result = None

# The following is necessary because ANSI escape sequences might have been
# added in the middle of multibyte characters, e.g. \x1b[H\x1b[2J is added
# into the middle of \xe2\x94\x80 to become \xe2\x1b[H\x1b[2J\x94\x80 which
# causes a UnicodeDecodeError when trying to decode \xe2. Such broken
# multibyte characters would need to be removed, otherwise the test will
# result in an error.
while not result:
try:
result = output.decode("utf-8")
except UnicodeDecodeError as ude:
faulty_idx_start = int(ude.start)
faulty_idx_end = int(ude.end)
output = output[:faulty_idx_start] + output[faulty_idx_end:]

if strip_ansi:
result = ansi_clean(result)

return result


def gdb_run_silent_cmd(
cmd: CommandType,
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
) -> str:
"""Disable the output and run entirely the `target` binary."""
before = [
*before,
"gef config context.clear_screen False",
"gef config context.layout '-code -stack'",
"run",
]
return gdb_run_cmd(cmd, before, after, target, strip_ansi)


def gdb_run_cmd_last_line(
cmd: CommandType,
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
) -> str:
"""Execute a command in GDB, and return only the last line of its output."""
return gdb_run_cmd(cmd, before, after, target, strip_ansi).splitlines()[-1]


def gdb_start_silent_cmd(
cmd: CommandType,
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
context: str = DEFAULT_CONTEXT,
) -> str:
"""Execute a command in GDB by starting an execution context. This command
disables the `context` and sets a tbreak at the most convenient entry
point."""
before = [
*before,
"gef config context.clear_screen False",
f"gef config context.layout '{context}'",
"entry-break",
]
return gdb_run_cmd(cmd, before, after, target, strip_ansi)


def gdb_start_silent_cmd_last_line(
cmd: CommandType,
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi=STRIP_ANSI_DEFAULT,
) -> str:
"""Execute `gdb_start_silent_cmd()` and return only the last line of its output."""
return gdb_start_silent_cmd(cmd, before, after, target, strip_ansi).splitlines()[-1]


def gdb_test_python_method(
meth: str,
before: str = "",
after: str = "",
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
) -> str:
brk = before + ";" if before else ""
cmd = f"pi {brk}print({meth});{after}"
return gdb_start_silent_cmd(cmd, target=target, strip_ansi=strip_ansi)


def gdb_time_python_method(
meth: str,
setup: str,
py_before: str = "",
py_after: str = "",
before: CommandType = (),
after: CommandType = (),
target: pathlib.Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT,
number: int = 1000,
) -> float:
brk = py_before + ";" if py_before else ""
cmd = (
f"""pi import timeit;{brk}print(timeit.timeit("{meth}", """
f"""setup="{setup}", number={number}));{py_after}"""
)
lines = gdb_run_cmd(
cmd, before=before, after=after, target=target, strip_ansi=strip_ansi
).splitlines()
return float(lines[-1])


def debug_target(name: str, extension: str = ".out") -> pathlib.Path:
target = TMPDIR / f"{name}{extension}"
if not target.exists():
Expand Down

0 comments on commit 3527392

Please sign in to comment.