📄 perldebug.pod
字号:
as well.
When a package is compiled, a line like this
Package lib/Carp.pm.
is printed with proper indentation.
=back
=head2 Debugging compile-time statements
If you have any compile-time executable statements (code within a BEGIN
block or a C<use> statement), these will C<NOT> be stopped by debugger,
although C<require>s will (and compile-time statements can be traced
with C<AutoTrace> option set in C<PERLDB_OPTS>). From your own Perl
code, however, you can
transfer control back to the debugger using the following statement,
which is harmless if the debugger is not running:
$DB::single = 1;
If you set C<$DB::single> to the value 2, it's equivalent to having
just typed the C<n> command, whereas a value of 1 means the C<s>
command. The C<$DB::trace> variable should be set to 1 to simulate
having typed the C<t> command.
Another way to debug compile-time code is to start debugger, set a
breakpoint on I<load> of some module thusly
DB<7> b load f:/perllib/lib/Carp.pm
Will stop on load of `f:/perllib/lib/Carp.pm'.
and restart debugger by C<R> command (if possible). One can use C<b
compile subname> for the same purpose.
=head2 Debugger Customization
Most probably you do not want to modify the debugger, it contains enough
hooks to satisfy most needs. You may change the behaviour of debugger
from the debugger itself, using C<O>ptions, from the command line via
C<PERLDB_OPTS> environment variable, and from I<customization files>.
You can do some customization by setting up a F<.perldb> file which
contains initialization code. For instance, you could make aliases
like these (the last one is one people expect to be there):
$DB::alias{'len'} = 's/^len(.*)/p length($1)/';
$DB::alias{'stop'} = 's/^stop (at|in)/b/';
$DB::alias{'ps'} = 's/^ps\b/p scalar /';
$DB::alias{'quit'} = 's/^quit(\s*)/exit\$/';
One changes options from F<.perldb> file via calls like this one;
parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
(the code is executed in the package C<DB>). Note that F<.perldb> is
processed before processing C<PERLDB_OPTS>. If F<.perldb> defines the
subroutine C<afterinit>, it is called after all the debugger
initialization ends. F<.perldb> may be contained in the current
directory, or in the C<LOGDIR>/C<HOME> directory.
If you want to modify the debugger, copy F<perl5db.pl> from the Perl
library to another name and modify it as necessary. You'll also want
to set your C<PERL5DB> environment variable to say something like this:
BEGIN { require "myperl5db.pl" }
As the last resort, one can use C<PERL5DB> to customize debugger by
directly setting internal variables or calling debugger functions.
=head2 Readline Support
As shipped, the only command line history supplied is a simplistic one
that checks for leading exclamation points. However, if you install
the Term::ReadKey and Term::ReadLine modules from CPAN, you will
have full editing capabilities much like GNU I<readline>(3) provides.
Look for these in the F<modules/by-module/Term> directory on CPAN.
A rudimentary command line completion is also available.
Unfortunately, the names of lexical variables are not available for
completion.
=head2 Editor Support for Debugging
If you have GNU B<emacs> installed on your system, it can interact with
the Perl debugger to provide an integrated software development
environment reminiscent of its interactions with C debuggers.
Perl is also delivered with a start file for making B<emacs> act like a
syntax-directed editor that understands (some of) Perl's syntax. Look in
the I<emacs> directory of the Perl source distribution.
(Historically, a similar setup for interacting with B<vi> and the
X11 window system had also been available, but at the time of this
writing, no debugger support for B<vi> currently exists.)
=head2 The Perl Profiler
If you wish to supply an alternative debugger for Perl to run, just
invoke your script with a colon and a package argument given to the B<-d>
flag. One of the most popular alternative debuggers for Perl is
B<DProf>, the Perl profiler. As of this writing, B<DProf> is not
included with the standard Perl distribution, but it is expected to
be included soon, for certain values of "soon".
Meanwhile, you can fetch the Devel::Dprof module from CPAN. Assuming
it's properly installed on your system, to profile your Perl program in
the file F<mycode.pl>, just type:
perl -d:DProf mycode.pl
When the script terminates the profiler will dump the profile information
to a file called F<tmon.out>. A tool like B<dprofpp> (also supplied with
the Devel::DProf package) can be used to interpret the information which is
in that profile.
=head2 Debugger support in perl
When you call the B<caller> function (see L<perlfunc/caller>) from the
package DB, Perl sets the array @DB::args to contain the arguments the
corresponding stack frame was called with.
If perl is run with B<-d> option, the following additional features
are enabled (cf. L<perlvar/$^P>):
=over
=item *
Perl inserts the contents of C<$ENV{PERL5DB}> (or C<BEGIN {require
'perl5db.pl'}> if not present) before the first line of the
application.
=item *
The array C<@{"_E<lt>$filename"}> is the line-by-line contents of
$filename for all the compiled files. Same for C<eval>ed strings which
contain subroutines, or which are currently executed. The C<$filename>
for C<eval>ed strings looks like C<(eval 34)>.
=item *
The hash C<%{"_E<lt>$filename"}> contains breakpoints and action (it is
keyed by line number), and individual entries are settable (as opposed
to the whole hash). Only true/false is important to Perl, though the
values used by F<perl5db.pl> have the form
C<"$break_condition\0$action">. Values are magical in numeric context:
they are zeros if the line is not breakable.
Same for evaluated strings which contain subroutines, or which are
currently executed. The $filename for C<eval>ed strings looks like
C<(eval 34)>.
=item *
The scalar C<${"_E<lt>$filename"}> contains C<"_E<lt>$filename">. Same for
evaluated strings which contain subroutines, or which are currently
executed. The $filename for C<eval>ed strings looks like C<(eval
34)>.
=item *
After each C<require>d file is compiled, but before it is executed,
C<DB::postponed(*{"_E<lt>$filename"})> is called (if subroutine
C<DB::postponed> exists). Here the $filename is the expanded name of
the C<require>d file (as found in values of %INC).
=item *
After each subroutine C<subname> is compiled existence of
C<$DB::postponed{subname}> is checked. If this key exists,
C<DB::postponed(subname)> is called (if subroutine C<DB::postponed>
exists).
=item *
A hash C<%DB::sub> is maintained, with keys being subroutine names,
values having the form C<filename:startline-endline>. C<filename> has
the form C<(eval 31)> for subroutines defined inside C<eval>s.
=item *
When execution of the application reaches a place that can have
a breakpoint, a call to C<DB::DB()> is performed if any one of
variables $DB::trace, $DB::single, or $DB::signal is true. (Note that
these variables are not C<local>izable.) This feature is disabled when
the control is inside C<DB::DB()> or functions called from it (unless
C<$^D & (1E<lt>E<lt>30)>).
=item *
When execution of the application reaches a subroutine call, a call
to C<&DB::sub>(I<args>) is performed instead, with C<$DB::sub> being
the name of the called subroutine. (Unless the subroutine is compiled
in the package C<DB>.)
=back
Note that if C<&DB::sub> needs some external data to be setup for it
to work, no subroutine call is possible until this is done. For the
standard debugger C<$DB::deep> (how many levels of recursion deep into
the debugger you can go before a mandatory break) gives an example of
such a dependency.
The minimal working debugger consists of one line
sub DB::DB {}
which is quite handy as contents of C<PERL5DB> environment
variable:
env "PERL5DB=sub DB::DB {}" perl -d your-script
Another (a little bit more useful) minimal debugger can be created
with the only line being
sub DB::DB {print ++$i; scalar <STDIN>}
This debugger would print the sequential number of encountered
statement, and would wait for your C<CR> to continue.
The following debugger is quite functional:
{
package DB;
sub DB {}
sub sub {print ++$i, " $sub\n"; &$sub}
}
It prints the sequential number of subroutine call and the name of the
called subroutine. Note that C<&DB::sub> should be compiled into the
package C<DB>.
=head2 Debugger Internals
At the start, the debugger reads your rc file (F<./.perldb> or
F<~/.perldb> under Unix), which can set important options. This file may
define a subroutine C<&afterinit> to be executed after the debugger is
initialized.
After the rc file is read, the debugger reads environment variable
PERLDB_OPTS and parses it as a rest of C<O ...> line in debugger prompt.
It also maintains magical internal variables, such as C<@DB::dbline>,
C<%DB::dbline>, which are aliases for C<@{"::_<current_file"}>
C<%{"::_<current_file"}>. Here C<current_file> is the currently
selected (with the debugger's C<f> command, or by flow of execution)
file.
Some functions are provided to simplify customization. See L<"Debugger
Customization"> for description of C<DB::parse_options(string)>. The
function C<DB::dump_trace(skip[, count])> skips the specified number
of frames, and returns a list containing info about the caller
frames (all if C<count> is missing). Each entry is a hash with keys
C<context> (C<$> or C<@>), C<sub> (subroutine name, or info about
eval), C<args> (C<undef> or a reference to an array), C<file>, and
C<line>.
The function C<DB::print_trace(FH, skip[, count[, short]])> prints
formatted info about caller frames. The last two functions may be
convenient as arguments to C<E<lt>>, C<E<lt>E<lt>> commands.
=head2 Other resources
You did try the B<-w> switch, didn't you?
=head2 BUGS
You cannot get the stack frame information or otherwise debug functions
that were not compiled by Perl, such as C or C++ extensions.
If you alter your @_ arguments in a subroutine (such as with B<shift>
or B<pop>, the stack backtrace will not show the original values.
=head1 Debugging Perl memory usage
Perl is I<very> frivolous with memory. There is a saying that to
estimate memory usage of Perl, assume a reasonable algorithm of
allocation, and multiply your estimages by 10. This is not absolutely
true, but may give you a good grasp of what happens.
Say, an integer cannot take less than 20 bytes of memory, a float
cannot take less than 24 bytes, a string cannot take less than 32
bytes (all these examples assume 32-bit architectures, the result are
much worse on 64-bit architectures). If a variable is accessed in two
of three different ways (which require an integer, a float, or a
string), the memory footprint may increase by another 20 bytes. A
sloppy malloc() implementation will make these numbers yet more.
On the opposite end of the scale, a declaration like
sub foo;
may take (on some versions of perl) up to 500 bytes of memory.
Off-the-cuff anecdotal estimates of a code bloat give a factor around
8. This means that the compiled form of reasonable (commented
indented etc.) code will take approximately 8 times more than the
disk space the code takes.
There are two Perl-specific ways to analyze the memory usage:
$ENV{PERL_DEBUG_MSTATS} and B<-DL> switch. First one is available
only if perl is compiled with Perl's malloc(), the second one only if
Perl compiled with C<-DDEBUGGING> (as with giving C<-D optimise=-g>
option to F<Configure>).
=head2 Using C<$ENV{PERL_DEBUG_MSTATS}>
If your perl is using Perl's malloc(), and compiled with correct
switches (this is the default), then it will print memory usage
statistics after compiling your code (if C<$ENV{PERL_DEBUG_MSTATS}> >
1), and before termination of the script (if
C<$ENV{PERL_DEBUG_MSTATS}> >= 1). The report format is similar to one
in the following example:
env PERL_DEBUG_MSTATS=2 perl -e "require Carp"
Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
14216 free: 130 117 28 7 9 0 2 2 1 0 0
437 61 36 0 5
60924 used: 125 137 161 55 7 8 6 16 2 0 1
74 109 304 84 20
Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
Memory allocation statistics after execution: (buckets 4(4)..8188(8192)
30888 free: 245 78 85 13 6 2 1 3 2 0 1
315 162 39 42 11
175816 used: 265 176 1112 111 26 22 11 27 2 1 1
196 178 1066 798 39
Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.
It is possible to ask for such a statistic at arbitrary moment by
usind Devel::Peek::mstats() (module Devel::Peek is available on CPAN).
Here is the explanation of different parts of the format:
=over
=item C<buckets SMALLEST(APPROX)..GREATEST(APPROX)>
Perl's malloc() uses bucketed allocations. Every request is rounded
up to the closest bucket size available, and a bucket of these size is
taken from the pool of the buckets of this size.
The above line describes limits of buckets currently in use. Each
bucket has two sizes: memory footprint, and the maximal size of user
data which may be put into this bucket. Say, in the above example the
smallest bucket is both sizes 4. The biggest bucket has usable size
8188, and the memory footprint 8192.
With debugging Perl some buckets may have negative usable size. This
means that these buckets cannot (and will not) be used. For greater
buckets the memory footprint may be one page greater than a power of
2. In such a case the corresponding power of two is printed instead
in the C<APPROX> field above.
=item Free/Used
The following 1 or 2 rows of numbers correspond to the number of
buckets of each size between C<SMALLEST> and C<GREATEST>. In the
first row the sizes (memory footprints) of buckets are powers of two
(or possibly one page greater). In the second row (if present) the
memory footprints of the buckets are between memory footprints of two
buckets "above".
Say, with the above example the memory footprints are (with current
algorith)
free: 8 16 32 64 128 256 512 1024 2048 4096 8192
4 12 24 48 80
With non-C<DEBUGGING> perl the buckets starting from C<128>-long ones
have 4-byte overhead, thus 8192-long bucket may take up to
8188-byte-long allocations.
=item C<Total sbrk(): SBRKed/SBRKs:CONTINUOUS>
The first two fields give the total amount of memory perl sbrk()ed,
and number of sbrk()s used. The third number is what perl thinks
about continuity of returned chunks. As far as this number is
positive, malloc() will assume that it is probable that sbrk() will
provide continuous memory.
The amounts sbrk()ed by external libraries is not counted.
=item C<pad: 0>
The amount of sbrk()ed memory needed to keep buckets aligned.
=item C<heads: 2192>
While memory overhead of bigger buckets is kept inside the bucket, for
smaller buckets it is kept in separate areas. This field gives the
total size of these areas.
=item C<chain: 0>
malloc() may want to subdivide a bigger bucket into smaller buckets.
If only a part of the deceased-bucket is left non-subdivided, the rest
is kept as an element of a linked list. This field gives the total
size of these chunks.
=item C<tail: 6144>
To minimize amount of sbrk()s malloc() asks for more memory. This
field gives the size of the yet-unused part, which is sbrk()ed, but
never touched.
=back
=head2 Example of using B<-DL> switch
Below we show how to analyse memory usage by
do 'lib/auto/POSIX/autosplit.ix';
The file in question contains a header and 146 lines similar to
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -