From: Paul Smith <paul@mad-scientist.net>
To: Jonathan Wakely <jwakely.gcc@gmail.com>
Cc: gcc-help <gcc-help@gcc.gnu.org>
Subject: Re: Help using the GDB C++ STL pretty-printers / xmethods
Date: Mon, 09 May 2022 10:05:49 -0400 [thread overview]
Message-ID: <597302fd641a990a594c836ad9ef9852ea9b231e.camel@mad-scientist.net> (raw)
In-Reply-To: <CAH6eHdRvJ8Vs9M=6QC+G4H=-PA4tyQOsmxz455EPBMomtRZ2eQ@mail.gmail.com>
[-- Attachment #1: Type: text/plain, Size: 1464 bytes --]
On Mon, 2022-05-09 at 12:23 +0100, Jonathan Wakely wrote:
> > But since what you want is something that works in arbitrary Python
> > code, not just within GDB, doesn't pybind11 already do everything
> > you
> > want?
> > https://github.com/pybind/pybind11
>
> If you don't want to (or can't) use pybind11 to create Python
> bindings, and you don't want to use the GDB Python API, then you will
> have a ton of work to do. The GDB Python API is what provides all the
> tools for traversing C++ class hierarchies, examining template
> arguments, casting values to related types etc.
I think I've given the wrong impression: I definitely do not want to
avoid using the GDB Python API and I have no need for my python code to
work outside of GDB.
I was playing with this yesterday and came up with the attached
creating an "accessors.py" API. It's certainly not fully-fleshed out
and is not well-tested; it doesn't try to address any container types.
More of a thought experiment.
The idea is that someone could import libstdcxx.v6.accessors and write
their own code using these Python types. An alternative would of
course be to write a bunch of free methods, rather than create classes.
I went the other way and started with the xmethod implementation, so
mine doesn't do much with tuples. I looked at printers.py a bit, and
considered moving the versioned namespace facilities to this new area
as well, but didn't go further.
[-- Attachment #2: accessors.py --]
[-- Type: text/x-python, Size: 4505 bytes --]
# Accessor methods for libstdc++.
# Copyright (C) 2022 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 <http://www.gnu.org/licenses/>.
import gdb
import re
try:
from typing import Optional
except ImportError:
pass
class AccessorBase(object):
"""Base class for accessors of C++ STL types."""
_name = None # type: str
_typere = None # type: str
_typerx = None # type: Optional[re.Match]
_ptr = None # type: Optional[gdb.Value]
@classmethod
def is_type(cls, otype):
# type: (gdb.Type) -> None
"""Return true if the provided type is of this class."""
if cls._typerx is None:
cls._typerx = re.compile(cls._typere)
return cls._typerx.match(otype.tag) is not None
def __init__(self, ptr):
# type: (gdb.Value) -> None
if not self.is_type(ptr.type):
raise ValueError("Value has type '%s', expected '%s'"
% (str(ptr.type), self._name))
self._ptr = ptr
def __str__(self):
# type: () -> str
return str(self._ptr)
class SmartPtr(AccessorBase):
"""Base accessor for C++ STL smart pointers."""
def get(self):
# type: () -> Optional[gdb.Value]
"""Return the pointer owned by this smart pointer, or None."""
raise NotImplementedError("get() not implemented")
class UniquePtr(SmartPtr):
"""Accessor for std::unique_ptr<>."""
_name = 'std::unique_ptr'
_typere = r'^std::(?:__\d+::)?unique_ptr<.*>$'
_newre = None # type: Optional[re.Match]
_oldre = None # type: Optional[re.Match]
def get(self):
# type: () -> Optional[gdb.Value]
"""Return the pointer owned by std::unique_ptr<>, or None."""
if self._ptr is None:
return None
impl_type = self._ptr.type.fields()[0].type.strip_typedefs()
# Check for new implementations first:
if UniquePtr._newre is None:
UniquePtr._newre = re.compile(r'^std::(?:__\d+::)?__uniq_ptr_(data|impl)<.*>$')
if UniquePtr._newre.match(impl_type):
tuple_member = self._ptr['_M_t']['_M_t']
else:
if UniquePtr._oldre is None:
UniquePtr._oldre = re.compile(r'^std::(?:__\d+::)?tuple<.*>$')
if UniquePtr._oldre.match(impl_type):
tuple_member = self._ptr['_M_t']
else:
raise ValueError("Unsupported implementation for unique_ptr: %s" % str(impl_type))
tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
head_field = tuple_head_type.fields()[0]
if head_field.name == '_M_head_impl':
return tuple_member['_M_head_impl']
if head_field.is_base_class:
return tuple_member.cast(head_field.type)
return None
class SharedPtr(SmartPtr):
"""Accessor for std::shared_ptr<>."""
_name = 'std::{shared,weak}_ptr'
_typere = r'^std::(?:__\d+::)?(?:shared|weak)_ptr<.*>$'
def get(self):
# type: () -> Optional[gdb.Value]
"""Return the pointer managed by std::shared_ptr<>, or None."""
if self._ptr is None:
return None
return self._ptr['_M_ptr']
def _get_refcounts(self):
# type: () -> Optional[gdb.Value]
"""Return the refcount struct or None."""
return self._ptr['_M_refcount']['_M_pi'] if self._ptr else None
def use_count(self):
# type: () -> int
"""Return the use count of the std::shared_ptr<>."""
refcounts = self._get_refcounts()
return refcounts['_M_use_count'] if refcounts else 0
def weak_count(self):
# type: () -> int
"""Return the weak count of the std::shared_ptr<>."""
refcounts = self._get_refcounts()
return refcounts['_M_weak_count'] if refcounts else 0
[-- Attachment #3: xmethods.diff --]
[-- Type: text/x-patch, Size: 2411 bytes --]
diff --git a/libstdc++-v3/python/libstdcxx/v6/xmethods.py b/libstdc++-v3/python/libstdcxx/v6/xmethods.py
index 130a658758b..c5e2e6f9363 100644
--- a/libstdc++-v3/python/libstdcxx/v6/xmethods.py
+++ b/libstdc++-v3/python/libstdcxx/v6/xmethods.py
@@ -19,6 +19,8 @@ import gdb
import gdb.xmethod
import re
+import accessors
+
matcher_name_prefix = 'libstdc++::'
def get_bool_type():
@@ -585,22 +587,9 @@ class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
return method_name == 'get' or not self._is_array
def __call__(self, obj):
- impl_type = obj.dereference().type.fields()[0].type.tag
- # Check for new implementations first:
- if re.match('^std::(__\d+::)?__uniq_ptr_(data|impl)<.*>$', impl_type):
- tuple_member = obj['_M_t']['_M_t']
- elif re.match('^std::(__\d+::)?tuple<.*>$', impl_type):
- tuple_member = obj['_M_t']
- else:
- return None
- tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
- tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
- head_field = tuple_head_type.fields()[0]
- if head_field.name == '_M_head_impl':
- return tuple_member.cast(tuple_head_type)['_M_head_impl']
- elif head_field.is_base_class:
- return tuple_member.cast(head_field.type)
- else:
+ try:
+ return accessors.UniquePtr(obj.dereference()).get()
+ except ValueError:
return None
class UniquePtrDerefWorker(UniquePtrGetWorker):
@@ -684,7 +673,10 @@ class SharedPtrGetWorker(gdb.xmethod.XMethodWorker):
return method_name == 'get' or not self._is_array
def __call__(self, obj):
- return obj['_M_ptr']
+ try:
+ return accessors.SharedPtr(obj.dereference()).get()
+ except ValueError:
+ return None
class SharedPtrDerefWorker(SharedPtrGetWorker):
"Implements std::shared_ptr<T>::operator*()"
@@ -739,8 +731,7 @@ class SharedPtrUseCountWorker(gdb.xmethod.XMethodWorker):
return gdb.lookup_type('long')
def __call__(self, obj):
- refcounts = obj['_M_refcount']['_M_pi']
- return refcounts['_M_use_count'] if refcounts else 0
+ return accessors.SharedPtr(obj.dereference()).use_count()
class SharedPtrUniqueWorker(SharedPtrUseCountWorker):
"Implements std::shared_ptr<T>::unique()"
next prev parent reply other threads:[~2022-05-09 14:05 UTC|newest]
Thread overview: 21+ messages / expand[flat|nested] mbox.gz Atom feed top
2022-05-07 1:23 Paul Smith
2022-05-07 11:19 ` Hannes Domani
2022-05-07 15:07 ` Paul Smith
2022-05-07 15:35 ` Jonathan Wakely
2022-05-07 19:07 ` Paul Smith
2022-05-07 19:51 ` Jonathan Wakely
2022-05-07 23:08 ` Paul Smith
2022-05-08 8:13 ` Jonathan Wakely
2022-05-08 8:16 ` Jonathan Wakely
2022-05-08 14:09 ` Paul Smith
2022-05-08 14:36 ` Jonathan Wakely
2022-05-08 19:44 ` Paul Smith
2022-05-08 20:26 ` Paul Smith
2022-05-09 10:47 ` Hannes Domani
2022-05-09 10:52 ` Hannes Domani
2022-05-09 9:32 ` Jonathan Wakely
2022-05-09 11:23 ` Jonathan Wakely
2022-05-09 14:05 ` Paul Smith [this message]
2022-05-09 14:40 ` Paul Smith
2022-05-07 15:44 ` Hannes Domani
2022-05-07 15:25 ` Jonathan Wakely
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=597302fd641a990a594c836ad9ef9852ea9b231e.camel@mad-scientist.net \
--to=paul@mad-scientist.net \
--cc=gcc-help@gcc.gnu.org \
--cc=jwakely.gcc@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).