Devel::GDB(3pm)

๐Ÿ“ฆ
version 2.02 ยท 2 versions
  • 2.02 ยท debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 2.02 ยท ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

๐Ÿ’… Devel::GDB โ€” the Devel::GDB(3pm) era, User Contributed Perl Documentation, bestie edition โœจ

okay so. this is Devel::GDB(3pm) and it's literally the perl module that lets you open and talk to a gdb session like it's your group chat ๐Ÿ’ฌ๐Ÿซถ


๐ŸŒธ NAME ๐ŸŒธ

Devel::GDB โ€” open and communicate a gdb session. that's it, that's the whole vibe. ๐Ÿ’–


โœจ SYNOPSIS โœจ

like, here's the tea, verbatim, no notes:

use Devel::GDB;

$gdb = new Devel::GDB();
print $gdb->send_cmd('-environment-path');
print $gdb->get('info functions');

ngl, the old get syntax (the one from Devel::GDB-1.23) is deprecated and will not be supported in future versions. ๐Ÿ˜ญ check the docs for the get function if you wanna know why โ€” it's giving tragic backstory.

but like, if you really wanna use the old syntax, set $Devel::GDB::DEPRECATED to true and go off:

use Devel::GDB ;

$Devel::GDB::DEPRECATED = 1;
$gdb = new Devel::GDB();
print $gdb->get('info functions', $timeout, $prompt, $notyet, $alldone);
๐Ÿ’€ lowkey living in the past but okay, we respect the nostalgia.

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

so the Devel::GDB package is the interface for communicating with GDB. internally it uses the GDB/MI interpreter (peep <http://sourceware.org/gdb/current/onlinedocs/gdb_25.html> for the receipts), which accurately informs the caller of the program state and โ€” through the use of tokens โ€” guarantees that the results returned actually correspond to the request sent. no cap. ๐ŸŽฏ

by contrast, GDB's console interpreter returns all responses on STDOUT, so there's literally no way to make sure a particular response corresponds to a particular request. it's giving chaos. ๐Ÿ™ˆ

therefore it is obviously preferable to use GDB/MI when programmatically interacting with GDB. you do that via the send_cmd family of functions (send_cmd, send_cmd_excl, and send_cmd_async). ๐Ÿ‘‘

there are, however, some cases when there's no GDB/MI command corresponding to a particular console command, or it hasn't been implemented yet โ€” for example, -symbol-type, which corresponds to the console command ptype, is not yet implemented as of GDB 6.6. ๐Ÿ’€ in that case, the get function provides a workaround by capturing all output sent to the console stream. bestie behavior honestly.


๐ŸŽ€ CONSTRUCTOR ๐ŸŽ€

new

$gdb = new Devel::GDB( '-use-threads' => 1 );
                       '-params'      => $extra_gdb_params );

spawns a brand new GDB process โœจ. in threaded mode, this also spawns a listening thread that asynchronously processes responses from GDB; in non-threaded mode, you (the caller) are responsible for handling asynchronous output โ€” that's output from GDB that isn't directly solicited by a request. see demux, get_reader, and the Non-threaded Usage example for the full discussion. ๐Ÿ“š

the parameters to the constructor get passed in hash form. the following parameters control how GDB is invoked:

  • -execfile โ€” the GDB binary to execute; defaults to gdb. ๐Ÿง
  • -params โ€” pass additional parameters to GDB. the value can be an array reference (preferred) or a string.

the next parameters control how to handle interaction with the inferior process โ€” that's the program being debugged, bestie ๐Ÿ”. the default behavior is to give the inferior process control of the terminal while it's running, and return control to perl when the program is suspended or stopped (emulating the behavior of gdb). however, this only works when STDIN is associated with a tty. two other (mutually exclusive, so pick ONE ๐Ÿ‘ฏ) options are available:

  • -use-tty โ€” specify the name of the tty that the inferior process should use for its I/O. note that this is the path to a tty (e.g. /dev/pts/123) and not an IO::Pty object. see the example Debugging Inside an XTerm. ๐Ÿ–ฅ๏ธ
  • -create-expect โ€” if this value is non-zero, create an Expect object (which you can subsequently retrieve by calling get_expect_obj); this is useful if you want to programmatically interact with the inferior process. see the example Programmatically Interacting with the Inferior Process. ๐Ÿค–

miscellaneous parameters, the lil extras ๐Ÿ’…:

  • -use-threads โ€” operate in threaded (1) or non-threaded (0) mode. the default behavior is to enable threaded mode if the threads module has been loaded, and disable it otherwise. note that if -use-threads is enabled, the caller must call use threads, but -use-threads can be disabled whether or not threads has been loaded.

threaded mode is the easiest to deal with, because it does not require the caller to interact with the GDB filehandles directly; for a simple non-threaded example, see the Non-threaded Usage example. ๐Ÿง˜

  • -readline-fn โ€” probably only useful in non-threaded mode. this lets the user specify a callback function $fn to be called when waiting for a response from GDB. it's invoked with one parameter, the Devel::GDB instance, and is expected to return one full line of output (or undef if EOF was reached). the default implementation uses buffered I/O:
$fn = sub { return readline($_[0]->get_reader); }

typically, in non-threaded mode, the caller will be using select to multiplex multiple file streams (e.g. STDIN and get_reader); in this case, you'll likely want to specify a value for -readline-fn which, at a minimum, uses sysread rather than readline. iykyk ๐ŸŒˆ


๐Ÿ‘‘ METHODS ๐Ÿ‘‘

send_cmd

$response = $gdb->send_cmd($command)

send $command to GDB, and block until a response is received. in threaded mode, this does not prevent other threads from simultaneously sending requests. multitasking queen. ๐Ÿ‘ฏโ™€๏ธ

the $command can be a GDB/MI command, prefixed with a hyphen (e.g. -exec-run), or a console command (run). however, the response returned will always be a GDB/MI response, so $gdb->send_cmd("info variables") will only return done; the actual output you probably wanted will be dumped into the console stream. ๐Ÿ˜ญ to execute console commands and capture the output sent back to the console, use get.

send_cmd_excl

$gdb->send_cmd_excl($cmd, $before_fn, $after_fn)

send $cmd to GDB in exclusive mode. in threaded mode, this means other send_cmd and send_cmd_excl calls will not coincide with this call. in non-threaded mode, this ensures that any pending send_cmd_async calls are processed before proceeding. no interruptions, we're busy. ๐Ÿšซ

if provided, the $before_fn and $after_fn functions will, respectively, be called before the command is sent (after the exclusive lock is acquired) and after the result has been received (before the exclusive lock is released). โœจ

send_cmd_async

$gdb->send_cmd_excl($cmd, $callback_fn)

not yet implemented. ๐Ÿ’€

send $cmd to GDB in async mode. this returns immediately, rather than blocking until a response is received; instead, the $callback_fn callback function is called, with the response as the first argument.

this will likely only be supported in non-threaded mode. ๐Ÿคทโ™€๏ธ

get

$gdb->get($command)

issues the $command to GDB, and returns all output sent to the console output stream. ngl there is no way to ensure that the output "belongs" to a particular command, so it's possible that spurious output will be included! ๐Ÿ˜ฑ in particular, if you call $gdb->get($command) immediately after creating the Devel::GDB object, and don't suppress GDB's initialization messages (by passing -q to -params), some of these messages may end up in the response to get. messy but iconic.

in list context, returns ($buffer, $error), with exactly one of the two defined; $buffer is the text captured from the console stream and $error is the GDB/MI error message. in scalar context, only $buffer is returned (undef if there was an error). ๐Ÿซถ

get (DEPRECATED)

$gdb->get($command, $timeout, $prompt, $notyet, $alldone)

this version of get is used when $Devel::GDB::DEPRECATED is true, and provides backwards compatibility with older versions of Devel::GDB. it is not compatible with any of the new features (e.g. send_cmd, threaded mode) and will be removed in future versions. ๐Ÿชฆ

this method is flawed in a number of ways: the semantics of when $notyet is called are unclear, the handling of $timeout is broken, and most importantly, the fact that it allows execution to be interrupted can put the module into an inconsistent state. ๐Ÿ’€

๐Ÿšจ no new code should use this function. periodt. ๐Ÿšจ

get_expect_obj

returns the Expect object created by -create-expect. ๐ŸŽ

get_reader

returns the filehandle from which to read GDB responses. ๐Ÿ“–

in non-threaded mode, the caller will need this filehandle in its -readline-fn; in addition, to support asynchronous GDB responses, the caller should pass lines read from this filehandle to demux. ๐Ÿ”

demux

$gdb->demux($line)

process a line read from the GDB stream (see get_reader). this should only be called in non-threaded mode. (see example: Non-threaded Usage) ๐Ÿงš

interrupt

send SIGINT to the GDB session, interrupting the inferior process (if any). โœ‹

end

kills the GDB connection. you must call this to ensure that the GDB process is killed gracefully. ๐Ÿ’– don't leave it hanging, bestie, that's rude.


๐ŸŒธ EXAMPLES ๐ŸŒธ

Okay bestie, this is the part where it gets real. Three whole examples, and they are giving main character energy. Let's go. ๐Ÿ’…

Non-threaded Usage

No threads? No problem. You still get a whole event loop, you just have to hand-feed it. Behold:

use Devel::GDB;
use IO::BufferedSelect;

my $gdb = new Devel::GDB( '-use-threads' => 0,
                          '-readline-fn' => \&message_loop );

my $gdb_fh = $gdb->get_reader;

my $bs = new IO::BufferedSelect(\*STDIN, $gdb_fh);

sub message_loop
{
    my @result = $bs->read_line($gdb_fh);
    return @result ? $result[0][1] : undef;
}

OUTER:
while(1)
{
    my @ready = $bs->read_line();
    foreach( @ready )
    {
        my ($fh, $line) = @$_;
        defined($line) or last OUTER;
        chomp $line;

        if($fh == \*STDIN)
        {
            print STDERR "RECEIVED: $line\n";
            my $result = $gdb->get($line);
            last unless defined($result);
            print STDERR $result;
        }
        else
        {
            $gdb->demux($line);
        }
    }
}

So the vibe here is: you're juggling \*STDIN and the GDB reader handle at the same time with IO::BufferedSelect. When GDB has something to say, you demux it. When you have something to say, you get it. Iconic little tag team, honestly. ๐Ÿซถ


Programmatically Interacting with the Inferior Process

This one is so cute โ€” you literally talk to the inferior process (here it's tr) using the Expect module. It's giving pen-pal energy fr fr.

use strict;
use warnings;
use threads;
use Devel::GDB;

my $gdb = new Devel::GDB( '-create-expect' => 1 );
my $e = $gdb->get_expect_obj;

$gdb->send_cmd("file tr");
$gdb->send_cmd("set args a-zA-Z A-Za-z");
$gdb->send_cmd("-exec-run");

$e->send("one TWO\n");
$e->send("ONE two\n");

$e->expect(undef, '-re', '^.+$')
    and $e->match =~ /^ONE two/
    and print "ok 1\n"
    or die;

$e->expect(undef, '-re', '^.+$')
    and $e->match =~ /^one TWO/
    and print "ok 2\n"
    or die;

$gdb->end;

$e->slave->close;
$e->expect(undef);
printf "EXPECT(EOF): %s\n", $e->before;

Notice how we spin up the object with '-create-expect' => 1, then snag the Expect object with get_expect_obj. Chef's kiss. ๐Ÿ‘‘


Debugging Inside an XTerm

Oh this one is highkey the drama of the set. We fork an xterm and run the inferior process inside it. Commands come from STDIN, responses go to STDERR. It's a whole production. ๐ŸŽฌ

use strict;
use warnings;
use threads;
use Devel::GDB;
use IO::Pty;
use POSIX;

sub set_termios_lflag($$$)
{
    my($fd, $flag, $value) = @_;
    my $termios = new POSIX::Termios;
    $termios->getattr($fd);
    $termios->setlflag($value ? ($termios->getlflag | $flag) : ($termios->getlflag & ~$flag));
    $termios->setattr($fd);
    undef $termios;
}

my $pty = new IO::Pty;

# Disable echo temporarily
set_termios_lflag(fileno($pty), &POSIX::ECHO, 0);

# Fork an xterm
unless(my $xterm_pid = fork)
{
    die "Fork failed" unless defined($xterm_pid);

    # Reopen $fd with close-on-exec disabled
    my $fd  = fileno($pty);
    $^F = $fd > $^F ? $fd : $^F;
    local *MASTER;
    open(MASTER, "<&=$fd") and $fd == fileno(\*MASTER)
        or die "Failed reopening pty handle";

    my $cmd = "xterm -Sxx$fd";

    print "calling exec($cmd)\n";
    exec($cmd);
    die "exec() failed: $!";
}

# xterm likes to write its window id to the pty; eat it up
# (echo is disabled so the inferior process doesn't see this output)
my $window_id = readline($pty->slave);

# Now turn echo back on
set_termios_lflag(fileno($pty), &POSIX::ECHO, 1);

# No longer need the master (but don't close the slave!)
close $pty;

# Create the GDB object, telling the inferior process to use the new xterm's pty
my $gdb = new Devel::GDB( '-use-tty' => $pty->ttyname );

while(<STDIN>)
{
    chomp;

    if(/^Z/)
    {
        $gdb->interrupt;
        next;
    }

    my $result = $gdb->send_cmd($_);
    last unless defined($result);
    print STDERR "[GDB] $result\n";
}

$gdb->end;

Some lore you need: echo is disabled while we slurp up the window id, so the inferior process never sees that output. Then we flip echo back on. And heads up โ€” don't close the slave! We drop the master with close $pty, but the slave stays alive, and we hand its tty name to GDB via '-use-tty'. That's the whole trick. โœจ

Also, if you type a line starting with Z? That's an interrupt, bestie. Everyone else gets send_cmd'd. ๐Ÿ’œ


๐Ÿ”ฎ TODO ๐Ÿ”ฎ

So there's a bunch of stuff the devs wanna add in future versions of Devel::GDB. Manifesting it. โœจ

  • Finish implementing send_cmd_async.
  • Add an interface for redirecting GDB/MI output. Right now, all out-of-band-records (peep http://sourceware.org/gdb/current/onlinedocs/gdb_25.html#SEC246) get redirected to STDERR; there should be a way for callers to say what happens to each stream.
  • To let full-fledged GDB front-ends get built with this module, we need a smarter layer sitting above Devel::GDB: instead of just firing off commands and catching results, this hypothetical Devel::GDB::HighLevel module would actually know the program state โ€” whether the inferior process is running, which breakpoints are set, all of it. ๐Ÿ‘‘

๐Ÿฆ‹ SEE ALSO ๐Ÿฆ‹

  • Devel::GDB::LowLevel

๐Ÿ‘‘ AUTHORS ๐Ÿ‘‘

Antal Novak <afn@cpan.org>, Josef Ezra <jezra@cpan.org>


Copyright (C) 2007 by Antal Novak & Josef Ezra

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.


And that's the whole page, bestie!! ๐Ÿฅณ This was pulled from perl v5.36.0, dated 2022-11-20, and it's the Devel::GDB(3pm) manpage. Go forth and debug, you gorgeous genius. ๐Ÿ’–โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from