3 # Copyright (c) 1996, 1997, 1998 Malcolm Beattie
5 # You may distribute under the terms of either the GNU General Public
6 # License or the Artistic License, as specified in the README file.
10 our $VERSION = '1.17';
16 # walkoptree_slow comes from B.pm (you are there),
17 # walkoptree comes from B.xs
18 @EXPORT_OK = qw(minus_c ppname save_BEGINs
19 class peekop cast_I32 cstring cchar hash threadsv_names
20 main_root main_start main_cv svref_2object opnumber
21 sub_generation amagic_generation perlstring
22 walkoptree_slow walkoptree walkoptree_exec walksymtable
23 parents comppadlist sv_undef compile_stats timing_info
24 begin_av init_av check_av end_av regex_padav dowarn defstash
25 curstash warnhook diehook inc_gv @optype @specialsv_name
27 push @EXPORT_OK, qw(unitcheck_av) if $] > 5.009;
31 @B::SV::ISA = 'B::OBJECT';
32 @B::NULL::ISA = 'B::SV';
33 @B::PV::ISA = 'B::SV';
34 @B::IV::ISA = 'B::SV';
35 @B::NV::ISA = 'B::SV';
36 @B::RV::ISA = 'B::SV';
37 @B::PVIV::ISA = qw(B::PV B::IV);
38 @B::PVNV::ISA = qw(B::PVIV B::NV);
39 @B::PVMG::ISA = 'B::PVNV';
40 # Change in the inheritance hierarchy post 5.9.0
41 @B::PVLV::ISA = $] > 5.009 ? 'B::GV' : 'B::PVMG';
42 # BM is eliminated post 5.9.5, but effectively is a specialisation of GV now.
43 @B::BM::ISA = $] > 5.009005 ? 'B::GV' : 'B::PVMG';
44 @B::AV::ISA = 'B::PVMG';
45 @B::GV::ISA = 'B::PVMG';
46 @B::HV::ISA = 'B::PVMG';
47 @B::CV::ISA = 'B::PVMG';
48 @B::IO::ISA = 'B::PVMG';
49 @B::FM::ISA = 'B::CV';
51 @B::OP::ISA = 'B::OBJECT';
52 @B::UNOP::ISA = 'B::OP';
53 @B::BINOP::ISA = 'B::UNOP';
54 @B::LOGOP::ISA = 'B::UNOP';
55 @B::LISTOP::ISA = 'B::BINOP';
56 @B::SVOP::ISA = 'B::OP';
57 @B::PADOP::ISA = 'B::OP';
58 @B::PVOP::ISA = 'B::OP';
59 @B::LOOP::ISA = 'B::LISTOP';
60 @B::PMOP::ISA = 'B::LISTOP';
61 @B::COP::ISA = 'B::OP';
63 @B::SPECIAL::ISA = 'B::OBJECT';
65 @B::optype = qw(OP UNOP BINOP LOGOP LISTOP PMOP SVOP PADOP PVOP LOOP COP);
66 # bytecode.pl contained the following comment:
67 # Nullsv *must* come first in the following so that the condition
68 # ($$sv == 0) can continue to be used to test (sv == Nullsv).
69 @B::specialsv_name = qw(Nullsv &PL_sv_undef &PL_sv_yes &PL_sv_no
70 (SV*)pWARN_ALL (SV*)pWARN_NONE (SV*)pWARN_STD);
73 # Stop "-w" from complaining about the lack of a real B::OBJECT class
78 my $name = (shift())->NAME;
80 # The regex below corresponds to the isCONTROLVAR macro
83 $name =~ s/^([\cA-\cZ\c\\c[\c]\c?\c_\c^])/"^".
84 chr( utf8::unicode_to_native( 64 ^ ord($1) ))/e;
86 # When we say unicode_to_native we really mean ascii_to_native,
87 # which matters iff this is a non-ASCII platform (EBCDIC).
92 sub B::IV::int_value {
94 return (($self->FLAGS() & SVf_IVisUV()) ? $self->UVX : $self->IV);
97 sub B::NULL::as_string() {""}
98 sub B::IV::as_string() {goto &B::IV::int_value}
99 sub B::PV::as_string() {goto &B::PV::PV}
106 my ($class, $value) = @_;
108 walkoptree_debug($value);
118 sub parents { \@parents }
123 return sprintf("%s (0x%x) %s", class($op), $$op, $op->name);
126 sub walkoptree_slow {
127 my($op, $method, $level) = @_;
128 $op_count++; # just for statistics
130 warn(sprintf("walkoptree: %d. %s\n", $level, peekop($op))) if $debug;
131 $op->$method($level) if $op->can($method);
132 if ($$op && ($op->flags & OPf_KIDS)) {
134 unshift(@parents, $op);
135 for ($kid = $op->first; $$kid; $kid = $kid->sibling) {
136 walkoptree_slow($kid, $method, $level + 1);
140 if (class($op) eq 'PMOP'
141 && ref($op->pmreplroot)
142 && ${$op->pmreplroot}
143 && $op->pmreplroot->isa( 'B::OP' ))
145 unshift(@parents, $op);
146 walkoptree_slow($op->pmreplroot, $method, $level + 1);
152 return "Total number of OPs processed: $op_count\n";
156 my ($sec, $min, $hr) = localtime;
157 my ($user, $sys) = times;
158 sprintf("%02d:%02d:%02d user=$user sys=$sys",
159 $hr, $min, $sec, $user, $sys);
169 my ($obj, $value) = @_;
170 # warn(sprintf("savesym: sym_%x => %s\n", $$obj, $value)); # debug
171 $symtable{sprintf("sym_%x", $$obj)} = $value;
176 return $symtable{sprintf("sym_%x", $$obj)};
179 sub walkoptree_exec {
180 my ($op, $method, $level) = @_;
183 my $prefix = " " x $level;
184 for (; $$op; $op = $op->next) {
187 print $prefix, "goto $sym\n";
190 savesym($op, sprintf("%s (0x%lx)", class($op), $$op));
191 $op->$method($level);
194 /^(d?or(assign)?|and(assign)?|mapwhile|grepwhile|entertry|range|cond_expr)$/)
196 print $prefix, uc($1), " => {\n";
197 walkoptree_exec($op->other, $method, $level + 1);
198 print $prefix, "}\n";
199 } elsif ($ppname eq "match" || $ppname eq "subst") {
200 my $pmreplstart = $op->pmreplstart;
202 print $prefix, "PMREPLSTART => {\n";
203 walkoptree_exec($pmreplstart, $method, $level + 1);
204 print $prefix, "}\n";
206 } elsif ($ppname eq "substcont") {
207 print $prefix, "SUBSTCONT => {\n";
208 walkoptree_exec($op->other->pmreplstart, $method, $level + 1);
209 print $prefix, "}\n";
211 } elsif ($ppname eq "enterloop") {
212 print $prefix, "REDO => {\n";
213 walkoptree_exec($op->redoop, $method, $level + 1);
214 print $prefix, "}\n", $prefix, "NEXT => {\n";
215 walkoptree_exec($op->nextop, $method, $level + 1);
216 print $prefix, "}\n", $prefix, "LAST => {\n";
217 walkoptree_exec($op->lastop, $method, $level + 1);
218 print $prefix, "}\n";
219 } elsif ($ppname eq "subst") {
220 my $replstart = $op->pmreplstart;
222 print $prefix, "SUBST => {\n";
223 walkoptree_exec($replstart, $method, $level + 1);
224 print $prefix, "}\n";
231 my ($symref, $method, $recurse, $prefix) = @_;
236 $prefix = '' unless defined $prefix;
237 while (($sym, $ref) = each %$symref) {
238 $fullname = "*main::".$prefix.$sym;
240 $sym = $prefix . $sym;
241 if ($sym ne "main::" && $sym ne "<none>::" && &$recurse($sym)) {
242 walksymtable(\%$fullname, $method, $recurse, $sym);
245 svref_2object(\*$fullname)->$method();
256 my ($class, $section, $symtable, $default) = @_;
257 $output_fh ||= FileHandle->new_tmpfile;
258 my $obj = bless [-1, $section, $symtable, $default], $class;
259 $sections{$section} = $obj;
264 my ($class, $section) = @_;
265 return $sections{$section};
270 while (defined($_ = shift)) {
271 print $output_fh "$section->[1]\t$_\n";
278 return $section->[0];
283 return $section->[1];
288 return $section->[2];
293 return $section->[3];
297 my ($section, $fh, $format) = @_;
298 my $name = $section->name;
299 my $sym = $section->symtable || {};
300 my $default = $section->default;
302 seek($output_fh, 0, 0);
303 while (<$output_fh>) {
308 exists($sym->{$1}) ? $sym->{$1} : $default;
310 printf $fh $format, $_;
324 B - The Perl Compiler
332 The C<B> module supplies classes which allow a Perl program to delve
333 into its own innards. It is the module used to implement the
334 "backends" of the Perl compiler. Usage of the compiler does not
335 require knowledge of this module: see the F<O> module for the
336 user-visible part. The C<B> module is of use to those who want to
337 write new compiler backends. This documentation assumes that the
338 reader knows a fair amount about perl's internals including such
339 things as SVs, OPs and the internal symbol table and syntax tree
344 The C<B> module contains a set of utility functions for querying the
345 current state of the Perl interpreter; typically these functions
346 return objects from the B::SV and B::OP classes, or their derived
347 classes. These classes in turn define methods for querying the
348 resulting objects about their own internal state.
350 =head1 Utility Functions
352 The C<B> module exports a variety of functions: some are simple
353 utility functions, others provide a Perl program with a way to
354 get an initial "handle" on an internal object.
356 =head2 Functions Returning C<B::SV>, C<B::AV>, C<B::HV>, and C<B::CV> objects
358 For descriptions of the class hierarchy of these objects and the
359 methods that can be called on them, see below, L<"OVERVIEW OF
360 CLASSES"> and L<"SV-RELATED CLASSES">.
366 Returns the SV object corresponding to the C variable C<sv_undef>.
370 Returns the SV object corresponding to the C variable C<sv_yes>.
374 Returns the SV object corresponding to the C variable C<sv_no>.
376 =item svref_2object(SVREF)
378 Takes a reference to any Perl value, and turns the referred-to value
379 into an object in the appropriate B::OP-derived or B::SV-derived
380 class. Apart from functions such as C<main_root>, this is the primary
381 way to get an initial "handle" on an internal perl data structure
382 which can then be followed with the other access methods.
384 The returned object will only be valid as long as the underlying OPs
385 and SVs continue to exist. Do not attempt to use the object after the
386 underlying structures are freed.
388 =item amagic_generation
390 Returns the SV object corresponding to the C variable C<amagic_generation>.
394 Returns the AV object (i.e. in class B::AV) representing INIT blocks.
398 Returns the AV object (i.e. in class B::AV) representing CHECK blocks.
402 Returns the AV object (i.e. in class B::AV) representing UNITCHECK blocks.
406 Returns the AV object (i.e. in class B::AV) representing BEGIN blocks.
410 Returns the AV object (i.e. in class B::AV) representing END blocks.
414 Returns the AV object (i.e. in class B::AV) of the global comppadlist.
418 Only when perl was compiled with ithreads.
422 Return the (faked) CV corresponding to the main part of the Perl
427 =head2 Functions for Examining the Symbol Table
431 =item walksymtable(SYMREF, METHOD, RECURSE, PREFIX)
433 Walk the symbol table starting at SYMREF and call METHOD on each
434 symbol (a B::GV object) visited. When the walk reaches package
435 symbols (such as "Foo::") it invokes RECURSE, passing in the symbol
436 name, and only recurses into the package if that sub returns true.
438 PREFIX is the name of the SYMREF you're walking.
442 # Walk CGI's symbol table calling print_subs on each symbol.
443 # Recurse only into CGI::Util::
444 walksymtable(\%CGI::, 'print_subs', sub { $_[0] eq 'CGI::Util::' },
447 print_subs() is a B::GV method you have declared. Also see L<"B::GV
452 =head2 Functions Returning C<B::OP> objects or for walking op trees
454 For descriptions of the class hierarchy of these objects and the
455 methods that can be called on them, see below, L<"OVERVIEW OF
456 CLASSES"> and L<"OP-RELATED CLASSES">.
462 Returns the root op (i.e. an object in the appropriate B::OP-derived
463 class) of the main part of the Perl program.
467 Returns the starting op of the main part of the Perl program.
469 =item walkoptree(OP, METHOD)
471 Does a tree-walk of the syntax tree based at OP and calls METHOD on
472 each op it visits. Each node is visited before its children. If
473 C<walkoptree_debug> (see below) has been called to turn debugging on then
474 the method C<walkoptree_debug> is called on each op before METHOD is
477 =item walkoptree_debug(DEBUG)
479 Returns the current debugging flag for C<walkoptree>. If the optional
480 DEBUG argument is non-zero, it sets the debugging flag to that. See
481 the description of C<walkoptree> above for what the debugging flag
486 =head2 Miscellaneous Utility Functions
492 Return the PP function name (e.g. "pp_add") of op number OPNUM.
496 Returns a string in the form "0x..." representing the value of the
497 internal hash function used by perl on string STR.
501 Casts I to the internal I32 type used by that perl.
505 Does the equivalent of the C<-c> command-line option. Obviously, this
506 is only useful in a BEGIN block or else the flag is set too late.
510 Returns a double-quote-surrounded escaped version of STR which can
511 be used as a string in C source code.
513 =item perlstring(STR)
515 Returns a double-quote-surrounded escaped version of STR which can
516 be used as a string in Perl source code.
520 Returns the class of an object without the part of the classname
521 preceding the first C<"::">. This is used to turn C<"B::UNOP"> into
522 C<"UNOP"> for example.
526 In a perl compiled for threads, this returns a list of the special
527 per-thread threadsv variables.
531 =head2 Exported utility variabiles
537 my $op_type = $optype[$op_type_num];
539 A simple mapping of the op type number to its type (like 'COP' or 'BINOP').
541 =item @specialsv_name
543 my $sv_name = $specialsv_name[$sv_index];
545 Certain SV types are considered 'special'. They're represented by
546 B::SPECIAL and are referred to by a number from the specialsv_list.
547 This array maps that number back to the name of the SV (like 'Nullsv'
553 =head1 OVERVIEW OF CLASSES
555 The C structures used by Perl's internals to hold SV and OP
556 information (PVIV, AV, HV, ..., OP, SVOP, UNOP, ...) are modelled on a
557 class hierarchy and the C<B> module gives access to them via a true
558 object hierarchy. Structure fields which point to other objects
559 (whether types of SV or types of OP) are represented by the C<B>
560 module as Perl objects of the appropriate class.
562 The bulk of the C<B> module is the methods for accessing fields of
565 Note that all access is read-only. You cannot modify the internals by
566 using this module. Also, note that the B::OP and B::SV objects created
567 by this module are only valid for as long as the underlying objects
568 exist; their creation doesn't increase the reference counts of the
569 underlying objects. Trying to access the fields of a freed object will
570 give incomprehensible results, or worse.
572 =head2 SV-RELATED CLASSES
574 B::IV, B::NV, B::RV, B::PV, B::PVIV, B::PVNV, B::PVMG, B::BM (5.9.5 and
575 earlier), B::PVLV, B::AV, B::HV, B::CV, B::GV, B::FM, B::IO. These classes
576 correspond in the obvious way to the underlying C structures of similar names.
577 The inheritance hierarchy mimics the underlying C "inheritance". For 5.9.5
582 +------------+------------+------------+
584 B::PV B::IV B::NV B::RV
596 +-----+-----+-----+-----+
598 B::AV B::GV B::HV B::CV B::IO
604 For 5.9.0 and earlier, PVLV is a direct subclass of PVMG, and BM is still
605 present as a distinct type, so the base of this diagram is
612 +------+-----+-----+-----+-----+-----+
614 B::PVLV B::BM B::AV B::GV B::HV B::CV B::IO
620 Access methods correspond to the underlying C macros for field access,
621 usually with the leading "class indication" prefix removed (Sv, Av,
622 Hv, ...). The leading prefix is only left in cases where its removal
623 would cause a clash in method name. For example, C<GvREFCNT> stays
624 as-is since its abbreviation would clash with the "superclass" method
625 C<REFCNT> (corresponding to the C function C<SvREFCNT>).
637 Returns a reference to the regular scalar corresponding to this
638 B::SV object. In other words, this method is the inverse operation
639 to the svref_2object() subroutine. This scalar and other data it points
640 at should be considered read-only: modifying them is neither safe nor
641 guaranteed to have a sensible effect.
651 Returns the value of the IV, I<interpreted as
652 a signed integer>. This will be misleading
653 if C<FLAGS & SVf_IVisUV>. Perhaps you want the
654 C<int_value> method instead?
662 This method returns the value of the IV as an integer.
663 It differs from C<IV> in that it returns the correct
664 value regardless of whether it's stored signed or
697 This method is the one you usually want. It constructs a
698 string using the length and offset information in the struct:
699 for ordinary scalars it will return the string that you'd see
700 from Perl, even if it contains null characters.
704 Same as B::RV::RV, except that it will die() if the PV isn't
709 This method is less often useful. It assumes that the string
710 stored in the struct is null-terminated, and disregards the
713 It is the appropriate method to use if you need to get the name
714 of a lexical variable from a padname array. Lexical variable names
715 are always stored with a null terminator, and the length field
716 (SvCUR) is overloaded for other purposes and can't be relied on here.
720 =head2 B::PVMG Methods
730 =head2 B::MAGIC Methods
738 Only valid on r-magic, returns the string that generated the regexp.
748 Will die() if called on r-magic.
754 Only valid on r-magic, returns the integer value of the REGEX stored
759 =head2 B::PVLV Methods
793 This method returns TRUE if the GP field of the GV is NULL.
799 This method returns the name of the glob, but if the first
800 character of the name is a control character, then it converts
801 it to ^X first, so that *^G would return "^G" rather than "\cG".
803 It's useful if you want to print out the name of a variable.
804 If you restrict yourself to globs which exist at compile-time
805 then the result ought to be unambiguous, because code like
806 C<${"^G"} = 1> is compiled as two ops - a constant string and
807 a dereference (rv2gv) - so that the glob is created at runtime.
809 If you're working with globs at runtime, and need to disambiguate
810 *^G from *{"^G"}, then you should use the raw NAME method.
874 Takes one arguments ( 'stdin' | 'stdout' | 'stderr' ) and returns true
875 if the IoIFP of the object is equal to the handle whose name was
876 passed as argument ( i.e. $io->IsSTD('stderr') is true if
877 IoIFP($io) == PerlIO_stdin() ).
893 Like C<ARRAY>, but takes an index as an argument to get only one element,
894 rather than a list of all of them.
898 This method is deprecated if running under Perl 5.8, and is no longer present
899 if running under Perl 5.9
903 This method returns the AV specific flags. In Perl 5.9 these are now stored
904 in with the main SV flags, so this method is no longer present.
934 For constant subroutines, returns the constant SV returned by the subroutine.
960 This method is not present if running under Perl 5.9, as the PMROOT
961 information is no longer stored directly in the hash.
965 =head2 OP-RELATED CLASSES
967 C<B::OP>, C<B::UNOP>, C<B::BINOP>, C<B::LOGOP>, C<B::LISTOP>, C<B::PMOP>,
968 C<B::SVOP>, C<B::PADOP>, C<B::PVOP>, C<B::LOOP>, C<B::COP>.
970 These classes correspond in the obvious way to the underlying C
971 structures of similar names. The inheritance hierarchy mimics the
972 underlying C "inheritance":
976 +---------------+--------+--------+-------+
978 B::UNOP B::SVOP B::PADOP B::COP B::PVOP
989 Access methods correspond to the underlying C structre field names,
990 with the leading "class indication" prefix (C<"op_">) removed.
994 These methods get the values of similarly named fields within the OP
995 data structure. See top of C<op.h> for more info.
1005 This returns the op name as a string (e.g. "add", "rv2av").
1009 This returns the function name as a string (e.g. "PL_ppaddr[OP_ADD]",
1010 "PL_ppaddr[OP_RV2AV]").
1014 This returns the op description from the global C PL_op_desc array
1015 (e.g. "addition" "array deref").
1031 =head2 B::UNOP METHOD
1039 =head2 B::BINOP METHOD
1047 =head2 B::LOGOP METHOD
1055 =head2 B::LISTOP METHOD
1063 =head2 B::PMOP Methods
1083 Only when perl was compiled with ithreads.
1087 =head2 B::SVOP METHOD
1097 =head2 B::PADOP METHOD
1105 =head2 B::PVOP METHOD
1113 =head2 B::LOOP Methods
1125 =head2 B::COP Methods
1156 Malcolm Beattie, C<mbeattie@sable.ox.ac.uk>