1PERLGUTS(1)            Perl Programmers Reference Guide            PERLGUTS(1)
2
3
4

NAME

6       perlguts - Introduction to the Perl API
7

DESCRIPTION

9       This document attempts to describe how to use the Perl API, as well as
10       to provide some info on the basic workings of the Perl core.  It is far
11       from complete and probably contains many errors.  Please refer any
12       questions or comments to the author below.
13

Variables

15   Datatypes
16       Perl has three typedefs that handle Perl's three main data types:
17
18           SV  Scalar Value
19           AV  Array Value
20           HV  Hash Value
21
22       Each typedef has specific routines that manipulate the various data
23       types.
24
25   What is an "IV"?
26       Perl uses a special typedef IV which is a simple signed integer type
27       that is guaranteed to be large enough to hold a pointer (as well as an
28       integer).  Additionally, there is the UV, which is simply an unsigned
29       IV.
30
31       Perl also uses several special typedefs to declare variables to hold
32       integers of (at least) a given size.  Use I8, I16, I32, and I64 to
33       declare a signed integer variable which has at least as many bits as
34       the number in its name.  These all evaluate to the native C type that
35       is closest to the given number of bits, but no smaller than that
36       number.  For example, on many platforms, a "short" is 16 bits long, and
37       if so, I16 will evaluate to a "short".  But on platforms where a
38       "short" isn't exactly 16 bits, Perl will use the smallest type that
39       contains 16 bits or more.
40
41       U8, U16, U32, and U64 are to declare the corresponding unsigned integer
42       types.
43
44       If the platform doesn't support 64-bit integers, both I64 and U64 will
45       be undefined.  Use IV and UV to declare the largest practicable, and
46       ""WIDEST_UTYPE" in perlapi" for the absolute maximum unsigned, but
47       which may not be usable in all circumstances.
48
49       A numeric constant can be specified with ""INT16_C"" in perlapi,
50       ""UINTMAX_C"" in perlapi, and similar.
51
52   Working with SVs
53       An SV can be created and loaded with one command.  There are five types
54       of values that can be loaded: an integer value (IV), an unsigned
55       integer value (UV), a double (NV), a string (PV), and another scalar
56       (SV).  ("PV" stands for "Pointer Value".  You might think that it is
57       misnamed because it is described as pointing only to strings.  However,
58       it is possible to have it point to other things.  For example, it could
59       point to an array of UVs.  But, using it for non-strings requires care,
60       as the underlying assumption of much of the internals is that PVs are
61       just for strings.  Often, for example, a trailing "NUL" is tacked on
62       automatically.  The non-string use is documented only in this
63       paragraph.)
64
65       The seven routines are:
66
67           SV*  newSViv(IV);
68           SV*  newSVuv(UV);
69           SV*  newSVnv(double);
70           SV*  newSVpv(const char*, STRLEN);
71           SV*  newSVpvn(const char*, STRLEN);
72           SV*  newSVpvf(const char*, ...);
73           SV*  newSVsv(SV*);
74
75       "STRLEN" is an integer type ("Size_t", usually defined as "size_t" in
76       config.h) guaranteed to be large enough to represent the size of any
77       string that perl can handle.
78
79       In the unlikely case of a SV requiring more complex initialization, you
80       can create an empty SV with newSV(len).  If "len" is 0 an empty SV of
81       type NULL is returned, else an SV of type PV is returned with len + 1
82       (for the "NUL") bytes of storage allocated, accessible via SvPVX.  In
83       both cases the SV has the undef value.
84
85           SV *sv = newSV(0);   /* no storage allocated  */
86           SV *sv = newSV(10);  /* 10 (+1) bytes of uninitialised storage
87                                 * allocated */
88
89       To change the value of an already-existing SV, there are eight
90       routines:
91
92           void  sv_setiv(SV*, IV);
93           void  sv_setuv(SV*, UV);
94           void  sv_setnv(SV*, double);
95           void  sv_setpv(SV*, const char*);
96           void  sv_setpvn(SV*, const char*, STRLEN)
97           void  sv_setpvf(SV*, const char*, ...);
98           void  sv_vsetpvfn(SV*, const char*, STRLEN, va_list *,
99                                               SV **, Size_t, bool *);
100           void  sv_setsv(SV*, SV*);
101
102       Notice that you can choose to specify the length of the string to be
103       assigned by using "sv_setpvn", "newSVpvn", or "newSVpv", or you may
104       allow Perl to calculate the length by using "sv_setpv" or by specifying
105       0 as the second argument to "newSVpv".  Be warned, though, that Perl
106       will determine the string's length by using "strlen", which depends on
107       the string terminating with a "NUL" character, and not otherwise
108       containing NULs.
109
110       The arguments of "sv_setpvf" are processed like "sprintf", and the
111       formatted output becomes the value.
112
113       "sv_vsetpvfn" is an analogue of "vsprintf", but it allows you to
114       specify either a pointer to a variable argument list or the address and
115       length of an array of SVs.  The last argument points to a boolean; on
116       return, if that boolean is true, then locale-specific information has
117       been used to format the string, and the string's contents are therefore
118       untrustworthy (see perlsec).  This pointer may be NULL if that
119       information is not important.  Note that this function requires you to
120       specify the length of the format.
121
122       The "sv_set*()" functions are not generic enough to operate on values
123       that have "magic".  See "Magic Virtual Tables" later in this document.
124
125       All SVs that contain strings should be terminated with a "NUL"
126       character.  If it is not "NUL"-terminated there is a risk of core dumps
127       and corruptions from code which passes the string to C functions or
128       system calls which expect a "NUL"-terminated string.  Perl's own
129       functions typically add a trailing "NUL" for this reason.
130       Nevertheless, you should be very careful when you pass a string stored
131       in an SV to a C function or system call.
132
133       To access the actual value that an SV points to, Perl's API exposes
134       several macros that coerce the actual scalar type into an IV, UV,
135       double, or string:
136
137       •   SvIV(SV*) ("IV") and SvUV(SV*) ("UV")
138
139       •   SvNV(SV*) ("double")
140
141       •   Strings are a bit complicated:
142
143           •   Byte string: "SvPVbyte(SV*, STRLEN len)" or SvPVbyte_nolen(SV*)
144
145               If the Perl string is "\xff\xff", then this returns a 2-byte
146               "char*".
147
148               This is suitable for Perl strings that represent bytes.
149
150           •   UTF-8 string: "SvPVutf8(SV*, STRLEN len)" or
151               SvPVutf8_nolen(SV*)
152
153               If the Perl string is "\xff\xff", then this returns a 4-byte
154               "char*".
155
156               This is suitable for Perl strings that represent characters.
157
158               CAVEAT: That "char*" will be encoded via Perl's internal UTF-8
159               variant, which means that if the SV contains non-Unicode code
160               points (e.g., 0x110000), then the result may contain extensions
161               over valid UTF-8.  See "is_strict_utf8_string" in perlapi for
162               some methods Perl gives you to check the UTF-8 validity of
163               these macros' returns.
164
165           •   You can also use "SvPV(SV*, STRLEN len)" or SvPV_nolen(SV*) to
166               fetch the SV's raw internal buffer. This is tricky, though; if
167               your Perl string is "\xff\xff", then depending on the SV's
168               internal encoding you might get back a 2-byte OR a 4-byte
169               "char*".  Moreover, if it's the 4-byte string, that could come
170               from either Perl "\xff\xff" stored UTF-8 encoded, or Perl
171               "\xc3\xbf\xc3\xbf" stored as raw octets. To differentiate
172               between these you MUST look up the SV's UTF8 bit (cf. "SvUTF8")
173               to know whether the source Perl string is 2 characters
174               ("SvUTF8" would be on) or 4 characters ("SvUTF8" would be off).
175
176               IMPORTANT: Use of "SvPV", "SvPV_nolen", or similarly-named
177               macros without looking up the SV's UTF8 bit is almost certainly
178               a bug if non-ASCII input is allowed.
179
180               When the UTF8 bit is on, the same CAVEAT about UTF-8 validity
181               applies here as for "SvPVutf8".
182
183           (See "How do I pass a Perl string to a C library?" for more
184           details.)
185
186           In "SvPVbyte", "SvPVutf8", and "SvPV", the length of the "char*"
187           returned is placed into the variable "len" (these are macros, so
188           you do not use &len). If you do not care what the length of the
189           data is, use "SvPVbyte_nolen", "SvPVutf8_nolen", or "SvPV_nolen"
190           instead.  The global variable "PL_na" can also be given to
191           "SvPVbyte"/"SvPVutf8"/"SvPV" in this case.  But that can be quite
192           inefficient because "PL_na" must be accessed in thread-local
193           storage in threaded Perl.  In any case, remember that Perl allows
194           arbitrary strings of data that may both contain NULs and might not
195           be terminated by a "NUL".
196
197           Also remember that C doesn't allow you to safely say
198           "foo(SvPVbyte(s, len), len);".  It might work with your compiler,
199           but it won't work for everyone.  Break this sort of statement up
200           into separate assignments:
201
202               SV *s;
203               STRLEN len;
204               char *ptr;
205               ptr = SvPVbyte(s, len);
206               foo(ptr, len);
207
208       If you want to know if the scalar value is TRUE, you can use:
209
210           SvTRUE(SV*)
211
212       Although Perl will automatically grow strings for you, if you need to
213       force Perl to allocate more memory for your SV, you can use the macro
214
215           SvGROW(SV*, STRLEN newlen)
216
217       which will determine if more memory needs to be allocated.  If so, it
218       will call the function "sv_grow".  Note that "SvGROW" can only
219       increase, not decrease, the allocated memory of an SV and that it does
220       not automatically add space for the trailing "NUL" byte (perl's own
221       string functions typically do "SvGROW(sv, len + 1)").
222
223       If you want to write to an existing SV's buffer and set its value to a
224       string, use SvPVbyte_force() or one of its variants to force the SV to
225       be a PV.  This will remove any of various types of non-stringness from
226       the SV while preserving the content of the SV in the PV.  This can be
227       used, for example, to append data from an API function to a buffer
228       without extra copying:
229
230           (void)SvPVbyte_force(sv, len);
231           s = SvGROW(sv, len + needlen + 1);
232           /* something that modifies up to needlen bytes at s+len, but
233              modifies newlen bytes
234                eg. newlen = read(fd, s + len, needlen);
235              ignoring errors for these examples
236            */
237           s[len + newlen] = '\0';
238           SvCUR_set(sv, len + newlen);
239           SvUTF8_off(sv);
240           SvSETMAGIC(sv);
241
242       If you already have the data in memory or if you want to keep your code
243       simple, you can use one of the sv_cat*() variants, such as sv_catpvn().
244       If you want to insert anywhere in the string you can use sv_insert() or
245       sv_insert_flags().
246
247       If you don't need the existing content of the SV, you can avoid some
248       copying with:
249
250           SvPVCLEAR(sv);
251           s = SvGROW(sv, needlen + 1);
252           /* something that modifies up to needlen bytes at s, but modifies
253              newlen bytes
254                eg. newlen = read(fd, s, needlen);
255            */
256           s[newlen] = '\0';
257           SvCUR_set(sv, newlen);
258           SvPOK_only(sv); /* also clears SVf_UTF8 */
259           SvSETMAGIC(sv);
260
261       Again, if you already have the data in memory or want to avoid the
262       complexity of the above, you can use sv_setpvn().
263
264       If you have a buffer allocated with Newx() and want to set that as the
265       SV's value, you can use sv_usepvn_flags().  That has some requirements
266       if you want to avoid perl re-allocating the buffer to fit the trailing
267       NUL:
268
269          Newx(buf, somesize+1, char);
270          /* ... fill in buf ... */
271          buf[somesize] = '\0';
272          sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_NUL);
273          /* buf now belongs to perl, don't release it */
274
275       If you have an SV and want to know what kind of data Perl thinks is
276       stored in it, you can use the following macros to check the type of SV
277       you have.
278
279           SvIOK(SV*)
280           SvNOK(SV*)
281           SvPOK(SV*)
282
283       Be aware that retrieving the numeric value of an SV can set IOK or NOK
284       on that SV, even when the SV started as a string.  Prior to Perl 5.36.0
285       retrieving the string value of an integer could set POK, but this can
286       no longer occur.  From 5.36.0 this can be used to distinguish the
287       original representation of an SV and is intended to make life simpler
288       for serializers:
289
290           /* references handled elsewhere */
291           if (SvIsBOOL(sv)) {
292               /* originally boolean */
293               ...
294           }
295           else if (SvPOK(sv)) {
296               /* originally a string */
297               ...
298           }
299           else if (SvNIOK(sv)) {
300               /* originally numeric */
301               ...
302           }
303           else {
304               /* something special or undef */
305           }
306
307       You can get and set the current length of the string stored in an SV
308       with the following macros:
309
310           SvCUR(SV*)
311           SvCUR_set(SV*, I32 val)
312
313       You can also get a pointer to the end of the string stored in the SV
314       with the macro:
315
316           SvEND(SV*)
317
318       But note that these last three macros are valid only if SvPOK() is
319       true.
320
321       If you want to append something to the end of string stored in an
322       "SV*", you can use the following functions:
323
324           void  sv_catpv(SV*, const char*);
325           void  sv_catpvn(SV*, const char*, STRLEN);
326           void  sv_catpvf(SV*, const char*, ...);
327           void  sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **,
328                                                                    I32, bool);
329           void  sv_catsv(SV*, SV*);
330
331       The first function calculates the length of the string to be appended
332       by using "strlen".  In the second, you specify the length of the string
333       yourself.  The third function processes its arguments like "sprintf"
334       and appends the formatted output.  The fourth function works like
335       "vsprintf".  You can specify the address and length of an array of SVs
336       instead of the va_list argument.  The fifth function extends the string
337       stored in the first SV with the string stored in the second SV.  It
338       also forces the second SV to be interpreted as a string.
339
340       The "sv_cat*()" functions are not generic enough to operate on values
341       that have "magic".  See "Magic Virtual Tables" later in this document.
342
343       If you know the name of a scalar variable, you can get a pointer to its
344       SV by using the following:
345
346           SV*  get_sv("package::varname", 0);
347
348       This returns NULL if the variable does not exist.
349
350       If you want to know if this variable (or any other SV) is actually
351       "defined", you can call:
352
353           SvOK(SV*)
354
355       The scalar "undef" value is stored in an SV instance called
356       "PL_sv_undef".
357
358       Its address can be used whenever an "SV*" is needed.  Make sure that
359       you don't try to compare a random sv with &PL_sv_undef.  For example
360       when interfacing Perl code, it'll work correctly for:
361
362         foo(undef);
363
364       But won't work when called as:
365
366         $x = undef;
367         foo($x);
368
369       So to repeat always use SvOK() to check whether an sv is defined.
370
371       Also you have to be careful when using &PL_sv_undef as a value in AVs
372       or HVs (see "AVs, HVs and undefined values").
373
374       There are also the two values "PL_sv_yes" and "PL_sv_no", which contain
375       boolean TRUE and FALSE values, respectively.  Like "PL_sv_undef", their
376       addresses can be used whenever an "SV*" is needed.
377
378       Do not be fooled into thinking that "(SV *) 0" is the same as
379       &PL_sv_undef.  Take this code:
380
381           SV* sv = (SV*) 0;
382           if (I-am-to-return-a-real-value) {
383                   sv = sv_2mortal(newSViv(42));
384           }
385           sv_setsv(ST(0), sv);
386
387       This code tries to return a new SV (which contains the value 42) if it
388       should return a real value, or undef otherwise.  Instead it has
389       returned a NULL pointer which, somewhere down the line, will cause a
390       segmentation violation, bus error, or just weird results.  Change the
391       zero to &PL_sv_undef in the first line and all will be well.
392
393       To free an SV that you've created, call SvREFCNT_dec(SV*).  Normally
394       this call is not necessary (see "Reference Counts and Mortality").
395
396   Offsets
397       Perl provides the function "sv_chop" to efficiently remove characters
398       from the beginning of a string; you give it an SV and a pointer to
399       somewhere inside the PV, and it discards everything before the pointer.
400       The efficiency comes by means of a little hack: instead of actually
401       removing the characters, "sv_chop" sets the flag "OOK" (offset OK) to
402       signal to other functions that the offset hack is in effect, and it
403       moves the PV pointer (called "SvPVX") forward by the number of bytes
404       chopped off, and adjusts "SvCUR" and "SvLEN" accordingly.  (A portion
405       of the space between the old and new PV pointers is used to store the
406       count of chopped bytes.)
407
408       Hence, at this point, the start of the buffer that we allocated lives
409       at "SvPVX(sv) - SvIV(sv)" in memory and the PV pointer is pointing into
410       the middle of this allocated storage.
411
412       This is best demonstrated by example.  Normally copy-on-write will
413       prevent the substitution from operator from using this hack, but if you
414       can craft a string for which copy-on-write is not possible, you can see
415       it in play.  In the current implementation, the final byte of a string
416       buffer is used as a copy-on-write reference count.  If the buffer is
417       not big enough, then copy-on-write is skipped.  First have a look at an
418       empty string:
419
420         % ./perl -Ilib -MDevel::Peek -le '$a=""; $a .= ""; Dump $a'
421         SV = PV(0x7ffb7c008a70) at 0x7ffb7c030390
422           REFCNT = 1
423           FLAGS = (POK,pPOK)
424           PV = 0x7ffb7bc05b50 ""\0
425           CUR = 0
426           LEN = 10
427
428       Notice here the LEN is 10.  (It may differ on your platform.)  Extend
429       the length of the string to one less than 10, and do a substitution:
430
431        % ./perl -Ilib -MDevel::Peek -le '$a=""; $a.="123456789"; $a=~s/.//; \
432                                                                   Dump($a)'
433        SV = PV(0x7ffa04008a70) at 0x7ffa04030390
434          REFCNT = 1
435          FLAGS = (POK,OOK,pPOK)
436          OFFSET = 1
437          PV = 0x7ffa03c05b61 ( "\1" . ) "23456789"\0
438          CUR = 8
439          LEN = 9
440
441       Here the number of bytes chopped off (1) is shown next as the OFFSET.
442       The portion of the string between the "real" and the "fake" beginnings
443       is shown in parentheses, and the values of "SvCUR" and "SvLEN" reflect
444       the fake beginning, not the real one.  (The first character of the
445       string buffer happens to have changed to "\1" here, not "1", because
446       the current implementation stores the offset count in the string
447       buffer.  This is subject to change.)
448
449       Something similar to the offset hack is performed on AVs to enable
450       efficient shifting and splicing off the beginning of the array; while
451       "AvARRAY" points to the first element in the array that is visible from
452       Perl, "AvALLOC" points to the real start of the C array.  These are
453       usually the same, but a "shift" operation can be carried out by
454       increasing "AvARRAY" by one and decreasing "AvFILL" and "AvMAX".
455       Again, the location of the real start of the C array only comes into
456       play when freeing the array.  See "av_shift" in av.c.
457
458   What's Really Stored in an SV?
459       Recall that the usual method of determining the type of scalar you have
460       is to use "Sv*OK" macros.  Because a scalar can be both a number and a
461       string, usually these macros will always return TRUE and calling the
462       "Sv*V" macros will do the appropriate conversion of string to
463       integer/double or integer/double to string.
464
465       If you really need to know if you have an integer, double, or string
466       pointer in an SV, you can use the following three macros instead:
467
468           SvIOKp(SV*)
469           SvNOKp(SV*)
470           SvPOKp(SV*)
471
472       These will tell you if you truly have an integer, double, or string
473       pointer stored in your SV.  The "p" stands for private.
474
475       There are various ways in which the private and public flags may
476       differ.  For example, in perl 5.16 and earlier a tied SV may have a
477       valid underlying value in the IV slot (so SvIOKp is true), but the data
478       should be accessed via the FETCH routine rather than directly, so SvIOK
479       is false.  (In perl 5.18 onwards, tied scalars use the flags the same
480       way as untied scalars.)  Another is when numeric conversion has
481       occurred and precision has been lost: only the private flag is set on
482       'lossy' values.  So when an NV is converted to an IV with loss, SvIOKp,
483       SvNOKp and SvNOK will be set, while SvIOK wont be.
484
485       In general, though, it's best to use the "Sv*V" macros.
486
487   Working with AVs
488       There are two main, longstanding ways to create and load an AV.  The
489       first method creates an empty AV:
490
491           AV*  newAV();
492
493       The second method both creates the AV and initially populates it with
494       SVs:
495
496           AV*  av_make(SSize_t num, SV **ptr);
497
498       The second argument points to an array containing "num" "SV*"'s.  Once
499       the AV has been created, the SVs can be destroyed, if so desired.
500
501       Perl v5.36 added two new ways to create an AV and allocate a SV** array
502       without populating it. These are more efficient than a newAV() followed
503       by an av_extend().
504
505           /* Creates but does not initialize (Zero) the SV** array */
506           AV *av = newAV_alloc_x(1);
507           /* Creates and does initialize (Zero) the SV** array */
508           AV *av = newAV_alloc_xz(1);
509
510       The numerical argument refers to the number of array elements to
511       allocate, not an array index, and must be >0. The first form must only
512       ever be used when all elements will be initialized before any read
513       occurs. Reading a non-initialized SV* - i.e. treating a random memory
514       address as a SV* - is a serious bug.
515
516       Once the AV has been created, the following operations are possible on
517       it:
518
519           void  av_push(AV*, SV*);
520           SV*   av_pop(AV*);
521           SV*   av_shift(AV*);
522           void  av_unshift(AV*, SSize_t num);
523
524       These should be familiar operations, with the exception of
525       "av_unshift".  This routine adds "num" elements at the front of the
526       array with the "undef" value.  You must then use "av_store" (described
527       below) to assign values to these new elements.
528
529       Here are some other functions:
530
531           SSize_t av_top_index(AV*);
532           SV**    av_fetch(AV*, SSize_t key, I32 lval);
533           SV**    av_store(AV*, SSize_t key, SV* val);
534
535       The "av_top_index" function returns the highest index value in an array
536       (just like $#array in Perl).  If the array is empty, -1 is returned.
537       The "av_fetch" function returns the value at index "key", but if "lval"
538       is non-zero, then "av_fetch" will store an undef value at that index.
539       The "av_store" function stores the value "val" at index "key", and does
540       not increment the reference count of "val".  Thus the caller is
541       responsible for taking care of that, and if "av_store" returns NULL,
542       the caller will have to decrement the reference count to avoid a memory
543       leak.  Note that "av_fetch" and "av_store" both return "SV**"'s, not
544       "SV*"'s as their return value.
545
546       A few more:
547
548           void  av_clear(AV*);
549           void  av_undef(AV*);
550           void  av_extend(AV*, SSize_t key);
551
552       The "av_clear" function deletes all the elements in the AV* array, but
553       does not actually delete the array itself.  The "av_undef" function
554       will delete all the elements in the array plus the array itself.  The
555       "av_extend" function extends the array so that it contains at least
556       "key+1" elements.  If "key+1" is less than the currently allocated
557       length of the array, then nothing is done.
558
559       If you know the name of an array variable, you can get a pointer to its
560       AV by using the following:
561
562           AV*  get_av("package::varname", 0);
563
564       This returns NULL if the variable does not exist.
565
566       See "Understanding the Magic of Tied Hashes and Arrays" for more
567       information on how to use the array access functions on tied arrays.
568
569       More efficient working with new or vanilla AVs
570
571       Perl v5.36 and v5.38 introduced streamlined, inlined versions of some
572       functions:
573
574       •   "av_store_simple"
575
576       •   "av_fetch_simple"
577
578       •   "av_push_simple"
579
580       These are drop-in replacements, but can only be used on straightforward
581       AVs that meet the following criteria:
582
583       •   are not magical
584
585       •   are not readonly
586
587       •   are "real" (refcounted) AVs
588
589       •   have an av_top_index value > -2
590
591       AVs created using newAV(), "av_make", "newAV_alloc_x", and
592       "newAV_alloc_xz" are all compatible at the time of creation. It is only
593       if they are declared readonly or unreal, have magic attached, or are
594       otherwise configured unusually that they will stop being compatible.
595
596       Note that some interpreter functions may attach magic to an AV as part
597       of normal operations. It is therefore safest, unless you are sure of
598       the lifecycle of an AV, to only use these new functions close to the
599       point of AV creation.
600
601   Working with HVs
602       To create an HV, you use the following routine:
603
604           HV*  newHV();
605
606       Once the HV has been created, the following operations are possible on
607       it:
608
609           SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
610           SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);
611
612       The "klen" parameter is the length of the key being passed in (Note
613       that you cannot pass 0 in as a value of "klen" to tell Perl to measure
614       the length of the key).  The "val" argument contains the SV pointer to
615       the scalar being stored, and "hash" is the precomputed hash value (zero
616       if you want "hv_store" to calculate it for you).  The "lval" parameter
617       indicates whether this fetch is actually a part of a store operation,
618       in which case a new undefined value will be added to the HV with the
619       supplied key and "hv_fetch" will return as if the value had already
620       existed.
621
622       Remember that "hv_store" and "hv_fetch" return "SV**"'s and not just
623       "SV*".  To access the scalar value, you must first dereference the
624       return value.  However, you should check to make sure that the return
625       value is not NULL before dereferencing it.
626
627       The first of these two functions checks if a hash table entry exists,
628       and the second deletes it.
629
630           bool  hv_exists(HV*, const char* key, U32 klen);
631           SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);
632
633       If "flags" does not include the "G_DISCARD" flag then "hv_delete" will
634       create and return a mortal copy of the deleted value.
635
636       And more miscellaneous functions:
637
638           void   hv_clear(HV*);
639           void   hv_undef(HV*);
640
641       Like their AV counterparts, "hv_clear" deletes all the entries in the
642       hash table but does not actually delete the hash table.  The "hv_undef"
643       deletes both the entries and the hash table itself.
644
645       Perl keeps the actual data in a linked list of structures with a
646       typedef of HE.  These contain the actual key and value pointers (plus
647       extra administrative overhead).  The key is a string pointer; the value
648       is an "SV*".  However, once you have an "HE*", to get the actual key
649       and value, use the routines specified below.
650
651           I32    hv_iterinit(HV*);
652                   /* Prepares starting point to traverse hash table */
653           HE*    hv_iternext(HV*);
654                   /* Get the next entry, and return a pointer to a
655                      structure that has both the key and value */
656           char*  hv_iterkey(HE* entry, I32* retlen);
657                   /* Get the key from an HE structure and also return
658                      the length of the key string */
659           SV*    hv_iterval(HV*, HE* entry);
660                   /* Return an SV pointer to the value of the HE
661                      structure */
662           SV*    hv_iternextsv(HV*, char** key, I32* retlen);
663                   /* This convenience routine combines hv_iternext,
664                      hv_iterkey, and hv_iterval.  The key and retlen
665                      arguments are return values for the key and its
666                      length.  The value is returned in the SV* argument */
667
668       If you know the name of a hash variable, you can get a pointer to its
669       HV by using the following:
670
671           HV*  get_hv("package::varname", 0);
672
673       This returns NULL if the variable does not exist.
674
675       The hash algorithm is defined in the "PERL_HASH" macro:
676
677           PERL_HASH(hash, key, klen)
678
679       The exact implementation of this macro varies by architecture and
680       version of perl, and the return value may change per invocation, so the
681       value is only valid for the duration of a single perl process.
682
683       See "Understanding the Magic of Tied Hashes and Arrays" for more
684       information on how to use the hash access functions on tied hashes.
685
686   Hash API Extensions
687       Beginning with version 5.004, the following functions are also
688       supported:
689
690           HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
691           HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);
692
693           bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
694           SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
695
696           SV*     hv_iterkeysv  (HE* entry);
697
698       Note that these functions take "SV*" keys, which simplifies writing of
699       extension code that deals with hash structures.  These functions also
700       allow passing of "SV*" keys to "tie" functions without forcing you to
701       stringify the keys (unlike the previous set of functions).
702
703       They also return and accept whole hash entries ("HE*"), making their
704       use more efficient (since the hash number for a particular string
705       doesn't have to be recomputed every time).  See perlapi for detailed
706       descriptions.
707
708       The following macros must always be used to access the contents of hash
709       entries.  Note that the arguments to these macros must be simple
710       variables, since they may get evaluated more than once.  See perlapi
711       for detailed descriptions of these macros.
712
713           HePV(HE* he, STRLEN len)
714           HeVAL(HE* he)
715           HeHASH(HE* he)
716           HeSVKEY(HE* he)
717           HeSVKEY_force(HE* he)
718           HeSVKEY_set(HE* he, SV* sv)
719
720       These two lower level macros are defined, but must only be used when
721       dealing with keys that are not "SV*"s:
722
723           HeKEY(HE* he)
724           HeKLEN(HE* he)
725
726       Note that both "hv_store" and "hv_store_ent" do not increment the
727       reference count of the stored "val", which is the caller's
728       responsibility.  If these functions return a NULL value, the caller
729       will usually have to decrement the reference count of "val" to avoid a
730       memory leak.
731
732   AVs, HVs and undefined values
733       Sometimes you have to store undefined values in AVs or HVs.  Although
734       this may be a rare case, it can be tricky.  That's because you're used
735       to using &PL_sv_undef if you need an undefined SV.
736
737       For example, intuition tells you that this XS code:
738
739           AV *av = newAV();
740           av_store( av, 0, &PL_sv_undef );
741
742       is equivalent to this Perl code:
743
744           my @av;
745           $av[0] = undef;
746
747       Unfortunately, this isn't true.  In perl 5.18 and earlier, AVs use
748       &PL_sv_undef as a marker for indicating that an array element has not
749       yet been initialized.  Thus, "exists $av[0]" would be true for the
750       above Perl code, but false for the array generated by the XS code.  In
751       perl 5.20, storing &PL_sv_undef will create a read-only element,
752       because the scalar &PL_sv_undef itself is stored, not a copy.
753
754       Similar problems can occur when storing &PL_sv_undef in HVs:
755
756           hv_store( hv, "key", 3, &PL_sv_undef, 0 );
757
758       This will indeed make the value "undef", but if you try to modify the
759       value of "key", you'll get the following error:
760
761           Modification of non-creatable hash value attempted
762
763       In perl 5.8.0, &PL_sv_undef was also used to mark placeholders in
764       restricted hashes.  This caused such hash entries not to appear when
765       iterating over the hash or when checking for the keys with the
766       "hv_exists" function.
767
768       You can run into similar problems when you store &PL_sv_yes or
769       &PL_sv_no into AVs or HVs.  Trying to modify such elements will give
770       you the following error:
771
772           Modification of a read-only value attempted
773
774       To make a long story short, you can use the special variables
775       &PL_sv_undef, &PL_sv_yes and &PL_sv_no with AVs and HVs, but you have
776       to make sure you know what you're doing.
777
778       Generally, if you want to store an undefined value in an AV or HV, you
779       should not use &PL_sv_undef, but rather create a new undefined value
780       using the "newSV" function, for example:
781
782           av_store( av, 42, newSV(0) );
783           hv_store( hv, "foo", 3, newSV(0), 0 );
784
785   References
786       References are a special type of scalar that point to other data types
787       (including other references).
788
789       To create a reference, use either of the following functions:
790
791           SV* newRV_inc((SV*) thing);
792           SV* newRV_noinc((SV*) thing);
793
794       The "thing" argument can be any of an "SV*", "AV*", or "HV*".  The
795       functions are identical except that "newRV_inc" increments the
796       reference count of the "thing", while "newRV_noinc" does not.  For
797       historical reasons, "newRV" is a synonym for "newRV_inc".
798
799       Once you have a reference, you can use the following macro to
800       dereference the reference:
801
802           SvRV(SV*)
803
804       then call the appropriate routines, casting the returned "SV*" to
805       either an "AV*" or "HV*", if required.
806
807       To determine if an SV is a reference, you can use the following macro:
808
809           SvROK(SV*)
810
811       To discover what type of value the reference refers to, use the
812       following macro and then check the return value.
813
814           SvTYPE(SvRV(SV*))
815
816       The most useful types that will be returned are:
817
818           SVt_PVAV    Array
819           SVt_PVHV    Hash
820           SVt_PVCV    Code
821           SVt_PVGV    Glob (possibly a file handle)
822
823       Any numerical value returned which is less than SVt_PVAV will be a
824       scalar of some form.
825
826       See "svtype" in perlapi for more details.
827
828   Blessed References and Class Objects
829       References are also used to support object-oriented programming.  In
830       perl's OO lexicon, an object is simply a reference that has been
831       blessed into a package (or class).  Once blessed, the programmer may
832       now use the reference to access the various methods in the class.
833
834       A reference can be blessed into a package with the following function:
835
836           SV* sv_bless(SV* sv, HV* stash);
837
838       The "sv" argument must be a reference value.  The "stash" argument
839       specifies which class the reference will belong to.  See "Stashes and
840       Globs" for information on converting class names into stashes.
841
842       /* Still under construction */
843
844       The following function upgrades rv to reference if not already one.
845       Creates a new SV for rv to point to.  If "classname" is non-null, the
846       SV is blessed into the specified class.  SV is returned.
847
848               SV* newSVrv(SV* rv, const char* classname);
849
850       The following three functions copy integer, unsigned integer or double
851       into an SV whose reference is "rv".  SV is blessed if "classname" is
852       non-null.
853
854               SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
855               SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
856               SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
857
858       The following function copies the pointer value (the address, not the
859       string!) into an SV whose reference is rv.  SV is blessed if
860       "classname" is non-null.
861
862               SV* sv_setref_pv(SV* rv, const char* classname, void* pv);
863
864       The following function copies a string into an SV whose reference is
865       "rv".  Set length to 0 to let Perl calculate the string length.  SV is
866       blessed if "classname" is non-null.
867
868           SV* sv_setref_pvn(SV* rv, const char* classname, char* pv,
869                                                                STRLEN length);
870
871       The following function tests whether the SV is blessed into the
872       specified class.  It does not check inheritance relationships.
873
874               int  sv_isa(SV* sv, const char* name);
875
876       The following function tests whether the SV is a reference to a blessed
877       object.
878
879               int  sv_isobject(SV* sv);
880
881       The following function tests whether the SV is derived from the
882       specified class.  SV can be either a reference to a blessed object or a
883       string containing a class name.  This is the function implementing the
884       "UNIVERSAL::isa" functionality.
885
886               bool sv_derived_from(SV* sv, const char* name);
887
888       To check if you've got an object derived from a specific class you have
889       to write:
890
891               if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
892
893   Creating New Variables
894       To create a new Perl variable with an undef value which can be accessed
895       from your Perl script, use the following routines, depending on the
896       variable type.
897
898           SV*  get_sv("package::varname", GV_ADD);
899           AV*  get_av("package::varname", GV_ADD);
900           HV*  get_hv("package::varname", GV_ADD);
901
902       Notice the use of GV_ADD as the second parameter.  The new variable can
903       now be set, using the routines appropriate to the data type.
904
905       There are additional macros whose values may be bitwise OR'ed with the
906       "GV_ADD" argument to enable certain extra features.  Those bits are:
907
908       GV_ADDMULTI
909           Marks the variable as multiply defined, thus preventing the:
910
911             Name <varname> used only once: possible typo
912
913           warning.
914
915       GV_ADDWARN
916           Issues the warning:
917
918             Had to create <varname> unexpectedly
919
920           if the variable did not exist before the function was called.
921
922       If you do not specify a package name, the variable is created in the
923       current package.
924
925   Reference Counts and Mortality
926       Perl uses a reference count-driven garbage collection mechanism.  SVs,
927       AVs, or HVs (xV for short in the following) start their life with a
928       reference count of 1.  If the reference count of an xV ever drops to 0,
929       then it will be destroyed and its memory made available for reuse.  At
930       the most basic internal level, reference counts can be manipulated with
931       the following macros:
932
933           int SvREFCNT(SV* sv);
934           SV* SvREFCNT_inc(SV* sv);
935           void SvREFCNT_dec(SV* sv);
936
937       (There are also suffixed versions of the increment and decrement
938       macros, for situations where the full generality of these basic macros
939       can be exchanged for some performance.)
940
941       However, the way a programmer should think about references is not so
942       much in terms of the bare reference count, but in terms of ownership of
943       references.  A reference to an xV can be owned by any of a variety of
944       entities: another xV, the Perl interpreter, an XS data structure, a
945       piece of running code, or a dynamic scope.  An xV generally does not
946       know what entities own the references to it; it only knows how many
947       references there are, which is the reference count.
948
949       To correctly maintain reference counts, it is essential to keep track
950       of what references the XS code is manipulating.  The programmer should
951       always know where a reference has come from and who owns it, and be
952       aware of any creation or destruction of references, and any transfers
953       of ownership.  Because ownership isn't represented explicitly in the xV
954       data structures, only the reference count need be actually maintained
955       by the code, and that means that this understanding of ownership is not
956       actually evident in the code.  For example, transferring ownership of a
957       reference from one owner to another doesn't change the reference count
958       at all, so may be achieved with no actual code.  (The transferring code
959       doesn't touch the referenced object, but does need to ensure that the
960       former owner knows that it no longer owns the reference, and that the
961       new owner knows that it now does.)
962
963       An xV that is visible at the Perl level should not become unreferenced
964       and thus be destroyed.  Normally, an object will only become
965       unreferenced when it is no longer visible, often by the same means that
966       makes it invisible.  For example, a Perl reference value (RV) owns a
967       reference to its referent, so if the RV is overwritten that reference
968       gets destroyed, and the no-longer-reachable referent may be destroyed
969       as a result.
970
971       Many functions have some kind of reference manipulation as part of
972       their purpose.  Sometimes this is documented in terms of ownership of
973       references, and sometimes it is (less helpfully) documented in terms of
974       changes to reference counts.  For example, the newRV_inc() function is
975       documented to create a new RV (with reference count 1) and increment
976       the reference count of the referent that was supplied by the caller.
977       This is best understood as creating a new reference to the referent,
978       which is owned by the created RV, and returning to the caller ownership
979       of the sole reference to the RV.  The newRV_noinc() function instead
980       does not increment the reference count of the referent, but the RV
981       nevertheless ends up owning a reference to the referent.  It is
982       therefore implied that the caller of newRV_noinc() is relinquishing a
983       reference to the referent, making this conceptually a more complicated
984       operation even though it does less to the data structures.
985
986       For example, imagine you want to return a reference from an XSUB
987       function.  Inside the XSUB routine, you create an SV which initially
988       has just a single reference, owned by the XSUB routine.  This reference
989       needs to be disposed of before the routine is complete, otherwise it
990       will leak, preventing the SV from ever being destroyed.  So to create
991       an RV referencing the SV, it is most convenient to pass the SV to
992       newRV_noinc(), which consumes that reference.  Now the XSUB routine no
993       longer owns a reference to the SV, but does own a reference to the RV,
994       which in turn owns a reference to the SV.  The ownership of the
995       reference to the RV is then transferred by the process of returning the
996       RV from the XSUB.
997
998       There are some convenience functions available that can help with the
999       destruction of xVs.  These functions introduce the concept of
1000       "mortality".  Much documentation speaks of an xV itself being mortal,
1001       but this is misleading.  It is really a reference to an xV that is
1002       mortal, and it is possible for there to be more than one mortal
1003       reference to a single xV.  For a reference to be mortal means that it
1004       is owned by the temps stack, one of perl's many internal stacks, which
1005       will destroy that reference "a short time later".  Usually the "short
1006       time later" is the end of the current Perl statement.  However, it gets
1007       more complicated around dynamic scopes: there can be multiple sets of
1008       mortal references hanging around at the same time, with different death
1009       dates.  Internally, the actual determinant for when mortal xV
1010       references are destroyed depends on two macros, SAVETMPS and FREETMPS.
1011       See perlcall and perlxs and "Temporaries Stack" below for more details
1012       on these macros.
1013
1014       Mortal references are mainly used for xVs that are placed on perl's
1015       main stack.  The stack is problematic for reference tracking, because
1016       it contains a lot of xV references, but doesn't own those references:
1017       they are not counted.  Currently, there are many bugs resulting from
1018       xVs being destroyed while referenced by the stack, because the stack's
1019       uncounted references aren't enough to keep the xVs alive.  So when
1020       putting an (uncounted) reference on the stack, it is vitally important
1021       to ensure that there will be a counted reference to the same xV that
1022       will last at least as long as the uncounted reference.  But it's also
1023       important that that counted reference be cleaned up at an appropriate
1024       time, and not unduly prolong the xV's life.  For there to be a mortal
1025       reference is often the best way to satisfy this requirement, especially
1026       if the xV was created especially to be put on the stack and would
1027       otherwise be unreferenced.
1028
1029       To create a mortal reference, use the functions:
1030
1031           SV*  sv_newmortal()
1032           SV*  sv_mortalcopy(SV*)
1033           SV*  sv_2mortal(SV*)
1034
1035       sv_newmortal() creates an SV (with the undefined value) whose sole
1036       reference is mortal.  sv_mortalcopy() creates an xV whose value is a
1037       copy of a supplied xV and whose sole reference is mortal.  sv_2mortal()
1038       mortalises an existing xV reference: it transfers ownership of a
1039       reference from the caller to the temps stack.  Because "sv_newmortal"
1040       gives the new SV no value, it must normally be given one via
1041       "sv_setpv", "sv_setiv", etc. :
1042
1043           SV *tmp = sv_newmortal();
1044           sv_setiv(tmp, an_integer);
1045
1046       As that is multiple C statements it is quite common so see this idiom
1047       instead:
1048
1049           SV *tmp = sv_2mortal(newSViv(an_integer));
1050
1051       The mortal routines are not just for SVs; AVs and HVs can be made
1052       mortal by passing their address (type-casted to "SV*") to the
1053       "sv_2mortal" or "sv_mortalcopy" routines.
1054
1055   Stashes and Globs
1056       A stash is a hash that contains all variables that are defined within a
1057       package.  Each key of the stash is a symbol name (shared by all the
1058       different types of objects that have the same name), and each value in
1059       the hash table is a GV (Glob Value).  This GV in turn contains
1060       references to the various objects of that name, including (but not
1061       limited to) the following:
1062
1063           Scalar Value
1064           Array Value
1065           Hash Value
1066           I/O Handle
1067           Format
1068           Subroutine
1069
1070       There is a single stash called "PL_defstash" that holds the items that
1071       exist in the "main" package.  To get at the items in other packages,
1072       append the string "::" to the package name.  The items in the "Foo"
1073       package are in the stash "Foo::" in PL_defstash.  The items in the
1074       "Bar::Baz" package are in the stash "Baz::" in "Bar::"'s stash.
1075
1076       To get the stash pointer for a particular package, use the function:
1077
1078           HV*  gv_stashpv(const char* name, I32 flags)
1079           HV*  gv_stashsv(SV*, I32 flags)
1080
1081       The first function takes a literal string, the second uses the string
1082       stored in the SV.  Remember that a stash is just a hash table, so you
1083       get back an "HV*".  The "flags" flag will create a new package if it is
1084       set to GV_ADD.
1085
1086       The name that "gv_stash*v" wants is the name of the package whose
1087       symbol table you want.  The default package is called "main".  If you
1088       have multiply nested packages, pass their names to "gv_stash*v",
1089       separated by "::" as in the Perl language itself.
1090
1091       Alternately, if you have an SV that is a blessed reference, you can
1092       find out the stash pointer by using:
1093
1094           HV*  SvSTASH(SvRV(SV*));
1095
1096       then use the following to get the package name itself:
1097
1098           char*  HvNAME(HV* stash);
1099
1100       If you need to bless or re-bless an object you can use the following
1101       function:
1102
1103           SV*  sv_bless(SV*, HV* stash)
1104
1105       where the first argument, an "SV*", must be a reference, and the second
1106       argument is a stash.  The returned "SV*" can now be used in the same
1107       way as any other SV.
1108
1109       For more information on references and blessings, consult perlref.
1110
1111   I/O Handles
1112       Like AVs and HVs, IO objects are another type of non-scalar SV which
1113       may contain input and output PerlIO objects or a "DIR *" from
1114       opendir().
1115
1116       You can create a new IO object:
1117
1118           IO*  newIO();
1119
1120       Unlike other SVs, a new IO object is automatically blessed into the
1121       IO::File class.
1122
1123       The IO object contains an input and output PerlIO handle:
1124
1125         PerlIO *IoIFP(IO *io);
1126         PerlIO *IoOFP(IO *io);
1127
1128       Typically if the IO object has been opened on a file, the input handle
1129       is always present, but the output handle is only present if the file is
1130       open for output.  For a file, if both are present they will be the same
1131       PerlIO object.
1132
1133       Distinct input and output PerlIO objects are created for sockets and
1134       character devices.
1135
1136       The IO object also contains other data associated with Perl I/O
1137       handles:
1138
1139         IV IoLINES(io);                /* $. */
1140         IV IoPAGE(io);                 /* $% */
1141         IV IoPAGE_LEN(io);             /* $= */
1142         IV IoLINES_LEFT(io);           /* $- */
1143         char *IoTOP_NAME(io);          /* $^ */
1144         GV *IoTOP_GV(io);              /* $^ */
1145         char *IoFMT_NAME(io);          /* $~ */
1146         GV *IoFMT_GV(io);              /* $~ */
1147         char *IoBOTTOM_NAME(io);
1148         GV *IoBOTTOM_GV(io);
1149         char IoTYPE(io);
1150         U8 IoFLAGS(io);
1151
1152        =for apidoc_sections $io_scn, $formats_section
1153       =for apidoc_section $reports
1154       =for apidoc Amh|IV|IoLINES|IO *io
1155       =for apidoc Amh|IV|IoPAGE|IO *io
1156       =for apidoc Amh|IV|IoPAGE_LEN|IO *io
1157       =for apidoc Amh|IV|IoLINES_LEFT|IO *io
1158       =for apidoc Amh|char *|IoTOP_NAME|IO *io
1159       =for apidoc Amh|GV *|IoTOP_GV|IO *io
1160       =for apidoc Amh|char *|IoFMT_NAME|IO *io
1161       =for apidoc Amh|GV *|IoFMT_GV|IO *io
1162       =for apidoc Amh|char *|IoBOTTOM_NAME|IO *io
1163       =for apidoc Amh|GV *|IoBOTTOM_GV|IO *io
1164       =for apidoc_section $io
1165       =for apidoc Amh|char|IoTYPE|IO *io
1166       =for apidoc Amh|U8|IoFLAGS|IO *io
1167
1168       Most of these are involved with formats.
1169
1170       IoFLAGs() may contain a combination of flags, the most interesting of
1171       which are "IOf_FLUSH" ($|) for autoflush and "IOf_UNTAINT", settable
1172       with IO::Handle's untaint() method.
1173
1174       The IO object may also contains a directory handle:
1175
1176         DIR *IoDIRP(io);
1177
1178       suitable for use with PerlDir_read() etc.
1179
1180       All of these accessors macros are lvalues, there are no distinct _set()
1181       macros to modify the members of the IO object.
1182
1183   Double-Typed SVs
1184       Scalar variables normally contain only one type of value, an integer,
1185       double, pointer, or reference.  Perl will automatically convert the
1186       actual scalar data from the stored type into the requested type.
1187
1188       Some scalar variables contain more than one type of scalar data.  For
1189       example, the variable $! contains either the numeric value of "errno"
1190       or its string equivalent from either "strerror" or "sys_errlist[]".
1191
1192       To force multiple data values into an SV, you must do two things: use
1193       the "sv_set*v" routines to add the additional scalar type, then set a
1194       flag so that Perl will believe it contains more than one type of data.
1195       The four macros to set the flags are:
1196
1197               SvIOK_on
1198               SvNOK_on
1199               SvPOK_on
1200               SvROK_on
1201
1202       The particular macro you must use depends on which "sv_set*v" routine
1203       you called first.  This is because every "sv_set*v" routine turns on
1204       only the bit for the particular type of data being set, and turns off
1205       all the rest.
1206
1207       For example, to create a new Perl variable called "dberror" that
1208       contains both the numeric and descriptive string error values, you
1209       could use the following code:
1210
1211           extern int  dberror;
1212           extern char *dberror_list;
1213
1214           SV* sv = get_sv("dberror", GV_ADD);
1215           sv_setiv(sv, (IV) dberror);
1216           sv_setpv(sv, dberror_list[dberror]);
1217           SvIOK_on(sv);
1218
1219       If the order of "sv_setiv" and "sv_setpv" had been reversed, then the
1220       macro "SvPOK_on" would need to be called instead of "SvIOK_on".
1221
1222   Read-Only Values
1223       In Perl 5.16 and earlier, copy-on-write (see the next section) shared a
1224       flag bit with read-only scalars.  So the only way to test whether
1225       "sv_setsv", etc., will raise a "Modification of a read-only value"
1226       error in those versions is:
1227
1228           SvREADONLY(sv) && !SvIsCOW(sv)
1229
1230       Under Perl 5.18 and later, SvREADONLY only applies to read-only
1231       variables, and, under 5.20, copy-on-write scalars can also be read-
1232       only, so the above check is incorrect.  You just want:
1233
1234           SvREADONLY(sv)
1235
1236       If you need to do this check often, define your own macro like this:
1237
1238           #if PERL_VERSION >= 18
1239           # define SvTRULYREADONLY(sv) SvREADONLY(sv)
1240           #else
1241           # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
1242           #endif
1243
1244   Copy on Write
1245       Perl implements a copy-on-write (COW) mechanism for scalars, in which
1246       string copies are not immediately made when requested, but are deferred
1247       until made necessary by one or the other scalar changing.  This is
1248       mostly transparent, but one must take care not to modify string buffers
1249       that are shared by multiple SVs.
1250
1251       You can test whether an SV is using copy-on-write with SvIsCOW(sv).
1252
1253       You can force an SV to make its own copy of its string buffer by
1254       calling sv_force_normal(sv) or SvPV_force_nolen(sv).
1255
1256       If you want to make the SV drop its string buffer, use
1257       "sv_force_normal_flags(sv, SV_COW_DROP_PV)" or simply "sv_setsv(sv,
1258       NULL)".
1259
1260       All of these functions will croak on read-only scalars (see the
1261       previous section for more on those).
1262
1263       To test that your code is behaving correctly and not modifying COW
1264       buffers, on systems that support mmap(2) (i.e., Unix) you can configure
1265       perl with "-Accflags=-DPERL_DEBUG_READONLY_COW" and it will turn buffer
1266       violations into crashes.  You will find it to be marvellously slow, so
1267       you may want to skip perl's own tests.
1268
1269   Magic Variables
1270       [This section still under construction.  Ignore everything here.  Post
1271       no bills.  Everything not permitted is forbidden.]
1272
1273       Any SV may be magical, that is, it has special features that a normal
1274       SV does not have.  These features are stored in the SV structure in a
1275       linked list of "struct magic"'s, typedef'ed to "MAGIC".
1276
1277           struct magic {
1278               MAGIC*      mg_moremagic;
1279               MGVTBL*     mg_virtual;
1280               U16         mg_private;
1281               char        mg_type;
1282               U8          mg_flags;
1283               I32         mg_len;
1284               SV*         mg_obj;
1285               char*       mg_ptr;
1286           };
1287
1288       Note this is current as of patchlevel 0, and could change at any time.
1289
1290   Assigning Magic
1291       Perl adds magic to an SV using the sv_magic function:
1292
1293         void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
1294
1295       The "sv" argument is a pointer to the SV that is to acquire a new
1296       magical feature.
1297
1298       If "sv" is not already magical, Perl uses the "SvUPGRADE" macro to
1299       convert "sv" to type "SVt_PVMG".  Perl then continues by adding new
1300       magic to the beginning of the linked list of magical features.  Any
1301       prior entry of the same type of magic is deleted.  Note that this can
1302       be overridden, and multiple instances of the same type of magic can be
1303       associated with an SV.
1304
1305       The "name" and "namlen" arguments are used to associate a string with
1306       the magic, typically the name of a variable.  "namlen" is stored in the
1307       "mg_len" field and if "name" is non-null then either a "savepvn" copy
1308       of "name" or "name" itself is stored in the "mg_ptr" field, depending
1309       on whether "namlen" is greater than zero or equal to zero respectively.
1310       As a special case, if "(name && namlen == HEf_SVKEY)" then "name" is
1311       assumed to contain an "SV*" and is stored as-is with its REFCNT
1312       incremented.
1313
1314       The sv_magic function uses "how" to determine which, if any, predefined
1315       "Magic Virtual Table" should be assigned to the "mg_virtual" field.
1316       See the "Magic Virtual Tables" section below.  The "how" argument is
1317       also stored in the "mg_type" field.  The value of "how" should be
1318       chosen from the set of macros "PERL_MAGIC_foo" found in perl.h.  Note
1319       that before these macros were added, Perl internals used to directly
1320       use character literals, so you may occasionally come across old code or
1321       documentation referring to 'U' magic rather than "PERL_MAGIC_uvar" for
1322       example.
1323
1324       The "obj" argument is stored in the "mg_obj" field of the "MAGIC"
1325       structure.  If it is not the same as the "sv" argument, the reference
1326       count of the "obj" object is incremented.  If it is the same, or if the
1327       "how" argument is "PERL_MAGIC_arylen", "PERL_MAGIC_regdatum",
1328       "PERL_MAGIC_regdata", or if it is a NULL pointer, then "obj" is merely
1329       stored, without the reference count being incremented.
1330
1331       See also "sv_magicext" in perlapi for a more flexible way to add magic
1332       to an SV.
1333
1334       There is also a function to add magic to an "HV":
1335
1336           void hv_magic(HV *hv, GV *gv, int how);
1337
1338       This simply calls "sv_magic" and coerces the "gv" argument into an
1339       "SV".
1340
1341       To remove the magic from an SV, call the function sv_unmagic:
1342
1343           int sv_unmagic(SV *sv, int type);
1344
1345       The "type" argument should be equal to the "how" value when the "SV"
1346       was initially made magical.
1347
1348       However, note that "sv_unmagic" removes all magic of a certain "type"
1349       from the "SV".  If you want to remove only certain magic of a "type"
1350       based on the magic virtual table, use "sv_unmagicext" instead:
1351
1352           int sv_unmagicext(SV *sv, int type, MGVTBL *vtbl);
1353
1354   Magic Virtual Tables
1355       The "mg_virtual" field in the "MAGIC" structure is a pointer to an
1356       "MGVTBL", which is a structure of function pointers and stands for
1357       "Magic Virtual Table" to handle the various operations that might be
1358       applied to that variable.
1359
1360       The "MGVTBL" has five (or sometimes eight) pointers to the following
1361       routine types:
1362
1363           int  (*svt_get)  (pTHX_ SV* sv, MAGIC* mg);
1364           int  (*svt_set)  (pTHX_ SV* sv, MAGIC* mg);
1365           U32  (*svt_len)  (pTHX_ SV* sv, MAGIC* mg);
1366           int  (*svt_clear)(pTHX_ SV* sv, MAGIC* mg);
1367           int  (*svt_free) (pTHX_ SV* sv, MAGIC* mg);
1368
1369           int  (*svt_copy) (pTHX_ SV *sv, MAGIC* mg, SV *nsv,
1370                                                 const char *name, I32 namlen);
1371           int  (*svt_dup)  (pTHX_ MAGIC *mg, CLONE_PARAMS *param);
1372           int  (*svt_local)(pTHX_ SV *nsv, MAGIC *mg);
1373
1374       This MGVTBL structure is set at compile-time in perl.h and there are
1375       currently 32 types.  These different structures contain pointers to
1376       various routines that perform additional actions depending on which
1377       function is being called.
1378
1379          Function pointer    Action taken
1380          ----------------    ------------
1381          svt_get             Do something before the value of the SV is
1382                              retrieved.
1383          svt_set             Do something after the SV is assigned a value.
1384          svt_len             Report on the SV's length.
1385          svt_clear           Clear something the SV represents.
1386          svt_free            Free any extra storage associated with the SV.
1387
1388          svt_copy            copy tied variable magic to a tied element
1389          svt_dup             duplicate a magic structure during thread cloning
1390          svt_local           copy magic to local value during 'local'
1391
1392       For instance, the MGVTBL structure called "vtbl_sv" (which corresponds
1393       to an "mg_type" of "PERL_MAGIC_sv") contains:
1394
1395           { magic_get, magic_set, magic_len, 0, 0 }
1396
1397       Thus, when an SV is determined to be magical and of type
1398       "PERL_MAGIC_sv", if a get operation is being performed, the routine
1399       "magic_get" is called.  All the various routines for the various
1400       magical types begin with "magic_".  NOTE: the magic routines are not
1401       considered part of the Perl API, and may not be exported by the Perl
1402       library.
1403
1404       The last three slots are a recent addition, and for source code
1405       compatibility they are only checked for if one of the three flags
1406       "MGf_COPY", "MGf_DUP", or "MGf_LOCAL" is set in mg_flags.  This means
1407       that most code can continue declaring a vtable as a 5-element value.
1408       These three are currently used exclusively by the threading code, and
1409       are highly subject to change.
1410
1411       The current kinds of Magic Virtual Tables are:
1412
1413        mg_type
1414        (old-style char and macro)   MGVTBL         Type of magic
1415        --------------------------   ------         -------------
1416        \0 PERL_MAGIC_sv             vtbl_sv        Special scalar variable
1417        #  PERL_MAGIC_arylen         vtbl_arylen    Array length ($#ary)
1418        %  PERL_MAGIC_rhash          (none)         Extra data for restricted
1419                                                    hashes
1420        *  PERL_MAGIC_debugvar       vtbl_debugvar  $DB::single, signal, trace
1421                                                    vars
1422        .  PERL_MAGIC_pos            vtbl_pos       pos() lvalue
1423        :  PERL_MAGIC_symtab         (none)         Extra data for symbol
1424                                                    tables
1425        <  PERL_MAGIC_backref        vtbl_backref   For weak ref data
1426        @  PERL_MAGIC_arylen_p       (none)         To move arylen out of XPVAV
1427        B  PERL_MAGIC_bm             vtbl_regexp    Boyer-Moore
1428                                                    (fast string search)
1429        c  PERL_MAGIC_overload_table vtbl_ovrld     Holds overload table
1430                                                    (AMT) on stash
1431        D  PERL_MAGIC_regdata        vtbl_regdata   Regex match position data
1432                                                    (@+ and @- vars)
1433        d  PERL_MAGIC_regdatum       vtbl_regdatum  Regex match position data
1434                                                    element
1435        E  PERL_MAGIC_env            vtbl_env       %ENV hash
1436        e  PERL_MAGIC_envelem        vtbl_envelem   %ENV hash element
1437        f  PERL_MAGIC_fm             vtbl_regexp    Formline
1438                                                    ('compiled' format)
1439        g  PERL_MAGIC_regex_global   vtbl_mglob     m//g target
1440        H  PERL_MAGIC_hints          vtbl_hints     %^H hash
1441        h  PERL_MAGIC_hintselem      vtbl_hintselem %^H hash element
1442        I  PERL_MAGIC_isa            vtbl_isa       @ISA array
1443        i  PERL_MAGIC_isaelem        vtbl_isaelem   @ISA array element
1444        k  PERL_MAGIC_nkeys          vtbl_nkeys     scalar(keys()) lvalue
1445        L  PERL_MAGIC_dbfile         (none)         Debugger %_<filename
1446        l  PERL_MAGIC_dbline         vtbl_dbline    Debugger %_<filename
1447                                                    element
1448        N  PERL_MAGIC_shared         (none)         Shared between threads
1449        n  PERL_MAGIC_shared_scalar  (none)         Shared between threads
1450        o  PERL_MAGIC_collxfrm       vtbl_collxfrm  Locale transformation
1451        P  PERL_MAGIC_tied           vtbl_pack      Tied array or hash
1452        p  PERL_MAGIC_tiedelem       vtbl_packelem  Tied array or hash element
1453        q  PERL_MAGIC_tiedscalar     vtbl_packelem  Tied scalar or handle
1454        r  PERL_MAGIC_qr             vtbl_regexp    Precompiled qr// regex
1455        S  PERL_MAGIC_sig            vtbl_sig       %SIG hash
1456        s  PERL_MAGIC_sigelem        vtbl_sigelem   %SIG hash element
1457        t  PERL_MAGIC_taint          vtbl_taint     Taintedness
1458        U  PERL_MAGIC_uvar           vtbl_uvar      Available for use by
1459                                                    extensions
1460        u  PERL_MAGIC_uvar_elem      (none)         Reserved for use by
1461                                                    extensions
1462        V  PERL_MAGIC_vstring        (none)         SV was vstring literal
1463        v  PERL_MAGIC_vec            vtbl_vec       vec() lvalue
1464        w  PERL_MAGIC_utf8           vtbl_utf8      Cached UTF-8 information
1465        X  PERL_MAGIC_destruct       vtbl_destruct  destruct callback
1466        x  PERL_MAGIC_substr         vtbl_substr    substr() lvalue
1467        Y  PERL_MAGIC_nonelem        vtbl_nonelem   Array element that does not
1468                                                    exist
1469        y  PERL_MAGIC_defelem        vtbl_defelem   Shadow "foreach" iterator
1470                                                    variable / smart parameter
1471                                                    vivification
1472        Z  PERL_MAGIC_hook           vtbl_hook      %{^HOOK} hash
1473        z  PERL_MAGIC_hookelem       vtbl_hookelem  %{^HOOK} hash element
1474        \  PERL_MAGIC_lvref          vtbl_lvref     Lvalue reference
1475                                                    constructor
1476        ]  PERL_MAGIC_checkcall      vtbl_checkcall Inlining/mutation of call
1477                                                    to this CV
1478        ^  PERL_MAGIC_extvalue       (none)         Value magic available for
1479                                                    use by extensions
1480        ~  PERL_MAGIC_ext            (none)         Variable magic available
1481                                                    for use by extensions
1482
1483       When an uppercase and lowercase letter both exist in the table, then
1484       the uppercase letter is typically used to represent some kind of
1485       composite type (a list or a hash), and the lowercase letter is used to
1486       represent an element of that composite type.  Some internals code makes
1487       use of this case relationship.  However, 'v' and 'V' (vec and v-string)
1488       are in no way related.
1489
1490       The "PERL_MAGIC_ext", "PERL_MAGIC_extvalue" and "PERL_MAGIC_uvar" magic
1491       types are defined specifically for use by extensions and will not be
1492       used by perl itself.  Extensions can use "PERL_MAGIC_ext" or
1493       "PERL_MAGIC_extvalue" magic to 'attach' private information to
1494       variables (typically objects).  This is especially useful because there
1495       is no way for normal perl code to corrupt this private information
1496       (unlike using extra elements of a hash object).  "PERL_MAGIC_extvalue"
1497       is value magic (unlike "PERL_MAGIC_ext" and "PERL_MAGIC_uvar") meaning
1498       that on localization the new value will not be magical.
1499
1500       Similarly, "PERL_MAGIC_uvar" magic can be used much like tie() to call
1501       a C function any time a scalar's value is used or changed.  The
1502       "MAGIC"'s "mg_ptr" field points to a "ufuncs" structure:
1503
1504           struct ufuncs {
1505               I32 (*uf_val)(pTHX_ IV, SV*);
1506               I32 (*uf_set)(pTHX_ IV, SV*);
1507               IV uf_index;
1508           };
1509
1510       When the SV is read from or written to, the "uf_val" or "uf_set"
1511       function will be called with "uf_index" as the first arg and a pointer
1512       to the SV as the second.  A simple example of how to add
1513       "PERL_MAGIC_uvar" magic is shown below.  Note that the ufuncs structure
1514       is copied by sv_magic, so you can safely allocate it on the stack.
1515
1516           void
1517           Umagic(sv)
1518               SV *sv;
1519           PREINIT:
1520               struct ufuncs uf;
1521           CODE:
1522               uf.uf_val   = &my_get_fn;
1523               uf.uf_set   = &my_set_fn;
1524               uf.uf_index = 0;
1525               sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
1526
1527       Attaching "PERL_MAGIC_uvar" to arrays is permissible but has no effect.
1528
1529       For hashes there is a specialized hook that gives control over hash
1530       keys (but not values).  This hook calls "PERL_MAGIC_uvar" 'get' magic
1531       if the "set" function in the "ufuncs" structure is NULL.  The hook is
1532       activated whenever the hash is accessed with a key specified as an "SV"
1533       through the functions "hv_store_ent", "hv_fetch_ent", "hv_delete_ent",
1534       and "hv_exists_ent".  Accessing the key as a string through the
1535       functions without the "..._ent" suffix circumvents the hook.  See
1536       "GUTS" in Hash::Util::FieldHash for a detailed description.
1537
1538       Note that because multiple extensions may be using "PERL_MAGIC_ext" or
1539       "PERL_MAGIC_uvar" magic, it is important for extensions to take extra
1540       care to avoid conflict.  Typically only using the magic on objects
1541       blessed into the same class as the extension is sufficient.  For
1542       "PERL_MAGIC_ext" magic, it is usually a good idea to define an
1543       "MGVTBL", even if all its fields will be 0, so that individual "MAGIC"
1544       pointers can be identified as a particular kind of magic using their
1545       magic virtual table.  "mg_findext" provides an easy way to do that:
1546
1547           STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };
1548
1549           MAGIC *mg;
1550           if ((mg = mg_findext(sv, PERL_MAGIC_ext, &my_vtbl))) {
1551               /* this is really ours, not another module's PERL_MAGIC_ext */
1552               my_priv_data_t *priv = (my_priv_data_t *)mg->mg_ptr;
1553               ...
1554           }
1555
1556       Also note that the "sv_set*()" and "sv_cat*()" functions described
1557       earlier do not invoke 'set' magic on their targets.  This must be done
1558       by the user either by calling the SvSETMAGIC() macro after calling
1559       these functions, or by using one of the "sv_set*_mg()" or
1560       "sv_cat*_mg()" functions.  Similarly, generic C code must call the
1561       SvGETMAGIC() macro to invoke any 'get' magic if they use an SV obtained
1562       from external sources in functions that don't handle magic.  See
1563       perlapi for a description of these functions.  For example, calls to
1564       the "sv_cat*()" functions typically need to be followed by
1565       SvSETMAGIC(), but they don't need a prior SvGETMAGIC() since their
1566       implementation handles 'get' magic.
1567
1568   Finding Magic
1569           MAGIC *mg_find(SV *sv, int type); /* Finds the magic pointer of that
1570                                              * type */
1571
1572       This routine returns a pointer to a "MAGIC" structure stored in the SV.
1573       If the SV does not have that magical feature, "NULL" is returned.  If
1574       the SV has multiple instances of that magical feature, the first one
1575       will be returned.  "mg_findext" can be used to find a "MAGIC" structure
1576       of an SV based on both its magic type and its magic virtual table:
1577
1578           MAGIC *mg_findext(SV *sv, int type, MGVTBL *vtbl);
1579
1580       Also, if the SV passed to "mg_find" or "mg_findext" is not of type
1581       SVt_PVMG, Perl may core dump.
1582
1583           int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
1584
1585       This routine checks to see what types of magic "sv" has.  If the
1586       mg_type field is an uppercase letter, then the mg_obj is copied to
1587       "nsv", but the mg_type field is changed to be the lowercase letter.
1588
1589   Understanding the Magic of Tied Hashes and Arrays
1590       Tied hashes and arrays are magical beasts of the "PERL_MAGIC_tied"
1591       magic type.
1592
1593       WARNING: As of the 5.004 release, proper usage of the array and hash
1594       access functions requires understanding a few caveats.  Some of these
1595       caveats are actually considered bugs in the API, to be fixed in later
1596       releases, and are bracketed with [MAYCHANGE] below.  If you find
1597       yourself actually applying such information in this section, be aware
1598       that the behavior may change in the future, umm, without warning.
1599
1600       The perl tie function associates a variable with an object that
1601       implements the various GET, SET, etc methods.  To perform the
1602       equivalent of the perl tie function from an XSUB, you must mimic this
1603       behaviour.  The code below carries out the necessary steps -- firstly
1604       it creates a new hash, and then creates a second hash which it blesses
1605       into the class which will implement the tie methods.  Lastly it ties
1606       the two hashes together, and returns a reference to the new tied hash.
1607       Note that the code below does NOT call the TIEHASH method in the MyTie
1608       class - see "Calling Perl Routines from within C Programs" for details
1609       on how to do this.
1610
1611           SV*
1612           mytie()
1613           PREINIT:
1614               HV *hash;
1615               HV *stash;
1616               SV *tie;
1617           CODE:
1618               hash = newHV();
1619               tie = newRV_noinc((SV*)newHV());
1620               stash = gv_stashpv("MyTie", GV_ADD);
1621               sv_bless(tie, stash);
1622               hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
1623               RETVAL = newRV_noinc(hash);
1624           OUTPUT:
1625               RETVAL
1626
1627       The "av_store" function, when given a tied array argument, merely
1628       copies the magic of the array onto the value to be "stored", using
1629       "mg_copy".  It may also return NULL, indicating that the value did not
1630       actually need to be stored in the array.  [MAYCHANGE] After a call to
1631       "av_store" on a tied array, the caller will usually need to call
1632       mg_set(val) to actually invoke the perl level "STORE" method on the
1633       TIEARRAY object.  If "av_store" did return NULL, a call to
1634       SvREFCNT_dec(val) will also be usually necessary to avoid a memory
1635       leak. [/MAYCHANGE]
1636
1637       The previous paragraph is applicable verbatim to tied hash access using
1638       the "hv_store" and "hv_store_ent" functions as well.
1639
1640       "av_fetch" and the corresponding hash functions "hv_fetch" and
1641       "hv_fetch_ent" actually return an undefined mortal value whose magic
1642       has been initialized using "mg_copy".  Note the value so returned does
1643       not need to be deallocated, as it is already mortal.  [MAYCHANGE] But
1644       you will need to call mg_get() on the returned value in order to
1645       actually invoke the perl level "FETCH" method on the underlying TIE
1646       object.  Similarly, you may also call mg_set() on the return value
1647       after possibly assigning a suitable value to it using "sv_setsv",
1648       which will invoke the "STORE" method on the TIE object. [/MAYCHANGE]
1649
1650       [MAYCHANGE] In other words, the array or hash fetch/store functions
1651       don't really fetch and store actual values in the case of tied arrays
1652       and hashes.  They merely call "mg_copy" to attach magic to the values
1653       that were meant to be "stored" or "fetched".  Later calls to "mg_get"
1654       and "mg_set" actually do the job of invoking the TIE methods on the
1655       underlying objects.  Thus the magic mechanism currently implements a
1656       kind of lazy access to arrays and hashes.
1657
1658       Currently (as of perl version 5.004), use of the hash and array access
1659       functions requires the user to be aware of whether they are operating
1660       on "normal" hashes and arrays, or on their tied variants.  The API may
1661       be changed to provide more transparent access to both tied and normal
1662       data types in future versions.  [/MAYCHANGE]
1663
1664       You would do well to understand that the TIEARRAY and TIEHASH
1665       interfaces are mere sugar to invoke some perl method calls while using
1666       the uniform hash and array syntax.  The use of this sugar imposes some
1667       overhead (typically about two to four extra opcodes per FETCH/STORE
1668       operation, in addition to the creation of all the mortal variables
1669       required to invoke the methods).  This overhead will be comparatively
1670       small if the TIE methods are themselves substantial, but if they are
1671       only a few statements long, the overhead will not be insignificant.
1672
1673   Localizing changes
1674       Perl has a very handy construction
1675
1676         {
1677           local $var = 2;
1678           ...
1679         }
1680
1681       This construction is approximately equivalent to
1682
1683         {
1684           my $oldvar = $var;
1685           $var = 2;
1686           ...
1687           $var = $oldvar;
1688         }
1689
1690       The biggest difference is that the first construction would reinstate
1691       the initial value of $var, irrespective of how control exits the block:
1692       "goto", "return", "die"/"eval", etc.  It is a little bit more efficient
1693       as well.
1694
1695       There is a way to achieve a similar task from C via Perl API: create a
1696       pseudo-block, and arrange for some changes to be automatically undone
1697       at the end of it, either explicit, or via a non-local exit (via die()).
1698       A block-like construct is created by a pair of "ENTER"/"LEAVE" macros
1699       (see "Returning a Scalar" in perlcall).  Such a construct may be
1700       created specially for some important localized task, or an existing one
1701       (like boundaries of enclosing Perl subroutine/block, or an existing
1702       pair for freeing TMPs) may be used.  (In the second case the overhead
1703       of additional localization must be almost negligible.)  Note that any
1704       XSUB is automatically enclosed in an "ENTER"/"LEAVE" pair.
1705
1706       Inside such a pseudo-block the following service is available:
1707
1708       "SAVEINT(int i)"
1709       "SAVEIV(IV i)"
1710       "SAVEI32(I32 i)"
1711       "SAVELONG(long i)"
1712       "SAVEI8(I8 i)"
1713       "SAVEI16(I16 i)"
1714       "SAVEBOOL(int i)"
1715       "SAVESTRLEN(STRLEN i)"
1716           These macros arrange things to restore the value of integer
1717           variable "i" at the end of the enclosing pseudo-block.
1718
1719       SAVESPTR(s)
1720       SAVEPPTR(p)
1721           These macros arrange things to restore the value of pointers "s"
1722           and "p".  "s" must be a pointer of a type which survives conversion
1723           to "SV*" and back, "p" should be able to survive conversion to
1724           "char*" and back.
1725
1726       "SAVERCPV(char **ppv)"
1727           This macro arranges to restore the value of a "char *" variable
1728           which was allocated with a call to rcpv_new() to its previous state
1729           when the current pseudo block is completed. The pointer stored in
1730           *ppv at the time of the call will be refcount incremented and
1731           stored on the save stack. Later when the current pseudo-block is
1732           completed the value stored in *ppv will be refcount decremented,
1733           and the previous value restored from the savestack which will also
1734           be refcount decremented.
1735
1736           This is the "RCPV" equivalent of SAVEGENERICSV().
1737
1738       "SAVEGENERICSV(SV **psv)"
1739           This macro arranges to restore the value of a "SV *" variable to
1740           its previous state when the current pseudo block is completed. The
1741           pointer stored in *psv at the time of the call will be refcount
1742           incremented and stored on the save stack. Later when the current
1743           pseudo-block is completed the value stored in *ppv will be refcount
1744           decremented, and the previous value restored from the savestack
1745           which will also be refcount decremented. This the C equivalent of
1746           "local $sv".
1747
1748       "SAVEFREESV(SV *sv)"
1749           The refcount of "sv" will be decremented at the end of pseudo-
1750           block.  This is similar to "sv_2mortal" in that it is also a
1751           mechanism for doing a delayed "SvREFCNT_dec".  However, while
1752           "sv_2mortal" extends the lifetime of "sv" until the beginning of
1753           the next statement, "SAVEFREESV" extends it until the end of the
1754           enclosing scope.  These lifetimes can be wildly different.
1755
1756           Also compare "SAVEMORTALIZESV".
1757
1758       "SAVEMORTALIZESV(SV *sv)"
1759           Just like "SAVEFREESV", but mortalizes "sv" at the end of the
1760           current scope instead of decrementing its reference count.  This
1761           usually has the effect of keeping "sv" alive until the statement
1762           that called the currently live scope has finished executing.
1763
1764       "SAVEFREEOP(OP *op)"
1765           The "OP *" is op_free()ed at the end of pseudo-block.
1766
1767       SAVEFREEPV(p)
1768           The chunk of memory which is pointed to by "p" is Safefree()ed at
1769           the end of the current pseudo-block.
1770
1771       "SAVEFREERCPV(char *pv)"
1772           Ensures that a "char *" which was created by a call to rcpv_new()
1773           is rcpv_free()ed at the end of the current pseudo-block.
1774
1775           This is the RCPV equivalent of SAVEFREESV().
1776
1777       "SAVECLEARSV(SV *sv)"
1778           Clears a slot in the current scratchpad which corresponds to "sv"
1779           at the end of pseudo-block.
1780
1781       "SAVEDELETE(HV *hv, char *key, I32 length)"
1782           The key "key" of "hv" is deleted at the end of pseudo-block.  The
1783           string pointed to by "key" is Safefree()ed.  If one has a key in
1784           short-lived storage, the corresponding string may be reallocated
1785           like this:
1786
1787             SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
1788
1789       "SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)"
1790           At the end of pseudo-block the function "f" is called with the only
1791           argument "p" which may be NULL.
1792
1793       "SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)"
1794           At the end of pseudo-block the function "f" is called with the
1795           implicit context argument (if any), and "p" which may be NULL.
1796
1797           Note the end of the current pseudo-block may occur much later than
1798           the end of the current statement. You may wish to look at the
1799           MORTALDESTRUCTOR_X() macro instead.
1800
1801       "MORTALSVFUNC_X(SVFUNC_t f, SV *sv)"
1802           At the end of the current statement the function "f" is called with
1803           the implicit context argument (if any), and "sv" which may be NULL.
1804
1805           Be aware that the parameter argument to the destructor function
1806           differs from the related SAVEDESTRUCTOR_X() in that it MUST be
1807           either NULL or an "SV*".
1808
1809           Note the end of the current statement may occur much before the the
1810           end of the current pseudo-block.  You may wish to look at the
1811           SAVEDESTRUCTOR_X() macro instead.
1812
1813       "MORTALDESTRUCTOR_SV(SV *coderef, SV *args)"
1814           At the end of the current statement the Perl function contained in
1815           "coderef" is called with the arguments provided (if any) in "args".
1816           See the documentation for mortal_destructor_sv() for details on the
1817           "args" parameter is handled.
1818
1819           Note the end of the current statement may occur much before the the
1820           end of the current pseudo-block.  If you wish to call a perl
1821           function at the end of the current pseudo block you should use the
1822           SAVEDESTRUCTOR_X() API instead, which will require you create a C
1823           wrapper to call the Perl function.
1824
1825       SAVESTACK_POS()
1826           The current offset on the Perl internal stack (cf. "SP") is
1827           restored at the end of pseudo-block.
1828
1829       The following API list contains functions, thus one needs to provide
1830       pointers to the modifiable data explicitly (either C pointers, or
1831       Perlish "GV *"s).  Where the above macros take "int", a similar
1832       function takes "int *".
1833
1834       Other macros above have functions implementing them, but its probably
1835       best to just use the macro, and not those or the ones below.
1836
1837       "SV* save_scalar(GV *gv)"
1838           Equivalent to Perl code "local $gv".
1839
1840       "AV* save_ary(GV *gv)"
1841       "HV* save_hash(GV *gv)"
1842           Similar to "save_scalar", but localize @gv and %gv.
1843
1844       "void save_item(SV *item)"
1845           Duplicates the current value of "SV". On the exit from the current
1846           "ENTER"/"LEAVE" pseudo-block the value of "SV" will be restored
1847           using the stored value.  It doesn't handle magic.  Use
1848           "save_scalar" if magic is affected.
1849
1850       "SV* save_svref(SV **sptr)"
1851           Similar to "save_scalar", but will reinstate an "SV *".
1852
1853       "void save_aptr(AV **aptr)"
1854       "void save_hptr(HV **hptr)"
1855           Similar to "save_svref", but localize "AV *" and "HV *".
1856
1857       The "Alias" module implements localization of the basic types within
1858       the caller's scope.  People who are interested in how to localize
1859       things in the containing scope should take a look there too.
1860

Subroutines

1862   XSUBs and the Argument Stack
1863       The XSUB mechanism is a simple way for Perl programs to access C
1864       subroutines.  An XSUB routine will have a stack that contains the
1865       arguments from the Perl program, and a way to map from the Perl data
1866       structures to a C equivalent.
1867
1868       The stack arguments are accessible through the ST(n) macro, which
1869       returns the "n"'th stack argument.  Argument 0 is the first argument
1870       passed in the Perl subroutine call.  These arguments are "SV*", and can
1871       be used anywhere an "SV*" is used.
1872
1873       Most of the time, output from the C routine can be handled through use
1874       of the RETVAL and OUTPUT directives.  However, there are some cases
1875       where the argument stack is not already long enough to handle all the
1876       return values.  An example is the POSIX tzname() call, which takes no
1877       arguments, but returns two, the local time zone's standard and summer
1878       time abbreviations.
1879
1880       To handle this situation, the PPCODE directive is used and the stack is
1881       extended using the macro:
1882
1883           EXTEND(SP, num);
1884
1885       where "SP" is the macro that represents the local copy of the stack
1886       pointer, and "num" is the number of elements the stack should be
1887       extended by.
1888
1889       Now that there is room on the stack, values can be pushed on it using
1890       "PUSHs" macro.  The pushed values will often need to be "mortal" (See
1891       "Reference Counts and Mortality"):
1892
1893           PUSHs(sv_2mortal(newSViv(an_integer)))
1894           PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
1895           PUSHs(sv_2mortal(newSVnv(a_double)))
1896           PUSHs(sv_2mortal(newSVpv("Some String",0)))
1897           /* Although the last example is better written as the more
1898            * efficient: */
1899           PUSHs(newSVpvs_flags("Some String", SVs_TEMP))
1900
1901       And now the Perl program calling "tzname", the two values will be
1902       assigned as in:
1903
1904           ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
1905
1906       An alternate (and possibly simpler) method to pushing values on the
1907       stack is to use the macro:
1908
1909           XPUSHs(SV*)
1910
1911       This macro automatically adjusts the stack for you, if needed.  Thus,
1912       you do not need to call "EXTEND" to extend the stack.
1913
1914       Despite their suggestions in earlier versions of this document the
1915       macros "(X)PUSH[iunp]" are not suited to XSUBs which return multiple
1916       results.  For that, either stick to the "(X)PUSHs" macros shown above,
1917       or use the new "m(X)PUSH[iunp]" macros instead; see "Putting a C value
1918       on Perl stack".
1919
1920       For more information, consult perlxs and perlxstut.
1921
1922   Autoloading with XSUBs
1923       If an AUTOLOAD routine is an XSUB, as with Perl subroutines, Perl puts
1924       the fully-qualified name of the autoloaded subroutine in the $AUTOLOAD
1925       variable of the XSUB's package.
1926
1927       But it also puts the same information in certain fields of the XSUB
1928       itself:
1929
1930           HV *stash           = CvSTASH(cv);
1931           const char *subname = SvPVX(cv);
1932           STRLEN name_length  = SvCUR(cv); /* in bytes */
1933           U32 is_utf8         = SvUTF8(cv);
1934
1935       SvPVX(cv) contains just the sub name itself, not including the package.
1936       For an AUTOLOAD routine in UNIVERSAL or one of its superclasses,
1937       CvSTASH(cv) returns NULL during a method call on a nonexistent package.
1938
1939       Note: Setting $AUTOLOAD stopped working in 5.6.1, which did not support
1940       XS AUTOLOAD subs at all.  Perl 5.8.0 introduced the use of fields in
1941       the XSUB itself.  Perl 5.16.0 restored the setting of $AUTOLOAD.  If
1942       you need to support 5.8-5.14, use the XSUB's fields.
1943
1944   Calling Perl Routines from within C Programs
1945       There are four routines that can be used to call a Perl subroutine from
1946       within a C program.  These four are:
1947
1948           I32  call_sv(SV*, I32);
1949           I32  call_pv(const char*, I32);
1950           I32  call_method(const char*, I32);
1951           I32  call_argv(const char*, I32, char**);
1952
1953       The routine most often used is "call_sv".  The "SV*" argument contains
1954       either the name of the Perl subroutine to be called, or a reference to
1955       the subroutine.  The second argument consists of flags that control the
1956       context in which the subroutine is called, whether or not the
1957       subroutine is being passed arguments, how errors should be trapped, and
1958       how to treat return values.
1959
1960       All four routines return the number of arguments that the subroutine
1961       returned on the Perl stack.
1962
1963       These routines used to be called "perl_call_sv", etc., before Perl
1964       v5.6.0, but those names are now deprecated; macros of the same name are
1965       provided for compatibility.
1966
1967       When using any of these routines (except "call_argv"), the programmer
1968       must manipulate the Perl stack.  These include the following macros and
1969       functions:
1970
1971           dSP
1972           SP
1973           PUSHMARK()
1974           PUTBACK
1975           SPAGAIN
1976           ENTER
1977           SAVETMPS
1978           FREETMPS
1979           LEAVE
1980           XPUSH*()
1981           POP*()
1982
1983       For a detailed description of calling conventions from C to Perl,
1984       consult perlcall.
1985
1986   Putting a C value on Perl stack
1987       A lot of opcodes (this is an elementary operation in the internal perl
1988       stack machine) put an SV* on the stack.  However, as an optimization
1989       the corresponding SV is (usually) not recreated each time.  The opcodes
1990       reuse specially assigned SVs (targets) which are (as a corollary) not
1991       constantly freed/created.
1992
1993       Each of the targets is created only once (but see "Scratchpads and
1994       recursion" below), and when an opcode needs to put an integer, a
1995       double, or a string on the stack, it just sets the corresponding parts
1996       of its target and puts the target on stack.
1997
1998       The macro to put this target on stack is "PUSHTARG", and it is directly
1999       used in some opcodes, as well as indirectly in zillions of others,
2000       which use it via "(X)PUSH[iunp]".
2001
2002       Because the target is reused, you must be careful when pushing multiple
2003       values on the stack.  The following code will not do what you think:
2004
2005           XPUSHi(10);
2006           XPUSHi(20);
2007
2008       This translates as "set "TARG" to 10, push a pointer to "TARG" onto the
2009       stack; set "TARG" to 20, push a pointer to "TARG" onto the stack".  At
2010       the end of the operation, the stack does not contain the values 10 and
2011       20, but actually contains two pointers to "TARG", which we have set to
2012       20.
2013
2014       If you need to push multiple different values then you should either
2015       use the "(X)PUSHs" macros, or else use the new "m(X)PUSH[iunp]" macros,
2016       none of which make use of "TARG".  The "(X)PUSHs" macros simply push an
2017       SV* on the stack, which, as noted under "XSUBs and the Argument Stack",
2018       will often need to be "mortal".  The new "m(X)PUSH[iunp]" macros make
2019       this a little easier to achieve by creating a new mortal for you (via
2020       "(X)PUSHmortal"), pushing that onto the stack (extending it if
2021       necessary in the case of the "mXPUSH[iunp]" macros), and then setting
2022       its value.  Thus, instead of writing this to "fix" the example above:
2023
2024           XPUSHs(sv_2mortal(newSViv(10)))
2025           XPUSHs(sv_2mortal(newSViv(20)))
2026
2027       you can simply write:
2028
2029           mXPUSHi(10)
2030           mXPUSHi(20)
2031
2032       On a related note, if you do use "(X)PUSH[iunp]", then you're going to
2033       need a "dTARG" in your variable declarations so that the "*PUSH*"
2034       macros can make use of the local variable "TARG".  See also "dTARGET"
2035       and "dXSTARG".
2036
2037   Scratchpads
2038       The question remains on when the SVs which are targets for opcodes are
2039       created.  The answer is that they are created when the current unit--a
2040       subroutine or a file (for opcodes for statements outside of
2041       subroutines)--is compiled.  During this time a special anonymous Perl
2042       array is created, which is called a scratchpad for the current unit.
2043
2044       A scratchpad keeps SVs which are lexicals for the current unit and are
2045       targets for opcodes.  A previous version of this document stated that
2046       one can deduce that an SV lives on a scratchpad by looking on its
2047       flags: lexicals have "SVs_PADMY" set, and targets have "SVs_PADTMP"
2048       set.  But this has never been fully true.  "SVs_PADMY" could be set on
2049       a variable that no longer resides in any pad.  While targets do have
2050       "SVs_PADTMP" set, it can also be set on variables that have never
2051       resided in a pad, but nonetheless act like targets.  As of perl 5.21.5,
2052       the "SVs_PADMY" flag is no longer used and is defined as 0.  SvPADMY()
2053       now returns true for anything without "SVs_PADTMP".
2054
2055       The correspondence between OPs and targets is not 1-to-1.  Different
2056       OPs in the compile tree of the unit can use the same target, if this
2057       would not conflict with the expected life of the temporary.
2058
2059   Scratchpads and recursion
2060       In fact it is not 100% true that a compiled unit contains a pointer to
2061       the scratchpad AV.  In fact it contains a pointer to an AV of
2062       (initially) one element, and this element is the scratchpad AV.  Why do
2063       we need an extra level of indirection?
2064
2065       The answer is recursion, and maybe threads.  Both these can create
2066       several execution pointers going into the same subroutine.  For the
2067       subroutine-child not write over the temporaries for the subroutine-
2068       parent (lifespan of which covers the call to the child), the parent and
2069       the child should have different scratchpads.  (And the lexicals should
2070       be separate anyway!)
2071
2072       So each subroutine is born with an array of scratchpads (of length 1).
2073       On each entry to the subroutine it is checked that the current depth of
2074       the recursion is not more than the length of this array, and if it is,
2075       new scratchpad is created and pushed into the array.
2076
2077       The targets on this scratchpad are "undef"s, but they are already
2078       marked with correct flags.
2079

Memory Allocation

2081   Allocation
2082       All memory meant to be used with the Perl API functions should be
2083       manipulated using the macros described in this section.  The macros
2084       provide the necessary transparency between differences in the actual
2085       malloc implementation that is used within perl.
2086
2087       The following three macros are used to initially allocate memory :
2088
2089           Newx(pointer, number, type);
2090           Newxc(pointer, number, type, cast);
2091           Newxz(pointer, number, type);
2092
2093       The first argument "pointer" should be the name of a variable that will
2094       point to the newly allocated memory.
2095
2096       The second and third arguments "number" and "type" specify how many of
2097       the specified type of data structure should be allocated.  The argument
2098       "type" is passed to "sizeof".  The final argument to "Newxc", "cast",
2099       should be used if the "pointer" argument is different from the "type"
2100       argument.
2101
2102       Unlike the "Newx" and "Newxc" macros, the "Newxz" macro calls "memzero"
2103       to zero out all the newly allocated memory.
2104
2105   Reallocation
2106           Renew(pointer, number, type);
2107           Renewc(pointer, number, type, cast);
2108           Safefree(pointer)
2109
2110       These three macros are used to change a memory buffer size or to free a
2111       piece of memory no longer needed.  The arguments to "Renew" and
2112       "Renewc" match those of "New" and "Newc" with the exception of not
2113       needing the "magic cookie" argument.
2114
2115   Moving
2116           Move(source, dest, number, type);
2117           Copy(source, dest, number, type);
2118           Zero(dest, number, type);
2119
2120       These three macros are used to move, copy, or zero out previously
2121       allocated memory.  The "source" and "dest" arguments point to the
2122       source and destination starting points.  Perl will move, copy, or zero
2123       out "number" instances of the size of the "type" data structure (using
2124       the "sizeof" function).
2125

PerlIO

2127       The most recent development releases of Perl have been experimenting
2128       with removing Perl's dependency on the "normal" standard I/O suite and
2129       allowing other stdio implementations to be used.  This involves
2130       creating a new abstraction layer that then calls whichever
2131       implementation of stdio Perl was compiled with.  All XSUBs should now
2132       use the functions in the PerlIO abstraction layer and not make any
2133       assumptions about what kind of stdio is being used.
2134
2135       For a complete description of the PerlIO abstraction, consult perlapio.
2136

Compiled code

2138   Code tree
2139       Here we describe the internal form your code is converted to by Perl.
2140       Start with a simple example:
2141
2142         $a = $b + $c;
2143
2144       This is converted to a tree similar to this one:
2145
2146                    assign-to
2147                  /           \
2148                 +             $a
2149               /   \
2150             $b     $c
2151
2152       (but slightly more complicated).  This tree reflects the way Perl
2153       parsed your code, but has nothing to do with the execution order.
2154       There is an additional "thread" going through the nodes of the tree
2155       which shows the order of execution of the nodes.  In our simplified
2156       example above it looks like:
2157
2158            $b ---> $c ---> + ---> $a ---> assign-to
2159
2160       But with the actual compile tree for "$a = $b + $c" it is different:
2161       some nodes optimized away.  As a corollary, though the actual tree
2162       contains more nodes than our simplified example, the execution order is
2163       the same as in our example.
2164
2165   Examining the tree
2166       If you have your perl compiled for debugging (usually done with
2167       "-DDEBUGGING" on the "Configure" command line), you may examine the
2168       compiled tree by specifying "-Dx" on the Perl command line.  The output
2169       takes several lines per node, and for "$b+$c" it looks like this:
2170
2171           5           TYPE = add  ===> 6
2172                       TARG = 1
2173                       FLAGS = (SCALAR,KIDS)
2174                       {
2175                           TYPE = null  ===> (4)
2176                             (was rv2sv)
2177                           FLAGS = (SCALAR,KIDS)
2178                           {
2179           3                   TYPE = gvsv  ===> 4
2180                               FLAGS = (SCALAR)
2181                               GV = main::b
2182                           }
2183                       }
2184                       {
2185                           TYPE = null  ===> (5)
2186                             (was rv2sv)
2187                           FLAGS = (SCALAR,KIDS)
2188                           {
2189           4                   TYPE = gvsv  ===> 5
2190                               FLAGS = (SCALAR)
2191                               GV = main::c
2192                           }
2193                       }
2194
2195       This tree has 5 nodes (one per "TYPE" specifier), only 3 of them are
2196       not optimized away (one per number in the left column).  The immediate
2197       children of the given node correspond to "{}" pairs on the same level
2198       of indentation, thus this listing corresponds to the tree:
2199
2200                          add
2201                        /     \
2202                      null    null
2203                       |       |
2204                      gvsv    gvsv
2205
2206       The execution order is indicated by "===>" marks, thus it is "3 4 5 6"
2207       (node 6 is not included into above listing), i.e., "gvsv gvsv add
2208       whatever".
2209
2210       Each of these nodes represents an op, a fundamental operation inside
2211       the Perl core.  The code which implements each operation can be found
2212       in the pp*.c files; the function which implements the op with type
2213       "gvsv" is "pp_gvsv", and so on.  As the tree above shows, different ops
2214       have different numbers of children: "add" is a binary operator, as one
2215       would expect, and so has two children.  To accommodate the various
2216       different numbers of children, there are various types of op data
2217       structure, and they link together in different ways.
2218
2219       The simplest type of op structure is "OP": this has no children.  Unary
2220       operators, "UNOP"s, have one child, and this is pointed to by the
2221       "op_first" field.  Binary operators ("BINOP"s) have not only an
2222       "op_first" field but also an "op_last" field.  The most complex type of
2223       op is a "LISTOP", which has any number of children.  In this case, the
2224       first child is pointed to by "op_first" and the last child by
2225       "op_last".  The children in between can be found by iteratively
2226       following the "OpSIBLING" pointer from the first child to the last (but
2227       see below).
2228
2229       There are also some other op types: a "PMOP" holds a regular
2230       expression, and has no children, and a "LOOP" may or may not have
2231       children.  If the "op_children" field is non-zero, it behaves like a
2232       "LISTOP".  To complicate matters, if a "UNOP" is actually a "null" op
2233       after optimization (see "Compile pass 2: context propagation") it will
2234       still have children in accordance with its former type.
2235
2236       Finally, there is a "LOGOP", or logic op. Like a "LISTOP", this has one
2237       or more children, but it doesn't have an "op_last" field: so you have
2238       to follow "op_first" and then the "OpSIBLING" chain itself to find the
2239       last child. Instead it has an "op_other" field, which is comparable to
2240       the "op_next" field described below, and represents an alternate
2241       execution path. Operators like "and", "or" and "?" are "LOGOP"s. Note
2242       that in general, "op_other" may not point to any of the direct children
2243       of the "LOGOP".
2244
2245       Starting in version 5.21.2, perls built with the experimental define
2246       "-DPERL_OP_PARENT" add an extra boolean flag for each op, "op_moresib".
2247       When not set, this indicates that this is the last op in an "OpSIBLING"
2248       chain. This frees up the "op_sibling" field on the last sibling to
2249       point back to the parent op. Under this build, that field is also
2250       renamed "op_sibparent" to reflect its joint role. The macro
2251       OpSIBLING(o) wraps this special behaviour, and always returns NULL on
2252       the last sibling.  With this build the op_parent(o) function can be
2253       used to find the parent of any op. Thus for forward compatibility, you
2254       should always use the OpSIBLING(o) macro rather than accessing
2255       "op_sibling" directly.
2256
2257       Another way to examine the tree is to use a compiler back-end module,
2258       such as B::Concise.
2259
2260   Compile pass 1: check routines
2261       The tree is created by the compiler while yacc code feeds it the
2262       constructions it recognizes.  Since yacc works bottom-up, so does the
2263       first pass of perl compilation.
2264
2265       What makes this pass interesting for perl developers is that some
2266       optimization may be performed on this pass.  This is optimization by
2267       so-called "check routines".  The correspondence between node names and
2268       corresponding check routines is described in opcode.pl (do not forget
2269       to run "make regen_headers" if you modify this file).
2270
2271       A check routine is called when the node is fully constructed except for
2272       the execution-order thread.  Since at this time there are no back-links
2273       to the currently constructed node, one can do most any operation to the
2274       top-level node, including freeing it and/or creating new nodes
2275       above/below it.
2276
2277       The check routine returns the node which should be inserted into the
2278       tree (if the top-level node was not modified, check routine returns its
2279       argument).
2280
2281       By convention, check routines have names "ck_*".  They are usually
2282       called from "new*OP" subroutines (or "convert") (which in turn are
2283       called from perly.y).
2284
2285   Compile pass 1a: constant folding
2286       Immediately after the check routine is called the returned node is
2287       checked for being compile-time executable.  If it is (the value is
2288       judged to be constant) it is immediately executed, and a constant node
2289       with the "return value" of the corresponding subtree is substituted
2290       instead.  The subtree is deleted.
2291
2292       If constant folding was not performed, the execution-order thread is
2293       created.
2294
2295   Compile pass 2: context propagation
2296       When a context for a part of compile tree is known, it is propagated
2297       down through the tree.  At this time the context can have 5 values
2298       (instead of 2 for runtime context): void, boolean, scalar, list, and
2299       lvalue.  In contrast with the pass 1 this pass is processed from top to
2300       bottom: a node's context determines the context for its children.
2301
2302       Additional context-dependent optimizations are performed at this time.
2303       Since at this moment the compile tree contains back-references (via
2304       "thread" pointers), nodes cannot be free()d now.  To allow optimized-
2305       away nodes at this stage, such nodes are null()ified instead of
2306       free()ing (i.e. their type is changed to OP_NULL).
2307
2308   Compile pass 3: peephole optimization
2309       After the compile tree for a subroutine (or for an "eval" or a file) is
2310       created, an additional pass over the code is performed.  This pass is
2311       neither top-down or bottom-up, but in the execution order (with
2312       additional complications for conditionals).  Optimizations performed at
2313       this stage are subject to the same restrictions as in the pass 2.
2314
2315       Peephole optimizations are done by calling the function pointed to by
2316       the global variable "PL_peepp".  By default, "PL_peepp" just calls the
2317       function pointed to by the global variable "PL_rpeepp".  By default,
2318       that performs some basic op fixups and optimisations along the
2319       execution-order op chain, and recursively calls "PL_rpeepp" for each
2320       side chain of ops (resulting from conditionals).  Extensions may
2321       provide additional optimisations or fixups, hooking into either the
2322       per-subroutine or recursive stage, like this:
2323
2324           static peep_t prev_peepp;
2325           static void my_peep(pTHX_ OP *o)
2326           {
2327               /* custom per-subroutine optimisation goes here */
2328               prev_peepp(aTHX_ o);
2329               /* custom per-subroutine optimisation may also go here */
2330           }
2331           BOOT:
2332               prev_peepp = PL_peepp;
2333               PL_peepp = my_peep;
2334
2335           static peep_t prev_rpeepp;
2336           static void my_rpeep(pTHX_ OP *first)
2337           {
2338               OP *o = first, *t = first;
2339               for(; o = o->op_next, t = t->op_next) {
2340                   /* custom per-op optimisation goes here */
2341                   o = o->op_next;
2342                   if (!o || o == t) break;
2343                   /* custom per-op optimisation goes AND here */
2344               }
2345               prev_rpeepp(aTHX_ orig_o);
2346           }
2347           BOOT:
2348               prev_rpeepp = PL_rpeepp;
2349               PL_rpeepp = my_rpeep;
2350
2351   Pluggable runops
2352       The compile tree is executed in a runops function.  There are two
2353       runops functions, in run.c and in dump.c.  "Perl_runops_debug" is used
2354       with DEBUGGING and "Perl_runops_standard" is used otherwise.  For fine
2355       control over the execution of the compile tree it is possible to
2356       provide your own runops function.
2357
2358       It's probably best to copy one of the existing runops functions and
2359       change it to suit your needs.  Then, in the BOOT section of your XS
2360       file, add the line:
2361
2362         PL_runops = my_runops;
2363
2364       This function should be as efficient as possible to keep your programs
2365       running as fast as possible.
2366
2367   Compile-time scope hooks
2368       As of perl 5.14 it is possible to hook into the compile-time lexical
2369       scope mechanism using "Perl_blockhook_register".  This is used like
2370       this:
2371
2372           STATIC void my_start_hook(pTHX_ int full);
2373           STATIC BHK my_hooks;
2374
2375           BOOT:
2376               BhkENTRY_set(&my_hooks, bhk_start, my_start_hook);
2377               Perl_blockhook_register(aTHX_ &my_hooks);
2378
2379       This will arrange to have "my_start_hook" called at the start of
2380       compiling every lexical scope.  The available hooks are:
2381
2382       "void bhk_start(pTHX_ int full)"
2383           This is called just after starting a new lexical scope.  Note that
2384           Perl code like
2385
2386               if ($x) { ... }
2387
2388           creates two scopes: the first starts at the "(" and has "full ==
2389           1", the second starts at the "{" and has "full == 0".  Both end at
2390           the "}", so calls to "start" and "pre"/"post_end" will match.
2391           Anything pushed onto the save stack by this hook will be popped
2392           just before the scope ends (between the "pre_" and "post_end"
2393           hooks, in fact).
2394
2395       "void bhk_pre_end(pTHX_ OP **o)"
2396           This is called at the end of a lexical scope, just before unwinding
2397           the stack.  o is the root of the optree representing the scope; it
2398           is a double pointer so you can replace the OP if you need to.
2399
2400       "void bhk_post_end(pTHX_ OP **o)"
2401           This is called at the end of a lexical scope, just after unwinding
2402           the stack.  o is as above.  Note that it is possible for calls to
2403           "pre_" and "post_end" to nest, if there is something on the save
2404           stack that calls string eval.
2405
2406       "void bhk_eval(pTHX_ OP *const o)"
2407           This is called just before starting to compile an "eval STRING",
2408           "do FILE", "require" or "use", after the eval has been set up.  o
2409           is the OP that requested the eval, and will normally be an
2410           "OP_ENTEREVAL", "OP_DOFILE" or "OP_REQUIRE".
2411
2412       Once you have your hook functions, you need a "BHK" structure to put
2413       them in.  It's best to allocate it statically, since there is no way to
2414       free it once it's registered.  The function pointers should be inserted
2415       into this structure using the "BhkENTRY_set" macro, which will also set
2416       flags indicating which entries are valid.  If you do need to allocate
2417       your "BHK" dynamically for some reason, be sure to zero it before you
2418       start.
2419
2420       Once registered, there is no mechanism to switch these hooks off, so if
2421       that is necessary you will need to do this yourself.  An entry in "%^H"
2422       is probably the best way, so the effect is lexically scoped; however it
2423       is also possible to use the "BhkDISABLE" and "BhkENABLE" macros to
2424       temporarily switch entries on and off.  You should also be aware that
2425       generally speaking at least one scope will have opened before your
2426       extension is loaded, so you will see some "pre"/"post_end" pairs that
2427       didn't have a matching "start".
2428

Examining internal data structures with the "dump" functions

2430       To aid debugging, the source file dump.c contains a number of functions
2431       which produce formatted output of internal data structures.
2432
2433       The most commonly used of these functions is "Perl_sv_dump"; it's used
2434       for dumping SVs, AVs, HVs, and CVs.  The "Devel::Peek" module calls
2435       "sv_dump" to produce debugging output from Perl-space, so users of that
2436       module should already be familiar with its format.
2437
2438       "Perl_op_dump" can be used to dump an "OP" structure or any of its
2439       derivatives, and produces output similar to "perl -Dx"; in fact,
2440       "Perl_dump_eval" will dump the main root of the code being evaluated,
2441       exactly like "-Dx".
2442
2443       Other useful functions are "Perl_dump_sub", which turns a "GV" into an
2444       op tree, "Perl_dump_packsubs" which calls "Perl_dump_sub" on all the
2445       subroutines in a package like so: (Thankfully, these are all xsubs, so
2446       there is no op tree)
2447
2448           (gdb) print Perl_dump_packsubs(PL_defstash)
2449
2450           SUB attributes::bootstrap = (xsub 0x811fedc 0)
2451
2452           SUB UNIVERSAL::can = (xsub 0x811f50c 0)
2453
2454           SUB UNIVERSAL::isa = (xsub 0x811f304 0)
2455
2456           SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
2457
2458           SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
2459
2460       and "Perl_dump_all", which dumps all the subroutines in the stash and
2461       the op tree of the main root.
2462

How multiple interpreters and concurrency are supported

2464   Background and MULTIPLICITY
2465       The Perl interpreter can be regarded as a closed box: it has an API for
2466       feeding it code or otherwise making it do things, but it also has
2467       functions for its own use.  This smells a lot like an object, and there
2468       is a way for you to build Perl so that you can have multiple
2469       interpreters, with one interpreter represented either as a C structure,
2470       or inside a thread-specific structure.  These structures contain all
2471       the context, the state of that interpreter.
2472
2473       The macro that controls the major Perl build flavor is MULTIPLICITY.
2474       The MULTIPLICITY build has a C structure that packages all the
2475       interpreter state, which is being passed to various perl functions as a
2476       "hidden" first argument. MULTIPLICITY makes multi-threaded perls
2477       possible (with the ithreads threading model, related to the macro
2478       USE_ITHREADS.)
2479
2480       PERL_IMPLICIT_CONTEXT is a legacy synonym for MULTIPLICITY.
2481
2482       To see whether you have non-const data you can use a BSD (or GNU)
2483       compatible "nm":
2484
2485         nm libperl.a | grep -v ' [TURtr] '
2486
2487       If this displays any "D" or "d" symbols (or possibly "C" or "c"), you
2488       have non-const data.  The symbols the "grep" removed are as follows:
2489       "Tt" are text, or code, the "Rr" are read-only (const) data, and the
2490       "U" is <undefined>, external symbols referred to.
2491
2492       The test t/porting/libperl.t does this kind of symbol sanity checking
2493       on "libperl.a".
2494
2495       All this obviously requires a way for the Perl internal functions to be
2496       either subroutines taking some kind of structure as the first argument,
2497       or subroutines taking nothing as the first argument.  To enable these
2498       two very different ways of building the interpreter, the Perl source
2499       (as it does in so many other situations) makes heavy use of macros and
2500       subroutine naming conventions.
2501
2502       First problem: deciding which functions will be public API functions
2503       and which will be private.  All functions whose names begin "S_" are
2504       private (think "S" for "secret" or "static").  All other functions
2505       begin with "Perl_", but just because a function begins with "Perl_"
2506       does not mean it is part of the API.  (See "Internal Functions".)  The
2507       easiest way to be sure a function is part of the API is to find its
2508       entry in perlapi.  If it exists in perlapi, it's part of the API.  If
2509       it doesn't, and you think it should be (i.e., you need it for your
2510       extension), submit an issue at <https://github.com/Perl/perl5/issues>
2511       explaining why you think it should be.
2512
2513       Second problem: there must be a syntax so that the same subroutine
2514       declarations and calls can pass a structure as their first argument, or
2515       pass nothing.  To solve this, the subroutines are named and declared in
2516       a particular way.  Here's a typical start of a static function used
2517       within the Perl guts:
2518
2519         STATIC void
2520         S_incline(pTHX_ char *s)
2521
2522       STATIC becomes "static" in C, and may be #define'd to nothing in some
2523       configurations in the future.
2524
2525       A public function (i.e. part of the internal API, but not necessarily
2526       sanctioned for use in extensions) begins like this:
2527
2528         void
2529         Perl_sv_setiv(pTHX_ SV* dsv, IV num)
2530
2531       "pTHX_" is one of a number of macros (in perl.h) that hide the details
2532       of the interpreter's context.  THX stands for "thread", "this", or
2533       "thingy", as the case may be.  (And no, George Lucas is not involved.
2534       :-) The first character could be 'p' for a prototype, 'a' for argument,
2535       or 'd' for declaration, so we have "pTHX", "aTHX" and "dTHX", and their
2536       variants.
2537
2538       When Perl is built without options that set MULTIPLICITY, there is no
2539       first argument containing the interpreter's context.  The trailing
2540       underscore in the pTHX_ macro indicates that the macro expansion needs
2541       a comma after the context argument because other arguments follow it.
2542       If MULTIPLICITY is not defined, pTHX_ will be ignored, and the
2543       subroutine is not prototyped to take the extra argument.  The form of
2544       the macro without the trailing underscore is used when there are no
2545       additional explicit arguments.
2546
2547       When a core function calls another, it must pass the context.  This is
2548       normally hidden via macros.  Consider "sv_setiv".  It expands into
2549       something like this:
2550
2551           #ifdef MULTIPLICITY
2552             #define sv_setiv(a,b)      Perl_sv_setiv(aTHX_ a, b)
2553             /* can't do this for vararg functions, see below */
2554           #else
2555             #define sv_setiv           Perl_sv_setiv
2556           #endif
2557
2558       This works well, and means that XS authors can gleefully write:
2559
2560           sv_setiv(foo, bar);
2561
2562       and still have it work under all the modes Perl could have been
2563       compiled with.
2564
2565       This doesn't work so cleanly for varargs functions, though, as macros
2566       imply that the number of arguments is known in advance.  Instead we
2567       either need to spell them out fully, passing "aTHX_" as the first
2568       argument (the Perl core tends to do this with functions like
2569       Perl_warner), or use a context-free version.
2570
2571       The context-free version of Perl_warner is called
2572       Perl_warner_nocontext, and does not take the extra argument.  Instead
2573       it does "dTHX;" to get the context from thread-local storage.  We
2574       "#define warner Perl_warner_nocontext" so that extensions get source
2575       compatibility at the expense of performance.  (Passing an arg is
2576       cheaper than grabbing it from thread-local storage.)
2577
2578       You can ignore [pad]THXx when browsing the Perl headers/sources.  Those
2579       are strictly for use within the core.  Extensions and embedders need
2580       only be aware of [pad]THX.
2581
2582   So what happened to dTHR?
2583       "dTHR" was introduced in perl 5.005 to support the older thread model.
2584       The older thread model now uses the "THX" mechanism to pass context
2585       pointers around, so "dTHR" is not useful any more.  Perl 5.6.0 and
2586       later still have it for backward source compatibility, but it is
2587       defined to be a no-op.
2588
2589   How do I use all this in extensions?
2590       When Perl is built with MULTIPLICITY, extensions that call any
2591       functions in the Perl API will need to pass the initial context
2592       argument somehow.  The kicker is that you will need to write it in such
2593       a way that the extension still compiles when Perl hasn't been built
2594       with MULTIPLICITY enabled.
2595
2596       There are three ways to do this.  First, the easy but inefficient way,
2597       which is also the default, in order to maintain source compatibility
2598       with extensions: whenever XSUB.h is #included, it redefines the aTHX
2599       and aTHX_ macros to call a function that will return the context.
2600       Thus, something like:
2601
2602               sv_setiv(sv, num);
2603
2604       in your extension will translate to this when MULTIPLICITY is in
2605       effect:
2606
2607               Perl_sv_setiv(Perl_get_context(), sv, num);
2608
2609       or to this otherwise:
2610
2611               Perl_sv_setiv(sv, num);
2612
2613       You don't have to do anything new in your extension to get this; since
2614       the Perl library provides Perl_get_context(), it will all just work.
2615
2616       The second, more efficient way is to use the following template for
2617       your Foo.xs:
2618
2619               #define PERL_NO_GET_CONTEXT     /* we want efficiency */
2620               #include "EXTERN.h"
2621               #include "perl.h"
2622               #include "XSUB.h"
2623
2624               STATIC void my_private_function(int arg1, int arg2);
2625
2626               STATIC void
2627               my_private_function(int arg1, int arg2)
2628               {
2629                   dTHX;       /* fetch context */
2630                   ... call many Perl API functions ...
2631               }
2632
2633               [... etc ...]
2634
2635               MODULE = Foo            PACKAGE = Foo
2636
2637               /* typical XSUB */
2638
2639               void
2640               my_xsub(arg)
2641                       int arg
2642                   CODE:
2643                       my_private_function(arg, 10);
2644
2645       Note that the only two changes from the normal way of writing an
2646       extension is the addition of a "#define PERL_NO_GET_CONTEXT" before
2647       including the Perl headers, followed by a "dTHX;" declaration at the
2648       start of every function that will call the Perl API.  (You'll know
2649       which functions need this, because the C compiler will complain that
2650       there's an undeclared identifier in those functions.)  No changes are
2651       needed for the XSUBs themselves, because the XS() macro is correctly
2652       defined to pass in the implicit context if needed.
2653
2654       The third, even more efficient way is to ape how it is done within the
2655       Perl guts:
2656
2657               #define PERL_NO_GET_CONTEXT     /* we want efficiency */
2658               #include "EXTERN.h"
2659               #include "perl.h"
2660               #include "XSUB.h"
2661
2662               /* pTHX_ only needed for functions that call Perl API */
2663               STATIC void my_private_function(pTHX_ int arg1, int arg2);
2664
2665               STATIC void
2666               my_private_function(pTHX_ int arg1, int arg2)
2667               {
2668                   /* dTHX; not needed here, because THX is an argument */
2669                   ... call Perl API functions ...
2670               }
2671
2672               [... etc ...]
2673
2674               MODULE = Foo            PACKAGE = Foo
2675
2676               /* typical XSUB */
2677
2678               void
2679               my_xsub(arg)
2680                       int arg
2681                   CODE:
2682                       my_private_function(aTHX_ arg, 10);
2683
2684       This implementation never has to fetch the context using a function
2685       call, since it is always passed as an extra argument.  Depending on
2686       your needs for simplicity or efficiency, you may mix the previous two
2687       approaches freely.
2688
2689       Never add a comma after "pTHX" yourself--always use the form of the
2690       macro with the underscore for functions that take explicit arguments,
2691       or the form without the argument for functions with no explicit
2692       arguments.
2693
2694   Should I do anything special if I call perl from multiple threads?
2695       If you create interpreters in one thread and then proceed to call them
2696       in another, you need to make sure perl's own Thread Local Storage (TLS)
2697       slot is initialized correctly in each of those threads.
2698
2699       The "perl_alloc" and "perl_clone" API functions will automatically set
2700       the TLS slot to the interpreter they created, so that there is no need
2701       to do anything special if the interpreter is always accessed in the
2702       same thread that created it, and that thread did not create or call any
2703       other interpreters afterwards.  If that is not the case, you have to
2704       set the TLS slot of the thread before calling any functions in the Perl
2705       API on that particular interpreter.  This is done by calling the
2706       "PERL_SET_CONTEXT" macro in that thread as the first thing you do:
2707
2708               /* do this before doing anything else with some_perl */
2709               PERL_SET_CONTEXT(some_perl);
2710
2711               ... other Perl API calls on some_perl go here ...
2712
2713       (You can always get the current context via "PERL_GET_CONTEXT".)
2714
2715   Future Plans and PERL_IMPLICIT_SYS
2716       Just as MULTIPLICITY provides a way to bundle up everything that the
2717       interpreter knows about itself and pass it around, so too are there
2718       plans to allow the interpreter to bundle up everything it knows about
2719       the environment it's running on.  This is enabled with the
2720       PERL_IMPLICIT_SYS macro.  Currently it only works with USE_ITHREADS on
2721       Windows.
2722
2723       This allows the ability to provide an extra pointer (called the "host"
2724       environment) for all the system calls.  This makes it possible for all
2725       the system stuff to maintain their own state, broken down into seven C
2726       structures.  These are thin wrappers around the usual system calls (see
2727       win32/perllib.c) for the default perl executable, but for a more
2728       ambitious host (like the one that would do fork() emulation) all the
2729       extra work needed to pretend that different interpreters are actually
2730       different "processes", would be done here.
2731
2732       The Perl engine/interpreter and the host are orthogonal entities.
2733       There could be one or more interpreters in a process, and one or more
2734       "hosts", with free association between them.
2735

Internal Functions

2737       All of Perl's internal functions which will be exposed to the outside
2738       world are prefixed by "Perl_" so that they will not conflict with XS
2739       functions or functions used in a program in which Perl is embedded.
2740       Similarly, all global variables begin with "PL_".  (By convention,
2741       static functions start with "S_".)
2742
2743       Inside the Perl core ("PERL_CORE" defined), you can get at the
2744       functions either with or without the "Perl_" prefix, thanks to a bunch
2745       of defines that live in embed.h.  Note that extension code should not
2746       set "PERL_CORE"; this exposes the full perl internals, and is likely to
2747       cause breakage of the XS in each new perl release.
2748
2749       The file embed.h is generated automatically from embed.pl and
2750       embed.fnc.  embed.pl also creates the prototyping header files for the
2751       internal functions, generates the documentation and a lot of other bits
2752       and pieces.  It's important that when you add a new function to the
2753       core or change an existing one, you change the data in the table in
2754       embed.fnc as well.  Here's a sample entry from that table:
2755
2756           Apd |SV**   |av_fetch   |AV* ar|I32 key|I32 lval
2757
2758       The first column is a set of flags, the second column the return type,
2759       the third column the name.  Columns after that are the arguments.  The
2760       flags are documented at the top of embed.fnc.
2761
2762       If you edit embed.pl or embed.fnc, you will need to run "make
2763       regen_headers" to force a rebuild of embed.h and other auto-generated
2764       files.
2765
2766   Formatted Printing of IVs, UVs, and NVs
2767       If you are printing IVs, UVs, or NVS instead of the stdio(3) style
2768       formatting codes like %d, %ld, %f, you should use the following macros
2769       for portability
2770
2771               IVdf            IV in decimal
2772               UVuf            UV in decimal
2773               UVof            UV in octal
2774               UVxf            UV in hexadecimal
2775               NVef            NV %e-like
2776               NVff            NV %f-like
2777               NVgf            NV %g-like
2778
2779       These will take care of 64-bit integers and long doubles.  For example:
2780
2781               printf("IV is %" IVdf "\n", iv);
2782
2783       The "IVdf" will expand to whatever is the correct format for the IVs.
2784       Note that the spaces are required around the format in case the code is
2785       compiled with C++, to maintain compliance with its standard.
2786
2787       Note that there are different "long doubles": Perl will use whatever
2788       the compiler has.
2789
2790       If you are printing addresses of pointers, use %p or UVxf combined with
2791       PTR2UV().
2792
2793   Formatted Printing of SVs
2794       The contents of SVs may be printed using the "SVf" format, like so:
2795
2796        Perl_croak(aTHX_ "This croaked because: %" SVf "\n", SVfARG(err_msg))
2797
2798       where "err_msg" is an SV.
2799
2800       Not all scalar types are printable.  Simple values certainly are: one
2801       of IV, UV, NV, or PV.  Also, if the SV is a reference to some value,
2802       either it will be dereferenced and the value printed, or information
2803       about the type of that value and its address are displayed.  The
2804       results of printing any other type of SV are undefined and likely to
2805       lead to an interpreter crash.  NVs are printed using a %g-ish format.
2806
2807       Note that the spaces are required around the "SVf" in case the code is
2808       compiled with C++, to maintain compliance with its standard.
2809
2810       Note that any filehandle being printed to under UTF-8 must be expecting
2811       UTF-8 in order to get good results and avoid Wide-character warnings.
2812       One way to do this for typical filehandles is to invoke perl with the
2813       "-C" parameter.  (See "-C [number/list]" in perlrun.
2814
2815       You can use this to concatenate two scalars:
2816
2817        SV *var1 = get_sv("var1", GV_ADD);
2818        SV *var2 = get_sv("var2", GV_ADD);
2819        SV *var3 = newSVpvf("var1=%" SVf " and var2=%" SVf,
2820                            SVfARG(var1), SVfARG(var2));
2821
2822       "SVf_QUOTEDPREFIX" is similar to "SVf" except that it restricts the
2823       number of the characters printed, showing at most the first
2824       "PERL_QUOTEDPREFIX_LEN" characters of the argument, and rendering it
2825       with double quotes and with the contents escaped using double quoted
2826       string escaping rules. If the string is longer than this then ellipses
2827       "..."  will be appended after the trailing quote. This is intended for
2828       error messages where the string is assumed to be a class name.
2829
2830       "HvNAMEf" and "HvNAMEf_QUOTEDPREFIX" are similar to "SVf" except they
2831       extract the string, length and utf8 flags from the argument using the
2832       HvNAME(), HvNAMELEN(), HvNAMEUTF8() macros. This is intended for
2833       stringifying a class name directly from an stash HV.
2834
2835   Formatted Printing of Strings
2836       If you just want the bytes printed in a 7bit NUL-terminated string, you
2837       can just use %s (assuming they are all really only 7bit).  But if there
2838       is a possibility the value will be encoded as UTF-8 or contains bytes
2839       above 0x7F (and therefore 8bit), you should instead use the "UTF8f"
2840       format.  And as its parameter, use the UTF8fARG() macro:
2841
2842        chr * msg;
2843
2844        /* U+2018: \xE2\x80\x98 LEFT SINGLE QUOTATION MARK
2845           U+2019: \xE2\x80\x99 RIGHT SINGLE QUOTATION MARK */
2846        if (can_utf8)
2847          msg = "\xE2\x80\x98Uses fancy quotes\xE2\x80\x99";
2848        else
2849          msg = "'Uses simple quotes'";
2850
2851        Perl_croak(aTHX_ "The message is: %" UTF8f "\n",
2852                         UTF8fARG(can_utf8, strlen(msg), msg));
2853
2854       The first parameter to "UTF8fARG" is a boolean: 1 if the string is in
2855       UTF-8; 0 if string is in native byte encoding (Latin1).  The second
2856       parameter is the number of bytes in the string to print.  And the third
2857       and final parameter is a pointer to the first byte in the string.
2858
2859       Note that any filehandle being printed to under UTF-8 must be expecting
2860       UTF-8 in order to get good results and avoid Wide-character warnings.
2861       One way to do this for typical filehandles is to invoke perl with the
2862       "-C" parameter.  (See "-C [number/list]" in perlrun.
2863
2864   Formatted Printing of "Size_t" and "SSize_t"
2865       The most general way to do this is to cast them to a UV or IV, and
2866       print as in the previous section.
2867
2868       But if you're using PerlIO_printf(), it's less typing and visual
2869       clutter to use the %z length modifier (for siZe):
2870
2871               PerlIO_printf("STRLEN is %zu\n", len);
2872
2873       This modifier is not portable, so its use should be restricted to
2874       PerlIO_printf().
2875
2876   Formatted Printing of "Ptrdiff_t", "intmax_t", "short" and other special
2877       sizes
2878       There are modifiers for these special situations if you are using
2879       PerlIO_printf().  See "size" in perlfunc.
2880
2881   Pointer-To-Integer and Integer-To-Pointer
2882       Because pointer size does not necessarily equal integer size, use the
2883       follow macros to do it right.
2884
2885               PTR2UV(pointer)
2886               PTR2IV(pointer)
2887               PTR2NV(pointer)
2888               INT2PTR(pointertotype, integer)
2889
2890       For example:
2891
2892               IV  iv = ...;
2893               SV *sv = INT2PTR(SV*, iv);
2894
2895       and
2896
2897               AV *av = ...;
2898               UV  uv = PTR2UV(av);
2899
2900       There are also
2901
2902        PTR2nat(pointer)   /* pointer to integer of PTRSIZE */
2903        PTR2ul(pointer)    /* pointer to unsigned long */
2904
2905       And "PTRV" which gives the native type for an integer the same size as
2906       pointers, such as "unsigned" or "unsigned long".
2907
2908   Exception Handling
2909       There are a couple of macros to do very basic exception handling in XS
2910       modules.  You have to define "NO_XSLOCKS" before including XSUB.h to be
2911       able to use these macros:
2912
2913               #define NO_XSLOCKS
2914               #include "XSUB.h"
2915
2916       You can use these macros if you call code that may croak, but you need
2917       to do some cleanup before giving control back to Perl.  For example:
2918
2919               dXCPT;    /* set up necessary variables */
2920
2921               XCPT_TRY_START {
2922                 code_that_may_croak();
2923               } XCPT_TRY_END
2924
2925               XCPT_CATCH
2926               {
2927                 /* do cleanup here */
2928                 XCPT_RETHROW;
2929               }
2930
2931       Note that you always have to rethrow an exception that has been caught.
2932       Using these macros, it is not possible to just catch the exception and
2933       ignore it.  If you have to ignore the exception, you have to use the
2934       "call_*" function.
2935
2936       The advantage of using the above macros is that you don't have to setup
2937       an extra function for "call_*", and that using these macros is faster
2938       than using "call_*".
2939
2940   Source Documentation
2941       There's an effort going on to document the internal functions and
2942       automatically produce reference manuals from them -- perlapi is one
2943       such manual which details all the functions which are available to XS
2944       writers.  perlintern is the autogenerated manual for the functions
2945       which are not part of the API and are supposedly for internal use only.
2946
2947       Source documentation is created by putting POD comments into the C
2948       source, like this:
2949
2950        /*
2951        =for apidoc sv_setiv
2952
2953        Copies an integer into the given SV.  Does not handle 'set' magic.  See
2954        L<perlapi/sv_setiv_mg>.
2955
2956        =cut
2957        */
2958
2959       Please try and supply some documentation if you add functions to the
2960       Perl core.
2961
2962   Backwards compatibility
2963       The Perl API changes over time.  New functions are added or the
2964       interfaces of existing functions are changed.  The "Devel::PPPort"
2965       module tries to provide compatibility code for some of these changes,
2966       so XS writers don't have to code it themselves when supporting multiple
2967       versions of Perl.
2968
2969       "Devel::PPPort" generates a C header file ppport.h that can also be run
2970       as a Perl script.  To generate ppport.h, run:
2971
2972           perl -MDevel::PPPort -eDevel::PPPort::WriteFile
2973
2974       Besides checking existing XS code, the script can also be used to
2975       retrieve compatibility information for various API calls using the
2976       "--api-info" command line switch.  For example:
2977
2978         % perl ppport.h --api-info=sv_magicext
2979
2980       For details, see "perldoc ppport.h".
2981

Unicode Support

2983       Perl 5.6.0 introduced Unicode support.  It's important for porters and
2984       XS writers to understand this support and make sure that the code they
2985       write does not corrupt Unicode data.
2986
2987   What is Unicode, anyway?
2988       In the olden, less enlightened times, we all used to use ASCII.  Most
2989       of us did, anyway.  The big problem with ASCII is that it's American.
2990       Well, no, that's not actually the problem; the problem is that it's not
2991       particularly useful for people who don't use the Roman alphabet.  What
2992       used to happen was that particular languages would stick their own
2993       alphabet in the upper range of the sequence, between 128 and 255.  Of
2994       course, we then ended up with plenty of variants that weren't quite
2995       ASCII, and the whole point of it being a standard was lost.
2996
2997       Worse still, if you've got a language like Chinese or Japanese that has
2998       hundreds or thousands of characters, then you really can't fit them
2999       into a mere 256, so they had to forget about ASCII altogether, and
3000       build their own systems using pairs of numbers to refer to one
3001       character.
3002
3003       To fix this, some people formed Unicode, Inc. and produced a new
3004       character set containing all the characters you can possibly think of
3005       and more.  There are several ways of representing these characters, and
3006       the one Perl uses is called UTF-8.  UTF-8 uses a variable number of
3007       bytes to represent a character.  You can learn more about Unicode and
3008       Perl's Unicode model in perlunicode.
3009
3010       (On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of
3011       UTF-8 adapted for EBCDIC platforms.  Below, we just talk about UTF-8.
3012       UTF-EBCDIC is like UTF-8, but the details are different.  The macros
3013       hide the differences from you, just remember that the particular
3014       numbers and bit patterns presented below will differ in UTF-EBCDIC.)
3015
3016   How can I recognise a UTF-8 string?
3017       You can't.  This is because UTF-8 data is stored in bytes just like
3018       non-UTF-8 data.  The Unicode character 200, (0xC8 for you hex types)
3019       capital E with a grave accent, is represented by the two bytes
3020       "v196.172".  Unfortunately, the non-Unicode string "chr(196).chr(172)"
3021       has that byte sequence as well.  So you can't tell just by looking --
3022       this is what makes Unicode input an interesting problem.
3023
3024       In general, you either have to know what you're dealing with, or you
3025       have to guess.  The API function "is_utf8_string" can help; it'll tell
3026       you if a string contains only valid UTF-8 characters, and the chances
3027       of a non-UTF-8 string looking like valid UTF-8 become very small very
3028       quickly with increasing string length.  On a character-by-character
3029       basis, "isUTF8_CHAR" will tell you whether the current character in a
3030       string is valid UTF-8.
3031
3032   How does UTF-8 represent Unicode characters?
3033       As mentioned above, UTF-8 uses a variable number of bytes to store a
3034       character.  Characters with values 0...127 are stored in one byte, just
3035       like good ol' ASCII.  Character 128 is stored as "v194.128"; this
3036       continues up to character 191, which is "v194.191".  Now we've run out
3037       of bits (191 is binary 10111111) so we move on; character 192 is
3038       "v195.128".  And so it goes on, moving to three bytes at character
3039       2048.  "Unicode Encodings" in perlunicode has pictures of how this
3040       works.
3041
3042       Assuming you know you're dealing with a UTF-8 string, you can find out
3043       how long the first character in it is with the "UTF8SKIP" macro:
3044
3045           char *utf = "\305\233\340\240\201";
3046           I32 len;
3047
3048           len = UTF8SKIP(utf); /* len is 2 here */
3049           utf += len;
3050           len = UTF8SKIP(utf); /* len is 3 here */
3051
3052       Another way to skip over characters in a UTF-8 string is to use
3053       "utf8_hop", which takes a string and a number of characters to skip
3054       over.  You're on your own about bounds checking, though, so don't use
3055       it lightly.
3056
3057       All bytes in a multi-byte UTF-8 character will have the high bit set,
3058       so you can test if you need to do something special with this character
3059       like this (the UTF8_IS_INVARIANT() is a macro that tests whether the
3060       byte is encoded as a single byte even in UTF-8):
3061
3062           U8 *utf;     /* Initialize this to point to the beginning of the
3063                           sequence to convert */
3064           U8 *utf_end; /* Initialize this to 1 beyond the end of the sequence
3065                           pointed to by 'utf' */
3066           UV uv;       /* Returned code point; note: a UV, not a U8, not a
3067                           char */
3068           STRLEN len; /* Returned length of character in bytes */
3069
3070           if (!UTF8_IS_INVARIANT(*utf))
3071               /* Must treat this as UTF-8 */
3072               uv = utf8_to_uvchr_buf(utf, utf_end, &len);
3073           else
3074               /* OK to treat this character as a byte */
3075               uv = *utf;
3076
3077       You can also see in that example that we use "utf8_to_uvchr_buf" to get
3078       the value of the character; the inverse function "uvchr_to_utf8" is
3079       available for putting a UV into UTF-8:
3080
3081           if (!UVCHR_IS_INVARIANT(uv))
3082               /* Must treat this as UTF8 */
3083               utf8 = uvchr_to_utf8(utf8, uv);
3084           else
3085               /* OK to treat this character as a byte */
3086               *utf8++ = uv;
3087
3088       You must convert characters to UVs using the above functions if you're
3089       ever in a situation where you have to match UTF-8 and non-UTF-8
3090       characters.  You may not skip over UTF-8 characters in this case.  If
3091       you do this, you'll lose the ability to match hi-bit non-UTF-8
3092       characters; for instance, if your UTF-8 string contains "v196.172", and
3093       you skip that character, you can never match a chr(200) in a non-UTF-8
3094       string.  So don't do that!
3095
3096       (Note that we don't have to test for invariant characters in the
3097       examples above.  The functions work on any well-formed UTF-8 input.
3098       It's just that its faster to avoid the function overhead when it's not
3099       needed.)
3100
3101   How does Perl store UTF-8 strings?
3102       Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly
3103       differently.  A flag in the SV, "SVf_UTF8", indicates that the string
3104       is internally encoded as UTF-8.  Without it, the byte value is the
3105       codepoint number and vice versa.  This flag is only meaningful if the
3106       SV is "SvPOK" or immediately after stringification via "SvPV" or a
3107       similar macro.  You can check and manipulate this flag with the
3108       following macros:
3109
3110           SvUTF8(sv)
3111           SvUTF8_on(sv)
3112           SvUTF8_off(sv)
3113
3114       This flag has an important effect on Perl's treatment of the string: if
3115       UTF-8 data is not properly distinguished, regular expressions,
3116       "length", "substr" and other string handling operations will have
3117       undesirable (wrong) results.
3118
3119       The problem comes when you have, for instance, a string that isn't
3120       flagged as UTF-8, and contains a byte sequence that could be UTF-8 --
3121       especially when combining non-UTF-8 and UTF-8 strings.
3122
3123       Never forget that the "SVf_UTF8" flag is separate from the PV value;
3124       you need to be sure you don't accidentally knock it off while you're
3125       manipulating SVs.  More specifically, you cannot expect to do this:
3126
3127           SV *sv;
3128           SV *nsv;
3129           STRLEN len;
3130           char *p;
3131
3132           p = SvPV(sv, len);
3133           frobnicate(p);
3134           nsv = newSVpvn(p, len);
3135
3136       The "char*" string does not tell you the whole story, and you can't
3137       copy or reconstruct an SV just by copying the string value.  Check if
3138       the old SV has the UTF8 flag set (after the "SvPV" call), and act
3139       accordingly:
3140
3141           p = SvPV(sv, len);
3142           is_utf8 = SvUTF8(sv);
3143           frobnicate(p, is_utf8);
3144           nsv = newSVpvn(p, len);
3145           if (is_utf8)
3146               SvUTF8_on(nsv);
3147
3148       In the above, your "frobnicate" function has been changed to be made
3149       aware of whether or not it's dealing with UTF-8 data, so that it can
3150       handle the string appropriately.
3151
3152       Since just passing an SV to an XS function and copying the data of the
3153       SV is not enough to copy the UTF8 flags, even less right is just
3154       passing a "char *" to an XS function.
3155
3156       For full generality, use the "DO_UTF8" macro to see if the string in an
3157       SV is to be treated as UTF-8.  This takes into account if the call to
3158       the XS function is being made from within the scope of "use bytes".  If
3159       so, the underlying bytes that comprise the UTF-8 string are to be
3160       exposed, rather than the character they represent.  But this pragma
3161       should only really be used for debugging and perhaps low-level testing
3162       at the byte level.  Hence most XS code need not concern itself with
3163       this, but various areas of the perl core do need to support it.
3164
3165       And this isn't the whole story.  Starting in Perl v5.12, strings that
3166       aren't encoded in UTF-8 may also be treated as Unicode under various
3167       conditions (see "ASCII Rules versus Unicode Rules" in perlunicode).
3168       This is only really a problem for characters whose ordinals are between
3169       128 and 255, and their behavior varies under ASCII versus Unicode rules
3170       in ways that your code cares about (see "The "Unicode Bug"" in
3171       perlunicode).  There is no published API for dealing with this, as it
3172       is subject to change, but you can look at the code for "pp_lc" in pp.c
3173       for an example as to how it's currently done.
3174
3175   How do I pass a Perl string to a C library?
3176       A Perl string, conceptually, is an opaque sequence of code points.
3177       Many C libraries expect their inputs to be "classical" C strings, which
3178       are arrays of octets 1-255, terminated with a NUL byte. Your job when
3179       writing an interface between Perl and a C library is to define the
3180       mapping between Perl and that library.
3181
3182       Generally speaking, "SvPVbyte" and related macros suit this task well.
3183       These assume that your Perl string is a "byte string", i.e., is either
3184       raw, undecoded input into Perl or is pre-encoded to, e.g., UTF-8.
3185
3186       Alternatively, if your C library expects UTF-8 text, you can use
3187       "SvPVutf8" and related macros. This has the same effect as encoding to
3188       UTF-8 then calling the corresponding "SvPVbyte"-related macro.
3189
3190       Some C libraries may expect other encodings (e.g., UTF-16LE). To give
3191       Perl strings to such libraries you must either do that encoding in Perl
3192       then use "SvPVbyte", or use an intermediary C library to convert from
3193       however Perl stores the string to the desired encoding.
3194
3195       Take care also that NULs in your Perl string don't confuse the C
3196       library. If possible, give the string's length to the C library; if
3197       that's not possible, consider rejecting strings that contain NUL bytes.
3198
3199       What about "SvPV", "SvPV_nolen", etc.?
3200
3201       Consider a 3-character Perl string "$foo = "\x64\x78\x8c"".  Perl can
3202       store these 3 characters either of two ways:
3203
3204       •   bytes: 0x64 0x78 0x8c
3205
3206       •   UTF-8: 0x64 0x78 0xc2 0x8c
3207
3208       Now let's say you convert $foo to a C string thus:
3209
3210           STRLEN strlen;
3211           char *str = SvPV(foo_sv, strlen);
3212
3213       At this point "str" could point to a 3-byte C string or a 4-byte one.
3214
3215       Generally speaking, we want "str" to be the same regardless of how Perl
3216       stores $foo, so the ambiguity here is undesirable. "SvPVbyte" and
3217       "SvPVutf8" solve that by giving predictable output: use "SvPVbyte" if
3218       your C library expects byte strings, or "SvPVutf8" if it expects UTF-8.
3219
3220       If your C library happens to support both encodings, then
3221       "SvPV"--always in tandem with lookups to "SvUTF8"!--may be safe and
3222       (slightly) more efficient.
3223
3224       TESTING TIP: Use utf8's "upgrade" and "downgrade" functions in your
3225       tests to ensure consistent handling regardless of Perl's internal
3226       encoding.
3227
3228   How do I convert a string to UTF-8?
3229       If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to
3230       upgrade the non-UTF-8 strings to UTF-8.  If you've got an SV, the
3231       easiest way to do this is:
3232
3233           sv_utf8_upgrade(sv);
3234
3235       However, you must not do this, for example:
3236
3237           if (!SvUTF8(left))
3238               sv_utf8_upgrade(left);
3239
3240       If you do this in a binary operator, you will actually change one of
3241       the strings that came into the operator, and, while it shouldn't be
3242       noticeable by the end user, it can cause problems in deficient code.
3243
3244       Instead, "bytes_to_utf8" will give you a UTF-8-encoded copy of its
3245       string argument.  This is useful for having the data available for
3246       comparisons and so on, without harming the original SV.  There's also
3247       "utf8_to_bytes" to go the other way, but naturally, this will fail if
3248       the string contains any characters above 255 that can't be represented
3249       in a single byte.
3250
3251   How do I compare strings?
3252       "sv_cmp" in perlapi and "sv_cmp_flags" in perlapi do a lexigraphic
3253       comparison of two SV's, and handle UTF-8ness properly.  Note, however,
3254       that Unicode specifies a much fancier mechanism for collation,
3255       available via the Unicode::Collate module.
3256
3257       To just compare two strings for equality/non-equality, you can just use
3258       memEQ() and memNE() as usual, except the strings must be both UTF-8 or
3259       not UTF-8 encoded.
3260
3261       To compare two strings case-insensitively, use foldEQ_utf8() (the
3262       strings don't have to have the same UTF-8ness).
3263
3264   Is there anything else I need to know?
3265       Not really.  Just remember these things:
3266
3267       •  There's no way to tell if a "char *" or "U8 *" string is UTF-8 or
3268          not.  But you can tell if an SV is to be treated as UTF-8 by calling
3269          "DO_UTF8" on it, after stringifying it with "SvPV" or a similar
3270          macro.  And, you can tell if SV is actually UTF-8 (even if it is not
3271          to be treated as such) by looking at its "SvUTF8" flag (again after
3272          stringifying it).  Don't forget to set the flag if something should
3273          be UTF-8.  Treat the flag as part of the PV, even though it's not --
3274          if you pass on the PV to somewhere, pass on the flag too.
3275
3276       •  If a string is UTF-8, always use "utf8_to_uvchr_buf" to get at the
3277          value, unless UTF8_IS_INVARIANT(*s) in which case you can use *s.
3278
3279       •  When writing a character UV to a UTF-8 string, always use
3280          "uvchr_to_utf8", unless "UVCHR_IS_INVARIANT(uv))" in which case you
3281          can use "*s = uv".
3282
3283       •  Mixing UTF-8 and non-UTF-8 strings is tricky.  Use "bytes_to_utf8"
3284          to get a new string which is UTF-8 encoded, and then combine them.
3285

Custom Operators

3287       Custom operator support is an experimental feature that allows you to
3288       define your own ops.  This is primarily to allow the building of
3289       interpreters for other languages in the Perl core, but it also allows
3290       optimizations through the creation of "macro-ops" (ops which perform
3291       the functions of multiple ops which are usually executed together, such
3292       as "gvsv, gvsv, add".)
3293
3294       This feature is implemented as a new op type, "OP_CUSTOM".  The Perl
3295       core does not "know" anything special about this op type, and so it
3296       will not be involved in any optimizations.  This also means that you
3297       can define your custom ops to be any op structure -- unary, binary,
3298       list and so on -- you like.
3299
3300       It's important to know what custom operators won't do for you.  They
3301       won't let you add new syntax to Perl, directly.  They won't even let
3302       you add new keywords, directly.  In fact, they won't change the way
3303       Perl compiles a program at all.  You have to do those changes yourself,
3304       after Perl has compiled the program.  You do this either by
3305       manipulating the op tree using a "CHECK" block and the "B::Generate"
3306       module, or by adding a custom peephole optimizer with the "optimize"
3307       module.
3308
3309       When you do this, you replace ordinary Perl ops with custom ops by
3310       creating ops with the type "OP_CUSTOM" and the "op_ppaddr" of your own
3311       PP function.  This should be defined in XS code, and should look like
3312       the PP ops in "pp_*.c".  You are responsible for ensuring that your op
3313       takes the appropriate number of values from the stack, and you are
3314       responsible for adding stack marks if necessary.
3315
3316       You should also "register" your op with the Perl interpreter so that it
3317       can produce sensible error and warning messages.  Since it is possible
3318       to have multiple custom ops within the one "logical" op type
3319       "OP_CUSTOM", Perl uses the value of "o->op_ppaddr" to determine which
3320       custom op it is dealing with.  You should create an "XOP" structure for
3321       each ppaddr you use, set the properties of the custom op with
3322       "XopENTRY_set", and register the structure against the ppaddr using
3323       "Perl_custom_op_register".  A trivial example might look like:
3324
3325           static XOP my_xop;
3326           static OP *my_pp(pTHX);
3327
3328           BOOT:
3329               XopENTRY_set(&my_xop, xop_name, "myxop");
3330               XopENTRY_set(&my_xop, xop_desc, "Useless custom op");
3331               Perl_custom_op_register(aTHX_ my_pp, &my_xop);
3332
3333       The available fields in the structure are:
3334
3335       xop_name
3336           A short name for your op.  This will be included in some error
3337           messages, and will also be returned as "$op->name" by the B module,
3338           so it will appear in the output of module like B::Concise.
3339
3340       xop_desc
3341           A short description of the function of the op.
3342
3343       xop_class
3344           Which of the various *OP structures this op uses.  This should be
3345           one of the "OA_*" constants from op.h, namely
3346
3347           OA_BASEOP
3348           OA_UNOP
3349           OA_BINOP
3350           OA_LOGOP
3351           OA_LISTOP
3352           OA_PMOP
3353           OA_SVOP
3354           OA_PADOP
3355           OA_PVOP_OR_SVOP
3356               This should be interpreted as '"PVOP"' only.  The "_OR_SVOP" is
3357               because the only core "PVOP", "OP_TRANS", can sometimes be a
3358               "SVOP" instead.
3359
3360           OA_LOOP
3361           OA_COP
3362
3363           The other "OA_*" constants should not be used.
3364
3365       xop_peep
3366           This member is of type "Perl_cpeep_t", which expands to "void
3367           (*Perl_cpeep_t)(aTHX_ OP *o, OP *oldop)".  If it is set, this
3368           function will be called from "Perl_rpeep" when ops of this type are
3369           encountered by the peephole optimizer.  o is the OP that needs
3370           optimizing; oldop is the previous OP optimized, whose "op_next"
3371           points to o.
3372
3373       "B::Generate" directly supports the creation of custom ops by name.
3374

Stacks

3376       Descriptions above occasionally refer to "the stack", but there are in
3377       fact many stack-like data structures within the perl interpreter. When
3378       otherwise unqualified, "the stack" usually refers to the value stack.
3379
3380       The various stacks have different purposes, and operate in slightly
3381       different ways. Their differences are noted below.
3382
3383   Value Stack
3384       This stack stores the values that regular perl code is operating on,
3385       usually intermediate values of expressions within a statement. The
3386       stack itself is formed of an array of SV pointers.
3387
3388       The base of this stack is pointed to by the interpreter variable
3389       "PL_stack_base", of type "SV **".
3390
3391       The head of the stack is "PL_stack_sp", and points to the most
3392       recently-pushed item.
3393
3394       Items are pushed to the stack by using the PUSHs() macro or its
3395       variants described above; XPUSHs(), mPUSHs(), mXPUSHs() and the typed
3396       versions. Note carefully that the non-"X" versions of these macros do
3397       not check the size of the stack and assume it to be big enough. These
3398       must be paired with a suitable check of the stack's size, such as the
3399       "EXTEND" macro to ensure it is large enough. For example
3400
3401           EXTEND(SP, 4);
3402           mPUSHi(10);
3403           mPUSHi(20);
3404           mPUSHi(30);
3405           mPUSHi(40);
3406
3407       This is slightly more performant than making four separate checks in
3408       four separate mXPUSHi() calls.
3409
3410       As a further performance optimisation, the various "PUSH" macros all
3411       operate using a local variable "SP", rather than the interpreter-global
3412       variable "PL_stack_sp". This variable is declared by the "dSP" macro -
3413       though it is normally implied by XSUBs and similar so it is rare you
3414       have to consider it directly. Once declared, the "PUSH" macros will
3415       operate only on this local variable, so before invoking any other perl
3416       core functions you must use the "PUTBACK" macro to return the value
3417       from the local "SP" variable back to the interpreter variable.
3418       Similarly, after calling a perl core function which may have had reason
3419       to move the stack or push/pop values to it, you must use the "SPAGAIN"
3420       macro which refreshes the local "SP" value back from the interpreter
3421       one.
3422
3423       Items are popped from the stack by using the "POPs" macro or its typed
3424       versions, There is also a macro "TOPs" that inspects the topmost item
3425       without removing it.
3426
3427       Note specifically that SV pointers on the value stack do not contribute
3428       to the overall reference count of the xVs being referred to. If newly-
3429       created xVs are being pushed to the stack you must arrange for them to
3430       be destroyed at a suitable time; usually by using one of the "mPUSH*"
3431       macros or sv_2mortal() to mortalise the xV.
3432
3433   Mark Stack
3434       The value stack stores individual perl scalar values as temporaries
3435       between expressions. Some perl expressions operate on entire lists; for
3436       that purpose we need to know where on the stack each list begins. This
3437       is the purpose of the mark stack.
3438
3439       The mark stack stores integers as I32 values, which are the height of
3440       the value stack at the time before the list began; thus the mark itself
3441       actually points to the value stack entry one before the list. The list
3442       itself starts at "mark + 1".
3443
3444       The base of this stack is pointed to by the interpreter variable
3445       "PL_markstack", of type "I32 *".
3446
3447       The head of the stack is "PL_markstack_ptr", and points to the most
3448       recently-pushed item.
3449
3450       Items are pushed to the stack by using the PUSHMARK() macro. Even
3451       though the stack itself stores (value) stack indices as integers, the
3452       "PUSHMARK" macro should be given a stack pointer directly; it will
3453       calculate the index offset by comparing to the "PL_stack_sp" variable.
3454       Thus almost always the code to perform this is
3455
3456           PUSHMARK(SP);
3457
3458       Items are popped from the stack by the "POPMARK" macro. There is also a
3459       macro "TOPMARK" that inspects the topmost item without removing it.
3460       These macros return I32 index values directly. There is also the
3461       "dMARK" macro which declares a new SV double-pointer variable, called
3462       "mark", which points at the marked stack slot; this is the usual macro
3463       that C code will use when operating on lists given on the stack.
3464
3465       As noted above, the "mark" variable itself will point at the most
3466       recently pushed value on the value stack before the list begins, and so
3467       the list itself starts at "mark + 1". The values of the list may be
3468       iterated by code such as
3469
3470           for(SV **svp = mark + 1; svp <= PL_stack_sp; svp++) {
3471             SV *item = *svp;
3472             ...
3473           }
3474
3475       Note specifically in the case that the list is already empty, "mark"
3476       will equal "PL_stack_sp".
3477
3478       Because the "mark" variable is converted to a pointer on the value
3479       stack, extra care must be taken if "EXTEND" or any of the "XPUSH"
3480       macros are invoked within the function, because the stack may need to
3481       be moved to extend it and so the existing pointer will now be invalid.
3482       If this may be a problem, a possible solution is to track the mark
3483       offset as an integer and track the mark itself later on after the stack
3484       had been moved.
3485
3486           I32 markoff = POPMARK;
3487
3488           ...
3489
3490           SP **mark = PL_stack_base + markoff;
3491
3492   Temporaries Stack
3493       As noted above, xV references on the main value stack do not contribute
3494       to the reference count of an xV, and so another mechanism is used to
3495       track when temporary values which live on the stack must be released.
3496       This is the job of the temporaries stack.
3497
3498       The temporaries stack stores pointers to xVs whose reference counts
3499       will be decremented soon.
3500
3501       The base of this stack is pointed to by the interpreter variable
3502       "PL_tmps_stack", of type "SV **".
3503
3504       The head of the stack is indexed by "PL_tmps_ix", an integer which
3505       stores the index in the array of the most recently-pushed item.
3506
3507       There is no public API to directly push items to the temporaries stack.
3508       Instead, the API function sv_2mortal() is used to mortalize an xV,
3509       adding its address to the temporaries stack.
3510
3511       Likewise, there is no public API to read values from the temporaries
3512       stack.  Instead, the macros "SAVETMPS" and "FREETMPS" are used. The
3513       "SAVETMPS" macro establishes the base levels of the temporaries stack,
3514       by capturing the current value of "PL_tmps_ix" into "PL_tmps_floor" and
3515       saving the previous value to the save stack. Thereafter, whenever
3516       "FREETMPS" is invoked all of the temporaries that have been pushed
3517       since that level are reclaimed.
3518
3519       While it is common to see these two macros in pairs within an "ENTER"/
3520       "LEAVE" pair, it is not necessary to match them. It is permitted to
3521       invoke "FREETMPS" multiple times since the most recent "SAVETMPS"; for
3522       example in a loop iterating over elements of a list. While you can
3523       invoke "SAVETMPS" multiple times within a scope pair, it is unlikely to
3524       be useful. Subsequent invocations will move the temporaries floor
3525       further up, thus effectively trapping the existing temporaries to only
3526       be released at the end of the scope.
3527
3528   Save Stack
3529       The save stack is used by perl to implement the "local" keyword and
3530       other similar behaviours; any cleanup operations that need to be
3531       performed when leaving the current scope. Items pushed to this stack
3532       generally capture the current value of some internal variable or state,
3533       which will be restored when the scope is unwound due to leaving,
3534       "return", "die", "goto" or other reasons.
3535
3536       Whereas other perl internal stacks store individual items all of the
3537       same type (usually SV pointers or integers), the items pushed to the
3538       save stack are formed of many different types, having multiple fields
3539       to them. For example, the "SAVEt_INT" type needs to store both the
3540       address of the "int" variable to restore, and the value to restore it
3541       to. This information could have been stored using fields of a "struct",
3542       but would have to be large enough to store three pointers in the
3543       largest case, which would waste a lot of space in most of the smaller
3544       cases.
3545
3546       Instead, the stack stores information in a variable-length encoding of
3547       "ANY" structures. The final value pushed is stored in the "UV" field
3548       which encodes the kind of item held by the preceding items; the count
3549       and types of which will depend on what kind of item is being stored.
3550       The kind field is pushed last because that will be the first field to
3551       be popped when unwinding items from the stack.
3552
3553       The base of this stack is pointed to by the interpreter variable
3554       "PL_savestack", of type "ANY *".
3555
3556       The head of the stack is indexed by "PL_savestack_ix", an integer which
3557       stores the index in the array at which the next item should be pushed.
3558       (Note that this is different to most other stacks, which reference the
3559       most recently-pushed item).
3560
3561       Items are pushed to the save stack by using the various "SAVE...()"
3562       macros.  Many of these macros take a variable and store both its
3563       address and current value on the save stack, ensuring that value gets
3564       restored on scope exit.
3565
3566           SAVEI8(i8)
3567           SAVEI16(i16)
3568           SAVEI32(i32)
3569           SAVEINT(i)
3570           ...
3571
3572       There are also a variety of other special-purpose macros which save
3573       particular types or values of interest. "SAVETMPS" has already been
3574       mentioned above.  Others include "SAVEFREEPV" which arranges for a PV
3575       (i.e. a string buffer) to be freed, or "SAVEDESTRUCTOR" which arranges
3576       for a given function pointer to be invoked on scope exit. A full list
3577       of such macros can be found in scope.h.
3578
3579       There is no public API for popping individual values or items from the
3580       save stack. Instead, via the scope stack, the "ENTER" and "LEAVE" pair
3581       form a way to start and stop nested scopes. Leaving a nested scope via
3582       "LEAVE" will restore all of the saved values that had been pushed since
3583       the most recent "ENTER".
3584
3585   Scope Stack
3586       As with the mark stack to the value stack, the scope stack forms a pair
3587       with the save stack. The scope stack stores the height of the save
3588       stack at which nested scopes begin, and allows the save stack to be
3589       unwound back to that point when the scope is left.
3590
3591       When perl is built with debugging enabled, there is a second part to
3592       this stack storing human-readable string names describing the type of
3593       stack context. Each push operation saves the name as well as the height
3594       of the save stack, and each pop operation checks the topmost name with
3595       what is expected, causing an assertion failure if the name does not
3596       match.
3597
3598       The base of this stack is pointed to by the interpreter variable
3599       "PL_scopestack", of type "I32 *". If enabled, the scope stack names are
3600       stored in a separate array pointed to by "PL_scopestack_name", of type
3601       "const char **".
3602
3603       The head of the stack is indexed by "PL_scopestack_ix", an integer
3604       which stores the index of the array or arrays at which the next item
3605       should be pushed. (Note that this is different to most other stacks,
3606       which reference the most recently-pushed item).
3607
3608       Values are pushed to the scope stack using the "ENTER" macro, which
3609       begins a new nested scope. Any items pushed to the save stack are then
3610       restored at the next nested invocation of the "LEAVE" macro.
3611

Dynamic Scope and the Context Stack

3613       Note: this section describes a non-public internal API that is subject
3614       to change without notice.
3615
3616   Introduction to the context stack
3617       In Perl, dynamic scoping refers to the runtime nesting of things like
3618       subroutine calls, evals etc, as well as the entering and exiting of
3619       block scopes. For example, the restoring of a "local"ised variable is
3620       determined by the dynamic scope.
3621
3622       Perl tracks the dynamic scope by a data structure called the context
3623       stack, which is an array of "PERL_CONTEXT" structures, and which is
3624       itself a big union for all the types of context. Whenever a new scope
3625       is entered (such as a block, a "for" loop, or a subroutine call), a new
3626       context entry is pushed onto the stack. Similarly when leaving a block
3627       or returning from a subroutine call etc. a context is popped. Since the
3628       context stack represents the current dynamic scope, it can be searched.
3629       For example, "next LABEL" searches back through the stack looking for a
3630       loop context that matches the label; "return" pops contexts until it
3631       finds a sub or eval context or similar; "caller" examines sub contexts
3632       on the stack.
3633
3634       Each context entry is labelled with a context type, "cx_type". Typical
3635       context types are "CXt_SUB", "CXt_EVAL" etc., as well as "CXt_BLOCK"
3636       and "CXt_NULL" which represent a basic scope (as pushed by "pp_enter")
3637       and a sort block. The type determines which part of the context union
3638       are valid.
3639
3640       The main division in the context struct is between a substitution scope
3641       ("CXt_SUBST") and block scopes, which are everything else. The former
3642       is just used while executing "s///e", and won't be discussed further
3643       here.
3644
3645       All the block scope types share a common base, which corresponds to
3646       "CXt_BLOCK". This stores the old values of various scope-related
3647       variables like "PL_curpm", as well as information about the current
3648       scope, such as "gimme". On scope exit, the old variables are restored.
3649
3650       Particular block scope types store extra per-type information. For
3651       example, "CXt_SUB" stores the currently executing CV, while the various
3652       for loop types might hold the original loop variable SV. On scope exit,
3653       the per-type data is processed; for example the CV has its reference
3654       count decremented, and the original loop variable is restored.
3655
3656       The macro "cxstack" returns the base of the current context stack,
3657       while "cxstack_ix" is the index of the current frame within that stack.
3658
3659       In fact, the context stack is actually part of a stack-of-stacks
3660       system; whenever something unusual is done such as calling a "DESTROY"
3661       or tie handler, a new stack is pushed, then popped at the end.
3662
3663       Note that the API described here changed considerably in perl 5.24;
3664       prior to that, big macros like "PUSHBLOCK" and "POPSUB" were used; in
3665       5.24 they were replaced by the inline static functions described below.
3666       In addition, the ordering and detail of how these macros/function work
3667       changed in many ways, often subtly. In particular they didn't handle
3668       saving the savestack and temps stack positions, and required additional
3669       "ENTER", "SAVETMPS" and "LEAVE" compared to the new functions. The old-
3670       style macros will not be described further.
3671
3672   Pushing contexts
3673       For pushing a new context, the two basic functions are "cx =
3674       cx_pushblock()", which pushes a new basic context block and returns its
3675       address, and a family of similar functions with names like
3676       cx_pushsub(cx) which populate the additional type-dependent fields in
3677       the "cx" struct. Note that "CXt_NULL" and "CXt_BLOCK" don't have their
3678       own push functions, as they don't store any data beyond that pushed by
3679       "cx_pushblock".
3680
3681       The fields of the context struct and the arguments to the "cx_*"
3682       functions are subject to change between perl releases, representing
3683       whatever is convenient or efficient for that release.
3684
3685       A typical context stack pushing can be found in "pp_entersub"; the
3686       following shows a simplified and stripped-down example of a non-XS
3687       call, along with comments showing roughly what each function does.
3688
3689        dMARK;
3690        U8 gimme      = GIMME_V;
3691        bool hasargs  = cBOOL(PL_op->op_flags & OPf_STACKED);
3692        OP *retop     = PL_op->op_next;
3693        I32 old_ss_ix = PL_savestack_ix;
3694        CV *cv        = ....;
3695
3696        /* ... make mortal copies of stack args which are PADTMPs here ... */
3697
3698        /* ... do any additional savestack pushes here ... */
3699
3700        /* Now push a new context entry of type 'CXt_SUB'; initially just
3701         * doing the actions common to all block types: */
3702
3703        cx = cx_pushblock(CXt_SUB, gimme, MARK, old_ss_ix);
3704
3705            /* this does (approximately):
3706                CXINC;              /* cxstack_ix++ (grow if necessary) */
3707                cx = CX_CUR();      /* and get the address of new frame */
3708                cx->cx_type        = CXt_SUB;
3709                cx->blk_gimme      = gimme;
3710                cx->blk_oldsp      = MARK - PL_stack_base;
3711                cx->blk_oldsaveix  = old_ss_ix;
3712                cx->blk_oldcop     = PL_curcop;
3713                cx->blk_oldmarksp  = PL_markstack_ptr - PL_markstack;
3714                cx->blk_oldscopesp = PL_scopestack_ix;
3715                cx->blk_oldpm      = PL_curpm;
3716                cx->blk_old_tmpsfloor = PL_tmps_floor;
3717
3718                PL_tmps_floor        = PL_tmps_ix;
3719            */
3720
3721
3722        /* then update the new context frame with subroutine-specific info,
3723         * such as the CV about to be executed: */
3724
3725        cx_pushsub(cx, cv, retop, hasargs);
3726
3727            /* this does (approximately):
3728                cx->blk_sub.cv          = cv;
3729                cx->blk_sub.olddepth    = CvDEPTH(cv);
3730                cx->blk_sub.prevcomppad = PL_comppad;
3731                cx->cx_type            |= (hasargs) ? CXp_HASARGS : 0;
3732                cx->blk_sub.retop       = retop;
3733                SvREFCNT_inc_simple_void_NN(cv);
3734            */
3735
3736       Note that cx_pushblock() sets two new floors: for the args stack (to
3737       "MARK") and the temps stack (to "PL_tmps_ix"). While executing at this
3738       scope level, every "nextstate" (amongst others) will reset the args and
3739       tmps stack levels to these floors. Note that since "cx_pushblock" uses
3740       the current value of "PL_tmps_ix" rather than it being passed as an
3741       arg, this dictates at what point "cx_pushblock" should be called. In
3742       particular, any new mortals which should be freed only on scope exit
3743       (rather than at the next "nextstate") should be created first.
3744
3745       Most callers of "cx_pushblock" simply set the new args stack floor to
3746       the top of the previous stack frame, but for "CXt_LOOP_LIST" it stores
3747       the items being iterated over on the stack, and so sets "blk_oldsp" to
3748       the top of these items instead. Note that, contrary to its name,
3749       "blk_oldsp" doesn't always represent the value to restore "PL_stack_sp"
3750       to on scope exit.
3751
3752       Note the early capture of "PL_savestack_ix" to "old_ss_ix", which is
3753       later passed as an arg to "cx_pushblock". In the case of "pp_entersub",
3754       this is because, although most values needing saving are stored in
3755       fields of the context struct, an extra value needs saving only when the
3756       debugger is running, and it doesn't make sense to bloat the struct for
3757       this rare case. So instead it is saved on the savestack. Since this
3758       value gets calculated and saved before the context is pushed, it is
3759       necessary to pass the old value of "PL_savestack_ix" to "cx_pushblock",
3760       to ensure that the saved value gets freed during scope exit.  For most
3761       users of "cx_pushblock", where nothing needs pushing on the save stack,
3762       "PL_savestack_ix" is just passed directly as an arg to "cx_pushblock".
3763
3764       Note that where possible, values should be saved in the context struct
3765       rather than on the save stack; it's much faster that way.
3766
3767       Normally "cx_pushblock" should be immediately followed by the
3768       appropriate "cx_pushfoo", with nothing between them; this is because if
3769       code in-between could die (e.g. a warning upgraded to fatal), then the
3770       context stack unwinding code in "dounwind" would see (in the example
3771       above) a "CXt_SUB" context frame, but without all the subroutine-
3772       specific fields set, and crashes would soon ensue.
3773
3774       Where the two must be separate, initially set the type to "CXt_NULL" or
3775       "CXt_BLOCK", and later change it to "CXt_foo" when doing the
3776       "cx_pushfoo". This is exactly what "pp_enteriter" does, once it's
3777       determined which type of loop it's pushing.
3778
3779   Popping contexts
3780       Contexts are popped using cx_popsub() etc. and cx_popblock(). Note
3781       however, that unlike "cx_pushblock", neither of these functions
3782       actually decrement the current context stack index; this is done
3783       separately using CX_POP().
3784
3785       There are two main ways that contexts are popped. During normal
3786       execution as scopes are exited, functions like "pp_leave",
3787       "pp_leaveloop" and "pp_leavesub" process and pop just one context using
3788       "cx_popfoo" and "cx_popblock". On the other hand, things like
3789       "pp_return" and "next" may have to pop back several scopes until a sub
3790       or loop context is found, and exceptions (such as "die") need to pop
3791       back contexts until an eval context is found. Both of these are
3792       accomplished by dounwind(), which is capable of processing and popping
3793       all contexts above the target one.
3794
3795       Here is a typical example of context popping, as found in "pp_leavesub"
3796       (simplified slightly):
3797
3798        U8 gimme;
3799        PERL_CONTEXT *cx;
3800        SV **oldsp;
3801        OP *retop;
3802
3803        cx = CX_CUR();
3804
3805        gimme = cx->blk_gimme;
3806        oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
3807
3808        if (gimme == G_VOID)
3809            PL_stack_sp = oldsp;
3810        else
3811            leave_adjust_stacks(oldsp, oldsp, gimme, 0);
3812
3813        CX_LEAVE_SCOPE(cx);
3814        cx_popsub(cx);
3815        cx_popblock(cx);
3816        retop = cx->blk_sub.retop;
3817        CX_POP(cx);
3818
3819        return retop;
3820
3821       The steps above are in a very specific order, designed to be the
3822       reverse order of when the context was pushed. The first thing to do is
3823       to copy and/or protect any return arguments and free any temps in the
3824       current scope. Scope exits like an rvalue sub normally return a mortal
3825       copy of their return args (as opposed to lvalue subs). It is important
3826       to make this copy before the save stack is popped or variables are
3827       restored, or bad things like the following can happen:
3828
3829           sub f { my $x =...; $x }  # $x freed before we get to copy it
3830           sub f { /(...)/;    $1 }  # PL_curpm restored before $1 copied
3831
3832       Although we wish to free any temps at the same time, we have to be
3833       careful not to free any temps which are keeping return args alive; nor
3834       to free the temps we have just created while mortal copying return
3835       args. Fortunately, leave_adjust_stacks() is capable of making mortal
3836       copies of return args, shifting args down the stack, and only
3837       processing those entries on the temps stack that are safe to do so.
3838
3839       In void context no args are returned, so it's more efficient to skip
3840       calling leave_adjust_stacks(). Also in void context, a "nextstate" op
3841       is likely to be imminently called which will do a "FREETMPS", so
3842       there's no need to do that either.
3843
3844       The next step is to pop savestack entries: CX_LEAVE_SCOPE(cx) is just
3845       defined as LEAVE_SCOPE(cx->blk_oldsaveix). Note that during the
3846       popping, it's possible for perl to call destructors, call "STORE" to
3847       undo localisations of tied vars, and so on. Any of these can die or
3848       call exit(). In this case, dounwind() will be called, and the current
3849       context stack frame will be re-processed. Thus it is vital that all
3850       steps in popping a context are done in such a way to support
3851       reentrancy.  The other alternative, of decrementing "cxstack_ix" before
3852       processing the frame, would lead to leaks and the like if something
3853       died halfway through, or overwriting of the current frame.
3854
3855       "CX_LEAVE_SCOPE" itself is safely re-entrant: if only half the
3856       savestack items have been popped before dying and getting trapped by
3857       eval, then the "CX_LEAVE_SCOPE"s in "dounwind" or "pp_leaveeval" will
3858       continue where the first one left off.
3859
3860       The next step is the type-specific context processing; in this case
3861       "cx_popsub". In part, this looks like:
3862
3863           cv = cx->blk_sub.cv;
3864           CvDEPTH(cv) = cx->blk_sub.olddepth;
3865           cx->blk_sub.cv = NULL;
3866           SvREFCNT_dec(cv);
3867
3868       where its processing the just-executed CV. Note that before it
3869       decrements the CV's reference count, it nulls the "blk_sub.cv". This
3870       means that if it re-enters, the CV won't be freed twice. It also means
3871       that you can't rely on such type-specific fields having useful values
3872       after the return from "cx_popfoo".
3873
3874       Next, "cx_popblock" restores all the various interpreter vars to their
3875       previous values or previous high water marks; it expands to:
3876
3877           PL_markstack_ptr = PL_markstack + cx->blk_oldmarksp;
3878           PL_scopestack_ix = cx->blk_oldscopesp;
3879           PL_curpm         = cx->blk_oldpm;
3880           PL_curcop        = cx->blk_oldcop;
3881           PL_tmps_floor    = cx->blk_old_tmpsfloor;
3882
3883       Note that it doesn't restore "PL_stack_sp"; as mentioned earlier, which
3884       value to restore it to depends on the context type (specifically "for
3885       (list) {}"), and what args (if any) it returns; and that will already
3886       have been sorted out earlier by leave_adjust_stacks().
3887
3888       Finally, the context stack pointer is actually decremented by
3889       CX_POP(cx).  After this point, it's possible that that the current
3890       context frame could be overwritten by other contexts being pushed.
3891       Although things like ties and "DESTROY" are supposed to work within a
3892       new context stack, it's best not to assume this. Indeed on debugging
3893       builds, CX_POP(cx) deliberately sets "cx" to null to detect code that
3894       is still relying on the field values in that context frame. Note in the
3895       pp_leavesub() example above, we grab "blk_sub.retop" before calling
3896       "CX_POP".
3897
3898   Redoing contexts
3899       Finally, there is cx_topblock(cx), which acts like a super-"nextstate"
3900       as regards to resetting various vars to their base values. It is used
3901       in places like "pp_next", "pp_redo" and "pp_goto" where rather than
3902       exiting a scope, we want to re-initialise the scope. As well as
3903       resetting "PL_stack_sp" like "nextstate", it also resets
3904       "PL_markstack_ptr", "PL_scopestack_ix" and "PL_curpm". Note that it
3905       doesn't do a "FREETMPS".
3906

Slab-based operator allocation

3908       Note: this section describes a non-public internal API that is subject
3909       to change without notice.
3910
3911       Perl's internal error-handling mechanisms implement "die" (and its
3912       internal equivalents) using longjmp. If this occurs during lexing,
3913       parsing or compilation, we must ensure that any ops allocated as part
3914       of the compilation process are freed. (Older Perl versions did not
3915       adequately handle this situation: when failing a parse, they would leak
3916       ops that were stored in C "auto" variables and not linked anywhere
3917       else.)
3918
3919       To handle this situation, Perl uses op slabs that are attached to the
3920       currently-compiling CV. A slab is a chunk of allocated memory. New ops
3921       are allocated as regions of the slab. If the slab fills up, a new one
3922       is created (and linked from the previous one). When an error occurs and
3923       the CV is freed, any ops remaining are freed.
3924
3925       Each op is preceded by two pointers: one points to the next op in the
3926       slab, and the other points to the slab that owns it. The next-op
3927       pointer is needed so that Perl can iterate over a slab and free all its
3928       ops. (Op structures are of different sizes, so the slab's ops can't
3929       merely be treated as a dense array.)  The slab pointer is needed for
3930       accessing a reference count on the slab: when the last op on a slab is
3931       freed, the slab itself is freed.
3932
3933       The slab allocator puts the ops at the end of the slab first. This will
3934       tend to allocate the leaves of the op tree first, and the layout will
3935       therefore hopefully be cache-friendly. In addition, this means that
3936       there's no need to store the size of the slab (see below on why slabs
3937       vary in size), because Perl can follow pointers to find the last op.
3938
3939       It might seem possible to eliminate slab reference counts altogether,
3940       by having all ops implicitly attached to "PL_compcv" when allocated and
3941       freed when the CV is freed. That would also allow "op_free" to skip
3942       "FreeOp" altogether, and thus free ops faster. But that doesn't work in
3943       those cases where ops need to survive beyond their CVs, such as re-
3944       evals.
3945
3946       The CV also has to have a reference count on the slab. Sometimes the
3947       first op created is immediately freed. If the reference count of the
3948       slab reaches 0, then it will be freed with the CV still pointing to it.
3949
3950       CVs use the "CVf_SLABBED" flag to indicate that the CV has a reference
3951       count on the slab. When this flag is set, the slab is accessible via
3952       "CvSTART" when "CvROOT" is not set, or by subtracting two pointers
3953       "(2*sizeof(I32 *))" from "CvROOT" when it is set. The alternative to
3954       this approach of sneaking the slab into "CvSTART" during compilation
3955       would be to enlarge the "xpvcv" struct by another pointer. But that
3956       would make all CVs larger, even though slab-based op freeing is
3957       typically of benefit only for programs that make significant use of
3958       string eval.
3959
3960       When the "CVf_SLABBED" flag is set, the CV takes responsibility for
3961       freeing the slab. If "CvROOT" is not set when the CV is freed or
3962       undeffed, it is assumed that a compilation error has occurred, so the
3963       op slab is traversed and all the ops are freed.
3964
3965       Under normal circumstances, the CV forgets about its slab (decrementing
3966       the reference count) when the root is attached. So the slab reference
3967       counting that happens when ops are freed takes care of freeing the
3968       slab. In some cases, the CV is told to forget about the slab
3969       ("cv_forget_slab") precisely so that the ops can survive after the CV
3970       is done away with.
3971
3972       Forgetting the slab when the root is attached is not strictly
3973       necessary, but avoids potential problems with "CvROOT" being written
3974       over. There is code all over the place, both in core and on CPAN, that
3975       does things with "CvROOT", so forgetting the slab makes things more
3976       robust and avoids potential problems.
3977
3978       Since the CV takes ownership of its slab when flagged, that flag is
3979       never copied when a CV is cloned, as one CV could free a slab that
3980       another CV still points to, since forced freeing of ops ignores the
3981       reference count (but asserts that it looks right).
3982
3983       To avoid slab fragmentation, freed ops are marked as freed and attached
3984       to the slab's freed chain (an idea stolen from DBM::Deep). Those freed
3985       ops are reused when possible. Not reusing freed ops would be simpler,
3986       but it would result in significantly higher memory usage for programs
3987       with large "if (DEBUG) {...}" blocks.
3988
3989       "SAVEFREEOP" is slightly problematic under this scheme. Sometimes it
3990       can cause an op to be freed after its CV. If the CV has forcibly freed
3991       the ops on its slab and the slab itself, then we will be fiddling with
3992       a freed slab. Making "SAVEFREEOP" a no-op doesn't help, as sometimes an
3993       op can be savefreed when there is no compilation error, so the op would
3994       never be freed. It holds a reference count on the slab, so the whole
3995       slab would leak. So "SAVEFREEOP" now sets a special flag on the op
3996       ("->op_savefree"). The forced freeing of ops after a compilation error
3997       won't free any ops thus marked.
3998
3999       Since many pieces of code create tiny subroutines consisting of only a
4000       few ops, and since a huge slab would be quite a bit of baggage for
4001       those to carry around, the first slab is always very small. To avoid
4002       allocating too many slabs for a single CV, each subsequent slab is
4003       twice the size of the previous.
4004
4005       Smartmatch expects to be able to allocate an op at run time, run it,
4006       and then throw it away. For that to work the op is simply malloced when
4007       "PL_compcv" hasn't been set up. So all slab-allocated ops are marked as
4008       such ("->op_slabbed"), to distinguish them from malloced ops.
4009

AUTHORS

4011       Until May 1997, this document was maintained by Jeff Okamoto
4012       <okamoto@corp.hp.com>.  It is now maintained as part of Perl itself by
4013       the Perl 5 Porters <perl5-porters@perl.org>.
4014
4015       With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
4016       Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
4017       Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
4018       Stephen McCamant, and Gurusamy Sarathy.
4019

SEE ALSO

4021       perlapi, perlintern, perlxs, perlembed
4022
4023
4024
4025perl v5.38.2                      2023-11-30                       PERLGUTS(1)
Impressum