This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Devel::Peek: Fix a couple of pod glitches
[perl5.git] / ext / Devel-Peek / Peek.pm
1 # Devel::Peek - A data debugging tool for the XS programmer
2 # The documentation is after the __END__
3
4 package Devel::Peek;
5
6 $VERSION = '1.24';
7 $XS_VERSION = $VERSION;
8 $VERSION = eval $VERSION;
9
10 require Exporter;
11 require XSLoader;
12
13 @ISA = qw(Exporter);
14 @EXPORT = qw(Dump mstat DeadCode DumpArray DumpWithOP DumpProg
15              fill_mstats mstats_fillhash mstats2hash runops_debug debug_flags);
16 @EXPORT_OK = qw(SvREFCNT CvGV);
17 %EXPORT_TAGS = ('ALL' => [@EXPORT, @EXPORT_OK]);
18
19 XSLoader::load();
20
21 sub import {
22   my $c = shift;
23   my $ops_rx = qr/^:opd(=[stP]*)?\b/;
24   my @db = grep m/$ops_rx/, @_;
25   @_ = grep !m/$ops_rx/, @_;
26   if (@db) {
27     die "Too many :opd options" if @db > 1;
28     runops_debug(1);
29     my $flags = ($db[0] =~ m/$ops_rx/ and $1);
30     $flags = 'st' unless defined $flags;
31     my $f = 0;
32     $f |= 2  if $flags =~ /s/;
33     $f |= 8  if $flags =~ /t/;
34     $f |= 64 if $flags =~ /P/;
35     $^D |= $f if $f;
36   }
37   unshift @_, $c;
38   goto &Exporter::import;
39 }
40
41 sub DumpWithOP ($;$) {
42    local($Devel::Peek::dump_ops)=1;
43    my $depth = @_ > 1 ? $_[1] : 4 ;
44    Dump($_[0],$depth);
45 }
46
47 $D_flags = 'psltocPmfrxuLHXDSTR';
48
49 sub debug_flags (;$) {
50   my $out = "";
51   for my $i (0 .. length($D_flags)-1) {
52     $out .= substr $D_flags, $i, 1 if $^D & (1<<$i);
53   }
54   my $arg = shift;
55   my $num = $arg;
56   if (defined $arg and $arg =~ /\D/) {
57     die "unknown flags in debug_flags()" if $arg =~ /[^-$D_flags]/;
58     my ($on,$off) = split /-/, "$arg-";
59     $num = $^D;
60     $num |=  (1<<index($D_flags, $_)) for split //, $on;
61     $num &= ~(1<<index($D_flags, $_)) for split //, $off;
62   }
63   $^D = $num if defined $arg;
64   $out
65 }
66
67 sub B::Deparse::pp_Devel_Peek_Dump {
68   my ($deparse,$op,$cx) = @_;
69   my @kids = $deparse->deparse($op->first, 6);
70   my $sib = $op->first->sibling;
71   if (ref $sib ne 'B::NULL') {
72     push @kids, $deparse->deparse($sib, 6);
73   }
74   return "Devel::Peek::Dump(" . join(", ", @kids) . ")";
75 }
76
77 1;
78 __END__
79
80 =head1 NAME
81
82 Devel::Peek - A data debugging tool for the XS programmer
83
84 =head1 SYNOPSIS
85
86         use Devel::Peek;
87         Dump( $a );
88         Dump( $a, 5 );
89         Dump( @a );
90         Dump( %h );
91         DumpArray( 5, $a, $b, ... );
92         mstat "Point 5";
93
94         use Devel::Peek ':opd=st';
95
96 =head1 DESCRIPTION
97
98 Devel::Peek contains functions which allows raw Perl datatypes to be
99 manipulated from a Perl script.  This is used by those who do XS programming
100 to check that the data they are sending from C to Perl looks as they think
101 it should look.  The trick, then, is to know what the raw datatype is
102 supposed to look like when it gets to Perl.  This document offers some tips
103 and hints to describe good and bad raw data.
104
105 It is very possible that this document will fall far short of being useful
106 to the casual reader.  The reader is expected to understand the material in
107 the first few sections of L<perlguts>.
108
109 Devel::Peek supplies a C<Dump()> function which can dump a raw Perl
110 datatype, and C<mstat("marker")> function to report on memory usage
111 (if perl is compiled with corresponding option).  The function
112 DeadCode() provides statistics on the data "frozen" into inactive
113 C<CV>.  Devel::Peek also supplies C<SvREFCNT()> which can query reference
114 counts on SVs.  This document will take a passive, and safe, approach
115 to data debugging and for that it will describe only the C<Dump()>
116 function.
117
118 All output is to STDERR.
119
120 The C<Dump()> function takes one or two arguments: something to dump, and
121 an optional limit for recursion and array elements (default is 4).  The
122 first argument is evaluted in rvalue scalar context, with exceptions for
123 @array and %hash, which dump the array or hash itself.  So C<Dump @array>
124 works, as does C<Dump $foo>.  And C<Dump pos> will call C<pos> in rvalue
125 context, whereas C<Dump ${\pos}> will call it in lvalue context.
126
127 Function C<DumpArray()> allows dumping of multiple values (useful when you
128 need to analyze returns of functions).
129
130 The global variable $Devel::Peek::pv_limit can be set to limit the
131 number of character printed in various string values.  Setting it to 0
132 means no limit.
133
134 If C<use Devel::Peek> directive has a C<:opd=FLAGS> argument,
135 this switches on debugging of opcode dispatch.  C<FLAGS> should be a
136 combination of C<s>, C<t>, and C<P> (see
137 L<< B<-D> flags in perlrun|perlrun/B<-D>I<letters> >>).
138
139 C<:opd> is a shortcut for C<:opd=st>.
140
141 =head2 Runtime debugging
142
143 C<CvGV($cv)> return one of the globs associated to a subroutine reference $cv.
144
145 debug_flags() returns a string representation of C<$^D> (similar to
146 what is allowed for B<-D> flag).  When called with a numeric argument,
147 sets $^D to the corresponding value.  When called with an argument of
148 the form C<"flags-flags">, set on/off bits of C<$^D> corresponding to
149 letters before/after C<->.  (The returned value is for C<$^D> before
150 the modification.)
151
152 runops_debug() returns true if the current I<opcode dispatcher> is the
153 debugging one.  When called with an argument, switches to debugging or
154 non-debugging dispatcher depending on the argument (active for
155 newly-entered subs/etc only).  (The returned value is for the dispatcher before the modification.)
156
157 =head2 Memory footprint debugging
158
159 When perl is compiled with support for memory footprint debugging
160 (default with Perl's malloc()), Devel::Peek provides an access to this API.
161
162 Use mstat() function to emit a memory state statistic to the terminal.
163 For more information on the format of output of mstat() see
164 L<perldebguts/Using $ENV{PERL_DEBUG_MSTATS}>.
165
166 Three additional functions allow access to this statistic from Perl.
167 First, use C<mstats_fillhash(%hash)> to get the information contained
168 in the output of mstat() into %hash. The field of this hash are
169
170   minbucket nbuckets sbrk_good sbrk_slack sbrked_remains sbrks
171   start_slack topbucket topbucket_ev topbucket_odd total total_chain
172   total_sbrk totfree
173
174 Two additional fields C<free>, C<used> contain array references which
175 provide per-bucket count of free and used chunks.  Two other fields
176 C<mem_size>, C<available_size> contain array references which provide
177 the information about the allocated size and usable size of chunks in
178 each bucket.  Again, see L<perldebguts/Using $ENV{PERL_DEBUG_MSTATS}>
179 for details.
180
181
182 Keep in mind that only the first several "odd-numbered" buckets are
183 used, so the information on size of the "odd-numbered" buckets which are
184 not used is probably meaningless.
185
186 The information in
187
188  mem_size available_size minbucket nbuckets
189
190 is the property of a particular build of perl, and does not depend on
191 the current process.  If you do not provide the optional argument to
192 the functions mstats_fillhash(), fill_mstats(), mstats2hash(), then
193 the information in fields C<mem_size>, C<available_size> is not
194 updated.
195
196 C<fill_mstats($buf)> is a much cheaper call (both speedwise and
197 memory-wise) which collects the statistic into $buf in
198 machine-readable form.  At a later moment you may need to call
199 C<mstats2hash($buf, %hash)> to use this information to fill %hash.
200
201 All three APIs C<fill_mstats($buf)>, C<mstats_fillhash(%hash)>, and
202 C<mstats2hash($buf, %hash)> are designed to allocate no memory if used
203 I<the second time> on the same $buf and/or %hash.
204
205 So, if you want to collect memory info in a cycle, you may call
206
207   $#buf = 999;
208   fill_mstats($_) for @buf;
209   mstats_fillhash(%report, 1);          # Static info too
210
211   foreach (@buf) {
212     # Do something...
213     fill_mstats $_;                     # Collect statistic
214   }
215   foreach (@buf) {
216     mstats2hash($_, %report);           # Preserve static info
217     # Do something with %report
218   }
219
220 =head1 EXAMPLES
221
222 The following examples don't attempt to show everything as that would be a
223 monumental task, and, frankly, we don't want this manpage to be an internals
224 document for Perl.  The examples do demonstrate some basics of the raw Perl
225 datatypes, and should suffice to get most determined people on their way.
226 There are no guidewires or safety nets, nor blazed trails, so be prepared to
227 travel alone from this point and on and, if at all possible, don't fall into
228 the quicksand (it's bad for business).
229
230 Oh, one final bit of advice: take L<perlguts> with you.  When you return we
231 expect to see it well-thumbed.
232
233 =head2 A simple scalar string
234
235 Let's begin by looking a simple scalar which is holding a string.
236
237         use Devel::Peek;
238         $a = 42; $a = "hello";
239         Dump $a;
240
241 The output:
242
243         SV = PVIV(0xbc288) at 0xbe9a8
244           REFCNT = 1
245           FLAGS = (POK,pPOK)
246           IV = 42
247           PV = 0xb2048 "hello"\0
248           CUR = 5
249           LEN = 8
250
251 This says C<$a> is an SV, a scalar.  The scalar type is a PVIV, which is
252 capable of holding an integer (IV) and/or a string (PV) value. The scalar's
253 head is allocated at address 0xbe9a8, while the body is at 0xbc288.
254 Its reference count is 1.  It has the C<POK> flag set, meaning its
255 current PV field is valid.  Because POK is set we look at the PV item
256 to see what is in the scalar.  The \0 at the end indicate that this
257 PV is properly NUL-terminated.
258 Note that the IV field still contains its old numeric value, but because
259 FLAGS doesn't have IOK set, we must ignore the IV item.
260 CUR indicates the number of characters in the PV.  LEN indicates the
261 number of bytes allocated for the PV (at least one more than CUR, because
262 LEN includes an extra byte for the end-of-string marker, then usually
263 rounded up to some efficient allocation unit).
264
265 =head2 A simple scalar number
266
267 If the scalar contains a number the raw SV will be leaner.
268
269         use Devel::Peek;
270         $a = 42;
271         Dump $a;
272
273 The output:
274
275         SV = IV(0xbc818) at 0xbe9a8
276           REFCNT = 1
277           FLAGS = (IOK,pIOK)
278           IV = 42
279
280 This says C<$a> is an SV, a scalar.  The scalar is an IV, a number.  Its
281 reference count is 1.  It has the C<IOK> flag set, meaning it is currently
282 being evaluated as a number.  Because IOK is set we look at the IV item to
283 see what is in the scalar.
284
285 =head2 A simple scalar with an extra reference
286
287 If the scalar from the previous example had an extra reference:
288
289         use Devel::Peek;
290         $a = 42;
291         $b = \$a;
292         Dump $a;
293
294 The output:
295
296         SV = IV(0xbe860) at 0xbe9a8
297           REFCNT = 2
298           FLAGS = (IOK,pIOK)
299           IV = 42
300
301 Notice that this example differs from the previous example only in its
302 reference count.  Compare this to the next example, where we dump C<$b>
303 instead of C<$a>.
304
305 =head2 A reference to a simple scalar
306
307 This shows what a reference looks like when it references a simple scalar.
308
309         use Devel::Peek;
310         $a = 42;
311         $b = \$a;
312         Dump $b;
313
314 The output:
315
316         SV = IV(0xf041c) at 0xbe9a0
317           REFCNT = 1
318           FLAGS = (ROK)
319           RV = 0xbab08
320           SV = IV(0xbe860) at 0xbe9a8
321             REFCNT = 2
322             FLAGS = (IOK,pIOK)
323             IV = 42
324
325 Starting from the top, this says C<$b> is an SV.  The scalar is an IV,
326 which is capable of holding an integer or reference value.
327 It has the C<ROK> flag set, meaning it is a reference (rather than an
328 integer or string).  Notice that Dump
329 follows the reference and shows us what C<$b> was referencing.  We see the
330 same C<$a> that we found in the previous example.
331
332 Note that the value of C<RV> coincides with the numbers we see when we
333 stringify $b. The addresses inside IV() are addresses of
334 C<X***> structures which hold the current state of an C<SV>. This
335 address may change during lifetime of an SV.
336
337 =head2 A reference to an array
338
339 This shows what a reference to an array looks like.
340
341         use Devel::Peek;
342         $a = [42];
343         Dump $a;
344
345 The output:
346
347         SV = IV(0xc85998) at 0xc859a8
348           REFCNT = 1
349           FLAGS = (ROK)
350           RV = 0xc70de8
351           SV = PVAV(0xc71e10) at 0xc70de8
352             REFCNT = 1
353             FLAGS = ()
354             ARRAY = 0xc7e820
355             FILL = 0
356             MAX = 0
357             ARYLEN = 0x0
358             FLAGS = (REAL)
359             Elt No. 0
360             SV = IV(0xc70f88) at 0xc70f98
361               REFCNT = 1
362               FLAGS = (IOK,pIOK)
363               IV = 42
364
365 This says C<$a> is a reference (ROK), which points to
366 another SV which is a PVAV, an array.  The array has one element,
367 element zero, which is another SV. The field C<FILL> above indicates
368 the last element in the array, similar to C<$#$a>.
369
370 If C<$a> pointed to an array of two elements then we would see the
371 following.
372
373         use Devel::Peek 'Dump';
374         $a = [42,24];
375         Dump $a;
376
377 The output:
378
379         SV = IV(0x158c998) at 0x158c9a8
380           REFCNT = 1
381           FLAGS = (ROK)
382           RV = 0x1577de8
383           SV = PVAV(0x1578e10) at 0x1577de8
384             REFCNT = 1
385             FLAGS = ()
386             ARRAY = 0x1585820
387             FILL = 1
388             MAX = 1
389             ARYLEN = 0x0
390             FLAGS = (REAL)
391             Elt No. 0
392             SV = IV(0x1577f88) at 0x1577f98
393               REFCNT = 1
394               FLAGS = (IOK,pIOK)
395               IV = 42
396             Elt No. 1
397             SV = IV(0x158be88) at 0x158be98
398               REFCNT = 1
399               FLAGS = (IOK,pIOK)
400               IV = 24
401
402 Note that C<Dump> will not report I<all> the elements in the array,
403 only several first (depending on how deep it already went into the
404 report tree).
405
406 =head2 A reference to a hash
407
408 The following shows the raw form of a reference to a hash.
409
410         use Devel::Peek;
411         $a = {hello=>42};
412         Dump $a;
413
414 The output:
415
416         SV = IV(0x8177858) at 0x816a618
417           REFCNT = 1
418           FLAGS = (ROK)
419           RV = 0x814fc10
420           SV = PVHV(0x8167768) at 0x814fc10
421             REFCNT = 1
422             FLAGS = (SHAREKEYS)
423             ARRAY = 0x816c5b8  (0:7, 1:1)
424             hash quality = 100.0%
425             KEYS = 1
426             FILL = 1
427             MAX = 7
428             RITER = -1
429             EITER = 0x0
430             Elt "hello" HASH = 0xc8fd181b
431             SV = IV(0x816c030) at 0x814fcf4
432               REFCNT = 1
433               FLAGS = (IOK,pIOK)
434               IV = 42
435
436 This shows C<$a> is a reference pointing to an SV.  That SV is a PVHV, a
437 hash. Fields RITER and EITER are used by C<L<perlfunc/each>>.
438
439 The "quality" of a hash is defined as the total number of comparisons needed
440 to access every element once, relative to the expected number needed for a
441 random hash. The value can go over 100%.
442
443 The total number of comparisons is equal to the sum of the squares of the
444 number of entries in each bucket.  For a random hash of C<<n>> keys into
445 C<<k>> buckets, the expected value is:
446
447                 n + n(n-1)/2k
448
449 =head2 Dumping a large array or hash
450
451 The C<Dump()> function, by default, dumps up to 4 elements from a
452 toplevel array or hash.  This number can be increased by supplying a
453 second argument to the function.
454
455         use Devel::Peek;
456         $a = [10,11,12,13,14];
457         Dump $a;
458
459 Notice that C<Dump()> prints only elements 10 through 13 in the above code.
460 The following code will print all of the elements.
461
462         use Devel::Peek 'Dump';
463         $a = [10,11,12,13,14];
464         Dump $a, 5;
465
466 =head2 A reference to an SV which holds a C pointer
467
468 This is what you really need to know as an XS programmer, of course.  When
469 an XSUB returns a pointer to a C structure that pointer is stored in an SV
470 and a reference to that SV is placed on the XSUB stack.  So the output from
471 an XSUB which uses something like the T_PTROBJ map might look something like
472 this:
473
474         SV = IV(0xf381c) at 0xc859a8
475           REFCNT = 1
476           FLAGS = (ROK)
477           RV = 0xb8ad8
478           SV = PVMG(0xbb3c8) at 0xc859a0
479             REFCNT = 1
480             FLAGS = (OBJECT,IOK,pIOK)
481             IV = 729160
482             NV = 0
483             PV = 0
484             STASH = 0xc1d10       "CookBookB::Opaque"
485
486 This shows that we have an SV which is a reference, which points at another
487 SV.  In this case that second SV is a PVMG, a blessed scalar.  Because it is
488 blessed it has the C<OBJECT> flag set.  Note that an SV which holds a C
489 pointer also has the C<IOK> flag set.  The C<STASH> is set to the package
490 name which this SV was blessed into.
491
492 The output from an XSUB which uses something like the T_PTRREF map, which
493 doesn't bless the object, might look something like this:
494
495         SV = IV(0xf381c) at 0xc859a8
496           REFCNT = 1
497           FLAGS = (ROK)
498           RV = 0xb8ad8
499           SV = PVMG(0xbb3c8) at 0xc859a0
500             REFCNT = 1
501             FLAGS = (IOK,pIOK)
502             IV = 729160
503             NV = 0
504             PV = 0
505
506 =head2 A reference to a subroutine
507
508 Looks like this:
509
510         SV = IV(0x24d2dd8) at 0x24d2de8
511           REFCNT = 1
512           FLAGS = (TEMP,ROK)
513           RV = 0x24e79d8
514           SV = PVCV(0x24e5798) at 0x24e79d8
515             REFCNT = 2
516             FLAGS = ()
517             COMP_STASH = 0x22c9c50      "main"
518             START = 0x22eed60 ===> 0
519             ROOT = 0x22ee490
520             GVGV::GV = 0x22de9d8        "MY" :: "top_targets"
521             FILE = "(eval 5)"
522             DEPTH = 0
523             FLAGS = 0x0
524             OUTSIDE_SEQ = 93
525             PADLIST = 0x22e9ed8
526             PADNAME = 0x22e9ec0(0x22eed00) PAD = 0x22e9ea8(0x22eecd0)
527             OUTSIDE = 0x22c9fb0 (MAIN)
528
529
530 This shows that 
531
532 =over 4
533
534 =item *
535
536 the subroutine is not an XSUB (since C<START> and C<ROOT> are
537 non-zero, and C<XSUB> is not listed, and is thus null);
538
539 =item *
540
541 that it was compiled in the package C<main>;
542
543 =item *
544
545 under the name C<MY::top_targets>; 
546
547 =item *
548
549 inside a 5th eval in the program;
550
551 =item *
552
553 it is not currently executed (because C<DEPTH> is 0);
554
555 =item *
556
557 it has no prototype (C<PROTOTYPE> field is missing).
558
559 =back
560
561 =head1 EXPORTS
562
563 C<Dump>, C<mstat>, C<DeadCode>, C<DumpArray>, C<DumpWithOP> and
564 C<DumpProg>, C<fill_mstats>, C<mstats_fillhash>, C<mstats2hash> by
565 default. Additionally available C<SvREFCNT>, C<SvREFCNT_inc> and
566 C<SvREFCNT_dec>.
567
568 =head1 BUGS
569
570 Readers have been known to skip important parts of L<perlguts>, causing much
571 frustration for all.
572
573 =head1 AUTHOR
574
575 Ilya Zakharevich        ilya@math.ohio-state.edu
576
577 Copyright (c) 1995-98 Ilya Zakharevich. All rights reserved.
578 This program is free software; you can redistribute it and/or
579 modify it under the same terms as Perl itself.
580
581 Author of this software makes no claim whatsoever about suitability,
582 reliability, edability, editability or usability of this product, and
583 should not be kept liable for any damage resulting from the use of
584 it. If you can use it, you are in luck, if not, I should not be kept
585 responsible. Keep a handy copy of your backup tape at hand.
586
587 =head1 SEE ALSO
588
589 L<perlguts>, and L<perlguts>, again.
590
591 =cut