perlguts.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,725 行 · 第 1/5 页

POD
1,725
字号

=item C<SAVEDELETE(HV *hv, char *key, I32 length)>

The key C<key> of C<hv> is deleted at the end of I<pseudo-block>. The
string pointed to by C<key> is Safefree()ed.  If one has a I<key> in
short-lived storage, the corresponding string may be reallocated like
this:

  SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));

=item C<SAVEDESTRUCTOR(f,p)>

At the end of I<pseudo-block> the function C<f> is called with the
only argument (of type C<void*>) C<p>.

=item C<SAVESTACK_POS()>

The current offset on the Perl internal stack (cf. C<SP>) is restored
at the end of I<pseudo-block>.

=back

The following API list contains functions, thus one needs to
provide pointers to the modifiable data explicitly (either C pointers,
or Perlish C<GV *>s).  Where the above macros take C<int>, a similar 
function takes C<int *>.

=over

=item C<SV* save_scalar(GV *gv)>

Equivalent to Perl code C<local $gv>.

=item C<AV* save_ary(GV *gv)>

=item C<HV* save_hash(GV *gv)>

Similar to C<save_scalar>, but localize C<@gv> and C<%gv>.

=item C<void save_item(SV *item)>

Duplicates the current value of C<SV>, on the exit from the current
C<ENTER>/C<LEAVE> I<pseudo-block> will restore the value of C<SV>
using the stored value.

=item C<void save_list(SV **sarg, I32 maxsarg)>

A variant of C<save_item> which takes multiple arguments via an array
C<sarg> of C<SV*> of length C<maxsarg>.

=item C<SV* save_svref(SV **sptr)>

Similar to C<save_scalar>, but will reinstate a C<SV *>.

=item C<void save_aptr(AV **aptr)>

=item C<void save_hptr(HV **hptr)>

Similar to C<save_svref>, but localize C<AV *> and C<HV *>.

=back

The C<Alias> module implements localization of the basic types within the
I<caller's scope>.  People who are interested in how to localize things in
the containing scope should take a look there too.

=head1 Subroutines

=head2 XSUBs and the Argument Stack

The XSUB mechanism is a simple way for Perl programs to access C subroutines.
An XSUB routine will have a stack that contains the arguments from the Perl
program, and a way to map from the Perl data structures to a C equivalent.

The stack arguments are accessible through the C<ST(n)> macro, which returns
the C<n>'th stack argument.  Argument 0 is the first argument passed in the
Perl subroutine call.  These arguments are C<SV*>, and can be used anywhere
an C<SV*> is used.

Most of the time, output from the C routine can be handled through use of
the RETVAL and OUTPUT directives.  However, there are some cases where the
argument stack is not already long enough to handle all the return values.
An example is the POSIX tzname() call, which takes no arguments, but returns
two, the local time zone's standard and summer time abbreviations.

To handle this situation, the PPCODE directive is used and the stack is
extended using the macro:

    EXTEND(SP, num);

where C<SP> is the macro that represents the local copy of the stack pointer,
and C<num> is the number of elements the stack should be extended by.

Now that there is room on the stack, values can be pushed on it using the
macros to push IVs, doubles, strings, and SV pointers respectively:

    PUSHi(IV)
    PUSHn(double)
    PUSHp(char*, I32)
    PUSHs(SV*)

And now the Perl program calling C<tzname>, the two values will be assigned
as in:

    ($standard_abbrev, $summer_abbrev) = POSIX::tzname;

An alternate (and possibly simpler) method to pushing values on the stack is
to use the macros:

    XPUSHi(IV)
    XPUSHn(double)
    XPUSHp(char*, I32)
    XPUSHs(SV*)

These macros automatically adjust the stack for you, if needed.  Thus, you
do not need to call C<EXTEND> to extend the stack.

For more information, consult L<perlxs> and L<perlxstut>.

=head2 Calling Perl Routines from within C Programs

There are four routines that can be used to call a Perl subroutine from
within a C program.  These four are:

    I32  perl_call_sv(SV*, I32);
    I32  perl_call_pv(char*, I32);
    I32  perl_call_method(char*, I32);
    I32  perl_call_argv(char*, I32, register char**);

The routine most often used is C<perl_call_sv>.  The C<SV*> argument
contains either the name of the Perl subroutine to be called, or a
reference to the subroutine.  The second argument consists of flags
that control the context in which the subroutine is called, whether
or not the subroutine is being passed arguments, how errors should be
trapped, and how to treat return values.

All four routines return the number of arguments that the subroutine returned
on the Perl stack.

When using any of these routines (except C<perl_call_argv>), the programmer
must manipulate the Perl stack.  These include the following macros and
functions:

    dSP
    SP
    PUSHMARK()
    PUTBACK
    SPAGAIN
    ENTER
    SAVETMPS
    FREETMPS
    LEAVE
    XPUSH*()
    POP*()

For a detailed description of calling conventions from C to Perl,
consult L<perlcall>.

=head2 Memory Allocation

It is suggested that you use the version of malloc that is distributed
with Perl.  It keeps pools of various sizes of unallocated memory in
order to satisfy allocation requests more quickly.  However, on some
platforms, it may cause spurious malloc or free errors.

    New(x, pointer, number, type);
    Newc(x, pointer, number, type, cast);
    Newz(x, pointer, number, type);

These three macros are used to initially allocate memory.

The first argument C<x> was a "magic cookie" that was used to keep track
of who called the macro, to help when debugging memory problems.  However,
the current code makes no use of this feature (most Perl developers now
use run-time memory checkers), so this argument can be any number.

The second argument C<pointer> should be the name of a variable that will
point to the newly allocated memory.

The third and fourth arguments C<number> and C<type> specify how many of
the specified type of data structure should be allocated.  The argument
C<type> is passed to C<sizeof>.  The final argument to C<Newc>, C<cast>,
should be used if the C<pointer> argument is different from the C<type>
argument.

Unlike the C<New> and C<Newc> macros, the C<Newz> macro calls C<memzero>
to zero out all the newly allocated memory.

    Renew(pointer, number, type);
    Renewc(pointer, number, type, cast);
    Safefree(pointer)

These three macros are used to change a memory buffer size or to free a
piece of memory no longer needed.  The arguments to C<Renew> and C<Renewc>
match those of C<New> and C<Newc> with the exception of not needing the
"magic cookie" argument.

    Move(source, dest, number, type);
    Copy(source, dest, number, type);
    Zero(dest, number, type);

These three macros are used to move, copy, or zero out previously allocated
memory.  The C<source> and C<dest> arguments point to the source and
destination starting points.  Perl will move, copy, or zero out C<number>
instances of the size of the C<type> data structure (using the C<sizeof>
function).

=head2 PerlIO

The most recent development releases of Perl has been experimenting with
removing Perl's dependency on the "normal" standard I/O suite and allowing
other stdio implementations to be used.  This involves creating a new
abstraction layer that then calls whichever implementation of stdio Perl
was compiled with.  All XSUBs should now use the functions in the PerlIO
abstraction layer and not make any assumptions about what kind of stdio
is being used.

For a complete description of the PerlIO abstraction, consult L<perlapio>.

=head2 Putting a C value on Perl stack

A lot of opcodes (this is an elementary operation in the internal perl
stack machine) put an SV* on the stack. However, as an optimization
the corresponding SV is (usually) not recreated each time. The opcodes
reuse specially assigned SVs (I<target>s) which are (as a corollary)
not constantly freed/created.

Each of the targets is created only once (but see
L<Scratchpads and recursion> below), and when an opcode needs to put
an integer, a double, or a string on stack, it just sets the
corresponding parts of its I<target> and puts the I<target> on stack.

The macro to put this target on stack is C<PUSHTARG>, and it is
directly used in some opcodes, as well as indirectly in zillions of
others, which use it via C<(X)PUSH[pni]>.

=head2 Scratchpads

The question remains on when the SVs which are I<target>s for opcodes
are created. The answer is that they are created when the current unit --
a subroutine or a file (for opcodes for statements outside of
subroutines) -- is compiled. During this time a special anonymous Perl
array is created, which is called a scratchpad for the current
unit.

A scratchpad keeps SVs which are lexicals for the current unit and are
targets for opcodes. One can deduce that an SV lives on a scratchpad
by looking on its flags: lexicals have C<SVs_PADMY> set, and
I<target>s have C<SVs_PADTMP> set.

The correspondence between OPs and I<target>s is not 1-to-1. Different
OPs in the compile tree of the unit can use the same target, if this
would not conflict with the expected life of the temporary.

=head2 Scratchpads and recursion

In fact it is not 100% true that a compiled unit contains a pointer to
the scratchpad AV. In fact it contains a pointer to an AV of
(initially) one element, and this element is the scratchpad AV. Why do
we need an extra level of indirection?

The answer is B<recursion>, and maybe (sometime soon) B<threads>. Both
these can create several execution pointers going into the same
subroutine. For the subroutine-child not write over the temporaries
for the subroutine-parent (lifespan of which covers the call to the
child), the parent and the child should have different
scratchpads. (I<And> the lexicals should be separate anyway!)

So each subroutine is born with an array of scratchpads (of length 1).
On each entry to the subroutine it is checked that the current
depth of the recursion is not more than the length of this array, and
if it is, new scratchpad is created and pushed into the array.

The I<target>s on this scratchpad are C<undef>s, but they are already
marked with correct flags.

=head1 Compiled code

=head2 Code tree

Here we describe the internal form your code is converted to by
Perl. Start with a simple example:

  $a = $b + $c;

This is converted to a tree similar to this one:

             assign-to
           /           \
          +             $a
        /   \
      $b     $c

(but slightly more complicated).  This tree reflects the way Perl
parsed your code, but has nothing to do with the execution order.
There is an additional "thread" going through the nodes of the tree
which shows the order of execution of the nodes.  In our simplified
example above it looks like:

     $b ---> $c ---> + ---> $a ---> assign-to

But with the actual compile tree for C<$a = $b + $c> it is different:
some nodes I<optimized away>.  As a corollary, though the actual tree
contains more nodes than our simplified example, the execution order
is the same as in our example.

=head2 Examining the tree

If you have your perl compiled for debugging (usually done with C<-D
optimize=-g> on C<Configure> command line), you may examine the
compiled tree by specifying C<-Dx> on the Perl command line.  The
output takes several lines per node, and for C<$b+$c> it looks like
this:

    5           TYPE = add  ===> 6
                TARG = 1
                FLAGS = (SCALAR,KIDS)
                {
                    TYPE = null  ===> (4)
                      (was rv2sv)
                    FLAGS = (SCALAR,KIDS)
                    {
    3                   TYPE = gvsv  ===> 4
                        FLAGS = (SCALAR)
                        GV = main::b
                    }
                }
                {
                    TYPE = null  ===> (5)
                      (was rv2sv)
                    FLAGS = (SCALAR,KIDS)
                    {
    4                   TYPE = gvsv  ===> 5
                        FLAGS = (SCALAR)
                        GV = main::c
                    }
                }

This tree has 5 nodes (one per C<TYPE> specifier), only 3 of them are
not optimized away (one per number in the left column).  The immediate
children of the given node correspond to C<{}> pairs on the same level
of indentation, thus this listing corresponds to the tree:

                   add
                 /     \

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?