From patchwork Thu Oct 27 15:38:01 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Andrew Burgess X-Patchwork-Id: 59550 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 039DE382A2C8 for ; Thu, 27 Oct 2022 15:42:12 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 039DE382A2C8 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sourceware.org; s=default; t=1666885332; bh=+k+u8SnGHRwPjpEQAdcymDgECMW3aW+e29n+L5QemtQ=; h=To:Subject:Date:In-Reply-To:References:List-Id:List-Unsubscribe: List-Archive:List-Post:List-Help:List-Subscribe:From:Reply-To:Cc: From; b=B6yBhuGsgRErpSWd35Kj4JPlZEDDC4rJ6ueOl2otIFgqYN6sptV1psRQ+jFoWNooB 6wTANCgAzcxsQHYYXCzJw/+SmKrzisAr+Mb2dsXgwHRDg/BwjwCtObdINNDn64jzxB 2ZidqUXnTWmv4GuuTQHSRYQjKBNMVJxv3FNAo6cg= X-Original-To: gdb-patches@sourceware.org Delivered-To: gdb-patches@sourceware.org Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by sourceware.org (Postfix) with ESMTPS id 6656E392AC24 for ; Thu, 27 Oct 2022 15:38:20 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org 6656E392AC24 Received: from mail-wr1-f69.google.com (mail-wr1-f69.google.com [209.85.221.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_128_GCM_SHA256) id us-mta-356-MFOEcPmkOKWnhDX3Cx7RjQ-1; Thu, 27 Oct 2022 11:38:19 -0400 X-MC-Unique: MFOEcPmkOKWnhDX3Cx7RjQ-1 Received: by mail-wr1-f69.google.com with SMTP id p7-20020adfba87000000b0022cc6f805b1so558057wrg.21 for ; Thu, 27 Oct 2022 08:38:18 -0700 (PDT) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=+k+u8SnGHRwPjpEQAdcymDgECMW3aW+e29n+L5QemtQ=; b=qLZe8oolCAqq8UrGT+oDBtuA1U/gshlCP2mcepWJqvBosGaq1F8bO8wuP9AiCGarwc nCsjAdrPvbStEIhpdWE3NhfCISynPLwqGU5UomcJSsAaJ1EKZ7wEbH14ipyscy8seIyE oA8iEbbQmvVIG/AilaKxoO/mKQZXQrs5B2numPIosz8/hh+zgk+8QTWmJl0qDNgk2Wtf aZVqW0C4MGTSAfkR5BmryapGvT1MI6ju5CK/JszAaNebRkAlgCH/Ld9y6pV0Xb4oDf8/ xfykU8U4E87ZzAyt6o4gpQiiMIjEZOH1t8aqNhLRO/Yj7n9PfROTAvokGkPiBdYUhYmN Px6g== X-Gm-Message-State: ACrzQf2iwgHcpdtLWBfqu113SWgqPPxvwG4/ddifks2pKmVU6CtAR9o7 spe5DJncCS6AK1M9tOhI7T2i9JysG8dDfvElmiB9hr71djmidvbOroDP6bauC3TX3QoHkkgALV0 dV2NZwvRzot/SQ5RpTr87Z5gq+x8DT/QnvF8zX6VfZ6L+opmgcD92aIpyC2QAoTuP4XkDpWnS+Q == X-Received: by 2002:a5d:5289:0:b0:236:5022:c683 with SMTP id c9-20020a5d5289000000b002365022c683mr23620863wrv.341.1666885097339; Thu, 27 Oct 2022 08:38:17 -0700 (PDT) X-Google-Smtp-Source: AMsMyM45WCT8YQepcq5xSefb0S1v9qVIZ7kQi19Sh5ClrQCClX5qfiJGoB272Q+F5JXeIVZXQYf7qQ== X-Received: by 2002:a5d:5289:0:b0:236:5022:c683 with SMTP id c9-20020a5d5289000000b002365022c683mr23620838wrv.341.1666885096876; Thu, 27 Oct 2022 08:38:16 -0700 (PDT) Received: from localhost ([31.111.84.238]) by smtp.gmail.com with ESMTPSA id i17-20020adfefd1000000b002365f326037sm1696823wrp.63.2022.10.27.08.38.15 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 27 Oct 2022 08:38:16 -0700 (PDT) To: gdb-patches@sourceware.org Subject: [PATCHv2 1/3] gdb/python: avoid throwing an exception over libopcodes code Date: Thu, 27 Oct 2022 16:38:01 +0100 Message-Id: <2924e27d733e1b398654bea3ae1e04b875e5fe43.1666884855.git.aburgess@redhat.com> X-Mailer: git-send-email 2.25.4 In-Reply-To: References: <20221024125016.2823862-1-aburgess@redhat.com> MIME-Version: 1.0 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com X-Spam-Status: No, score=-11.8 required=5.0 tests=BAYES_00, DKIMWL_WL_HIGH, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H2, SPF_HELO_NONE, SPF_NONE, TXREP 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.29 Precedence: list List-Id: Gdb-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: Andrew Burgess via Gdb-patches From: Andrew Burgess Reply-To: Andrew Burgess Cc: Simon Marchi Errors-To: gdb-patches-bounces+patchwork=sourceware.org@sourceware.org Sender: "Gdb-patches" Bug gdb/29712 identifies a problem with the Python disassembler API. In some cases GDB will try to throw an exception through the libopcodes disassembler code, however, not all targets include exception unwind information when compiling C code, for targets that don't include this information GDB will terminate when trying to pass the exception through libopcodes. To explain what GDB is trying to do, consider the following trivial use of the Python disassembler API: class ExampleDisassembler(gdb.disassembler.Disassembler): class MyInfo(gdb.disassembler.DisassembleInfo): def __init__(self, info): super().__init__(info) def read_memory(self, length, offset): return super().read_memory(length, offset) def __init__(self): super().__init__("ExampleDisassembler") def __call__(self, info): info = self.MyInfo(info) return gdb.disassembler.builtin_disassemble(info) This disassembler doesn't add any value, it defers back to GDB to do all the actual work, but it serves to allow us to discuss the problem. The problem occurs when a Python exception is raised by the MyInfo.read_memory method. The MyInfo.read_memory method is called from the C++ function gdbpy_disassembler::read_memory_func. The C++ stack at the point this function is called looks like this: #0 gdbpy_disassembler::read_memory_func (memaddr=4198805, buff=0x7fff9ab9d2a8 "\220ӹ\232\377\177", len=1, info=0x7fff9ab9d558) at ../../src/gdb/python/py-disasm.c:510 #1 0x000000000104ba06 in fetch_data (info=0x7fff9ab9d558, addr=0x7fff9ab9d2a9 "ӹ\232\377\177") at ../../src/opcodes/i386-dis.c:305 #2 0x000000000104badb in ckprefix (ins=0x7fff9ab9d100) at ../../src/opcodes/i386-dis.c:8571 #3 0x000000000104e28e in print_insn (pc=4198805, info=0x7fff9ab9d558, intel_syntax=-1) at ../../src/opcodes/i386-dis.c:9548 #4 0x000000000104f4d4 in print_insn_i386 (pc=4198805, info=0x7fff9ab9d558) at ../../src/opcodes/i386-dis.c:9949 #5 0x00000000004fa7ea in default_print_insn (memaddr=4198805, info=0x7fff9ab9d558) at ../../src/gdb/arch-utils.c:1033 #6 0x000000000094fe5e in i386_print_insn (pc=4198805, info=0x7fff9ab9d558) at ../../src/gdb/i386-tdep.c:4072 #7 0x0000000000503d49 in gdbarch_print_insn (gdbarch=0x5335560, vma=4198805, info=0x7fff9ab9d558) at ../../src/gdb/gdbarch.c:3351 #8 0x0000000000bcc8c6 in disasmpy_builtin_disassemble (self=0x7f2ab07f54d0, args=0x7f2ab0789790, kw=0x0) at ../../src/gdb/python/py-disasm.c:324 ### ... snip lots of frames as we pass through Python itself ... #22 0x0000000000bcd860 in gdbpy_print_insn (gdbarch=0x5335560, memaddr=0x401195, info=0x7fff9ab9e3c8) at ../../src/gdb/python/py-disasm.c:783 #23 0x00000000008995a5 in ext_lang_print_insn (gdbarch=0x5335560, address=0x401195, info=0x7fff9ab9e3c8) at ../../src/gdb/extension.c:939 #24 0x0000000000741aaa in gdb_print_insn_1 (gdbarch=0x5335560, vma=0x401195, info=0x7fff9ab9e3c8) at ../../src/gdb/disasm.c:1078 #25 0x0000000000741bab in gdb_disassembler::print_insn (this=0x7fff9ab9e3c0, memaddr=0x401195, branch_delay_insns=0x0) at ../../src/gdb/disasm.c:1101 So gdbpy_disassembler::read_memory_func is called from the libopcodes disassembler to read memory, this C++ function then calls into user supplied Python code to do the work. If the user supplied Python code raises an gdb.MemoryError exception indicating the memory read failed, this this is fine. The C++ code converts this exception back into a return value that libopcodes can understand, and returns to libopcodes. However, if the user supplied Python code raises some other exception, what we want is for this exception to propagate through GDB and appear as if raised by the call to gdb.disassembler.builtin_disassemble. To achieve this, when gdbpy_disassembler::read_memory_func spots an unknown Python exception, we must pass the information about this exception from frame #0 to frame #8 in the above backtrace. Frame #8 is the C++ implementation of gdb.disassembler.builtin_disassemble, and so it is this function that we want to re-raise the unknown Python exception, so the user can, if they want, catch the exception in their code. The previous mechanism by which the exception was passed was to pack the details of the Python exception into a C++ exception, then throw the exception from frame #0, and catch the exception in frame #8, unpack the details of the Python exception, and re-raise it. However, this relies on the exception passing through frames #1 to #7, some of which are in libopcodes, which is C code, and so, might not be compiled with exception support. This commit proposes an alternative solution that does not rely on throwing a C++ exception. When we spot an unhandled Python exception in frame #0, we will store the details of this exception within the gdbpy_disassembler object currently in use. Then we return to libopcodes a value indicating that the memory_read failed. libopcodes will now continue to disassemble as though that memory read failed (with one special case described below), then, when we eventually return to disasmpy_builtin_disassemble we check to see if there is an exception stored in the gdbpy_disassembler object. If there is then this exception can immediately be installed, and then we return back to Python, when the user will be able to catch the exception. There is one extra change in gdbpy_disassembler::read_memory_func. After the first call that results in an exception being stored on the gdbpy_disassembler object, any future calls to the ::read_memory_func function will immediately return as if the read failed. This avoids any additional calls into user supplied Python code. My thinking here is that should the first call fail with some unknown error, GDB should not keep trying with any additional calls. This maintains the illusion that the exception raised from MyInfo.read_memory is immediately raised by gdb.disassembler.builtin_disassemble. I have no tests for this change though - to trigger this issue would rely on a libopcodes disassembler that will try to read further memory even after the first failed read. I'm not aware of any such disassembler that currently does this, but that doesn't mean such a disassembler couldn't exist in the future. With this change in place the gdb.python/py-disasm.exp test should now pass on AArch64. Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29712 --- gdb/python/py-disasm.c | 79 +++++++++++++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 16 deletions(-) diff --git a/gdb/python/py-disasm.c b/gdb/python/py-disasm.c index c37452fcf72..1d460997831 100644 --- a/gdb/python/py-disasm.c +++ b/gdb/python/py-disasm.c @@ -122,6 +122,28 @@ struct gdbpy_disassembler : public gdb_printing_disassembler return m_string_file.release (); } + /* If there is a Python exception stored in this disassembler then + restore it (i.e. set the PyErr_* state), clear the exception within + this disassembler, and return true. There must be no current + exception set (i.e. !PyErr_Occurred()) when this function is called, + as any such exception might get lost. + + Otherwise, there is no exception stored in this disassembler, return + false. */ + bool restore_exception () + { + gdb_assert (!PyErr_Occurred ()); + if (m_stored_exception.has_value ()) + { + gdbpy_err_fetch ex = std::move (*m_stored_exception); + m_stored_exception.reset (); + ex.restore (); + return true; + } + + return false; + } + private: /* Where the disassembler result is written. */ @@ -138,6 +160,25 @@ struct gdbpy_disassembler : public gdb_printing_disassembler memory source object then a pointer to the object is placed in here, otherwise, this field is nullptr. */ PyObject *m_memory_source; + + /* Move the exception EX into this disassembler object. */ + void store_exception (gdbpy_err_fetch &&ex) + { + /* The only calls to store_exception are from read_memory_func, which + will return early if there's already an exception stored. */ + gdb_assert (!m_stored_exception.has_value ()); + m_stored_exception.emplace (std::move (ex)); + } + + /* Return true if there is an exception stored in this disassembler. */ + bool has_stored_exception () const + { + return m_stored_exception.has_value (); + } + + /* Store a single exception. This is used to pass Python exceptions back + from ::memory_read to disasmpy_builtin_disassemble. */ + gdb::optional m_stored_exception; }; /* Return true if OBJ is still valid, otherwise, return false. A valid OBJ @@ -288,20 +329,15 @@ disasmpy_builtin_disassemble (PyObject *self, PyObject *args, PyObject *kw) the disassembled instruction, or -1 if there was a memory-error encountered while disassembling. See below more more details on handling of -1 return value. */ - int length; - try - { - length = gdbarch_print_insn (disasm_info->gdbarch, disasm_info->address, + int length = gdbarch_print_insn (disasm_info->gdbarch, disasm_info->address, disassembler.disasm_info ()); - } - catch (gdbpy_err_fetch &pyerr) - { - /* Reinstall the Python exception held in PYERR. This clears to - pointers held in PYERR, hence the need to catch as a non-const - reference. */ - pyerr.restore (); - return nullptr; - } + + /* It is possible that, while calling a user overridden memory read + function, a Python exception was raised that couldn't be + translated into a standard memory-error. In this case the first such + exception is stored in the disassembler and restored here. */ + if (disassembler.restore_exception ()) + return nullptr; if (length == -1) { @@ -483,6 +519,14 @@ gdbpy_disassembler::read_memory_func (bfd_vma memaddr, gdb_byte *buff, = static_cast (info->application_data); disasm_info_object *obj = dis->py_disasm_info (); + /* If a previous read attempt resulted in an exception, then we don't + allow any further reads to succeed. We only do this check for the + read_memory_func as this is the only one the user can hook into, + thus, this check prevents us calling back into user code if a + previous call has already thrown an error. */ + if (dis->has_stored_exception ()) + return -1; + /* The DisassembleInfo.read_memory method expects an offset from the address stored within the DisassembleInfo object; calculate that offset here. */ @@ -513,7 +557,8 @@ gdbpy_disassembler::read_memory_func (bfd_vma memaddr, gdb_byte *buff, exception and throw it, this will then be caught in disasmpy_builtin_disassemble, at which point the exception will be restored. */ - throw gdbpy_err_fetch (); + dis->store_exception (gdbpy_err_fetch ()); + return -1; } /* Convert the result to a buffer. */ @@ -523,7 +568,8 @@ gdbpy_disassembler::read_memory_func (bfd_vma memaddr, gdb_byte *buff, { PyErr_Format (PyExc_TypeError, _("Result from read_memory is not a buffer")); - throw gdbpy_err_fetch (); + dis->store_exception (gdbpy_err_fetch ()); + return -1; } /* Wrap PY_BUFF so that it is cleaned up correctly at the end of this @@ -536,7 +582,8 @@ gdbpy_disassembler::read_memory_func (bfd_vma memaddr, gdb_byte *buff, PyErr_Format (PyExc_ValueError, _("Buffer returned from read_memory is sized %d instead of the expected %d"), py_buff.len, len); - throw gdbpy_err_fetch (); + dis->store_exception (gdbpy_err_fetch ()); + return -1; } /* Copy the data out of the Python buffer and return success. */