[RFC 1/9] gdb/python: preserve identity for gdb.Symtab objects

Jan Vrany
2025-01-27T10:49:27Z

This commit changes symtab_to_symtab_object() so that each it is called
with a particular struct symtab * it returns the very same gdb.Symtab
object.

This is done by searching per-objfile linked list of instances and - if
found - return it rather than creating new gdb.Symtab.
---
gdb/python/py-symtab.c | 18 ++++++++++++++++-
gdb/testsuite/gdb.python/py-symtab.exp | 28 ++++++++++++++++++++++++++
2 files changed, 45 insertions(+), 1 deletion(-)

diff --git a/gdb/python/py-symtab.c b/gdb/python/py-symtab.c
index 99a5094ba60..7b51e211daf 100644
--- a/gdb/python/py-symtab.c
+++ b/gdb/python/py-symtab.c
@@ -449,7 +449,7 @@ set_symtab (symtab_object *obj, struct symtab *symtab)
{
obj->symtab = symtab;
obj->prev = NULL;
- if (symtab)
+ if (symtab != nullptr)
{
obj->next = stpy_objfile_data_key.get (symtab->compunit ()->objfile ());
if (obj->next)
@@ -467,6 +467,22 @@ symtab_to_symtab_object (struct symtab *symtab)
{
symtab_object *symtab_obj;

+ /* Look if there's already a gdb.Symtab object for given SYMTAB
+ and if so, return it. */
+ if (symtab != nullptr)
+ {
+ symtab_obj = stpy_objfile_data_key.get (symtab->compunit ()->objfile ());
+ while (symtab_obj != nullptr)
+ {
+ if (symtab_obj->symtab == symtab)
+ {
+ Py_INCREF (symtab_obj);
+ return (PyObject*)symtab_obj;
+ }
+ symtab_obj = symtab_obj->next;
+ }
+ }
+
symtab_obj = PyObject_New (symtab_object, &symtab_object_type);
if (symtab_obj)
set_symtab (symtab_obj, symtab);
diff --git a/gdb/testsuite/gdb.python/py-symtab.exp b/gdb/testsuite/gdb.python/py-symtab.exp
index 4765ef5cb2f..18d77a0296f 100644
--- a/gdb/testsuite/gdb.python/py-symtab.exp
+++ b/gdb/testsuite/gdb.python/py-symtab.exp
@@ -90,6 +90,34 @@ gdb_test_multiple "python print (\"simple_struct\" in static_symbols)" \
}
}

+# Test symtab identity
+gdb_test "python print (symtab is symtab)"\
+ "True" \
+ "test symtab identity 1"
+gdb_test "python print (symtab is gdb.selected_frame().find_sal().symtab)"\
+ "True" \
+ "test symtab identity 2"
+gdb_test "python print (sal.symtab is gdb.selected_frame().find_sal().symtab)"\
+ "True" \
+ "test symtab identity 3"
+gdb_test "python print (symtab is not \"xxx\")"\
+ "True" \
+ "test symtab non-identity with non-symtab"
+
+# Test symtab equality
+gdb_test "python print (symtab == symtab)"\
+ "True" \
+ "test symtab equality 1"
+gdb_test "python print (symtab == gdb.selected_frame().find_sal().symtab)"\
+ "True" \
+ "test symtab equality 2"
+gdb_test "python print (sal.symtab == gdb.selected_frame().find_sal().symtab)"\
+ "True" \
+ "test symtab equality 3"
+gdb_test "python print (symtab != \"xxx\")"\
+ "True" \
+ "test symtab non-equality with non-symtab"
+
# Test is_valid when the objfile is unloaded. This must be the last
# test as it unloads the object file in GDB.
gdb_unload
--
2.45.2