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