From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mail-wr1-x42a.google.com (mail-wr1-x42a.google.com [IPv6:2a00:1450:4864:20::42a]) by sourceware.org (Postfix) with ESMTPS id BA879385AC26 for ; Tue, 5 Oct 2021 12:02:31 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org BA879385AC26 Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=embecosm.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=embecosm.com Received: by mail-wr1-x42a.google.com with SMTP id t8so37015070wri.1 for ; Tue, 05 Oct 2021 05:02:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=embecosm.com; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=r8Tp7lHjeKoZdA686PqF63eQsV41kYysMhSSNZm0hwo=; b=SqZBDOkQSZDKT9hTpcee1K1XBuAg2wa809uYplBNKTyYMJQ2DFhziBjQBYZ2j16gTN dg4ZyvcCg3Do7egJl6fM0A+fuTj3js3/H4UekT2+scWJUQRwQk9kAtvE1/98dgITCU9t WuETxrAc/BTCHqwDYlbcOFtD4bCGssEHNosW7kvfLTLF1QERnIlBzGrf+aZRwoqw/PKJ yksPGsX9VmQW76164webr/oZJ6ev4VDxTSBqxPujHq4U4e5+RiWA9xVX58RT9ak1t71a eyqmYvbvEH4j7/hNB7EOjEDhjDCSIljFe68poXr6utMk2Rkx5n7o+NhdG4nd3J24S+wE 9V/A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=r8Tp7lHjeKoZdA686PqF63eQsV41kYysMhSSNZm0hwo=; b=vSm18a7nd7C/ryQ/+g9iNfRU8Y/YNzM4P64y7C+m3pj795inWSYo8KhwWud6V8xlfq io3mCzUBvJ0hsWWJeJJPMHL8GzNB7EGZA3HLKz/umM70cgA432qd6G9LIRRWUv4m+1fT PfY4i21At4a6V7Nhaw090CPnsqBzSDV9zRGyxxPz1/ZQWmzszBNII+6JjIhK3fKPEP4/ 96F2l4SfnIWd65PKI9CPsixBQDBOPIQ+UbPoeDEvyPUny7+8d6eF9DxTRmq5Tykd9l7V hH5Jp1aSL/uFqDHyMo310UkHYRNYqFo4p7r5jCv9/63iKPA1h8qDClF3HBYmhARmGdRD 4cHQ== X-Gm-Message-State: AOAM5326umjSdrNx1QOWHIJxt/qaRlwhVmae0yu6yZsQL85mhY1XDAXA Lr39PTdg4lKxRreTz+peFoD5kKRF/0UDJg== X-Google-Smtp-Source: ABdhPJypeN5rlFzGkvkKu2XQBAC4t/R4uAy28IHLjWiVIwz+g+3TgNthAb5+ZJx5bFeNR2CJXYf/kw== X-Received: by 2002:a5d:64e6:: with SMTP id g6mr20286089wri.151.1633435348784; Tue, 05 Oct 2021 05:02:28 -0700 (PDT) Received: from localhost (host86-169-137-11.range86-169.btcentralplus.com. [86.169.137.11]) by smtp.gmail.com with ESMTPSA id r9sm17488484wru.2.2021.10.05.05.02.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 05 Oct 2021 05:02:28 -0700 (PDT) From: Andrew Burgess To: gdb-patches@sourceware.org Subject: [PATCHv2] gdb/python: fix memory leak in python inferior code Date: Tue, 5 Oct 2021 13:02:24 +0100 Message-Id: <20211005120224.75706-1-andrew.burgess@embecosm.com> X-Mailer: git-send-email 2.25.4 In-Reply-To: <20210905085309.2153900-1-andrew.burgess@embecosm.com> References: <20210905085309.2153900-1-andrew.burgess@embecosm.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Spam-Status: No, score=-10.5 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_BARRACUDACENTRAL, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP autolearn=ham autolearn_force=no version=3.4.4 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) 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-List-Received-Date: Tue, 05 Oct 2021 12:02:34 -0000 Compared to v1, I have: 1. Rewritten the commit message to, I hope, make it clearer what is going on, 2. Written a test using Python's tracemalloc module so show this bug exists, 3. The actual code change in GDB is identical to v1. Thanks, Andrew --- When a user creates a gdb.Inferior object for the first time a new Python object is created. This object is then cached within GDB's inferior object using the registry mechanism (see inferior_to_inferior_object in py-inferior.c, specifically the calls to inferior_data and set_inferior_data). The Python Reference to the gdb.Inferior object held within the real inferior object ensures that the reference count on the Python gdb.Inferior object never reaches zero while the GDB inferior object continues to exist. At the same time, the gdb.Inferior object maintains a C++ pointer back to GDB's real inferior object. We therefore end up with a system that looks like this: Python Reference | | .----------. | .--------------. | |------------------->| | | inferior | | gdb.Inferior | | |<-------------------| | '----------' | '--------------' | | C++ Pointer When GDB's inferior object is deleted (say the inferior exits) then py_free_inferior is called (thanks to the registry system), this function looks up the Python gdb.Inferior object and sets the C++ pointer to nullptr and finally reduces the reference count on the Python gdb.Inferior object. If at this point the user still holds a reference to the Python gdb.Inferior object then nothing happens. However, the gdb.Inferior object is now in the non-valid state (see infpy_is_valid in py-inferior.c), but otherwise, everything is fine. However, if there are no further references to the Python gdb.Inferior object, or, once the user has given up all their references to the gdb.Inferior object, then infpy_dealloc is called. This function currently checks to see if the inferior pointer within the gdb.Inferior object is nullptr or not. If the pointer is nullptr then infpy_dealloc immediately returns. Only when the inferior point in the gdb.Inferior is not nullptr do we (a) set the gdb.Inferior reference inside GDB's inferior to nullptr, and (b) call the underlying Python tp_free function. There are a number things wrong here: 1. The Python gdb.Inferior reference within GDB's inferior object holds a reference count, thus, setting this reference to nullptr without first decrementing the reference count would leak a reference, however... 2. As GDB's inferior holds a reference then infpy_dealloc will never be called until GDB's inferior object is deleted. Deleting a GDB inferior ohject calls py_free_inferior, and so gives up the reference. At this point there is no longer a need to call set_inferior_data to set the field back to NULL, that field must have been cleared in order to get the reference count to zero, which means... 3. If we know that py_free_inferior must be called before infpy_dealloc, then we know that the inferior pointer in gdb.Inferior will always be nullptr when infpy_dealloc is called, this means that the call to the underlying tp_free function will always be skipped. Skipping this call will cause Python to leak the memory associated with the gdb.Inferior object, which is what we currently always do. Given all of the above, I assert that the C++ pointer within gdb.Inferior will always be nullptr when infpy_dealloc is called. That's what this patch does. I wrote a test for this issue making use of Pythons tracemalloc module, which allows us to spot this memory leak. --- gdb/python/py-inferior.c | 16 ++- gdb/testsuite/gdb.python/py-inferior-leak.c | 22 ++++ gdb/testsuite/gdb.python/py-inferior-leak.exp | 33 ++++++ gdb/testsuite/gdb.python/py-inferior-leak.py | 109 ++++++++++++++++++ 4 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 gdb/testsuite/gdb.python/py-inferior-leak.c create mode 100644 gdb/testsuite/gdb.python/py-inferior-leak.exp create mode 100644 gdb/testsuite/gdb.python/py-inferior-leak.py diff --git a/gdb/python/py-inferior.c b/gdb/python/py-inferior.c index 0659c28ea9c..c8de41dd009 100644 --- a/gdb/python/py-inferior.c +++ b/gdb/python/py-inferior.c @@ -864,12 +864,20 @@ static void infpy_dealloc (PyObject *obj) { inferior_object *inf_obj = (inferior_object *) obj; - struct inferior *inf = inf_obj->inferior; - if (! inf) - return; + /* The inferior itself holds a reference to this Python object, which + will keep the reference count of this object above zero until GDB + deletes the inferior and py_free_inferior is called. + + Once py_free_inferior has been called then the link between this + Python object and the inferior is set to nullptr, and then the + reference count on this Python object is decremented. + + The result of all this is that the link between this Python object and + the inferior should always have been set to nullptr before this + function is called. */ + gdb_assert (inf_obj->inferior == nullptr); - set_inferior_data (inf, infpy_inf_data_key, NULL); Py_TYPE (obj)->tp_free (obj); } diff --git a/gdb/testsuite/gdb.python/py-inferior-leak.c b/gdb/testsuite/gdb.python/py-inferior-leak.c new file mode 100644 index 00000000000..bfe52c018d4 --- /dev/null +++ b/gdb/testsuite/gdb.python/py-inferior-leak.c @@ -0,0 +1,22 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2021 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 . */ + +int +main (void) +{ + return 0; +} diff --git a/gdb/testsuite/gdb.python/py-inferior-leak.exp b/gdb/testsuite/gdb.python/py-inferior-leak.exp new file mode 100644 index 00000000000..259a35e90bb --- /dev/null +++ b/gdb/testsuite/gdb.python/py-inferior-leak.exp @@ -0,0 +1,33 @@ +# Copyright (C) 2021 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 . + +# This file is part of the GDB testsuite. It checks for memory leaks +# associated with allocating and deallocation gdb.Inferior objects. + +load_lib gdb-python.exp + +standard_testfile + +clean_restart + +# Skip all tests if Python scripting is not enabled. +if { [skip_python_tests] } { continue } + +set pyfile [gdb_remote_download host ${srcdir}/${subdir}/${testfile}.py] + +# Source the Python script, this runs the test (which is written +# completely in Python), and either prints PASS, or thows an +# exception. +gdb_test "source ${pyfile}" "PASS" "source python script" diff --git a/gdb/testsuite/gdb.python/py-inferior-leak.py b/gdb/testsuite/gdb.python/py-inferior-leak.py new file mode 100644 index 00000000000..914fb3ecc08 --- /dev/null +++ b/gdb/testsuite/gdb.python/py-inferior-leak.py @@ -0,0 +1,109 @@ +# Copyright (C) 2021 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 . + +import tracemalloc +import gdb +import re + +# A global variable in which we store a reference to the gdb.Inferior +# object sent to us in the new_inferior event. +inf = None + +# Register the new_inferior event handler. +def new_inferior_handler(event): + global inf + inf = event.inferior + + +gdb.events.new_inferior.connect(new_inferior_handler) + +# A global filters list, we only care about memory allocations +# originating from this script. +filters = [tracemalloc.Filter(True, "*py-inferior-leak.py")] + +# Add a new inferior, and return the number of the new inferior. +def add_inferior(): + output = gdb.execute("add-inferior", False, True) + m = re.search(r"Added inferior (\d+)", output) + if m: + num = int(m.group(1)) + else: + raise RuntimeError("no match") + return num + + +# Run the test. When CLEAR is True we clear the global INF variable +# before comparing the before and after memory allocation traces. +# When CLEAR is False we leave INF set to reference the gdb.Inferior +# object, thus preventing the gdb.Inferior from being deallocated. +def test(clear): + global filters, inf + + # Start tracing, and take a snapshot of the current allocations. + tracemalloc.start() + snapshot1 = tracemalloc.take_snapshot() + + # Create an inferior, this triggers the new_inferior event, which + # in turn holds a reference to the new gdb.Inferior object in the + # global INF variable. + num = add_inferior() + gdb.execute("remove-inferiors %s" % num) + + # Possibly clear the global INF variable. + if clear: + inf = None + + # Now grab a second snapshot of memory allocations, and stop + # tracing memory allocations. + snapshot2 = tracemalloc.take_snapshot() + tracemalloc.stop() + + # Filter the snapshots; we only care about allocations originating + # from this file. + snapshot1 = snapshot1.filter_traces(filters) + snapshot2 = snapshot2.filter_traces(filters) + + # Compare the snapshots, this leaves only things that were + # allocated, but not deallocated since the first snapshot. + stats = snapshot2.compare_to(snapshot1, "traceback") + + # Total up all the deallocated things. + total = 0 + for stat in stats: + total += stat.size_diff + return total + + +# The first time we run this some global state will be allocated which +# shows up as memory that is allocated, but not released. So, run the +# test once and discard the result. +test(True) + +# Now run the test twice, the first time we clear our global reference +# to the gdb.Inferior object, which should allow Python to deallocate +# the object. The second time we hold onto the global reference, +# preventing Python from performing the deallocation. +bytes_with_clear = test(True) +bytes_without_clear = test(False) + +# The bug that used to exist in GDB was that even when we released the +# global reference the gdb.Inferior object would not be deallocated. +if bytes_with_clear > 0: + raise gdb.GdbError("memory leak when gdb.Inferior should be released") +if bytes_without_clear == 0: + raise gdb.GdbError("gdb.Inferior object is no longer allocated") + +# Print a PASS message that the test script can see. +print("PASS") -- 2.25.4