=head1 NAME
perl5db.pl - the perl debugger
=head1 SYNOPSIS
perl -d your_Perl_script
=head1 DESCRIPTION
C is the perl debugger. It is loaded automatically by Perl when
you invoke a script with C. This documentation tries to outline the
structure and services provided by C, and to describe how you
can use them.
=head1 GENERAL NOTES
The debugger can look pretty forbidding to many Perl programmers. There are
a number of reasons for this, many stemming 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 things one would normally have done using such
features was done using global variables, globs and the C operator
in creative ways.
Some of these have survived into the current debugger; a few of the more
interesting and still-useful idioms are noted in this section, along with notes
on the comments themselves.
=head2 Why not use more lexicals?
Experienced Perl programmers will note that the debugger code tends to use
mostly package globals rather than lexically-scoped variables. This is done
to allow a significant amount of control of the debugger from outside the
debugger itself.
Unfortunately, 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
I 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.
=head2 Automated variable stacking via C
As you may recall from reading C, the C 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;
}
What happens is that on entry to the subroutine, C<$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 I. Of particular note is C,
which lets the debugger get control inside of C'ed code. The debugger
localizes a saved copy of C<$@> inside the subroutine, which allows it to
keep C<$@> safe until it C returns, at which point the previous
value of C<$@> is restored. This makes it simple (well, I) to keep
track of C<$@> inside Cs which C other C.
In any case, watch for this pattern. It occurs fairly often.
=head2 The C<^> trick
This is used to cleverly reverse the sense of a logical test depending on
the value of an auxiliary variable. For instance, the debugger's C
(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:
=over 4
=item * 0 ^ 0 = 0
(! not present and no match) --> false, don't print
=item * 0 ^ 1 = 1
(! not present and matches) --> true, print
=item * 1 ^ 0 = 1
(! present and no match) --> true, print
=item * 1 ^ 1 = 0
(! present and matches) --> false, don't print
=back
As you can see, the first pair applies when C 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
explanation...
=head2 FLAGS, FLAGS, FLAGS
There is a certain C programming legacy in the debugger. Some variables,
such as C<$single>, C<$trace>, and C<$frame>, have I 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, C<$scalar> is acting sort of like
an array of bits. Obviously, since the contents of C<$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?
=over 4
=item *
First, doing an arithmetical or bitwise operation on a scalar is
just about the fastest thing you can do in Perl: C actually
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 I. 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.
=item *
Second, it's very easy to serialize a scalar number. This is done in
the restart code; the debugger state variables are saved in C<%ENV> and then
restored when the debugger is restarted. Having them be just numbers makes
this trivial.
=item *
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).
=back
=head2 What are those C comments for?
Any comment containing C 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 C.
=head1 DATA STRUCTURES MAINTAINED BY CORE
There are a number of special data structures provided to the debugger by
the Perl interpreter.
The array C<@{$main::{'_<'.$filename}}> (aliased locally to C<@dbline> via glob
assignment) contains the text from C<$filename>, with each element
corresponding to a single line of C<$filename>.
The hash C<%{'_<'.$filename}> (aliased locally to C<%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; C uses C<$break_condition\0$action>.
Values are magical in numeric context: 1 if the line is breakable, 0 if not.
The scalar C<${"_<$filename"}> simply contains the string C<_<$filename>.
This is also the case for evaluated strings that contain subroutines, or
which are currently being executed. The $filename for Ced strings looks
like C<(eval 34)> or C<(re_eval 19)>.
=head1 DEBUGGER STARTUP
When C starts, it reads an rcfile (C for
non-interactive sessions, C<.perldb> for interactive ones) that can set a number
of options. In addition, this file may define a subroutine C<&afterinit>
that will be executed (in the debugger's context) after the debugger has
initialized itself.
Next, it checks the C environment variable and treats its
contents as the argument of a C command in the debugger.
=head2 STARTUP-ONLY OPTIONS
The following options can only be specified at startup.
To set them in your rcfile, add a call to
C<&parse_options("optionName=new_value")>.
=over 4
=item * TTY
the TTY to use for debugging i/o.
=item * noTTY
if set, goes in NonStop mode. On interrupt, if TTY is not set,
uses the value of noTTY or F<$HOME/.perldbtty$$> to find TTY using
Term::Rendezvous. Current variant is to have the name of TTY in this
file.
=item * ReadLine
if false, a dummy ReadLine is used, so you can debug
ReadLine applications.
=item * NonStop
if true, no i/o is performed until interrupt.
=item * LineInfo
file or pipe to print line number info to. If it is a
pipe, a short "emacs like" message is used.
=item * RemotePort
host:port to connect to on remote host for remote debugging.
=item * HistFile
file to store session history to. There is no default and so no
history file is written unless this variable is explicitly set.
=item * HistSize
number of commands to store to the file specified in C.
Default is 100.
=back
=head3 SAMPLE RCFILE
&parse_options("NonStop=1 LineInfo=db.out");
sub afterinit { $trace = 1; }
The script will run without human intervention, putting trace
information into C. (If you interrupt it, you had better
reset C to something I!)
=head1 INTERNALS DESCRIPTION
=head2 DEBUGGER INTERFACE VARIABLES
Perl supplies the values for C<%sub>. It effectively inserts
a C<&DB::DB();> in front of each place that can have a
breakpoint. At each subroutine call, it calls C<&DB::sub> with
C<$DB::sub> set to the called subroutine. It also inserts a C before the first line.
After each Cd file is compiled, but before it is executed, a
call to C<&DB::postponed($main::{'_<'.$filename})> is done. C<$filename>
is the expanded name of the Cd file (as found via C<%INC>).
=head3 IMPORTANT INTERNAL VARIABLES
=head4 C<$CreateTTY>
Used to control when the debugger will attempt to acquire another TTY to be
used for input.
=over
=item * 1 - on C
=item * 2 - debugger is started inside debugger
=item * 4 - on startup
=back
=head4 C<$doret>
The value -2 indicates that no return value should be printed.
Any other positive value causes C to print return values.
=head4 C<$evalarg>
The item to be eval'ed by C. Used to prevent messing with the current
contents of C<@_> when C is called.
=head4 C<$frame>
Determines what messages (if any) will get printed when a subroutine (or eval)
is entered or exited.
=over 4
=item * 0 - No enter/exit messages
=item * 1 - Print I messages on subroutine entry
=item * 2 - Adds exit messages on subroutine exit. If no other flag is on, acts like 1+2.
=item * 4 - Extended messages: C<< I=I from I:I >>. If no other flag is on, acts like 1+4.
=item * 8 - Adds parameter information to messages, and overloaded stringify and tied FETCH is enabled on the printed arguments. Ignored if C<4> is not on.
=item * 16 - Adds C return from I: I> messages on subroutine/eval exit. Ignored if C<4> is is not on.
=back
To get everything, use C<$frame=30> (or C as a debugger command).
The debugger internally juggles the value of C<$frame> during execution to
protect external modules that the debugger uses from getting traced.
=head4 C<$level>
Tracks current debugger nesting level. Used to figure out how many
CE> pairs to surround the line number with when the debugger
outputs a prompt. Also used to help determine if the program has finished
during command parsing.
=head4 C<$onetimeDump>
Controls what (if anything) C will print after evaluating an
expression.
=over 4
=item * C - don't print anything
=item * C - use C to display the value returned
=item * C - print the methods callable on the first item returned
=back
=head4 C<$onetimeDumpDepth>
Controls how far down C will go before printing C<...> while
dumping a structure. Numeric. If C, print all levels.
=head4 C<$signal>
Used to track whether or not an C signal has been detected. C,
which is called before every statement, checks this and puts the user into
command mode if it finds C<$signal> set to a true value.
=head4 C<$single>
Controls behavior during single-stepping. Stacked in C<@stack> on entry to
each subroutine; popped again at the end of each subroutine.
=over 4
=item * 0 - run continuously.
=item * 1 - single-step, go into subs. The C command.
=item * 2 - single-step, don't go into subs. The C command.
=item * 4 - print current sub depth (turned on to force this when C occurs.
=back
=head4 C<$trace>
Controls the output of trace information.
=over 4
=item * 1 - The C command was entered to turn on tracing (every line executed is printed)
=item * 2 - watch expressions are active
=item * 4 - user defined a C in C
=back
=head4 C<$slave_editor>
1 if C was directed to a pipe; 0 otherwise.
=head4 C<@cmdfhs>
Stack of filehandles that C will read commands from.
Manipulated by the debugger's C command and C itself.
=head4 C<@dbline>
Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> ,
supplied by the Perl interpreter to the debugger. Contains the source.
=head4 C<@old_watch>
Previous values of watch expressions. First set when the expression is
entered; reset whenever the watch expression changes.
=head4 C<@saved>
Saves important globals (C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W>)
so that the debugger can substitute safe values while it's running, and
restore them when it returns control.
=head4 C<@stack>
Saves the current value of C<$single> on entry to a subroutine.
Manipulated by the C command to turn off tracing in all subs above the
current one.
=head4 C<@to_watch>
The 'watch' expressions: to be evaluated before each line is executed.
=head4 C<@typeahead>
The typeahead buffer, used by C.
=head4 C<%alias>
Command aliases. Stored as character strings to be substituted for a command
entered.
=head4 C<%break_on_load>
Keys are file names, values are 1 (break when this file is loaded) or undef
(don't break when it is loaded).
=head4 C<%dbline>
Keys are line numbers, values are C. If used in numeric
context, values are 0 if not breakable, 1 if breakable, no matter what is
in the actual hash entry.
=head4 C<%had_breakpoints>
Keys are file names; values are bitfields:
=over 4
=item * 1 - file has a breakpoint in it.
=item * 2 - file has an action in it.
=back
A zero or undefined value means this file has neither.
=head4 C<%option>
Stores the debugger options. These are character string values.
=head4 C<%postponed>
Saves breakpoints for code that hasn't been compiled yet.
Keys are subroutine names, values are:
=over 4
=item * C - break when this sub is compiled
=item * C<< break +0 if >> - break (conditionally) at the start of this routine. The condition will be '1' if no condition was specified.
=back
=head4 C<%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 (C).
=head1 DEBUGGER INITIALIZATION
The debugger's initialization actually jumps all over the place inside this
package. This is because there are several BEGIN blocks (which of course
execute immediately) spread through the code. Why is that?
The debugger needs to be able to change some things and set some things up
before the debugger code is compiled; most notably, the C<$deep> variable that
C uses to tell when a program has recursed deeply. In addition, 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 begins
executing.
The first C block simply turns off warnings by saving the current
setting of C<$^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 C<$^X> back to its former value.
We'll detail the second C block later; just remember that if you need
to initialize something before the debugger starts really executing, that's
where it has to go.
=cut
package DB;
BEGIN {eval 'use IO::Handle'}; # Needed for flush only? breaks under miniperl
# Debugger for Perl 5.00x; perl5db.pl patch level:
$VERSION = 1.32;
$header = "perl5db.pl version $VERSION";
=head1 DEBUGGER ROUTINES
=head2 C
This function replaces straight C inside the debugger; it simplifies
the process of evaluating code in the user's context.
The code to be evaluated is passed via the package global variable
C<$DB::evalarg>; this is done to avoid fiddling with the contents of C<@_>.
Before we do the C, we preserve the current settings of C<$trace>,
C<$single>, C<$^D> and C<$usercontext>. The latter contains the
preserved values of C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W> and the
user's current package, grabbed when C got control. This causes the
proper context to be used when the eval is actually done. Afterward, we
restore C<$trace>, C<$single>, and C<$^D>.
Next we need to handle C<$@> without getting confused. We save C<$@> in a
local lexical, localize C<$saved[0]> (which is where C will put
C<$@>), and then call C to capture C<$@>, C<$!>, C<$^E>, C<$,>,
C<$/>, C<$\>, and C<$^W>) and set C<$,>, C<$/>, C<$\>, and C<$^W> to values
considered sane by the debugger. If there was an C error, we print
it on the debugger's output. If C<$onetimedump> is defined, we call
C if it's set to 'dump', or C 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 C to the caller,
and unwinding restores the former version of C<$@> in C<@saved> as well
(the localization of C<$saved[0]> goes away at the end of this scope).
=head3 Parameters and variables influencing execution of DB::eval()
C isn't parameterized in the standard way; this is to keep the
debugger's calls to C from mucking with C<@_>, among other things.
The variables listed below influence C's execution directly.
=over 4
=item C<$evalarg> - the thing to actually be eval'ed
=item C<$trace> - Current state of execution tracing
=item C<$single> - Current state of single-stepping
=item C<$onetimeDump> - what is to be displayed after the evaluation
=item C<$onetimeDumpDepth> - how deep C should go when dumping results
=back
The following variables are altered by C during its execution. They
are "stacked" via C, enabling recursive calls to C.
=over 4
=item C<@res> - used to capture output from actual C.
=item C<$otrace> - saved value of C<$trace>.
=item C<$osingle> - saved value of C<$single>.
=item C<$od> - saved value of C<$^D>.
=item C<$saved[0]> - saved value of C<$@>.
=item $\ - for output of C<$@> if there is an evaluation error.
=back
=head3 The problem of lexicals
The context of C presents us with some problems. 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 C can see localized
variables; and we can't use C either for the same reason. The code
in this routine compromises and uses C.
After this routine is over, we don't have user code executing in the debugger's
context, so we can use C freely.
=cut
############################################## Begin lexical danger zone
# 'my' variables used here could leak into (that is, be visible in)
# the context that the code being evaluated is executing in. This means that
# the code could modify the debugger's variables.
#
# Fiddling with the debugger's context could be Bad. We insulate things as
# much as we can.
sub eval {
# 'my' would make it visible from user code
# but so does local! --tchrist
# Remember: this localizes @DB::res, not @main::res.
local @res;
{
# Try to keep the user code from messing with us. Save these so that
# even if the eval'ed code changes them, we can put them back again.
# Needed because the user could refer directly to the debugger's
# package globals (and any 'my' variables in this containing scope)
# inside the eval(), and we want to try to stay safe.
local $otrace = $trace;
local $osingle = $single;
local $od = $^D;
# Untaint the incoming eval() argument.
{ ($evalarg) = $evalarg =~ /(.*)/s; }
# $usercontext built in DB::DB near the comment
# "set up the context for DB::eval ..."
# Evaluate and save any results.
@res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
# Restore those old values.
$trace = $otrace;
$single = $osingle;
$^D = $od;
}
# Save the current value of $@, and preserve it in the debugger's copy
# of the saved precious globals.
my $at = $@;
# Since we're only saving $@, we only have to localize the array element
# that it will be stored in.
local $saved[0]; # Preserve the old value of $@
eval { &DB::save };
# Now see whether we need to report an error back to the user.
if ($at) {
local $\ = '';
print $OUT $at;
}
# Display as required by the caller. $onetimeDump and $onetimedumpDepth
# are package globals.
elsif ($onetimeDump) {
if ( $onetimeDump eq 'dump' ) {
local $option{dumpDepth} = $onetimedumpDepth
if defined $onetimedumpDepth;
dumpit( $OUT, \@res );
}
elsif ( $onetimeDump eq 'methods' ) {
methods( $res[0] );
}
} ## end elsif ($onetimeDump)
@res;
} ## end sub eval
############################################## End lexical danger zone
# After this point it is safe to introduce lexicals.
# The code being debugged will be executing in its own context, and
# can't see the inside of the debugger.
#
# However, one should not overdo it: leave as much control from outside as
# possible. If you make something a lexical, it's not going to be addressable
# from outside the debugger even if you know its name.
# This file is automatically included if you do perl -d.
# It's probably not useful to include this yourself.
#
# Before venturing further into these twisty passages, it is
# wise to read the perldebguts man page or risk the ire of dragons.
#
# (It should be noted that perldebguts will tell you a lot about
# the underlying mechanics of how the debugger interfaces into the
# Perl interpreter, but not a lot about the debugger itself. The new
# comments in this code try to address this problem.)
# Note that no subroutine call is possible until &DB::sub is defined
# (for subroutines defined outside of the package DB). In fact the same is
# true if $deep is not defined.
# Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
# modified Perl debugger, to be run from Emacs in perldb-mode
# Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
# Johan Vromans -- upgrade to 4.0 pl 10
# Ilya Zakharevich -- patches after 5.001 (and some before ;-)
# (We have made efforts to clarify the comments in the change log
# in other places; some of them may seem somewhat obscure as they
# were originally written, and explaining them away from the code
# in question seems conterproductive.. -JM)
########################################################################
# Changes: 0.94
# + A lot of things changed after 0.94. First of all, core now informs
# debugger about entry into XSUBs, overloaded operators, tied operations,
# BEGIN and END. Handy with `O f=2'.
# + This can make debugger a little bit too verbose, please be patient
# and report your problems promptly.
# + Now the option frame has 3 values: 0,1,2. XXX Document!
# + Note that if DESTROY returns a reference to the object (or object),
# the deletion of data may be postponed until the next function call,
# due to the need to examine the return value.
#
# Changes: 0.95
# + `v' command shows versions.
#
# Changes: 0.96
# + `v' command shows version of readline.
# primitive completion works (dynamic variables, subs for `b' and `l',
# options). Can `p %var'
# + Better help (`h <' now works). New commands <<, >>, {, {{.
# {dump|print}_trace() coded (to be able to do it from <, <, or {. (A command
# without an argument should *never* be a destructive action; this
# API is fundamentally screwed up; likewise option setting, which
# is equally buggered.)
# + Added command stack dump on argument of "?" for >, <, or {.
# + Added a semi-built-in doc viewer command that calls man with the
# proper %Config::Config path (and thus gets caching, man -k, etc),
# or else perldoc on obstreperous platforms.
# + Added to and rearranged the help information.
# + Detected apparent misuse of { ... } to declare a block; this used
# to work but now is a command, and mysteriously gave no complaint.
#
# Changes: 1.08: Apr 25, 2001 Jon Eveland
# BUG FIX:
# + This patch to perl5db.pl cleans up formatting issues on the help
# summary (h h) screen in the debugger. Mostly columnar alignment
# issues, plus converted the printed text to use all spaces, since
# tabs don't seem to help much here.
#
# Changes: 1.09: May 19, 2001 Ilya Zakharevich
# Minor bugs corrected;
# + Support for auto-creation of new TTY window on startup, either
# unconditionally, or if started as a kid of another debugger session;
# + New `O'ption CreateTTY
# I bits control attempts to create a new TTY on events:
# 1: on fork()
# 2: debugger is started inside debugger
# 4: on startup
# + Code to auto-create a new TTY window on OS/2 (currently one
# extra window per session - need named pipes to have more...);
# + Simplified interface for custom createTTY functions (with a backward
# compatibility hack); now returns the TTY name to use; return of ''
# means that the function reset the I/O handles itself;
# + Better message on the semantic of custom createTTY function;
# + Convert the existing code to create a TTY into a custom createTTY
# function;
# + Consistent support for TTY names of the form "TTYin,TTYout";
# + Switch line-tracing output too to the created TTY window;
# + make `b fork' DWIM with CORE::GLOBAL::fork;
# + High-level debugger API cmd_*():
# cmd_b_load($filenamepart) # b load filenamepart
# cmd_b_line($lineno [, $cond]) # b lineno [cond]
# cmd_b_sub($sub [, $cond]) # b sub [cond]
# cmd_stop() # Control-C
# cmd_d($lineno) # d lineno (B)
# The cmd_*() API returns FALSE on failure; in this case it outputs
# the error message to the debugging output.
# + Low-level debugger API
# break_on_load($filename) # b load filename
# @files = report_break_on_load() # List files with load-breakpoints
# breakable_line_in_filename($name, $from [, $to])
# # First breakable line in the
# # range $from .. $to. $to defaults
# # to $from, and may be less than
# # $to
# breakable_line($from [, $to]) # Same for the current file
# break_on_filename_line($name, $lineno [, $cond])
# # Set breakpoint,$cond defaults to
# # 1
# break_on_filename_line_range($name, $from, $to [, $cond])
# # As above, on the first
# # breakable line in range
# break_on_line($lineno [, $cond]) # As above, in the current file
# break_subroutine($sub [, $cond]) # break on the first breakable line
# ($name, $from, $to) = subroutine_filename_lines($sub)
# # The range of lines of the text
# The low-level API returns TRUE on success, and die()s on failure.
#
# Changes: 1.10: May 23, 2001 Daniel Lewart
# BUG FIXES:
# + Fixed warnings generated by "perl -dWe 42"
# + Corrected spelling errors
# + Squeezed Help (h) output into 80 columns
#
# Changes: 1.11: May 24, 2001 David Dyck
# + Made "x @INC" work like it used to
#
# Changes: 1.12: May 24, 2001 Daniel Lewart
# + Fixed warnings generated by "O" (Show debugger options)
# + Fixed warnings generated by "p 42" (Print expression)
# Changes: 1.13: Jun 19, 2001 Scott.L.Miller@compaq.com
# + Added windowSize option
# Changes: 1.14: Oct 9, 2001 multiple
# + Clean up after itself on VMS (Charles Lane in 12385)
# + Adding "@ file" syntax (Peter Scott in 12014)
# + Debug reloading selfloaded stuff (Ilya Zakharevich in 11457)
# + $^S and other debugger fixes (Ilya Zakharevich in 11120)
# + Forgot a my() declaration (Ilya Zakharevich in 11085)
# Changes: 1.15: Nov 6, 2001 Michael G Schwern
# + Updated 1.14 change log
# + Added *dbline explainatory comments
# + Mentioning perldebguts man page
# Changes: 1.16: Feb 15, 2002 Mark-Jason Dominus
# + $onetimeDump improvements
# Changes: 1.17: Feb 20, 2002 Richard Foley
# Moved some code to cmd_[.]()'s for clarity and ease of handling,
# rationalised the following commands and added cmd_wrapper() to
# enable switching between old and frighteningly consistent new
# behaviours for diehards: 'o CommandSet=pre580' (sigh...)
# a(add), A(del) # action expr (added del by line)
# + b(add), B(del) # break [line] (was b,D)
# + w(add), W(del) # watch expr (was W,W)
# # added del by expr
# + h(summary), h h(long) # help (hh) (was h h,h)
# + m(methods), M(modules) # ... (was m,v)
# + o(option) # lc (was O)
# + v(view code), V(view Variables) # ... (was w,V)
# Changes: 1.18: Mar 17, 2002 Richard Foley
# + fixed missing cmd_O bug
# Changes: 1.19: Mar 29, 2002 Spider Boardman
# + Added missing local()s -- DB::DB is called recursively.
# Changes: 1.20: Feb 17, 2003 Richard Foley
# + pre'n'post commands no longer trashed with no args
# + watch val joined out of eval()
# Changes: 1.21: Jun 04, 2003 Joe McMahon
# + Added comments and reformatted source. No bug fixes/enhancements.
# + Includes cleanup by Robin Barker and Jarkko Hietaniemi.
# Changes: 1.22 Jun 09, 2003 Alex Vandiver
# + Flush stdout/stderr before the debugger prompt is printed.
# Changes: 1.23: Dec 21, 2003 Dominique Quatravaux
# + Fix a side-effect of bug #24674 in the perl debugger ("odd taint bug")
# Changes: 1.24: Mar 03, 2004 Richard Foley
# + Added command to save all debugger commands for sourcing later.
# + Added command to display parent inheritance tree of given class.
# + Fixed minor newline in history bug.
# Changes: 1.25: Apr 17, 2004 Richard Foley
# + Fixed option bug (setting invalid options + not recognising valid short forms)
# Changes: 1.26: Apr 22, 2004 Richard Foley
# + unfork the 5.8.x and 5.9.x debuggers.
# + whitespace and assertions call cleanup across versions
# + H * deletes (resets) history
# + i now handles Class + blessed objects
# Changes: 1.27: May 09, 2004 Richard Foley
# + updated pod page references - clunky.
# + removed windowid restriction for forking into an xterm.
# + more whitespace again.
# + wrapped restart and enabled rerun [-n] (go back n steps) command.
# Changes: 1.28: Oct 12, 2004 Richard Foley
# + Added threads support (inc. e and E commands)
# Changes: 1.29: Nov 28, 2006 Bo Lindbergh
# + Added macosx_get_fork_TTY support
# Changes: 1.30: Mar 06, 2007 Andreas Koenig
# + Added HistFile, HistSize
# Changes: 1.31
# + Remove support for assertions and -A
# + stop NEXT::AUTOLOAD from emitting warnings under the debugger. RT #25053
# + "update for Mac OS X 10.5" [finding the tty device]
# + "What I needed to get the forked debugger to work" [on VMS]
# + [perl #57016] debugger: o warn=0 die=0 ignored
# + Note, but don't use, PERLDBf_SAVESRC
# + Fix #7013: lvalue subs not working inside debugger
########################################################################
=head1 DEBUGGER INITIALIZATION
The debugger starts up in phases.
=head2 BASIC SETUP
First, it initializes the environment it wants to run in: turning off
warnings during its own compilation, defining variables which it will need
to avoid warnings later, setting itself up to not exit when the program
terminates, and defaulting to printing return values for the C command.
=cut
# Needed for the statement after exec():
#
# This BEGIN block is simply used to switch off warnings during debugger
# compiliation. Probably it would be better practice to fix the warnings,
# but this is how it's done at the moment.
BEGIN {
$ini_warn = $^W;
$^W = 0;
} # Switch compilation warnings off until another BEGIN.
local ($^W) = 0; # Switch run-time warnings off during init.
=head2 THREADS SUPPORT
If we are running under a threaded Perl, we require threads and threads::shared
if the environment variable C is set, to enable proper
threaded debugger control. C<-dt> can also be used to set this.
Each new thread will be announced and the debugger prompt will always inform
you of each new thread created. It will also indicate the thread id in which
we are currently running within the prompt like this:
[tid] DB<$i>
Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger
command prompt. The prompt will show: C<[0]> when running under threads, but
not actually in a thread. C<[tid]> is consistent with C usage.
While running under threads, when you set or delete a breakpoint (etc.), this
will apply to all threads, not just the currently running one. When you are
in a currently executing thread, you will stay there until it completes. With
the current implementation it is not currently possible to hop from one thread
to another.
The C and C commands are currently fairly minimal - see C and C.
Note that threading support was built into the debugger as of Perl version
C<5.8.6> and debugger version C<1.2.8>.
=cut
BEGIN {
# ensure we can share our non-threaded variables or no-op
if ($ENV{PERL5DB_THREADED}) {
require threads;
require threads::shared;
import threads::shared qw(share);
$DBGR;
share(\$DBGR);
lock($DBGR);
print "Threads support enabled\n";
} else {
*lock = sub(*) {};
*share = sub(*) {};
}
}
# This would probably be better done with "use vars", but that wasn't around
# when this code was originally written. (Neither was "use strict".) And on
# the principle of not fiddling with something that was working, this was
# left alone.
warn( # Do not ;-)
# These variables control the execution of 'dumpvar.pl'.
$dumpvar::hashDepth,
$dumpvar::arrayDepth,
$dumpvar::dumpDBFiles,
$dumpvar::dumpPackages,
$dumpvar::quoteHighBit,
$dumpvar::printUndef,
$dumpvar::globPrint,
$dumpvar::usageOnly,
# used to save @ARGV and extract any debugger-related flags.
@ARGS,
# used to control die() reporting in diesignal()
$Carp::CarpLevel,
# used to prevent multiple entries to diesignal()
# (if for instance diesignal() itself dies)
$panic,
# used to prevent the debugger from running nonstop
# after a restart
$second_time,
)
if 0;
foreach my $k (keys (%INC)) {
&share(\$main::{'_<'.$filename});
};
# Command-line + PERLLIB:
# Save the contents of @INC before they are modified elsewhere.
@ini_INC = @INC;
# This was an attempt to clear out the previous values of various
# trapped errors. Apparently it didn't help. XXX More info needed!
# $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
# We set these variables to safe values. We don't want to blindly turn
# off warnings, because other packages may still want them.
$trace = $signal = $single = 0; # Uninitialized warning suppression
# (local $^W cannot help - other packages!).
# Default to not exiting when program finishes; print the return
# value when the 'r' command is used to return from a subroutine.
$inhibit_exit = $option{PrintRet} = 1;
=head1 OPTION PROCESSING
The debugger's options are actually spread out over the debugger itself and
C; some of these are variables to be set, while others are
subs to be called with a value. To try to make this a little easier to
manage, the debugger uses a few data structures to define what options
are legal and how they are to be processed.
First, the C<@options> array defines the I of all the options that
are to be accepted.
=cut
@options = qw(
CommandSet HistFile HistSize
hashDepth arrayDepth dumpDepth
DumpDBFiles DumpPackages DumpReused
compactDump veryCompact quote
HighBit undefPrint globPrint
PrintRet UsageOnly frame
AutoTrace TTY noTTY
ReadLine NonStop LineInfo
maxTraceLen recallCommand ShellBang
pager tkRunning ornaments
signalLevel warnLevel dieLevel
inhibit_exit ImmediateStop bareStringify
CreateTTY RemotePort windowSize
DollarCaretP
);
@RememberOnROptions = qw(DollarCaretP);
=pod
Second, C lists the variables that each option uses to save its
state.
=cut
%optionVars = (
hashDepth => \$dumpvar::hashDepth,
arrayDepth => \$dumpvar::arrayDepth,
CommandSet => \$CommandSet,
DumpDBFiles => \$dumpvar::dumpDBFiles,
DumpPackages => \$dumpvar::dumpPackages,
DumpReused => \$dumpvar::dumpReused,
HighBit => \$dumpvar::quoteHighBit,
undefPrint => \$dumpvar::printUndef,
globPrint => \$dumpvar::globPrint,
UsageOnly => \$dumpvar::usageOnly,
CreateTTY => \$CreateTTY,
bareStringify => \$dumpvar::bareStringify,
frame => \$frame,
AutoTrace => \$trace,
inhibit_exit => \$inhibit_exit,
maxTraceLen => \$maxtrace,
ImmediateStop => \$ImmediateStop,
RemotePort => \$remoteport,
windowSize => \$window,
HistFile => \$histfile,
HistSize => \$histsize,
);
=pod
Third, C<%optionAction> defines the subroutine to be called to process each
option.
=cut
%optionAction = (
compactDump => \&dumpvar::compactDump,
veryCompact => \&dumpvar::veryCompact,
quote => \&dumpvar::quote,
TTY => \&TTY,
noTTY => \&noTTY,
ReadLine => \&ReadLine,
NonStop => \&NonStop,
LineInfo => \&LineInfo,
recallCommand => \&recallCommand,
ShellBang => \&shellBang,
pager => \&pager,
signalLevel => \&signalLevel,
warnLevel => \&warnLevel,
dieLevel => \&dieLevel,
tkRunning => \&tkRunning,
ornaments => \&ornaments,
RemotePort => \&RemotePort,
DollarCaretP => \&DollarCaretP,
);
=pod
Last, the C<%optionRequire> notes modules that must be Cd if an
option is used.
=cut
# Note that this list is not complete: several options not listed here
# actually require that dumpvar.pl be loaded for them to work, but are
# not in the table. A subsequent patch will correct this problem; for
# the moment, we're just recommenting, and we are NOT going to change
# function.
%optionRequire = (
compactDump => 'dumpvar.pl',
veryCompact => 'dumpvar.pl',
quote => 'dumpvar.pl',
);
=pod
There are a number of initialization-related variables which can be set
by putting code to set them in a BEGIN block in the C environment
variable. These are:
=over 4
=item C<$rl> - readline control XXX needs more explanation
=item C<$warnLevel> - whether or not debugger takes over warning handling
=item C<$dieLevel> - whether or not debugger takes over die handling
=item C<$signalLevel> - whether or not debugger takes over signal handling
=item C<$pre> - preprompt actions (array reference)
=item C<$post> - postprompt actions (array reference)
=item C<$pretype>
=item C<$CreateTTY> - whether or not to create a new TTY for this debugger
=item C<$CommandSet> - which command set to use (defaults to new, documented set)
=back
=cut
# These guys may be defined in $ENV{PERL5DB} :
$rl = 1 unless defined $rl;
$warnLevel = 1 unless defined $warnLevel;
$dieLevel = 1 unless defined $dieLevel;
$signalLevel = 1 unless defined $signalLevel;
$pre = [] unless defined $pre;
$post = [] unless defined $post;
$pretype = [] unless defined $pretype;
$CreateTTY = 3 unless defined $CreateTTY;
$CommandSet = '580' unless defined $CommandSet;
share($rl);
share($warnLevel);
share($dieLevel);
share($signalLevel);
share($pre);
share($post);
share($pretype);
share($rl);
share($CreateTTY);
share($CommandSet);
=pod
The default C, C, and C handlers are set up.
=cut
warnLevel($warnLevel);
dieLevel($dieLevel);
signalLevel($signalLevel);
=pod
The pager to be used is needed next. We try to get it from the
environment first. If it's not defined there, we try to find it in
the Perl C. If it's not there, we default to C. We
then call the C function to save the pager name.
=cut
# This routine makes sure $pager is set up so that '|' can use it.
pager(
# If PAGER is defined in the environment, use it.
defined $ENV{PAGER}
? $ENV{PAGER}
# If not, see if Config.pm defines it.
: eval { require Config }
&& defined $Config::Config{pager}
? $Config::Config{pager}
# If not, fall back to 'more'.
: 'more'
)
unless defined $pager;
=pod
We set up the command to be used to access the man pages, the command
recall character (C unless otherwise defined) and the shell escape
character (C unless otherwise defined). Yes, these do conflict, and
neither works in the debugger at the moment.
=cut
setman();
# Set up defaults for command recall and shell escape (note:
# these currently don't work in linemode debugging).
&recallCommand("!") unless defined $prc;
&shellBang("!") unless defined $psh;
=pod
We then 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.
=cut
sethelp();
# If we didn't get a default for the length of eval/stack trace args,
# set it here.
$maxtrace = 400 unless defined $maxtrace;
=head2 SETTING UP THE DEBUGGER GREETING
The debugger I helps to inform the user how many debuggers are
running, and whether the current debugger is the primary or a child.
If we are the primary, we just hang onto our pid so we'll have it when
or if we start a child debugger. If we are a child, we'll 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 C environment variable
because we mess around with it. We'll 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 give them one later via C.
=cut
# Save the current contents of the environment; we're about to
# much with it. We'll need this if we have to restart.
$ini_pids = $ENV{PERLDB_PIDS};
if ( defined $ENV{PERLDB_PIDS} ) {
# We're a child. Make us a label out of the current PID structure
# recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having
# a term yet so the parent will give us one later via resetterm().
my $env_pids = $ENV{PERLDB_PIDS};
$pids = "[$env_pids]";
# Unless we are on OpenVMS, all programs under the DCL shell run under
# the same PID.
if (($^O eq 'VMS') && ($env_pids =~ /\b$$\b/)) {
$term_pid = $$;
}
else {
$ENV{PERLDB_PIDS} .= "->$$";
$term_pid = -1;
}
} ## end if (defined $ENV{PERLDB_PIDS...
else {
# We're the parent PID. Initialize PERLDB_PID in case we end up with a
# child debugger, and mark us as the parent, so we'll know to set up
# more TTY's is we have to.
$ENV{PERLDB_PIDS} = "$$";
$pids = "[pid=$$]";
$term_pid = $$;
}
$pidprompt = '';
# Sets up $emacs as a synonym for $slave_editor.
*emacs = $slave_editor if $slave_editor; # May be used in afterinit()...
=head2 READING THE RC FILE
The debugger will read a file of initialization options if supplied. If
running interactively, this is C<.perldb>; if not, it's C.
=cut
# As noted, this test really doesn't check accurately that the debugger
# is running at a terminal or not.
my $dev_tty = '/dev/tty';
$dev_tty = 'TT:' if ($^O eq 'VMS');
if ( -e $dev_tty ) { # this is the wrong metric!
$rcfile = ".perldb";
}
else {
$rcfile = "perldb.ini";
}
=pod
The debugger does a safety test of the file to be read. It must be owned
either by the current user or root, and must only be writable by the owner.
=cut
# This wraps a safety test around "do" to read and evaluate the init file.
#
# This isn't really safe, because there's a race
# between checking and opening. The solution is to
# open and fstat the handle, but then you have to read and
# eval the contents. But then the silly thing gets
# your lexical scope, which is unfortunate at best.
sub safe_do {
my $file = shift;
# Just exactly what part of the word "CORE::" don't you understand?
local $SIG{__WARN__};
local $SIG{__DIE__};
unless ( is_safe_file($file) ) {
CORE::warn < command is invoked, it
tries to capture all of the state it can into environment variables, and
then sets C. When we start executing again, we check to see
if C is there; if so, 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.
=cut
if ( exists $ENV{PERLDB_RESTART} ) {
# We're restarting, so we don't need the flag that says to restart anymore.
delete $ENV{PERLDB_RESTART};
# $restart = 1;
@hist = get_list('PERLDB_HIST');
%break_on_load = get_list("PERLDB_ON_LOAD");
%postponed = get_list("PERLDB_POSTPONE");
share(@hist);
share(@truehist);
share(%break_on_load);
share(%postponed);
# restore breakpoints/actions
my @had_breakpoints = get_list("PERLDB_VISITED");
for ( 0 .. $#had_breakpoints ) {
my %pf = get_list("PERLDB_FILE_$_");
$postponed_file{ $had_breakpoints[$_] } = \%pf if %pf;
}
# restore options
my %opt = get_list("PERLDB_OPT");
my ( $opt, $val );
while ( ( $opt, $val ) = each %opt ) {
$val =~ s/[\\\']/\\$1/g;
parse_options("$opt'$val'");
}
# restore original @INC
@INC = get_list("PERLDB_INC");
@ini_INC = @INC;
# return pre/postprompt actions and typeahead buffer
$pretype = [ get_list("PERLDB_PRETYPE") ];
$pre = [ get_list("PERLDB_PRE") ];
$post = [ get_list("PERLDB_POST") ];
@typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead );
} ## end if (exists $ENV{PERLDB_RESTART...
=head2 SETTING UP THE TERMINAL
Now, we'll decide how the debugger is going to interact with the user.
If there's no TTY, we set the debugger to run non-stop; there's not going
to be anyone there to enter commands.
=cut
if ($notty) {
$runnonstop = 1;
share($runnonstop);
}
=pod
If there is a TTY, we have to determine who it belongs to before we can
proceed. If this is a slave editor or graphical debugger (denoted by
the first command-line switch being '-emacs'), we shift this off and
set C<$rl> to 0 (XXX ostensibly to do straight reads).
=cut
else {
# Is Perl being run from a slave editor or graphical debugger?
# If so, don't use readline, and set $slave_editor = 1.
$slave_editor =
( ( defined $main::ARGV[0] ) and ( $main::ARGV[0] eq '-emacs' ) );
$rl = 0, shift(@main::ARGV) if $slave_editor;
#require Term::ReadLine;
=pod
We then determine what the console should be on various systems:
=over 4
=item * Cygwin - We use C instead of a separate device.
=cut
if ( $^O eq 'cygwin' ) {
# /dev/tty is binary. use stdin for textmode
undef $console;
}
=item * Unix - use C.
=cut
elsif ( -e "/dev/tty" ) {
$console = "/dev/tty";
}
=item * Windows or MSDOS - use C.
=cut
elsif ( $^O eq 'dos' or -e "con" or $^O eq 'MSWin32' ) {
$console = "con";
}
=item * MacOS - use C if this is the MPW version; C if not.
Note that Mac OS X returns C, not C. Also note that the debugger doesn't do anything special for C. Maybe it should.
=cut
elsif ( $^O eq 'MacOS' ) {
if ( $MacPerl::Version !~ /MPW/ ) {
$console =
"Dev:Console:Perl Debug"; # Separate window for application
}
else {
$console = "Dev:Console";
}
} ## end elsif ($^O eq 'MacOS')
=item * VMS - use C.
=cut
else {
# everything else is ...
$console = "sys\$command";
}
=pod
=back
Several other systems don't use a specific console. We C
for those (Windows using a slave editor/graphical debugger, NetWare, OS/2
with a slave editor, Epoc).
=cut
if ( ( $^O eq 'MSWin32' ) and ( $slave_editor or defined $ENV{EMACS} ) ) {
# /dev/tty is binary. use stdin for textmode
$console = undef;
}
if ( $^O eq 'NetWare' ) {
# /dev/tty is binary. use stdin for textmode
$console = undef;
}
# In OS/2, we need to use STDIN to get textmode too, even though
# it pretty much looks like Unix otherwise.
if ( defined $ENV{OS2_SHELL} and ( $slave_editor or $ENV{WINDOWID} ) )
{ # In OS/2
$console = undef;
}
# EPOC also falls into the 'got to use STDIN' camp.
if ( $^O eq 'epoc' ) {
$console = undef;
}
=pod
If there is a TTY hanging around from a parent, we use that as the console.
=cut
$console = $tty if defined $tty;
=head2 SOCKET HANDLING
The debugger is capable of opening a socket and carrying out a debugging
session over the socket.
If C was defined in the options, the debugger assumes that 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.
=cut
# Handle socket stuff.
if ( defined $remoteport ) {
# If RemotePort was defined in the options, connect input and output
# to the socket.
require IO::Socket;
$OUT = new IO::Socket::INET(
Timeout => '10',
PeerAddr => $remoteport,
Proto => 'tcp',
);
if ( !$OUT ) { die "Unable to connect to remote host: $remoteport\n"; }
$IN = $OUT;
} ## end if (defined $remoteport)
=pod
If no C 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.
=cut
# Non-socket.
else {
# Two debuggers running (probably a system or a backtick that invokes
# the debugger itself under the running one). create a new IN and OUT
# filehandle, and do the necessary mojo to create a new tty if we
# know how, and we can.
create_IN_OUT(4) if $CreateTTY & 4;
if ($console) {
# If we have a console, check to see if there are separate ins and
# outs to open. (They are assumed identical if not.)
my ( $i, $o ) = split /,/, $console;
$o = $i unless defined $o;
# read/write on in, or just read, or read on STDIN.
open( IN, "+<$i" )
|| open( IN, "<$i" )
|| open( IN, "<&STDIN" );
# read/write/create/clobber out, or write/create/clobber out,
# or merge with STDERR, or merge with STDOUT.
open( OUT, "+>$o" )
|| open( OUT, ">$o" )
|| open( OUT, ">&STDERR" )
|| open( OUT, ">&STDOUT" ); # so we don't dongle stdout
} ## end if ($console)
elsif ( not defined $console ) {
# No console. Open STDIN.
open( IN, "<&STDIN" );
# merge with STDERR, or with STDOUT.
open( OUT, ">&STDERR" )
|| open( OUT, ">&STDOUT" ); # so we don't dongle stdout
$console = 'STDIN/OUT';
} ## end elsif (not defined $console)
# Keep copies of the filehandles so that when the pager runs, it
# can close standard input without clobbering ours.
$IN = \*IN, $OUT = \*OUT if $console or not defined $console;
} ## end elsif (from if(defined $remoteport))
# Unbuffer DB::OUT. We need to see responses right away.
my $previous = select($OUT);
$| = 1; # for DB::OUT
select($previous);
# Line info goes to debugger output unless pointed elsewhere.
# Pointing elsewhere makes it possible for slave editors to
# keep track of file and position. We have both a filehandle
# and a I/O description to keep track of.
$LINEINFO = $OUT unless defined $LINEINFO;
$lineinfo = $console unless defined $lineinfo;
# share($LINEINFO); # <- unable to share globs
share($lineinfo); #
=pod
To finish initialization, we show the debugger greeting,
and then call the C subroutine if there is one.
=cut
# Show the debugger greeting.
$header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
unless ($runnonstop) {
local $\ = '';
local $, = '';
if ( $term_pid eq '-1' ) {
print $OUT "\nDaughter DB session started...\n";
}
else {
print $OUT "\nLoading DB routines from $header\n";
print $OUT (
"Editor support ",
$slave_editor ? "enabled" : "available", ".\n"
);
print $OUT
"\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
} ## end else [ if ($term_pid eq '-1')
} ## end unless ($runnonstop)
} ## end else [ if ($notty)
# XXX This looks like a bug to me.
# Why copy to @ARGS and then futz with @args?
@ARGS = @ARGV;
for (@args) {
# Make sure backslashes before single quotes are stripped out, and
# keep args unless they are numeric (XXX why?)
# s/\'/\\\'/g; # removed while not justified understandably
# s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto
}
# If there was an afterinit() sub defined, call it. It will get
# executed in our scope, so it can fiddle with debugger globals.
if ( defined &afterinit ) { # May be defined in $rcfile
&afterinit();
}
# Inform us about "Stack dump during die enabled ..." in dieLevel().
$I_m_init = 1;
############################################################ Subroutines
=head1 SUBROUTINES
=head2 DB
This gigantic subroutine is the heart of the debugger. Called before every
statement, its job is to determine if a breakpoint has been reached, and
stop if so; read commands from the user, parse them, and execute
them, and hen 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 C<$cmd> variable
to create other commands to be executed later. This is all highly I
but can be confusing. Check the comments for each C<$cmd ... && do {}> to
see what's happening in any given command.
=cut
sub DB {
# lock the debugger and get the thread id for the prompt
lock($DBGR);
my $tid;
if ($ENV{PERL5DB_THREADED}) {
$tid = eval { "[".threads->tid."]" };
}
# Check for whether we should be running continuously or not.
# _After_ the perl program is compiled, $single is set to 1:
if ( $single and not $second_time++ ) {
# Options say run non-stop. Run until we get an interrupt.
if ($runnonstop) { # Disable until signal
# If there's any call stack in place, turn off single
# stepping into subs throughout the stack.
for ( $i = 0 ; $i <= $stack_depth ; ) {
$stack[ $i++ ] &= ~1;
}
# And we are now no longer in single-step mode.
$single = 0;
# If we simply returned at this point, we wouldn't get
# the trace info. Fall on through.
# return;
} ## end if ($runnonstop)
elsif ($ImmediateStop) {
# We are supposed to stop here; XXX probably a break.
$ImmediateStop = 0; # We've processed it; turn it off
$signal = 1; # Simulate an interrupt to force
# us into the command loop
}
} ## end if ($single and not $second_time...
# If we're in single-step mode, or an interrupt (real or fake)
# has occurred, turn off non-stop mode.
$runnonstop = 0 if $single or $signal;
# Preserve current values of $@, $!, $^E, $,, $/, $\, $^W.
# The code being debugged may have altered them.
&save;
# Since DB::DB gets called after every line, we can use caller() to
# figure out where we last were executing. Sneaky, eh? This works because
# caller is returning all the extra information when called from the
# debugger.
local ( $package, $filename, $line ) = caller;
local $filename_ini = $filename;
# set up the context for DB::eval, so it can properly execute
# code on behalf of the user. We add the package in so that the
# code is eval'ed in the proper package (not in the debugger!).
local $usercontext =
'($@, $!, $^E, $,, $/, $\, $^W) = @saved;' . "package $package;";
# Create an alias to the active file magical array to simplify
# the code here.
local (*dbline) = $main::{ '_<' . $filename };
# we need to check for pseudofiles on Mac OS (these are files
# not attached to a filename, but instead stored in Dev:Pseudo)
if ( $^O eq 'MacOS' && $#dbline < 0 ) {
$filename_ini = $filename = 'Dev:Pseudo';
*dbline = $main::{ '_<' . $filename };
}
# Last line in the program.
local $max = $#dbline;
# if we have something here, see if we should break.
if ( $dbline{$line}
&& ( ( $stop, $action ) = split( /\0/, $dbline{$line} ) ) )
{
# Stop if the stop criterion says to just stop.
if ( $stop eq '1' ) {
$signal |= 1;
}
# It's a conditional stop; eval it in the user's context and
# see if we should stop. If so, remove the one-time sigil.
elsif ($stop) {
$evalarg = "\$DB::signal |= 1 if do {$stop}";
&eval;
$dbline{$line} =~ s/;9($|\0)/$1/;
}
} ## end if ($dbline{$line} && ...
# Preserve the current stop-or-not, and see if any of the W
# (watch expressions) has changed.
my $was_signal = $signal;
# If we have any watch expressions ...
if ( $trace & 2 ) {
for ( my $n = 0 ; $n <= $#to_watch ; $n++ ) {
$evalarg = $to_watch[$n];
local $onetimeDump; # Tell DB::eval() to not output results
# Fix context DB::eval() wants to return an array, but
# we need a scalar here.
my ($val) = join( "', '", &eval );
$val = ( ( defined $val ) ? "'$val'" : 'undef' );
# Did it change?
if ( $val ne $old_watch[$n] ) {
# Yep! Show the difference, and fake an interrupt.
$signal = 1;
print $OUT <
C is a function that can be defined by the user; it is a
function which will be run on each entry to C; it gets the
current package, filename, and line as its parameters.
The watchfunction can do anything it likes; it is executing in the
debugger's context, so it has access to all of the debugger's internal
data structures and functions.
C can control the debugger's actions. Any of the following
will cause the debugger to return control to the user's program after
C executes:
=over 4
=item *
Returning a false value from the C itself.
=item *
Altering C<$single> to a false value.
=item *
Altering C<$signal> to a false value.
=item *
Turning off the C<4> bit in C<$trace> (this also disables the
check for C. This can be done with
$trace &= ~4;
=back
=cut
# If there's a user-defined DB::watchfunction, call it with the
# current package, filename, and line. The function executes in
# the DB:: package.
if ( $trace & 4 ) { # User-installed watch
return
if watchfunction( $package, $filename, $line )
and not $single
and not $was_signal
and not( $trace & ~4 );
} ## end if ($trace & 4)
# Pick up any alteration to $signal in the watchfunction, and
# turn off the signal now.
$was_signal = $signal;
$signal = 0;
=head2 GETTING READY TO EXECUTE COMMANDS
The debugger decides to take control if single-step mode is on, the
C 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.
=cut
# Check to see if we should grab control ($single true,
# trace set appropriately, or we got a signal).
if ( $single || ( $trace & 1 ) || $was_signal ) {
# Yes, grab control.
if ($slave_editor) {
# Tell the editor to update its position.
$position = "\032\032$filename:$line:0\n";
print_lineinfo($position);
}
=pod
Special check: if we're in package C, we've gone through the
C block at least once. We set up everything so that we can continue
to enter commands and have a valid context to be in.
=cut
elsif ( $package eq 'DB::fake' ) {
# Fallen off the end already.
$term || &setterm;
print_help(< to quit or B to restart,
use B I to avoid stopping after program termination,
B, B or B to get additional info.
EOP
# Set the DB::eval context appropriately.
$package = 'main';
$usercontext =
'($@, $!, $^E, $,, $/, $\, $^W) = @saved;'
. "package $package;"; # this won't let them modify, alas
} ## end elsif ($package eq 'DB::fake')
=pod
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.
=cut
else {
# Still somewhere in the midst of execution. Set up the
# debugger prompt.
$sub =~ s/\'/::/; # Swap Perl 4 package separators (') to
# Perl 5 ones (sorry, we don't print Klingon
#module names)
$prefix = $sub =~ /::/ ? "" : "${'package'}::";
$prefix .= "$sub($filename:";
$after = ( $dbline[$line] =~ /\n$/ ? '' : "\n" );
# Break up the prompt if it's really long.
if ( length($prefix) > 30 ) {
$position = "$prefix$line):\n$line:\t$dbline[$line]$after";
$prefix = "";
$infix = ":\t";
}
else {
$infix = "):\t";
$position = "$prefix$line$infix$dbline[$line]$after";
}
# Print current line info, indenting if necessary.
if ($frame) {
print_lineinfo( ' ' x $stack_depth,
"$line:\t$dbline[$line]$after" );
}
else {
print_lineinfo($position);
}
# Scan forward, stopping at either the end or the next
# unbreakable line.
for ( $i = $line + 1 ; $i <= $max && $dbline[$i] == 0 ; ++$i )
{ #{ vi
# Drop out on null statements, block closers, and comments.
last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
# Drop out if the user interrupted us.
last if $signal;
# Append a newline if the line doesn't have one. Can happen
# in eval'ed text, for instance.
$after = ( $dbline[$i] =~ /\n$/ ? '' : "\n" );
# Next executable line.
$incr_pos = "$prefix$i$infix$dbline[$i]$after";
$position .= $incr_pos;
if ($frame) {
# Print it indented if tracing is on.
print_lineinfo( ' ' x $stack_depth,
"$i:\t$dbline[$i]$after" );
}
else {
print_lineinfo($incr_pos);
}
} ## end for ($i = $line + 1 ; $i...
} ## end else [ if ($slave_editor)
} ## end if ($single || ($trace...
=pod
If there's an action to be executed for the line we stopped at, execute it.
If there are any preprompt actions, execute those as well.
=cut
# If there's an action, do it now.
$evalarg = $action, &eval if $action;
# Are we nested another level (e.g., did we evaluate a function
# that had a breakpoint in it at the debugger prompt)?
if ( $single || $was_signal ) {
# Yes, go down a level.
local $level = $level + 1;
# Do any pre-prompt actions.
foreach $evalarg (@$pre) {
&eval;
}
# Complain about too much recursion if we passed the limit.
print $OUT $stack_depth . " levels deep in subroutine calls!\n"
if $single & 4;
# The line we're currently on. Set $incr to -1 to stay here
# until we get a command that tells us to advance.
$start = $line;
$incr = -1; # for backward motion.
# Tack preprompt debugger actions ahead of any actual input.
@typeahead = ( @$pretype, @typeahead );
=head2 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. This is done via the C<$incr>, C<$start>, and C<$max> variables.
C<$incr> controls by how many lines the I line should move forward
after a command is executed. If set to -1, this indicates that the I
line shouldn't change.
C<$start> is the I line. It is used for things like knowing where to
move forwards or backwards from when doing an C or C<-> command.
C<$max> tells the debugger where the last line of the current file is. It's
used to terminate loops most often.
=head2 THE COMMAND LOOP
Most of C is actually a command parsing and dispatch loop. It comes
in two parts:
=over 4
=item *
The outer part of the loop, starting at the C label. This loop
reads a command and then executes it.
=item *
The inner part of the loop, starting at the C label. This part
is wholly contained inside the C block and only executes a command.
Used to handle commands running inside a pager.
=back
So why have two labels to restart the loop? Because sometimes, it's easier to
have a command I another command and then re-execute the loop to do
the new command. This is faster, but perhaps a bit more convoluted.
=cut
# The big command dispatch loop. It keeps running until the
# user yields up control again.
#
# If we have a terminal for input, and we get something back
# from readline(), keep on processing.
CMD:
while (
# We have a terminal, or can get one ...
( $term || &setterm ),
# ... and it belogs to this PID or we get one for this PID ...
( $term_pid == $$ or resetterm(1) ),
# ... and we got a line of command input ...
defined(
$cmd = &readline(
"$pidprompt $tid DB"
. ( '<' x $level )
. ( $#hist + 1 )
. ( '>' x $level ) . " "
)
)
)
{
share($cmd);
# ... try to execute the input as debugger commands.
# Don't stop running.
$single = 0;
# No signal is active.
$signal = 0;
# Handle continued commands (ending with \):
$cmd =~ s/\\$/\n/ && do {
$cmd .= &readline(" cont: ");
redo CMD;
};
=head4 The null command
A newline entered by itself means I. We grab the
command out of C<$laststep> (where it was recorded previously), and copy it
back into C<$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.
=cut
# Empty input means repeat the last command.
$cmd =~ /^$/ && ( $cmd = $laststep );
chomp($cmd); # get rid of the annoying extra newline
push( @hist, $cmd ) if length($cmd) > 1;
push( @truehist, $cmd );
share(@hist);
share(@truehist);
# This is a restart point for commands that didn't arrive
# via direct user input. It allows us to 'redo PIPE' to
# re-execute command processing without reading a new command.
PIPE: {
$cmd =~ s/^\s+//s; # trim annoying leading whitespace
$cmd =~ s/\s+$//s; # trim annoying trailing whitespace
($i) = split( /\s+/, $cmd );
=head3 COMMAND ALIASES
The debugger can create aliases for commands (these are stored in the
C<%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.
=cut
# See if there's an alias for the command, and set it up if so.
if ( $alias{$i} ) {
# Squelch signal handling; we want to keep control here
# if something goes loco during the alias eval.
local $SIG{__DIE__};
local $SIG{__WARN__};
# This is a command, so we eval it in the DEBUGGER's
# scope! Otherwise, we can't see the special debugger
# variables, or get to the debugger's subs. (Well, we
# _could_, but why make it even more complicated?)
eval "\$cmd =~ $alias{$i}";
if ($@) {
local $\ = '';
print $OUT "Couldn't evaluate `$i' alias: $@";
next CMD;
}
} ## end if ($alias{$i})
=head3 MAIN-LINE COMMANDS
All of these commands work up to and after the program being debugged has
terminated.
=head4 C - quit
Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't
try to execute further, cleaning any restart-related stuff out of the
environment, and executing with the last value of C<$?>.
=cut
$cmd =~ /^q$/ && do {
$fall_off_end = 1;
clean_ENV();
exit $?;
};
=head4 C - trace
Turn tracing on or off. Inverts the appropriate bit in C<$trace> (q.v.).
=cut
$cmd =~ /^t$/ && do {
$trace ^= 1;
local $\ = '';
print $OUT "Trace = "
. ( ( $trace & 1 ) ? "on" : "off" ) . "\n";
next CMD;
};
=head4 C - list subroutines matching/not matching a pattern
Walks through C<%sub>, checking to see whether or not to print the name.
=cut
$cmd =~ /^S(\s+(!)?(.+))?$/ && do {
$Srev = defined $2; # Reverse scan?
$Spatt = $3; # The pattern (if any) to use.
$Snocheck = !defined $1; # No args - print all subs.
# Need to make these sane here.
local $\ = '';
local $, = '';
# Search through the debugger's magical hash of subs.
# If $nocheck is true, just print the sub name.
# Otherwise, check it against the pattern. We then use
# the XOR trick to reverse the condition as required.
foreach $subname ( sort( keys %sub ) ) {
if ( $Snocheck or $Srev ^ ( $subname =~ /$Spatt/ ) ) {
print $OUT $subname, "\n";
}
}
next CMD;
};
=head4 C - list variables in current package
Since the C command actually processes this, just change this to the
appropriate C command and fall through.
=cut
$cmd =~ s/^X\b/V $package/;
=head4 C - list variables
Uses C to dump out the current values for selected variables.
=cut
# Bare V commands get the currently-being-debugged package
# added.
$cmd =~ /^V$/ && do {
$cmd = "V $package";
};
# V - show variables in package.
$cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
# Save the currently selected filehandle and
# force output to debugger's filehandle (dumpvar
# just does "print" for output).
local ($savout) = select($OUT);
# Grab package name and variables to dump.
$packname = $1;
@vars = split( ' ', $2 );
# If main::dumpvar isn't here, get it.
do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
if ( defined &main::dumpvar ) {
# We got it. Turn off subroutine entry/exit messages
# for the moment, along with return values.
local $frame = 0;
local $doret = -2;
# must detect sigpipe failures - not catching
# then will cause the debugger to die.
eval {
&main::dumpvar(
$packname,
defined $option{dumpDepth}
? $option{dumpDepth}
: -1, # assume -1 unless specified
@vars
);
};
# The die doesn't need to include the $@, because
# it will automatically get propagated for us.
if ($@) {
die unless $@ =~ /dumpvar print failed/;
}
} ## end if (defined &main::dumpvar)
else {
# Couldn't load dumpvar.
print $OUT "dumpvar.pl not available.\n";
}
# Restore the output filehandle, and go round again.
select($savout);
next CMD;
};
=head4 C - evaluate and print an expression
Hands the expression off to C, setting it up to print the value
via C instead of just printing it directly.
=cut
$cmd =~ s/^x\b/ / && do { # Remainder gets done by DB::eval()
$onetimeDump = 'dump'; # main::dumpvar shows the output
# handle special "x 3 blah" syntax XXX propagate
# doc back to special variables.
if ( $cmd =~ s/^\s*(\d+)(?=\s)/ / ) {
$onetimedumpDepth = $1;
}
};
=head4 C - print methods
Just uses C to determine what methods are available.
=cut
$cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
methods($1);
next CMD;
};
# m expr - set up DB::eval to do the work
$cmd =~ s/^m\b/ / && do { # Rest gets done by DB::eval()
$onetimeDump = 'methods'; # method output gets used there
};
=head4 C - switch files
=cut
$cmd =~ /^f\b\s*(.*)/ && do {
$file = $1;
$file =~ s/\s+$//;
# help for no arguments (old-style was return from sub).
if ( !$file ) {
print $OUT
"The old f command is now the r command.\n"; # hint
print $OUT "The new f command switches filenames.\n";
next CMD;
} ## end if (!$file)
# if not in magic file list, try a close match.
if ( !defined $main::{ '_<' . $file } ) {
if ( ($try) = grep( m#^_<.*$file#, keys %main:: ) ) {
{
$try = substr( $try, 2 );
print $OUT "Choosing $try matching `$file':\n";
$file = $try;
}
} ## end if (($try) = grep(m#^_<.*$file#...
} ## end if (!defined $main::{ ...
# If not successfully switched now, we failed.
if ( !defined $main::{ '_<' . $file } ) {
print $OUT "No file matching `$file' is loaded.\n";
next CMD;
}
# We switched, so switch the debugger internals around.
elsif ( $file ne $filename ) {
*dbline = $main::{ '_<' . $file };
$max = $#dbline;
$filename = $file;
$start = 1;
$cmd = "l";
} ## end elsif ($file ne $filename)
# We didn't switch; say we didn't.
else {
print $OUT "Already in $file.\n";
next CMD;
}
};
=head4 C<.> - return to last-executed line.
We set C<$incr> to -1 to indicate that the debugger shouldn't move ahead,
and then we look up the line in the magical C<%dbline> hash.
=cut
# . command.
$cmd =~ /^\.$/ && do {
$incr = -1; # stay at current line
# Reset everything to the old location.
$start = $line;
$filename = $filename_ini;
*dbline = $main::{ '_<' . $filename };
$max = $#dbline;
# Now where are we?
print_lineinfo($position);
next CMD;
};
=head4 C<-> - back one window
We change C<$start> to be one window back; if we go back past the first line,
we set it to be the first line. We ser C<$incr> to put us back at the
currently-executing line, and then put a C (list one window from
C<$start>) in C<$cmd> to be executed later.
=cut
# - - back a window.
$cmd =~ /^-$/ && do {
# back up by a window; go to 1 if back too far.
$start -= $incr + $window + 1;
$start = 1 if $start <= 0;
$incr = $window - 1;
# Generate and execute a "l +" command (handled below).
$cmd = 'l ' . ($start) . '+';
};
=head3 PRE-580 COMMANDS VS. NEW COMMANDS: C, EE, {, {{>
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. 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 C to
deal with them instead of processing them in-line.
=cut
# All of these commands were remapped in perl 5.8.0;
# we send them off to the secondary dispatcher (see below).
$cmd =~ /^([aAbBeEhilLMoOPvwW]\b|[<>\{]{1,2})\s*(.*)/so && do {
&cmd_wrapper( $1, $2, $line );
next CMD;
};
=head4 C - List lexicals in higher scope
Uses C to find the lexicals supplied as arguments in a scope
above the current one and then displays then using C.
=cut
$cmd =~ /^y(?:\s+(\d*)\s*(.*))?$/ && do {
# See if we've got the necessary support.
eval { require PadWalker; PadWalker->VERSION(0.08) }
or &warn(
$@ =~ /locate/
? "PadWalker module not found - please install\n"
: $@
)
and next CMD;
# Load up dumpvar if we don't have it. If we can, that is.
do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
defined &main::dumpvar
or print $OUT "dumpvar.pl not available.\n"
and next CMD;
# Got all the modules we need. Find them and print them.
my @vars = split( ' ', $2 || '' );
# Find the pad.
my $h = eval { PadWalker::peek_my( ( $1 || 0 ) + 1 ) };
# Oops. Can't find it.
$@ and $@ =~ s/ at .*//, &warn($@), next CMD;
# Show the desired vars with dumplex().
my $savout = select($OUT);
# Have dumplex dump the lexicals.
dumpvar::dumplex( $_, $h->{$_},
defined $option{dumpDepth} ? $option{dumpDepth} : -1,
@vars )
for sort keys %$h;
select($savout);
next CMD;
};
=head3 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.
=head4 C - single step, but don't trace down into subs
Done by setting C<$single> to 2, which forces subs to execute straight through
when entered (see C). We also save the C command in C<$laststep>,
so a null command knows what to re-execute.
=cut
# n - next
$cmd =~ /^n$/ && do {
end_report(), next CMD if $finished and $level <= 1;
# Single step, but don't enter subs.
$single = 2;
# Save for empty command (repeat last).
$laststep = $cmd;
last CMD;
};
=head4 C - single-step, entering subs
Sets C<$single> to 1, which causes C to continue tracing inside
subs. Also saves C as C<$lastcmd>.
=cut
# s - single step.
$cmd =~ /^s$/ && do {
# Get out and restart the command loop if program
# has finished.
end_report(), next CMD if $finished and $level <= 1;
# Single step should enter subs.
$single = 1;
# Save for empty command (repeat last).
$laststep = $cmd;
last CMD;
};
=head4 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 C<@dbline> and then turn off single-stepping
in this and all call levels above this one.
=cut
# c - start continuous execution.
$cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
# Hey, show's over. The debugged program finished
# executing already.
end_report(), next CMD if $finished and $level <= 1;
# Capture the place to put a one-time break.
$subname = $i = $1;
# Probably not needed, since we finish an interactive
# sub-session anyway...
# local $filename = $filename;
# local *dbline = *dbline; # XXX Would this work?!
#
# The above question wonders if localizing the alias
# to the magic array works or not. Since it's commented
# out, we'll just leave that to speculation for now.
# If the "subname" isn't all digits, we'll assume it
# is a subroutine name, and try to find it.
if ( $subname =~ /\D/ ) { # subroutine name
# Qualify it to the current package unless it's
# already qualified.
$subname = $package . "::" . $subname
unless $subname =~ /::/;
# find_sub will return "file:line_number" corresponding
# to where the subroutine is defined; we call find_sub,
# break up the return value, and assign it in one
# operation.
( $file, $i ) = ( find_sub($subname) =~ /^(.*):(.*)$/ );
# Force the line number to be numeric.
$i += 0;
# If we got a line number, we found the sub.
if ($i) {
# Switch all the debugger's internals around so
# we're actually working with that file.
$filename = $file;
*dbline = $main::{ '_<' . $filename };
# Mark that there's a breakpoint in this file.
$had_breakpoints{$filename} |= 1;
# Scan forward to the first executable line
# after the 'sub whatever' line.
$max = $#dbline;
++$i while $dbline[$i] == 0 && $i < $max;
} ## end if ($i)
# We didn't find a sub by that name.
else {
print $OUT "Subroutine $subname not found.\n";
next CMD;
}
} ## end if ($subname =~ /\D/)
# At this point, either the subname was all digits (an
# absolute line-break request) or we've scanned through
# the code following the definition of the sub, looking
# for an executable, which we may or may not have found.
#
# If $i (which we set $subname from) is non-zero, we
# got a request to break at some line somewhere. On
# one hand, if there wasn't any real subroutine name
# involved, this will be a request to break in the current
# file at the specified line, so we have to check to make
# sure that the line specified really is breakable.
#
# On the other hand, if there was a subname supplied, the
# preceding block has moved us to the proper file and
# location within that file, and then scanned forward
# looking for the next executable line. We have to make
# sure that one was found.
#
# On the gripping hand, we can't do anything unless the
# current value of $i points to a valid breakable line.
# Check that.
if ($i) {
# Breakable?
if ( $dbline[$i] == 0 ) {
print $OUT "Line $i not breakable.\n";
next CMD;
}
# Yes. Set up the one-time-break sigil.
$dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
} ## end if ($i)
# Turn off stack tracing from here up.
for ( $i = 0 ; $i <= $stack_depth ; ) {
$stack[ $i++ ] &= ~1;
}
last CMD;
};
=head4 C - return from a subroutine
For C 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 C is executed, set C<$doret>
appropriately, and force us out of the command loop.
=cut
# r - return from the current subroutine.
$cmd =~ /^r$/ && do {
# Can't do anythign if the program's over.
end_report(), next CMD if $finished and $level <= 1;
# Turn on stack trace.
$stack[$stack_depth] |= 1;
# Print return value unless the stack is empty.
$doret = $option{PrintRet} ? $stack_depth - 1 : -2;
last CMD;
};
=head4 C - stack trace
Just calls C.
=cut
$cmd =~ /^T$/ && do {
print_trace( $OUT, 1 ); # skip DB
next CMD;
};
=head4 C - List window around current line.
Just calls C.
=cut
$cmd =~ /^w\b\s*(.*)/s && do { &cmd_w( 'w', $1 ); next CMD; };
=head4 C - watch-expression processing.
Just calls C.
=cut
$cmd =~ /^W\b\s*(.*)/s && do { &cmd_W( 'W', $1 ); next CMD; };
=head4 C> - 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 C it and exit.
If not, we create some code to do the search and C it so it can't
mess us up.
=cut
$cmd =~ /^\/(.*)$/ && do {
# The pattern as a string.
$inpat = $1;
# Remove the final slash.
$inpat =~ s:([^\\])/$:$1:;
# If the pattern isn't null ...
if ( $inpat ne "" ) {
# Turn of warn and die procesing for a bit.
local $SIG{__DIE__};
local $SIG{__WARN__};
# Create the pattern.
eval '$inpat =~ m' . "\a$inpat\a";
if ( $@ ne "" ) {
# Oops. Bad pattern. No biscuit.
# Print the eval error and go back for more
# commands.
print $OUT "$@";
next CMD;
}
$pat = $inpat;
} ## end if ($inpat ne "")
# Set up to stop on wrap-around.
$end = $start;
# Don't move off the current line.
$incr = -1;
# Done in eval so nothing breaks if the pattern
# does something weird.
eval '
for (;;) {
# Move ahead one line.
++$start;
# Wrap if we pass the last line.
$start = 1 if ($start > $max);
# Stop if we have gotten back to this line again,
last if ($start == $end);
# A hit! (Note, though, that we are doing
# case-insensitive matching. Maybe a qr//
# expression would be better, so the user could
# do case-sensitive matching if desired.
if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
if ($slave_editor) {
# Handle proper escaping in the slave.
print $OUT "\032\032$filename:$start:0\n";
}
else {
# Just print the line normally.
print $OUT "$start:\t",$dbline[$start],"\n";
}
# And quit since we found something.
last;
}
} ';
# If we wrapped, there never was a match.
print $OUT "/$pat/: not found\n" if ( $start == $end );
next CMD;
};
=head4 C> - search backward for a string in the source
Same as for C>, except the loop runs backwards.
=cut
# ? - backward pattern search.
$cmd =~ /^\?(.*)$/ && do {
# Get the pattern, remove trailing question mark.
$inpat = $1;
$inpat =~ s:([^\\])\?$:$1:;
# If we've got one ...
if ( $inpat ne "" ) {
# Turn off die & warn handlers.
local $SIG{__DIE__};
local $SIG{__WARN__};
eval '$inpat =~ m' . "\a$inpat\a";
if ( $@ ne "" ) {
# Ouch. Not good. Print the error.
print $OUT $@;
next CMD;
}
$pat = $inpat;
} ## end if ($inpat ne "")
# Where we are now is where to stop after wraparound.
$end = $start;
# Don't move away from this line.
$incr = -1;
# Search inside the eval to prevent pattern badness
# from killing us.
eval '
for (;;) {
# Back up a line.
--$start;
# Wrap if we pass the first line.
$start = $max if ($start <= 0);
# Quit if we get back where we started,
last if ($start == $end);
# Match?
if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
if ($slave_editor) {
# Yep, follow slave editor requirements.
print $OUT "\032\032$filename:$start:0\n";
}
else {
# Yep, just print normally.
print $OUT "$start:\t",$dbline[$start],"\n";
}
# Found, so done.
last;
}
} ';
# Say we failed if the loop never found anything,
print $OUT "?$pat?: not found\n" if ( $start == $end );
next CMD;
};
=head4 C<$rc> - Recall command
Manages the commands in C<@hist> (which is created if C reports
that the terminal supports history). It find the the command required, puts it
into C<$cmd>, and redoes the loop to execute it.
=cut
# $rc - recall command.
$cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
# No arguments, take one thing off history.
pop(@hist) if length($cmd) > 1;
# Relative (- found)?
# Y - index back from most recent (by 1 if bare minus)
# N - go to that particular command slot or the last
# thing if nothing following.
$i = $1 ? ( $#hist - ( $2 || 1 ) ) : ( $2 || $#hist );
# Pick out the command desired.
$cmd = $hist[$i];
# Print the command to be executed and restart the loop
# with that command in the buffer.
print $OUT $cmd, "\n";
redo CMD;
};
=head4 C<$sh$sh> - C command
Calls the C to handle the command. This keeps the C and
C from getting messed up.
=cut
# $sh$sh - run a shell command (if it's all ASCII).
# Can't run shell commands with Unicode in the debugger, hmm.
$cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
# System it.
&system($1);
next CMD;
};
=head4 C<$rc I $rc> - Search command history
Another command to manipulate C<@hist>: this one searches it with a pattern.
If a command is found, it is placed in C<$cmd> and executed via C.
=cut
# $rc pattern $rc - find a command in the history.
$cmd =~ /^$rc([^$rc].*)$/ && do {
# Create the pattern to use.
$pat = "^$1";
# Toss off last entry if length is >1 (and it always is).
pop(@hist) if length($cmd) > 1;
# Look backward through the history.
for ( $i = $#hist ; $i ; --$i ) {
# Stop if we find it.
last if $hist[$i] =~ /$pat/;
}
if ( !$i ) {
# Never found it.
print $OUT "No such command!\n\n";
next CMD;
}
# Found it. Put it in the buffer, print it, and process it.
$cmd = $hist[$i];
print $OUT $cmd, "\n";
redo CMD;
};
=head4 C<$sh> - Invoke a shell
Uses C to invoke a shell.
=cut
# $sh - start a shell.
$cmd =~ /^$sh$/ && do {
# Run the user's shell. If none defined, run Bourne.
# We resume execution when the shell terminates.
&system( $ENV{SHELL} || "/bin/sh" );
next CMD;
};
=head4 C<$sh I> - Force execution of a command in a shell
Like the above, but the command is passed to the shell. Again, we use
C to avoid problems with C and C.
=cut
# $sh command - start a shell and run a command in it.
$cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
# XXX: using csh or tcsh destroys sigint retvals!
#&system($1); # use this instead
# use the user's shell, or Bourne if none defined.
&system( $ENV{SHELL} || "/bin/sh", "-c", $1 );
next CMD;
};
=head4 C - display commands in history
Prints the contents of C<@hist> (if any).
=cut
$cmd =~ /^H\b\s*\*/ && do {
@hist = @truehist = ();
print $OUT "History cleansed\n";
next CMD;
};
$cmd =~ /^H\b\s*(-(\d+))?/ && do {
# Anything other than negative numbers is ignored by
# the (incorrect) pattern, so this test does nothing.
$end = $2 ? ( $#hist - $2 ) : 0;
# Set to the minimum if less than zero.
$hist = 0 if $hist < 0;
# Start at the end of the array.
# Stay in while we're still above the ending value.
# Tick back by one each time around the loop.
for ( $i = $#hist ; $i > $end ; $i-- ) {
# Print the command unless it has no arguments.
print $OUT "$i: ", $hist[$i], "\n"
unless $hist[$i] =~ /^.?$/;
}
next CMD;
};
=head4 C - look up documentation
Just calls C to print the appropriate document.
=cut
# man, perldoc, doc - show manual pages.
$cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
runman($1);
next CMD;
};
=head4 C - print
Builds a C expression in the C<$cmd>; this will get executed at
the bottom of the loop.
=cut
# p - print (no args): print $_.
$cmd =~ s/^p$/print {\$DB::OUT} \$_/;
# p - print the given expression.
$cmd =~ s/^p\b/print {\$DB::OUT} /;
=head4 C<=> - define command alias
Manipulates C<%alias> to add or list command aliases.
=cut
# = - set up a command alias.
$cmd =~ s/^=\s*// && do {
my @keys;
if ( length $cmd == 0 ) {
# No args, get current aliases.
@keys = sort keys %alias;
}
elsif ( my ( $k, $v ) = ( $cmd =~ /^(\S+)\s+(\S.*)/ ) ) {
# Creating a new alias. $k is alias name, $v is
# alias value.
# can't use $_ or kill //g state
for my $x ( $k, $v ) {
# Escape "alarm" characters.
$x =~ s/\a/\\a/g;
}
# Substitute key for value, using alarm chars
# as separators (which is why we escaped them in
# the command).
$alias{$k} = "s\a$k\a$v\a";
# Turn off standard warn and die behavior.
local $SIG{__DIE__};
local $SIG{__WARN__};
# Is it valid Perl?
unless ( eval "sub { s\a$k\a$v\a }; 1" ) {
# Nope. Bad alias. Say so and get out.
print $OUT "Can't alias $k to $v: $@\n";
delete $alias{$k};
next CMD;
}
# We'll only list the new one.
@keys = ($k);
} ## end elsif (my ($k, $v) = ($cmd...
# The argument is the alias to list.
else {
@keys = ($cmd);
}
# List aliases.
for my $k (@keys) {
# Messy metaquoting: Trim the substiution code off.
# We use control-G as the delimiter because it's not
# likely to appear in the alias.
if ( ( my $v = $alias{$k} ) =~ ss\a$k\a(.*)\a$1 ) {
# Print the alias.
print $OUT "$k\t= $1\n";
}
elsif ( defined $alias{$k} ) {
# Couldn't trim it off; just print the alias code.
print $OUT "$k\t$alias{$k}\n";
}
else {
# No such, dude.
print "No alias for $k\n";
}
} ## end for my $k (@keys)
next CMD;
};
=head4 C - read commands from a file.
Opens a lexical filehandle and stacks it on C<@cmdfhs>; C will
pick it up.
=cut
# source - read commands from a file (or pipe!) and execute.
$cmd =~ /^source\s+(.*\S)/ && do {
if ( open my $fh, $1 ) {
# Opened OK; stick it in the list of file handles.
push @cmdfhs, $fh;
}
else {
# Couldn't open it.
&warn("Can't execute `$1': $!\n");
}
next CMD;
};
=head4 C - send current history to a file
Takes the complete history, (not the shrunken version you see with C),
and saves it to the given filename, so it can be replayed using C.
Note that all C<^(save|source)>'s are commented out with a view to minimise recursion.
=cut
# save source - write commands to a file for later use
$cmd =~ /^save\s*(.*)$/ && do {
my $file = $1 || '.perl5dbrc'; # default?
if ( open my $fh, "> $file" ) {
# chomp to remove extraneous newlines from source'd files
chomp( my @truelist =
map { m/^\s*(save|source)/ ? "#$_" : $_ }
@truehist );
print $fh join( "\n", @truelist );
print "commands saved in $file\n";
}
else {
&warn("Can't save debugger commands in '$1': $!\n");
}
next CMD;
};
=head4 C - restart
Restart the debugger session.
=head4 C - rerun the current session
Return to any given position in the B