"""Exercise a VLS debug adapter on recorded GCC events using the public stdio protocol.""" import argparse import hashlib import json import queue import shutil import subprocess import tempfile import threading from pathlib import Path class Client: def __init__(self, adapter, trace): self.child = subprocess.Popen( [adapter, "--replay", trace], cwd=trace.parent, env={"PATH": "", "LC_ALL": "C"}, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.incoming = queue.Queue() self.reader = threading.Thread(target=self._read, daemon=True) self.reader.start() self.outgoing_seq = 0 self.incoming_seq = 0 def _read(self): try: stream = self.child.stdout while line := stream.readline(8192): assert line.startswith(b"Content-Length: ") and line.endswith(b"\r\n"), line length = int(line[16:]) assert 0 < length <= 16 * 1024 * 1024 and stream.readline(8192) == b"\r\n" self.incoming.put(json.loads(stream.read(length))) self.incoming.put(EOFError("adapter stdout closed")) except Exception as error: self.incoming.put(error) def __enter__(self): return self def __exit__(self, *exc): self.child.stdin.close() if self.child.poll() is None: self.child.kill() self.child.wait(timeout=5) self.reader.join(timeout=5) self.child.stdout.close() self.child.stderr.close() def send(self, command, args=None): self.outgoing_seq += 1 message = {"seq": self.outgoing_seq, "type": "request", "command": command, "arguments": {} if args is None else args} body = json.dumps(message).encode() self.child.stdin.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body) self.child.stdin.flush() return self.outgoing_seq def receive(self): message = self.incoming.get(timeout=5) if isinstance(message, Exception): raise message self.incoming_seq += 1 assert message["seq"] == self.incoming_seq, message assert "jsonrpc" not in message, message return message def response(self, seq, command, success=True): reply = self.receive() assert (reply["type"], reply["request_seq"], reply["command"], reply["success"]) == ( "response", seq, command, success), reply return reply.get("body", {}) def request(self, command, args=None, success=True): return self.response(self.send(command, args), command, success) def event(self, name): event = self.receive() assert event["type"] == "event" and event["event"] == name, event return event.get("body", {}) def initialize(self, paging=True): caps = self.request("initialize", {"adapterID": "vls", "supportsVariablePaging": paging}) assert caps["supportsConfigurationDoneRequest"] and caps["supportsLoadedSourcesRequest"] assert not caps.get("supportsStepBack") self.event("initialized") def launch(self, paging=True): self.initialize(paging) launch = self.send("launch") self.request("configurationDone") self.response(launch, "launch") self.stopped() return self.request("vls/session") def stopped(self): stopped = self.event("stopped") assert stopped["threadId"] == 1 and stopped["allThreadsStopped"] def disconnect(self, terminated=False): self.request("disconnect") if not terminated: self.event("terminated") assert self.child.wait(timeout=5) == 0 assert self.child.stderr.read() == b"" assert isinstance(self.incoming.get(timeout=5), EOFError), "extra adapter output" def identity(state): return {key: state[key] for key in ("schemaVersion", "sessionId", "generation")} def page(client, command, state, start=0, count=64): reply = client.request(command, {**identity(state), "start": start, "count": count}) assert identity(reply) == identity(state) return reply def seek(client, state, **destination): reply = client.request("vls/seek", {**identity(state), **destination}) client.stopped() current = client.request("vls/session") assert identity(current) == identity(reply) assert current["generation"] > state["generation"] return current def inspect_value(client, expected): stack = client.request("stackTrace", {"threadId": 1}) frames = stack["stackFrames"] assert stack["totalFrames"] == len(frames) and len(frames) >= 1 assert all(f["line"] == 0 and f["column"] == 0 and "source" not in f for f in frames) top = frames[0]["id"] scopes = client.request("scopes", {"frameId": top})["scopes"] ref = scopes[0]["variablesReference"] assert ref > 0 and ref != top variables = client.request("variables", {"variablesReference": ref})["variables"] assert [v["value"] for v in variables if v["name"] == "Result"] == [str(expected)], variables return top, ref def replay(adapter, selected, replacement, work, expected): private = work / "selected.vls" shutil.copyfile(selected, private) with Client(adapter, private) as client: state = client.launch() assert state["mode"] == "replay" and state["pauseKind"] == "recordedStop" assert state["schemaVersion"] == 1 and state["eventSequence"] == 6 assert state["recording"]["outcome"] == "completed" and state["recording"]["exitCode"] == 0 assert not state["recording"]["partial"] and not state["recording"]["corrupt"] session_id = state["sessionId"] top, scope = inspect_value(client, expected) source = client.request("loadedSources")["sources"] assert len(source) == 1 and "path" not in source[0] ref = source[0]["sourceReference"] assert ref == state["sourceReference"] and ref > 0 source_args = {"sourceReference": ref, "source": {"path": str(replacement)}} captured = client.request("source", source_args)["content"].encode() assert f"Ready = {expected}".encode() in captured assert len(captured) == state["sourceByteLength"] assert hashlib.sha256(captured).hexdigest() == state["sourceSha256"] client.request("source", {**source_args, "source": {"sourceReference": ref + 1}}, False) client.request("source", {"sourceReference": 0, "source": {"path": str(replacement)}}, False) # Later requests must use the bytes and index acquired on launch. newer = work / "new.vls" shutil.copyfile(replacement, newer) newer.replace(private) private.unlink() assert client.request("source", source_args)["content"].encode() == captured events = page(client, "vls/timeline", state) assert events["total"] == len(events["events"]) == state["recording"]["eventCount"] indexed = {event["sequence"]: event for event in events["events"]} assert (indexed[7]["acknowledgedStop"], indexed[7]["acknowledgedAction"]) == (6, "step") assert (indexed[11]["acknowledgedStop"], indexed[11]["acknowledgedAction"]) == (10, "continue") assert page(client, "vls/timeline", state, events["total"], 0)["events"] == [] for bad_page in ({"count": 257}, {"count": -1}, {"start": events["total"] + 1}, {"start": 0.5}, {"sessionId": "other"}, {"schemaVersion": 2}): args = {**identity(state), "start": 0, "count": 1, **bad_page} client.request("vls/timeline", args, False) view = page(client, "vls/frames", state) assert [f["name"] for f in view["frames"]] == ["reflected_value", "twice"] assert view["frames"][0]["sourceKind"] == "logicalDeclaration" first = state state = seek(client, state, eventSequence=5) view = page(client, "vls/frames", state) assert state["pauseKind"] == "value" and view["stop"] is None assert view["frames"][0]["valueProvisional"] and view["lastLeave"] is None state = seek(client, state, eventSequence=8) view = page(client, "vls/frames", state) assert [f["name"] for f in view["frames"]] == ["twice"] assert view["lastLeave"]["outcome"] == "returned" and not view["lastLeave"]["valueProvisional"] state = seek(client, state, direction="previousValue") assert state["eventSequence"] == 6 and state["sessionId"] == session_id assert inspect_value(client, expected)[0] != top client.request("scopes", {"frameId": top}, False) client.request("variables", {"variablesReference": scope}, False) client.request("vls/frames", {**identity(first), "start": 0, "count": 1}, False) client.request("vls/seek", {**identity(first), "eventSequence": 10}, False) client.request("continue", {"threadId": 1, "vlsContext": identity(first)}, False) client.request("next", {"threadId": 1}, False) for value, sequence, kind in ((expected * 2, 10, "recordedStop"), (expected + 5, 20, "value"), ((expected + 5) * 2, 22, "value")): client.request("continue", {"threadId": 1, "vlsContext": identity(state)}) client.stopped() state = client.request("vls/session") assert (state["eventSequence"], state["pauseKind"]) == (sequence, kind) inspect_value(client, value) client.request("continue", {"threadId": 1}) client.event("terminated") client.disconnect(terminated=True) return session_id def cancelled(adapter, fixture): with Client(adapter, fixture) as client: state = client.launch() assert state["recording"]["outcome"] == "cancelled" and state["recording"]["exitCode"] == 125 assert state["recording"]["partial"] and not state["recording"]["corrupt"] inspect_value(client, 41) events = page(client, "vls/timeline", state)["events"] assert events[-1]["sequence"] == 7 and events[-1]["kind"] == "terminal" client.request("continue", {"threadId": 1}) client.event("terminated") client.disconnect(terminated=True) def failures(adapter, valid, work): invalid = work / "invalid.vls" invalid.write_bytes(b"invalid") with Client(adapter, invalid) as client: client.initialize() client.request("launch", {"trace": str(valid)}, False) client.request("launch", success=False) client.disconnect() with Client(adapter, valid) as client: client.initialize() for invalid_option in (True, "false", None): client.request("launch", {"noDebug": invalid_option}, False) client.request("configurationDone") client.request("launch", {"noDebug": False}) client.stopped() client.disconnect() peer_reply = b'{"seq":3,"type":"response","request_seq":1,"command":"initialize","success":true}' reply_frame = f"Content-Length: {len(peer_reply)}\r\n\r\n".encode() + peer_reply for raw in (b"Content-Length: 20\r\n\r\n{}", b"Content-Length: 3\r\n\r\nabc", b"Content-Length: 1\r\nContent-Length: 1\r\n\r\n0", b"Content-Len", reply_frame): child = subprocess.run([adapter, "--replay", valid], input=raw, capture_output=True, env={"PATH": ""}, timeout=5) assert child.returncode != 0 and not child.stdout and child.stderr with Client(adapter, valid) as client: client.initialize() pending = client.send("launch") client.child.stdin.write(raw) client.child.stdin.close() client.response(pending, "launch", False) assert client.child.wait(timeout=5) != 0 assert isinstance(client.incoming.get(timeout=5), EOFError) def incomplete_and_paging(adapter, valid, work): raw = valid.read_bytes() assert hashlib.sha256(raw).hexdigest() == "4efd70044105ed7e2ae1104780e564d1b8e20bc7d9494f3e0ed82156cef95ea4" # The original recording reaches the second function body at this record boundary. prefix = work / "before-first-return.vls" prefix.write_bytes(raw[:1995]) with Client(adapter, prefix) as client: state = client.launch() assert state["eventSequence"] == 4 and state["pauseKind"] == "event" assert state["recording"]["partial"] and state["recording"]["eventCount"] == 5 state = seek(client, state, eventSequence=1) assert [f["name"] for f in page(client, "vls/frames", state)["frames"]] == ["twice"] client.disconnect() for paged in (False, True): with Client(adapter, valid) as client: client.launch(paged) _, ref = inspect_value(client, 17) var_args = {"variablesReference": ref} all_vars = client.request("variables", var_args)["variables"] subset = client.request("variables", {**var_args, "start": 1, "count": 1})["variables"] assert subset == (all_vars[1:2] if paged else all_vars) assert client.request("stackTrace", {"threadId": 1, "startFrame": 2**32-1})["stackFrames"] == [] if paged: assert client.request("variables", {**var_args, "start": 2**32-1})["variables"] == [] for breakpoint in ({}, {"line": "5"}, {"line": 3, "column": -1}): client.request("setBreakpoints", {"source": {}, "breakpoints": [breakpoint]}, False) client.disconnect() with Client(adapter, valid) as client: client.initialize() seq = client.send("launch") client.outgoing_seq -= 1 # A second packet reuses the outstanding launch correlation. assert client.send("launch") == seq client.response(seq, "launch", False) assert client.child.wait(timeout=5) != 0 assert isinstance(client.incoming.get(timeout=5), EOFError), "duplicate launch response" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--adapter", required=True, type=Path) parser.add_argument("--fixtures", type=Path, default=Path(__file__).resolve().parents[1] / "debug" / "fixtures") args = parser.parse_args() adapter = args.adapter.resolve(strict=True) a, b, c = (args.fixtures.resolve() / name for name in ("integral-17.vls", "integral-41.vls", "cancelled-41.vls")) with tempfile.TemporaryDirectory(prefix="vls-dap-") as directory: work = Path(directory) first = replay(adapter, a, b, work, 17) second = replay(adapter, b, a, work, 41) assert first != second cancelled(adapter, c) failures(adapter, a, work) incomplete_and_paging(adapter, a, work) print("DAP replay passed: 17/34/22/44, 41/82/46/92, cancelled prefix 41, expired " "handles and pages, immutable source, ordered acknowledgements and malformed frames") if __name__ == "__main__": main()