perlhack.html

来自「perl教程」· HTML 代码 · 共 1,154 行 · 第 1/5 页

HTML
1,154 行
字号
</dd>
<dd>
<pre>
    <span class="variable">my_perl</span> <span class="operator">=</span> <span class="operator">(</span><span class="variable">PerlInterpreter</span><span class="operator">*)</span><span class="variable">PerlMem_malloc</span><span class="operator">(</span><span class="variable">sizeof</span><span class="operator">(</span><span class="variable">PerlInterpreter</span><span class="operator">));</span>
</pre>
</dd>
<dd>
<p>Here you see an example of Perl's system abstraction, which we'll see
later: <code>PerlMem_malloc</code> is either your system's <code>malloc</code>, or Perl's
own <code>malloc</code> as defined in <em>malloc.c</em> if you selected that option at
configure time.</p>
</dd>
<dd>
<p>Next, in line 7, we construct the interpreter; this sets up all the
special variables that Perl needs, the stacks, and so on.</p>
</dd>
<dd>
<p>Now we pass Perl the command line options, and tell it to go:</p>
</dd>
<dd>
<pre>
    <span class="variable">exitstatus</span> <span class="operator">=</span> <span class="variable">perl_parse</span><span class="operator">(</span><span class="variable">my_perl</span><span class="operator">,</span> <span class="variable">xs_init</span><span class="operator">,</span> <span class="variable">argc</span><span class="operator">,</span> <span class="variable">argv</span><span class="operator">,</span> <span class="operator">(</span><span class="variable">char</span> <span class="operator">**)</span><span class="keyword">NULL</span><span class="operator">);</span>
    <span class="keyword">if</span> <span class="operator">(!</span><span class="variable">exitstatus</span><span class="operator">)</span> <span class="operator">{</span>
        <span class="variable">exitstatus</span> <span class="operator">=</span> <span class="variable">perl_run</span><span class="operator">(</span><span class="variable">my_perl</span><span class="operator">);</span>
    <span class="operator">}</span>
</pre>
</dd>
<dd>
<p><code>perl_parse</code> is actually a wrapper around <code>S_parse_body</code>, as defined
in <em>perl.c</em>, which processes the command line options, sets up any
statically linked XS modules, opens the program and calls <code>yyparse</code> to
parse it.</p>
</dd>
</li>
<dt><strong><a name="item_parsing">Parsing</a></strong>

<dd>
<p>The aim of this stage is to take the Perl source, and turn it into an op
tree. We'll see what one of those looks like later. Strictly speaking,
there's three things going on here.</p>
</dd>
<dd>
<p><code>yyparse</code>, the parser, lives in <em>perly.c</em>, although you're better off
reading the original YACC input in <em>perly.y</em>. (Yes, Virginia, there
<strong>is</strong> a YACC grammar for Perl!) The job of the parser is to take your
code and &quot;understand&quot; it, splitting it into sentences, deciding which
operands go with which operators and so on.</p>
</dd>
<dd>
<p>The parser is nobly assisted by the lexer, which chunks up your input
into tokens, and decides what type of thing each token is: a variable
name, an operator, a bareword, a subroutine, a core function, and so on.
The main point of entry to the lexer is <code>yylex</code>, and that and its
associated routines can be found in <em>toke.c</em>. Perl isn't much like
other computer languages; it's highly context sensitive at times, it can
be tricky to work out what sort of token something is, or where a token
ends. As such, there's a lot of interplay between the tokeniser and the
parser, which can get pretty frightening if you're not used to it.</p>
</dd>
<dd>
<p>As the parser understands a Perl program, it builds up a tree of
operations for the interpreter to perform during execution. The routines
which construct and link together the various operations are to be found
in <em>op.c</em>, and will be examined later.</p>
</dd>
</li>
<dt><strong><a name="item_optimization">Optimization</a></strong>

<dd>
<p>Now the parsing stage is complete, and the finished tree represents
the operations that the Perl interpreter needs to perform to execute our
program. Next, Perl does a dry run over the tree looking for
optimisations: constant expressions such as <code>3 + 4</code> will be computed
now, and the optimizer will also see if any multiple operations can be
replaced with a single one. For instance, to fetch the variable <code>$foo</code>,
instead of grabbing the glob <code>*foo</code> and looking at the scalar
component, the optimizer fiddles the op tree to use a function which
directly looks up the scalar in question. The main optimizer is <code>peep</code>
in <em>op.c</em>, and many ops have their own optimizing functions.</p>
</dd>
</li>
<dt><strong><a name="item_running">Running</a></strong>

<dd>
<p>Now we're finally ready to go: we have compiled Perl byte code, and all
that's left to do is run it. The actual execution is done by the
<code>runops_standard</code> function in <em>run.c</em>; more specifically, it's done by
these three innocent looking lines:</p>
</dd>
<dd>
<pre>
    <span class="keyword">while</span> <span class="operator">((</span><span class="variable">PL_op</span> <span class="operator">=</span> <span class="variable">CALL_FPTR</span><span class="operator">(</span><span class="variable">PL_op</span><span class="operator">-&gt;</span><span class="variable">op_ppaddr</span><span class="operator">)(</span><span class="variable">aTHX</span><span class="operator">)))</span> <span class="operator">{</span>
        <span class="variable">PERL_ASYNC_CHECK</span><span class="operator">();</span>
    <span class="operator">}</span>
</pre>
</dd>
<dd>
<p>You may be more comfortable with the Perl version of that:</p>
</dd>
<dd>
<pre>
    <span class="variable">PERL_ASYNC_CHECK</span><span class="operator">()</span> <span class="keyword">while</span> <span class="variable">$Perl::op</span> <span class="operator">=</span> <span class="operator">&amp;{</span><span class="variable">$Perl::op</span><span class="operator">-&gt;</span><span class="operator">{</span><span class="string">function</span><span class="operator">}</span><span class="operator">};</span>
</pre>
</dd>
<dd>
<p>Well, maybe not. Anyway, each op contains a function pointer, which
stipulates the function which will actually carry out the operation.
This function will return the next op in the sequence - this allows for
things like <code>if</code> which choose the next op dynamically at run time.
The <code>PERL_ASYNC_CHECK</code> makes sure that things like signals interrupt
execution if required.</p>
</dd>
<dd>
<p>The actual functions called are known as PP code, and they're spread
between four files: <em>pp_hot.c</em> contains the &quot;hot&quot; code, which is most
often used and highly optimized, <em>pp_sys.c</em> contains all the
system-specific functions, <em>pp_ctl.c</em> contains the functions which
implement control structures (<code>if</code>, <code>while</code> and the like) and <em>pp.c</em>
contains everything else. These are, if you like, the C code for Perl's
built-in functions and operators.</p>
</dd>
<dd>
<p>Note that each <code>pp_</code> function is expected to return a pointer to the next
op. Calls to perl subs (and eval blocks) are handled within the same
runops loop, and do not consume extra space on the C stack. For example,
<code>pp_entersub</code> and <code>pp_entertry</code> just push a <code>CxSUB</code> or <code>CxEVAL</code> block
struct onto the context stack which contain the address of the op
following the sub call or eval. They then return the first op of that sub
or eval block, and so execution continues of that sub or block.  Later, a
<code>pp_leavesub</code> or <code>pp_leavetry</code> op pops the <code>CxSUB</code> or <code>CxEVAL</code>,
retrieves the return op from it, and returns it.</p>
</dd>
</li>
<dt><strong><a name="item_exception_handing">Exception handing</a></strong>

<dd>
<p>Perl's exception handing (i.e. <a href="../../lib/Pod/perlfunc.html#item_die"><code>die</code></a> etc) is built on top of the low-level
<code>setjmp()</code>/<code>longjmp()</code> C-library functions. These basically provide a
way to capture the current PC and SP registers and later restore them; i.e.
a <code>longjmp()</code> continues at the point in code where a previous <code>setjmp()</code>
was done, with anything further up on the C stack being lost. This is why
code should always save values using <code>SAVE_FOO</code> rather than in auto
variables.</p>
</dd>
<dd>
<p>The perl core wraps <code>setjmp()</code> etc in the macros <code>JMPENV_PUSH</code> and
<code>JMPENV_JUMP</code>. The basic rule of perl exceptions is that <a href="../../lib/Pod/perlfunc.html#item_exit"><code>exit</code></a>, and
<a href="../../lib/Pod/perlfunc.html#item_die"><code>die</code></a> (in the absence of <a href="../../lib/Pod/perlfunc.html#item_eval"><code>eval</code></a>) perform a <code>JMPENV_JUMP(2)</code>, while
<a href="../../lib/Pod/perlfunc.html#item_die"><code>die</code></a> within <a href="../../lib/Pod/perlfunc.html#item_eval"><code>eval</code></a> does a <code>JMPENV_JUMP(3)</code>.</p>
</dd>
<dd>
<p>At entry points to perl, such as <code>perl_parse()</code>, <code>perl_run()</code> and
<code>call_sv(cv, G_EVAL)</code> each does a <code>JMPENV_PUSH</code>, then enter a runops
loop or whatever, and handle possible exception returns. For a 2 return,
final cleanup is performed, such as popping stacks and calling <code>CHECK</code> or
<code>END</code> blocks. Amongst other things, this is how scope cleanup still
occurs during an <a href="../../lib/Pod/perlfunc.html#item_exit"><code>exit</code></a>.</p>
</dd>
<dd>
<p>If a <a href="../../lib/Pod/perlfunc.html#item_die"><code>die</code></a> can find a <code>CxEVAL</code> block on the context stack, then the
stack is popped to that level and the return op in that block is assigned
to <code>PL_restartop</code>; then a <code>JMPENV_JUMP(3)</code> is performed.  This normally
passes control back to the guard. In the case of <code>perl_run</code> and
<code>call_sv</code>, a non-null <code>PL_restartop</code> triggers re-entry to the runops
loop. The is the normal way that <a href="../../lib/Pod/perlfunc.html#item_die"><code>die</code></a> or <code>croak</code> is handled within an
<a href="../../lib/Pod/perlfunc.html#item_eval"><code>eval</code></a>.</p>
</dd>
<dd>
<p>Sometimes ops are executed within an inner runops loop, such as tie, sort
or overload code. In this case, something like</p>
</dd>
<dd>
<pre>
    <span class="keyword">sub</span><span class="variable"> FETCH </span><span class="operator">{</span> <span class="keyword">eval</span> <span class="operator">{</span> <span class="keyword">die</span> <span class="operator">}</span> <span class="operator">}</span>
</pre>
</dd>
<dd>
<p>would cause a longjmp right back to the guard in <code>perl_run</code>, popping both
runops loops, which is clearly incorrect. One way to avoid this is for the
tie code to do a <code>JMPENV_PUSH</code> before executing <code>FETCH</code> in the inner
runops loop, but for efficiency reasons, perl in fact just sets a flag,
using <code>CATCH_SET(TRUE)</code>. The <code>pp_require</code>, <code>pp_entereval</code> and
<code>pp_entertry</code> ops check this flag, and if true, they call <code>docatch</code>,
which does a <code>JMPENV_PUSH</code> and starts a new runops level to execute the
code, rather than doing it on the current loop.</p>
</dd>
<dd>
<p>As a further optimisation, on exit from the eval block in the <code>FETCH</code>,
execution of the code following the block is still carried on in the inner
loop.  When an exception is raised, <code>docatch</code> compares the <code>JMPENV</code>
level of the <code>CxEVAL</code> with <code>PL_top_env</code> and if they differ, just
re-throws the exception. In this way any inner loops get popped.</p>
</dd>
<dd>
<p>Here's an example.</p>
</dd>
<dd>
<pre>
    <span class="number">1</span><span class="operator">:</span> <span class="keyword">eval</span> <span class="operator">{</span> <span class="keyword">tie</span> <span class="variable">@a</span><span class="operator">,</span> <span class="string">'A'</span> <span class="operator">};</span>
    <span class="number">2</span><span class="operator">:</span> <span class="keyword">sub</span><span class="variable"> A::TIEARRAY </span><span class="operator">{</span>
    <span class="number">3</span><span class="operator">:</span>     <span class="keyword">eval</span> <span class="operator">{</span> <span class="keyword">die</span> <span class="operator">};</span>
    <span class="number">4</span><span class="operator">:</span>     <span class="keyword">die</span><span class="operator">;</span>
    <span class="number">5</span><span class="operator">:</span> <span class="operator">}</span>
</pre>
</dd>
<dd>
<p>To run this code, <code>perl_run</code> is called, which does a <code>JMPENV_PUSH</code> then
enters a runops loop. This loop executes the eval and tie ops on line 1,
with the eval pushing a <code>CxEVAL</code> onto the context stack.</p>
</dd>
<dd>
<p>The <code>pp_tie</code> does a <code>CATCH_SET(TRUE)</code>, then starts a second runops loop
to execute the body of <code>TIEARRAY</code>. When it executes the entertry op on
line 3, <code>CATCH_GET</code> is true, so <code>pp_entertry</code> calls <code>docatch</code> which
does a <code>JMPENV_PUSH</code> and starts a third runops loop, which then executes
the die op. At this point the C call stack looks like this:</p>
</dd>
<dd>
<pre>
    Perl_pp_die
    Perl_runops      # third loop
    S_docatch_body
    S_docatch
    Perl_pp_entertry
    Perl_runops      # second loop
    S_call_body
    Perl_call_sv
    Perl_pp_tie
    Perl_runops      # first loop
    S_run_

⌨️ 快捷键说明

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