PATCH 5.6 perldebguts grammar cleanup
[p5sagit/p5-mst-13.2.git] / pod / perldebguts.pod
CommitLineData
055fd3a9 1=head1 NAME
2
3perldebguts - Guts of Perl debugging
4
5=head1 DESCRIPTION
6
7This is not the perldebug(1) manpage, which tells you how to use
8the debugger. This manpage describes low-level details ranging
9between difficult and impossible for anyone who isn't incredibly
10intimate with Perl's guts to understand. Caveat lector.
11
12=head1 Debugger Internals
13
14Perl has special debugging hooks at compile-time and run-time used
15to create debugging environments. These hooks are not to be confused
4375e838 16with the I<perl -Dxxx> command described in L<perlrun>, which is
17usable only if a special Perl is built per the instructions in the
055fd3a9 18F<INSTALL> podpage in the Perl source tree.
19
20For example, whenever you call Perl's built-in C<caller> function
21from the package DB, the arguments that the corresponding stack
106325ad 22frame was called with are copied to the @DB::args array. The
055fd3a9 23general mechanisms is enabled by calling Perl with the B<-d> switch, the
24following additional features are enabled (cf. L<perlvar/$^P>):
25
26=over
27
28=item *
29
30Perl inserts the contents of C<$ENV{PERL5DB}> (or C<BEGIN {require
31'perl5db.pl'}> if not present) before the first line of your program.
32
33=item *
34
aa0b556f 35Each array C<@{"_<$filename"}> holds the lines of $filename for a
36file compiled by Perl. The same for C<eval>ed strings that contain
055fd3a9 37subroutines, or which are currently being executed. The $filename
38for C<eval>ed strings looks like C<(eval 34)>. Code assertions
8894c26d 39in regexes look like C<(re_eval 19)>.
40
41Values in this array are magical in numeric context: they compare
42equal to zero only if the line is not breakable.
055fd3a9 43
44=item *
45
aa0b556f 46Each hash C<%{"_<$filename"}> contains breakpoints and actions keyed
055fd3a9 47by line number. Individual entries (as opposed to the whole hash)
48are settable. Perl only cares about Boolean true here, although
49the values used by F<perl5db.pl> have the form
8894c26d 50C<"$break_condition\0$action">.
055fd3a9 51
52The same holds for evaluated strings that contain subroutines, or
53which are currently being executed. The $filename for C<eval>ed strings
54looks like C<(eval 34)> or C<(re_eval 19)>.
55
56=item *
57
aa0b556f 58Each scalar C<${"_<$filename"}> contains C<"_<$filename">. This is
055fd3a9 59also the case for evaluated strings that contain subroutines, or
60which are currently being executed. The $filename for C<eval>ed
61strings looks like C<(eval 34)> or C<(re_eval 19)>.
62
63=item *
64
65After each C<require>d file is compiled, but before it is executed,
66C<DB::postponed(*{"_<$filename"})> is called if the subroutine
67C<DB::postponed> exists. Here, the $filename is the expanded name of
68the C<require>d file, as found in the values of %INC.
69
70=item *
71
72After each subroutine C<subname> is compiled, the existence of
73C<$DB::postponed{subname}> is checked. If this key exists,
74C<DB::postponed(subname)> is called if the C<DB::postponed> subroutine
75also exists.
76
77=item *
78
79A hash C<%DB::sub> is maintained, whose keys are subroutine names
80and whose values have the form C<filename:startline-endline>.
81C<filename> has the form C<(eval 34)> for subroutines defined inside
82C<eval>s, or C<(re_eval 19)> for those within regex code assertions.
83
84=item *
85
86When the execution of your program reaches a point that can hold a
87breakpoint, the C<DB::DB()> subroutine is called any of the variables
88$DB::trace, $DB::single, or $DB::signal is true. These variables
89are not C<local>izable. This feature is disabled when executing
90inside C<DB::DB()>, including functions called from it
91unless C<< $^D & (1<<30) >> is true.
92
93=item *
94
95When execution of the program reaches a subroutine call, a call to
96C<&DB::sub>(I<args>) is made instead, with C<$DB::sub> holding the
97name of the called subroutine. This doesn't happen if the subroutine
98was compiled in the C<DB> package.)
99
100=back
101
102Note that if C<&DB::sub> needs external data for it to work, no
103subroutine call is possible until this is done. For the standard
104debugger, the C<$DB::deep> variable (how many levels of recursion
105deep into the debugger you can go before a mandatory break) gives
106an example of such a dependency.
107
108=head2 Writing Your Own Debugger
109
110The minimal working debugger consists of one line
111
112 sub DB::DB {}
113
114which is quite handy as contents of C<PERL5DB> environment
115variable:
116
117 $ PERL5DB="sub DB::DB {}" perl -d your-script
118
119Another brief debugger, slightly more useful, could be created
120with only the line:
121
122 sub DB::DB {print ++$i; scalar <STDIN>}
123
124This debugger would print the sequential number of encountered
125statement, and would wait for you to hit a newline before continuing.
126
127The following debugger is quite functional:
128
129 {
130 package DB;
131 sub DB {}
132 sub sub {print ++$i, " $sub\n"; &$sub}
133 }
134
135It prints the sequential number of subroutine call and the name of the
136called subroutine. Note that C<&DB::sub> should be compiled into the
137package C<DB>.
138
139At the start, the debugger reads your rc file (F<./.perldb> or
140F<~/.perldb> under Unix), which can set important options. This file may
141define a subroutine C<&afterinit> to be executed after the debugger is
142initialized.
143
144After the rc file is read, the debugger reads the PERLDB_OPTS
145environment variable and parses this as the remainder of a C<O ...>
146line as one might enter at the debugger prompt.
147
148The debugger also maintains magical internal variables, such as
149C<@DB::dbline>, C<%DB::dbline>, which are aliases for
150C<@{"::_<current_file"}> C<%{"::_<current_file"}>. Here C<current_file>
151is the currently selected file, either explicitly chosen with the
152debugger's C<f> command, or implicitly by flow of execution.
153
154Some functions are provided to simplify customization. See
155L<perldebug/"Options"> for description of options parsed by
156C<DB::parse_options(string)>. The function C<DB::dump_trace(skip[,
157count])> skips the specified number of frames and returns a list
158containing information about the calling frames (all of them, if
106325ad 159C<count> is missing). Each entry is reference to a hash with
055fd3a9 160keys C<context> (either C<.>, C<$>, or C<@>), C<sub> (subroutine
161name, or info about C<eval>), C<args> (C<undef> or a reference to
162an array), C<file>, and C<line>.
163
164The function C<DB::print_trace(FH, skip[, count[, short]])> prints
165formatted info about caller frames. The last two functions may be
166convenient as arguments to C<< < >>, C<< << >> commands.
167
168Note that any variables and functions that are not documented in
169this manpages (or in L<perldebug>) are considered for internal
170use only, and as such are subject to change without notice.
171
172=head1 Frame Listing Output Examples
173
174The C<frame> option can be used to control the output of frame
175information. For example, contrast this expression trace:
176
177 $ perl -de 42
178 Stack dump during die enabled outside of evals.
179
180 Loading DB routines from perl5db.pl patch level 0.94
181 Emacs support available.
182
183 Enter h or `h h' for help.
184
185 main::(-e:1): 0
186 DB<1> sub foo { 14 }
187
188 DB<2> sub bar { 3 }
189
190 DB<3> t print foo() * bar()
191 main::((eval 172):3): print foo() + bar();
192 main::foo((eval 168):2):
193 main::bar((eval 170):2):
194 42
195
196with this one, once the C<O>ption C<frame=2> has been set:
197
198 DB<4> O f=2
199 frame = '2'
200 DB<5> t print foo() * bar()
201 3: foo() * bar()
202 entering main::foo
203 2: sub foo { 14 };
204 exited main::foo
205 entering main::bar
206 2: sub bar { 3 };
207 exited main::bar
208 42
209
210By way of demonstration, we present below a laborious listing
211resulting from setting your C<PERLDB_OPTS> environment variable to
212the value C<f=n N>, and running I<perl -d -V> from the command line.
213Examples use various values of C<n> are shown to give you a feel
214for the difference between settings. Long those it may be, this
215is not a complete listing, but only excerpts.
216
217=over 4
218
219=item 1
220
221 entering main::BEGIN
222 entering Config::BEGIN
223 Package lib/Exporter.pm.
224 Package lib/Carp.pm.
225 Package lib/Config.pm.
226 entering Config::TIEHASH
227 entering Exporter::import
228 entering Exporter::export
229 entering Config::myconfig
230 entering Config::FETCH
231 entering Config::FETCH
232 entering Config::FETCH
233 entering Config::FETCH
234
235=item 2
236
237 entering main::BEGIN
238 entering Config::BEGIN
239 Package lib/Exporter.pm.
240 Package lib/Carp.pm.
241 exited Config::BEGIN
242 Package lib/Config.pm.
243 entering Config::TIEHASH
244 exited Config::TIEHASH
245 entering Exporter::import
246 entering Exporter::export
247 exited Exporter::export
248 exited Exporter::import
249 exited main::BEGIN
250 entering Config::myconfig
251 entering Config::FETCH
252 exited Config::FETCH
253 entering Config::FETCH
254 exited Config::FETCH
255 entering Config::FETCH
256
257=item 4
258
259 in $=main::BEGIN() from /dev/null:0
260 in $=Config::BEGIN() from lib/Config.pm:2
261 Package lib/Exporter.pm.
262 Package lib/Carp.pm.
263 Package lib/Config.pm.
264 in $=Config::TIEHASH('Config') from lib/Config.pm:644
265 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
266 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li
267 in @=Config::myconfig() from /dev/null:0
268 in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
269 in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
270 in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
271 in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
272 in $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574
273 in $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574
274
275=item 6
276
277 in $=main::BEGIN() from /dev/null:0
278 in $=Config::BEGIN() from lib/Config.pm:2
279 Package lib/Exporter.pm.
280 Package lib/Carp.pm.
281 out $=Config::BEGIN() from lib/Config.pm:0
282 Package lib/Config.pm.
283 in $=Config::TIEHASH('Config') from lib/Config.pm:644
284 out $=Config::TIEHASH('Config') from lib/Config.pm:644
285 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
286 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
287 out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
288 out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
289 out $=main::BEGIN() from /dev/null:0
290 in @=Config::myconfig() from /dev/null:0
291 in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
292 out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
293 in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
294 out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
295 in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
296 out $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
297 in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
298
299=item 14
300
301 in $=main::BEGIN() from /dev/null:0
302 in $=Config::BEGIN() from lib/Config.pm:2
303 Package lib/Exporter.pm.
304 Package lib/Carp.pm.
305 out $=Config::BEGIN() from lib/Config.pm:0
306 Package lib/Config.pm.
307 in $=Config::TIEHASH('Config') from lib/Config.pm:644
308 out $=Config::TIEHASH('Config') from lib/Config.pm:644
309 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
310 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
311 out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
312 out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
313 out $=main::BEGIN() from /dev/null:0
314 in @=Config::myconfig() from /dev/null:0
315 in $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
316 out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
317 in $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
318 out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
319
320=item 30
321
322 in $=CODE(0x15eca4)() from /dev/null:0
323 in $=CODE(0x182528)() from lib/Config.pm:2
324 Package lib/Exporter.pm.
325 out $=CODE(0x182528)() from lib/Config.pm:0
326 scalar context return from CODE(0x182528): undef
327 Package lib/Config.pm.
328 in $=Config::TIEHASH('Config') from lib/Config.pm:628
329 out $=Config::TIEHASH('Config') from lib/Config.pm:628
330 scalar context return from Config::TIEHASH: empty hash
331 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
332 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
333 out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
334 scalar context return from Exporter::export: ''
335 out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
336 scalar context return from Exporter::import: ''
337
338=back
339
340In all cases shown above, the line indentation shows the call tree.
341If bit 2 of C<frame> is set, a line is printed on exit from a
342subroutine as well. If bit 4 is set, the arguments are printed
343along with the caller info. If bit 8 is set, the arguments are
344printed even if they are tied or references. If bit 16 is set, the
345return value is printed, too.
346
347When a package is compiled, a line like this
348
349 Package lib/Carp.pm.
350
351is printed with proper indentation.
352
353=head1 Debugging regular expressions
354
355There are two ways to enable debugging output for regular expressions.
356
357If your perl is compiled with C<-DDEBUGGING>, you may use the
358B<-Dr> flag on the command line.
359
360Otherwise, one can C<use re 'debug'>, which has effects at
361compile time and run time. It is not lexically scoped.
362
363=head2 Compile-time output
364
365The debugging output at compile time looks like this:
366
367 compiling RE `[bc]d(ef*g)+h[ij]k$'
368 size 43 first at 1
369 1: ANYOF(11)
370 11: EXACT <d>(13)
371 13: CURLYX {1,32767}(27)
372 15: OPEN1(17)
373 17: EXACT <e>(19)
374 19: STAR(22)
375 20: EXACT <f>(0)
376 22: EXACT <g>(24)
377 24: CLOSE1(26)
378 26: WHILEM(0)
379 27: NOTHING(28)
380 28: EXACT <h>(30)
381 30: ANYOF(40)
382 40: EXACT <k>(42)
383 42: EOL(43)
384 43: END(0)
385 anchored `de' at 1 floating `gh' at 3..2147483647 (checking floating)
386 stclass `ANYOF' minlen 7
387
388The first line shows the pre-compiled form of the regex. The second
389shows the size of the compiled form (in arbitrary units, usually
3904-byte words) and the label I<id> of the first node that does a
391match.
392
393The last line (split into two lines above) contains optimizer
394information. In the example shown, the optimizer found that the match
395should contain a substring C<de> at offset 1, plus substring C<gh>
396at some offset between 3 and infinity. Moreover, when checking for
397these substrings (to abandon impossible matches quickly), Perl will check
398for the substring C<gh> before checking for the substring C<de>. The
399optimizer may also use the knowledge that the match starts (at the
400C<first> I<id>) with a character class, and the match cannot be
401shorter than 7 chars.
402
403The fields of interest which may appear in the last line are
404
405=over
406
407=item C<anchored> I<STRING> C<at> I<POS>
408
409=item C<floating> I<STRING> C<at> I<POS1..POS2>
410
411See above.
412
413=item C<matching floating/anchored>
414
415Which substring to check first.
416
417=item C<minlen>
418
419The minimal length of the match.
420
421=item C<stclass> I<TYPE>
422
423Type of first matching node.
424
425=item C<noscan>
426
427Don't scan for the found substrings.
428
429=item C<isall>
430
431Means that the optimizer info is all that the regular
432expression contains, and thus one does not need to enter the regex engine at
433all.
434
435=item C<GPOS>
436
437Set if the pattern contains C<\G>.
438
439=item C<plus>
440
441Set if the pattern starts with a repeated char (as in C<x+y>).
442
443=item C<implicit>
444
445Set if the pattern starts with C<.*>.
446
447=item C<with eval>
448
449Set if the pattern contain eval-groups, such as C<(?{ code })> and
450C<(??{ code })>.
451
452=item C<anchored(TYPE)>
453
454If the pattern may match only at a handful of places, (with C<TYPE>
455being C<BOL>, C<MBOL>, or C<GPOS>. See the table below.
456
457=back
458
459If a substring is known to match at end-of-line only, it may be
460followed by C<$>, as in C<floating `k'$>.
461
462The optimizer-specific info is used to avoid entering (a slow) regex
463engine on strings that will not definitely match. If C<isall> flag
464is set, a call to the regex engine may be avoided even when the optimizer
465found an appropriate place for the match.
466
467The rest of the output contains the list of I<nodes> of the compiled
468form of the regex. Each line has format
469
470C< >I<id>: I<TYPE> I<OPTIONAL-INFO> (I<next-id>)
471
472=head2 Types of nodes
473
474Here are the possible types, with short descriptions:
475
476 # TYPE arg-description [num-args] [longjump-len] DESCRIPTION
477
478 # Exit points
479 END no End of program.
480 SUCCEED no Return from a subroutine, basically.
481
482 # Anchors:
483 BOL no Match "" at beginning of line.
484 MBOL no Same, assuming multiline.
485 SBOL no Same, assuming singleline.
486 EOS no Match "" at end of string.
487 EOL no Match "" at end of line.
488 MEOL no Same, assuming multiline.
489 SEOL no Same, assuming singleline.
490 BOUND no Match "" at any word boundary
491 BOUNDL no Match "" at any word boundary
492 NBOUND no Match "" at any word non-boundary
493 NBOUNDL no Match "" at any word non-boundary
494 GPOS no Matches where last m//g left off.
495
496 # [Special] alternatives
497 ANY no Match any one character (except newline).
498 SANY no Match any one character.
499 ANYOF sv Match character in (or not in) this class.
500 ALNUM no Match any alphanumeric character
501 ALNUML no Match any alphanumeric char in locale
502 NALNUM no Match any non-alphanumeric character
503 NALNUML no Match any non-alphanumeric char in locale
504 SPACE no Match any whitespace character
505 SPACEL no Match any whitespace char in locale
506 NSPACE no Match any non-whitespace character
507 NSPACEL no Match any non-whitespace char in locale
508 DIGIT no Match any numeric character
509 NDIGIT no Match any non-numeric character
510
511 # BRANCH The set of branches constituting a single choice are hooked
512 # together with their "next" pointers, since precedence prevents
513 # anything being concatenated to any individual branch. The
514 # "next" pointer of the last BRANCH in a choice points to the
515 # thing following the whole choice. This is also where the
516 # final "next" pointer of each individual branch points; each
517 # branch starts with the operand node of a BRANCH node.
518 #
519 BRANCH node Match this alternative, or the next...
520
521 # BACK Normal "next" pointers all implicitly point forward; BACK
522 # exists to make loop structures possible.
523 # not used
524 BACK no Match "", "next" ptr points backward.
525
526 # Literals
527 EXACT sv Match this string (preceded by length).
528 EXACTF sv Match this string, folded (prec. by length).
529 EXACTFL sv Match this string, folded in locale (w/len).
530
531 # Do nothing
532 NOTHING no Match empty string.
533 # A variant of above which delimits a group, thus stops optimizations
534 TAIL no Match empty string. Can jump here from outside.
535
536 # STAR,PLUS '?', and complex '*' and '+', are implemented as circular
537 # BRANCH structures using BACK. Simple cases (one character
538 # per match) are implemented with STAR and PLUS for speed
539 # and to minimize recursive plunges.
540 #
541 STAR node Match this (simple) thing 0 or more times.
542 PLUS node Match this (simple) thing 1 or more times.
543
544 CURLY sv 2 Match this simple thing {n,m} times.
545 CURLYN no 2 Match next-after-this simple thing
546 # {n,m} times, set parens.
547 CURLYM no 2 Match this medium-complex thing {n,m} times.
548 CURLYX sv 2 Match this complex thing {n,m} times.
549
550 # This terminator creates a loop structure for CURLYX
551 WHILEM no Do curly processing and see if rest matches.
552
553 # OPEN,CLOSE,GROUPP ...are numbered at compile time.
554 OPEN num 1 Mark this point in input as start of #n.
555 CLOSE num 1 Analogous to OPEN.
556
557 REF num 1 Match some already matched string
558 REFF num 1 Match already matched string, folded
559 REFFL num 1 Match already matched string, folded in loc.
560
561 # grouping assertions
562 IFMATCH off 1 2 Succeeds if the following matches.
563 UNLESSM off 1 2 Fails if the following matches.
564 SUSPEND off 1 1 "Independent" sub-regex.
565 IFTHEN off 1 1 Switch, should be preceded by switcher .
566 GROUPP num 1 Whether the group matched.
567
568 # Support for long regex
569 LONGJMP off 1 1 Jump far away.
570 BRANCHJ off 1 1 BRANCH with long offset.
571
572 # The heavy worker
573 EVAL evl 1 Execute some Perl code.
574
575 # Modifiers
576 MINMOD no Next operator is not greedy.
577 LOGICAL no Next opcode should set the flag only.
578
579 # This is not used yet
580 RENUM off 1 1 Group with independently numbered parens.
581
582 # This is not really a node, but an optimized away piece of a "long" node.
583 # To simplify debugging output, we mark it as if it were a node
584 OPTIMIZED off Placeholder for dump.
585
586=head2 Run-time output
587
588First of all, when doing a match, one may get no run-time output even
589if debugging is enabled. This means that the regex engine was never
590entered and that all of the job was therefore done by the optimizer.
591
592If the regex engine was entered, the output may look like this:
593
594 Matching `[bc]d(ef*g)+h[ij]k$' against `abcdefg__gh__'
595 Setting an EVAL scope, savestack=3
596 2 <ab> <cdefg__gh_> | 1: ANYOF
597 3 <abc> <defg__gh_> | 11: EXACT <d>
598 4 <abcd> <efg__gh_> | 13: CURLYX {1,32767}
599 4 <abcd> <efg__gh_> | 26: WHILEM
600 0 out of 1..32767 cc=effff31c
601 4 <abcd> <efg__gh_> | 15: OPEN1
602 4 <abcd> <efg__gh_> | 17: EXACT <e>
603 5 <abcde> <fg__gh_> | 19: STAR
604 EXACT <f> can match 1 times out of 32767...
605 Setting an EVAL scope, savestack=3
606 6 <bcdef> <g__gh__> | 22: EXACT <g>
607 7 <bcdefg> <__gh__> | 24: CLOSE1
608 7 <bcdefg> <__gh__> | 26: WHILEM
609 1 out of 1..32767 cc=effff31c
610 Setting an EVAL scope, savestack=12
611 7 <bcdefg> <__gh__> | 15: OPEN1
612 7 <bcdefg> <__gh__> | 17: EXACT <e>
613 restoring \1 to 4(4)..7
614 failed, try continuation...
615 7 <bcdefg> <__gh__> | 27: NOTHING
616 7 <bcdefg> <__gh__> | 28: EXACT <h>
617 failed...
618 failed...
619
620The most significant information in the output is about the particular I<node>
621of the compiled regex that is currently being tested against the target string.
622The format of these lines is
623
624C< >I<STRING-OFFSET> <I<PRE-STRING>> <I<POST-STRING>> |I<ID>: I<TYPE>
625
626The I<TYPE> info is indented with respect to the backtracking level.
627Other incidental information appears interspersed within.
628
629=head1 Debugging Perl memory usage
630
631Perl is a profligate wastrel when it comes to memory use. There
632is a saying that to estimate memory usage of Perl, assume a reasonable
633algorithm for memory allocation, multiply that estimate by 10, and
634while you still may miss the mark, at least you won't be quite so
4375e838 635astonished. This is not absolutely true, but may provide a good
055fd3a9 636grasp of what happens.
637
638Assume that an integer cannot take less than 20 bytes of memory, a
639float cannot take less than 24 bytes, a string cannot take less
640than 32 bytes (all these examples assume 32-bit architectures, the
641result are quite a bit worse on 64-bit architectures). If a variable
642is accessed in two of three different ways (which require an integer,
643a float, or a string), the memory footprint may increase yet another
b9449ee0 64420 bytes. A sloppy malloc(3) implementation can inflate these
055fd3a9 645numbers dramatically.
646
647On the opposite end of the scale, a declaration like
648
649 sub foo;
650
651may take up to 500 bytes of memory, depending on which release of Perl
652you're running.
653
654Anecdotal estimates of source-to-compiled code bloat suggest an
655eightfold increase. This means that the compiled form of reasonable
656(normally commented, properly indented etc.) code will take
657about eight times more space in memory than the code took
658on disk.
659
660There are two Perl-specific ways to analyze memory usage:
661$ENV{PERL_DEBUG_MSTATS} and B<-DL> command-line switch. The first
662is available only if Perl is compiled with Perl's malloc(); the
663second only if Perl was built with C<-DDEBUGGING>. See the
664instructions for how to do this in the F<INSTALL> podpage at
665the top level of the Perl source tree.
666
667=head2 Using C<$ENV{PERL_DEBUG_MSTATS}>
668
669If your perl is using Perl's malloc() and was compiled with the
670necessary switches (this is the default), then it will print memory
4375e838 671usage statistics after compiling your code when C<< $ENV{PERL_DEBUG_MSTATS}
055fd3a9 672> 1 >>, and before termination of the program when C<<
673$ENV{PERL_DEBUG_MSTATS} >= 1 >>. The report format is similar to
674the following example:
675
676 $ PERL_DEBUG_MSTATS=2 perl -e "require Carp"
677 Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
678 14216 free: 130 117 28 7 9 0 2 2 1 0 0
679 437 61 36 0 5
680 60924 used: 125 137 161 55 7 8 6 16 2 0 1
681 74 109 304 84 20
682 Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
683 Memory allocation statistics after execution: (buckets 4(4)..8188(8192)
684 30888 free: 245 78 85 13 6 2 1 3 2 0 1
685 315 162 39 42 11
686 175816 used: 265 176 1112 111 26 22 11 27 2 1 1
687 196 178 1066 798 39
688 Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.
689
690It is possible to ask for such a statistic at arbitrary points in
b9449ee0 691your execution using the mstat() function out of the standard
055fd3a9 692Devel::Peek module.
693
694Here is some explanation of that format:
695
696=over
697
698=item C<buckets SMALLEST(APPROX)..GREATEST(APPROX)>
699
700Perl's malloc() uses bucketed allocations. Every request is rounded
701up to the closest bucket size available, and a bucket is taken from
702the pool of buckets of that size.
703
704The line above describes the limits of buckets currently in use.
705Each bucket has two sizes: memory footprint and the maximal size
706of user data that can fit into this bucket. Suppose in the above
707example that the smallest bucket were size 4. The biggest bucket
708would have usable size 8188, and the memory footprint would be 8192.
709
710In a Perl built for debugging, some buckets may have negative usable
711size. This means that these buckets cannot (and will not) be used.
712For larger buckets, the memory footprint may be one page greater
713than a power of 2. If so, case the corresponding power of two is
714printed in the C<APPROX> field above.
715
716=item Free/Used
717
718The 1 or 2 rows of numbers following that correspond to the number
719of buckets of each size between C<SMALLEST> and C<GREATEST>. In
720the first row, the sizes (memory footprints) of buckets are powers
721of two--or possibly one page greater. In the second row, if present,
722the memory footprints of the buckets are between the memory footprints
723of two buckets "above".
724
4375e838 725For example, suppose under the previous example, the memory footprints
055fd3a9 726were
727
728 free: 8 16 32 64 128 256 512 1024 2048 4096 8192
729 4 12 24 48 80
730
731With non-C<DEBUGGING> perl, the buckets starting from C<128> have
732a 4-byte overhead, and thus a 8192-long bucket may take up to
7338188-byte allocations.
734
735=item C<Total sbrk(): SBRKed/SBRKs:CONTINUOUS>
736
737The first two fields give the total amount of memory perl sbrk(2)ed
738(ess-broken? :-) and number of sbrk(2)s used. The third number is
739what perl thinks about continuity of returned chunks. So long as
740this number is positive, malloc() will assume that it is probable
741that sbrk(2) will provide continuous memory.
742
743Memory allocated by external libraries is not counted.
744
745=item C<pad: 0>
746
747The amount of sbrk(2)ed memory needed to keep buckets aligned.
748
749=item C<heads: 2192>
750
751Although memory overhead of bigger buckets is kept inside the bucket, for
752smaller buckets, it is kept in separate areas. This field gives the
753total size of these areas.
754
755=item C<chain: 0>
756
757malloc() may want to subdivide a bigger bucket into smaller buckets.
758If only a part of the deceased bucket is left unsubdivided, the rest
759is kept as an element of a linked list. This field gives the total
760size of these chunks.
761
762=item C<tail: 6144>
763
764To minimize the number of sbrk(2)s, malloc() asks for more memory. This
765field gives the size of the yet unused part, which is sbrk(2)ed, but
766never touched.
767
768=back
769
770=head2 Example of using B<-DL> switch
771
772Below we show how to analyse memory usage by
773
774 do 'lib/auto/POSIX/autosplit.ix';
775
776The file in question contains a header and 146 lines similar to
777
778 sub getcwd;
779
780B<WARNING>: The discussion below supposes 32-bit architecture. In
781newer releases of Perl, memory usage of the constructs discussed
782here is greatly improved, but the story discussed below is a real-life
783story. This story is mercilessly terse, and assumes rather more than cursory
784knowledge of Perl internals. Type space to continue, `q' to quit.
785(Actually, you just want to skip to the next section.)
786
787Here is the itemized list of Perl allocations performed during parsing
788of this file:
789
790 !!! "after" at test.pl line 3.
791 Id subtot 4 8 12 16 20 24 28 32 36 40 48 56 64 72 80 80+
792 0 02 13752 . . . . 294 . . . . . . . . . . 4
793 0 54 5545 . . 8 124 16 . . . 1 1 . . . . . 3
794 5 05 32 . . . . . . . 1 . . . . . . . .
795 6 02 7152 . . . . . . . . . . 149 . . . . .
796 7 02 3600 . . . . . 150 . . . . . . . . . .
797 7 03 64 . -1 . 1 . . 2 . . . . . . . . .
798 7 04 7056 . . . . . . . . . . . . . . . 7
799 7 17 38404 . . . . . . . 1 . . 442 149 . . 147 .
800 9 03 2078 17 249 32 . . . . 2 . . . . . . . .
801
802
803To see this list, insert two C<warn('!...')> statements around the call:
804
805 warn('!');
806 do 'lib/auto/POSIX/autosplit.ix';
807 warn('!!! "after"');
808
4375e838 809and run it with Perl's B<-DL> option. The first warn() will print
055fd3a9 810memory allocation info before parsing the file and will memorize
811the statistics at this point (we ignore what it prints). The second
812warn() prints increments with respect to these memorized data. This
813is the printout shown above.
814
815Different I<Id>s on the left correspond to different subsystems of
816the perl interpreter. They are just the first argument given to
817the perl memory allocation API named New(). To find what C<9 03>
818means, just B<grep> the perl source for C<903>. You'll find it in
819F<util.c>, function savepvn(). (I know, you wonder why we told you
820to B<grep> and then gave away the answer. That's because grepping
821the source is good for the soul.) This function is used to store
822a copy of an existing chunk of memory. Using a C debugger, one can
823see that the function was called either directly from gv_init() or
824via sv_magic(), and that gv_init() is called from gv_fetchpv()--which
825was itself called from newSUB(). Please stop to catch your breath now.
826
827B<NOTE>: To reach this point in the debugger and skip the calls to
828savepvn() during the compilation of the main program, you should
829set a C breakpoint
830in Perl_warn(), continue until this point is reached, and I<then> set
831a C breakpoint in Perl_savepvn(). Note that you may need to skip a
832handful of Perl_savepvn() calls that do not correspond to mass production
833of CVs (there are more C<903> allocations than 146 similar lines of
834F<lib/auto/POSIX/autosplit.ix>). Note also that C<Perl_> prefixes are
835added by macroization code in perl header files to avoid conflicts
836with external libraries.
837
838Anyway, we see that C<903> ids correspond to creation of globs, twice
839per glob - for glob name, and glob stringification magic.
840
841Here are explanations for other I<Id>s above:
842
843=over
844
845=item C<717>
846
4375e838 847Creates bigger C<XPV*> structures. In the case above, it
055fd3a9 848creates 3 C<AV>s per subroutine, one for a list of lexical variable
849names, one for a scratchpad (which contains lexical variables and
850C<targets>), and one for the array of scratchpads needed for
851recursion.
852
853It also creates a C<GV> and a C<CV> per subroutine, all called from
854start_subparse().
855
856=item C<002>
857
858Creates a C array corresponding to the C<AV> of scratchpads and the
859scratchpad itself. The first fake entry of this scratchpad is
860created though the subroutine itself is not defined yet.
861
862It also creates C arrays to keep data for the stash. This is one HV,
863but it grows; thus, there are 4 big allocations: the big chunks are not
864freed, but are kept as additional arenas for C<SV> allocations.
865
866=item C<054>
867
868Creates a C<HEK> for the name of the glob for the subroutine. This
869name is a key in a I<stash>.
870
871Big allocations with this I<Id> correspond to allocations of new
872arenas to keep C<HE>.
873
874=item C<602>
875
876Creates a C<GP> for the glob for the subroutine.
877
878=item C<702>
879
880Creates the C<MAGIC> for the glob for the subroutine.
881
882=item C<704>
883
884Creates I<arenas> which keep SVs.
885
886=back
887
888=head2 B<-DL> details
889
890If Perl is run with B<-DL> option, then warn()s that start with `!'
891behave specially. They print a list of I<categories> of memory
892allocations, and statistics of allocations of different sizes for
893these categories.
894
895If warn() string starts with
896
897=over
898
899=item C<!!!>
900
901print changed categories only, print the differences in counts of allocations.
902
903=item C<!!>
904
905print grown categories only; print the absolute values of counts, and totals.
906
907=item C<!>
908
909print nonempty categories, print the absolute values of counts and totals.
910
911=back
912
913=head2 Limitations of B<-DL> statistics
914
915If an extension or external library does not use the Perl API to
916allocate memory, such allocations are not counted.
917
918=head1 SEE ALSO
919
920L<perldebug>,
921L<perlguts>,
922L<perlrun>
923L<re>,
924and
925L<Devel::Dprof>.