From patchwork Fri Dec 1 15:41:02 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tom Tromey X-Patchwork-Id: 81128 Return-Path: X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 2A3EE385E45D for ; Fri, 1 Dec 2023 15:41:56 +0000 (GMT) X-Original-To: gdb-patches@sourceware.org Delivered-To: gdb-patches@sourceware.org Received: from mail-il1-x12c.google.com (mail-il1-x12c.google.com [IPv6:2607:f8b0:4864:20::12c]) by sourceware.org (Postfix) with ESMTPS id C7DFE385E03D for ; Fri, 1 Dec 2023 15:41:04 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org C7DFE385E03D Authentication-Results: sourceware.org; dmarc=pass (p=none dis=none) header.from=adacore.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=adacore.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org C7DFE385E03D Authentication-Results: server2.sourceware.org; arc=none smtp.remote-ip=2607:f8b0:4864:20::12c ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1701445267; cv=none; b=F8UwBmoDYhvoVADrX6/7ZK/r04EnN7e/YEZNo2WS0X8nyll1X4w35I/syS2jz4SKdR8paJGbMBbQAtbdVpwl4MT+8JElQmjv7hPkuoIwbH8l2jUD25wecHHnG9mWs+FPrFQ+V4y/Iy+qhZuwZuby6qWdopzNmCi+RGGZC6i1bSE= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1701445267; c=relaxed/simple; bh=WgJ9DQ1L2gLTFfvqqqTeWPeAZDWXumUpErOamgGTRIM=; h=DKIM-Signature:From:Date:Subject:MIME-Version:Message-Id:To; b=n6aSDqlp+kec6prCdJpE9y46tuApP2TwVvnLy8dlwDNKLqxeAsBFVj9FZRhu05G0hAUxcntoG6xLtlUeTcfP4pM1SS1v0FoEVrimvp10wLgcL39MQXO8x34OveiFhT68cMnGGjAkFT7LU74NcWaZn5BqDI4wZ7NSDZwFcfYuiv0= ARC-Authentication-Results: i=1; server2.sourceware.org Received: by mail-il1-x12c.google.com with SMTP id e9e14a558f8ab-35d3b220b64so7123175ab.2 for ; Fri, 01 Dec 2023 07:41:04 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=adacore.com; s=google; t=1701445264; x=1702050064; darn=sourceware.org; h=to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=DXCVO7ae5YLjInU7nFq5uVJ7Mll2QDJQhQ+LQbADjUQ=; b=SWuIe+zsLp6orHsbjLP2PO6MRwUdPMbZZDMi4K9rwiNc2wzpn4RJh4aERH3jL4IFno 6eckzK/qzaIcUfPl8BdIixBf/nfpoGcum0xeB8WCKBdr79G5eEUx6rZjWQMOgf3ltOFn Ao8/RlEzCflot/kfxyGFncH961H5sJt21g3PL0rHb4gqKqwoVff9azsLzQGwjGWRMRe5 nNlkdAvENl/GEuJFlFvH/NpfCbN/Bn0KvFQQaGJxXoNYGrfsXwfXKyeg1kDtTX7Jj+Yj Gu0Z7Wdyauk2BOqLhONsK9EX2uVRCrzFXvoovtrOjDnOWQPrDwKYwK3K7EWX11oTQoTr HjKQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1701445264; x=1702050064; h=to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=DXCVO7ae5YLjInU7nFq5uVJ7Mll2QDJQhQ+LQbADjUQ=; b=q8G/lRVh8lRiEFHWZSUG0EXELNdsmZ0YuUcMZ2GTqaJVTE37QA3BK8Z2J5vw7tkMZH 8Z2w0BpTmSxHgJj6XtCp5wgG5bgqHksbqtJG+zl7EWZ7o1uzqH+zdpQ/ZZE8sO+Hxw+p 5mVFWHvJP/KPB/kOmE8bd2xcTcK2Vo+956d09+uN82TzyC9LuAUoojAQcVDJUCjrgzPQ dlaDMJhq8mYb816vmHMYa1p56BDXAQ1uY1cY/lVOwsaOP73B1W05EEb0uyM1VMVZo86j 3oIQMXAwIoy4AkbECO9H9kCIrAA/YJtmH6PsgLX31YYaaEWYbd0sGkkxQiycwKX6yfwk AYaA== X-Gm-Message-State: AOJu0YwM8fnCwBrMsFp4VCD5ob5D6sojvizO1aNu4l8S3nJjiUVN3JMI MEEQ5psvn2uQ76NVRR9BTvKo0b/VdKVb73vmELQ= X-Google-Smtp-Source: AGHT+IG9T3gXO4usNx2ppHGsLWPJYU3xKhTOXdABNgLizvJr6tfPv77BERDgj6rt5i7+NTj5vrJfmQ== X-Received: by 2002:a05:6e02:106e:b0:35d:47b1:b656 with SMTP id q14-20020a056e02106e00b0035d47b1b656mr3496681ilj.6.1701445263890; Fri, 01 Dec 2023 07:41:03 -0800 (PST) Received: from localhost.localdomain (97-122-77-73.hlrn.qwest.net. [97.122.77.73]) by smtp.gmail.com with ESMTPSA id f4-20020a02cac4000000b0046662226e54sm906829jap.168.2023.12.01.07.41.02 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 01 Dec 2023 07:41:03 -0800 (PST) From: Tom Tromey Date: Fri, 01 Dec 2023 08:41:02 -0700 Subject: [PATCH 6/6] Implement DAP cancellation MIME-Version: 1.0 Message-Id: <20231201-dap-cancel-v1-6-872022fc328a@adacore.com> References: <20231201-dap-cancel-v1-0-872022fc328a@adacore.com> In-Reply-To: <20231201-dap-cancel-v1-0-872022fc328a@adacore.com> To: gdb-patches@sourceware.org X-Mailer: b4 0.12.4 X-Spam-Status: No, score=-11.7 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP, T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gdb-patches@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Gdb-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: gdb-patches-bounces+patchwork=sourceware.org@sourceware.org This implements DAP cancellation. A new object is introduced that handles the details of cancellation. While cancellation is inherently racy, this code attempts to make it so that gdb doesn't inadvertently cancel the wrong request. Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30472 Reviewed-By: Eli Zaretskii --- gdb/doc/gdb.texinfo | 16 +++++++ gdb/python/lib/gdb/dap/server.py | 91 ++++++++++++++++++++++++++++++++++++++-- gdb/testsuite/gdb.dap/pause.exp | 71 +++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 3 deletions(-) diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo index e4c00143fd1..c7c56f2e967 100644 --- a/gdb/doc/gdb.texinfo +++ b/gdb/doc/gdb.texinfo @@ -39541,6 +39541,22 @@ to return the bytes of each instruction in an implementation-defined format. @value{GDBN} implements this by sending a string with the bytes encoded in hex, like @code{"55a2b900"}. +When the @code{repl} context is used for the @code{evaluate} request, +@value{GDBN} evaluates the provided expression as a CLI command. + +Evaluation in general can cause the inferior to continue execution. +For example, evaluating the @code{continue} command could do this, as +could evaluating an expression that involves an inferior function +call. + +@code{repl} evaluation can also cause @value{GDBN} to appear to stop +responding to requests, for example if a CLI script does a lengthy +computation. + +Evaluations like this can be interrupted using the DAP @code{cancel} +request. (In fact, @code{cancel} should work for any request, but it +is unlikely to be useful for most of them.) + @node JIT Interface @chapter JIT Compilation Interface @cindex just-in-time compilation diff --git a/gdb/python/lib/gdb/dap/server.py b/gdb/python/lib/gdb/dap/server.py index 53a0ca7f448..44dffb1b809 100644 --- a/gdb/python/lib/gdb/dap/server.py +++ b/gdb/python/lib/gdb/dap/server.py @@ -14,8 +14,11 @@ # along with this program. If not, see . import functools +import gdb +import heapq import inspect import json +import threading from .io import start_json_writer, read_json from .startup import ( @@ -48,6 +51,52 @@ class NotStoppedException(Exception): pass +# This is used to handle cancellation requests. It tracks all the +# needed state, so that we can cancel both requests that are in flight +# as well as queued requests. +class CancellationHandler: + def __init__(self): + # Methods on this class acquire this lock before proceeding. + self.lock = threading.Lock() + # The request currently being handled, or None. + self.in_flight = None + self.reqs = [] + + def starting(self, req): + """Call at the start of the given request. + + Throws the appropriate exception if the request should be + immediately cancelled.""" + with self.lock: + self.in_flight = req + while len(self.reqs) > 0 and self.reqs[0] <= req: + if heapq.heappop(self.reqs) == req: + raise KeyboardInterrupt() + + def done(self, req): + """Indicate that the request is done.""" + with self.lock: + self.in_flight = None + + def cancel(self, req): + """Call to cancel a request. + + If the request has already finished, this is ignored. + If the request is in flight, it is interrupted. + If the request has not yet been seen, the cancellation is queued.""" + with self.lock: + if req == self.in_flight: + gdb.interrupt() + else: + # We don't actually ignore the request here, but in + # the 'starting' method. This way we don't have to + # track as much state. Also, this implementation has + # the weird property that a request can be cancelled + # before it is even sent. It didn't seem worthwhile + # to try to check for this. + heapq.heappush(self.reqs, req) + + class Server: """The DAP server class.""" @@ -64,6 +113,7 @@ class Server: # requests is kept. self.read_queue = DAPQueue() self.done = False + self.canceller = CancellationHandler() global _server _server = self @@ -71,13 +121,14 @@ class Server: # PARAMS is just a dictionary from the JSON. @in_dap_thread def _handle_command(self, params): - # We don't handle 'cancel' for now. + req = params["seq"] result = { - "request_seq": params["seq"], + "request_seq": req, "type": "response", "command": params["command"], } try: + self.canceller.starting(req) if "arguments" in params: args = params["arguments"] else: @@ -90,10 +141,15 @@ class Server: except NotStoppedException: result["success"] = False result["message"] = "notStopped" + except KeyboardInterrupt: + # This can only happen when a request has been canceled. + result["success"] = False + result["message"] = "cancelled" except BaseException as e: log_stack() result["success"] = False result["message"] = str(e) + self.canceller.done(req) return result # Read inferior output and sends OutputEvents to the client. It @@ -115,11 +171,25 @@ class Server: self.write_queue.put(obj) # This is run in a separate thread and simply reads requests from - # the client and puts them into a queue. + # the client and puts them into a queue. A separate thread is + # used so that 'cancel' requests can be handled -- the DAP thread + # will normally block, waiting for each request to complete. def _reader_thread(self): while True: cmd = read_json(self.in_stream) log("READ: <<<" + json.dumps(cmd) + ">>>") + # Be extra paranoid about the form here. If anything is + # missing, it will be put in the queue and then an error + # issued by ordinary request processing. + if ( + "command" in cmd + and cmd["command"] == "cancel" + and "arguments" in cmd + # gdb does not implement progress, so there's no need + # to check for progressId. + and "requestId" in cmd["arguments"] + ): + self.canceller.cancel(cmd["arguments"]["requestId"]) self.read_queue.put(cmd) @in_dap_thread @@ -316,3 +386,18 @@ def disconnect(*, terminateDebuggee: bool = False, **args): if terminateDebuggee: send_gdb_with_response("kill") _server.shutdown() + + +@request("cancel", on_dap_thread=True, expect_stopped=False) +@capability("supportsCancelRequest") +def cancel(**args): + # If a 'cancel' request can actually be satisfied, it will be + # handled specially in the reader thread. However, in order to + # construct a proper response, the request is also added to the + # command queue and so ends up here. Additionally, the spec says: + # The cancel request may return an error if it could not cancel + # an operation but a client should refrain from presenting this + # error to end users. + # ... which gdb takes to mean that it is fine for all cancel + # requests to report success. + return None diff --git a/gdb/testsuite/gdb.dap/pause.exp b/gdb/testsuite/gdb.dap/pause.exp index 1b65dcac836..0f2fcbc6b2d 100644 --- a/gdb/testsuite/gdb.dap/pause.exp +++ b/gdb/testsuite/gdb.dap/pause.exp @@ -75,4 +75,75 @@ foreach event [lindex $result 1] { } gdb_assert {$seen == "pass"} "continue event from inferior call" +# +# Test that a repl evaluation that causes a continue can be canceled. +# + +set cont_id [dap_send_request evaluate \ + {o expression [s continue] context [s repl]}] +dap_wait_for_event_and_check "continued" continued + +set cancel_id [dap_send_request cancel \ + [format {o requestId [i %d]} $cont_id]] + +# The stop event will come before any responses to the requests. +dap_wait_for_event_and_check "stopped by cancel" stopped + +# Now we can wait for the 'continue' request to complete, and then the +# 'cancel' request. +dap_read_response evaluate $cont_id +dap_read_response cancel $cancel_id + +# +# Test that a repl evaluation of a long-running gdb command (that does +# not continue the inferior) can be canceled. +# + +proc write_file {suffix contents} { + global testfile + + set gdbfile [standard_output_file ${testfile}.$suffix] + set ofd [open $gdbfile w] + puts $ofd $contents + close $ofd + return $gdbfile +} + +set gdbfile [write_file gdb "set \$x = 0\nwhile 1\nset \$x = \$x + 1\nend"] +set cont_id [dap_send_request evaluate \ + [format {o expression [s "source %s"] context [s repl]} \ + $gdbfile]] + +# Wait a little to try to ensure the command is running. +sleep 0.2 +set cancel_id [dap_send_request cancel \ + [format {o requestId [i %d]} $cont_id]] + +set info [lindex [dap_read_response evaluate $cont_id] 0] +gdb_assert {[dict get $info success] == "false"} "gdb command failed" +gdb_assert {[dict get $info message] == "cancelled"} "gdb command canceled" + +dap_read_response cancel $cancel_id + +# +# Test that a repl evaluation of a long-running Python command (that +# does not continue the inferior) can be canceled. +# + +write_file py "while True:\n pass" +set cont_id [dap_send_request evaluate \ + [format {o expression [s "source %s"] context [s repl]} \ + $gdbfile]] + +# Wait a little to try to ensure the command is running. +sleep 0.2 +set cancel_id [dap_send_request cancel \ + [format {o requestId [i %d]} $cont_id]] + +set info [lindex [dap_read_response evaluate $cont_id] 0] +gdb_assert {[dict get $info success] == "false"} "python command failed" +gdb_assert {[dict get $info message] == "cancelled"} "python command canceled" + +dap_read_response cancel $cancel_id + dap_shutdown