PDLdb(3pm)
π PDLdb(3pm) β the perl debugger with PDL support π
okay bestie, welcome to the PDLdb.pl era. this is PDLdb.pl, aka the perl debugger with PDL support β an enhanced version of the perl debugger that gets PDL::NiceSlice constructs. we're doing this in 9 parts, this is part 1, so get comfy, grab a π snack, and let's go.
β¨ SYNOPSIS β¨
export PERL5DB='BEGIN { require "PDLdb.pl" }' # e.g., with sh/bash
perl -d your_Perl_script
πΈ DESCRIPTION πΈ
okay so PDLdb.pl is literally the perl debugger but upgraded, and the whole thing it brings to the table is PDL support β specifically PDL::NiceSlice constructs. all you do is set the PERL5DB environment variable like we showed you up there in the synopsis, and Perl will load it automatically the second you run a script with perl -d. no cap. π«Ά
and this documentation? it's here to outline the structure and services that PDLdb.pl (i.e. perl5db.pl) provides, and to tell you how you can actually use them. very main character of it.
π GENERAL NOTES π
ngl, the debugger can look pretty forbidding to a lot of Perl programmers. there are a bunch of reasons for that, and honestly a lot of them come straight out of the debugger's history.
when the debugger was first written, Perl didn't have a lot of its nicer features β no references, no lexical variables, no closures, no object-oriented programming. so a lot of the stuff one would normally do with those features got done using global variables, globs, and the local() operator in very creative ways.
some of those tricks survived into the current debugger, and a few of the more interesting and still-useful idioms are noted in this section, along with notes on the comments themselves.
π Why not use more lexicals?
experienced Perl programmers will clock this immediately: the debugger code tends to use mostly package globals instead of lexically-scoped variables. why? because it allows a significant amount of control of the debugger from outside the debugger itself. iconic behavior, honestly.
unfortunately, even though the variables are accessible, they're not well documented, so it's generally been a decision that hasn't made a lot of difference to most users. where appropriate, comments have been added to make variables more accessible and usable, with the understanding that these are debugger internals, and are therefore subject to change. future development should probably attempt to replace the globals with a well-defined API, but for now, the variables are what we've got. we work with what we have bestie π
π Automated variable stacking via local()
as you may recall from reading perlfunc, the local() operator makes a temporary copy of a variable in the current scope. when the scope ends, the old copy is restored. this is often used in the debugger to handle the automatic stacking of variables during recursive calls:
sub foo {
local $some_global++;
# Do some stuff, then ...
return;
}
so what happens is that on entry to the subroutine, $some_global is localized, then altered. when the subroutine returns, Perl automatically undoes the localization, restoring the previous value. voila, automatic stack management β¨
the debugger uses this trick a lot. of particular note is DB::eval, which lets the debugger get control inside of eval'ed code. the debugger localizes a saved copy of $@ inside the subroutine, which allows it to keep $@ safe until it DB::eval returns, at which point the previous value of $@ is restored. this makes it simple (well, simpler) to keep track of $@ inside evals which eval other eval's.
in any case, watch for this pattern. it occurs fairly often.
π The "^" trick
this one is used to cleverly reverse the sense of a logical test depending on the value of an auxiliary variable. for instance, the debugger's S (search for subroutines by pattern) allows you to negate the pattern like this:
# Find all non-'foo' subs:
S !/foo/
boolean algebra states that the truth table for XOR looks like this:
0 ^ 0 = 0
(! not present and no match) --> false, don't print
0 ^ 1 = 1
(! not present and matches) --> true, print
1 ^ 0 = 1
(! present and no match) --> true, print
1 ^ 1 = 0
(! present and matches) --> false, don't print
as you can see, the first pair applies when ! isn't supplied, and the second pair applies when it is. the XOR simply allows us to compact a more complicated if-then-elseif-else into a more elegant (but perhaps overly clever) single test. after all, it needed this whole explanation... π
π₯ FLAGS, FLAGS, FLAGS
there is a certain C programming legacy in the debugger. some variables, such as $single, $trace, and $frame, have magical values composed of 1, 2, 4, etc. (powers of 2) OR'ed together. this allows several pieces of state to be stored independently in a single scalar.
a test like
if ($scalar & 4) ...
is checking to see if the appropriate bit is on. since each bit can be "addressed" independently in this way, $scalar is acting sort of like an array of bits. obviously, since the contents of $scalar are just a bit-pattern, we can save and restore it easily (it will just look like a number).
the problem, is of course, that this tends to leave magic numbers scattered all over your program whenever a bit is set, cleared, or checked. so why do it?
- first, doing an arithmetical or bitwise operation on a scalar is just about the fastest thing you can do in Perl:
use constantactually creates a subroutine call, and array and hash lookups are much slower. is this over-optimization at the expense of readability? possibly, but the debugger accesses these variables a lot. any rewrite of the code will probably have to benchmark alternate implementations and see which is the best balance of readability and speed, and then document how it actually works. - second, it's very easy to serialize a scalar number. this is done in the restart code; the debugger state variables are saved in
%ENVand then restored when the debugger is restarted. having them be just numbers makes this trivial. slay π - third, some of these variables are being shared with the Perl core smack in the middle of the interpreter's execution loop. it's much faster for a C program (like the interpreter) to check a bit in a scalar than to access several different variables (or a Perl array).
π What are those "XXX" comments for?
any comment containing XXX means that the comment is either somewhat speculative β it's not exactly clear what a given variable or chunk of code is doing β or that it is incomplete: the basics may be clear, but the subtleties are not completely documented.
send in a patch if you can clear up, fill out, or clarify an XXX. be the change you want to see π«Ά
π¦ DATA STRUCTURES MAINTAINED BY CORE π¦
there are a number of special data structures provided to the debugger by the Perl interpreter. let's go through them because they're lowkey important.
the array @{$main::{'_<'.$filename}} (aliased locally to @dbline via glob assignment) contains the text from $filename, with each element corresponding to a single line of $filename.
the hash %{'_<'.$filename} (aliased locally to %dbline via glob assignment) contains breakpoints and actions. the keys are line numbers; you can set individual values, but not the whole hash. the Perl interpreter uses this hash to determine where breakpoints have been set. any true value is considered to be a breakpoint; perl5db.pl uses "$break_condition\0$action". values are magical in numeric context: 1 if the line is breakable, 0 if not.
the scalar ${"_<$filename"} simply contains the string "_<$filename". this is also the case for evaluated strings that contain subroutines, or which are currently being executed. the $filename for evaled strings looks like (eval 34) or (re_eval 19).
β DEBUGGER STARTUP β
when perl5db.pl starts, it reads an rcfile (perl5db.ini for non-interactive sessions, .perldb for interactive ones) that can set a number of options. in addition, this file may define a subroutine &afterinit that will be executed (in the debugger's context) after the debugger has initialized itself.
next, it checks the PERLDB_OPTS environment variable and treats its contents as the argument of a o command in the debugger. cute, right?
π§ STARTUP-ONLY OPTIONS
the following options can only be specified at startup. to set them in your rcfile, add a call to &parse_options("optionName=new_value").
TTYβ the TTY to use for debugging i/o.noTTYβ if set, goes in NonStop mode. on interrupt, if TTY is not set, uses the value of noTTY or$HOME/.perldbtty$$to find TTY using Term::Rendezvous. current variant is to have the name of TTY in this file.ReadLineβ if false, a dummy ReadLine is used, so you can debug ReadLine applications.NonStopβ if true, no i/o is performed until interrupt.LineInfoβ file or pipe to print line number info to. if it is a pipe, a short "emacs like" message is used.RemotePortβ host:port to connect to on remote host for remote debugging.HistFileβ file to store session history to. there is no default and so no history file is written unless this variable is explicitly set.HistSizeβ number of commands to store to the file specified inHistFile. default is100.
πΈ SAMPLE RCFILE
&parse_options("NonStop=1 LineInfo=db.out");
sub afterinit { $trace = 1; }
the script will run without human intervention, putting trace information into db.out. (if you interrupt it, you had better reset LineInfo to something interactive!) π
seriously bestie, that LineInfo reset is not a suggestion. you interrupt it, you deal with the consequences.
still with me? good, because there's more. π«Ά
π¦ INTERNALS DESCRIPTION π¦
π DEBUGGER INTERFACE VARIABLES π
Okay so bestie, here's the tea on how Perl actually talks to the debugger. Perl is the one supplying the values for %sub, not the debugger itself. What it does is basically slide a &DB::DB(); in front of every single spot that could possibly have a breakpoint. And at every subroutine call it hits up &DB::sub with $DB::sub set to whichever sub got called. It also drops a BEGIN {require 'perl5db.pl'} before the very first line. π
And after each required file gets compiled β but before it runs, note the order β a call to &DB::postponed($main::{'_<'.$filename}) happens. $filename there is the expanded name of the required file (the one you'd find via %INC). π«Ά
π IMPORTANT INTERNAL VARIABLES π
$CreateTTYβ the lil switch that controls when the debugger tries to grab another TTY for input.1β onfork()2β debugger is started inside debugger4β on startup
$doretβ if it's-2, that means no return value should get printed, periodt. Any other positive value makesDB::subprint return values.$evalargβ the item thatDB::evalis gonna eval. It lives here specifically so nothing messes with the current contents of@_whenDB::evalgets called. Iconic behavior honestly.$frameβ decides which messages (if any) get printed when a subroutine (or eval) is entered or exited.0β No enter/exit messages1β Print entering messages on subroutine entry2β Adds exit messages on subroutine exit. If no other flag is on, acts like 1+2.4β Extended messages:<in|out> context=fully-qualified sub name from file:line. If no other flag is on, acts like 1+4.8β Adds parameter information to messages, and overloaded stringify and tied FETCH is enabled on the printed arguments. Ignored if 4 is not on.16β Addscontext return from subname: valuemessages on subroutine/eval exit. Ignored if 4 is is not on.
To get everything, use $frame=30 (or o f=30 as a debugger command). The debugger internally juggles the value of $frame during execution so that external modules the debugger uses don't get traced. π
$levelβ tracks the current debugger nesting level. Used to figure out how many<>pairs to wrap the line number in when the debugger prints a prompt. Also helps determine if the program has finished while commands are being parsed.$onetimeDumpβ controls what (if anything)DB::eval()prints after it evaluates an expression.undefβ don't print anythingdumpβ usedumpvar.plto display the value returnedmethodsβ print the methods callable on the first item returned
$onetimeDumpDepthβ controls how far downdumpvar.plwill go before printing...while dumping a structure. It's numeric. If it'sundef, print all levels. All of them. No cap. π$signalβ tracks whether or not anINTsignal has been detected.DB::DB(), which gets called before every statement, checks this and puts the user into command mode if it finds$signalset to a true value.$singleβ controls behavior during single-stepping. It gets stacked in@stackon entry to each subroutine, and popped again at the end of each subroutine.0β run continuously.1β single-step, go into subs. Thescommand.2β single-step, don't go into subs. Thencommand.4β print current sub depth (turned on to force this when "too much recursion" occurs.
$traceβ controls the output of trace information.1β Thetcommand was entered to turn on tracing (every line executed is printed)2β watch expressions are active4β user defined awatchfunction()inafterinit()
$slave_editorβ1ifLINEINFOwas directed to a pipe;0otherwise.@cmdfhsβ a stack of filehandles thatDB::readline()will read commands from. Manipulated by the debugger'ssourcecommand and byDB::readline()itself.@dblineβ a local alias to the magical line array,@{$main::{'_<'.$filename}}, handed to the debugger by the Perl interpreter. Contains the source. β¨@old_watchβ previous values of watch expressions. First set when the expression is entered; reset whenever the watch expression changes.@savedβ saves important globals ($@,$!,$^E,$,,$/,$\,$^W) so the debugger can swap in safe values while it's running, then restore them when it hands control back.@stackβ saves the current value of$singleon entry to a subroutine. Manipulated by theccommand to turn off tracing in all subs above the current one.@to_watchβ the 'watch' expressions: to be evaluated before each line is executed.@typeaheadβ the typeahead buffer, used byDB::readline.%aliasβ command aliases. Stored as character strings to be substituted for a command entered.%break_on_loadβ keys are file names, values are1(break when this file is loaded) orundef(don't break when it is loaded).%dblineβ keys are line numbers, values arecondition\0action. If used in numeric context, values are0if not breakable,1if breakable, no matter what is in the actual hash entry. Sneaky. π%had_breakpointsβ keys are file names; values are bitfields:1β file has a breakpoint in it.2β file has an action in it.
A zero or undefined value means this file has neither.
%optionβ stores the debugger options. These are character string values.%postponedβ saves breakpoints for code that hasn't been compiled yet. Keys are subroutine names, values are:compileβ break when this sub is compiledbreak +0 if <condition>β break (conditionally) at the start of this routine. The condition will be'1'if no condition was specified.
%postponed_fileβ this hash keeps track of breakpoints that need to be set for files that have not yet been compiled. Keys are filenames; values are references to hashes. Each of these hashes is keyed by line number, and its values are breakpoint definitions (condition\0action).
π DEBUGGER INITIALIZATION π
The debugger's initialization actually jumps all over the place inside this package, and that's genuinely not a bug. It's because there are several BEGIN blocks (which, obviously, execute immediately) scattered through the code. Why tho? π€
Well, the debugger needs to be able to change some things and set some things up before the debugger code is compiled. Most notably, the $deep variable that DB::sub uses to tell when a program has recursed deeply. On top of that, the debugger has to turn off warnings while the debugger code is compiled, but then restore them to their original setting before the program being debugged starts executing.
The first BEGIN block just turns off warnings by saving the current setting of $^W and then setting it to zero. The second one initializes the debugger variables that are needed before the debugger begins executing. The third one puts $^X back to its former value. π§
We'll detail that second BEGIN block later; for now just remember that if you need to initialize something before the debugger starts really executing, that's where it has to go. Nowhere else. Periodt.
π DEBUGGER ROUTINES π
π DB::eval() π
This function replaces straight eval() inside the debugger; it simplifies the whole process of evaluating code in the user's context.
The code to be evaluated is passed via the package global variable $DB::evalarg; this is done to avoid fiddling with the contents of @_. Protect the @_ at all costs, fr fr.
Before we do the eval(), we preserve the current settings of $trace, $single, $^D and $usercontext. The latter contains the preserved values of $@, $!, $^E, $,, $/, $\, $^W and the user's current package, grabbed when DB::DB got control. This causes the proper context to be used when the eval is actually done. Afterwards, we restore $trace, $single, and $^D.
Next we need to handle $@ without getting confused. We save $@ in a local lexical, localize $saved[0] (which is where save() will put $@), and then call save() to capture $@, $!, $^E, $,, $/, $\, and $^W and set $,, $/, $\, and $^W to values considered sane by the debugger. If there was an eval() error, we print it on the debugger's output. If $onetimedump is defined, we call dumpit if it's set to 'dump', or methods if it's set to 'methods'. Setting it to something else causes the debugger to do the eval but not print the result β handy if you want to do something else with it (the "watch expressions" code does this to get the value of the watch expression but not show it unless it matters). π
In any case, we then return the list of output from eval to the caller, and unwinding restores the former version of $@ in @saved as well (the localization of $saved[0] goes away at the end of this scope).
πΈ Parameters and variables influencing execution of DB::eval() πΈ
DB::eval isn't parameterized in the standard way; this is to keep the debugger's calls to DB::eval() from mucking with @_, among other things. The variables listed below influence DB::eval()'s execution directly.
$evalargβ the thing to actually be eval'ed$traceβ Current state of execution tracing$singleβ Current state of single-stepping$onetimeDumpβ what is to be displayed after the evaluation$onetimeDumpDepthβ how deepdumpit()should go when dumping results
The following variables are altered by DB::eval() during its execution. They are "stacked" via local(), which enables recursive calls to DB::eval(). π¦
@resβ used to capture output from actualeval.$otraceβ saved value of$trace.$osingleβ saved value of$single.$odβ saved value of$^D.$saved[0]β saved value of$@.$\β for output of$@if there is an evaluation error.
β¨ The problem of lexicals β¨
The context of DB::eval() presents us with some problems, ngl. Obviously, we want to be 'sandboxed' away from the debugger's internals when we do the eval, but we need some way to control how punctuation variables and debugger globals are used.
We can't use local, because the code inside DB::eval can see localized variables; and we can't use my either for the same reason. The code in this routine compromises and uses my. π
After this routine is over, we don't have user code executing in the debugger's context, so we can use my freely. Slay. π
π«Ά DEBUGGER INITIALIZATION π«Ά
okay so bestie, the debugger does not just spawn in fully formed. it goes through phases, like a glow-up montage but for your debugging session. π
β¨ BASIC SETUP β¨
First things first: it initializes the environment it wants to run in. That means it turns warnings off during its own compilation (self-care fr), defines the variables it's gonna need later so it doesn't get nagged by warnings, sets itself up to not exit when the program terminates, and defaults to printing return values for the r command. iconic behavior tbh.
π§΅ THREADS SUPPORT π§΅
If we're running under a threaded Perl, and the environment variable PERL5DB_THREADED is set, then we require both threads and threads::shared β that's what unlocks proper threaded debugger control. You can also use -dt to set this. iykyk.
Every new thread gets announced, and the debugger prompt always lets you know about each new thread created. It'll also show you the thread id you're currently running in, right inside the prompt, like this:
[tid] DB<$i>
Where [tid] is an integer thread id and $i is the familiar debugger command prompt. The prompt shows [0] when you're running under threads but not actually inside a thread. And [tid] is consistent with gdb usage β cute, right?
While running under threads, when you set or delete a breakpoint (etc.), that applies to all threads, not just the one you're currently in. And when you're in a currently executing thread, you stay there until it completes. With the current implementation, it is not currently possible to hop from one thread to another. no fast travel, sad. π
The e and E commands are currently fairly minimal β see h e and h E.
π‘ lil history note: threading support was built into the debugger as of Perl version5.8.6and debugger version1.2.8. periodt.
π OPTION PROCESSING π
So the debugger's options are actually spread out over two places: the debugger itself and dumpvar.pl. Some of these are variables to be set, and others are subs to be called with a value. To keep this manageable (because wow), the debugger uses a few data structures to define which options are legal and how they should be processed:
- First, the
@optionsarray defines the names of all the options that are to be accepted. - Second,
optionVarslists the variables that each option uses to save its state. - Third,
%optionActiondefines the subroutine to be called to process each option. - Last, the
%optionRequirenotes modules that must berequired if an option is used.
There are also a number of initialization-related variables that you can set by putting code to set them in a BEGIN block inside the PERL5DB environment variable. These are:
$rlβ readline control XXX needs more explanation$warnLevelβ whether or not debugger takes over warning handling$dieLevelβ whether or not debugger takes over die handling$signalLevelβ whether or not debugger takes over signal handling$preβ preprompt actions (array reference)$postβ postprompt actions (array reference)$pretype$CreateTTYβ whether or not to create a new TTY for this debugger$CommandSetβ which command set to use (defaults to new, documented set)
The default die, warn, and signal handlers are set up. β¨
Next up, we need the pager. We try to grab it from the environment first. If it's not defined there, we go hunting in the Perl Config.pm. If it's not there either, we just default to more. Then we call the pager() function to save the pager name.
Then we set up the command used to access the man pages, the command recall character (! unless otherwise defined), and the shell escape character (! unless otherwise defined). Yes, these do conflict, and neither works in the debugger at the moment. π
After that we set up the gigantic string containing the debugger help. We also set the limit on the number of arguments we'll display during a trace.
πΈ SETTING UP THE DEBUGGER GREETING πΈ
The debugger greeting is basically its little "hi bestie" β it tells the user how many debuggers are running, and whether the current debugger is the primary or a child.
If we're the primary, we just hang onto our pid so we'll have it when (or if) we start a child debugger. If we're a child, we set things up so we'll have a unique greeting and so the parent will give us our own TTY later. π
We save the current contents of the PERLDB_PIDS environment variable because we mess around with it. We also need to hang onto it because we'll need it if we restart.
Child debuggers make a label out of the current PID structure recorded in PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY yet, so the parent will hand them one later via resetterm().
π READING THE RC FILE π
The debugger will read a file of initialization options if one is supplied. If you're running interactively, that file is .perldb; if not, it's perldb.ini.
The debugger does a safety test on the file before reading it. It must be owned either by the current user or root, and it must only be writable by the owner. no sketchy world-writable rc files in this house.
The last thing we do during initialization is figure out which subroutine to use to obtain a new terminal when a new debugger is started. Right now, the debugger only handles X Windows, OS/2, and Mac OS X (darwin).
π RESTART PROCESSING π
This whole section is about the restart command. When the R command is invoked, it tries to capture all of the state it can into environment variables, and then it sets PERLDB_RESTART. When we start executing again, we check whether PERLDB_RESTART is there; if it is, we reload all the information that the R command stuffed into the environment variables.
PERLDB_RESTART - flag only, contains no restart data itself.
PERLDB_HIST - command history, if it's available
PERLDB_ON_LOAD - breakpoints set by the rc file
PERLDB_POSTPONE - subs that have been loaded/not executed, and have actions
PERLDB_VISITED - files that had breakpoints
PERLDB_FILE_... - breakpoints for a file
PERLDB_OPT - active options
PERLDB_INC - the original @INC
PERLDB_PRETYPE - preprompt debugger actions
PERLDB_PRE - preprompt Perl code
PERLDB_POST - post-prompt Perl code
PERLDB_TYPEAHEAD - typeahead captured by readline()
We chug through all these variables and plug the values saved in them back into the appropriate spots in the debugger. π«Ά
π SETTING UP THE TERMINAL π
Now we decide how the debugger is gonna interact with the user. If there's no TTY at all, we set the debugger to run non-stop β because there's literally not going to be anyone there to type commands. π
If there is a TTY, we have to figure out who it belongs to before we can proceed. If this is a slave editor or a graphical debugger (denoted by the first command-line switch being -emacs), we shift this off and set $rl to 0 (XXX ostensibly to do straight reads).
Then we determine what the console should be on the various systems:
- Cygwin β we use
stdininstead of a separate device. - Unix β use
/dev/tty. - Windows or MSDOS β use
con. - MacOS β use
Dev:Console:Perl Debugif this is the MPW version;Dev: Consoleif not.
π note that Mac OS X returnsdarwin, notMacOS. Also note that the debugger doesn't do anything special fordarwin. Maybe it should. π€
- VMS β use
sys$command.
Several other systems don't use a specific console at all. We undef $console for those ones β that's Windows using a slave editor/graphical debugger, NetWare, OS/2 with a slave editor, and Epoc.
And if there's a TTY hanging around from a parent, we use that as the console. slay.
π₯ SOCKET HANDLING π₯
The debugger is capable of opening a socket and carrying out a debugging session over that socket. yes, remote debugging, we love to see it.
If RemotePort was defined in the options, the debugger assumes it should try to start a debugging session on that port. It builds the socket and then tries to connect the input and output filehandles to it.
If no RemotePort was defined, and we want to create a TTY on startup, this is probably a situation where multiple debuggers are running (for example, a backticked command that starts up another debugger). We create a new IN and OUT filehandle, and do the necessary mojo to create a new TTY if we know how and if we can.
To finish up initialization, we show the debugger greeting, and then we call the afterinit() subroutine if there is one.
π SUBROUTINES π
π DB π
This gigantic subroutine is the heart of the debugger. It's called before every single statement, and its job is to figure out if a breakpoint has been reached and stop if so; read commands from the user, parse them, and execute them; and then send execution off to the next statement.
β οΈ note that the order in which the commands are processed is very important. Some commands earlier in the loop will actually alter the$cmdvariable to create other commands to be executed later. This is all highly optimized, but it can be confusing. Check the comments for each$cmd ... && do {}to see what's happening in any given command.
π¦ watchfunction() π¦
watchfunction() is a function that you, the user, can define; it's a function that will be run on each entry to DB::DB. It gets the current package, filename, and line as its parameters.
The watchfunction can do anything it likes β it's executing in the debugger's context, so it has access to all of the debugger's internal data structures and functions. main character energy, honestly. π
watchfunction() can also control the debugger's actions. Any of the following will cause the debugger to return control to the user's program after watchfunction() executes:
- Returning a false value from the
watchfunction()itself. - Altering
$singleto a false value. - Altering
$signalto a false value. - Turning off the
4bit in$trace(this also disables the check forwatchfunction(). This can be done with
$trace &= ~4;
π GETTING READY TO EXECUTE COMMANDS π
The debugger decides to take control if single-step mode is on, the t command was entered, or the user generated a signal. If the program has fallen off the end, we set things up so that entering further commands won't cause trouble, and we say that the program is over. β¨
Special check: if we're in package DB::fake, we've gone through the END block at least once. We set up everything so that we can continue to enter commands and have a valid context to be in.
If the program hasn't finished executing, we scan forward to the next executable line, print that out, build the prompt from the file and line number information, and print that.
If there's an action to be executed for the line we stopped at, we execute it. And if there are any preprompt actions, we execute those as well.
β WHERE ARE WE? β
XXX Relocate this section?
The debugger normally shows the line corresponding to the current line of execution. Sometimes, though, we want to see the next line, or to move elsewhere in the file. That's done via the $incr, $start, and $max variables. π«Ά
$incrβ bestie this one controls how many lines the current line skips forward once a command finishes doing its thing. Set it to-1and it's giving "we are NOT moving, stay right here" energy.$startβ this is the current line, bestie. It's what we consult for stuff like knowing where to move forwards or backwards from when you run an"L"or"-"command. π$maxβ tells the debugger where the last line of the current file is. Most often it's the thing that terminates loops. The end, literally.
β¨ THE COMMAND LOOP β¨
Most of "DB::DB" is actually a command parsing and dispatch loop, no cap. And it comes in two parts:
- The outer part of the loop, starting at the
"CMD"label. This is the one that reads a command and then executes it. π - The inner part of the loop, starting at the
"PIPE"label. This part is wholly contained inside the"CMD"block and only executes a command. It's used to handle commands running inside a pager.
So why have two labels to restart the loop? Because sometimes, it's easier to have a command generate another command and then re-execute the loop to do the new command. This is faster, but perhaps a bit more convoluted. Feral optimization behavior honestly π
The null command
A newline entered by itself means re-execute the last command. We grab the command out of $laststep (where it was recorded previously), and copy it back into $cmd to be executed below. If there wasn't any previous command, we'll do nothing below (no command will match). If there was, we also save it in the command history and fall through to allow the command parsing to pick it up. β― rewind energy fr
COMMAND ALIASES
The debugger can create aliases for commands (these are stored in the %alias hash). Before a command is executed, the command loop looks it up in the alias hash and substitutes the contents of the alias for the command, completely replacing it. Not me replacing your whole command like that π«Ά
MAIN-LINE COMMANDS
All of these commands work up to and after the program being debugged has terminated. π
"q"β quit. Quit the debugger. This entails setting the$fall_off_endflag, so we don't try to execute further, cleaning any restart-related stuff out of the environment, and executing with the last value of$?. bye bestie π"t"β trace. Turn tracing on or off. Inverts the appropriate bit in$trace(q.v.)."S"β list subroutines matching/not matching a pattern. Walks through%sub, checking to see whether or not to print the name."X"β list variables in current package. Since the"V"command actually processes this, just change this to the appropriate"V"command and fall through."V"β list variables. Uses"dumpvar.pl"to dump out the current values for selected variables."x"β evaluate and print an expression. Hands the expression off to"DB::eval", setting it up to print the value via"dumpvar.pl"instead of just printing it directly."m"β print methods. Just uses"DB::methods"to determine what methods are available."f"β switch files."."β return to last-executed line. We set$incrto-1to indicate that the debugger shouldn't move ahead, and then we look up the line in the magical%dblinehash. β¨"-"β back one window. We change$startto be one window back; if we go back past the first line, we set it to be the first line. We ser$incrto put us back at the currently-executing line, and then put a"l $start +"(list one window from$start) in$cmdto be executed later.
PRE-580 COMMANDS VS. NEW COMMANDS: "a, A, b, B, h, l, L, M, o, O, P, v, w, W, <, <<, {, {{"
In Perl 5.8.0, a realignment of the commands was done to fix up a number of problems, most notably that the default case of several commands destroying the user's work in setting watchpoints, actions, etc. That was SO rude of them π We wanted, however, to retain the old commands for those who were used to using them or who preferred them. At this point, we check for the new commands and call "cmd_wrapper" to deal with them instead of processing them in-line.
"y"β List lexicals in higher scope. Uses"PadWalker"to find the lexicals supplied as arguments in a scope above the current one and then displays then using"dumpvar.pl".
COMMANDS NOT WORKING AFTER PROGRAM ENDS
All of the commands below this point don't work after the program being debugged has ended. All of them check to see if the program has ended; this allows the commands to be relocated without worrying about a 'line of demarcation' above which commands can be entered anytime, and below which they can't. π§
"n"β single step, but don't trace down into subs. Done by setting$singleto2, which forces subs to execute straight through when entered (see"DB::sub"). We also save the"n"command in$laststep, so a null command knows what to re-execute."s"β single-step, entering subs. Sets$singleto1, which causes"DB::sub"to continue tracing inside subs. Also saves"s"as$lastcmd."c"β run continuously, setting an optional breakpoint. Most of the code for this command is taken up with locating the optional breakpoint, which is either a subroutine name or a line number. We set the appropriate one-time-break in@dblineand then turn off single-stepping in this and all call levels above this one."r"β return from a subroutine. For"r"to work properly, the debugger has to stop execution again immediately after the return is executed. This is done by forcing single-stepping to be on in the call level above the current one. If we are printing return values when a"r"is executed, set$doretappropriately, and force us out of the command loop."T"β stack trace. Just calls"DB::print_trace"."w"β List window around current line. Just calls"DB::cmd_w"."W"β watch-expression processing. Just calls"DB::cmd_W"."/"β search forward for a string in the source. We take the argument and treat it as a pattern. If it turns out to be a bad one, we return the error we got from trying to"eval"it and exit. If not, we create some code to do the search and"eval"it so it can't mess us up. π₯"?"β search backward for a string in the source. Same as for"/", except the loop runs backwards.$rcβ Recall command. Manages the commands in@hist(which is created if"Term::ReadLine"reports that the terminal supports history). It find the the command required, puts it into$cmd, and redoes the loop to execute it."$sh$sh"β system() command. Calls the DB::system() to handle the command. This keeps the"STDIN"and"STDOUT"from getting messed up."$rc pattern $rc"β Search command history. Another command to manipulate@hist: this one searches it with a pattern. If a command is found, it is placed in$cmdand executed via"redo".$shβ Invoke a shell. Uses"DB::system"to invoke a shell."$sh command"β Force execution of a command in a shell. Like the above, but the command is passed to the shell. Again, we use"DB::system"to avoid problems with"STDIN"and"STDOUT"."H"β display commands in history. Prints the contents of@hist(if any)."man, doc, perldoc"β look up documentation. Just calls runman() to print the appropriate document."p"β print. Builds a"print EXPR"expression in the$cmd; this will get executed at the bottom of the loop."="β define command alias. Manipulates%aliasto add or list command aliases."source"β read commands from a file. Opens a lexical filehandle and stacks it on@cmdfhs;"DB::readline"will pick it up."save"β send current history to a file. Takes the complete history, (not the shrunken version you see with"H"), and saves it to the given filename, so it can be replayed using"source".
Note that all "^(save|source)"'s are commented out with a view to minimise recursion. π
"R"β restart. Restart the debugger session."rerun"β rerun the current session. Return to any given position in the true-history list."|, ||"β pipe output through the pager. For"|", we save"OUT"(the debugger's output filehandle) and"STDOUT"(the program's standard output). For"||", we only save"OUT". We open a pipe to the pager (restoring the output filehandles if this fails). If this is the"|"command, we also set up a"SIGPIPE"handler which will simply set$signal, sending us back into the debugger.
We then trim off the pipe symbols and "redo" the command loop at the "PIPE" label, causing us to evaluate the command in $cmd without reading another.
END OF COMMAND PARSING
Anything left in $cmd at this point is a Perl expression that we want to evaluate. We'll always evaluate in the user's context, and fully qualify any variables we might want to address in the "DB" package. π
POST-COMMAND PROCESSING
After each command, we check to see if the command output was piped anywhere. If so, we go through the necessary code to unhook the pipe and go back to our standard filehandles for input and output. cleanup era β¨
COMMAND LOOP TERMINATION
When commands have finished executing, we come here. If the user closed the input filehandle, we turn on $fall_off_end to emulate a "q" command. We evaluate any post-prompt items. We restore $@, $!, $^E, $,, $/, "$\", and $^W, and return a null list as expected by the Perl interpreter. The interpreter will then execute the next line and then return control to us again. π
sub
"sub" is called whenever a subroutine call happens in the program being debugged. The variable $DB::sub contains the name of the subroutine being called.
The core function of this subroutine is to actually call the sub in the proper context, capturing its output. This of course causes "DB::DB" to get called again, repeating until the subroutine ends and returns control to "DB::sub" again. Once control returns, "DB::sub" figures out whether or not to dump the return value, and returns its captured copy of the return value as its own return value. The value then feeds back into the program being debugged as if "DB::sub" hadn't been there at all. no cap, it's invisible π
"sub" does all the work of printing the subroutine entry and exit messages enabled by setting $frame. It notes what sub the autoloader got called for, and also prints the return value if needed (for the "r" command and if the 16 bit is set in $frame).
It also tracks the subroutine call depth by saving the current setting of $single in the @stack package global; if this exceeds the value in $deep, "sub" automatically turns on printing of the current depth by setting the 4 bit in $single. In any case, it keeps the current setting of stop/don't stop on entry to subs set as it currently is set.
caller() support
If caller() is called from the package "DB", it provides some additional data, in the following order:
$packageβ the package name the sub was in$filenameβ the filename it was defined in$lineβ the line number it was defined on$subroutine
the name of the subroutine, or (eval) if it's an eval(). β¨
$hasargsβ1if it's got arguments,0if it's giving nothing. π$wantarrayβ1if we're in array context,0if it's scalar context. periodt.$evaltextβ the"eval"() text, if there is any (undefined for"eval BLOCK", so don't come for her). π$is_requireβ this frame was created by a"use"or"require"statement.$hintsβ pragma information; subject to change between versions, so don't get attached bestie. π$bitmaskβ pragma information; also subject to change between versions. same energy.@DB::argsβ the arguments with which the subroutine was invoked. π«Ά
π EXTENDED COMMAND HANDLING AND THE COMMAND API π
So in Perl 5.8.0 there was a whole major realignment of the commands and what they do β a glow-up, honestly. Most of the changes were to systematize the command structure and to eliminate commands that just threw away user input without checking it first. rude behavior, honestly, glad it's gone. π
The following sections describe the code added to make it easy to support multiple command sets with conflicting command names. This section is a start at unifying all command processing to make it simpler to develop commands. iykyk.
ngl, note this: all the cmd_[a-zA-Z] subroutines require the command name, a line number, and $dbline (the current line) as arguments. no exceptions, that's the vibe check.
Support functions in this section which have multiple modes of failure "die" on error; the rest simply return a false value.
The user-interface functions (all of the "cmd_*" functions) just output error messages. that's it, that's the job. π
%set
The %set hash defines the mapping from command letter to subroutine name suffix. iconic.
%set is a two-level hash, indexed by set name and then by command name. Note that trying to set the CommandSet to "foobar" simply results in the 5.8.0 command set being used, since there's no top-level entry for "foobar". so like, it just silently falls back, no cap. π¦
cmd_wrapper() (API)
cmd_wrapper() allows the debugger to switch command sets depending on the value of the "CommandSet" option.
It tries to look up the command in the %set package-level lexical (which means external entities can't fiddle with it, gatekeeping fr) and create the name of the sub to call based on the value found in the hash (if it's there). All of the commands to be handled in a set have to be added to %set; if they aren't found, the 5.8.0 equivalent is called (if there is one).
This code uses symbolic references. β
"cmd_a" (command)
The "a" command handles pre-execution actions. These are associated with a particular line, so they're stored in %dbline. We default to the current line if none is specified. slay.
"cmd_A" (command)
Delete actions. Similar to above, except the delete code is in a separate subroutine, "delete_action". separating concerns, we love to see it. β¨
"delete_action" (API)
"delete_action" accepts either a line number or "undef". If a line number is specified, we check for the line being executable (if it's not, it couldn't have had an action β no thoughts, no action π). If it is, we just take the action off (this will get any kind of an action, including breakpoints).
"cmd_b" (command)
Set breakpoints. Since breakpoints can be set in so many places, in so many ways, conditionally or not, the breakpoint code is kind of complex. Mostly, we try to parse the command type, and then shuttle it off to an appropriate subroutine to actually do the work of setting the breakpoint in the right place. multitasking queen. π
"break_on_load" (API)
We want to break when this file is loaded. Mark this file in the %break_on_load hash, and note that it has a breakpoint in %had_breakpoints. noted, logged, done. π
"report_break_on_load" (API)
Gives us an array of filenames that are set to break on load. Note that only files with break-on-load are in here, so simply showing the keys suffices. easy. πΈ
"cmd_b_load" (command)
We take the file passed in and try to find it in %INC (which maps modules to files they came from). We mark those files for break-on-load via "break_on_load" and then report that it was done. π
$filename_error (API package global)
Several of the functions we need to implement in the API need to work both on the current file and on other files. We don't want to duplicate code (copy-paste is NOT the vibe), so $filename_error is used to contain the name of the file that's being worked on (if it's not the current one).
We can now build functions in pairs: the basic function works on the current file, and uses $filename_error as part of its error message. Since this is initialized to "", no filename will appear when we are working on the current file.
The second function is a wrapper which does the following:
- Localizes
$filename_errorand sets it to the name of the file to be processed. - Localizes the
*dblineglob and reassigns it to point to the file we want to process. - Calls the first function.
The first function works on the current file (i.e., the one we changed to), and prints $filename_error in the error message (the name of the other file) if it needs to. When the functions return, *dbline is restored to point to the actual current file (the one we're executing in) and $filename_error is restored to "". This restores everything to the way it was before the second function was called at all. we love a clean restore. β¨
See the comments in "breakable_line" and "breakable_line_in_file" for more details.
breakable_line(from, to) (API)
The subroutine decides whether or not a line in the current file is breakable. It walks through @dbline within the range of lines specified, looking for the first line that is breakable. little stroll through the code, cute. πΆββοΈ
If $to is greater than $from, the search moves forwards, finding the first line after $to that's breakable, if there is one.
If $from is greater than $to, the search goes backwards, finding the first line before $to that's breakable, if there is one.
breakable_line_in_filename(file, from, to) (API)
Like "breakable_line", but look in another file. plot twist. π
break_on_line(lineno, [condition]) (API)
Adds a breakpoint with the specified condition (or 1 if no condition was specified) to the specified line. Dies if it can't. no chill. π
cmd_b_line(line, [condition]) (command)
Wrapper for "break_on_line". Prints the failure message if it doesn't work.
break_on_filename_line(file, line, [condition]) (API)
Switches to the file specified and then calls "break_on_line" to set the breakpoint.
break_on_filename_line_range(file, from, to, [condition]) (API)
Switch to another file, search the range of lines specified for an executable one, and put a breakpoint on the first one you find. first come, first break. π₯
subroutine_filename_lines(subname, [condition]) (API)
Search for a subroutine within a given file. The condition is ignored (not today, condition). Uses "find_sub" to locate the desired subroutine.
break_subroutine(subname) (API)
Places a break on the first line possible in the specified subroutine. Uses "subroutine_filename_lines" to find the subroutine, and "break_on_filename_line_range" to place the break. teamwork makes the dream work. π«Ά
cmd_b_sub(subname, [condition]) (command)
We take the incoming subroutine name and fully-qualify it as best we can. the glow-up process:
- If it's already fully-qualified, leave it alone. respect.
- Try putting it in the current package.
- If it's not there, try putting it in
CORE::GLOBALif it exists there. - If it starts with
'::', put it in'main::'.
After all this cleanup, we call "break_subroutine" to try to set the breakpoint.
"cmd_B" - delete breakpoint(s) (command)
The command mostly parses the command line and tries to turn the argument into a line spec. If it can't, it uses the current line. It then calls "delete_breakpoint" to actually do the work.
If "*" is specified, "cmd_B" calls "delete_breakpoint" with no arguments, thereby deleting all the breakpoints. scorched earth, honestly. π₯
delete_breakpoint([line]) (API)
This actually does the work of deleting either a single breakpoint, or all of them. the main character of deletion.
For a single line, we look for it in @dbline. If it's nonbreakable, we just drop out with a message saying so. If it is, we remove the condition part of the 'condition\0action' that says there's a breakpoint here. If, after we've done that, there's nothing left, we delete the corresponding line in %dbline to signal that no action needs to be taken for this line.
For all breakpoints, we iterate through the keys of %had_breakpoints, which lists all currently-loaded files which have breakpoints. We then look at each line in each of these files, temporarily switching the %dbline and @dbline structures to point to the files in question, and do what we did in the single line case: delete the condition in @dbline, and delete the key in %dbline if nothing's left.
We then wholesale delete %postponed, %postponed_file, and %break_on_load, because these structures contain breakpoints for files and code that haven't been loaded yet. We can just kill these off because there are no magical debugger structures associated with them. bye besties ππ
cmd_stop (command)
This is meant to be part of the new command API, but it isn't called or used anywhere else in the debugger. XXX It is probably meant for use in development of new commands. an unfinished icon, truly. π
"cmd_e" - threads
Display the current thread id:
e
This could be how (when implemented) to send commands to this thread id (e cmd) or that thread id (e tid cmd). someday bestie, someday. π¦
"cmd_E" - list of thread ids
Display the list of available thread ids:
E
This could be used (when implemented) to send commands to all threads (E cmd).
"cmd_h" - help command (command)
Does the work of either
- Showing all the debugger help
- Showing help for a specific command
so helpful of her, honestly. πΈ
"cmd_i" - inheritance display
Display the (nested) parentage of the module or object given. family tree reveal. π
"cmd_l" - list lines (command)
Most of the command is taken up with transforming all the different line specification syntaxes into 'start-stop'. After that is done, the command runs a loop over @dbline for the specified range of lines. It handles the printing of each line and any markers ("==>" for current line, "b" for break on this line, "a" for action on this line, ":" for this line breakable). the little markers are so cuuute, it's giving wayfinding. π
We save the last line listed in the $start global for further listing later.
"cmd_L" - list breakpoints, actions, and watch expressions (command)
To list breakpoints, the command has to look determine where all of them are first. It starts a %had_breakpoints, which tells us what all files have breakpoints and/or actions. For each file, we switch the *dbline glob (the magic source and breakpoint data structures) to the file, and then look through %dbline for lines with breakpoints and/or actions, listing them out. We look through %postponed not-yet-compiled subroutines that have breakpoints, and through %postponed_file for not-yet-"require"'d files that have breakpoints.
Watchpoints are simpler: we just list the entries in @to_watch. β¨
"cmd_M" - list modules (command)
Just call "list_modules". short and sweet. π
"cmd_o" - options (command)
- If it's just
oall by itself, no vibes attached, we show off the current settings viadump_option. But if there's a nonblank value chilling after it, that goes straight toparse_optionsfor processing. β¨ cmd_Oβ nonexistent in 5.8.x (command)
This one's whole job is gently telling the user that the O command got a glow-up and a new name. rip to the O command's past life π
cmd_vβ view window (command)
Uses the $preview variable that got set way back in the second BEGIN block (q.v. bestie) to scoot back a few lines and show the selected line in context, the way it was meant to be seen. Then it hands off to cmd_l to do the actual listing once it's figured out the range of lines to request. π
cmd_wβ add a watch expression (command)
The 5.8 version of this command adds a watch expression if you actually give it one. If you enter it with no operands at all? It justβ¦ does nothing. Living its truth. π
So we extract the expression, save it, evaluate it in the user's context, and save the value. We're gonna re-evaluate it every single time the debugger passes a line, and we stop (see the code at the top of the command loop, iykyk) if the value of any of the expressions changes. π
cmd_Wβ delete watch expressions (command)
This command accepts either a watch expression to be removed from the watch expression list, or * to delete them all. All of them. Periodt.
If * is specified, we simply empty the watch expression list and the watch expression value list. We also turn off the bit that says we've got watch expressions β that flag is so over.
If an expression (or partial expression) is specified, we pattern-match through the expressions and remove the ones that match. We also discard the corresponding values, no hoarding. And if no watch expressions are left? We turn off the watching-expressions bit. Clean break. π
π SUPPORT ROUTINES π
These are the general support routines that get used all over the place throughout the debugger. The backbone. The glue. The real ones. π«Ά
save
save() saves the user's versions of globals that would mess us up into @saved, and installs the versions we like better. Think of it as curating the vibe. β¨
print_lineinfo β show where we are now
print_lineinfo prints whatever it is that it is handed; it prints it to the $LINEINFO filehandle instead of just printing it to STDOUT. Why? Because that way we can feed line information to a slave editor without messing up the debugger output. Considerate. We love that. π
postponed_sub
Handles setting postponed breakpoints in subroutines once they're compiled. So for breakpoints, we use DB::find_sub to locate the source file and line range for the subroutine, then mark the file as having a breakpoint, temporarily switch the *dbline glob over to the source file, and then search the given range of lines to find a breakable line. If we find one, we set the breakpoint on it, deleting the breakpoint from %postponed. Bye bestie, you served your purpose. π¦
postponed
Called after each required file is compiled, but before it is executed; also called if the name of a just-compiled subroutine is a key of %postponed. Propagates saved breakpoints (from b compile, b load, etc.) into the just-compiled code. The breakpoints finally found their forever home. π
If this is a require'd file, the incoming parameter is the glob *{"_<$filename"}, with $filename the name of the require'd file.
If it's a subroutine, the incoming parameter is the subroutine name.
dumpit
dumpit is the debugger's wrapper around dumpvar.pl. Iconic crossover event. π₯
It gets a filehandle (to which dumpvar.pl's output will be directed) and a reference to a variable (the thing to be dumped) as its input.
The incoming filehandle is selected for output (dumpvar.pl is printing to the currently-selected filehandle, thank you very much π
). The current values of the package globals $single and $trace are backed up in lexicals, and they are turned off (this keeps the debugger from trying to single-step through dumpvar.pl (I think.)). $frame is localized to preserve its current value and it is set to zero to prevent entry/exit messages from printing, and $doret is localized as well and set to -2 to prevent return values from being shown.
dumpit() then checks to see if it needs to load dumpvar.pl and tries to load it (note: if you have a dumpvar.pl ahead of the installed version in @INC, yours will be used instead. Possible security problem?).
π¨ heads up bestie β that @INC thing up there is a real note in the docs, a possible security problem, not a vibe. eyes open.
It then checks to see if the subroutine main::dumpValue is now defined (it should have been defined by dumpvar.pl). If it has, dumpit() localizes the globals necessary for things to be sane when main::dumpValue() is called, and picks up the variable to be dumped from the parameter list.
It checks the package global %options to see if there's a dumpDepth specified. If not, -1 is assumed; if so, the supplied value gets passed on to dumpvar.pl. This tells dumpvar.pl where to leave off when dumping a structure: -1 means dump everything. No holding back. β¨
dumpValue() is then called if possible; if not, dumpit() just prints a warning. π
In either case, $single, $trace, $frame, and $doret are restored and we then return to the caller. Everything put back where it belongs, the way we found it. π«Ά
print_trace
print_trace's job is to print a stack trace. It does this via the dump_trace routine, which actually does all the ferreting-out of the stack trace data. print_trace takes care of formatting it nicely and printing it to the proper filehandle. One does the digging, one does the styling. π
Parameters:
- The filehandle to print to.
- How many frames to skip before starting trace.
- How many frames to print.
- A flag: if true, print a short trace without filenames, line numbers, or arguments
The original comment below seems to be noting that the traceback may not be correct if this routine is called in a tied method. noted, lowkey a caveat, keep it in mind bestie π
dump_trace(skip[,count])
Actually collect the traceback information available via caller(). It does some filtering and cleanup of the data, but mostly it just collects it to make print_trace()'s job easier. Teamwork honestly. π«Ά
skip defines the number of stack frames to be skipped, working backwards from the most current. count determines the total number of frames to be returned; all of them (well, the first 10^9) are returned if count is omitted. yes, 10^9. that's the actual number. iconic.
This routine returns a list of hashes, from most-recent to least-recent stack frame. Each has the following keys and values:
contextβ.(null),$(scalar), or@(array)subβ subroutine name, orevalinformationargsβ undef, or a reference to an array of argumentsfileβ the file in which this item was defined (if any)lineβ the line on which it was defined
action()
action() takes input provided as the argument to an add-action command, either pre- or post-, and makes sure it's a complete command. It doesn't do any fancy parsing; it just keeps reading input until it gets a string without a trailing backslash. Simple. Unbothered. Thriving. β¨
unbalanced
This routine mostly just packages up a regular expression to be used to check that the thing it's being matched against has properly-matched curly braces. Balance check, bestie. π
Of note is the definition of the $balanced_brace_re global via ||=, which speeds things up by only creating the qr//'ed expression once; if it's already defined, we don't try to define it again. A speed hack. We love a little optimization moment. π₯
gets()
gets() is a primitive (very primitive) routine to read continuations. It was devised for reading continuations for actions. it just reads more input with readline() and returns it. Short king. No notes. π
DB::system() β handle calls to <system()> without messing up the debugger
The system() function assumes that it can just go ahead and use STDIN and STDOUT, but under the debugger, we want it to use the debugger's input and outout filehandles. (Yes, the docs say "outout." We are not touching that typo. It's part of the lore now. π)
DB::system() socks away the program's STDIN and STDOUT, and then substitutes the debugger's IN and OUT filehandles for them. It does the system() call, and then puts everything back again. Swap, run, restore. The full routine. π
πΈ TTY MANAGEMENT πΈ
The subs here do some of the terminal management for multiple debuggers. Terminal girlies, this one's for you. β¨
setterm
Top-level function called when we want to set up a new terminal for use by the debugger.
If the noTTY debugger option was set, we'll either use the terminal supplied (the value of the noTTY option), or we'll use Term::Rendezvous to find one. If we're a forked debugger, we call resetterm to try to get a whole new terminal if we can. Manifesting a fresh terminal. π¦
In either case, we set up the terminal next. If the ReadLine option was true, we'll get a Term::ReadLine object for the current terminal and save the appropriate attributes. We then
β¨ GET_FORK_TTY EXAMPLE FUNCTIONS β¨
ok so here's the thing bestie: when the process we're debugging forks, or when it runs a command through system() that spins up a whole new debugger, we need fresh IN and OUT filehandles for that new debugger. if we don't? the two processes literally start beefing over the terminal and you can never quite be sure who's gonna get the input you're typing. chaos. not the cute kind. π
get_fork_TTY is a glob-aliased function that calls the real function β the one actually tasked with doing all the necessary operating system mojo to grab a new TTY (and probably another window) and then point the new debugger at it to read and write there.
the debugger ships get_fork_TTY functions that work for X Windows, OS/2, and Mac OS X. other systems are not supported. and honestly? you're encouraged to write get_fork_TTY functions that work for your platform and contribute them. main character energy, go off π«Ά
xterm_get_fork_TTYβ this one provides theget_fork_TTYfunction for X windows. if a program running under the debugger forks, a new<xterm>window gets opened and the subsidiary debugger gets directed there.
the open() call is of particular note here, and by "of particular note" I mean look at this lil trick π we have the new xterm we're spawning route file number 3 to STDOUT, and then execute the tty command (which prints the device name of the TTY we'll want to use for input and output to STDOUT, then sleep for a very long time, routing this output to file number 3. this way we can simply read from the <XT> filehandle (which is STDOUT from the commands we ran) to get the TTY we want to use.
only works if xterm is in your path and $ENV{DISPLAY}, etc. are properly set up. no setup, no window, no vibes. πΈ
os2_get_fork_TTYβ XXX It behooves an OS/2 expert to write the necessary documentation for this! (not me writing it, not you reading it, an OS/2 expert. come through please π)macosx_get_fork_TTYβ the Mac OS X version uses AppleScript to tell Terminal.app to create a new window. slay π
create_IN_OUT($flags)
creates a new pair of filehandles pointing to a new TTY. and if that's impossible? we try to diagnose why. like a little detective π΅οΈββοΈ
the flags are:
1β Don't know how to create a new TTY.2β Debugger has forked, but we can't get a new TTY.4β standard debugger startup is happening.
"resetterm"
handles rejiggering the prompt when we've forked off a new debugger. β¨
if the new debugger happened because of a system() that invoked a program under the debugger, the arrow between the old pid and the new one in the prompt has two dashes instead of one. noted.
we take the current list of pids and add this one to the end. if there isn't any list yet, we make one up out of the initial pid associated with the terminal and our new pid, sticking an arrow (either one-dashed or two-dashed) in between them. cute, right? π
if CreateTTY is off, or resetterm was called with no arguments, we don't try to create a new IN and OUT filehandle. otherwise, we go ahead and try to do that.
"readline"
three-step vibe check, in order:
- first, we handle stuff in the typeahead buffer. if there is any, we shift off the next line, print a message saying we got it, add it to the terminal history (if possible), and return it. π
- if there's nothing in the typeahead buffer, check the command filehandle stack. if there are any filehandles there, read from the last one, and return the line if we got one. if not, we pop the filehandle off and close it, and try the next one up the stack.
- if we've emptied the filehandle stack, we check to see if we've got a socket open, and we read that and return it if we do. if we don't, we just call the core
readline()and return its value.
π OPTIONS SUPPORT ROUTINES π
these routines handle listing and setting option values. the infrastructure, the backbone, the girls that get it. π
"dump_option" - list the current value of an option setting
this routine uses option_val to look up the value for an option. it cleans up escaped single-quotes and then displays the option and its value. clean, simple, iconic.
"option_val" - find the current value of an option
this can't just be a simple hash lookup because of the indirect way that the option values are stored. some are retrieved by calling a subroutine, some are just variables. it's giving β¨ layers β¨
you must supply a default value to be used in case the option isn't set.
"parse_options"
handles the parsing and execution of option setting/displaying commands.
an option entered by itself is assumed to be set me to 1 (the default value) if the option is a boolean one. if not, the user is prompted to enter a valid value or to query the current value (via option? ).
if option=value is entered, we try to extract a quoted string from the value (if it is quoted). if it's not, we just use the whole value as-is.
we load any modules required to service this option, and then we set it: if it just gets stuck in a variable, we do that; if there's a subroutine to handle setting the option, we call that. whichever one applies, no cap.
finally, if we're running in interactive mode, we display the effect of the user's command back to the terminal β skipping this if we're setting things during initialization. π¦
π RESTART SUPPORT π
these routines are used to store (and restore) lists of items in environment variables during a restart.
set_list
set_list packages up items to be stored in a set of environment variables (VAR_n, containing the number of items, and VAR_0, VAR_1, etc., containing the values). values outside the standard ASCII charset are stored by encoding them as hexadecimal values. π
get_list
reverse the set_list operation: grab VAR_n to see how many we should be getting back, and then pull VAR_0, VAR_1. etc. back out.
(and yes that's a period after VAR_1, not a comma. we're keeping it exactly as it lives in the source of truth. πΈ)
π₯ MISCELLANEOUS SIGNAL AND I/O MANAGEMENT π₯
catch()
the catch() subroutine is the essence of fast and low-impact. we simply set an already-existing global scalar variable to a constant value. this avoids allocating any memory possibly in the middle of something that will get all confused if we do, particularly under unsafe signals. no allocation, no drama, no confused state. periodt. π
warn()
warn emits a warning, by joining together its arguments and printing them, with a couple of fillips.
if the composited message doesn't end with a newline, we automatically add $! and a newline to the end of the message. the subroutine expects $OUT to be set to the filehandle to be used to output warnings; it makes no assumptions about what filehandles are available. independent queen behavior π
π INITIALIZATION TTY SUPPORT π
"reset_IN_OUT"
this routine handles restoring the debugger's input and output filehandles after we've tried and failed to move them elsewhere. in addition, it assigns the debugger's output filehandle to $LINEINFO if it was already open there.
β OPTION SUPPORT ROUTINES β
the following routines are used to process some of the more complicated debugger options. yes, this heading is almost the same as the one a few screens up. no, they are not the same heading. read the letters. π§
"TTY"
sets the input and output filehandles to the specified files or pipes. if the terminal supports switching, we go ahead and do it. if not, and there's already a terminal in place, we save the information to take effect on restart.
if there's no terminal yet (for instance, during debugger initialization), we go ahead and set $console and $tty to the file indicated.
"noTTY"
sets the $notty global, controlling whether or not the debugger tries to get a terminal to read from. if called after a terminal is already in place, we save the value to use it if we're restarted.
"ReadLine"
sets the $rl option variable. if 0, we use Term::ReadLine::Stub (essentially, no readline processing on this terminal). otherwise, we use Term::ReadLine. can't be changed after a terminal's in place; we save the value in case a restart is done so we can change it then.
"RemotePort"
sets the port that the debugger will try to connect to when starting up. if the terminal's already been set up, we can't do it, but we remember the setting in case the user does a restart.
"tkRunning"
checks with the terminal to see if Tk is running, and returns true or false. returns false if the current terminal doesn't support readline.
"NonStop"
sets nonstop mode. if a terminal's already been set up, it's too late; the debugger remembers the setting in case you restart, though. π
"pager"
set up the $pager variable. adds a pipe to the front unless there's one there already.
"shellBang"
sets the shell escape command, and generates a printable copy to be used in the help.
"ornaments"
if the terminal has its own ornaments, fetch them. otherwise accept whatever was passed as the argument. (this means you can't override the terminal's ornaments. the terminal said what it said. π)
"recallCommand"
sets the recall command, and builds a printable version which will appear in the help text.
"LineInfo" - where the line number information goes
called with no arguments, returns the file or pipe that line info should go to.
called with an argument (a file or a pipe), it opens that onto the LINEINFO filehandle, unbuffers the filehandle, and then returns the file or pipe again to the caller.
πΈ COMMAND SUPPORT ROUTINES πΈ
these subroutines provide functionality for various commands.
"list_modules"
for the M command: list modules loaded and their versions. essentially just runs through the keys in %INC, picks each package's $VERSION variable, gets the file name, and formats the information for output. a lil inventory moment πβ¨
sethelp()
sets up the monster string used to format and print the help. and when we say monster we mean monster. π
HELP MESSAGE FORMAT
the help message is a peculiar format unto itself; it mixes "pod" ornaments ("" "") with tabs to come up with a format that's fairly easy to parse and portable, but which still allows the help to be a little nicer than just plain text.
essentially, you define the command name (usually marked up with "" and ""), followed by a tab, and then the descriptive text, ending in a newline. the descriptive text can also be marked up in the same way. if you need to continue the descriptive text to another line, start that line with just tabs and then enter the marked-up text.
β οΈ if you are modifying the help text, be careful. the help-string parser is not very sophisticated, and if you don't follow these rules it will mangle the help beyond hope until you fix the string. like, genuinely beyond hope. don't test it. π
print_help()
most of what print_help does is just text formatting. it finds the B and I ornaments, cleans them off, and substitutes the proper terminal control characters to simulate them (courtesy of Term::ReadLine::TermCap). π
"fix_less"
this routine does a lot of gyrations to be sure that the pager is less. it checks for less masquerading as more and records the result in $ENV{LESS} so we don't have to go through doing the stats again. it's giving detective work in service of your scrolling experience π΅οΈββοΈβ¨
π DIE AND WARN MANAGEMENT π
okay bestie, this is the part where the debugger handles all the dying and the warning, and honestly it's giving crisis management main character energy. buckle up π«Ά
πΈ diesignal
diesignal is a just-drop-dead die handler. like, literally no survival instincts whatsoever. It's most useful when you're trying to debug a debugger problem (yes, that's real, yes it's as cursed as it sounds π« ).
It does its best to report the error that occurred, and then forces the program, the debugger, and everything to die. that's it. that's the whole vibe. π
β¨ dbwarn
The debugger's own default $SIG{__WARN__} handler. We load Carp so we can get a stack trace, and then we output the warning message through DB::dbwarn(). slay, warnings, but make them traceable π
π¦ dbdie
The debugger's own $SIG{__DIE__} handler. Handles providing a stack trace by loading Carp and calling Carp::longmess() to get it.
We turn off single stepping and tracing during the call to Carp::longmess so we're not sitting there debugging it, bestie β we just want to use it. not everything is the main event π
So like, the dieLevel rules, listen up:
- If
dieLevelis zero, we let the program being debugged handle the exceptions. - If it's 1, you get backtraces for any exception.
- If it's 2, the debugger takes over all exception handling, printing a backtrace and displaying the exception via its
dbwarn()routine.
π warnLevel()
Set the $DB::warnLevel variable that stores the value of the warnLevel option.
Calling warnLevel() with a positive value results in the debugger taking over all warning handlers. Setting warnLevel to zero leaves any warning handlers set up by the program being debugged in place. your warnings, your rules π«Ά
β dieLevel
Similar to warnLevel. Non-zero values for dieLevel result in the DB::dbdie() function overriding any other die() handler. Setting it to zero lets you use your own die() handler. iconic, honestly. let the girl cook π₯
πΈ signalLevel
Number three in a series (a trilogy, a saga, a whole cinematic universe β¨): set signalLevel to zero to keep your own signal handler for SIGSEGV and/or SIGBUS. Otherwise, the debugger takes over and handles them with DB::diesignal().
π§ SUBROUTINE DECODING SUPPORT π§
These subroutines are used during the x and X commands to try to produce as much information as possible about a code reference. They use Devel::Peek to try to find the glob in which this code reference lives (if it does) β and that's what allows us to actually code references which correspond to named subroutines (including those aliased via glob assignment). it's giving detective work ππ
π CvGV_name()
Wrapper for CvGV_name_or_bust; tries to get the name of a reference via that routine. If this fails, return the reference again (when the reference is stringified, it'll come out as SOMETHING(0x...)). so you get something, even if it's not a name. no cap π«
π CvGV_name_or_bust coderef
Calls Devel::Peek to try to find the glob the ref lives in; returns undef if Devel::Peek can't be loaded, or if Devel::Peek::CvGV can't find a glob for this ref.
Returns package::glob name if the code ref is found in a glob. periodt. π
πΈ find_sub
A utility routine used in various places; finds the file where a subroutine was defined, and returns that filename and a line-number range.
Tries to use @sub first. If it can't find it there, it tries building a reference to the subroutine and uses CvGV_name_or_bust to locate it, loading it into @sub as a side effect (XXX I think). If it can't find it this way, it brute-force searches %sub, checking for identical references. when in doubt, brute force, bestie πͺ
π¦ methods
A subroutine that uses the utility function methods_via to find all the methods in the class corresponding to the current reference and in UNIVERSAL. collecting them all like pokΓ©mon β¨
π methods_via($class, $prefix, $crawl_upward)
methods_via does the work of crawling up the @ISA tree and reporting all the parent class methods.
$classis the name of the next class to try.$prefixis the message prefix, which gets built up as we go up the@ISAtree to show parentage.$crawl_upwardis 1 if we should try to go higher in the@ISAtree, 0 if we should stop.
basically climbing the family tree π§βοΈπ³
π setman β figure out which command to use to show documentation
Just checks the contents of $^O and sets the $doccmd global accordingly. short, sweet, does the job π
π runman β run the appropriate command to show documentation
Accepts a man page name; runs the appropriate command to display it (set up during debugger initialization). Uses DB::system to avoid mucking up the program's STDIN and STDOUT.
don't touch my filehandles, bestie π€ careful with the STDIN and STDOUT β that's why we route through DB::system.
π DEBUGGER INITIALIZATION β THE SECOND BEGIN BLOCK π
Because of the way the debugger interface to the Perl core is designed, any debugger package globals that DB::sub() requires have to be defined before any subroutines can be called. These are defined in the second BEGIN block.
This block sets things up so that (basically) the world is sane before the debugger starts executing πβ¨. We set up various variables that the debugger has to have set up before the Perl core starts running:
- The debugger's own filehandles (copies of
STDandSTDOUTfor now). π - Characters for shell escapes, the recall command, and the history command.
- The maximum recursion depth.
- The size of a
wcommand's window. - The before-this-line context to be printed in a
v(view a window around this line) command. π - The fact that we're not in a sub at all right now.
- The default
SIGINThandler for the debugger. - The appropriate value of the flag in
$^Dthat says the debugger is running. - The current debugger recursion level.
- The list of postponed items and the
$singlestack (XXX define this). - That we want no return values and no subroutine entry/exit trace.
like, it's a whole checklist. it's a pre-game routine. get ready with me πβ¨
π¦ READLINE SUPPORT β COMPLETION FUNCTION π¦
β¨ db_complete
readline support β adds command completion to basic readline. yes bestie, tab completion, the most beloved feature in all of computing, fr fr π
Returns a list of possible completions to readline when invoked. readline will print the longest common substring following the text already entered.
If there is only a single possible completion, readline will use it in full. π
This code uses map and grep heavily to create lists of possible completion. Think LISP in this section. that's the vibe check, it's very functional up in here π
π b postpone|compile
- Find all the subroutines that might match in this package
- Add
postpone,load, andcompileas possibles (we may be completing the keyword itself) - Include all the rest of the subs that are known
grepout the ones that match the text we have so far- Return this as the list of possible completions
πΈ b load
Get all the possible files from @INC as it currently stands and select the ones that match the text so far.
π V (list variable) and m (list modules)
There are two entry points for these commands:
π Unqualified package names
Get the top-level packages and grab everything that matches the text so far. For each match, recursively complete the partial packages to get all possible matching packages. Return this sorted list.
π Qualified package names
Take a partially-qualified package and find all subpackages for it by getting all the subpackages for the package so far, matching all the subpackages against the text, and discarding all of them which start with 'main::'. Return this list.
π¦ f β switch files
Here, we want to get a fully-qualified filename for the f command. Possibilities are:
- The original source file itself
- A file from
@INC - An
eval(the debugger gets a(eval N)fake file for eacheval).
Under the debugger, source files are represented as _</fullpath/to/file (evals are _<(eval NNN)) keys in %main::. We pull all of these out of %main::, add the initial source file, and extract the ones that match the completion text so far. little scavenger hunt πβ¨
β Subroutine name completion
We look through all of the defined subs (the keys of %sub) and return both all the possible matches to the subroutine name plus all the matches qualified to the current package.
π Scalar, array, and hash completion: partially qualified package
Much like the above, except we have to do a little more cleanup:
- Determine the package that the symbol is in. Put it in
"::"(effectively"main::") if no package is specified. - Figure out the prefix vs. what needs completing.
- Look through all the symbols in the package.
grepout all the possible hashes/arrays/scalars, and thengrepthe possible matches out of those.mapthe prefix onto all the possibilities. - If there's only one hit, and it's a package qualifier, and it's not equal to the initial text, re-complete it using the symbol we actually found.
π
Symbol completion: current package or package main.
- If it's
main, deletemainto just get"::"leading. - We set the prefix to the item's sigil, and trim off the sigil to get the text to be completed.
- If the package is
"::"(main), create an empty list; if it's something else, create a list of all the packages known. Append whichever list to a list of all the possible symbols in the current package.grepout the matches to the text entered so far, thenmapthe prefix back onto the symbols. - If there's only one hit, it's a package qualifier, and it's not equal to the initial text, recomplete using this symbol.
π Options
We use option_val() to look up the current value of the option. If there's only a single value, we complete the command in such a way that it is a complete command for setting the option in question. If there are multiple possible values, we generate a command consisting of the option plus a trailing question mark, which, if executed, will list the current value of the option.
so either you get the full answer, or you get a ? and a promise to tell you later πβ¨
πΈ Filename completion
For entering filenames. We simply call readline's filename_list() method with the completion text to get the possible completions. easy, breezy, beautiful π«Ά
π MISCELLANEOUS SUPPORT FUNCTIONS π
okay so these are the functions that honestly possibly ought to be somewhere else β like they live here but the vibes are "someone else's problem". no cap, that's literally the official description. π
end_report
just... says we're done. that's it. that's the whole function. it announces completion and we move on. iconic minimalism honestly. β¨
clean_ENV
if we've got $ini_pids kicking around, we save it in the environment. if we don't, we remove it from the environment. bestie, this one's the cleanup crew for the "R" (restart) command. π§Ή
rerun
Rerun the current session β and you can aim it wherever:
rerun current position
rerun 4 command number 4
rerun -4 current command minus 4 (go back 4 steps)
Whether this always makes sense in the current context? unknowable, fr fr. it's partly left as a useful exersize for the reader π. This sub returns the appropriate arguments to rerun the current session.
restart
restarting the debugger is a complex operation that happens in several phases β it's giving main character energy but in like, a multi-act play way. π
First, we try to reconstruct the command line that was used to invoke Perl and the debugger.
After the command line has been reconstructed, next step: save the debugger's status into environment variables. The DB::set_list routine does the aggregate variables (both hashes and arrays, she contains multitudes); scalars just get popped into environment variables directly. π
The most complex part of this whole situation is saving all of the breakpoints. They can live in an awful lot of places, and we have to go through all of them, find the breakpoints, and then save them in the appropriate environment variable via DB::set_list. every single one. no skipping. π€
After all the debugger status has been saved, we take the command we built up and then return it, so we can exec() it. The debugger will spot the PERLDB_RESTART environment variable and realize it needs to reload its state from the environment. periodt. π«Ά
πΈ END PROCESSING - THE "END" BLOCK πΈ
Come here at the very end of processing. We want to go into a loop where we let the user enter commands and interact with the debugger, but we do not want anything else to execute. like, we're here, we're chatting, but nothing else is running, okay babe?
First we set the $finished variable, so that some commands that shouldn't be run after the end of program quit working. (yes, some commands get grounded. they knew what they did. π«)
Then we figure out whether we're truly done β as in, the user entered a "q" command, or we finished execution while running nonstop. If we aren't done, we set $single to 1 (causing the debugger to get control again).
Then we call DB::fake::at_exit(), which returns the "Use 'q' to quit ..." message and returns control to the debugger. Repeat. π Repeat. π Repeat.
When the user finally enters a "q" command, $fall_off_end is set to 1 and the "END" block simply exits with $single set to 0 (don't break, run to completion.). and that's the whole arc. character development. π¦
π PRE-5.8 COMMANDS π
Some of the commands changed function quite a bit in the 5.8 command realignment β so much so that the old code had to be replaced completely. Because we wanted to keep the option of going back to the former command set, we moved the old code off to this section. it's the nostalgia shelf. π
There's an awful lot of duplicated code here. We've duplicated the comments too, to keep things clear. (copy-paste but make it intentional β¨)
Null command
Does nothing. Used to turn off commands. truly the slacker of the command world, and we respect her for it. π€
Old "a" command.
This version added actions if you supplied them, and deleted them if you didn't.
Old "b" command
Add breakpoints.
Old "D" command.
Delete all breakpoints unconditionally. no thoughts, no questions, just deletion. π
Old "h" command
Print help. Defaults to printing the long-form help; the 5.8 version prints the summary by default. so if you're wondering why the output feels different, that's the tea. β
Old "W" command
"W <expr>" adds a watch expression, "W" deletes them all.
π PRE-AND-POST-PROMPT COMMANDS AND ACTIONS π
The debugger used to have a whole bunch of nearly-identical code to handle the pre-and-post-prompt action commands β like five siblings wearing the same outfit. cmd_pre590_prepost and cmd_prepost unify all this into one set of code to handle the appropriate actions. one outfit, many occasions. slay. π
"cmd_pre590_prepost"
A small wrapper around "cmd_prepost"; it makes sure that the default doesn't do something destructive. In pre 5.8 debuggers, the default action was to delete all the actions. so yeah, we needed the wrapper. safety first bestie. π
"cmd_prepost"
Actually does all the handling for "<", ">", "{{", "{", etc. Since the lists of actions are all held in arrays that are pointed to by references anyway, all we have to do is pick the right array reference and then use generic code to all, delete, or list actions. one function, three moods. π
π DB::fake π
Contains the "at_exit" routine that the debugger uses to issue the "Debugged program terminated ..." message after the program completes. See the "END" block documentation for more details. (yes, we're referencing ourselves. it's called self-love. π)
and that's a wrap on PDLdb(3pm)!! you made it all the way to the end of a genuinely massive manpage and honestly? obsessed with you π«Ά this whole page ships as part of perl, version v5.42.3, dated 2026-08-20, and it lives in the PDLdb(3pm) section β so if you ever need to find your way back, you know exactly where she is. q to quit, and go take a break, you've earned it π
β¨πΈ
π¦ where this page comes from
- ubuntu stonking: pdl 1:2.106-1build1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms