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.
12 @B::ISA = qw(Exporter);
14 # walkoptree_slow comes from B.pm (you are there),
15 # walkoptree comes from B.xs
21 # Our BOOT code needs $VERSION set, and will append to @EXPORT_OK.
22 # Want our constants loaded before the compiler meets OPf_KIDS below, as
23 # the combination of having the constant stay a Proxy Constant Subroutine
24 # and its value being inlined saves a little over .5K
30 push @B::EXPORT_OK, (qw(minus_c ppname save_BEGINs
31 class peekop cast_I32 cstring cchar hash threadsv_names
32 main_root main_start main_cv svref_2object opnumber
33 sub_generation amagic_generation perlstring
34 walkoptree_slow walkoptree walkoptree_exec walksymtable
35 parents comppadlist sv_undef compile_stats timing_info
36 begin_av init_av check_av end_av regex_padav dowarn
37 defstash curstash warnhook diehook inc_gv @optype
38 @specialsv_name unitcheck_av));
40 @B::SV::ISA = 'B::OBJECT';
41 @B::NULL::ISA = 'B::SV';
42 @B::PV::ISA = 'B::SV';
43 @B::IV::ISA = 'B::SV';
44 @B::NV::ISA = 'B::SV';
45 # RV is eliminated with 5.11.0, but effectively is a specialisation of IV now.
46 @B::RV::ISA = $] >= 5.011 ? 'B::IV' : 'B::SV';
47 @B::PVIV::ISA = qw(B::PV B::IV);
48 @B::PVNV::ISA = qw(B::PVIV B::NV);
49 @B::PVMG::ISA = 'B::PVNV';
50 @B::REGEXP::ISA = 'B::PVMG' if $] >= 5.011;
51 @B::PVLV::ISA = 'B::GV';
52 @B::BM::ISA = 'B::GV';
53 @B::AV::ISA = 'B::PVMG';
54 @B::GV::ISA = 'B::PVMG';
55 @B::HV::ISA = 'B::PVMG';
56 @B::CV::ISA = 'B::PVMG';
57 @B::IO::ISA = 'B::PVMG';
58 @B::FM::ISA = 'B::CV';
60 @B::OP::ISA = 'B::OBJECT';
61 @B::UNOP::ISA = 'B::OP';
62 @B::BINOP::ISA = 'B::UNOP';
63 @B::LOGOP::ISA = 'B::UNOP';
64 @B::LISTOP::ISA = 'B::BINOP';
65 @B::SVOP::ISA = 'B::OP';
66 @B::PADOP::ISA = 'B::OP';
67 @B::PVOP::ISA = 'B::OP';
68 @B::LOOP::ISA = 'B::LISTOP';
69 @B::PMOP::ISA = 'B::LISTOP';
70 @B::COP::ISA = 'B::OP';
72 @B::SPECIAL::ISA = 'B::OBJECT';
74 @B::optype = qw(OP UNOP BINOP LOGOP LISTOP PMOP SVOP PADOP PVOP LOOP COP);
75 # bytecode.pl contained the following comment:
76 # Nullsv *must* come first in the following so that the condition
77 # ($$sv == 0) can continue to be used to test (sv == Nullsv).
78 @B::specialsv_name = qw(Nullsv &PL_sv_undef &PL_sv_yes &PL_sv_no
79 (SV*)pWARN_ALL (SV*)pWARN_NONE (SV*)pWARN_STD);
82 # Stop "-w" from complaining about the lack of a real B::OBJECT class
87 my $name = (shift())->NAME;
89 # The regex below corresponds to the isCONTROLVAR macro
92 $name =~ s/^([\cA-\cZ\c\\c[\c]\c?\c_\c^])/"^".
93 chr( utf8::unicode_to_native( 64 ^ ord($1) ))/e;
95 # When we say unicode_to_native we really mean ascii_to_native,
96 # which matters iff this is a non-ASCII platform (EBCDIC).
101 sub B::IV::int_value {
103 return (($self->FLAGS() & SVf_IVisUV()) ? $self->UVX : $self->IV);
106 sub B::NULL::as_string() {""}
107 *B::IV::as_string = \*B::IV::int_value;
108 *B::PV::as_string = \*B::PV::PV;
110 # The input typemap checking makes no distinction between different SV types,
111 # so the XS body will generate the same C code, despite the different XS
112 # "types". So there is no change in behaviour from doing "newXS" like this,
113 # compared with the old approach of having a (near) duplicate XS body.
114 # We should fix the typemap checking.
115 *B::IV::RV = \*B::PV::RV if $] > 5.012;
122 my ($class, $value) = @_;
124 walkoptree_debug($value);
134 sub parents { \@parents }
139 return sprintf("%s (0x%x) %s", class($op), $$op, $op->name);
142 sub walkoptree_slow {
143 my($op, $method, $level) = @_;
144 $op_count++; # just for statistics
146 warn(sprintf("walkoptree: %d. %s\n", $level, peekop($op))) if $debug;
147 $op->$method($level) if $op->can($method);
148 if ($$op && ($op->flags & OPf_KIDS)) {
150 unshift(@parents, $op);
151 for ($kid = $op->first; $$kid; $kid = $kid->sibling) {
152 walkoptree_slow($kid, $method, $level + 1);
156 if (class($op) eq 'PMOP'
157 && ref($op->pmreplroot)
158 && ${$op->pmreplroot}
159 && $op->pmreplroot->isa( 'B::OP' ))
161 unshift(@parents, $op);
162 walkoptree_slow($op->pmreplroot, $method, $level + 1);
168 return "Total number of OPs processed: $op_count\n";
172 my ($sec, $min, $hr) = localtime;
173 my ($user, $sys) = times;
174 sprintf("%02d:%02d:%02d user=$user sys=$sys",
175 $hr, $min, $sec, $user, $sys);
185 my ($obj, $value) = @_;
186 # warn(sprintf("savesym: sym_%x => %s\n", $$obj, $value)); # debug
187 $symtable{sprintf("sym_%x", $$obj)} = $value;
192 return $symtable{sprintf("sym_%x", $$obj)};
195 sub walkoptree_exec {
196 my ($op, $method, $level) = @_;
199 my $prefix = " " x $level;
200 for (; $$op; $op = $op->next) {
203 print $prefix, "goto $sym\n";
206 savesym($op, sprintf("%s (0x%lx)", class($op), $$op));
207 $op->$method($level);
210 /^(d?or(assign)?|and(assign)?|mapwhile|grepwhile|entertry|range|cond_expr)$/)
212 print $prefix, uc($1), " => {\n";
213 walkoptree_exec($op->other, $method, $level + 1);
214 print $prefix, "}\n";
215 } elsif ($ppname eq "match" || $ppname eq "subst") {
216 my $pmreplstart = $op->pmreplstart;
218 print $prefix, "PMREPLSTART => {\n";
219 walkoptree_exec($pmreplstart, $method, $level + 1);
220 print $prefix, "}\n";
222 } elsif ($ppname eq "substcont") {
223 print $prefix, "SUBSTCONT => {\n";
224 walkoptree_exec($op->other->pmreplstart, $method, $level + 1);
225 print $prefix, "}\n";
227 } elsif ($ppname eq "enterloop") {
228 print $prefix, "REDO => {\n";
229 walkoptree_exec($op->redoop, $method, $level + 1);
230 print $prefix, "}\n", $prefix, "NEXT => {\n";
231 walkoptree_exec($op->nextop, $method, $level + 1);
232 print $prefix, "}\n", $prefix, "LAST => {\n";
233 walkoptree_exec($op->lastop, $method, $level + 1);
234 print $prefix, "}\n";
235 } elsif ($ppname eq "subst") {
236 my $replstart = $op->pmreplstart;
238 print $prefix, "SUBST => {\n";
239 walkoptree_exec($replstart, $method, $level + 1);
240 print $prefix, "}\n";
247 my ($symref, $method, $recurse, $prefix) = @_;
252 $prefix = '' unless defined $prefix;
253 foreach my $sym ( sort keys %$symref ) {
254 $ref= $symref->{$sym};
255 $fullname = "*main::".$prefix.$sym;
257 $sym = $prefix . $sym;
258 if (svref_2object(\*$sym)->NAME ne "main::" && $sym ne "<none>::" && &$recurse($sym)) {
259 walksymtable(\%$fullname, $method, $recurse, $sym);
262 svref_2object(\*$fullname)->$method();
273 my ($class, $section, $symtable, $default) = @_;
274 $output_fh ||= FileHandle->new_tmpfile;
275 my $obj = bless [-1, $section, $symtable, $default], $class;
276 $sections{$section} = $obj;
281 my ($class, $section) = @_;
282 return $sections{$section};
287 while (defined($_ = shift)) {
288 print $output_fh "$section->[1]\t$_\n";
295 return $section->[0];
300 return $section->[1];
305 return $section->[2];
310 return $section->[3];
314 my ($section, $fh, $format) = @_;
315 my $name = $section->name;
316 my $sym = $section->symtable || {};
317 my $default = $section->default;
319 seek($output_fh, 0, 0);
320 while (<$output_fh>) {
325 exists($sym->{$1}) ? $sym->{$1} : $default;
327 printf $fh $format, $_;
339 B - The Perl Compiler Backend
347 The C<B> module supplies classes which allow a Perl program to delve
348 into its own innards. It is the module used to implement the
349 "backends" of the Perl compiler. Usage of the compiler does not
350 require knowledge of this module: see the F<O> module for the
351 user-visible part. The C<B> module is of use to those who want to
352 write new compiler backends. This documentation assumes that the
353 reader knows a fair amount about perl's internals including such
354 things as SVs, OPs and the internal symbol table and syntax tree
359 The C<B> module contains a set of utility functions for querying the
360 current state of the Perl interpreter; typically these functions
361 return objects from the B::SV and B::OP classes, or their derived
362 classes. These classes in turn define methods for querying the
363 resulting objects about their own internal state.
365 =head1 Utility Functions
367 The C<B> module exports a variety of functions: some are simple
368 utility functions, others provide a Perl program with a way to
369 get an initial "handle" on an internal object.
371 =head2 Functions Returning C<B::SV>, C<B::AV>, C<B::HV>, and C<B::CV> objects
373 For descriptions of the class hierarchy of these objects and the
374 methods that can be called on them, see below, L<"OVERVIEW OF
375 CLASSES"> and L<"SV-RELATED CLASSES">.
381 Returns the SV object corresponding to the C variable C<sv_undef>.
385 Returns the SV object corresponding to the C variable C<sv_yes>.
389 Returns the SV object corresponding to the C variable C<sv_no>.
391 =item svref_2object(SVREF)
393 Takes a reference to any Perl value, and turns the referred-to value
394 into an object in the appropriate B::OP-derived or B::SV-derived
395 class. Apart from functions such as C<main_root>, this is the primary
396 way to get an initial "handle" on an internal perl data structure
397 which can then be followed with the other access methods.
399 The returned object will only be valid as long as the underlying OPs
400 and SVs continue to exist. Do not attempt to use the object after the
401 underlying structures are freed.
403 =item amagic_generation
405 Returns the SV object corresponding to the C variable C<amagic_generation>.
406 As of Perl 5.18, this is just an alias to C<PL_na>, so its value is
411 Returns the AV object (i.e. in class B::AV) representing INIT blocks.
415 Returns the AV object (i.e. in class B::AV) representing CHECK blocks.
419 Returns the AV object (i.e. in class B::AV) representing UNITCHECK blocks.
423 Returns the AV object (i.e. in class B::AV) representing BEGIN blocks.
427 Returns the AV object (i.e. in class B::AV) representing END blocks.
431 Returns the PADLIST object (i.e. in class B::PADLIST) of the global
432 comppadlist. In Perl 5.16 and earlier it returns an AV object (class
437 Only when perl was compiled with ithreads.
441 Return the (faked) CV corresponding to the main part of the Perl
446 =head2 Functions for Examining the Symbol Table
450 =item walksymtable(SYMREF, METHOD, RECURSE, PREFIX)
452 Walk the symbol table starting at SYMREF and call METHOD on each
453 symbol (a B::GV object) visited. When the walk reaches package
454 symbols (such as "Foo::") it invokes RECURSE, passing in the symbol
455 name, and only recurses into the package if that sub returns true.
457 PREFIX is the name of the SYMREF you're walking.
461 # Walk CGI's symbol table calling print_subs on each symbol.
462 # Recurse only into CGI::Util::
463 walksymtable(\%CGI::, 'print_subs',
464 sub { $_[0] eq 'CGI::Util::' }, 'CGI::');
466 print_subs() is a B::GV method you have declared. Also see L<"B::GV
471 =head2 Functions Returning C<B::OP> objects or for walking op trees
473 For descriptions of the class hierarchy of these objects and the
474 methods that can be called on them, see below, L<"OVERVIEW OF
475 CLASSES"> and L<"OP-RELATED CLASSES">.
481 Returns the root op (i.e. an object in the appropriate B::OP-derived
482 class) of the main part of the Perl program.
486 Returns the starting op of the main part of the Perl program.
488 =item walkoptree(OP, METHOD)
490 Does a tree-walk of the syntax tree based at OP and calls METHOD on
491 each op it visits. Each node is visited before its children. If
492 C<walkoptree_debug> (see below) has been called to turn debugging on then
493 the method C<walkoptree_debug> is called on each op before METHOD is
496 =item walkoptree_debug(DEBUG)
498 Returns the current debugging flag for C<walkoptree>. If the optional
499 DEBUG argument is non-zero, it sets the debugging flag to that. See
500 the description of C<walkoptree> above for what the debugging flag
505 =head2 Miscellaneous Utility Functions
511 Return the PP function name (e.g. "pp_add") of op number OPNUM.
515 Returns a string in the form "0x..." representing the value of the
516 internal hash function used by perl on string STR.
520 Casts I to the internal I32 type used by that perl.
524 Does the equivalent of the C<-c> command-line option. Obviously, this
525 is only useful in a BEGIN block or else the flag is set too late.
529 Returns a double-quote-surrounded escaped version of STR which can
530 be used as a string in C source code.
532 =item perlstring(STR)
534 Returns a double-quote-surrounded escaped version of STR which can
535 be used as a string in Perl source code.
539 Returns the class of an object without the part of the classname
540 preceding the first C<"::">. This is used to turn C<"B::UNOP"> into
541 C<"UNOP"> for example.
545 In a perl compiled for threads, this returns a list of the special
546 per-thread threadsv variables.
550 =head2 Exported utility variables
556 my $op_type = $optype[$op_type_num];
558 A simple mapping of the op type number to its type (like 'COP' or 'BINOP').
560 =item @specialsv_name
562 my $sv_name = $specialsv_name[$sv_index];
564 Certain SV types are considered 'special'. They're represented by
565 B::SPECIAL and are referred to by a number from the specialsv_list.
566 This array maps that number back to the name of the SV (like 'Nullsv'
572 =head1 OVERVIEW OF CLASSES
574 The C structures used by Perl's internals to hold SV and OP
575 information (PVIV, AV, HV, ..., OP, SVOP, UNOP, ...) are modelled on a
576 class hierarchy and the C<B> module gives access to them via a true
577 object hierarchy. Structure fields which point to other objects
578 (whether types of SV or types of OP) are represented by the C<B>
579 module as Perl objects of the appropriate class.
581 The bulk of the C<B> module is the methods for accessing fields of
584 Note that all access is read-only. You cannot modify the internals by
585 using this module. Also, note that the B::OP and B::SV objects created
586 by this module are only valid for as long as the underlying objects
587 exist; their creation doesn't increase the reference counts of the
588 underlying objects. Trying to access the fields of a freed object will
589 give incomprehensible results, or worse.
591 =head2 SV-RELATED CLASSES
593 B::IV, B::NV, B::RV, B::PV, B::PVIV, B::PVNV, B::PVMG, B::BM (5.9.5 and
594 earlier), B::PVLV, B::AV, B::HV, B::CV, B::GV, B::FM, B::IO. These classes
595 correspond in the obvious way to the underlying C structures of similar names.
596 The inheritance hierarchy mimics the underlying C "inheritance". For the
597 5.10.x branch, (I<ie> 5.10.0, 5.10.1 I<etc>) this is:
601 +------------+------------+------------+
603 B::PV B::IV B::NV B::RV
615 +-----+-----+-----+-----+
617 B::AV B::GV B::HV B::CV B::IO
622 For 5.9.0 and earlier, PVLV is a direct subclass of PVMG, and BM is still
623 present as a distinct type, so the base of this diagram is
630 +------+-----+-----+-----+-----+-----+
632 B::PVLV B::BM B::AV B::GV B::HV B::CV B::IO
637 For 5.11.0 and later, B::RV is abolished, and IVs can be used to store
638 references, and a new type B::REGEXP is introduced, giving this structure:
642 +------------+------------+
656 +-------+-------+---+---+-------+-------+
658 B::AV B::GV B::HV B::CV B::IO B::REGEXP
664 Access methods correspond to the underlying C macros for field access,
665 usually with the leading "class indication" prefix removed (Sv, Av,
666 Hv, ...). The leading prefix is only left in cases where its removal
667 would cause a clash in method name. For example, C<GvREFCNT> stays
668 as-is since its abbreviation would clash with the "superclass" method
669 C<REFCNT> (corresponding to the C function C<SvREFCNT>).
681 Returns a reference to the regular scalar corresponding to this
682 B::SV object. In other words, this method is the inverse operation
683 to the svref_2object() subroutine. This scalar and other data it points
684 at should be considered read-only: modifying them is neither safe nor
685 guaranteed to have a sensible effect.
695 Returns the value of the IV, I<interpreted as
696 a signed integer>. This will be misleading
697 if C<FLAGS & SVf_IVisUV>. Perhaps you want the
698 C<int_value> method instead?
706 This method returns the value of the IV as an integer.
707 It differs from C<IV> in that it returns the correct
708 value regardless of whether it's stored signed or
741 This method is the one you usually want. It constructs a
742 string using the length and offset information in the struct:
743 for ordinary scalars it will return the string that you'd see
744 from Perl, even if it contains null characters.
748 Same as B::RV::RV, except that it will die() if the PV isn't
753 This method is less often useful. It assumes that the string
754 stored in the struct is null-terminated, and disregards the
757 It is the appropriate method to use if you need to get the name
758 of a lexical variable from a padname array. Lexical variable names
759 are always stored with a null terminator, and the length field
760 (CUR) is overloaded for other purposes and can't be relied on here.
764 This method returns the internal length field, which consists of the number
765 of internal bytes, not necessarily the number of logical characters.
769 This method returns the number of bytes allocated (via malloc) for storing
770 the string. This is 0 if the scalar does not "own" the string.
774 =head2 B::PVMG Methods
784 =head2 B::MAGIC Methods
792 Only valid on r-magic, returns the string that generated the regexp.
802 Will die() if called on r-magic.
808 Only valid on r-magic, returns the integer value of the REGEX stored
813 =head2 B::PVLV Methods
847 This method returns TRUE if the GP field of the GV is NULL.
853 This method returns the name of the glob, but if the first
854 character of the name is a control character, then it converts
855 it to ^X first, so that *^G would return "^G" rather than "\cG".
857 It's useful if you want to print out the name of a variable.
858 If you restrict yourself to globs which exist at compile-time
859 then the result ought to be unambiguous, because code like
860 C<${"^G"} = 1> is compiled as two ops - a constant string and
861 a dereference (rv2gv) - so that the glob is created at runtime.
863 If you're working with globs at runtime, and need to disambiguate
864 *^G from *{"^G"}, then you should use the raw NAME method.
898 B::IO objects derive from IO objects and you will get more information from
899 the IO object itself.
903 $gvio = B::svref_2object(\*main::stdin)->IO;
904 $IO = $gvio->object_2svref();
933 A character symbolizing the type of IO Handle.
946 \0 closed internal handle
952 Takes one argument ( 'stdin' | 'stdout' | 'stderr' ) and returns true
953 if the IoIFP of the object is equal to the handle whose name was
954 passed as argument; i.e., $io->IsSTD('stderr') is true if
955 IoIFP($io) == PerlIO_stderr().
971 Like C<ARRAY>, but takes an index as an argument to get only one element,
972 rather than a list of all of them.
976 This method is deprecated if running under Perl 5.8, and is no longer present
977 if running under Perl 5.9
981 This method returns the AV specific
982 flags. In Perl 5.9 these are now stored
983 in with the main SV flags, so this method is no longer present.
1005 Returns a B::PADLIST object under Perl 5.18 or higher, or a B::AV in
1016 For constant subroutines, returns the constant SV returned by the subroutine.
1024 =head2 B::HV Methods
1042 This method is not present if running under Perl 5.9, as the PMROOT
1043 information is no longer stored directly in the hash.
1047 =head2 OP-RELATED CLASSES
1049 C<B::OP>, C<B::UNOP>, C<B::BINOP>, C<B::LOGOP>, C<B::LISTOP>, C<B::PMOP>,
1050 C<B::SVOP>, C<B::PADOP>, C<B::PVOP>, C<B::LOOP>, C<B::COP>.
1052 These classes correspond in the obvious way to the underlying C
1053 structures of similar names. The inheritance hierarchy mimics the
1054 underlying C "inheritance":
1058 +---------------+--------+--------+-------+
1060 B::UNOP B::SVOP B::PADOP B::COP B::PVOP
1071 Access methods correspond to the underlying C structure field names,
1072 with the leading "class indication" prefix (C<"op_">) removed.
1074 =head2 B::OP Methods
1076 These methods get the values of similarly named fields within the OP
1077 data structure. See top of C<op.h> for more info.
1087 This returns the op name as a string (e.g. "add", "rv2av").
1091 This returns the function name as a string (e.g. "PL_ppaddr[OP_ADD]",
1092 "PL_ppaddr[OP_RV2AV]").
1096 This returns the op description from the global C PL_op_desc array
1097 (e.g. "addition" "array deref").
1113 =head2 B::UNOP METHOD
1121 =head2 B::BINOP METHOD
1129 =head2 B::LOGOP METHOD
1137 =head2 B::LISTOP METHOD
1145 =head2 B::PMOP Methods
1155 Only up to Perl 5.9.4
1167 Only when perl was compiled with ithreads.
1175 =head2 B::SVOP METHOD
1185 =head2 B::PADOP METHOD
1193 =head2 B::PVOP METHOD
1201 =head2 B::LOOP Methods
1213 =head2 B::COP Methods
1223 =item stashoff (threaded only)
1243 =head2 OTHER CLASSES
1245 Perl 5.18 introduces a new class, B::PADLIST, returned by B::CV's
1248 =head2 B::PADLIST Methods
1256 A list of pads. The first one contains the names. These are currently
1257 B::AV objects, but that is likely to change in future versions.
1261 Like C<ARRAY>, but takes an index as an argument to get only one element,
1262 rather than a list of all of them.
1270 Although the optree is read-only, there is an overlay facility that allows
1271 you to override what values the various B::*OP methods return for a
1272 particular op. C<$B::overlay> should be set to reference a two-deep hash:
1273 indexed by OP address, then method name. Whenever a an op method is
1274 called, the value in the hash is returned if it exists. This facility is
1275 used by B::Deparse to "undo" some optimisations. For example:
1278 local $B::overlay = {};
1280 if ($op->name eq "foo") {
1281 $B::overlay->{$$op} = {
1283 next => $op->next->next,
1287 $op->name # returns "bar"
1288 $op->next # returns the next op but one
1293 Malcolm Beattie, C<mbeattie@sable.ox.ac.uk>