1
0
Fork 0

Add reproduction for failing to attach

This commit is contained in:
Duncan Ogilvie 2026-05-27 23:30:24 +02:00
parent e8645119b4
commit d1216c56cd
7 changed files with 266 additions and 6 deletions

View File

@ -174,6 +174,7 @@ set(X64DBG_STANDARD_TESTS
issue3803
issue3808
issue3865
cmdline_attach
cmdline_init
cmdline_setcommandline
guard_page

View File

@ -29,6 +29,8 @@ src/tests/<rel>/
optional plugin.cpp
test.txt
optional test.<variant>.txt
optional driver.py
optional driver.<variant>.py
optional check.py
optional check.<variant>.py
optional absolute_cf
@ -41,6 +43,7 @@ Conventions:
- `plugin.cpp` is optional; if present it is built automatically as `<rel>.dp32|dp64`
- `test.txt` is the primary script for test id `<rel>`
- `test.<variant>.txt` creates test id `<rel>/<variant>`
- `driver.py` and `driver.<variant>.py` are optional Python drivers for tests that need custom process setup before headless starts
- `check.py` and `check.<variant>.py` are optional fallback validators used by `run.py`
- `absolute_cf` makes `run.py` pass the script path to `-cf` as an absolute path

View File

@ -0,0 +1,11 @@
# cmdline_attach
Regression test for command-line attach startup handling.
The Python driver starts `cmdline_attach.exe`, waits for its ready line, then launches:
```text
headless.exe -testing -p <pid> -cf test.txt
```
The script asserts that the attach command completed and set `$pid`/`$hp`, then detaches. A startup attach freeze is reported as a headless timeout.

View File

@ -0,0 +1,157 @@
from __future__ import annotations
import argparse
import os
import queue
import subprocess
import sys
import threading
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Drive the command-line attach regression test.")
parser.add_argument("--headless", required=True)
parser.add_argument("--debuggee", required=True)
parser.add_argument("--script", required=True)
parser.add_argument("--runtime-dir", required=True)
parser.add_argument("--userdir", required=True)
parser.add_argument("--log", required=True)
parser.add_argument("--artifacts-dir", required=True)
parser.add_argument("--engine", required=True)
parser.add_argument("--timeout", type=int, required=True)
parser.add_argument("--no-console-window", action="store_true")
return parser.parse_args()
def path_arg(path: Path, cwd: Path) -> str:
try:
return os.path.relpath(path, cwd)
except ValueError:
return str(path)
def append_log(log_path: Path, text: str) -> None:
log_path.parent.mkdir(parents=True, exist_ok=True)
with log_path.open("a", encoding="utf-8", errors="replace") as log_file:
log_file.write(text)
if not text.endswith("\n"):
log_file.write("\n")
def fail(log_path: Path, reason: str, message: str) -> int:
append_log(log_path, f'[x64dbg-test] ASSERT FAIL source=driver message="{message}"')
append_log(log_path, f"[x64dbg-test] FINAL status=fail asserts=1 reason={reason}")
return 1
def wait_for_ready(process: subprocess.Popen[str], timeout: float) -> str | None:
if process.stdout is None:
return None
lines: queue.Queue[str] = queue.Queue(maxsize=1)
def read_line() -> None:
lines.put(process.stdout.readline())
threading.Thread(target=read_line, daemon=True).start()
try:
line = lines.get(timeout=timeout)
except queue.Empty:
return None
if process.poll() is not None or not line:
return None
return line.strip()
def stop_target(process: subprocess.Popen[str]) -> None:
if process.poll() is not None:
return
try:
if process.stdin is not None:
process.stdin.write("\n")
process.stdin.flush()
process.wait(timeout=5)
return
except Exception:
pass
try:
process.terminate()
process.wait(timeout=5)
except Exception:
try:
process.kill()
except Exception:
pass
def main() -> int:
args = parse_args()
headless = Path(args.headless).resolve()
debuggee = Path(args.debuggee).resolve()
script = Path(args.script).resolve()
userdir = Path(args.userdir).resolve()
log_path = Path(args.log).resolve()
artifacts_dir = Path(args.artifacts_dir).resolve()
headless_dir = headless.parent
artifacts_dir.mkdir(parents=True, exist_ok=True)
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if args.no_console_window else 0
target = subprocess.Popen(
[str(debuggee)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
creationflags=creationflags,
)
try:
ready_line = wait_for_ready(target, timeout=10)
if not ready_line or not ready_line.startswith("ready "):
return fail(log_path, "target_not_ready", f"target did not print a ready line: {ready_line!r}")
command = [
str(headless),
"-testing",
"-userdir",
str(userdir),
"-p",
str(target.pid),
"-c",
f'RedirectLog "{path_arg(log_path, headless_dir)}"',
"-cf",
path_arg(script, headless_dir),
]
print("[cmdline-attach-driver] " + " ".join(command), flush=True)
try:
completed = subprocess.run(
command,
cwd=headless_dir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=args.timeout,
text=True,
encoding="utf-8",
errors="replace",
creationflags=creationflags,
)
except subprocess.TimeoutExpired as exc:
output = exc.stdout or ""
(artifacts_dir / "headless.stdout.txt").write_text(output + "\n[TIMEOUT]\n", encoding="utf-8", errors="replace")
return fail(log_path, "headless_timeout", "headless timed out while attaching with -p")
(artifacts_dir / "headless.stdout.txt").write_text(completed.stdout, encoding="utf-8", errors="replace")
if completed.returncode != 0:
return fail(log_path, f"headless_exit_{completed.returncode}", f"headless exited with {completed.returncode}")
return 0
finally:
stop_target(target)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,17 @@
#include <windows.h>
#include <cstdio>
extern "C" __declspec(dllexport) void CmdlineAttachTargetMarker()
{
}
int main()
{
std::printf("ready %lu\n", GetCurrentProcessId());
std::fflush(stdout);
// Keep the process alive until the Python driver releases stdin.
(void)std::getchar();
return 0;
}

View File

@ -0,0 +1,3 @@
testassert $pid != 0, "attach command line set $pid"
testassert $hp != 0, "attach command line set $hp"
detach

View File

@ -33,6 +33,7 @@ class TestCase:
runtime_script: Path
debuggee: Path
plugins: list[Path]
driver: Path | None
fallback_check: Path | None
absolute_command_file: bool
@ -106,13 +107,21 @@ def test_id_from_rel(rel_dir: str, variant: str) -> str:
return f"{rel_dir}/{variant}" if rel_dir else variant
def variant_check_path(source_dir: Path, variant: str) -> Path | None:
def variant_python_hook_path(source_dir: Path, variant: str, stem: str) -> Path | None:
if variant:
check_path = source_dir / f"check.{variant}.py"
if check_path.is_file():
return check_path
check_path = source_dir / "check.py"
return check_path if check_path.is_file() else None
hook_path = source_dir / f"{stem}.{variant}.py"
if hook_path.is_file():
return hook_path
hook_path = source_dir / f"{stem}.py"
return hook_path if hook_path.is_file() else None
def variant_check_path(source_dir: Path, variant: str) -> Path | None:
return variant_python_hook_path(source_dir, variant, "check")
def variant_driver_path(source_dir: Path, variant: str) -> Path | None:
return variant_python_hook_path(source_dir, variant, "driver")
def discover_tests(repo_root: Path, arch: str, requested: set[str], validate_runtime: bool = True) -> list[TestCase]:
@ -145,6 +154,7 @@ def discover_tests(repo_root: Path, arch: str, requested: set[str], validate_run
runtime_script=runtime_script,
debuggee=debuggee,
plugins=sorted(runtime_dir.glob(f"*{plugin_suffix}")),
driver=variant_driver_path(script.parent, variant),
fallback_check=variant_check_path(script.parent, variant),
absolute_command_file=(script.parent / ABSOLUTE_CF_MARKER).is_file(),
)
@ -254,6 +264,61 @@ def run_fallback_check(check_path: Path, log_path: Path, userdir: Path, runtime_
return True, "pass"
def run_driver_test(headless: Path, test: TestCase, timeout: int, artifact_dir: Path, userdir: Path, log_path: Path, stdout_path: Path, engine: str, no_console_window: bool) -> TestResult:
assert test.driver is not None
command = [
sys.executable,
str(test.driver),
"--headless",
str(headless),
"--debuggee",
str(test.debuggee),
"--script",
str(test.runtime_script),
"--runtime-dir",
str(test.runtime_dir),
"--userdir",
str(userdir),
"--log",
str(log_path),
"--artifacts-dir",
str(artifact_dir),
"--engine",
engine,
"--timeout",
str(timeout),
]
if no_console_window:
command.append("--no-console-window")
try:
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
completed = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=timeout + 15,
text=True,
encoding="utf-8",
errors="replace",
creationflags=creationflags,
)
stdout_path.write_text(completed.stdout, encoding="utf-8", errors="replace")
except subprocess.TimeoutExpired as exc:
stdout_path.write_text((exc.stdout or "") + "\n[DRIVER TIMEOUT]\n", encoding="utf-8", errors="replace")
return TestResult(test.rel, False, "driver_timeout", None, None, artifact_dir)
passed, asserts, reason = parse_final_line(log_path)
if completed.returncode != 0:
passed = False
if reason in {"pass", "missing_final"}:
reason = f"driver_exit_{completed.returncode}"
if passed and test.fallback_check is not None:
passed, reason = run_fallback_check(test.fallback_check, log_path, userdir, test.runtime_dir, artifact_dir)
return TestResult(test.rel, passed, reason, asserts, completed.returncode, artifact_dir)
def run_test(headless: Path, test: TestCase, timeout: int, artifact_root: Path, engine: str, no_console_window: bool) -> TestResult:
artifact_dir = artifact_root / test.rel.replace("/", "__")
if artifact_dir.exists():
@ -266,6 +331,9 @@ def run_test(headless: Path, test: TestCase, timeout: int, artifact_root: Path,
log_path = artifact_dir / "debug.log"
stdout_path = artifact_dir / "stdout.txt"
if test.driver is not None:
return run_driver_test(headless, test, timeout, artifact_dir, userdir, log_path, stdout_path, engine, no_console_window)
headless_dir = headless.parent
command = [
str(headless),