From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from simark.ca by simark.ca with LMTP id v+VjDzlJCGvxVwAAWB0awg (envelope-from ) for ; Thu, 26 Nov 2026 09:59:05 -0500 Authentication-Results: simark.ca; dkim=pass (1024-bit key; unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=BJvwErge; dkim-atps=neutral Received: by simark.ca (Postfix, from userid 112) id 2B4B01E166; Thu, 26 Nov 2026 09:59:05 -0500 (EST) X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-25) on simark.ca X-Spam-Level: X-Spam-Status: No, score=-6.4 required=5.0 tests=ARC_SIGNED,ARC_VALID,BAYES_00, DKIMWL_WL_HIGH,DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,MAILING_LIST_MULTI, RCVD_IN_DNSWL_MED autolearn=ham autolearn_force=no version=4.0.1 Received: from vm01.sourceware.org (vm01.sourceware.org [38.145.34.32]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by simark.ca (Postfix) with ESMTPS id 245CD1E09B for ; Thu, 26 Nov 2026 09:59:02 -0500 (EST) Received: from vm01.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 6D86E4E34B10 for ; Thu, 26 Nov 2026 14:58:54 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 6D86E4E34B10 Authentication-Results: sourceware.org; dkim=pass (1024-bit key, unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=BJvwErge Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by sourceware.org (Postfix) with ESMTP id 8CB1649AF143 for ; Thu, 26 Nov 2026 14:58:18 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 8CB1649AF143 Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=redhat.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org 8CB1649AF143 Authentication-Results: sourceware.org; arc=none smtp.remote-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1795705098; cv=none; b=Plxe5iZ00fnHUF6iRh0xvY7p3iro2myUOwU3cNvVgR097EIleWAsOdFxCTQCb46aJn/SUywQFq7LM160cELZLYKUB/0Iwm8eH9Tts6yqAe80fbz1Bjn4cMyKP8sDEhMR2dcZ1GgLNDOan6S1Ye9BXSuJPASNjxqE7SBxqEej5WY= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1795705098; c=relaxed/simple; bh=puyEJWUblSrJ+DgAry03EXy0cc57i4sPt1J6phbQooQ=; h=DKIM-Signature:From:To:Subject:Date:Message-ID:MIME-Version; b=Q5Np0wRdW249NvlWVnv9qcyL8Ed8RPAjyHa85QV1fISGXOTvz8KhLFA5uKUzXukIG3IUVYxTVSixph05aVQOvZhtviTTtFYQMwXkbEHbwTl+oXhQGQkUEdL+acuJJWmVV08h5wzGx2J8SpSKIzKGlRxu6DxpC6kck2roHB0TAss= ARC-Authentication-Results: i=1; sourceware.org; dkim=pass (1024-bit key, unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=BJvwErge DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 8CB1649AF143 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1795705097; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: in-reply-to:in-reply-to:references:references; bh=8OwWuKhTobsYiXKDjTJr6JbkkbkmXBrCCT7C5U27FSQ=; b=BJvwErgeuyGkNZlLgsaxTZO6gYF721gxrQuyg34n3ALtwxRargYUUbULd0qj9yHfwc5XcU ogfT9P+FFUiQ9IG1l37F9ZzJ4XD1JKx6KVcJTY8a4gJkGZzMcUM5b4v4t3gy6GQqbX7dzU a2mE3CfmeorMqKsDndhaCo3S5NHkaA4= Received: from mail-wm1-f69.google.com (mail-wm1-f69.google.com [209.85.128.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-359-k-SCn9ZiMYep78DYKkRaig-1; Thu, 26 Nov 2026 14:58:15 +0000 X-MC-Unique: k-SCn9ZiMYep78DYKkRaig-1 X-Mimecast-MFC-AGG-ID: k-SCn9ZiMYep78DYKkRaig_1795705094 Received: by mail-wm1-f69.google.com with SMTP id 5b1f17b1804b1-4bb66fc3aa6so59431125e9.2 for ; Thu, 26 Nov 2026 06:58:15 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795705094; x=1796309894; h=content-type:mime-version:message-id:date:references:in-reply-to :subject:to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=8OwWuKhTobsYiXKDjTJr6JbkkbkmXBrCCT7C5U27FSQ=; b=qByzrWiCwYLagkF+Ou3DheaJiGJeLlrsGdfCvcjPPj/sF7dTgICNI4jIYT4pwzZpQa XN4E9IrqkbA1uaG1STLmgP8rVVdGvQmXO/74D1Cs/S3KaTR4IxvmJsgQTR0hl1H+9Ltp 5zygB4CoJztxXAyFDhwKA6k+ZG46+R0nok5zNwf0dJ2EkYkybTTXMoEHVyx1DoClqkm4 egcGo556Z1TzgJ2c/yIQNKrXneJnDw1J1e2ddBVvr4iHCDbVx5LLVvPPxwJlgvkvhCbI mXZrQ/RO6rlEtfBJUPEF7vfVDJtTIGRurDPX6ilyEZEHvjm3/Hz2Jyi22+kzoeXViqg7 k5mw== X-Forwarded-Encrypted: i=1; AL+hErE5+5OBPyePLbx8iQZy6rUGG/yTMiRNYgwHgxDF4c/OJjUPbzg64uKqNHcZfUNgQkPF5ZuYekJ9nuKYEA==@sourceware.org X-Gm-Message-State: APuU4Z8WjuPZuJlZmzNmdw/A3/bHIF7OaOQ1aiUsIm9hO+euAyAJHT1z lCHlQWhKs+HH7k9A7m5Lr5yMnmSVBFHfiscZLC702bm6brpNbcLmVPZJesIlQrS5b5NLV9/dJLO dFEB6fu4xFayUCD0LuWa5+JKQXCdN1CCop06/8TpZrF3YFARm7g4z4cX7KHIqV6x5c7x6K1Q= X-Gm-Gg: AZFdTZdjgVC/HleP862qWwB7gozVqXBKg1W0YiP2+ytUT5a72LR7upZwJo3TRj7MKSj Ds+111Uqe2SpkK8jpztW9yL77CAytXgdJlDCBJKVLm/R5Bbky0Q5HSOvxUEMSK88192M/hTYnIb zn0qQXkbcY7aLzGi5YPyURePC/JixgAvRCF4eJ7CKPjU+h9D16i4lLv1zID7ealaOKnHjscIp8m rFkmRaXfqFAu5BnEavZDU8+swygC0Y97i6EADqVpbOss3V3gb1eOFBo6fvkgWpRi5A8luZCxUk8 vARjgsCagRIYEhMnE4gbabmiX72NT0z6hsFgNrJmdyTzvElxUr4NH4E48PdJWSUTlsrcvtK5jRO r1M7bd6P0zAl7YGZmKTvFimOL54zXibWiZLlES/sJji87nQ== X-Received: by 2002:a05:600c:5246:b0:4bb:60ba:49e0 with SMTP id 5b1f17b1804b1-4bb88930707mr457932885e9.26.1795705093269; Thu, 26 Nov 2026 06:58:13 -0800 (PST) X-Received: by 2002:a05:600c:5246:b0:4bb:60ba:49e0 with SMTP id 5b1f17b1804b1-4bb88930707mr457932275e9.26.1795705092420; Thu, 26 Nov 2026 06:58:12 -0800 (PST) Received: from localhost ([83.216.138.189]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-4bb90660cb4sm567832435e9.2.2026.11.26.06.58.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 26 Nov 2026 06:58:11 -0800 (PST) From: Andrew Burgess To: Kevin Buettner , gdb-patches@sourceware.org Subject: Re: [PATCH 2/5] gdbserver: merge look_up_one_symbol and relocate_instruction packet handling In-Reply-To: <93333453-b4d8-40e2-a20f-adabf34d9690@redhat.com> References: <18919cf28001b47de5aa101126ad7a17a69a469a.1795186852.git.aburgess@redhat.com> <93333453-b4d8-40e2-a20f-adabf34d9690@redhat.com> Date: Thu, 26 Nov 2026 14:58:10 +0000 Message-ID: MIME-Version: 1.0 X-Mimecast-Spam-Score: 0 X-Mimecast-MFC-PROC-ID: vP_9FF4VEfp3RQY-nZduvLyMtx-HA0UiHZaayCntjeU_1795705094 X-Mimecast-Originator: redhat.com Content-Type: text/plain 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~public-inbox=simark.ca@sourceware.org Kevin Buettner writes: > On 11/20/26 8:12 AM, Andrew Burgess wrote: >> Both the look_up_one_symbol and relocate_instruction functions contain a >> loop which handles a limited number of packets received from GDB. This >> commit merges these loops in order to reduce code duplication. A >> follow-up commit fixes a buffer overflow bug in this code. The bug was >> present at both locations, merging the code means only one site needs >> fixing. The new merged code is added in a new function >> handle_limited_packets_while_waiting. >> >> There is a potentially user-visible change in this commit though. >> Previously look_up_one_symbol handled m, x, and v packets only, while >> relocate_instruction handled m, M, x, and X packets. By merging the >> code both functions now handle the superset of these packets, m, M, x, >> X, and v. Both functions contained a comment saying something along the >> lines of "we should really handle all packets here, but for now these >> will do", I assume the current lists are based on what GDB happens to >> send. Supporting more packets in each case should not have any negative >> consequences. If it turns out that there are problems caused by >> accepting this wider set of packets then we can add a packet filter >> argument to handle_limited_packets_while_waiting, but I'd prefer to only >> do this once we know there's a need for it. >> >> As part of the commit, the result of sending the reply to a 'v' packet >> is now error checked; previously, the look_up_one_symbol loop ignored a >> failure to send this reply. >> >> Additionally, while thinking about the 'v' packet handling, I wondered >> what would happen if we received a vCont or vKill while we were within >> look_up_one_symbol or relocate_instruction, and I suspect the outcome >> would not be good. If the inferior disappeared then these functions >> might end up trying to operate on freed process state. The 'v' packet >> handling was added in commit: >> >> commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e >> Date: Sat Mar 12 14:03:26 2016 +0100 >> >> gdbserver: Handle 'v' packet while processing qSymbol. >> >> The commit message talks about needing vFile support. So, while making >> this merge I have made the 'v' packet handling stricter. We now drop >> out of the handle_limited_packets_while_waiting loop for vCont, vAttach, >> vRun, or vKill. All other 'v' packets (including vFile) are handled as >> before. >> >> To the best of my knowledge, existing GDB does not send any packets >> other than m, M, x, X, or v during these two exchanges. If it did, the >> old code would have rejected the packet as a malformed response, and the >> resulting symbol lookup or instruction relocation failure would most >> likely have shown up as a failing test somewhere. There should >> therefore be no visible changes after this commit. > > I ran the entire series through an AI patch review. After reading > through a very dense version of what has now been rewritten to be more > comprehensible, it appeared to me that you were aware of these concerns. > Nonetheless, you may wish to read what Claude thought of this patch: > > I have one point, and I'd class it as a nit: four 'v' packets now get > no reply when they arrive during a qSymbol or qRelocInsn exchange. > > As I read handle_limited_packets_while_waiting, anything other than > m, M, x, X, or a 'v' packet ends the loop and is handed back to the > caller, which expects it to be the qSymbol or qRelocInsn answer. > With this patch, vCont;, vAttach;, vRun;, and vKill; also end the > loop instead of being carried out. I agree with the reason you give: > carrying out any of them in the middle of the exchange could resume, > kill, or replace the inferior, and leave the caller working on stale > or freed state. Removing that risk fits well in this series. > > The side effect I noticed is that neither caller recognises these > packets when they come back. Both print "Malformed response ..." > and give up, and nothing ever replies to the packet itself. In the > qSymbol case the main loop then sends "OK", so a client that sent > vCont would get "OK" instead of a stop reply, and the two sides end > up out of step. > > When I compared this with master, I found: > > - qSymbol path: this is new with the patch. On master these > packets were carried out and answered (unsafely, as you point > out). > > - qRelocInsn path: this was already the case. On master that loop > ended on every 'v' packet and dropped it in the same way. > > - More generally, any unexpected packet (a 'g', say) was already > handled like this in both loops. The patch just puts these four > packets into that existing group. > > I don't think this needs to hold up the series. Your commit message > covers it: these packets now end the loop, existing GDB sends nothing > but m, M, x, X, or v during these exchanges, and you'd rather add > filtering "once we know there's a need for it". GDB can't send vCont > in the middle of the exchange anyway, because it is busy servicing > the exchange. What's left is a protocol mix-up with a client that > has already broken the protocol, not a memory-safety bug, so leaving > it seems a reasonable choice to me. > > If you do want to tidy it up, one option would be to reply with an > error rather than ending the loop: > > if (startswith (cs.own_buf, "vCont;") > || startswith (cs.own_buf, "vAttach;") > || startswith (cs.own_buf, "vRun;") > || startswith (cs.own_buf, "vKill;")) > write_enn (cs.own_buf); > else > handle_v_requests (cs.own_buf, len, &new_len); > > The putpkt at the bottom of the loop would send the E01 straight back > as the reply to the refused packet, and the loop would go on waiting > for the real qSymbol or qRelocInsn answer. The client gets a clear > refusal, and clients already have to cope with E01 from these > packets. The comment above the check would then say "refuse with an > error" rather than "don't service". I'd be equally happy to see this > as a follow-up. I thought about this over night and I agree with you that what I have here is not ideal. But nor do I think your proposal is the right way to go. My concern with you proposal is that we end up "stuck" in the secondary packet loop. I mean, if we want to return E01 to a vKill, then surely we should return E01 for 'g', or any other packet. So then we end with a loop which will only exit by sending a valid qSymbol or qRelocInsn packet. A debug client that somehow gets out of sync would then never break from the loop. If we take qSymbol handling as an example, what I think we should do is this: in server.cc, in handle_query, where we handle qSymbol, we eventually reach these lines: if (current_thread != NULL) the_target->look_up_symbols (); strcpy (own_buf, "OK"); return; We should wrap these like this: try { if (current_thread != NULL) the_target->look_up_symbols (); strcpy (own_buf, "OK"); } catch (const gdb_exception_error &exception) { sprintf (cs.own_buf, "E.%s", exception.what ()); } return; Then, in handle_limited_packets_while_waiting, when we see a packet that we're not expecting, instead of printing a warning, we should raise an error. This error would be caught above and we'd return an error packet to GDB. I don't want to get sidetracked fixing the above right now, so I don't plan to address this issue in this commit. I have however, made some changes to this commit: - I moved the checks for the error packet, and for the expected final packet, inside handle_limited_packets_while_waiting. - I've added a test that exercises the current behaviour. I don't think either of these really change the core of this patch though, so I have applied your approved-by tag. Still, I'll wait a while before pushing in case you wish to re-review this new version. Thanks, Andrew --- commit 69d373278050dfe4f797aa5840d0cb6a484a05f8 Author: Andrew Burgess Date: Tue Nov 17 13:57:07 2026 +0000 gdbserver: merge look_up_one_symbol and relocate_instruction packet handling Both the look_up_one_symbol and relocate_instruction functions contain a loop which handles a limited number of packets received from GDB. This commit merges these loops in order to reduce code duplication. A follow-up commit fixes a buffer overflow bug in this code. The bug was present at both locations, merging the code means only one site needs fixing. The new merged code is added in a new function handle_limited_packets_while_waiting. There is a potentially user-visible change in this commit though. Previously look_up_one_symbol handled m, x, and v packets only, while relocate_instruction handled m, M, x, and X packets. By merging the code both functions now handle the superset of these packets, m, M, x, X, and v. Both functions contained a comment saying something along the lines of "we should really handle all packets here, but for now these will do", I assume the current lists are based on what GDB happens to send. Supporting more packets in each case should not have any negative consequences. If it turns out that there are problems caused by accepting this wider set of packets then we can add a packet filter argument to handle_limited_packets_while_waiting, but I'd prefer to only do this once we know there's a need for it. As part of the commit, the result of sending the reply to a 'v' packet is now error checked; previously, the look_up_one_symbol loop ignored a failure to send this reply. Additionally, while thinking about the 'v' packet handling, I wondered what would happen if we received a vCont or vKill while we were within look_up_one_symbol or relocate_instruction, and I suspect the outcome would not be good. If the inferior disappeared then these functions might end up trying to operate on freed process state. The 'v' packet handling was added in commit: commit 28170b88cc8b40fdea2b065dafe6e1872a47ee4e Date: Sat Mar 12 14:03:26 2016 +0100 gdbserver: Handle 'v' packet while processing qSymbol. The commit message talks about needing vFile support. So, while making this merge I have made the 'v' packet handling stricter. We now drop out of the handle_limited_packets_while_waiting loop for vCont, vAttach, vRun, or vKill. All other 'v' packets (including vFile) are handled as before. To the best of my knowledge, existing GDB does not send any packets other than m, M, x, X, or v during these two exchanges. If it did, the old code would have rejected the packet as a malformed response, and the resulting symbol lookup or instruction relocation failure would most likely have shown up as a failing test somewhere. There should therefore be no visible changes after this commit. During review [1] it was asked why, for things like vKill, vCont, etc, we return from handle_limited_packets_while_waiting rather than sending back an error packet and remaining in the loop. I think that replying with an error is the correct way to go, but I think we also need to return from handle_limited_packets_while_waiting. If we don't return then there is a risk that a debug client will get stuck within the handle_limited_packets_while_waiting loop. However, as the code is currently written, returning from handle_limited_packets_while_waiting means that gdbserver will send some other reply packet, either a subsequent qSymbol request, or the final OK. If we send an error then we will end up sending two packets in response to a single packet from the debug client, and this will definitely cause the communication to get out of sync. I think the correct solution is to have handle_limited_packets_while_waiting throw an exception which is caught further up the stack. For qSymbol this would be in handle_query where the initial qSymbol packet is being dealt with. At this point gdbserver would catch the exception and return an error packet. A similar fix would be needed for qRelocInsn. I don't plan to make this change in this series which is focused on bugs in m, M, x, and X packet handling. [1] https://inbox.sourceware.org/gdb-patches/93333453-b4d8-40e2-a20f-adabf34d9690@redhat.com Approved-By: Kevin Buettner diff --git a/gdb/testsuite/gdb.server/qSymbol-bad-reply.c b/gdb/testsuite/gdb.server/qSymbol-bad-reply.c new file mode 100644 index 00000000000..dc3a92d8031 --- /dev/null +++ b/gdb/testsuite/gdb.server/qSymbol-bad-reply.c @@ -0,0 +1,63 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2026 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include +#include + +unsigned char *buffer = NULL; +size_t buffer_length = 1024 * 1024 * 100; +volatile int global_var = 0; + +/* Is C a byte that must be escaped in a reply from gdbserver to + GDB? Return 1 if it is, otherwise, return 0. */ +static int +is_escapable_byte (unsigned char c) +{ + switch (c) + { + case 0x23: + case 0x24: + case 0x7d: + case 0x2a: + return 1; + default: + return 0; + } +} + +int +main () +{ + buffer = malloc ( buffer_length ); + assert (buffer != NULL); + + unsigned char val = 0; + for (size_t i = 0; i < buffer_length; ++i) + { + buffer[i] = val; + do + { + val = (val + 1) % UCHAR_MAX; + } + while (is_escapable_byte (val)); + } + + global_var = 42; /* Break here. */ + + return 0; +} diff --git a/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp b/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp new file mode 100644 index 00000000000..7c3dce4d9be --- /dev/null +++ b/gdb/testsuite/gdb.server/qSymbol-bad-reply.exp @@ -0,0 +1,142 @@ +# This testcase is part of GDB, the GNU debugger. +# +# Copyright 2026 Free Software Foundation, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# The qSymbol and qRelocInsn handling includes a mini packet loop which only +# handles a small subset of packets while gdbserver and GDB are finalising the +# qSymbol or qRelocInsn conversation. The gdbserver code that handles this +# packet subset is shared between qSymbol and qRelocInsn, but qSymbol is far +# easier to trigger, so we use that here for testing, +# +# This test was added when the packet handling for qSymbol and qRelocInsn was +# merged together into a single function, and this captures the current +# behaviour at that time. However, this behaviour is probably not the ideal +# behaviour, and hopefully will be improved in the future. When that happens +# this test will need to be updated and/or rewritten. That's OK. +# +# To understand what's wrong with the current code, consider the case where the +# debug client first sends 'qSymbol::'. gdbserver then replies with a qSymbol +# packet asking for a particular symbol. If the debug client at this point +# sends back a 'g' packet, which is not one the qSymbol loop can handle, then +# currently gdbserver breaks from the secondary packet handling loop and +# returns. gdbserver will then send the next qSymbol request. This is bad +# because qSymbol is not a documented reply to a 'g' packet. +# +# However, fixing this will require some bigger changes to how qSymbol and +# qRelocInsn are handled, especially the error cases, within gdbserver. +# +# This test uses 'maint packet ...' to trigger a qSymbol packet exchange with +# gdbserver. Then sends unexpected packets to gdbserver and check how the +# server handles them. + +load_lib gdbserver-support.exp + +require allow_gdbserver_tests + +standard_testfile + +save_vars { GDBFLAGS } { + # If GDB and GDBserver are both running locally, set the sysroot to avoid + # reading files via the remote protocol (the `is_remote target` check is + # already done above). + if { ![is_remote host] && ![is_remote target] } { + set GDBFLAGS "$GDBFLAGS -ex \"set sysroot\"" + } + if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} { + return + } +} + +# Make sure we're disconnected, in case we're testing with an +# extended-remote board, therefore already connected. +gdb_test "disconnect" ".*" + +# Start gdbserver and connect. +set res [gdbserver_spawn ""] +lassign $res gdbserver_protocol gdbserver_gdbport +set res [gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport] +if {![gdb_assert {$res == 0} "connect"]} { + return +} + +# Get into position for the test. +gdb_breakpoint [gdb_get_line_number "/* Break here. */"] +gdb_continue_to_breakpoint "test position" + +# Run BODY within a qSymbol packet processing loop. Send 'qSymbol::' to +# gdbserver . It should either reply with 'qSymbol:' or 'OK'. +# +# If we get OK then gdbserver doesn't want to know any symbols from GDB, so we +# cannot get access to its inner packet processing loop. Issue an UNSUPPORTED +# and return without running BODY. +# +# If we get back a symbol request then we can execute BODY which will send some +# unexpected packets to gdbserver. +proc within_qSymbol_loop { body } { + set first_symbol_requested "" + gdb_test_multiple "maint packet qSymbol::" "start qSymbol loop" { + -re -wrap "\r\nreceived: \"OK\"" { + unsupported "$gdb_test_name (no symbols requested)" + } + + -re -wrap "\r\nreceived: \"qSymbol:(\[^\"\]+)\"" { + set first_symbol_requested $expect_out(1,string) + pass $gdb_test_name + } + } + + # We got a symbol request from gdbserver then run BODY. Each BODY will run + # until gdbserver exits the qSymbol packet processing loop. + if { $first_symbol_requested ne "" } { + with_test_prefix "in qSymbol loop" { + transparent_uplevel $body + } + } +} + +# After gdbserver sends a qSymbol request, send back an unexpected packet. See +# the comments at the top of this file for the limitations of this test. +# +# Place a limit of 100 symbol requests. This is more than gdbserver currently +# asks for on GNU/Linux, but should stop thi test getting stuck in a loop if +# something unexpected goes wrong. +foreach_with_prefix packet { E01 g vKill; } { + within_qSymbol_loop { + set limit 100 + gdb_test_multiple "maint packet $packet" "reply with error" { + -i $server_spawn_id + -re "gdbserver: unexpected \[^\r\n\]+\r\n" { + exp_continue + } + + -i $gdb_spawn_id + -re -wrap "received: \"qSymbol:\[^\r\n\]+\"" { + incr limit -1 + if { $limit == 0 } { + fail $gdb_test_name + } else { + send_gdb "maint packet $packet\n" + exp_continue + } + } + + -i $gdb_spawn_id + -re -wrap "received: \"OK\"" { + pass $gdb_test_name + } + } + } +} diff --git a/gdbserver/remote-utils.cc b/gdbserver/remote-utils.cc index 8192e4577f2..abb1789eb76 100644 --- a/gdbserver/remote-utils.cc +++ b/gdbserver/remote-utils.cc @@ -1417,6 +1417,199 @@ clear_symbol_cache (struct sym_cache **symcache_p) *symcache_p = NULL; } +/* In some cases a packet from the debug client triggers a prolonged packet + exchange between gdbserver and the client. For example, gdbserver can + send a qRelocInsn request in response to some packets. When the debug + client receives the qRelocInsn request it will perform a series of memory + accesses using x, X, m, or M packets before finally sending its own + qRelocInsn reply. + + Similarly, the debug client can send 'qSymbol::'; gdbserver will then + request symbol values, which the debug client provides with another + qSymbol packet. Before sending the final qSymbol packet, the debug + client might access memory or send 'v' packets (for vFile transfers). + + This function takes care of handling the limited set of packets that + might arrive while waiting for the final response packet. + + EXPECTED_PACKET_PREFIX is the first part of the final response packet + that we are waiting for. This code fetches packets from the debug + client and then: + + + If it is one of the packets this function handles, the packet is + handled, and then loops around to fetch and handle another packet. + + + If the packet is empty, is an error (starts with 'E'), or is not one + this function can handle and doesn't start with EXPECTED_PACKET_PREFIX, + then this function returns false, and the unexpected, unhandled packet + is left in the client_state's OWN_BUF. + + + If the packet is not one this function can handle and does start with + EXPECTED_PACKET_PREFIX, then this is the final packet we were waiting + for. This function returns true and the unhandled final packet is left + in the client_state's OWN_BUF. + + If this function returns with either true or false, then no response will + have been sent to the debug client. Returning from this function will + result in a reply being sent, so if we send a reply before returning then + this would result in multiple reply packets. The debug client is not + expecting this and will get out of sync. + + We ought to handle pretty much any packet at this point while we wait for + the final response, but that requires re-entering the main loop. For + now, this is an adequate approximation. */ + +static bool +handle_limited_packets_while_waiting (const char *expected_packet_prefix) +{ + client_state &cs = get_client_state (); + + bool leave_packet_handling_loop = false; + while (!leave_packet_handling_loop) + { + int len = getpkt (cs.own_buf); + if (len < 0) + return false; + + CORE_ADDR mem_addr; + unsigned char *mem_buf = nullptr; + unsigned int mem_len; + int new_len = -1; + + switch (cs.own_buf[0]) + { + case 'm': + { + decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len); + mem_buf = (unsigned char *) xmalloc (mem_len); + if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) + bin2hex (mem_buf, cs.own_buf, mem_len); + else + write_enn (cs.own_buf); + } + break; + case 'x': + { + decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len); + mem_buf = (unsigned char *) xmalloc (mem_len); + if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) + { + gdb_byte *buffer = (gdb_byte *) cs.own_buf; + *buffer++ = 'b'; + + int out_len_units; + new_len = remote_escape_output (mem_buf, mem_len, 1, + buffer, + &out_len_units, + PBUFSIZ); + new_len++; /* For the 'b' marker. */ + + if (out_len_units != mem_len) + { + write_enn (cs.own_buf); + new_len = -1; + } + else + suppress_next_putpkt_log (); + } + else + write_enn (cs.own_buf); + } + break; + case 'X': + { + if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr, + &mem_len, &mem_buf) < 0 + || target_write_memory (mem_addr, mem_buf, mem_len) != 0) + write_enn (cs.own_buf); + else + write_ok (cs.own_buf); + } + break; + case 'M': + { + decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf); + if (target_write_memory (mem_addr, mem_buf, mem_len) == 0) + write_ok (cs.own_buf); + else + write_enn (cs.own_buf); + } + break; + case 'v': + /* Don't service packets that change which process we are + debugging, or its execution state, while we are in the middle + of another operation. Handling these here could leave the + caller operating on freed, or stale, state. Any other 'v' + packets, e.g. vFile, are fine to handle. */ + if (startswith (cs.own_buf, "vCont;") + || startswith (cs.own_buf, "vAttach;") + || startswith (cs.own_buf, "vRun;") + || startswith (cs.own_buf, "vKill;")) + leave_packet_handling_loop = true; + else + handle_v_requests (cs.own_buf, len, &new_len); + break; + default: + leave_packet_handling_loop = true; + break; + } + free (mem_buf); + + if (!leave_packet_handling_loop) + { + int res = ((new_len == -1) + ? putpkt (cs.own_buf) + : putpkt_binary (cs.own_buf, new_len)); + if (res < 0) + return false; + } + } + + if (cs.own_buf[0] == '\0') + { + warning (_("an unexpected empty packet occurred while waiting for '%s'"), + expected_packet_prefix); + return false; + } + else if (cs.own_buf[0] == 'E') + { + /* Don't describe an error as unexpected. For both qSymbol and + qRelocInsn, if the debug client needs to read inferior memory to + service the request then the read could fail and the debug client + might return an error. There's still not much we can do beyond + returning false here; we cannot continue handling the qSymbol or + qRelocInsn, but the warning message should not indicate that this + is necessarily a bug. */ + warning (_("an error occurred while waiting for '%s': %s"), + expected_packet_prefix, cs.own_buf); + return false; + } + else if (!startswith (cs.own_buf, expected_packet_prefix)) + { + /* We got an unexpected packet from the debug client. Do not send an + error packet back at this point. If we send back an error at this + point then we also need to fetch another packet from the debug + client, which means we need another go around this packet handling + loop again. There is risk that a debug client could get stuck in + this loop. + + By instead just returning false we let our caller know that + something went wrong, they can choose to handle this how they want. + But at least gdbserver is making progress towards returning to the + main packet handling loop. + + In the future it might be better if we threw an exception at this + point, but that will require a suitable catch in our call stack. + If the exception is allowed to propagate all the way back to + captured_main then this will reset the connection. */ + warning (_("unexpected packet while waiting for '%s', ignoring: %s"), + expected_packet_prefix, cs.own_buf); + return false; + } + + return true; +} + /* Get the address of NAME, and return it in ADDRP if found. if MAY_ASK_GDB is false, assume symbol cache misses are failures. Returns 1 if the symbol is found, 0 if it is not, -1 on error. */ @@ -1426,7 +1619,6 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb) { client_state &cs = get_client_state (); char *p, *q; - int len; struct sym_cache *sym; struct process_info *proc; @@ -1452,88 +1644,10 @@ look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb) if (putpkt (cs.own_buf) < 0) return -1; - len = getpkt (cs.own_buf); - if (len < 0) + if (!handle_limited_packets_while_waiting ("qSymbol:")) return -1; - /* We ought to handle pretty much any packet at this point while we - wait for the qSymbol "response". That requires re-entering the - main loop. For now, this is an adequate approximation; allow - GDB to read from memory and handle 'v' packets (for vFile transfers) - while it figures out the address of the symbol. */ - while (1) - { - CORE_ADDR mem_addr; - unsigned char *mem_buf; - unsigned int mem_len; - int new_len = -1; - - if (cs.own_buf[0] == 'm') - { - decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len); - mem_buf = (unsigned char *) xmalloc (mem_len); - if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) - bin2hex (mem_buf, cs.own_buf, mem_len); - else - write_enn (cs.own_buf); - free (mem_buf); - if (putpkt (cs.own_buf) < 0) - return -1; - } - else if (cs.own_buf[0] == 'x') - { - decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len); - mem_buf = (unsigned char *) xmalloc (mem_len); - if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) - { - gdb_byte *buffer = (gdb_byte *) cs.own_buf; - *buffer++ = 'b'; - - int out_len_units; - new_len = remote_escape_output (mem_buf, mem_len, 1, - buffer, - &out_len_units, - PBUFSIZ); - new_len++; /* For the 'b' marker. */ - - if (out_len_units != mem_len) - { - write_enn (cs.own_buf); - new_len = -1; - } - else - suppress_next_putpkt_log (); - } - else - write_enn (cs.own_buf); - - free (mem_buf); - int res = ((new_len == -1) - ? putpkt (cs.own_buf) - : putpkt_binary (cs.own_buf, new_len)); - if (res < 0) - return -1; - } - else if (cs.own_buf[0] == 'v') - { - handle_v_requests (cs.own_buf, len, &new_len); - if (new_len != -1) - putpkt_binary (cs.own_buf, new_len); - else - putpkt (cs.own_buf); - } - else - break; - len = getpkt (cs.own_buf); - if (len < 0) - return -1; - } - - if (!startswith (cs.own_buf, "qSymbol:")) - { - warning (_("Malformed response to qSymbol, ignoring: %s"), cs.own_buf); - return -1; - } + gdb_assert (startswith (cs.own_buf, "qSymbol:")); p = cs.own_buf + strlen ("qSymbol:"); q = p; @@ -1572,7 +1686,6 @@ int relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc) { client_state &cs = get_client_state (); - int len; ULONGEST written = 0; /* Send the request. */ @@ -1581,100 +1694,10 @@ relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc) if (putpkt (cs.own_buf) < 0) return -1; - len = getpkt (cs.own_buf); - if (len < 0) + if (!handle_limited_packets_while_waiting ("qRelocInsn:")) return -1; - /* We ought to handle pretty much any packet at this point while we - wait for the qRelocInsn "response". That requires re-entering - the main loop. For now, this is an adequate approximation; allow - GDB to access memory. */ - while (cs.own_buf[0] == 'm' || cs.own_buf[0] == 'M' - || cs.own_buf[0] == 'X' || cs.own_buf[0] == 'x') - { - CORE_ADDR mem_addr; - unsigned char *mem_buf = NULL; - unsigned int mem_len; - int new_len = -1; - - if (cs.own_buf[0] == 'm') - { - decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len); - mem_buf = (unsigned char *) xmalloc (mem_len); - if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) - bin2hex (mem_buf, cs.own_buf, mem_len); - else - write_enn (cs.own_buf); - } - else if (cs.own_buf[0] == 'x') - { - decode_x_packet (&cs.own_buf[1], &mem_addr, &mem_len); - mem_buf = (unsigned char *) xmalloc (mem_len); - if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0) - { - gdb_byte *buffer = (gdb_byte *) cs.own_buf; - *buffer++ = 'b'; - - int out_len_units; - new_len = remote_escape_output (mem_buf, mem_len, 1, - buffer, - &out_len_units, - PBUFSIZ); - new_len++; /* For the 'b' marker. */ - - if (out_len_units != mem_len) - { - write_enn (cs.own_buf); - new_len = -1; - } - else - suppress_next_putpkt_log (); - } - else - write_enn (cs.own_buf); - } - else if (cs.own_buf[0] == 'X') - { - if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr, - &mem_len, &mem_buf) < 0 - || target_write_memory (mem_addr, mem_buf, mem_len) != 0) - write_enn (cs.own_buf); - else - write_ok (cs.own_buf); - } - else - { - decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf); - if (target_write_memory (mem_addr, mem_buf, mem_len) == 0) - write_ok (cs.own_buf); - else - write_enn (cs.own_buf); - } - free (mem_buf); - - int res = ((new_len == -1) - ? putpkt (cs.own_buf) - : putpkt_binary (cs.own_buf, new_len)); - if (res < 0) - return -1; - len = getpkt (cs.own_buf); - if (len < 0) - return -1; - } - - if (cs.own_buf[0] == 'E') - { - warning (_("An error occurred while relocating an instruction: %s"), - cs.own_buf); - return -1; - } - - if (!startswith (cs.own_buf, "qRelocInsn:")) - { - warning (_("Malformed response to qRelocInsn, ignoring: %s"), - cs.own_buf); - return -1; - } + gdb_assert (startswith (cs.own_buf, "qRelocInsn:")); unpack_varlen_hex (cs.own_buf + strlen ("qRelocInsn:"), &written);