PERLGUTS(1)

okay bestie, welcome to perlguts(1) from the Perl Programmers Reference Guide ๐Ÿ’–โœจ this is the manual page that's gonna hold your hand through the Perl API, no cap.

โœจ NAME โœจ

perlguts - Introduction to the Perl API

๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so this document is literally trying its best to describe how to use the Perl API, plus give you some deets on the basic workings of the Perl core ๐Ÿซถ. ngl it is far from complete and probably contains many errors ๐Ÿ˜ญ. please send any questions or comments to the author below.


๐ŸŒธ Variables ๐ŸŒธ

โœจ Datatypes โœจ

Perl has three typedefs that handle Perl's three main data types:

SV  Scalar Value
AV  Array Value
HV  Hash Value

Each typedef has specific routines that manipulate the various data types. slay.

๐Ÿ’… What is an "IV"? ๐Ÿ’…

Perl uses a special typedef IV which is a simple signed integer type that is guaranteed to be large enough to hold a pointer, but may be larger, depending on how perl is Configured ๐Ÿ‘‘. Additionally, there is the UV, which is simply an unsigned IV.

Perl also uses several special typedefs to declare variables to hold integers of (at least) a given size. Use I8, I16, I32, and I64 to declare a signed integer variable which has at least as many bits as the number in its name. These all evaluate to the native C type that is closest to the given number of bits, but no smaller than that number. For example, on many platforms, a short is 16 bits long, and if so, I16 will evaluate to a short. But on platforms where a short isn't exactly 16 bits, Perl will use the smallest type that contains 16 bits or more.

U8, U16, U32, and U64 are to declare the corresponding unsigned integer types.

If the platform doesn't support 64-bit integers, both I64 and U64 will be undefined ๐Ÿซ . Use IV and UV to declare the largest practicable, and "WIDEST_UTYPE" in perlapi for the absolute maximum unsigned, but which may not be usable in all circumstances.

A numeric constant can be specified with "INT16_C" in perlapi, "UINTMAX_C" in perlapi, and similar.

๐Ÿฆ‹ Working with SVs ๐Ÿฆ‹

An SV can be created and loaded with one command. There are five types of values that can be loaded: an integer value (IV), an unsigned integer value (UV), a double (NV), a string (PV), and another scalar (SV). ("PV" stands for "Pointer Value". You might think that it is misnamed because it is described as pointing only to strings. However, it is possible to have it point to other things. For example, it could point to an array of UVs. But, using it for non-strings requires care, as the underlying assumption of much of the internals is that PVs are just for strings. Often, for example, a trailing NUL is tacked on automatically. The non-string use is documented only in this paragraph.)

There are more than a few routines that create and initialize SVs, with new ones occasionally added. These are all documented in "SV Handling" in perlapi; each one's name begins with newSV. Here are the basic ones:

SV*  newSVbool(boolean_value);
SV*  newSViv(IV);
SV*  newSVuv(UV);
SV*  newSVnv(double);
SV*  newSVpv(const char*, STRLEN);
SV*  newSVpvf_nocontext(const char * const pat, ...)
SV*  newSVpvn(const char*, STRLEN);
SV*  newSVpvs("literal string")
SV*  newSVpvz(STRLEN)
SV*  newSVsv(SV*);

STRLEN is an integer type (Size_t, usually defined as size_t in config.h) guaranteed to be large enough to represent the size of any string that perl can handle.

literal string is a string enclosed in double quote characters, and the created SV is of string type (a PV), initialized to contain a copy of the literal string parameter. newSVpvs("") creates an SV containing an empty (zero-length) string and returns a pointer to it.

newSVpvz is like newSVpvs(""), but it reserves the number of bytes specified by its parameter for future growth, without having to reallocate memory. It is useful in situations where you don't know what the string eventually will be, but you have a pretty good idea of its eventual minimum size.

In the case of an SV requiring more complex initialization, you can create an empty SV with newSV(len). If len is 0 an empty SV of type NULL is returned, else an SV of type PV is returned with len + 1 (for the NUL) bytes of storage allocated, accessible via SvPVX. In both cases the SV has the undef value.

SV *sv = newSV(0);   /* no storage allocated  */
SV *sv = newSV(10);  /* 10 (+1) bytes of uninitialised storage
                      * allocated */

To change the value of an already-existing SV, these are the basic routines (with more specified in "SV Handling" in perlapi):

void  sv_setbool(SV*, bool);
void  sv_setiv(SV*, IV);
void  sv_setuv(SV*, UV);
void  sv_setnv(SV*, double);
void  sv_setpv(SV*, const char*);
void  sv_setpvn(SV*, const char*, STRLEN)
void  sv_setpvf(SV*, const char*, ...);
void  sv_vsetpvfn(SV*, const char*, STRLEN, va_list *,
                                    SV **, Size_t, bool *);
void  sv_setsv(SV*, SV*);

Notice that you can choose to specify the length of the string to be assigned by using sv_setpvn, newSVpvn, or newSVpv, or you may allow Perl to calculate the length by using sv_setpv or by specifying 0 as the second argument to newSVpv. Be warned, though, that Perl will determine the string's length by using strlen, which depends on the string terminating with a NUL character, and not otherwise containing NULs. so like, no sneaky NULs in the middle, bestie.

The arguments of sv_setpvf are processed like sprintf, and the formatted output becomes the value.

sv_vsetpvfn is an analogue of vsprintf, but it allows you to specify either a pointer to a variable argument list or the address and length of an array of SVs. The last argument points to a boolean; on return, if that boolean is true, then locale-specific information has been used to format the string, and the string's contents are therefore untrustworthy (see perlsec). This pointer may be NULL if that information is not important. Note that this function requires you to specify the length of the format.

The sv_set*() functions are not generic enough to operate on values that have "magic". See "Magic Virtual Tables" later in this document.

All SVs that contain strings should be terminated with a NUL character. If it is not NUL-terminated there is a risk of core dumps and corruptions from code which passes the string to C functions or system calls which expect a NUL-terminated string ๐Ÿ˜ฑ. Perl's own functions typically add a trailing NUL for this reason. Nevertheless, you should be very careful when you pass a string stored in an SV to a C function or system call.

To access the actual value that an SV points to, Perl's API exposes several macros that coerce the actual scalar type into an IV, UV, double, or string:

  • SvIV(SV*) (IV) and SvUV(SV*) (UV)
  • SvNV(SV*) (double)
  • Strings are a bit complicated:
    • Byte string: SvPVbyte(SV*, STRLEN len) or SvPVbyte_nolen(SV*)

If the Perl string is "\xff\xff", then this returns a 2-byte char*.

This is suitable for Perl strings that represent bytes.

  • UTF-8 string: SvPVutf8(SV*, STRLEN len) or SvPVutf8_nolen(SV*)

If the Perl string is "\xff\xff", then this returns a 4-byte char*.

This is suitable for Perl strings that represent characters.

CAVEAT: That char* will be encoded via Perl's internal UTF-8 variant, which means that if the SV contains non-Unicode code points (e.g., 0x110000), then the result may contain extensions over valid UTF-8. See "is_strict_utf8_string" in perlapi for some methods Perl gives you to check the UTF-8 validity of these macros' returns.

  • You can also use SvPV(SV*, STRLEN len) or SvPV_nolen(SV*) to fetch the SV's raw internal buffer. This is tricky, though; if your Perl string is "\xff\xff", then depending on the SV's internal encoding you might get back a 2-byte OR a 4-byte char*. Moreover, if it's the 4-byte string, that could come from either Perl "\xff\xff" stored UTF-8 encoded, or Perl "\xc3\xbf\xc3\xbf" stored as raw octets. To differentiate between these you MUST look up the SV's UTF8 bit (cf. SvUTF8) to know whether the source Perl string is 2 characters (SvUTF8 would be on) or 4 characters (SvUTF8 would be off).

IMPORTANT: Use of SvPV, SvPV_nolen, or similarly-named macros without looking up the SV's UTF8 bit is almost certainly a bug if non-ASCII input is allowed.

When the UTF8 bit is on, the same CAVEAT about UTF-8 validity applies here as for SvPVutf8.

(See "How do I pass a Perl string to a C library?" for more details.)

In SvPVbyte, SvPVutf8, and SvPV, the length of the char* returned is placed into the variable len (these are macros, so you do not use &len). If you do not care what the length of the data is, use SvPVbyte_nolen, SvPVutf8_nolen, or SvPV_nolen instead. The global variable PL_na can also be given to SvPVbyte/SvPVutf8/SvPV in this case. But that can be quite inefficient because PL_na must be accessed in thread-local storage in threaded Perl. In any case, remember that Perl allows arbitrary strings of data that may both contain NULs and might not be terminated by a NUL.

Also remember that C doesn't allow you to safely say foo(SvPVbyte(s, len), len);. It might work with your compiler, but it won't work for everyone. Break this sort of statement up into separate assignments:

SV *s;
STRLEN len;
char *ptr;
ptr = SvPVbyte(s, len);
foo(ptr, len);

If you want to know if the scalar value is TRUE, you can use:

SvTRUE(SV*)

Although Perl will automatically grow strings for you, if you need to force Perl to allocate more memory for your SV, you can use the macro

SvGROW(SV*, STRLEN newlen)

which will determine if more memory needs to be allocated. If so, it will call the function sv_grow. Note that SvGROW can only increase, not decrease, the allocated memory of an SV and that it does not automatically add space for the trailing NUL byte (perl's own string functions typically do SvGROW(sv, len + 1)).

If you want to write to an existing SV's buffer and set its value to a string, use SvPVbyte_force() or one of its variants to force the SV to be a PV. This will remove any of various types of non-stringness from the SV while preserving the content of the SV in the PV. This can be used, for example, to append data from an API function to a buffer without extra copying:

           (void)SvPVbyte_force(sv, len);
           s = SvGROW(sv, len + needlen + 1);
           /* something that modifies up to needlen bytes at s+len, but
              modifies newlen bytes
                eg. newlen = read(fd, s + len, needlen);
              ignoring errors for these examples
            */
           s[len + newlen] = '\0';
           SvCUR_set(sv, len + newlen);
           SvUTF8_off(sv);
           SvSETMAGIC(sv);

okay so bestie, if you already have the data in memory or you just want to keep your code simple, you can use one of the sv_cat*() variants, like sv_catpvn(). and if you wanna insert anywhere in the string? use sv_insert() or sv_insert_flags(). slay โœจ

if you don't need the existing content of the SV, you can avoid some copying with:

           SvPVCLEAR(sv);
           s = SvGROW(sv, needlen + 1);
           /* something that modifies up to needlen bytes at s, but modifies
              newlen bytes
                eg. newlen = read(fd, s, needlen);
            */
           s[newlen] = '\0';
           SvCUR_set(sv, newlen);
           SvPOK_only(sv); /* also clears SVf_UTF8 */
           SvSETMAGIC(sv);

again, if you already have the data in memory or want to avoid the complexity of the above, you can use sv_setpvn().

if you have a buffer allocated with Newx() and want to set that as the SV's value, you can use sv_usepvn_flags(). that has some requirements if you want to avoid perl re-allocating the buffer to fit the trailing NUL:

          Newx(buf, somesize+1, char);
          /* ... fill in buf ... */
          buf[somesize] = '\0';
          sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_NUL);
          /* buf now belongs to perl, don't release it */

if you have an SV and want to know what kind of data Perl thinks is stored in it, you can use the following macros to check the type of SV you have.

    SvIOK(SV*)
    SvNOK(SV*)
    SvPOK(SV*)

lowkey important: retrieving the numeric value of an SV can set IOK or NOK on that SV, even when the SV started as a string. prior to Perl 5.36.0 retrieving the string value of an integer could set POK, but this can no longer occur. from 5.36.0 this can be used to distinguish the original representation of an SV and is intended to make life simpler for serializers:

    /* references handled elsewhere */
    if (SvIsBOOL(sv)) {
        /* originally boolean */
        ...
    }
    else if (SvPOK(sv)) {
        /* originally a string */
        ...
    }
    else if (SvNIOK(sv)) {
        /* originally numeric */
        ...
    }
    else {
        /* something special or undef */
    }

you can get and set the current length of the string stored in an SV with the following macros:

    SvCUR(SV*)
    SvCUR_set(SV*, I32 val)

you can also get a pointer to the end of the string stored in the SV with the macro:

SvEND(SV*)

but note that these last three macros are valid only if SvPOK() is true. periodt ๐Ÿ’…

if you want to append something to the end of string stored in an SV*, you can use the following functions:

    void  sv_catpv(SV*, const char*);
    void  sv_catpvn(SV*, const char*, STRLEN);
    void  sv_catpvf(SV*, const char*, ...);
    void  sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **,
                                                             I32, bool);
    void  sv_catsv(SV*, SV*);

the first function calculates the length of the string to be appended by using strlen. in the second, you specify the length of the string yourself. the third function processes its arguments like sprintf and appends the formatted output. the fourth function works like vsprintf. you can specify the address and length of an array of SVs instead of the va_list argument. the fifth function extends the string stored in the first SV with the string stored in the second SV. it also forces the second SV to be interpreted as a string.

the sv_cat*() functions are not generic enough to operate on values that have "magic". see "Magic Virtual Tables" later in this document.

if you know the name of a scalar variable, you can get a pointer to its SV by using the following:

SV* get_sv("package::varname", 0);

this returns NULL if the variable does not exist.

if you want to know if this variable (or any other SV) is actually "defined", you can call:

SvOK(SV*)

the scalar undef value is stored in an SV instance called PL_sv_undef.

its address can be used whenever an SV* is needed. make sure that you don't try to compare a random sv with &PL_sv_undef. for example when interfacing Perl code, it'll work correctly for:

  foo(undef);

but won't work when called as:

  $x = undef;
  foo($x);

so to repeat always use SvOK() to check whether an sv is defined. no cap ๐Ÿซถ

also you have to be careful when using &PL_sv_undef as a value in AVs or HVs (see "AVs, HVs and undefined values").

there are also the two values PL_sv_yes and PL_sv_no, which contain boolean TRUE and FALSE values, respectively. like PL_sv_undef, their addresses can be used whenever an SV* is needed.

do not be fooled into thinking that (SV *) 0 is the same as &PL_sv_undef. take this code:

    SV* sv = (SV*) 0;
    if (I-am-to-return-a-real-value) {
            sv = sv_2mortal(newSViv(42));
    }
    sv_setsv(ST(0), sv);

this code tries to return a new SV (which contains the value 42) if it should return a real value, or undef otherwise. instead it has returned a NULL pointer which, somewhere down the line, will cause a segmentation violation, bus error, or just weird results. change the zero to &PL_sv_undef in the first line and all will be well. ๐Ÿ’€

to free an SV that you've created, call SvREFCNT_dec(SV*). normally this call is not necessary (see "Reference Counts and Mortality").


๐ŸŒธ Offsets ๐ŸŒธ

Perl provides the function sv_chop to efficiently remove characters from the beginning of a string; you give it an SV and a pointer to somewhere inside the PV, and it discards everything before the pointer. the efficiency comes by means of a little hack: instead of actually removing the characters, sv_chop sets the flag OOK (offset OK) to signal to other functions that the offset hack is in effect, and it moves the PV pointer (called SvPVX) forward by the number of bytes chopped off, and adjusts SvCUR and SvLEN accordingly. (a portion of the space between the old and new PV pointers is used to store the count of chopped bytes.)

hence, at this point, the start of the buffer that we allocated lives at SvPVX(sv) - SvIV(sv) in memory and the PV pointer is pointing into the middle of this allocated storage.

this is best demonstrated by example. normally copy-on-write will prevent the substitution from operator from using this hack, but if you can craft a string for which copy-on-write is not possible, you can see it in play. in the current implementation, the final byte of a string buffer is used as a copy-on-write reference count. if the buffer is not big enough, then copy-on-write is skipped. first have a look at an empty string:

  % ./perl -Ilib -MDevel::Peek -le '$a=""; $a .= ""; Dump $a'
  SV = PV(0x7ffb7c008a70) at 0x7ffb7c030390
    REFCNT = 1
    FLAGS = (POK,pPOK)
    PV = 0x7ffb7bc05b50 ""\0
    CUR = 0
    LEN = 10

notice here the LEN is 10. (it may differ on your platform.) extend the length of the string to one less than 10, and do a substitution:

 % ./perl -Ilib -MDevel::Peek -le '$a=""; $a.="123456789"; $a=~s/.//; \
                                                            Dump($a)'
 SV = PV(0x7ffa04008a70) at 0x7ffa04030390
   REFCNT = 1
   FLAGS = (POK,OOK,pPOK)
   OFFSET = 1
   PV = 0x7ffa03c05b61 ( "\1" . ) "23456789"\0
   CUR = 8
   LEN = 9

here the number of bytes chopped off (1) is shown next as the OFFSET. the portion of the string between the "real" and the "fake" beginnings is shown in parentheses, and the values of SvCUR and SvLEN reflect the fake beginning, not the real one. (the first character of the string buffer happens to have changed to "\1" here, not "1", because the current implementation stores the offset count in the string buffer. this is subject to change.)

something similar to the offset hack is performed on AVs to enable efficient shifting and splicing off the beginning of the array; while AvARRAY points to the first element in the array that is visible from Perl, AvALLOC points to the real start of the C array. these are usually the same, but a shift operation can be carried out by increasing AvARRAY by one and decreasing AvFILL and AvMAX. again, the location of the real start of the C array only comes into play when freeing the array. see av_shift in av.c.

๐Ÿ’– What's Really Stored in an SV? ๐Ÿ’–

recall that the usual method of determining the type of scalar you have is to use Sv*OK macros. because a scalar can be both a number and a string, usually these macros will always return TRUE and calling the Sv*V macros will do the appropriate conversion of string to integer/double or integer/double to string.

if you really need to know if you have an integer, double, or string pointer in an SV, you can use the following three macros instead:

    SvIOKp(SV*)
    SvNOKp(SV*)
    SvPOKp(SV*)

these will tell you if you truly have an integer, double, or string pointer stored in your SV. the "p" stands for private.

there are various ways in which the private and public flags may differ. for example, in perl 5.16 and earlier a tied SV may have a valid underlying value in the IV slot (so SvIOKp is true), but the data should be accessed via the FETCH routine rather than directly, so SvIOK is false. (in perl 5.18 onwards, tied scalars use the flags the same way as untied scalars.) another is when numeric conversion has occurred and precision has been lost: only the private flag is set on 'lossy' values. so when an NV is converted to an IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK won't be.

in general, though, it's best to use the Sv*V macros.

๐Ÿ”’ Read-Only Values ๐Ÿ”’

in Perl 5.16 and earlier, copy-on-write (see the next section) shared a flag bit with read-only scalars. so the only way to test whether sv_setsv, etc., will raise a "Modification of a read-only value" error in those versions is:

    SvREADONLY(sv) && !SvIsCOW(sv)

under Perl 5.18 and later, SvREADONLY only applies to read-only variables, and, under 5.20, copy-on-write scalars can also be read-only, so the above check is incorrect. you just want:

    SvREADONLY(sv)

if you need to do this check often, define your own macro like this:

#if PERL_VERSION >= 18
# define SvTRULYREADONLY(sv) SvREADONLY(sv)
#else
# define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
#endif

Or honestly bestie, just scroll down and read about the THINKFIRST macros. They're right there. ๐Ÿ’…


๐ŸŒธ Copy on Write ๐ŸŒธ

Okay so Perl does this absolutely iconic thing with scalars called copy-on-write, aka COW. The whole vibe is: when someone asks for a string copy, Perl is like "bestieโ€ฆ do we actually need a whole new copy rn? ๐Ÿคจ" and it defers the copy until one of the scalars involved actually changes. So the copy happens lazily, only when it's literally necessary.

It's mostly transparent โ€” you don't notice it, it just works โ€” BUT here's the catch: you must not go modifying string buffers that are shared by multiple SVs. That's a no-no. Do not do that. ๐Ÿ™ˆ

Wanna know if an SV is out here living that COW life? Check with SvIsCOW(sv).

Wanna force an SV to make its own personal copy of its string buffer? Call sv_force_normal(sv) or SvPV_force_nolen(sv). Making it stand on its own. Main character energy, honestly. ๐Ÿ‘‘

If instead you want the SV to just drop its string buffer entirely, use sv_force_normal_flags(sv, SV_COW_DROP_PV) โ€” or, even simpler, sv_setsv(sv, NULL).

โš ๏ธ Heads up: all of these functions will croak on read-only scalars. (See the previous section for the tea on those.) So, like, don't.

If you want to test that your code is actually behaving and not sneakily mutating COW buffers, and you're on a system that supports mmap(2) (think Unix, Linux, BSDs, macOS), you can configure perl with -Accflags=-DPERL_DEBUG_READONLY_COW and it will straight up turn buffer violations into crashes. Dramatic? Yes. Effective? Also yes. ๐Ÿ’€

It will be marvellously slow, so you may want to skip perl's own tests. Like, it's giving molasses. ๐ŸŒ

โœจ THINKFIRST before writing to a string buffer โœจ

You are way more likely to see โ€” and usually you should see โ€” the SvTHINKFIRST(sv) macro, because it's used to check whether an SV is even ready to be written to. It's one combined single check that asks: is this SV doing any of the following?

  • Pointing to a COW buffer
  • Being READONLY
  • Containing a reference
  • Having some relevant magic assigned

Two related macros do those checks and take action if it's needed:

  • SV_CHECK_THINKFIRST(sv) โ€” calls sv_force_normal(sv) to copy the string buffer, turning it into a mutable string. Now it's editable, slay.
  • SV_CHECK_THINKFIRST_COW_DROP(sv) โ€” calls sv_force_normal_flags(sv, SV_COW_DROP_PV), which drops any string buffer that sv points to. Usually you use this to avoid copying a COW string into a new buffer when you're about to write a completely new string into sv anyway. Waste not, want not. ๐ŸŽ€

๐Ÿฆ‹ Working with AVs ๐Ÿฆ‹

There are two main, longstanding ways to create and load an AV. Method one creates an empty AV:

AV*  newAV();

Method two creates the AV and populates it with SVs right off the bat:

AV*  av_make(SSize_t num, SV **ptr);

That second argument points to an array holding num SV*'s. And once the AV has been created, those SVs can be destroyed if you feel like it. Free them. Let them go. ๐Ÿ•Š๏ธ

Then Perl v5.36 came through and added two new ways to create an AV and allocate a SV** array without populating it. These are more efficient than doing a newAV() followed by an av_extend() โ€” glow up โœจ:

/* Creates but does not initialize (Zero) the SV** array */
AV *av = newAV_alloc_x(1);
/* Creates and does initialize (Zero) the SV** array */
AV *av = newAV_alloc_xz(1);

That numerical argument is the number of array elements to allocate โ€” not an array index โ€” and it must be >0. Also:

๐Ÿšจ The first form must only ever be used when all elements will be initialized before any read occurs. Reading a non-initialized SV* โ€” i.e. treating a random memory address as a SV* โ€” is a serious bug. Not cute. Not the vibe. Don't. ๐Ÿ’€

Once your AV exists, here's what you can do to it:

void  av_push(AV*, SV*);
SV*   av_pop(AV*);
SV*   av_shift(AV*);
void  av_unshift(AV*, SSize_t num);

These should feel familiar, except for av_unshift โ€” that one's the quirky one. It adds num elements at the front of the array, all with the undef value. Then you have to use av_store (described below) to actually assign values to those new elements. You put them there, now you gotta fill them in. ๐Ÿ’…

Here are some other functions:

Size_t  av_count(AV*);
SSize_t av_top_index(AV*);
SV**    av_fetch(AV*, SSize_t key, I32 lval);
SV**    av_store(AV*, SSize_t key, SV* val);
  • av_count returns the number of elements in the array โ€” and yes, that includes any empty slots (undefined ones) that are intermixed with the filled-in ones.
  • av_top_index returns the highest index value in an array, just like $#array in Perl. If the array is empty, it returns -1. It is always equal to av_count() - 1.
  • av_fetch returns the value at index key, but if lval is non-zero, then av_fetch will store an undef value at that index.
  • av_store stores the value val at index key, and โ€” important โ€” it does not increment the reference count of val. So the caller is responsible for taking care of that. And if av_store returns NULL, the caller will have to decrement the reference count to avoid a memory leak. ๐Ÿ˜ญ
Also clock this: both av_fetch and av_store return SV**'s, not SV*'s. Double pointer, bestie. Don't forget the second star. โญ

A few more:

void  av_clear(AV*);
void  av_undef(AV*);
void  av_extend(AV*, SSize_t key);
  • av_clear deletes all the elements in the AV* array, but does not actually delete the array itself. The array stays. Just empty.
  • av_undef deletes all the elements in the array plus the array itself. Gone gone. ๐Ÿซถ
  • av_extend extends the array so it contains at least key+1 elements. But if key+1 is less than the currently allocated length of the array, then nothing happens. Nothing. Zero. Nada.

If you already know the name of an array variable, you can grab a pointer to its AV like this:

AV*  get_av("package::varname", 0);

This returns NULL if the variable does not exist. (Rude of the variable, honestly.)

See "Understanding the Magic of Tied Hashes and Arrays" for more info on how to use the array access functions on tied arrays. ๐Ÿ”ฎ


๐ŸŒˆ More efficient working with new or vanilla AVs

Perl v5.36 and v5.38 introduced streamlined, inlined versions of some functions:

  • av_store_simple
  • av_fetch_simple
  • av_push_simple

These are drop-in replacements โ€” but only for straightforward AVs that meet the following criteria:

  • are not magical
  • are not readonly
  • are "real" AVs (see next section)
  • have an av_top_index value > -2

AVs created using newAV(), av_make, newAV_alloc_x, and newAV_alloc_xz are all compatible at the time of creation. It's only once they get declared readonly or unreal, have magic attached, or are otherwise configured unusually that they stop being compatible. So they can lose their eligibility. It's giving situationship. ๐Ÿ˜ญ

Note that some interpreter functions may attach magic to an AV as part of normal operations. So unless you're sure of the lifecycle of an AV, it's safest to only use these new functions close to the point of AV creation. Fresh AV, fresh functions. ๐Ÿงš

๐Ÿ’œ Real AVs - and those that are not

The standard or typical AV is sometimes referred to as being a "real" AV โ€” a state you can check for with the AvREAL macro. What this state basically signifies is that:

  • Every accessible element in the array is either initialized but empty, or contains a pointer to a live SV.
  • When a SV* is assigned to an array element, the reference count on the SV is incremented. Conversely, when the element is unset, or assigned a different SV*, the reference count of the expelled SV is decremented. Balanced. Accounted for. Mature. ๐Ÿ‘‘

"Fake" AVs are intended for specific, limited use cases only. Use outside of core perl is strongly discouraged. Like, please don't. ๐Ÿ™ˆ

For example, the interpreter's argument stack is implemented as an AV, but it is not AvREAL. Its elements were historically not reference counted, which gives rise to the "stack-not-refcounted" class of bugs โ€” the kind that happen when SVs are freed during the execution of a statement but are still needed later in that same statement. Chaos. ๐Ÿ˜ต

Efforts are currently underway to move to a refcounted stack to fix this class of bugs: see the "Reference-counted argument stack" section in this document. ๐Ÿ‘€

A "fake" AV can be converted into a "real" AV by av_reify. Conversion must occur if the AV has the SVpav_REIFY flag set, which you can check for using the AvREIFY() macro. Trying to store a SV* into, or delete from, an AV usually involves an AvREIFY() check and conversion if needed. So it'll sort itself out most of the time, but now you know what's happening under the hood. โœจ

See comments in av.h and the functions in av.c if you really want to know more. That's the deep lore. ๐Ÿ“š


๐Ÿ“ Working with HVs ๐Ÿ“

To create an HV, you use this routine:

HV*  newHV();

Once the HV has been created, the following operations are possible on it:

SV**  hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
SV**  hv_fetch(HV*, const char* key, U32 klen, I32 lval);

Let's break these down, because there's a lot going on:

  • The klen parameter is the length of the key being passed in. (Note that you cannot pass 0 in as a value of klen to tell Perl to measure the length of the key. It will not do that. You have to tell it. ๐Ÿ’…)
  • The val argument contains the SV pointer to the scalar being stored.
  • hash is the precomputed hash value โ€” pass 0 if you want hv_store to calculate it for you. Let it do the math. ๐Ÿงฎ
  • The lval parameter indicates whether this fetch is actually part of a store operation, in which case a new undefined value will be added to the HV with the supplied key, and hv_fetch will return as if the value had already existed.
Remember: hv_store and hv_fetch return SV**'s and not just SV*. To access the scalar value, you must first dereference the return value. And โ€” very important โ€” check that the return value is not NULL before you dereference it. Always check. No cap. ๐Ÿšจ

The first of these two functions checks if a hash table entry exists, and the second deletes it:

bool  hv_exists(HV*, const char* key, U32 klen);
SV*   hv_delete(HV*, const char* key, U32 klen, I32 flags);

If flags does not include the G_DISCARD flag, then hv_delete will create and return a mortal copy of the deleted value. It's a little ghost of the thing you just deleted. ๐Ÿ‘ป

And more miscellaneous functions:

void   hv_clear(HV*);
void   hv_undef(HV*);

Like their AV counterparts, hv_clear deletes all the entries in the hash table but does not actually delete the hash table itself. The hv_undef deletes both the entries and the hash table itself. Two very different energy levels. ๐ŸŽ€

Perl keeps the actual data in a linked list of structures with a typedef of HE. These contain the actual key and value pointers (plus extra administrative overhead, the boring paperwork of it all). The key is a string pointer; the value is an SV*. However, once you have an HE*, to get the actual key and value, use the routines specified below.

Ok so we're deep in the hash-iteration era of this page and it's giving โœจ traversalโœจ. Buckle up bestie, these are the little functions that let you walk a whole hash table like it's a runway ๐Ÿ’…

I32    hv_iterinit(HV*);
        /* Prepares starting point to traverse hash table */
HE*    hv_iternext(HV*);
        /* Get the next entry, and return a pointer to a
           structure that has both the key and value */
char*  hv_iterkey(HE* entry, I32* retlen);
        /* Get the key from an HE structure and also return
           the length of the key string */
SV*    hv_iterval(HV*, HE* entry);
        /* Return an SV pointer to the value of the HE
           structure */
SV*    hv_iternextsv(HV*, char** key, I32* retlen);
        /* This convenience routine combines hv_iternext,
           hv_iterkey, and hv_iterval.  The key and retlen
           arguments are return values for the key and its
           length.  The value is returned in the SV* argument */

If you already know the name of a hash variable, you can snag a pointer to its HV like this:

HV*  get_hv("package::varname", 0);

And if that variable doesn't exist? You get NULL back. No variable, no pointer, periodt ๐Ÿซฅ

The actual hash algorithm lives inside the PERL_HASH macro:

PERL_HASH(hash, key, klen)

Important lore alert: the exact implementation of this macro depends on your architecture and your version of perl, and the return value can literally change per invocation. So that value is only valid for the duration of a single perl process. Don't be storing it, bestie ๐Ÿ™ˆ

If you want the tea on using these hash access functions on tied hashes, go read "Understanding the Magic of Tied Hashes and Arrays".


๐ŸŒˆ Hash API Extensions ๐ŸŒˆ

Starting with version 5.004, these functions joined the party too:

HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);

bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);

SV*     hv_iterkeysv  (HE* entry);

Not me pointing out that these take SV* keys ๐Ÿ‘€ โ€” which makes writing extension code for hash structures so much easier. They also let you pass SV* keys straight into tie functions without being forced to stringify them first (unlike the previous set of functions, rip to those).

They also return and accept whole hash entries (HE*), which is more efficient (because the hash number for a particular string doesn't have to be recomputed every single time โ€” slay). Detailed descriptions? perlapi has you.

The following macros must always be used to access the contents of hash entries. Note that the arguments to these macros must be simple variables, since they may get evaluated more than once (sneaky, ik). See perlapi for the full deets.

HePV(HE* he, STRLEN len)
HeVAL(HE* he)
HeHASH(HE* he)
HeSVKEY(HE* he)
HeSVKEY_force(HE* he)
HeSVKEY_set(HE* he, SV* sv)

These two lower-level macros are defined too, but they must only be used when you're dealing with keys that aren't SV*s:

HeKEY(HE* he)
HeKLEN(HE* he)

Also, heads up: both hv_store and hv_store_ent do not increment the reference count of the stored val โ€” that's on you, the caller. And if these functions return a NULL value, you'll usually have to decrement the reference count of val yourself to avoid a memory leak. Memory leaks are not cute. Do your refcounts. ๐Ÿ˜ญ


๐Ÿ’€ AVs, HVs and undefined values ๐Ÿ’€

Sometimes you gotta store undefined values in AVs or HVs. Rare case? Sure. Tricky? absolutely. Because you're so used to reaching for &PL_sv_undef whenever you need an undefined SV.

Like, your intuition is screaming that this XS code:

AV *av = newAV();
av_store( av, 0, &PL_sv_undef );

is equivalent to this Perl code:

my @av;
$av[0] = undef;

But bestieโ€ฆ it's not. ๐Ÿ’€ In perl 5.18 and earlier, AVs use &PL_sv_undef as a marker for indicating that an array element has not yet been initialized. So exists $av[0] would be true for that Perl code, but false for the array generated by the XS code. And in perl 5.20, storing &PL_sv_undef will create a read-only element, because the scalar &PL_sv_undef itself is stored โ€” not a copy.

Similar problems can occur when storing &PL_sv_undef in HVs:

hv_store( hv, "key", 3, &PL_sv_undef, 0 );

This will indeed make the value undef, but the moment you try to modify the value of key, you'll get hit with:

Modification of non-creatable hash value attempted

And in perl 5.8.0, &PL_sv_undef was also used to mark placeholders in restricted hashes. This caused such hash entries not to appear when iterating over the hash, or when checking for the keys with the hv_exists function. Messy behavior, honestly ๐Ÿ™ˆ

You can run into similar problems when you store &PL_sv_yes or &PL_sv_no into AVs or HVs. Trying to modify such elements will give you:

Modification of a read-only value attempted

To make a long story short: you can use the special variables &PL_sv_undef, &PL_sv_yes and &PL_sv_no with AVs and HVs, but you have to make sure you know what you're doing. Periodt.

Generally, if you want to store an undefined value in an AV or HV, you should not use &PL_sv_undef, but rather create a new undefined value using the newSV function, for example:

av_store( av, 42, newSV(0) );
hv_store( hv, "foo", 3, newSV(0), 0 );

๐Ÿฆ‹ References ๐Ÿฆ‹

References are a special type of scalar that point to other data types (including other references, yes, it's references all the way down).

To create a reference, use either of these functions:

SV* newRV_inc((SV*) thing);
SV* newRV_noinc((SV*) thing);

The thing argument can be any of an SV*, AV*, or HV*. These two are identical except that newRV_inc increments the reference count of the thing, while newRV_noinc does not. And for historical reasons, newRV is a synonym for newRV_inc.

Once you have a reference, dereference it with this macro:

SvRV(SV*)

โ€ฆthen call the appropriate routines, casting the returned SV* to either an AV* or HV* if you need to.

Wanna know if an SV is a reference? Use this:

SvROK(SV*)

And to discover what type of value the reference refers to, use this macro and then check the return value:

SvTYPE(SvRV(SV*))

The most useful types you'll get back are:

SVt_PVAV    Array
SVt_PVHV    Hash
SVt_PVCV    Code
SVt_PVGV    Glob (possibly a file handle)

Any numerical value returned which is less than SVt_PVAV will be a scalar of some form. See "svtype" in perlapi for more details.


๐Ÿ‘‘ Blessed References and Class Objects ๐Ÿ‘‘

References are also what make object-oriented programming work. In perl's OO lexicon, an object is simply a reference that has been blessed into a package (or class). Once blessed, the programmer may now use the reference to access the various methods in the class. Main character energy, honestly.

A reference can be blessed into a package with this function:

SV* sv_bless(SV* sv, HV* stash);

The sv argument must be a reference value. The stash argument specifies which class the reference will belong to. See "Stashes and Globs" for info on converting class names into stashes.

/* Still under construction */

The following function upgrades rv to reference if not already one. Creates a new SV for rv to point to. If classname is non-null, the SV is blessed into the specified class. SV is returned.

SV* newSVrv(SV* rv, const char* classname);

The following three functions copy integer, unsigned integer or double into an SV whose reference is rv. SV is blessed if classname is non-null.

SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
SV* sv_setref_nv(SV* rv, const char* classname, NV iv);

The following function copies the pointer value (the address, not the string!) into an SV whose reference is rv. SV is blessed if classname is non-null.

SV* sv_setref_pv(SV* rv, const char* classname, void* pv);

The following function copies a string into an SV whose reference is rv. Set length to 0 to let Perl calculate the string length. SV is blessed if classname is non-null.

SV* sv_setref_pvn(SV* rv, const char* classname, char* pv,
                                                     STRLEN length);

The following function tests whether the SV is blessed into the specified class. It does not check inheritance relationships.

int  sv_isa(SV* sv, const char* name);

The following function tests whether the SV is a reference to a blessed object.

int  sv_isobject(SV* sv);

The following function tests whether the SV is derived from the specified class. SV can be either a reference to a blessed object or a string containing a class name. This is the function implementing the UNIVERSAL::isa functionality.

bool sv_derived_from(SV* sv, const char* name);

To check if you've got an object derived from a specific class you have to write:

if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }

โœจ Creating New Variables โœจ

To create a new Perl variable with an undef value which can be accessed from your Perl script, use the following routines, depending on the variable type:

SV*  get_sv("package::varname", GV_ADD);
AV*  get_av("package::varname", GV_ADD);
HV*  get_hv("package::varname", GV_ADD);

Notice the use of GV_ADD as the second parameter ๐Ÿ‘€ The new variable can now be set, using the routines appropriate to the data type.

There are additional macros whose values may be bitwise OR'ed with the GV_ADD argument to enable certain extra features. Those bits are:

  • GV_ADDMULTI โ€” marks the variable as multiply defined, thus preventing the:
Name <varname> used only once: possible typo

warning. (Typos found, typos forgiven ๐Ÿ’…)

  • GV_ADDWARN โ€” issues the warning:
Had to create <varname> unexpectedly

if the variable did not exist before the function was called.

If you do not specify a package name, the variable is created in the current package.


๐ŸŽ€ Reference Counts and Mortality ๐ŸŽ€

Perl uses a reference count-driven garbage collection mechanism. SVs, AVs, or HVs (xV for short in the following) start their life with a reference count of 1. If the reference count of an xV ever drops to 0, then it will be destroyed and its memory made available for reuse. At the most basic internal level, reference counts can be manipulated with these macros:

int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);

(There are also suffixed versions of the increment and decrement macros, for situations where the full generality of these basic macros can be exchanged for some performance. Trade-offs, bestie โœจ)

Okay so here's the thing bestie: the way you should actually think about references isn't the raw reference count โ€” it's ownership. โœจ Like, who owns this reference?? A reference to an xV can be owned by literally so many entities: another xV, the Perl interpreter itself, an XS data structure, a piece of running code, or a dynamic scope. And here's the tea ๐Ÿซ– โ€” an xV usually has no idea which entities own references to it. It only knows how many references exist. That number is the reference count. That's it. That's the whole vibe.

To keep reference counts correct, you have to keep track of what references your XS code is touching. Periodt. ๐Ÿ’… The programmer should always know where a reference came from, who owns it, and be aware of every creation, destruction, and transfer of ownership. And here's the lowkey cursed part: ownership isn't represented explicitly in the xV data structures at all โ€” only the reference count gets actually maintained by the code. Which means all your beautiful ownership understanding is not evident in the code. ๐Ÿ’€ For example, transferring ownership of a reference from one owner to another doesn't change the reference count at all, so it might be achieved with zero actual code. (The transferring code doesn't touch the referenced object, but it does need to make sure the former owner knows it no longer owns the reference, and the new owner knows it now does. Communication is key, bestie. ๐Ÿซถ)

An xV that's visible at the Perl level should not become unreferenced and thus be destroyed. Normally an object only becomes unreferenced when it's no longer visible โ€” often by the very same means that makes it invisible. Like, a Perl reference value (RV) owns a reference to its referent, so if the RV gets overwritten, that reference gets destroyed, and the no-longer-reachable referent may get destroyed as a result. Ripples. ๐ŸŒŠ

Many functions have some kind of reference manipulation baked into their whole purpose. Sometimes this is documented in terms of ownership of references, and sometimes (less helpfully, ngl ๐Ÿ˜ญ) it's documented in terms of changes to reference counts. For example, the newRV_inc() function is documented to create a new RV (with reference count 1) and increment the reference count of the referent that was supplied by the caller. But the best way to understand it is: it creates a new reference to the referent, owned by the created RV, and hands back to the caller ownership of the sole reference to the RV. Iconic. ๐Ÿ‘‘

The newRV_noinc() function instead does not increment the reference count of the referent, but the RV nevertheless ends up owning a reference to the referent. So it's implied that the caller of newRV_noinc() is relinquishing a reference to the referent โ€” which makes this conceptually a more complicated operation even though it does less to the data structures. The way that's so unfair honestly. ๐Ÿ™ˆ

For example, imagine you want to return a reference from an XSUB function. Inside the XSUB routine, you create an SV which initially has just a single reference, owned by the XSUB routine. That reference needs to be disposed of before the routine is complete, otherwise it will leak, preventing the SV from ever being destroyed. So to create an RV referencing the SV, it's most convenient to pass the SV to newRV_noinc(), which consumes that reference. Now the XSUB routine no longer owns a reference to the SV, but it does own a reference to the RV, which in turn owns a reference to the SV. The ownership of the reference to the RV is then transferred by the process of returning the RV from the XSUB. Slay, clean handoff. ๐ŸŽ€

There are some convenience functions available that can help with the destruction of xVs. These functions introduce the concept of "mortality". ๐Ÿฆ‹ Much documentation speaks of an xV itself being mortal, but that's misleading โ€” it's really a reference to an xV that's mortal, and there can be more than one mortal reference to a single xV. For a reference to be mortal means it's owned by the temps stack, one of perl's many internal stacks, which will destroy that reference "a short time later". Usually that "short time later" is the end of the current Perl statement. But it gets more complicated around dynamic scopes: there can be multiple sets of mortal references hanging around at the same time, with different death dates. ๐Ÿ˜ตโ€๐Ÿ’ซ Internally, the actual determinant for when mortal xV references are destroyed depends on two macros, SAVETMPS and FREETMPS. See perlcall and perlxs and "Temporaries Stack" below for more details on these macros.

Mortal references are mainly used for xVs that are placed on perl's main stack. The stack is problematic for reference tracking, because it contains a lot of xV references, but doesn't own those references: they are not counted. Currently, there are many bugs resulting from xVs being destroyed while referenced by the stack, because the stack's uncounted references aren't enough to keep the xVs alive. ๐Ÿ˜ฑ So when putting an (uncounted) reference on the stack, it is vitally important to ensure that there will be a counted reference to the same xV that will last at least as long as the uncounted reference. But it's also important that counted reference be cleaned up at an appropriate time, and not unduly prolong the xV's life. For there to be a mortal reference is often the best way to satisfy this requirement โ€” especially if the xV was created especially to be put on the stack and would otherwise be unreferenced.

To create a mortal reference, use the functions:

SV*  sv_newmortal()
SV*  sv_mortalcopy(SV*)
SV*  sv_2mortal(SV*)

sv_newmortal() creates an SV (with the undefined value) whose sole reference is mortal. sv_mortalcopy() creates an xV whose value is a copy of a supplied xV and whose sole reference is mortal. sv_2mortal() mortalises an existing xV reference: it transfers ownership of a reference from the caller to the temps stack. Because sv_newmortal gives the new SV no value, it must normally be given one via sv_setpv, sv_setiv, etc.:

SV *tmp = sv_newmortal();
sv_setiv(tmp, an_integer);

As that is multiple C statements it is quite common so see this idiom instead:

SV *tmp = sv_2mortal(newSViv(an_integer));

The mortal routines are not just for SVs; AVs and HVs can be made mortal by passing their address (type-casted to SV*) to the sv_2mortal or sv_mortalcopy routines.


โœจ Stashes and Globs โœจ

A stash is a hash that contains all variables that are defined within a package. ๐ŸŽ Each key of the stash is a symbol name (shared by all the different types of objects that have the same name), and each value in the hash table is a GV (Glob Value). This GV in turn contains references to the various objects of that name, including (but not limited to) the following:

Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine

There is a single stash called PL_defstash that holds the items that exist in the main package. To get at the items in other packages, append the string :: to the package name. The items in the Foo package are in the stash Foo:: in PL_defstash. The items in the Bar::Baz package are in the stash Baz:: in Bar::'s stash. It's giving nesting dolls. ๐Ÿช†

To get the stash pointer for a particular package, use the function:

HV*  gv_stashpv(const char* name, I32 flags)
HV*  gv_stashsv(SV*, I32 flags)

The first function takes a literal string, the second uses the string stored in the SV. Remember that a stash is just a hash table, so you get back an HV*. The flags flag will create a new package if it is set to GV_ADD. ๐Ÿ†•

The name that gv_stash*v wants is the name of the package whose symbol table you want. The default package is called main. If you have multiply nested packages, pass their names to gv_stash*v, separated by :: as in the Perl language itself.

Alternately, if you have an SV that is a blessed reference, you can find out the stash pointer by using:

HV*  SvSTASH(SvRV(SV*));

then use the following to get the package name itself:

char*  HvNAME(HV* stash);

If you need to bless or re-bless an object you can use the following function:

SV*  sv_bless(SV*, HV* stash)

where the first argument, an SV*, must be a reference, and the second argument is a stash. The returned SV* can now be used in the same way as any other SV. โœจ

For more information on references and blessings, consult perlref.


๐Ÿซถ I/O Handles ๐Ÿซถ

Like AVs and HVs, IO objects are another type of non-scalar SV which may contain input and output PerlIO objects or a DIR * from opendir().

You can create a new IO object:

IO*  newIO();

Unlike other SVs, a new IO object is automatically blessed into the IO::File class. Fancy. ๐Ÿ‘‘

The IO object contains an input and output PerlIO handle:

PerlIO *IoIFP(IO *io);
PerlIO *IoOFP(IO *io);

Typically if the IO object has been opened on a file, the input handle is always present, but the output handle is only present if the file is open for output. For a file, if both are present they will be the same PerlIO object.

Distinct input and output PerlIO objects are created for sockets and character devices.

The IO object also contains other data associated with Perl I/O handles:

IV IoLINES(io);                /* $. */
IV IoPAGE(io);                 /* $% */
IV IoPAGE_LEN(io);             /* $= */
IV IoLINES_LEFT(io);           /* $- */
char *IoTOP_NAME(io);          /* $^ */
GV *IoTOP_GV(io);              /* $^ */
char *IoFMT_NAME(io);          /* $~ */
GV *IoFMT_GV(io);              /* $~ */
char *IoBOTTOM_NAME(io);
GV *IoBOTTOM_GV(io);
char IoTYPE(io);
U8 IoFLAGS(io);

Most of these are involved with formats. ๐ŸŽ€

IoFLAGs() may contain a combination of flags, the most interesting of which are IOf_FLUSH ($|) for autoflush and IOf_UNTAINT, settable with IO::Handle's untaint() method.

The IO object may also contain a directory handle:

DIR *IoDIRP(io);

suitable for use with PerlDir_read() etc.

All of these accessors macros are lvalues, there are no distinct _set() macros to modify the members of the IO object. No setters, only vibes. ๐Ÿ’…


๐ŸŒˆ Double-Typed SVs ๐ŸŒˆ

Scalar variables normally contain only one type of value: an integer, double, pointer, or reference. Perl will automatically convert the actual scalar data from the stored type into the requested type.

Some scalar variables contain more than one type of scalar data. For example, the variable $! contains either the numeric value of errno or its string equivalent from either strerror or sys_errlist[]. Two-for-one special, we love to see it. ๐Ÿ“

To force multiple data values into an SV, you must do two things: use the sv_set*v routines to add the additional scalar type, then set a flag so that Perl will believe it contains more than one type of data. The four macros to set the flags are:

  • SvIOK_on
  • SvNOK_on
  • SvPOK_on
  • SvROK_on

Which one of these bad boys you reach for depends entirely on which sv_set*v routine you called first, bestie. That's the whole tea. Every single sv_set*v routine flips on the bit for the one type of data it's setting and flips off all the others. It's giving one (1) type at a time, no sharing. ๐Ÿ’…

So like, say you wanna make a brand new Perl variable called dberror that holds both the numeric error value and the descriptive string version of it? You'd do this:

    extern int  dberror;
    extern char *dberror_list;

    SV* sv = get_sv("dberror", GV_ADD);
    sv_setiv(sv, (IV) dberror);
    sv_setpv(sv, dberror_list[dberror]);
    SvIOK_on(sv);

And here's the plot twist: if you'd called sv_setiv and sv_setpv in the opposite order, then you'd have to call SvPOK_on instead of SvIOK_on. Order matters, periodt. โœจ

๐Ÿ”ฎ Magic Variables ๐Ÿ”ฎ

[This section still under construction. Ignore everything here. Post no bills. Everything not permitted is forbidden.]

Okay so literally any SV can be โœจmagicalโœจ โ€” meaning it has special features that a regular, boring, no-magic SV just doesn't have. These features live in the SV structure in a linked list of struct magic's, typedef'ed to MAGIC. Obsessed honestly.

    struct magic {
        MAGIC*      mg_moremagic;
        MGVTBL*     mg_virtual;
        U16         mg_private;
        char        mg_type;
        U8          mg_flags;
        I32         mg_len;
        SV*         mg_obj;
        char*       mg_ptr;
    };
Heads up bestie: this is current as of patchlevel 0, and it could change at any time. So likeโ€ฆ don't get too attached. ๐Ÿ˜ญ

๐Ÿช„ Assigning Magic ๐Ÿช„

Perl adds magic to an SV using the sv_magic function:

  void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);

The sv argument is a pointer to the SV that's about to acquire a brand new magical feature. Main character transformation arc fr. ๐Ÿฆ‹

If sv isn't already magical, Perl uses the SvUPGRADE macro to convert sv to type SVt_PVMG. Then Perl keeps going by adding the new magic to the beginning of the linked list of magical features. And any prior entry of the same type of magic? Deleted. Gone. ๐Ÿ’€ That said, this can be overridden, and multiple instances of the same type of magic can be associated with an SV, so don't come for me.

The name and namlen arguments are used to associate a string with the magic โ€” typically the name of a variable. namlen gets stored in the mg_len field, and if name is non-null then either a savepvn copy of name or name itself gets stored in the mg_ptr field, depending on whether namlen is greater than zero or equal to zero respectively. As a special case, if (name && namlen == HEf_SVKEY) then name is assumed to contain an SV* and is stored as-is with its REFCNT incremented.

The sv_magic function uses how to figure out which (if any) predefined "Magic Virtual Table" should get assigned to the mg_virtual field. (Peep the "Magic Virtual Tables" section below for that lore.) The how argument also gets stored in the mg_type field. The value of how should be chosen from the set of macros PERL_MAGIC_foo found in perl.h. Quick history lesson: before these macros existed, Perl internals used to straight up use character literals, so you might occasionally stumble across old code or documentation referring to 'U' magic rather than PERL_MAGIC_uvar, for example. Vintage. ๐ŸŽ€

The obj argument gets stored in the mg_obj field of the MAGIC structure. If it's not the same as the sv argument, the reference count of the obj object is incremented. If it is the same, or if the how argument is PERL_MAGIC_arylen, PERL_MAGIC_regdatum, PERL_MAGIC_regdata, or if it's a NULL pointer, then obj is merely stored โ€” no reference count incrementing happening. ๐Ÿ™…

See also sv_magicext in perlapi for a more flexible way to add magic to an SV.

There's also a function to add magic to an HV:

    void hv_magic(HV *hv, GV *gv, int how);

This just calls sv_magic and coerces the gv argument into an SV. Simple as that. ๐Ÿ’

To remove the magic from an SV, call the function sv_unmagic:

    int sv_unmagic(SV *sv, int type);

The type argument should equal the how value from back when the SV was initially made magical. Keeping receipts, iykyk.

But wait โ€” plot twist โ€” note that sv_unmagic removes all magic of a certain type from the SV. If you wanna remove only certain magic of a type based on the magic virtual table, use sv_unmagicext instead:

    int sv_unmagicext(SV *sv, int type, MGVTBL *vtbl);

๐Ÿงš Magic Virtual Tables ๐Ÿงš

The mg_virtual field in the MAGIC structure is a pointer to an MGVTBL, which is a structure of function pointers and stands for "Magic Virtual Table" โ€” it handles the various operations that might get applied to that variable.

The MGVTBL has five (or sometimes eight) pointers to the following routine types:

    int  (*svt_get)  (pTHX_ SV* sv, MAGIC* mg);
    int  (*svt_set)  (pTHX_ SV* sv, MAGIC* mg);
    U32  (*svt_len)  (pTHX_ SV* sv, MAGIC* mg);
    int  (*svt_clear)(pTHX_ SV* sv, MAGIC* mg);
    int  (*svt_free) (pTHX_ SV* sv, MAGIC* mg);

    int  (*svt_copy) (pTHX_ SV *sv, MAGIC* mg, SV *nsv,
                                          const char *name, I32 namlen);
    int  (*svt_dup)  (pTHX_ MAGIC *mg, CLONE_PARAMS *param);
    int  (*svt_local)(pTHX_ SV *nsv, MAGIC *mg);

This MGVTBL structure gets set at compile-time in perl.h, and there are currently 32 types. These different structures contain pointers to various routines that perform extra actions depending on which function is being called. Here's the rundown:

  • svt_get โ€” Do something before the value of the SV is retrieved.
  • svt_set โ€” Do something after the SV is assigned a value.
  • svt_len โ€” Report on the SV's length.
  • svt_clear โ€” Clear something the SV represents.
  • svt_free โ€” Free any extra storage associated with the SV.
  • svt_copy โ€” copy tied variable magic to a tied element
  • svt_dup โ€” duplicate a magic structure during thread cloning
  • svt_local โ€” copy magic to local value during 'local'

For instance, the MGVTBL structure called vtbl_sv (which corresponds to an mg_type of PERL_MAGIC_sv) contains:

    { magic_get, magic_set, magic_len, 0, 0 }

So when an SV is determined to be magical and of type PERL_MAGIC_sv, and a get operation is being performed, the routine magic_get gets called. All the various routines for the various magical types begin with magic_. ๐Ÿ‘‘

NOTE: the magic routines are not considered part of the Perl API, and may not be exported by the Perl library. So likeโ€ฆ don't build your whole personality on them, bestie. ๐Ÿ™ˆ

The last three slots are a recent addition, and for source code compatibility they're only checked for if one of the three flags MGf_COPY, MGf_DUP, or MGf_LOCAL is set in mg_flags. This means most code can keep on declaring a vtable as a 5-element value. These three are currently used exclusively by the threading code, and are highly subject to change. So, y'know. Fragile. Handle with care. ๐ŸŒธ

The current kinds of Magic Virtual Tables are:

๐ŸŽ€ the magic table, but make it a glow-up ๐ŸŽ€

okay bestie so here's the whole vibe โ€” every magic type has an old-style char, a macro, an MGVTBL, and a job. four columns, zero skips:

  • \0 โ€” PERL_MAGIC_sv โ€” vtbl_sv โ€” Special scalar variable
  • # โ€” PERL_MAGIC_arylen โ€” vtbl_arylen โ€” Array length ($#ary)
  • % โ€” PERL_MAGIC_rhash โ€” (none) โ€” Extra data for restricted hashes
  • * โ€” PERL_MAGIC_debugvar โ€” vtbl_debugvar โ€” $DB::single, signal, trace vars
  • . โ€” PERL_MAGIC_pos โ€” vtbl_pos โ€” pos() lvalue
  • : โ€” PERL_MAGIC_symtab โ€” (none) โ€” Extra data for symbol tables
  • < โ€” PERL_MAGIC_backref โ€” vtbl_backref โ€” For weak ref data
  • @ โ€” PERL_MAGIC_arylen_p โ€” (none) โ€” To move arylen out of XPVAV
  • B โ€” PERL_MAGIC_bm โ€” vtbl_regexp โ€” Boyer-Moore (fast string search)
  • c โ€” PERL_MAGIC_overload_table โ€” vtbl_ovrld โ€” Holds overload table (AMT) on stash
  • D โ€” PERL_MAGIC_regdata โ€” vtbl_regdata โ€” Regex match position data (@+ and @- vars)
  • d โ€” PERL_MAGIC_regdatum โ€” vtbl_regdatum โ€” Regex match position data element
  • E โ€” PERL_MAGIC_env โ€” vtbl_env โ€” %ENV hash
  • e โ€” PERL_MAGIC_envelem โ€” vtbl_envelem โ€” %ENV hash element
  • f โ€” PERL_MAGIC_fm โ€” vtbl_regexp โ€” Formline ('compiled' format)
  • g โ€” PERL_MAGIC_regex_global โ€” vtbl_mglob โ€” m//g target
  • H โ€” PERL_MAGIC_hints โ€” vtbl_hints โ€” %^H hash
  • h โ€” PERL_MAGIC_hintselem โ€” vtbl_hintselem โ€” %^H hash element
  • I โ€” PERL_MAGIC_isa โ€” vtbl_isa โ€” @ISA array
  • i โ€” PERL_MAGIC_isaelem โ€” vtbl_isaelem โ€” @ISA array element
  • k โ€” PERL_MAGIC_nkeys โ€” vtbl_nkeys โ€” scalar(keys()) lvalue
  • L โ€” PERL_MAGIC_dbfile โ€” (none) โ€” Debugger %_<filename
  • l โ€” PERL_MAGIC_dbline โ€” vtbl_dbline โ€” Debugger %_<filename element
  • N โ€” PERL_MAGIC_shared โ€” (none) โ€” Shared between threads
  • n โ€” PERL_MAGIC_shared_scalar โ€” (none) โ€” Shared between threads
  • o โ€” PERL_MAGIC_collxfrm โ€” vtbl_collxfrm โ€” Locale transformation
  • P โ€” PERL_MAGIC_tied โ€” vtbl_pack โ€” Tied array or hash
  • p โ€” PERL_MAGIC_tiedelem โ€” vtbl_packelem โ€” Tied array or hash element
  • q โ€” PERL_MAGIC_tiedscalar โ€” vtbl_packelem โ€” Tied scalar or handle
  • r โ€” PERL_MAGIC_qr โ€” vtbl_regexp โ€” Precompiled qr// regex
  • S โ€” PERL_MAGIC_sig โ€” vtbl_sig โ€” %SIG hash
  • s โ€” PERL_MAGIC_sigelem โ€” vtbl_sigelem โ€” %SIG hash element
  • t โ€” PERL_MAGIC_taint โ€” vtbl_taint โ€” Taintedness
  • U โ€” PERL_MAGIC_uvar โ€” vtbl_uvar โ€” Available for use by extensions
  • u โ€” PERL_MAGIC_uvar_elem โ€” (none) โ€” Reserved for use by extensions
  • V โ€” PERL_MAGIC_vstring โ€” (none) โ€” SV was vstring literal
  • v โ€” PERL_MAGIC_vec โ€” vtbl_vec โ€” vec() lvalue
  • w โ€” PERL_MAGIC_utf8 โ€” vtbl_utf8 โ€” Cached UTF-8 information
  • X โ€” PERL_MAGIC_destruct โ€” vtbl_destruct โ€” destruct callback
  • x โ€” PERL_MAGIC_substr โ€” vtbl_substr โ€” substr() lvalue
  • Y โ€” PERL_MAGIC_nonelem โ€” vtbl_nonelem โ€” Array element that does not exist
  • y โ€” PERL_MAGIC_defelem โ€” vtbl_defelem โ€” Shadow "foreach" iterator variable / smart parameter vivification
  • Z โ€” PERL_MAGIC_hook โ€” vtbl_hook โ€” %{^HOOK} hash
  • z โ€” PERL_MAGIC_hookelem โ€” vtbl_hookelem โ€” %{^HOOK} hash element
  • \ โ€” PERL_MAGIC_lvref โ€” vtbl_lvref โ€” Lvalue reference constructor
  • ] โ€” PERL_MAGIC_checkcall โ€” vtbl_checkcall โ€” Inlining/mutation of call to this CV
  • ^ โ€” PERL_MAGIC_extvalue โ€” (none) โ€” Value magic available for use by extensions
  • ~ โ€” PERL_MAGIC_ext โ€” (none) โ€” Variable magic available for use by extensions

so when an uppercase letter and its lowercase twin both show up in that table, the uppercase one is typically the composite-type rep (a list or a hash, iconic behavior) and the lowercase one reps an element of that composite. some internals code literally relies on this case relationship. BUT โ€” and this is the plot twist โ€” 'v' and 'V' (vec and v-string) are in no way related. not sisters, not cousins, not even mutuals. ๐Ÿ’€

the PERL_MAGIC_ext, PERL_MAGIC_extvalue and PERL_MAGIC_uvar magic types are defined specifically for extensions to use, and perl itself will never touch them. extensions can use PERL_MAGIC_ext or PERL_MAGIC_extvalue magic to 'attach' private info to variables (typically objects). this is especially useful because normal perl code literally has no way to corrupt that private info (unlike, say, stuffing extra elements into a hash object ๐Ÿ™ˆ). PERL_MAGIC_extvalue is value magic (unlike PERL_MAGIC_ext and PERL_MAGIC_uvar), meaning that on localization the new value will not be magical.

similarly, PERL_MAGIC_uvar magic can be used a lot like tie() to call a C function any time a scalar's value is used or changed. the MAGIC's mg_ptr field points to a ufuncs structure:

struct ufuncs {
    I32 (*uf_val)(pTHX_ IV, SV*);
    I32 (*uf_set)(pTHX_ IV, SV*);
    IV uf_index;
};

when the SV is read from or written to, the uf_val or uf_set function gets called with uf_index as the first arg and a pointer to the SV as the second. here's a little baby example of how to add PERL_MAGIC_uvar magic โ€” and note that the ufuncs structure is copied by sv_magic, so you can safely allocate it on the stack, no stress:

void
Umagic(sv)
    SV *sv;
PREINIT:
    struct ufuncs uf;
CODE:
    uf.uf_val   = &my_get_fn;
    uf.uf_set   = &my_set_fn;
    uf.uf_index = 0;
    sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));

attaching PERL_MAGIC_uvar to arrays is permissible but has no effect. (it's giving decorative. ๐ŸŽ€)

for hashes there's a specialized hook that gives you control over hash keys (but not values). this hook calls PERL_MAGIC_uvar 'get' magic if the "set" function in the ufuncs structure is NULL. the hook activates whenever the hash is accessed with a key specified as an SV through the functions hv_store_ent, hv_fetch_ent, hv_delete_ent, and hv_exists_ent. accessing the key as a string through the functions without the ..._ent suffix circumvents the hook. for a detailed description see "GUTS" in Hash::Util::FieldHash.

heads up bestie: because multiple extensions may be using PERL_MAGIC_ext or PERL_MAGIC_uvar magic, extensions really really need to take extra care to avoid conflict. typically only using the magic on objects blessed into the same class as the extension is sufficient. for PERL_MAGIC_ext magic, it's usually a good idea to define an MGVTBL, even if all its fields will be 0, so that individual MAGIC pointers can be identified as a particular kind of magic using their magic virtual table. mg_findext provides an easy way to do that:
STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };

MAGIC *mg;
if ((mg = mg_findext(sv, PERL_MAGIC_ext, &my_vtbl))) {
    /* this is really ours, not another module's PERL_MAGIC_ext */
    my_priv_data_t *priv = (my_priv_data_t *)mg->mg_ptr;
    ...
}

also also also โ€” the sv_set*() and sv_cat*() functions described earlier do not invoke 'set' magic on their targets. you gotta do that yourself, either by calling the SvSETMAGIC() macro after calling these functions, or by using one of the sv_set*_mg() or sv_cat*_mg() functions. same energy the other way: generic C code must call the SvGETMAGIC() macro to invoke any 'get' magic if they use an SV obtained from external sources in functions that don't handle magic. perlapi has the full description of these functions. for example, calls to the sv_cat*() functions typically need to be followed by SvSETMAGIC(), but they don't need a prior SvGETMAGIC() since their implementation handles 'get' magic. โœจ


โœจ Finding Magic โœจ

MAGIC *mg_find(SV *sv, int type); /* Finds the magic pointer of that
                                   * type */

this routine returns a pointer to a MAGIC structure stored in the SV. if the SV doesn't have that magical feature, NULL comes back. if the SV has multiple instances of that magical feature, the first one gets returned. mg_findext can be used to find a MAGIC structure of an SV based on both its magic type and its magic virtual table:

MAGIC *mg_findext(SV *sv, int type, MGVTBL *vtbl);
also, real talk: if the SV passed to mg_find or mg_findext is not of type SVt_PVMG, Perl may core dump. ๐Ÿ’€
int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);

this routine checks to see what types of magic sv has. if the mg_type field is an uppercase letter, then the mg_obj is copied to nsv, but the mg_type field is changed to be the lowercase letter. (the case-swap pipeline, fr fr.)


๐Ÿฆ‹ Understanding the Magic of Tied Hashes and Arrays ๐Ÿฆ‹

tied hashes and arrays are magical beasts of the PERL_MAGIC_tied magic type. no cap.

WARNING: as of the 5.004 release, proper usage of the array and hash access functions requires understanding a few caveats. some of these caveats are actually considered bugs in the API, to be fixed in later releases, and are bracketed with [MAYCHANGE] below. if you find yourself actually applying such information in this section, be aware that the behavior may change in the future, umm, without warning. ๐Ÿ˜ญ

the perl tie function associates a variable with an object that implements the various GET, SET, etc methods. to perform the equivalent of the perl tie function from an XSUB, you must mimic this behaviour. the code below carries out the necessary steps โ€” firstly it creates a new hash, and then creates a second hash which it blesses into the class which will implement the tie methods. lastly it ties the two hashes together, and returns a reference to the new tied hash. note that the code below does NOT call the TIEHASH method in the MyTie class โ€” see "Calling Perl Routines from within C Programs" for details on how to do this. ๐Ÿซถ

SV*
mytie()
PREINIT:
    HV *hash;
    HV *stash;
    SV *tie;
CODE:
    hash = newHV();
    tie = newRV_noinc((SV*)newHV());
    stash = gv_stashpv("MyTie", GV_ADD);
    sv_bless(tie, stash);
    hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
    SvREFCNT_dec(tie); /* hv_magic() increases tie ref count */
    RETVAL = newRV_noinc(hash);
OUTPUT:
    RETVAL

okay bestie, this next bit is lowkey unhinged but stay with me ๐Ÿ’…

The av_store function, when you hand it a tied array, literally does not store anything โ€” it just copies the magic of the array onto the value that was supposed to be "stored", using mg_copy. It may also return NULL, which is its little way of saying "nah, this value never actually needed to go into the array anyway". [MAYCHANGE] After a call to av_store on a tied array, the caller will usually need to call mg_set(val) to actually invoke the perl level STORE method on the TIEARRAY object. And if av_store did return NULL, a call to SvREFCNT_dec(val) will also usually be necessary to avoid a memory leak ๐Ÿซ  [/MAYCHANGE]

And the previous paragraph applies verbatim to tied hash access using the hv_store and hv_store_ent functions as well. Same energy, different data structure.

av_fetch and the matching hash functions hv_fetch and hv_fetch_ent actually return an undefined mortal value whose magic has been initialized using mg_copy. Note that the value you get back does not need to be deallocated, because it's already mortal โ€” it's on the clock, not your problem ๐ŸŒธ. [MAYCHANGE] But you will need to call mg_get() on the returned value in order to actually invoke the perl level FETCH method on the underlying TIE object. Similarly, you may also call mg_set() on the return value after possibly assigning a suitable value to it using sv_setsv, which will invoke the STORE method on the TIE object. [/MAYCHANGE]

[MAYCHANGE] In other words: the array and hash fetch/store functions don't really fetch and store actual values when you're dealing with tied arrays and hashes. They merely call mg_copy to attach magic to the values that were meant to be "stored" or "fetched". Later calls to mg_get and mg_set are the ones that actually do the job of invoking the TIE methods on the underlying objects. So the magic mechanism currently implements a kind of lazy access to arrays and hashes. Very "I'll do it later, bestie" of it.

Currently (as of perl version 5.004), use of the hash and array access functions requires the user to be aware of whether they are operating on "normal" hashes and arrays, or on their tied variants. The API may be changed to provide more transparent access to both tied and normal data types in future versions. [/MAYCHANGE]

You would do well to understand that the TIEARRAY and TIEHASH interfaces are mere sugar to invoke some perl method calls while using the uniform hash and array syntax. And like all sugar, it costs you: this sugar imposes some overhead โ€” typically about two to four extra opcodes per FETCH/STORE operation, on top of the creation of all the mortal variables required to invoke the methods. This overhead will be comparatively small if the TIE methods are themselves substantial, but if they're only a few statements long, the overhead will not be insignificant. No cap.


โœจ Localizing changes โœจ

Perl has a very handy construction

{
  local $var = 2;
  ...
}

This construction is approximately equivalent to

{
  my $oldvar = $var;
  $var = 2;
  ...
  $var = $oldvar;
}

The biggest difference is that the first construction would reinstate the initial value of $var, irrespective of how control exits the block: goto, return, die/eval, etc. It is a little bit more efficient as well. slay.

There is a way to achieve a similar task from C via the Perl API: create a pseudo-block, and arrange for some changes to be automatically undone at the end of it โ€” either explicit, or via a non-local exit (via die()). A block-like construct is created by a pair of ENTER/LEAVE macros (see "Returning a Scalar" in perlcall). Such a construct may be created specially for some important localized task, or an existing one may be used (like the boundaries of an enclosing Perl subroutine/block, or an existing pair for freeing TMPs). (In the second case the overhead of additional localization must be almost negligible.) Note that any XSUB is automatically enclosed in an ENTER/LEAVE pair. ๐Ÿฆ‹

Inside such a pseudo-block, the following service is available:

  • SAVEINT(int i) โ€” restore the value of integer variable i at the end of the enclosing pseudo-block.
  • SAVEIV(IV i) โ€” same vibe, IV flavour.
  • SAVEI32(I32 i) โ€” same vibe, I32 flavour.
  • SAVEI8(I8 i) โ€” same vibe, I8 flavour.
  • SAVEI16(I16 i) โ€” same vibe, I16 flavour.
  • SAVEBOOL(int i) โ€” same vibe, boolean flavour.
  • SAVESTRLEN(STRLEN i) โ€” same vibe, STRLEN flavour.

These macros arrange things to restore the value of integer variable i at the end of the enclosing pseudo-block.

  • SAVESPTR(s) โ€” restore the value of pointer s. s must be a pointer of a type which survives conversion to SV* and back.
  • SAVEPPTR(p) โ€” restore the value of pointer p. p should be able to survive conversion to char* and back.
  • SAVERCPV(char **ppv) โ€” this macro arranges to restore the value of a char * variable which was allocated with a call to rcpv_new() to its previous state when the current pseudo block is completed. The pointer stored in *ppv at the time of the call will be refcount incremented and stored on the save stack. Later, when the current pseudo-block is completed, the value stored in *ppv will be refcount decremented, and the previous value restored from the savestack โ€” which will also be refcount decremented.

This is the "RCPV" equivalent of SAVEGENERICSV().

  • SAVEGENERICSV(SV **psv) โ€” this macro arranges to restore the value of a SV * variable to its previous state when the current pseudo block is completed. The pointer stored in *psv at the time of the call will be refcount incremented and stored on the save stack. Later, when the current pseudo-block is completed, the value stored in *ppv will be refcount decremented, and the previous value restored from the savestack, which will also be refcount decremented. This is the C equivalent of local $sv. ๐Ÿ’–
  • SAVEFREESV(SV *sv) โ€” the refcount of sv will be decremented at the end of the pseudo-block. This is similar to sv_2mortal in that it is also a mechanism for doing a delayed SvREFCNT_dec. However, while sv_2mortal extends the lifetime of sv until the beginning of the next statement, SAVEFREESV extends it until the end of the enclosing scope. These lifetimes can be wildly different.

Also compare SAVEMORTALIZESV.

  • SAVEMORTALIZESV(SV *sv) โ€” just like SAVEFREESV, but mortalizes sv at the end of the current scope instead of decrementing its reference count. This usually has the effect of keeping sv alive until the statement that called the currently live scope has finished executing.
  • SAVEFREEOP(OP *op) โ€” the OP * is op_free()ed at the end of the pseudo-block.
  • SAVEFREEPV(p) โ€” the chunk of memory which is pointed to by p is Safefree()ed at the end of the current pseudo-block.
  • SAVEFREERCPV(char *pv) โ€” ensures that a char * which was created by a call to rcpv_new() is rcpv_free()ed at the end of the current pseudo-block.

This is the RCPV equivalent of SAVEFREESV().

  • SAVECLEARSV(SV *sv) โ€” clears a slot in the current scratchpad which corresponds to sv at the end of the pseudo-block.
  • SAVEDELETE(HV *hv, char *key, I32 length) โ€” the key key of hv is deleted at the end of the pseudo-block. The string pointed to by key is Safefree()ed. If one has a key in short-lived storage, the corresponding string may be reallocated like this:
SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
  • SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p) โ€” at the end of the pseudo-block the function f is called with the only argument p, which may be NULL.
  • SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p) โ€” at the end of the pseudo-block the function f is called with the implicit context argument (if any), and p, which may be NULL.
Note the end of the current pseudo-block may occur much later than the end of the current statement. You may wish to look at the MORTALSVFUNC_X() macro instead.
  • MORTALSVFUNC_X(SVFUNC_t f, SV *sv) โ€” at the end of the current statement the function f is called with the implicit context argument (if any), and sv, which may be NULL.

Be aware that the parameter argument to the destructor function differs from the related SAVEDESTRUCTOR_X() in that it MUST be either NULL or an SV*.

Note the end of the current statement may occur much before the end of the current pseudo-block. You may wish to look at the SAVEDESTRUCTOR_X() macro instead.
  • MORTALDESTRUCTOR_SV(SV *coderef, SV *args) โ€” at the end of the current statement the Perl function contained in coderef is called with the arguments provided (if any) in args. See the documentation for mortal_destructor_sv() for details on how the args parameter is handled.
Note the end of the current statement may occur much before the end of the current pseudo-block. If you wish to call a perl function at the end of the current pseudo block you should use the SAVEDESTRUCTOR_X() API instead, which will require you create a C wrapper to call the Perl function.
  • SAVESTACK_POS() โ€” the current offset on the Perl internal stack (cf. SP) is restored at the end of the pseudo-block.

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

Other macros above have functions implementing them, but it's probably best to just use the macro, and not those or the ones below. ๐Ÿ™ˆ

  • SV* save_scalar(GV *gv) โ€” equivalent to Perl code local $gv.
  • AV* save_ary(GV *gv)
  • HV* save_hash(GV *gv) โ€” similar to save_scalar, but localize @gv and %gv.
  • void save_item(SV *item) โ€” duplicates the current value of SV. On the exit from the current ENTER/LEAVE pseudo-block the value of SV will be restored using the stored value. It doesn't handle magic. Use save_scalar if magic is affected.
  • SV* save_svref(SV **sptr) โ€” similar to save_scalar, but will reinstate an SV *.
  • void save_aptr(AV **aptr)
  • void save_hptr(HV **hptr) โ€” similar to save_svref, but localize AV * and HV *.

The Alias module implements localization of the basic types within the caller's scope. People who are interested in how to localize things in the containing scope should take a look there too. ๐ŸŽ€

Subroutines ๐Ÿ’ซ

๐ŸŽ€ XSUBs and the Argument Stack ๐ŸŽ€

okay so bestie, the XSUB situation is genuinely so simple when you get it: it's just how Perl programs reach into C subroutines. An XSUB routine gets its own stack holding the args from the Perl program, plus a whole way to map Perl data structures over to their C equivalents. iconic behavior tbh.

You grab stack args with the ST(n) macro โ€” it hands you the *n*th stack argument. Heads up: argument 0 is the first argument passed in the Perl subroutine call. These args are SV*, and you can use them literally anywhere an SV* goes. periodt.

Most of the time you can handle output from the C routine with the RETVAL and OUTPUT directives, super chill. BUT โ€” and this is the plot twist โ€” sometimes the argument stack isn't already long enough to hold all the return values. Case in point: the POSIX tzname() call. It takes zero arguments but returns two: the local time zone's standard and summer time abbreviations. two-for-one, no cap.

To handle that, you use the PPCODE directive and extend the stack with this macro:

EXTEND(SP, num);

where SP is the macro that represents the local copy of the stack pointer, and num is the number of elements the stack should be extended by. got it? got it. ๐Ÿ’…

Now that there's room, you push values onto it with the PUSHs macro. And the pushed values will often need to be mortal (peep "Reference Counts and Mortality" for the tea):

PUSHs(sv_2mortal(newSViv(an_integer)))
PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
PUSHs(sv_2mortal(newSVnv(a_double)))
PUSHs(sv_2mortal(newSVpv("Some String",0)))
/* Although the last example is better written as the more
 * efficient: */
PUSHs(newSVpvs_flags("Some String", SVs_TEMP))

And then when the Perl program calls tzname, those two values get assigned like this:

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

There's also an alternate (and possibly simpler!) way to push values on the stack, using this macro:

XPUSHs(SV*)

This one adjusts the stack for you automatically if it needs to. So you do not need to call EXTEND to extend the stack. lowkey a lifesaver. ๐Ÿซถ

ngl, despite what earlier versions of this document suggested, the macros (X)PUSH[iunp] are not suited to XSUBs which return multiple results. For that, either stick to the (X)PUSHs macros shown above, or use the new m(X)PUSH[iunp] macros instead โ€” see "Putting a C value on Perl stack".

For more info, go consult perlxs and perlxstut. ๐Ÿ“š

โœจ Autoloading with XSUBs โœจ

If an AUTOLOAD routine is an XSUB, then โ€” same as with Perl subroutines โ€” Perl drops the fully-qualified name of the autoloaded subroutine into the $AUTOLOAD variable of the XSUB's package.

But wait, there's more: it also puts that same info into certain fields of the XSUB itself:

HV *stash           = CvSTASH(cv);
const char *subname = SvPVX(cv);
STRLEN name_length  = SvCUR(cv); /* in bytes */
U32 is_utf8         = SvUTF8(cv);

SvPVX(cv) contains just the sub name itself โ€” not including the package. And for an AUTOLOAD routine in UNIVERSAL or one of its superclasses, CvSTASH(cv) returns NULL during a method call on a nonexistent package. noted bestie. ๐Ÿ“

Note: Setting $AUTOLOAD stopped working in 5.6.1, which did not support XS AUTOLOAD subs at all. Perl 5.8.0 introduced the use of fields in the XSUB itself. Perl 5.16.0 restored the setting of $AUTOLOAD. If you need to support 5.8-5.14, use the XSUB's fields.

๐ŸŒธ Calling Perl Routines from within C Programs ๐ŸŒธ

There are four routines that can call a Perl subroutine from inside a C program. the whole squad:

I32  call_sv(SV*, I32);
I32  call_pv(const char*, I32);
I32  call_method(const char*, I32);
I32  call_argv(const char*, I32, char**);

The routine used most often is call_sv. Its SV* argument holds either the name of the Perl subroutine you wanna call, or a reference to the subroutine. The second argument is flags that control the context the subroutine is called in, whether or not it's being passed arguments, how errors get trapped, and how to treat return values. so many vibes in one int, honestly.

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

Fun history moment: these used to be called perl_call_sv, etc., before Perl v5.6.0 โ€” but those names are now deprecated. Macros of the same name are provided for compatibility, so don't come for them.

When you're using any of these routines (except call_argv), you the programmer must manipulate the Perl stack yourself. That involves these macros and functions:

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

For a detailed description of calling conventions from C to Perl, consult perlcall. ๐Ÿ’–

๐Ÿ‘‘ Putting a C value on Perl stack ๐Ÿ‘‘

A lot of opcodes (an opcode being an elementary operation in the internal perl stack machine) put an SV* on the stack. But as an optimization, that corresponding SV is (usually) not recreated every single time. The opcodes reuse specially assigned SVs โ€” targets โ€” which, as a corollary, are not constantly freed and created. recycling queen behavior. โ™ป๏ธ

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

The macro that puts this target on the stack is PUSHTARG, and it's used directly in some opcodes, plus indirectly in zillions of others that use it via (X)PUSH[iunp].

Because the target gets reused, you must be careful when pushing multiple values. This code right here will not do what you think it does:

XPUSHi(10);
XPUSHi(20);

This translates as "set TARG to 10, push a pointer to TARG onto the stack; set TARG to 20, push a pointer to TARG onto the stack". So at the end of the operation, the stack does not contain the values 10 and 20 โ€” it actually contains two pointers to TARG, which we have set to 20. plot twist ๐Ÿ’€

If you need to push multiple different values, then either use the (X)PUSHs macros, or use the new m(X)PUSH[iunp] macros โ€” neither of which makes use of TARG. The (X)PUSHs macros just push an SV* on the stack, which, as noted under "XSUBs and the Argument Stack", will often need to be mortal. The new m(X)PUSH[iunp] macros make that a lil easier by creating a new mortal for you (via (X)PUSHmortal), pushing that onto the stack (extending it if necessary in the case of the mXPUSH[iunp] macros), and then setting its value.

So instead of writing this to "fix" the example above:

XPUSHs(sv_2mortal(newSViv(10)))
XPUSHs(sv_2mortal(newSViv(20)))

you can simply write:

mXPUSHi(10)
mXPUSHi(20)

Obsessed. ๐Ÿคฉ

On a related note: if you do use (X)PUSH[iunp], then you're gonna need a dTARG in your variable declarations so that the *PUSH* macros can make use of the local variable TARG. See also dTARGET and dXSTARG.

Be careful with TARG: each non-recursive call to your OP, or XSUB for dXSTARG, will use the same SV for TARG for each call, so you can't assume the SV is pristine โ€” since the results from the previous call to your OP or XSUB may still be in TARG.

Other state, like a cached numeric version of a PV or the cached UTF-8 length, may also be set. You can dodge problems here by using the normal sv_set*() APIs instead of trying to optimize by directly manipulating the SV. fr fr, just use the API.

For OPs that implement the OA_TARGLEX optimization, TARG may be special in other ways โ€” there may be references to it, it might be blessed, it might be tied, or magical in other ways. ๐Ÿ‘ป

You must not use TARG to return a reference, since that reference will be live until the next time the OP or XSUB executes non-recursively, or until perl exits. that's a whole lingering commitment bestie, don't do it.

๐Ÿฆ‹ Scratchpads ๐Ÿฆ‹

The question that remains: when are the SVs that are targets for opcodes actually created? Answer: they're created when the current unit โ€” a subroutine, or a file (for opcodes for statements outside of subroutines) โ€” gets compiled. During that time a special anonymous Perl array is created, called a scratchpad for the current unit. cute name, very on-brand.

A scratchpad keeps SVs which are lexicals for the current unit and are targets for opcodes. A previous version of this document said you can deduce that an SV lives on a scratchpad by looking at its flags: lexicals have SVs_PADMY set, and targets have SVs_PADTMP set. But that has never been fully true. SVs_PADMY could be set on a variable that no longer resides in any pad. And while targets do have SVs_PADTMP set, it can also be set on variables that have never resided in a pad, but nonetheless act like targets. As of perl 5.21.5, the SVs_PADMY flag is no longer used and is defined as 0. SvPADMY() now returns true for anything without SVs_PADTMP.

The correspondence between OPs and targets is not 1-to-1. Different OPs in the compile tree of the unit can use the same target, if that wouldn't conflict with the expected life of the temporary. sharing is caring, when it's safe. โœจ

๐Ÿงš Scratchpads and recursion ๐Ÿงš

ngl it is not 100% true that a compiled unit contains a pointer to the scratchpad AV. Actually, it contains a pointer to an AV of (initially) one element, and this element is the scratchpad AV. So why do we need that extra level of indirection? great question bestie.

The answer is recursion, and maybe threads. Both of those can create several execution pointers going into the same subroutine. And for the subroutine-child to not write over the temporaries for the subroutine-parent (whose lifespan covers the call to the child), the parent and the child should have different scratchpads. (And the lexicals should be separate anyway! obviously!)

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

The targets on this scratchpad are undefs, but they're already marked with the correct flags.

๐Ÿ’พ MEMORY ALLOCATION ๐Ÿ’พ

โœจ Allocation โœจ

okay bestie, listen up: every single scrap of memory you're meant to use with the Perl API functions has to be handled with the macros in this section, no exceptions. They're the little translators that smooth over all the differences between whatever actual malloc implementation perl got built with. ๐Ÿซถ

DO NOT pass pointers between Newx, Renew, Safefree and their libc equivalents malloc, realloc, free. They are not from the same memory pool or allocator. You'll get either an instant or delayed SEGV, or โ€” even sneakier โ€” subtle memory leaks or subtle heap corruption. ๐Ÿ’€

These three macros are the ones you reach for to allocate memory for the first time:

Newx(pointer, number, type);
Newxc(pointer, number, type, cast);
Newxz(pointer, number, type);

The first argument pointer should be the name of a variable that will point to the newly allocated memory. โœจ

The second and third arguments number and type say how many of the specified type of data structure should be allocated. The argument type is passed to sizeof. The final argument to Newxc, cast, should be used if the pointer argument is different from the type argument. ๐ŸŽ€

And unlike the Newx and Newxc macros, the Newxz macro calls memzero to zero out all the newly allocated memory. squeaky clean, no leftovers. ๐Ÿงš

๐Ÿ” Reallocation ๐Ÿ”

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

These three macros are used to change a memory buffer size or to free a piece of memory you don't need anymore. The arguments to Renew and Renewc match those of New and Newc, except you don't need the magic cookie argument. periodt. ๐Ÿ’…

๐Ÿšš Moving ๐Ÿšš

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

These three macros move, copy, or zero out memory you already allocated. The source and dest arguments point to the source and destination starting points. Perl will move, copy, or zero out number instances of the size of the type data structure (using the sizeof function). ๐Ÿฆ‹


๐ŸŒŠ PerlIO ๐ŸŒŠ

The most recent development releases of Perl have been experimenting with removing Perl's dependency on the "normal" standard I/O suite and letting other stdio implementations be used instead. What that involves is creating a new abstraction layer that then calls whichever implementation of stdio Perl was compiled with. So all XSUBs should now use the functions in the PerlIO abstraction layer and not make any assumptions about what kind of stdio is being used. no cap. ๐Ÿซถ

For a complete description of the PerlIO abstraction, go consult perlapio. ๐Ÿ’œ


๐Ÿงฌ Compiled code ๐Ÿงฌ

๐ŸŒณ Code tree ๐ŸŒณ

Here's where we describe the internal form your code gets converted into by Perl. Start with a simple example:

$a = $b + $c;

This is converted to a tree similar to this one:

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

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

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

But with the actual compile tree for $a = $b + $c it's different: some nodes get optimized away. As a corollary, even though the actual tree contains more nodes than our simplified example, the execution order is the same as in our example. ๐Ÿคฏ

๐Ÿ” Examining the tree ๐Ÿ”

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

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

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

                   add
                 /     \
               null    null
                |       |
               gvsv    gvsv

The execution order is indicated by ===> marks, so it's 3 4 5 6 (node 6 is not included in the above listing), i.e., gvsv gvsv add whatever. โœจ

Each of these nodes represents an op, a fundamental operation inside the Perl core. The code which implements each operation can be found in the pp*.c files; the function which implements the op with type gvsv is pp_gvsv, and so on. As the tree above shows, different ops have different numbers of children: add is a binary operator, as one would expect, and so has two children. To accommodate the various different numbers of children, there are various types of op data structure, and they link together in different ways. ๐Ÿงฉ

The simplest type of op structure is OP: this has no children. Unary operators, UNOPs, have one child, and this is pointed to by the op_first field. Binary operators (BINOPs) have not only an op_first field but also an op_last field. The most complex type of op is a LISTOP, which has any number of children. In this case, the first child is pointed to by op_first and the last child by op_last. The children in between can be found by iteratively following the OpSIBLING pointer from the first child to the last (but see below). ๐Ÿ‘‘

There are also some other op types: a PMOP holds a regular expression, and has no children, and a LOOP may or may not have children. If the op_children field is non-zero, it behaves like a LISTOP. To complicate matters, if a UNOP is actually a null op after optimization (see "Compile pass 2: context propagation") it will still have children in accordance with its former type. ๐Ÿ˜ญ

Finally, there's a LOGOP, or logic op. Like a LISTOP, this has one or more children, but it doesn't have an op_last field: so you have to follow op_first and then the OpSIBLING chain itself to find the last child. Instead it has an op_other field, which is comparable to the op_next field described below, and represents an alternate execution path. Operators like and, or and ? are LOGOPs. Note that in general, op_other may not point to any of the direct children of the LOGOP. ๐ŸŒˆ

Starting in version 5.21.2, perls built with the experimental define -DPERL_OP_PARENT add an extra boolean flag for each op, op_moresib. When not set, this indicates that this is the last op in an OpSIBLING chain. This frees up the op_sibling field on the last sibling to point back to the parent op. Under this build, that field is also renamed op_sibparent to reflect its joint role. The macro OpSIBLING(o) wraps this special behaviour, and always returns NULL on the last sibling. With this build the op_parent(o) function can be used to find the parent of any op. So for forward compatibility, you should always use the OpSIBLING(o) macro rather than accessing op_sibling directly. bestie, write it down. ๐Ÿ“

Another way to examine the tree is to use a compiler back-end module, such as B::Concise. ๐Ÿ’–

โœ… Compile pass 1: check routines โœ…

The tree is created by the compiler while yacc code feeds it the constructions it recognizes. Since yacc works bottom-up, so does the first pass of perl compilation. ๐Ÿฆ‹

What makes this pass interesting for perl developers is that some optimization may be performed on this pass. This is optimization by so-called "check routines". The correspondence between node names and corresponding check routines is described in opcode.pl (do not forget to run make regen_headers if you modify this file). โš ๏ธ

A check routine is called when the node is fully constructed except for the execution-order thread. Since at this time there are no back-links to the currently constructed node, one can do most any operation to the top-level node, including freeing it and/or creating new nodes above/below it. ๐ŸŽ€

The check routine returns the node which should be inserted into the tree (if the top-level node was not modified, check routine returns its argument).

By convention, check routines have names ck_*. They are usually called from new*OP subroutines (or convert) (which in turn are called from perly.y). ๐Ÿ’…

๐ŸงŠ Compile pass 1a: constant folding ๐ŸงŠ

Immediately after the check routine is called the returned node is checked for being compile-time executable. If it is (the value is judged to be constant) it is immediately executed, and a constant node with the "return value" of the corresponding subtree is substituted instead. The subtree is deleted. poof, gone. โœจ

If constant folding was not performed, the execution-order thread is created. ๐ŸŒธ

๐ŸŒŠ Compile pass 2: context propagation ๐ŸŒŠ

When a context for a part of the compile tree is known, it is propagated down through the tree. At this time the context can have 5 values (instead of 2 for runtime context): void, boolean, scalar, list, and lvalue. In contrast with the pass 1 this pass is processed from top to bottom: a node's context determines the context for its children. โฌ‡๏ธ

Additional context-dependent optimizations are performed at this time. Since at this moment the compile tree contains back-references (via thread pointers), nodes cannot be free()d now. To allow optimized-away nodes at this stage, such nodes are null()ified instead of free()ing (i.e. their type is changed to OP_NULL). ๐Ÿ™ˆ

๐Ÿ‘€ Compile pass 3: peephole optimization ๐Ÿ‘€

After the compile tree for a subroutine (or for an eval or a file) is created, an additional pass over the code is performed. This pass is neither top-down nor bottom-up, but in the execution order (with additional complications for conditionals). Optimizations performed at this stage are subject to the same restrictions as in the pass 2. ๐Ÿ”ฅ

okay so peephole optimizations are done by calling the function that the global variable PL_peepp points to. By default, PL_peepp just calls the function that the global variable PL_rpeepp points to. By default, that one does some basic op fixups and optimisations along the execution-order op chain, and recursively calls PL_rpeepp for each side chain of ops (which come from conditionals). Extensions can provide additional optimisations or fixups, hooking into either the per-subroutine or recursive stage, like this:

           static peep_t prev_peepp;
           static void my_peep(pTHX_ OP *o)
           {
               /* custom per-subroutine optimisation goes here */
               prev_peepp(aTHX_ o);
               /* custom per-subroutine optimisation may also go here */
           }
           BOOT:
               prev_peepp = PL_peepp;
               PL_peepp = my_peep;

           static peep_t prev_rpeepp;
           static void my_rpeep(pTHX_ OP *first)
           {
               OP *o = first, *t = first;
               for(; o = o->op_next, t = t->op_next) {
                   /* custom per-op optimisation goes here */
                   o = o->op_next;
                   if (!o || o == t) break;
                   /* custom per-op optimisation goes AND here */
               }
               prev_rpeepp(aTHX_ orig_o);
           }
           BOOT:
               prev_rpeepp = PL_rpeepp;
               PL_rpeepp = my_rpeep;

That's the whole peephole hook situation, no cap ๐Ÿ’…


โœจ Pluggable runops โœจ

The compile tree is executed in a runops function. There are two runops functions, in run.c and in dump.c. Perl_runops_debug is used with DEBUGGING and Perl_runops_standard is used otherwise. For fine control over the execution of the compile tree it is possible to provide your own runops function.

It's probably best to copy one of the existing runops functions and change it to suit your needs. Then, in the BOOT section of your XS file, add the line:

         PL_runops = my_runops;

This function should be as efficient as possible to keep your programs running as fast as possible. periodt โœจ


๐ŸŽ€ Compile-time scope hooks ๐ŸŽ€

As of perl 5.14 it is possible to hook into the compile-time lexical scope mechanism using Perl_blockhook_register. This is used like this:

           STATIC void my_start_hook(pTHX_ int full);
           STATIC BHK my_hooks;

           BOOT:
               BhkENTRY_set(&my_hooks, bhk_start, my_start_hook);
               Perl_blockhook_register(aTHX_ &my_hooks);

This will arrange to have my_start_hook called at the start of compiling every lexical scope. The available hooks are:

  • void bhk_start(pTHX_ int full) โ€” this is called just after starting a new lexical scope. Note that Perl code like
             if ($x) { ... }

creates two scopes: the first starts at the ( and has full == 1, the second starts at the { and has full == 0. Both end at the }, so calls to start and pre/post_end will match. Anything pushed onto the save stack by this hook will be popped just before the scope ends (between the pre_ and post_end hooks, in fact).

  • void bhk_pre_end(pTHX_ OP **o) โ€” this is called at the end of a lexical scope, just before unwinding the stack. o is the root of the optree representing the scope; it is a double pointer so you can replace the OP if you need to.
  • void bhk_post_end(pTHX_ OP **o) โ€” this is called at the end of a lexical scope, just after unwinding the stack. o is as above. Note that it is possible for calls to pre_ and post_end to nest, if there is something on the save stack that calls string eval.
  • void bhk_eval(pTHX_ OP *const o) โ€” this is called just before starting to compile an eval STRING, do FILE, require or use, after the eval has been set up. o is the OP that requested the eval, and will normally be an OP_ENTEREVAL, OP_DOFILE or OP_REQUIRE.

Once you have your hook functions, you need a BHK structure to put them in. It's best to allocate it statically, since there is no way to free it once it's registered. The function pointers should be inserted into this structure using the BhkENTRY_set macro, which will also set flags indicating which entries are valid. If you do need to allocate your BHK dynamically for some reason, be sure to zero it before you start.

Once registered, there is no mechanism to switch these hooks off, so if that is necessary you will need to do this yourself. An entry in %^H is probably the best way, so the effect is lexically scoped; however it is also possible to use the BhkDISABLE and BhkENABLE macros to temporarily switch entries on and off. You should also be aware that generally speaking at least one scope will have opened before your extension is loaded, so you will see some pre/post_end pairs that didn't have a matching start.


๐Ÿ” Examining internal data structures with the "dump" functions ๐Ÿ”

To aid debugging, the source file dump.c contains a number of functions which produce formatted output of internal data structures.

The most commonly used of these functions is Perl_sv_dump; it's used for dumping SVs, AVs, HVs, and CVs. The Devel::Peek module calls sv_dump to produce debugging output from Perl-space, so users of that module should already be familiar with its format.

Perl_op_dump can be used to dump an OP structure or any of its derivatives, and produces output similar to perl -Dx; in fact, Perl_dump_eval will dump the main root of the code being evaluated, exactly like -Dx.

Other useful functions are Perl_dump_sub, which turns a GV into an op tree, Perl_dump_packsubs which calls Perl_dump_sub on all the subroutines in a package like so: (Thankfully, these are all xsubs, so there is no op tree)

           (gdb) print Perl_dump_packsubs(PL_defstash)

           SUB attributes::bootstrap = (xsub 0x811fedc 0)

           SUB UNIVERSAL::can = (xsub 0x811f50c 0)

           SUB UNIVERSAL::isa = (xsub 0x811f304 0)

           SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)

           SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)

and Perl_dump_all, which dumps all the subroutines in the stash and the op tree of the main root.


๐ŸŒˆ How multiple interpreters and concurrency are supported ๐ŸŒˆ

๐Ÿ’– Background and MULTIPLICITY ๐Ÿ’–

The Perl interpreter can be regarded as a closed box: it has an API for feeding it code or otherwise making it do things, but it also has functions for its own use. This smells a lot like an object, and there is a way for you to build Perl so that you can have multiple interpreters, with one interpreter represented either as a C structure, or inside a thread-specific structure. These structures contain all the context, the state of that interpreter.

The macro that controls the major Perl build flavor is MULTIPLICITY. The MULTIPLICITY build has a C structure that packages all the interpreter state, which is being passed to various perl functions as a "hidden" first argument. MULTIPLICITY makes multi-threaded perls possible (with the ithreads threading model, related to the macro USE_ITHREADS.)

PERL_IMPLICIT_CONTEXT is a legacy synonym for MULTIPLICITY.

To see whether you have non-const data you can use a BSD (or GNU) compatible nm:

         nm libperl.a | grep -v ' [TURtr] '

If this displays any D or d symbols (or possibly C or c), you have non-const data. The symbols the grep removed are as follows: Tt are text, or code, the Rr are read-only (const) data, and the U is <undefined>, external symbols referred to.

The test t/porting/libperl.t does this kind of symbol sanity checking on libperl.a.

All this obviously requires a way for the Perl internal functions to be either subroutines taking some kind of structure as the first argument, or subroutines taking nothing as the first argument. To enable these two very different ways of building the interpreter, the Perl source (as it does in so many other situations) makes heavy use of macros and subroutine naming conventions.

First problem: deciding which functions will be public API functions and which will be private. All functions whose names begin S_ are private (think "S" for "secret" or "static"). All other functions begin with Perl_, but just because a function begins with Perl_ does not mean it is part of the API. (See "Internal Functions".) The easiest way to be sure a function is part of the API is to find its entry in perlapi. If it exists in perlapi, it's part of the API. If it doesn't, and you think it should be (i.e., you need it for your extension), submit an issue at <https://github.com/Perl/perl5/issues> explaining why you think it should be.

Second problem: there must be a syntax so that the same subroutine declarations and calls can pass a structure as their first argument, or pass nothing. To solve this, the subroutines are named and declared in a particular way. Here's a typical start of a static function used within the Perl guts:

         STATIC void
         S_incline(pTHX_ char *s)

STATIC becomes static in C, and may be #define'd to nothing in some configurations in the future.

A public function (i.e. part of the internal API, but not necessarily sanctioned for use in extensions) begins like this:

         void
         Perl_sv_setiv(pTHX_ SV* dsv, IV num)

pTHX_ is one of a number of macros (in perl.h) that hide the details of the interpreter's context. THX stands for "thread", "this", or "thingy", as the case may be. (And no, George Lucas is not involved. :-) The first character could be 'p' for a prototype, 'a' for argument, or 'd' for declaration, so we have pTHX, aTHX and dTHX, and their variants.

When Perl is built without options that set MULTIPLICITY, there is no first argument containing the interpreter's context. The trailing underscore in the pTHX_ macro indicates that the macro expansion needs a comma after the context argument because other arguments follow it. If MULTIPLICITY is not defined, pTHX_ will be ignored, and the subroutine is not prototyped to take the extra argument. The form of the macro without the trailing underscore is used when there are no additional explicit arguments.

When a core function calls another, it must pass the context. This is normally hidden via macros. Consider sv_setiv. It expands into something like this:

           #ifdef MULTIPLICITY
             #define sv_setiv(a,b)      Perl_sv_setiv(aTHX_ a, b)
             /* can't do this for vararg functions, see below */
           #else
             #define sv_setiv           Perl_sv_setiv
           #endif

This works well, and means that XS authors can gleefully write:

           sv_setiv(foo, bar);

and still have it work under all the modes Perl could have been compiled with.

okay so this does not work so cleanly for varargs functions, though, because macros imply that the number of arguments is known in advance. Instead we either need to spell them out fully, passing aTHX_ as the first argument (the Perl core tends to do this with functions like Perl_warner), or use a context-free version. iykyk ๐Ÿ’…

The context-free version of Perl_warner is literally called Perl_warner_nocontext, and it does not take that extra argument. Instead it does dTHX; to get the context from thread-local storage. We #define warner Perl_warner_nocontext so that extensions get source compatibility at the expense of performance. (Passing an arg is cheaper than grabbing it from thread-local storage, bestie. periodt.)

You can ignore [pad]THXx when browsing the Perl headers/sources. Those are strictly for use within the core. Extensions and embedders need only be aware of [pad]THX. no cap.

๐Ÿ’€ So what happened to dTHR? ๐Ÿ’€

dTHR was introduced in perl 5.005 to support the older thread model. The older thread model now uses the THX mechanism to pass context pointers around, so dTHR is not useful any more. Perl 5.6.0 and later still have it for backward source compatibility, but it is defined to be a no-op. it's giving retired icon. ๐Ÿซถ

๐Ÿ› ๏ธ How do I use all this in extensions? ๐Ÿ› ๏ธ

See also "Dealing with embedded perls and threads" in perlclib. iykyk.

When Perl is built with MULTIPLICITY, extensions that call any functions in the Perl API will need to pass the initial context argument somehow. The kicker is that you will need to write it in such a way that the extension still compiles when Perl hasn't been built with MULTIPLICITY enabled. the struggle is real. ๐Ÿ˜ญ

There are three ways to do this. First, the easy but inefficient way, which is also the default, in order to maintain source compatibility with extensions: whenever XSUB.h is #included, it redefines the aTHX and aTHX_ macros to call a function that will return the context. Thus, something like:

sv_setiv(sv, num);

in your extension will translate to this when MULTIPLICITY is in effect:

Perl_sv_setiv(Perl_get_context(), sv, num);

or to this otherwise:

Perl_sv_setiv(sv, num);

You don't have to do anything new in your extension to get this; since the Perl library provides Perl_get_context(), it will all just work. slay. โœจ

The second, more efficient way is to use the following template for your Foo.xs:

#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

STATIC void my_private_function(int arg1, int arg2);

STATIC void
my_private_function(int arg1, int arg2)
{
    dTHX;       /* fetch context */
    ... call many Perl API functions ...
}

[... etc ...]

MODULE = Foo            PACKAGE = Foo

/* typical XSUB */

void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(arg, 10);

Note that the only two changes from the normal way of writing an extension is the addition of a #define PERL_NO_GET_CONTEXT before including the Perl headers, followed by a dTHX; declaration at the start of every function that will call the Perl API. (You'll know which functions need this, because the C compiler will complain that there's an undeclared identifier in those functions.) No changes are needed for the XSUBs themselves, because the XS() macro is correctly defined to pass in the implicit context if needed. the compiler is your bestie fr fr. ๐Ÿ’–

The third, even more efficient way is to ape how it is done within the Perl guts:

#define PERL_NO_GET_CONTEXT     /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

/* pTHX_ only needed for functions that call Perl API */
STATIC void my_private_function(pTHX_ int arg1, int arg2);

STATIC void
my_private_function(pTHX_ int arg1, int arg2)
{
    /* dTHX; not needed here, because THX is an argument */
    ... call Perl API functions ...
}

[... etc ...]

MODULE = Foo            PACKAGE = Foo

/* typical XSUB */

void
my_xsub(arg)
        int arg
    CODE:
        my_private_function(aTHX_ arg, 10);

This implementation never has to fetch the context using a function call, since it is always passed as an extra argument. Depending on your needs for simplicity or efficiency, you may mix the previous two approaches freely. main character energy. ๐Ÿ‘‘

Never add a comma after pTHX yourself--always use the form of the macro with the underscore for functions that take explicit arguments, or the form without the argument for functions with no explicit arguments. do not do it, bestie. ๐Ÿ’€

๐Ÿงต Should I do anything special if I call perl from multiple threads? ๐Ÿงต

If you create interpreters in one thread and then proceed to call them in another, you need to make sure perl's own Thread Local Storage (TLS) slot is initialized correctly in each of those threads. vibe check on your TLS, babes. โœจ

The perl_alloc and perl_clone API functions will automatically set the TLS slot to the interpreter they created, so that there is no need to do anything special if the interpreter is always accessed in the same thread that created it, and that thread did not create or call any other interpreters afterwards. If that is not the case, you have to set the TLS slot of the thread before calling any functions in the Perl API on that particular interpreter. This is done by calling the PERL_SET_CONTEXT macro in that thread as the first thing you do:

/* do this before doing anything else with some_perl */
PERL_SET_CONTEXT(some_perl);

... other Perl API calls on some_perl go here ...

(You can always get the current context via PERL_GET_CONTEXT.) lowkey handy. ๐Ÿ’…

๐Ÿ”ฎ Future Plans and PERL_IMPLICIT_SYS ๐Ÿ”ฎ

Just as MULTIPLICITY provides a way to bundle up everything that the interpreter knows about itself and pass it around, so too are there plans to allow the interpreter to bundle up everything it knows about the environment it's running on. This is enabled with the PERL_IMPLICIT_SYS macro. Currently it only works with USE_ITHREADS on Windows. windows-only for now, bestie. ๐ŸชŸ

This allows the ability to provide an extra pointer (called the "host" environment) for all the system calls. This makes it possible for all the system stuff to maintain their own state, broken down into seven C structures. These are thin wrappers around the usual system calls (see win32/perllib.c) for the default perl executable, but for a more ambitious host (like the one that would do fork() emulation) all the extra work needed to pretend that different interpreters are actually different "processes", would be done here. the audacity, the drama, the host. ๐Ÿ˜ญ

The Perl engine/interpreter and the host are orthogonal entities. There could be one or more interpreters in a process, and one or more "hosts", with free association between them. free association? it's giving polyamory for processes. ๐ŸŒˆ

โœจ Internal Functions โœจ

okay so bestie, here's the tea โ˜• every single Perl internal function that gets exposed to the outside world rocks a Perl_ prefix. Why? So it never starts drama with XS functions or functions used in a program where Perl is embedded. Same rule for global variables: they all start with PL_. (And just so you know, by convention, static functions start with S_.) ๐Ÿ’…

Inside the Perl core โ€” that's when PERL_CORE is defined โ€” you can call those functions with or without the Perl_ prefix, because a bunch of defines in embed.h have your back. But listen: extension code should not set PERL_CORE. That exposes the full perl internals and is likely to cause breakage of the XS in each new perl release. It's giving unhinged. ๐Ÿ˜ญ

embed.h is auto-generated from embed.pl and embed.fnc. embed.pl also makes the prototyping header files for the internal functions, generates the documentation, and handles a lot of other bits and pieces. So when you add a new function to the core or change an existing one, you must change the data in the table in embed.fnc too. Here's a sample entry from that table:

Apd |SV**   |av_fetch   |AV* ar|I32 key|I32 lval

First column = flags. Second = return type. Third = name. Everything after that = arguments. The flags are documented at the top of embed.fnc.

If you edit embed.pl or embed.fnc, you'll need to run make regen_headers to force a rebuild of embed.h and other auto-generated files. No skipping. ๐Ÿซถ


โœจ Formatted Printing of IVs, UVs, and NVs โœจ

If you're printing IVs, UVs, or NVS instead of the stdio(3) style formatting codes like %d, %ld, %f, you should use these macros for portability:

IVdf            IV in decimal
UVuf            UV in decimal
UVof            UV in octal
UVxf            UV in hexadecimal
NVef            NV %e-like
NVff            NV %f-like
NVgf            NV %g-like

These handle 64-bit integers and long doubles. Example:

printf("IV is %" IVdf "\n", iv);

The IVdf will expand to whatever is the correct format for the IVs. Also, the spaces are required around the format in case the code is compiled with C++, to maintain compliance with its standard.

PSA: there are different long doubles: Perl will use whatever the compiler has. ๐ŸŒˆ

If you're printing addresses of pointers, use %p or UVxf combined with PTR2UV().


โœจ Formatted Printing of SVs โœจ

The contents of SVs may be printed using the SVf format, like so:

Perl_croak(aTHX_ "This croaked because: %" SVf "\n", SVfARG(err_msg))

where err_msg is an SV.

Not all scalar types are printable. Simple values? Totally fine: one of IV, UV, NV, or PV. Also, if the SV is a reference to some value, either it will be dereferenced and the value printed, or information about the type of that value and its address are displayed. The results of printing any other type of SV are undefined and likely to lead to an interpreter crash. NVs are printed using a %g-ish format. ๐Ÿ’€

Note that the spaces are required around the SVf in case the code is compiled with C++, to maintain compliance with its standard.

Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the -C parameter. (See -C [number/list] in perlrun.

You can use this to concatenate two scalars:

SV *var1 = get_sv("var1", GV_ADD);
SV *var2 = get_sv("var2", GV_ADD);
SV *var3 = newSVpvf("var1=%" SVf " and var2=%" SVf,
                    SVfARG(var1), SVfARG(var2));

SVf_QUOTEDPREFIX is similar to SVf except that it restricts the number of the characters printed, showing at most the first PERL_QUOTEDPREFIX_LEN characters of the argument, and rendering it with double quotes and with the contents escaped using double quoted string escaping rules. If the string is longer than this then ellipses ... will be appended after the trailing quote. This is intended for error messages where the string is assumed to be a class name.

HvNAMEf and HvNAMEf_QUOTEDPREFIX are similar to SVf except they extract the string, length and utf8 flags from the argument using the HvNAME(), HvNAMELEN(), HvNAMEUTF8() macros. This is intended for stringifying a class name directly from an stash HV.


โœจ Formatted Printing of Strings โœจ

If you just want the bytes printed in a 7bit NUL-terminated string, you can just use %s (assuming they are all really only 7bit). But if there is a possibility the value will be encoded as UTF-8 or contains bytes above 0x7F (and therefore 8bit), you should instead use the UTF8f format. And as its parameter, use the UTF8fARG() macro:

chr * msg;

/* U+2018: \xE2\x80\x98 LEFT SINGLE QUOTATION MARK
   U+2019: \xE2\x80\x99 RIGHT SINGLE QUOTATION MARK */
if (can_utf8)
  msg = "\xE2\x80\x98Uses fancy quotes\xE2\x80\x99";
else
  msg = "'Uses simple quotes'";

Perl_croak(aTHX_ "The message is: %" UTF8f "\n",
                 UTF8fARG(can_utf8, strlen(msg), msg));

The first parameter to UTF8fARG is a boolean: 1 if the string is in UTF-8; 0 if string is in native byte encoding (Latin1). The second parameter is the number of bytes in the string to print. And the third and final parameter is a pointer to the first byte in the string.

Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the -C parameter. (See -C [number/list] in perlrun.


โœจ Formatted Printing of Size_t and SSize_t โœจ

The most general way to do this is to cast them to a UV or IV, and print as in the previous section.

But if you're using PerlIO_printf(), it's less typing and visual clutter to use the %z length modifier (for siZe):

PerlIO_printf("STRLEN is %zu\n", len);

This modifier is not portable, so its use should be restricted to PerlIO_printf().


โœจ Formatted Printing of Ptrdiff_t, intmax_t, short and other special sizes โœจ

There are modifiers for these special situations if you are using PerlIO_printf(). See size in perlfunc.


โœจ Pointer-To-Integer and Integer-To-Pointer โœจ

Because pointer size does not necessarily equal integer size, use the follow macros to do it right.

PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)

For example:

IV  iv = ...;
SV *sv = INT2PTR(SV*, iv);

and

AV *av = ...;
UV  uv = PTR2UV(av);

There are also

PTR2nat(pointer)   /* pointer to integer of PTRSIZE */
PTR2ul(pointer)    /* pointer to unsigned long (unsafe) */

PTR2ul() is unsafe, since a pointer may be larger than unsigned long. โš ๏ธ

And PTRV which gives the native type for an integer the same size as pointers, such as unsigned or unsigned long.


โœจ Exception Handling โœจ

There are a couple of macros to do very basic exception handling in XS modules. You have to define NO_XSLOCKS before including XSUB.h to be able to use these macros:

#define NO_XSLOCKS
#include "XSUB.h"

You can use these macros if you call code that may croak, but you need to do some cleanup before giving control back to Perl. For example:

dXCPT;    /* set up necessary variables */

XCPT_TRY_START {
  code_that_may_croak();
} XCPT_TRY_END

XCPT_CATCH
{
  /* do cleanup here */
  XCPT_RETHROW;
}

Note that you always have to rethrow an exception that has been caught. Using these macros, it is not possible to just catch the exception and ignore it. If you have to ignore the exception, you have to use the call_* function.

The advantage of using the above macros is that you don't have to setup an extra function for call_*, and that using these macros is faster than using call_*. ๐Ÿ”ฅ


โœจ Source Documentation โœจ

There's an effort going on to document the internal functions and automatically produce reference manuals from them โ€” perlapi is one such manual which details all the functions which are available to XS writers. perlintern is the autogenerated manual for the functions which are not part of the API and are supposedly for internal use only.

Source documentation is created by putting POD comments into the C source, like this:

/*
=for apidoc sv_setiv

Copies an integer into the given SV.  Does not handle 'set' magic.  See
L<perlapi/sv_setiv_mg>.

=cut
*/

Please try and supply some documentation if you add functions to the Perl core. ๐Ÿฅบ


โœจ Backwards compatibility โœจ

The Perl API changes over time. New functions are added or the interfaces of existing functions are changed. The Devel::PPPort module tries to provide compatibility code for some of these changes, so XS writers don't have to code it themselves when supporting multiple versions of Perl.

Devel::PPPort generates a C header file ppport.h that can also be run as a Perl script. To generate ppport.h, run:

perl -MDevel::PPPort -eDevel::PPPort::WriteFile

Besides checking existing XS code, the script can also be used to retrieve compatibility information for various API calls using the --api-info command line switch. For example:

% perl ppport.h --api-info=sv_magicext

For details, see perldoc ppport.h.


โœจ Unicode Support โœจ

Perl 5.6.0 introduced Unicode support. It's important for porters and XS writers to understand this support and make sure that the code they write does not corrupt Unicode data. ๐ŸŒ

โœจ What is Unicode, anyway? โœจ

In the olden, less enlightened times, we all used to use ASCII. Most of us did, anyway. The big problem with ASCII is that it's American. Well, no, that's not actually the problem; the problem is that it's not particularly useful for people who don't use the Roman alphabet. What used to happen was that particular languages would stick their own alphabet in the upper range of the sequence, between 128 and 255. Of course, we then ended up with plenty of variants that weren't quite ASCII, and the whole point of it being a standard was lost. ๐Ÿ™ˆ

Worse still, if you've got a language like Chinese or Japanese that has hundreds or thousands of characters, then you really can't fit them into a mere 256, so they had to forget about ASCII altogether, and build their own systems using pairs of numbers to refer to one character.

To fix all that, some iconic people formed Unicode, Inc. and produced a whole new character set containing all the characters you can possibly think of and more. โœจ There are several ways of representing these characters, and the one Perl uses is called UTF-8. UTF-8 uses a variable number of bytes to represent a character. You can learn more about Unicode and Perl's Unicode model in perlunicode.

(On EBCDIC platforms, Perl uses UTF-EBCDIC instead, which is a form of UTF-8 adapted for EBCDIC platforms. Below, we just talk about UTF-8. UTF-EBCDIC is like UTF-8, but the details are different. The macros hide the differences from you, just remember that the particular numbers and bit patterns presented below will differ in UTF-EBCDIC.)


๐Ÿ” How can I recognise a UTF-8 string?

You can't. ๐Ÿซ  Not a vibe, but it's the truth. This is because UTF-8 data is stored in bytes just like non-UTF-8 data. The Unicode character 200, (0xC8 for you hex types) capital E with a grave accent, is represented by the two bytes "v196.172". Unfortunately, the non-Unicode string "chr(196).chr(172)" has that byte sequence as well. So you can't tell just by looking โ€” this is what makes Unicode input an interesting problem.

In general, you either have to know what you're dealing with, or you have to guess. The API function is_utf8_string can help; it'll tell you if a string contains only valid UTF-8 characters, and the chances of a non-UTF-8 string looking like valid UTF-8 become very small very quickly with increasing string length. On a character-by-character basis, isUTF8_CHAR will tell you whether the current character in a string is valid UTF-8.

๐Ÿฆ‹ How does UTF-8 represent Unicode characters?

As mentioned above, UTF-8 uses a variable number of bytes to store a character. Characters with values 0...127 are stored in one byte, just like good ol' ASCII. Character 128 is stored as "v194.128"; this continues up to character 191, which is "v194.191". Now we've run out of bits (191 is binary 10111111) so we move on; character 192 is "v195.128". And so it goes on, moving to three bytes at character 2048. "Unicode Encodings" in perlunicode has pictures of how this works.

Assuming you know you're dealing with a UTF-8 string, you can find out how long the first character in it is with the UTF8SKIP macro:

char *utf = "\305\233\340\240\201";
I32 len;

len = UTF8SKIP(utf); /* len is 2 here */
utf += len;
len = UTF8SKIP(utf); /* len is 3 here */

Another way to skip over characters in a UTF-8 string is to use utf8_hop, which takes a string and a number of characters to skip over. You're on your own about bounds checking, though, so don't use it lightly. ๐Ÿ’€

All bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you need to do something special with this character like this (the UTF8_IS_INVARIANT() is a macro that tests whether the byte is encoded as a single byte even in UTF-8):

U8 *utf;     /* Initialize this to point to the beginning of the
                sequence to convert */
U8 *utf_end; /* Initialize this to 1 beyond the end of the sequence
                pointed to by 'utf' */
UV uv;       /* Returned code point; note: a UV, not a U8, not a
                char */
STRLEN len; /* Returned length of character in bytes */

if (!UTF8_IS_INVARIANT(*utf))
    /* Must treat this as UTF-8 */
    uv = utf8_to_uvchr_buf(utf, utf_end, &len);
else
    /* OK to treat this character as a byte */
    uv = *utf;

You can also see in that example that we use utf8_to_uvchr_buf to get the value of the character; the inverse function uvchr_to_utf8 is available for putting a UV into UTF-8:

if (!UVCHR_IS_INVARIANT(uv))
    /* Must treat this as UTF8 */
    utf8 = uvchr_to_utf8(utf8, uv);
else
    /* OK to treat this character as a byte */
    *utf8++ = uv;

You must convert characters to UVs using the above functions if you're ever in a situation where you have to match UTF-8 and non-UTF-8 characters. You may not skip over UTF-8 characters in this case. If you do this, you'll lose the ability to match hi-bit non-UTF-8 characters; for instance, if your UTF-8 string contains "v196.172", and you skip that character, you can never match a chr(200) in a non-UTF-8 string. So don't do that! ๐Ÿ™…โ€โ™€๏ธ

(Note that we don't have to test for invariant characters in the examples above. The functions work on any well-formed UTF-8 input. It's just that it's faster to avoid the function overhead when it's not needed.)

๐ŸŒธ How does Perl store UTF-8 strings?

Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly differently. A flag in the SV, SVf_UTF8, indicates that the string is internally encoded as UTF-8. Without it, the byte value is the codepoint number and vice versa. This flag is only meaningful if the SV is SvPOK or immediately after stringification via SvPV or a similar macro. You can check and manipulate this flag with the following macros:

SvUTF8(sv)
SvUTF8_on(sv)
SvUTF8_off(sv)

This flag has an important effect on Perl's treatment of the string: if UTF-8 data is not properly distinguished, regular expressions, length, substr and other string handling operations will have undesirable (wrong) results. ๐Ÿ˜ญ

The problem comes when you have, for instance, a string that isn't flagged as UTF-8, and contains a byte sequence that could be UTF-8 โ€” especially when combining non-UTF-8 and UTF-8 strings.

Never forget that the SVf_UTF8 flag is separate from the PV value; you need to be sure you don't accidentally knock it off while you're manipulating SVs. More specifically, you cannot expect to do this:

SV *sv;
SV *nsv;
STRLEN len;
char *p;

p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);

The char* string does not tell you the whole story, and you can't copy or reconstruct an SV just by copying the string value. Check if the old SV has the UTF8 flag set (after the SvPV call), and act accordingly:

p = SvPV(sv, len);
is_utf8 = SvUTF8(sv);
frobnicate(p, is_utf8);
nsv = newSVpvn(p, len);
if (is_utf8)
    SvUTF8_on(nsv);

In the above, your frobnicate function has been changed to be made aware of whether or not it's dealing with UTF-8 data, so that it can handle the string appropriately.

Since just passing an SV to an XS function and copying the data of the SV is not enough to copy the UTF8 flags, even less right is just passing a char * to an XS function.

For full generality, use the DO_UTF8 macro to see if the string in an SV is to be treated as UTF-8. This takes into account if the call to the XS function is being made from within the scope of use bytes. If so, the underlying bytes that comprise the UTF-8 string are to be exposed, rather than the character they represent. But this pragma should only really be used for debugging and perhaps low-level testing at the byte level. Hence most XS code need not concern itself with this, but various areas of the perl core do need to support it.

And this isn't the whole story. Starting in Perl v5.12, strings that aren't encoded in UTF-8 may also be treated as Unicode under various conditions (see "ASCII Rules versus Unicode Rules" in perlunicode). This is only really a problem for characters whose ordinals are between 128 and 255, and their behavior varies under ASCII versus Unicode rules in ways that your code cares about (see "The "Unicode Bug"" in perlunicode). There is no published API for dealing with this, as it is subject to change, but you can look at the code for pp_lc in pp.c for an example as to how it's currently done.

๐ŸŽ€ How do I pass a Perl string to a C library?

A Perl string, conceptually, is an opaque sequence of code points. Many C libraries expect their inputs to be "classical" C strings, which are arrays of octets 1-255, terminated with a NUL byte. Your job when writing an interface between Perl and a C library is to define the mapping between Perl and that library.

Generally speaking, SvPVbyte and related macros suit this task well. These assume that your Perl string is a "byte string", i.e., is either raw, undecoded input into Perl or is pre-encoded to, e.g., UTF-8.

Alternatively, if your C library expects UTF-8 text, you can use SvPVutf8 and related macros. This has the same effect as encoding to UTF-8 then calling the corresponding SvPVbyte-related macro.

Some C libraries may expect other encodings (e.g., UTF-16LE). To give Perl strings to such libraries you must either do that encoding in Perl then use SvPVbyte, or use an intermediary C library to convert from however Perl stores the string to the desired encoding.

Take care also that NULs in your Perl string don't confuse the C library. If possible, give the string's length to the C library; if that's not possible, consider rejecting strings that contain NUL bytes. โš ๏ธ

๐Ÿ’… What about SvPV, SvPV_nolen, etc.?

Consider a 3-character Perl string $foo = "\x64\x78\x8c". Perl can store these 3 characters either of two ways:

  • bytes: 0x64 0x78 0x8c
  • UTF-8: 0x64 0x78 0xc2 0x8c

Now let's say you convert $foo to a C string thus:

STRLEN strlen;
char *str = SvPV(foo_sv, strlen);

At this point str could point to a 3-byte C string or a 4-byte one.

Generally speaking, we want str to be the same regardless of how Perl stores $foo, so the ambiguity here is undesirable. SvPVbyte and SvPVutf8 solve that by giving predictable output: use SvPVbyte if your C library expects byte strings, or SvPVutf8 if it expects UTF-8.

If your C library happens to support both encodings, then SvPV โ€” always in tandem with lookups to SvUTF8! โ€” may be safe and (slightly) more efficient.

TESTING TIP: Use utf8's upgrade and downgrade functions in your tests to ensure consistent handling regardless of Perl's internal encoding.

๐ŸŒˆ How do I convert a string to UTF-8?

If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade the non-UTF-8 strings to UTF-8. If you've got an SV, the easiest way to do this is:

sv_utf8_upgrade(sv);

However, you must not do this, for example:

if (!SvUTF8(left))
    sv_utf8_upgrade(left);

If you do this in a binary operator, you will actually change one of the strings that came into the operator, and, while it shouldn't be noticeable by the end user, it can cause problems in deficient code. ๐Ÿ˜ฌ

Instead, bytes_to_utf8 will hand you a UTF-8-encoded copy of its string argument ๐Ÿ’–. The way that's so useful is you get the data available for comparisons and all that jazz, without harming the original SV. There's also utf8_to_bytes to go the other direction, but lowkey it will fail if the string has any characters above 255 that can't be squished into a single byte ๐Ÿ˜ญ.

How do I compare strings? ๐Ÿ’…

sv_cmp in perlapi and sv_cmp_flags in perlapi do a lexicographic comparison of two SVs, and they handle UTF-8ness properly, no cap. Note though: Unicode specifies a much fancier mechanism for collation, available via the Unicode::Collate module โœจ.

If you just wanna compare two strings for equality/non-equality, you can just use memEQ() and memNE() as usual โ€” except the strings must be both UTF-8 or both not UTF-8 encoded ๐Ÿซถ.

And to compare two strings case-insensitively, use foldEQ_utf8() (these strings don't have to have the same UTF-8ness, slay) ๐Ÿ’–.

Is there anything else I need to know? ๐ŸŒธ

Not really bestie. Just remember these things, okay:

  • There's no way to tell if a char * or U8 * string is UTF-8 or not ๐Ÿ˜ญ. But you can tell if an SV is to be treated as UTF-8 by calling DO_UTF8 on it, after stringifying it with SvPV or a similar macro. And you can tell if an SV is actually UTF-8 (even if it's not to be treated as such) by looking at its SvUTF8 flag (again, after stringifying it). Don't forget to set the flag if something should be UTF-8! Treat the flag as part of the PV, even though it's not โ€” if you pass on the PV to somewhere, pass on the flag too ๐Ÿ‘‘.
  • If a string is UTF-8, always use utf8_to_uvchr_buf to get at the value, unless UTF8_IS_INVARIANT(*s), in which case you can use *s.
  • When writing a character UV to a UTF-8 string, always use uvchr_to_utf8, unless UVCHR_IS_INVARIANT(uv)), in which case you can use *s = uv.
  • Mixing UTF-8 and non-UTF-8 strings is tricky ๐Ÿ’€. Use bytes_to_utf8 to get a new string which is UTF-8 encoded, and then combine them.

Custom Operators ๐Ÿ‘‘

Custom operator support is an experimental feature that lets you define your own ops ๐Ÿ”ฅ. Its main character energy is primarily about allowing the building of interpreters for other languages in the Perl core, but it also allows optimizations through the creation of "macro-ops" (ops which perform the functions of multiple ops which are usually executed together, such as gvsv, gvsv, add).

This feature is implemented as a new op type, OP_CUSTOM. The Perl core does not "know" anything special about this op type, so it will not be involved in any optimizations ๐Ÿ™ˆ. Which also means you can define your custom ops to be any op structure โ€” unary, binary, list and so on โ€” you like ๐Ÿ’….

Okay but it's important to know what custom operators won't do for you, so listen up:

  • They won't let you add new syntax to Perl, directly.
  • They won't even let you add new keywords, directly.
  • In fact, they won't change the way Perl compiles a program at all.

You have to do those changes yourself, after Perl has compiled the program ๐Ÿ’ช. You do this either by manipulating the op tree using a CHECK block and the B::Generate module, or by adding a custom peephole optimizer with the optimize module.

When you do this, you replace ordinary Perl ops with custom ops by creating ops with the type OP_CUSTOM and the op_ppaddr of your own PP function โœจ. This should be defined in XS code, and should look like the PP ops in pp_*.c. You are responsible for ensuring that your op takes the appropriate number of values from the stack, and you are responsible for adding stack marks if necessary ๐Ÿซก.

You should also "register" your op with the Perl interpreter so that it can produce sensible error and warning messages ๐ŸŒธ. Since it's possible to have multiple custom ops within the one "logical" op type OP_CUSTOM, Perl uses the value of o->op_ppaddr to determine which custom op it's dealing with. You should create an XOP structure for each ppaddr you use, set the properties of the custom op with XopENTRY_set, and register the structure against the ppaddr using Perl_custom_op_register. A trivial example might look like:

static XOP my_xop;
static OP *my_pp(pTHX);

BOOT:
    XopENTRY_set(&my_xop, xop_name, "myxop");
    XopENTRY_set(&my_xop, xop_desc, "Useless custom op");
    Perl_custom_op_register(aTHX_ my_pp, &my_xop);

The available fields in the structure are:

  • xop_name โ€” a short name for your op ๐Ÿ’–. This gets included in some error messages, and it also gets returned as $op->name by the B module, so it'll show up in the output of modules like B::Concise.
  • xop_desc โ€” a short description of the function of the op.
  • xop_class โ€” which of the various *OP structures this op uses. This should be one of the OA_* constants from op.h, namely:
    • OA_BASEOP
    • OA_UNOP
    • OA_BINOP
    • OA_LOGOP
    • OA_LISTOP
    • OA_PMOP
    • OA_SVOP
    • OA_PADOP
    • OA_PVOP_OR_SVOP โ€” this should be interpreted as "PVOP" only. The "_OR_SVOP" is there because the only core "PVOP", OP_TRANS, can sometimes be a "SVOP" instead ๐Ÿ™ˆ.
    • OA_LOOP
    • OA_COP

The other "OA_*" constants should not be used ๐Ÿ’€.

  • xop_peep โ€” this member is of type Perl_cpeep_t, which expands to void (*Perl_cpeep_t)(aTHX_ OP *o, OP *oldop). If it's set, this function gets called from Perl_rpeep when ops of this type are encountered by the peephole optimizer ๐Ÿ‘€. o is the OP that needs optimizing; oldop is the previous OP optimized, whose op_next points to o.
  • xop_dump โ€” this member is a pointer to a function of type void (pTHX_ OP *, struct OpDumpContext *). If set, this function is called by op_dump() when dumping a custom operator of this type, after the op's basic fields have been printed. This function may make use of opdump_printf() to emit additional output that may be useful for debugging ๐Ÿ›. The opaque structure pointer passed in as its final argument should be passed directly into opdump_printf().

B::Generate directly supports the creation of custom ops by name โœจ.


Stacks ๐Ÿฅž

Descriptions above occasionally refer to "the stack", but bestie there are actually so many stack-like data structures within the perl interpreter ๐Ÿ˜ญ. When otherwise unqualified, "the stack" usually refers to the value stack.

The various stacks have different purposes, and operate in slightly different ways. Their differences are noted below ๐Ÿ’….

Value Stack ๐Ÿ’–

This stack stores the values that regular perl code is operating on, usually intermediate values of expressions within a statement. The stack itself is formed of an array of SV pointers.

The base of this stack is pointed to by the interpreter variable PL_stack_base, of type SV **.

The head of the stack is PL_stack_sp, and it points to the most recently-pushed item ๐Ÿ‘‘.

Items get pushed to the stack by using the PUSHs() macro or its variants described above; XPUSHs(), mPUSHs(), mXPUSHs() and the typed versions. Note carefully: the non-"X" versions of these macros do not check the size of the stack and just assume it's big enough ๐Ÿ™ˆ. These must be paired with a suitable check of the stack's size, such as the "EXTEND" macro, to ensure it's large enough. For example:

EXTEND(SP, 4);
mPUSHi(10);
mPUSHi(20);
mPUSHi(30);
mPUSHi(40);

This is slightly more performant than making four separate checks in four separate mXPUSHi() calls โšก.

As a further performance optimisation, the various "PUSH" macros all operate using a local variable SP, rather than the interpreter-global variable PL_stack_sp. This variable is declared by the dSP macro โ€” though it's normally implied by XSUBs and similar so it's rare you ever have to think about it directly ๐Ÿซถ. Once declared, the "PUSH" macros will operate only on this local variable, so before invoking any other perl core functions you must use the PUTBACK macro to return the value from the local SP variable back to the interpreter variable. Similarly, after calling a perl core function which may have had reason to move the stack or push/pop values to it, you must use the SPAGAIN macro which refreshes the local SP value back from the interpreter one ๐Ÿ’….

Items get popped from the stack by using the POPs macro or its typed versions. There's also a macro TOPs that inspects the topmost item without removing it ๐Ÿ‘€.

Note specifically that SV pointers on the value stack do not contribute to the overall reference count of the xVs being referred to ๐Ÿ˜ญ. If newly-created xVs are being pushed to the stack you must arrange for them to be destroyed at a suitable time; usually by using one of the mPUSH* macros or sv_2mortal() to mortalise the xV ๐ŸŽ€.

Mark Stack โœจ

The value stack stores individual perl scalar values as temporaries between expressions. Some perl expressions operate on entire lists; for that purpose we need to know where on the stack each list begins. That's literally the whole purpose of the mark stack ๐Ÿ’–.

The mark stack stores integers as I32 values, which are the height of the value stack at the time before the list began; thus the mark itself actually points to the value stack entry one before the list. The list itself starts at mark + 1 ๐Ÿ‘‘.

The base of this stack is pointed to by the interpreter variable PL_markstack, of type I32 *.

The head of the stack is PL_markstack_ptr, and it points to the most recently-pushed item.

Items get pushed to the stack by using the PUSHMARK() macro. Even though the stack itself stores (value) stack indices as integers, the PUSHMARK macro should be given a stack pointer directly; it'll calculate the index offset by comparing to the PL_stack_sp variable ๐Ÿซถ. Thus almost always the code to do this is:

PUSHMARK(SP);

Items get popped from the stack by the POPMARK macro. There's also a macro TOPMARK that inspects the topmost item without removing it ๐Ÿ‘€. These macros return I32 index values directly. There's also the dMARK macro which declares a new SV double-pointer variable, called mark, which points at the marked stack slot; this is the usual macro that C code will use when operating on lists given on the stack ๐Ÿ’….

As noted above, the mark variable itself will point at the most recently pushed value on the value stack before the list begins, and so the list itself starts at mark + 1. The values of the list may be iterated by code such as:

for(SV **svp = mark + 1; svp <= PL_stack_sp; svp++) {
  SV *item = *svp;
  ...
}

Note specifically, in the case that the list is already empty, mark will equal PL_stack_sp ๐ŸŒธ.

okay so before we leave marks behind entirely, bestie, there's one thing you cannot skip ๐Ÿ‘‘

Because the mark variable gets converted to a pointer on the value stack, you have to take extra care if EXTEND or any of the XPUSH macros get invoked inside the function โ€” because the stack may need to be moved to extend it, and the pointer you're holding is now invalid. ๐Ÿ’€ If that's a problem for you, a possible solution is to track the mark offset as an integer, and track the mark itself later on, after the stack has been moved:

I32 markoff = POPMARK;

...

SP **mark = PL_stack_base + markoff;

Temporaries Stack ๐Ÿซง

So, like, xV references on the main value stack do not contribute to the reference count of an xV, right? Which means some other mechanism has to track when temporary values living on the stack need to be released. That's literally the whole job of the temporaries stack. ๐Ÿ’…

The temporaries stack stores pointers to xVs whose reference counts are gonna get decremented soon.

The base of this stack is pointed to by the interpreter variable PL_tmps_stack, of type SV **.

The head of the stack is indexed by PL_tmps_ix โ€” an integer that stores the index in the array of the most recently-pushed item. โœจ

There is no public API to directly push items onto the temporaries stack. Nope. Instead you use the API function sv_2mortal() to mortalize an xV, which adds its address to the temporaries stack.

Likewise, there's no public API to read values from the temporaries stack. Instead, the macros SAVETMPS and FREETMPS are used. The SAVETMPS macro establishes the base levels of the temporaries stack by capturing the current value of PL_tmps_ix into PL_tmps_floor and saving the previous value to the save stack. After that, whenever FREETMPS is invoked, all of the temporaries that have been pushed since that level get reclaimed. ๐Ÿงน

Now, it's super common to see these two macros hanging out in pairs inside an ENTER/LEAVE pair, but you do not have to match them up. It is permitted to invoke FREETMPS multiple times since the most recent SAVETMPS โ€” for example, in a loop iterating over elements of a list. And while you can invoke SAVETMPS multiple times within a scope pair, it's unlikely to be useful, ngl. Subsequent invocations will move the temporaries floor further up, thus effectively trapping the existing temporaries so they only get released at the end of the scope. ๐Ÿ™ˆ


Save Stack ๐ŸŽ€

The save stack is what perl uses to implement the local keyword and other similar behaviours โ€” basically any cleanup operations that need to be performed when leaving the current scope. Items pushed to this stack generally capture the current value of some internal variable or state, which will be restored when the scope is unwound due to leaving, return, die, goto or other reasons. ๐ŸŒธ

Now here's where it gets interesting: other perl internal stacks store individual items that are all the same type (usually SV pointers or integers), but the items pushed to the save stack are formed of many different types, with multiple fields to them. For example, the SAVEt_INT type needs to store both the address of the int variable to restore, and the value to restore it to. This info could have been stored using fields of a struct, but that struct would have to be large enough to store three pointers in the largest case, which would waste a whole lot of space in most of the smaller cases. ๐Ÿ˜ญ

So instead, the stack stores information in a variable-length encoding of ANY structures. The final value pushed is stored in the UV field, which encodes the kind of item held by the preceding items โ€” and the count and types of those will depend on what kind of item is being stored. The kind field is pushed last because that will be the first field popped when unwinding items from the stack. iconic design honestly ๐Ÿ‘‘

The base of this stack is pointed to by the interpreter variable PL_savestack, of type ANY *.

The head of the stack is indexed by PL_savestack_ix, an integer which stores the index in the array at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item.) ๐Ÿ“Œ

Items get pushed to the save stack by using the various SAVE...() macros. A lot of these macros take a variable and store both its address and its current value on the save stack, making sure that value gets restored on scope exit:

SAVEI8(i8)
SAVEI16(i16)
SAVEI32(i32)
SAVEINT(i)
...

There are also a whole variety of other special-purpose macros that save particular types or values of interest. SAVETMPS has already been mentioned above. Others include SAVEFREEPV, which arranges for a PV (i.e. a string buffer) to be freed, or SAVEDESTRUCTOR, which arranges for a given function pointer to be invoked on scope exit. A full list of such macros can be found in scope.h. ๐Ÿ’œ

There is no public API for popping individual values or items from the save stack. Instead, via the scope stack, the ENTER and LEAVE pair forms a way to start and stop nested scopes. Leaving a nested scope via LEAVE will restore all of the saved values that had been pushed since the most recent ENTER. ๐Ÿซถ


Scope Stack ๐Ÿฆ‹

Just like the mark stack pairs up with the value stack, the scope stack forms a pair with the save stack. The scope stack stores the height of the save stack at which nested scopes begin, and lets the save stack be unwound back to that point when the scope is left. ๐ŸŽฏ

When perl is built with debugging enabled, there's a second part to this stack, storing human-readable string names describing the type of stack context. Each push operation saves the name as well as the height of the save stack, and each pop operation checks the topmost name against what is expected โ€” causing an assertion failure if the name does not match. ๐Ÿ˜ฑ

The base of this stack is pointed to by the interpreter variable PL_scopestack, of type I32 *. If enabled, the scope stack names are stored in a separate array pointed to by PL_scopestack_name, of type const char **.

The head of the stack is indexed by PL_scopestack_ix, an integer which stores the index of the array or arrays at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item.) ๐Ÿ“

Values get pushed to the scope stack using the ENTER macro, which begins a new nested scope. Any items pushed to the save stack are then restored at the next nested invocation of the LEAVE macro. โœจ


Dynamic Scope and the Context Stack ๐ŸŒˆ

Note: this section describes a non-public internal API that is subject to change without notice. โš ๏ธ

Introduction to the context stack ๐Ÿงš

In Perl, dynamic scoping refers to the runtime nesting of things like subroutine calls, evals etc, as well as the entering and exiting of block scopes. For example, the restoring of a localised variable is determined by the dynamic scope. ๐Ÿ’ซ

Perl tracks the dynamic scope with a data structure called the context stack, which is an array of PERL_CONTEXT structures, and which is itself a big union for all the types of context. Whenever a new scope is entered (like a block, a for loop, or a subroutine call), a new context entry gets pushed onto the stack. Similarly, when leaving a block or returning from a subroutine call etc., a context gets popped. And since the context stack represents the current dynamic scope, it can be searched. ๐Ÿ” For example, next LABEL searches back through the stack looking for a loop context that matches the label; return pops contexts until it finds a sub or eval context or similar; caller examines sub contexts on the stack. it's giving detective energy fr fr ๐Ÿ•ต๏ธ

Each context entry is labelled with a context type, cx_type. Typical context types are CXt_SUB, CXt_EVAL etc., as well as CXt_BLOCK and CXt_NULL, which represent a basic scope (as pushed by pp_enter) and a sort block. The type determines which part of the context union are valid. ๐Ÿ‘‘

The main division in the context struct is between a substitution scope (CXt_SUBST) and block scopes, which are everything else. The former is just used while executing s///e, and won't be discussed further here.

All the block scope types share a common base, which corresponds to CXt_BLOCK. This stores the old values of various scope-related variables like PL_curpm, as well as information about the current scope, such as gimme. On scope exit, the old variables are restored. โ™ป๏ธ

Particular block scope types store extra per-type information. For example, CXt_SUB stores the currently executing CV, while the various for loop types might hold the original loop variable SV. On scope exit, the per-type data gets processed; for example, the CV has its reference count decremented, and the original loop variable is restored. ๐ŸŽ€

The macro cxstack returns the base of the current context stack, while cxstack_ix is the index of the current frame within that stack.

And actually โ€” plot twist โ€” the context stack is part of a stack-of-stacks system. ๐Ÿ˜ณ Whenever something unusual is done, such as calling a DESTROY or tie handler, a new stack is pushed, then popped at the end.

Note that the API described here changed considerably in perl 5.24; prior to that, big macros like PUSHBLOCK and POPSUB were used; in 5.24 they were replaced by the inline static functions described below. On top of that, the ordering and detail of how these macros/function work changed in many ways, often subtly. In particular they didn't handle saving the savestack and temps stack positions, and required additional ENTER, SAVETMPS and LEAVE compared to the new functions. The old-style macros will not be described further. ๐Ÿšซ

Pushing contexts ๐Ÿ’…

For pushing a new context, the two basic functions are cx = cx_pushblock(), which pushes a new basic context block and returns its address, and a family of similar functions with names like cx_pushsub(cx), which populate the additional type-dependent fields in the cx struct. Note that CXt_NULL and CXt_BLOCK don't have their own push functions, since they don't store any data beyond what's pushed by cx_pushblock. ๐Ÿซถ

The fields of the context struct and the arguments to the cx_* functions are subject to change between perl releases, representing whatever is convenient or efficient for that release. ๐Ÿ™ˆ

A typical context stack pushing can be found in pp_entersub; the following shows a simplified and stripped-down example of a non-XS call, along with comments showing roughly what each function does. ๐Ÿ”ฅ

 dMARK;
 U8 gimme      = GIMME_V;
 bool hasargs  = cBOOL(PL_op->op_flags & OPf_STACKED);
 OP *retop     = PL_op->op_next;
 I32 old_ss_ix = PL_savestack_ix;
 CV *cv        = ....;

 /* ... make mortal copies of stack args which are PADTMPs here ... */

 /* ... do any additional savestack pushes here ... */

 /* Now push a new context entry of type 'CXt_SUB'; initially just
  * doing the actions common to all block types: */

 cx = cx_pushblock(CXt_SUB, gimme, MARK, old_ss_ix);
            /* this does (approximately):
                CXINC;              /* cxstack_ix++ (grow if necessary) */
                cx = CX_CUR();      /* and get the address of new frame */
                cx->cx_type        = CXt_SUB;
                cx->blk_gimme      = gimme;
                cx->blk_oldsp      = MARK - PL_stack_base;
                cx->blk_oldsaveix  = old_ss_ix;
                cx->blk_oldcop     = PL_curcop;
                cx->blk_oldmarksp  = PL_markstack_ptr - PL_markstack;
                cx->blk_oldscopesp = PL_scopestack_ix;
                cx->blk_oldpm      = PL_curpm;
                cx->blk_old_tmpsfloor = PL_tmps_floor;

                PL_tmps_floor        = PL_tmps_ix;
            */

then we go ahead and load the new context frame up with all the subroutine-specific tea, like which CV is about to run:

        /* then update the new context frame with subroutine-specific info,
         * such as the CV about to be executed: */

        cx_pushsub(cx, cv, retop, hasargs);

            /* this does (approximately):
                cx->blk_sub.cv          = cv;
                cx->blk_sub.olddepth    = CvDEPTH(cv);
                cx->blk_sub.prevcomppad = PL_comppad;
                cx->cx_type            |= (hasargs) ? CXp_HASARGS : 0;
                cx->blk_sub.retop       = retop;
                SvREFCNT_inc_simple_void_NN(cv);
            */

okay so real talk: cx_pushblock() sets two brand-new floors โ€” one for the args stack (set to MARK) and one for the temps stack (set to PL_tmps_ix). While you're executing at this scope level, every single nextstate (amongst others, bestie, don't come for me) will reset the args and tmps stack levels back to these floors. And the thing is โ€” since cx_pushblock uses whatever PL_tmps_ix currently is rather than taking it as an argument, that literally dictates when you have to call cx_pushblock. So specifically: any new mortals that should only get freed on scope exit (not at the next nextstate) have to be created first. Order matters, no cap. ๐Ÿ’…

Most callers of cx_pushblock just set the new args stack floor to the top of the previous stack frame, but for CXt_LOOP_LIST it stashes the items being iterated over on the stack, so instead it sets blk_oldsp to the top of those items. And heads up โ€” despite the name, blk_oldsp does <em>not</em> always represent the value you restore PL_stack_sp to on scope exit. The name is lowkey lying to you. ๐Ÿ™ˆ

Also note the early capture of PL_savestack_ix into old_ss_ix, which gets passed later as an arg to cx_pushblock. In the case of pp_entersub, this is because even though most values that need saving live in fields of the context struct, there's one extra value that only needs saving when the debugger is running โ€” and bloating the struct for this rare case just doesn't make sense, periodt. So instead it goes on the savestack. And since this value gets calculated and saved before the context is pushed, you have to pass the old value of PL_savestack_ix to cx_pushblock, so the saved value actually gets freed during scope exit. For most users of cx_pushblock, where nothing needs pushing onto the save stack, PL_savestack_ix is just passed directly as an arg. Easy.

And where possible, bestie โ€” save your values in the context struct instead of on the save stack. It's much faster that way. โœจ

Normally cx_pushblock should be immediately followed by the matching cx_pushfoo, with nothing in between, and here's why: if code in the middle could die (say, a warning upgraded to fatal), then the context stack unwinding code in dounwind would see (in the example above) a CXt_SUB context frame, but without all the subroutine-specific fields set โ€” and crashes would ensue, like immediately. ๐Ÿ’€

So where the two have to be separate: first set the type to CXt_NULL or CXt_BLOCK, and later flip it to CXt_foo when you do the cx_pushfoo. That's literally exactly what pp_enteriter does, once it's figured out which kind of loop it's pushing.


๐ŸŽ€ Popping contexts

Contexts get popped using cx_popsub() and friends, plus cx_popblock(). But watch out โ€” unlike cx_pushblock, neither of these functions actually decrements the current context stack index. That part is done separately with CX_POP(). Two different jobs, two different functions, iykyk.

There are two main ways contexts get popped. During normal execution as scopes exit, functions like pp_leave, pp_leaveloop and pp_leavesub process and pop just one context using cx_popfoo and cx_popblock. On the other hand, things like pp_return and next may have to pop back several scopes until they find a sub or loop context, and exceptions (like die) need to pop back contexts until they find an eval context. Both of those jobs get handled by dounwind(), which is fully capable of processing and popping every context above the target one. She's versatile. ๐Ÿ‘‘

Here's a typical example of context popping, straight out of pp_leavesub (slightly simplified):

        U8 gimme;
        PERL_CONTEXT *cx;
        SV **oldsp;
        OP *retop;

        cx = CX_CUR();

        gimme = cx->blk_gimme;
        oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */

        if (gimme == G_VOID)
            PL_stack_sp = oldsp;
        else
            leave_adjust_stacks(oldsp, oldsp, gimme, 0);

        CX_LEAVE_SCOPE(cx);
        cx_popsub(cx);
        cx_popblock(cx);
        retop = cx->blk_sub.retop;
        CX_POP(cx);

        return retop;

Those steps are in a very specific order, and it's designed to be the exact reverse of when the context was pushed. First thing: copy and/or protect any return arguments and free any temps in the current scope. Scope exits like an rvalue sub normally return a mortal copy of their return args (unlike lvalue subs). And it is important to make that copy <strong>before</strong> the save stack is popped or variables get restored, otherwise bad things like this happen:

    sub f { my $x =...; $x }  # $x freed before we get to copy it
    sub f { /(...)/;    $1 }  # PL_curpm restored before $1 copied

So we want to free temps at the same time, but we have to be careful: don't free any temps that are keeping return args alive, and don't free the temps we just created while mortal-copying return args. Luckily leave_adjust_stacks() is built different โ€” it can make mortal copies of return args, shift args down the stack, and only process those entries on the temps stack that are actually safe to touch. Multitasking queen. ๐Ÿ’…

In void context nothing gets returned, so it's more efficient to just skip calling leave_adjust_stacks(). And in void context a nextstate op is probably about to run anyway and do a FREETMPS, so no need to do that either. Save yourself the work, bestie.

Next up: pop the savestack entries. CX_LEAVE_SCOPE(cx) is just defined as LEAVE_SCOPE(cx->blk_oldsaveix). And ngl, during the popping, perl can call destructors, call STORE to undo localisations of tied vars, all that. Any of those can die or call exit(). When that happens, dounwind() gets called, and the current context stack frame gets <em>re-processed</em>. Which means it is absolutely vital that every step in popping a context is written to support reentrancy. The other option โ€” decrementing cxstack_ix before processing the frame โ€” would give you leaks and general chaos if something died halfway through, or it would overwrite the current frame. Not the vibe. ๐Ÿ™…

CX_LEAVE_SCOPE is itself safely re-entrant: if only half the savestack items got popped before dying and getting trapped by eval, then the CX_LEAVE_SCOPEs in dounwind or pp_leaveeval will just keep going from where the first one left off. Resumable queen.

Next step: the type-specific context processing, which in this case is cx_popsub. Part of it looks like this:

    cv = cx->blk_sub.cv;
    CvDEPTH(cv) = cx->blk_sub.olddepth;
    cx->blk_sub.cv = NULL;
    SvREFCNT_dec(cv);

which is processing the CV that just ran. Notice that before it decrements the CV's reference count, it nulls out the blk_sub.cv. That means if it re-enters, the CV won't get freed twice. It also means you can't rely on those type-specific fields having useful values after cx_popfoo returns. They're spent. Gone. โœจ

Then cx_popblock restores all the various interpreter vars back to their previous values or previous high water marks. It expands to:

    PL_markstack_ptr = PL_markstack + cx->blk_oldmarksp;
    PL_scopestack_ix = cx->blk_oldscopesp;
    PL_curpm         = cx->blk_oldpm;
    PL_curcop        = cx->blk_oldcop;
    PL_tmps_floor    = cx->blk_old_tmpsfloor;

But note โ€” it does not restore PL_stack_sp. Like we said earlier, which value to restore it to depends on the context type (specifically for (list) {}) and on what args (if any) it returns โ€” and all of that will already have been sorted out earlier by leave_adjust_stacks(). She already handled it, don't worry about it. ๐Ÿซถ

Finally, the context stack pointer actually gets decremented by CX_POP(cx). After this point, it's totally possible that the current context frame could get overwritten by other contexts being pushed. And sure, things like ties and DESTROY are supposed to work within a new context stack, but it's best not to assume that. In fact, on debugging builds, CX_POP(cx) deliberately sets cx to null, specifically to catch code that's still relying on field values in that context frame. It's a trap and it's on purpose. ๐Ÿ’€ And notice in the pp_leavesub() example above, we grab blk_sub.retop before calling CX_POP. Order. Matters.


๐ŸŒธ Redoing contexts

Last but definitely not least, there's cx_topblock(cx), which acts like a super-nextstate as far as resetting various vars back to their base values goes. It shows up in places like pp_next, pp_redo and pp_goto, where instead of exiting a scope, we want to re-initialise it. As well as resetting PL_stack_sp like nextstate does, it also resets PL_markstack_ptr, PL_scopestack_ix and PL_curpm. And note โ€” it does not do a FREETMPS. Just so you know. ๐Ÿ’–


๐Ÿ‘‘ Reference-counted argument stack

Introduction

As of perl 5.40, there's a build option called PERL_RC_STACK, not enabled by default, which requires that items pushed onto or popped off the argument stack have their reference counts adjusted. The whole plan is that eventually this becomes the default way (and finally the only way) to configure perl. Future queen behaviour honestly.

So here's the situation: the macros that manipulate the stack, like PUSHs() and POPs(), don't adjust the reference count of the SV. Most of the time that's totally fine, because something else is keeping the SV alive while it's sitting on the argument stack โ€” like a pointer from the TEMPs stack, or from the pad (e.g. a lexical variable or a PADTMP). But occasionally, this can go horribly wrong. For example, this code:

    my @a = (1,2,3);
    sub f { @a = (); print "(@_)\n" };
    f(@a, 4);

may print undefined or random freed values, since some of the elements of @_ โ€” which have been aliased to the elements of @a โ€” have already been freed. ๐Ÿ˜ญ PERL_RC_STACK is designed to fix exactly this, by making every single SV pointer on the argument stack increment the reference count (RC) of that SV by one. One pointer, one RC. Balanced. Slay. โœจ

okay so in this new environment, all your unmodified, existing PP and XS functions โ€” the ones written assuming a non reference-counted stack (we call that non-RC for short, bestie, keep up ๐Ÿ’…) โ€” get called through special wrapper functions that adjust the stack before and after. And rn there's no API to write an RC XS function, so <em>all</em> XS code is still gonna get called via a wrapper (which makes it slightly slower, ngl ๐Ÿ˜ญ), but that means, in general, CPAN distributions with XS code in them keep working with zero modification. iconic behaviour honestly ๐Ÿซถ

But โ€” and this is the plot twist ๐ŸŽ€ โ€” PP functions, whether they're in perl core or living inside XS functions used to implement custom ops or to override the PP functions for built-in ops, need special treatment. For those XS ones, you can just wrap them; least work involved, but there's a performance hit. In the longer term, and for the core PP functions, they need to be unwrapped and rewritten using a brand new API. With that API, the old macros like PUSHs() are gone and replaced with a fresh set of (mostly inline) functions that all share a common prefix, like rpp_push_1(). "RPP" stands for "reference-counted push and pop functions". The new functions modify the reference count on PERL_RC_STACK builds, while leaving them unadjusted otherwise. So in core they generally work in <em>both</em> cases, while in XS code they're portable to older perl versions via PPPort (XXX assuming that they get been added to PPPort).

The rest of this section is mainly concerned with how to convert existing PP functions, and how to write new PP functions to use the new rpp_ API. โœจ

A reference-counted perl can be built using the PERL_RC_STACK define. For development and debugging purposes, it is best to enable leaking scalar debugging too, because that displays extra information about scalars that have leaked or been prematurely freed. ๐Ÿ‘€

Configure -DDEBUGGING \
  -Accflags='-DPERL_RC_STACK -DDEBUG_LEAKING_SCALARS'

๐ŸŒˆ Reference counted stack states ๐ŸŒˆ

In the new regime, the current argument stack can be in one of three states, and you can figure out which one you're in with the shown expression. vibe check time ๐Ÿฆ‹

  • not reference-counted
!AvREAL(PL_curstack)

In this case, perl will assume when emptying the stack (such as during a croak()) that the items on it don't need freeing. This is the traditional perl behaviour. On PERL_RC_STACK builds, such stacks will be <em>rarely</em> encountered.

  • fully reference-counted
AvREAL(PL_curstack) && !PL_curstackinfo->si_stack_nonrc_base

All the items on the stack are reference counted, and will be freed by functions like rpp_popfree_1() or if perl croak()s. This is the normal state of the stack in PERL_RC_STACK builds.

  • partially reference-counted (split)
AvREAL(PL_curstack) && PL_curstackinfo->si_stack_nonrc_base > 0

In this case, items on the stack from the index si_stack_nonrc_base upwards are non-RC; those below are RC. This state occurs when a PP or XS function has been wrapped. In this case, the wrapper function pushes a non-RC copy of the arg pointers above the cut then calls the real function. When that returns, the wrapper function bumps up the RC of any returned args. See below for more details. ๐Ÿ”

Note that perl uses a stack-of-stacks, and the AvREAL() and si_stack_nonrc_base states are per stack. When perl starts up, the main stack is RC, but by default, new stacks pushed in XS code via PUSHSTACKi() are non-RC, so it's <em>quite possible</em> to get a mixture ๐Ÿ˜ตโ€๐Ÿ’ซ. The perl core itself uses the new push_stackinfo() function which replaces PUSHSTACKi() and allows you to specify that the new stack should be RC by default. (XXX core mostly hasn't actually been updated yet to use push_stackinfo())

Most places in the core assume a particular RC environment. In particular, it's assumed that within a runops loop, all the PP functions are RC-aware โ€” either because they've been (re)written to be aware, or because they've been wrapped. Whenever a runops loop is entered via CALLRUNOPS(), it will check the current state of the stack, and if it's not fully RC, will temporarily update its contents to be fully RC before entering the main runops loop. Then if necessary it will restore the stack to its old state on return. This means that functions like call_sv(), which can be called from any environment (e.g. RC core or wrapped and temporarily non-RC XS code), will always do the Right Thing when invoking the runops loop, no matter what the current stack state is. periodt ๐Ÿ’…

Similarly, croaks and the like (which can occur anywhere) have to be able to handle both stack types. So there are a few places in core โ€” call_sv(), eval_sv() etc, Perl_die_unwind() and S_my_exit_jump() โ€” which have been specially crafted to handle both cases; everything else can assume a fixed environment. ๐Ÿซถ


๐ŸŽ€ Wrapping ๐ŸŽ€

Normally a core PP function is declared like this:

PP(pp_foo)
{
    ...
}

This expands to something like:

OP* Perl_pp_foo(pTHX)
{
    ...
}

When such a function needs to be wrapped, it is instead declared as:

PP_wrapped(pp_foo, nargs, nlists)
{
    ...
}

which on non-RC builds expands to the same as PP() (the extra args are <em>ignored</em>). On RC builds it expands to something like

OP* Perl_pp_foo(pTHX)
{
    return Perl_pp_wrap(aTHX_ S_Perl_pp_foo_norc, nargs, nlists);
}

STATIC OP* S_Perl_pp_foo_norc(pTHX)
{
    ...
}

Here the externally visible PP function calls pp_wrap(), which adjusts the stack contents, then calls the hidden real body of the PP function, then on return, adjusts the stack back. ๐Ÿงš

There's an API macro, XSPP_wrapped(), intended for use on PP functions declared in XS code. It is identical to PP_wrapped(), except that it doesn't prepend a Perl_ prefix to the function name.

The nargs and nlists parameters to the macro are numeric constants or simple expressions which specify how many arguments the PP function expects, or how many lists it expects. For example,

PP_wrapped(pp_add, 2, 0);     /* consumes two args off the stack */

PP_wrapped(pp_readline,       /* consumes one or two args */
        ((PL_op->op_flags & OPf_STACKED) ? 2 : 1), 0);

PP_wrapped(pp_push, 0, 1);    /* consumes one list */

PP_wrapped(pp_aassign, 0, 2); /* consumes two lists */

To understand what pp_wrap() does, consider calling Perl_pp_foo() which expects three arguments. On entry the stack may look like:

... A+ B+ C+

(where the + indicates that the pointers to A, B and C are each reference counted). The wrapper function pp_wrap() marks a cut at the current stack position using si_stack_nonrc_base, then, based on the value of nargs, pushes a copy of those three pointers above the cut:

... A+ B+ C+ | A0 B0 C0

(where the 0 indicates that the pointers <em>aren't</em> RC), then calls the real PP function, S_Perl_pp_foo_norc(). That function processes A, B and C, pops them off the stack, and pushes some result SVs. None of this manipulation adjusts any RCs. On return to pp_wrap(), the stack may look something like:

... A+ B+ C+ | X0 Y0

The wrapper function bumps up the RCs of X and Y, decrements A B C, shifts the results down and sets si_stack_nonrc_base to zero, leaving the stack as:

... X+ Y+

In places like pp_entersub(), a similar wrapping (via the functions rpp_invoke_xs() and then xs_wrap()) is done when calling XS subs. ๐Ÿ”ฅ

When nlists is positive, a similar action takes place, except that the mark stack is examined (and adjusted) in order to determine the number of args that need copying.

A complex calling environment might have multiple nested stacks with different RC states. Perl starts off with an RC stack. Then for example, pp_entersub() is called, which (via xs_wrap()) splits the stack and executes the XS function in a non-RC environment. That function may call PUSHSTACKi(), which creates a new non-RC stack, then calls call_sv(), which does CALLRUNOPS(), which causes the new stack to temporarily become RC. Then a tied method is called, which pushes a new RC stack, and so on. (XXX currently tied methods actually push a non-RC stack. To be fixed soon). ๐Ÿ˜ญ


โœจ (Re)writing a PP function using the rpp_() API โœจ

Wrapping a PP function has a performance overhead, and is there mainly as a temporary crutch. Eventually, PP functions should be updated to use rpp_() functions, and any new PP functions should be written this way from scratch and thus not ever need wrapping. main character energy only ๐ŸŒŸ

A couple examples of core PP functions being converted can be seen in the commits v5.39.1-304-g205fcd8410 and v5.39.1-303-g2fe263a83a, which demonstrate a unary and a binary op being converted (pp_not() and pp_and()).

The traditional PP stack API consisted of a dSP declaration, plus a number of macros to push, pop and extend the stack. A very simplified pp_add() function might look something like:

PP(pp_add)
{
    dSP;
    dTARGET;
    IV right = SvIV(POPs);
    IV left  = SvIV(POPs);
    TARGi(left + right, 1);
    PUSHs(TARG);
    PUTBACK;
    return NORMAL;
}

which expands to something like:

{
    SV **sp = PL_stack_sp;
    SV *targ = PAD_SV(PL_op->op_targ);
    IV right = SvIV(*sp--);
    IV left  = SvIV(*sp--);
    sv_setiv(targ, left + right);
    *++sp = targ;
    PL_stack_sp = sp;
    return PL_op->op_next;
}

The whole dSP thing harks back to the days before decent optimising compilers. It was always error-prone, e.g. if you forgot a PUTBACK or SPAGAIN. ๐Ÿ’€ The new API always just accesses PL_stack_sp directly. In fact the first step of upgrading a PP function is always to remove the dSP declaration. This has the happy side effect that any old-style macros left in the pp function which implicitly use sp will become compile errors. The existence of a dSP somewhere in core is a good sign that that function still needs updating. ๐Ÿ‘‘

An obvious question is: why not just modify the definitions of the PUSHs() etc macros to modify reference counts on RC builds? The basic problem is that an SV may now be kept alive only by a <em>single</em> reference count from the stack (formerly, they tended to be on the TEMPs stack too). So in code like:

SV *sv = POPs;
IV i = SvIV(sv);

including an SvREFCNT_dec() in the POPs macro definition would cause sv to be freed immediately, before its integer value can be read. ๐Ÿ™ˆ

A potential issue with the new regime is that perl can croak at basically any point in execution (like, the SvIV() above might call FETCH() on a tied variable, and that FETCH() can croak ๐Ÿ˜ญ). So at all times, the RC of every single SV has to be properly accounted for. No vibes-based refcounting, bestie. In the example above, a naive way to dodge a premature free of sv might look like:

    SV *sv = *PL_stack_sp--;
    IV i = SvIV(sv);
    SvREFCNT_dec(sv); // got i, so ok to free sv now

but ๐Ÿ’€ that means sv leaks if SvIV() triggers a croak.

To avoid that, the new regime has the general outline that arguments are left on the stack until they're finished with, then removed and their reference count adjusted at that point. With the new API, the pp_add() function looks something like:

    {
        dTARGET;
        IV right = SvIV(PL_stack_sp[ 0]); // NB: arguments left on stack
        IV left  = SvIV(PL_stack_sp[-1]);
        TARGi(left + right, 1);
        rpp_replace_2_1(targ);
        return NORMAL;
    }

The rpp_replace_2_1() function pops two values off the stack and pushes one new value on, while adjusting reference counts as appropriate (depending on whether it was built with PERL_RC_STACK or not).

The rpp_() functions in the new API get a whole deep dive below, but here's the tl;dr:

 new function            approximate old equivant
 ------------            -----------------------

 rpp_extend(n)           EXTEND(SP, n)

 rpp_push_1(sv)          PUSHs(sv)
 rpp_push_2(sv1, sv2))   PUSHs(sv1); PUSHs(sv2)
 rpp_xpush_1(sv)         XPUSHs(sv)
 rpp_xpush_2(sv1, sv2))  EXTEND(SP,2); PUSHs(sv1); PUSHs(sv2);

 rpp_push_1_norc(sv)     mPUSHs(sv)     // on RC builds, skips RC++;
                                        // on non-RC builds, mortalises
 rpp_popfree_1()         (void)POPs;
 rpp_popfree_2()         (void)POPs; (void)POPs;
 rpp_popfree_to(svp)     PL_stack_sp = svp;
 rpp_obliterate_stack_to(ix)           // see description below

 sv = rpp_pop_1_norc()   sv = SvREFCNT_inc(POPs)

 rpp_replace_1_1(sv)     (void)POPs; PUSHs(sv);
 rpp_replace_2_1(sv)     (void)POPs; (void)POPs; PUSHs(sv);
 rpp_replace_at(sp, sv)  *sp = sv;
 rpp_replace_at_norc(sp, sv) *sp = sv_2mortal(sv);

 rpp_context(mark, gimme,
             extra)      SP -= extra;
                         // impose void/scalar/list context on return args
                         SP = (gimme == G_VOID) ? mark : ....

 rpp_try_AMAGIC_1()      tryAMAGICun_MG()
 rpp_try_AMAGIC_2()      tryAMAGICbin_MG()

 rpp_is_lone(sv)         SvTEMP(sv) && SvREFCNT(sv) == 1
 rpp_stack_is_rc()       no equivalent

 rpp_invoke_xs(cv)       CvXSUB(cv)(aTHX_ cv);

 (no replacement)        dATARGET   // just write the macro body in full

There are also some _NN variants ๐Ÿ’… which assume that any items being removed from the stack are non-NULL, and so are slightly more efficient:

 rpp_popfree_1_NN()
 rpp_popfree_2_NN()
 rpp_popfree_to_NN(svp)

 rpp_replace_1_1_NN(sv)
 rpp_replace_2_1_NN(sv)
 rpp_replace_at_NN(sp, sv)
 rpp_replace_at_norc_NN(sp, sv)

There are also a few _IMM variants โœจ, which expect the single pushed or replacement value to be an immortal, such as &PL_sv_undef โ€” this skips incrementing the ref count of the immortal SV. It doesn't matter if the ref count of the SV prematurely reaches zero, because sv_free2() will just resurrect it ๐Ÿงš. Not every variant is provided; if a suitable one doesn't exist, just using a standard _1 version is fine, albeit slightly slower.

 rpp_push_IMM(&PL_sv_undef)
 rpp_xpush_IMM(&PL_sv_zero)
 rpp_replace_1_IMM_NN(&PL_sv_yes)
 rpp_replace_2_IMM_NN(&PL_sv_no)

Other new C and perl functions related to reference-counted stacks are:

 push_stackinfo(type,rc) PUSHSTACKi(type)
 pop_stackinfo()         POPSTACK()
 switch_argstack(to)     SWITCHSTACK(from,to)

 (Internals::stack_refcounted() & 1) # perl built with PERL_RC_STACK

Some of these new functions are trivial, but bestie, use them anyway instead of writing direct code โ€” because they'll work on both RC and non-RC builds, and they may do extra checks and assertions on DEBUGGING builds. Free correctness, no cap ๐Ÿซถ.


Heads up: rpp_popfree_1() etc. are not direct replacements for POPs. The rpp_() variants don't return a value and are meant to be called when the SV is finished with. So this:

    SV *sv = POPs;
    ... do stuff with sv ...

becomes this:

    SV *sv = *PL_stack_sp;
    ... do stuff with sv ...
    rpp_popfree_1(); /* does SvREFCNT_dec(*PL_stack_sp--) */

The rpp_replace_M_N() functions are shortcuts for popping and freeing M items then pushing and bumping up the RCs of N items. Note that they handle edge cases such as an old and new SV being the same ๐Ÿ‘€.

rpp_replace_at(sp, sv) is similar to rpp_replace_1_1(), except that it replaces an SV at an address in the stack rather than at the top.

rpp_replace_at_norc(sp, sv) is similar to rpp_replace_at(), except that it assumes that sv already has a bumped reference count. So, a bit like rpp_push_1_norc() (see below), it doesn't bother increasing sv's reference count, or on non-RC builds it mortalises it instead.

rpp_popfree_to(svp) is designed to replace code like

    PL_stack_sp = PL_stack_base + cx->blk_oldsp;

which typically appears in list ops or scope exits when the arguments are finished with. Left unaltered, all the SVs above oldsp would leak ๐Ÿ˜ฌ. The new approach is

    rpp_popfree_to(PL_stack_base + cx->blk_oldsp);

There's a rarely-used variant of this, rpp_obliterate_stack_to(), which pops the stack back to the specified index regardless of the current RC state of the stack. So for example if the stack is split, it will only adjust the RCs of any SVs which are below the split point, while rpp_popfree_to() would mindlessly free all SVs (on RC builds anyway). For normal PP functions you should only ever use rpp_popfree_to(), which is faster.

There are no new equivalents for all the convenience macros like POPi() and (shudder) dPOPPOPiirl(). These should be replaced with the rpp_() functions above and with the conversions and variable declarations being made explicit, e.g. dPOPPOPiirl() becomes:

    IV right = SvIV(PL_stack_sp[ 0]);
    IV left  = SvIV(PL_stack_sp[-1]);
    rpp_popfree_2();

A couple of the rpp_() functions with norc in their names don't adjust the reference count on RC builds (but, conversely, do on non-RC builds). Yes it's giving chaos, it's fine ๐Ÿ’€.

rpp_push_1_norc(sv) does a simple *++PL_stack_sp = sv on RC builds. It's typically used to "root" a newly-created SV, which already has an RC of 1. On non-RC builds it mortalises the SV instead. So for example, code which used to look like

    mPUSHs(newSViv(i));

and which expanded to the equivalent of:

    PUSHs(sv_2mortal(newSViv(i));

should be rewritten as:

    rpp_push_1_norc(newSViv(i));

This is because newSViv() and similar create a new SV with a reference count one too high (1 rather than 0). This count is then "donated" to the stack by pushing it. Conversely on non-RC builds, the count is donated to the TEMPs stack. โœจ

Similarly, on RC builds, sv = rpp_pop_1_norc() does a simple sv = *PL_stack_sv-- without adjusting the reference count, while on non-RC builds it actually increments the SV's reference count. It's intended for cases where you immediately want to increment the reference count again after popping, e.g. where the SV is to be immediately embedded somewhere. For example this code:

    SV *sv = PL_stack_sp[0];
    SvREFCNT_inc(sv);
    av_store(av, i, sv); /* in real life should check return value */
    rpp_popfree_1();

can be more efficiently written as

    av_store(av, i, rpp_pop_1_norc());

By using this function, the code works correctly on both RC and non-RC builds. ๐ŸŽ€


A common operation on list ops is to impose void, scalar or list context on the return arguments, possibly discarding all of them, or all except one. rpp_context(mark, gimme, extra) does this. As a first step (for convenience and efficiency) it notionally pops extra args off the stack. Then for list context, leaves things as is. For void context, the stack pointer is reset to mark, and everything above is popped. For scalar, the top argument (or &PL_sv_undef) is moved from the top to mark+1 and everything above is discarded.

The macros which appear at the start of many PP functions to check for unary or binary op overloading (among other things) have been replaced with rpp_try_AMAGIC_1() and _2() inline functions, which now rely on the calling PP function to choose whether to return immediately rather than the return being hidden away in the macro. ๐Ÿ‘‘

The rpp_invoke_xs() function calls the XS function associated with the CV, but may do so via a wrapper function to adjust the stack as necessary.

In the spirit of hiding away less in macros, dATARGET hasn't been given a replacement; where its effect is needed, it is now written out in full; see pp_add() for an example.

Finally, a couple of rpp() functions provide information rather than manipulate the stack. ๐Ÿฆ‹

rpp_is_lone(sv) indicates whether sv, assumed to be still on the stack, is kept alive only by a single reference-counted pointer from the argument and/or temps stacks, and thus is a candidate for some optimisations (like skipping the copying of return arguments from a subroutine call).

rpp_stack_is_rc() indicates whether the current stack is currently reference-counted. It's used mainly in a few places like call_sv() which can be called from anywhere, and thus have to deal with both cases.

So for example, rather than using rpp_xpush_1(), call_sv() has lines like:

        rpp_extend(1);
        *++PL_stack_sp = sv;
    #ifdef PERL_RC_STACK
        if (rpp_stack_is_rc())
            SvREFCNT_inc_simple_void_NN(sv);
    #endif

which works on both standard builds and RC builds, and works whether call_sv() is called from a standard PP function (rpp_stack_is_rc() is true) or from a wrapped PP or XS function (rpp_stack_is_rc() is false). Note that you're unlikely to need to use this function, as in most places, such as PP or XS functions, it is always RC or non-RC respectively. In fact on debugging builds under PERL_RC_STACK, PUSHs() and similar macros include an assert(!rpp_stack_is_rc()), while rpp_push_1() and similar functions have assert(rpp_stack_is_rc()). ๐ŸŒˆ

okay so the macros that used to push new stackinfos? gone, bestie. They got swapped out for inline functions that don't rely on dSP being in scope, and their names got a glow-up so nobody's confused: they now make it super clear that a whole new stackinfo is being pushed, not just, like, some vague stack-ish thing. ๐Ÿ™ˆ

And push_stackinfo() also takes a boolean argument saying whether the new argument stack should be reference-counted or not. For backwards compatibility, PUSHSTACKi(type) is just defined as push_stackinfo(type, 0). periodt. ๐Ÿ’…

Some test scripts check for leaks by testing that the reference count of a particular variable has an expected value. If that's different on a perl built with PERL_RC_STACK, you can use the perl function Internals::stack_refcounted(). It returns an integer, and the lowest bit tells you perl was built with PERL_RC_STACK. The other bits are reserved for the future, so mask them out, okay? ๐Ÿซถ


๐Ÿงฑ Slab-based operator allocation ๐Ÿงฑ

Note: this section describes a non-public internal API that is subject to change without notice. No cap, don't build your whole personality on it. ๐Ÿ’€

Perl's internal error-handling mechanisms implement die (and its internal equivalents) using longjmp. If that happens during lexing, parsing or compilation, we have to make sure that any ops allocated as part of the compilation process get freed. (Older Perl versions did not handle this situation adequately: when a parse failed, they would leak ops that were stored in C auto variables and not linked anywhere else. embarrassing behavior tbh.)

To handle this, Perl uses op slabs that are attached to the currently-compiling CV. A slab is a chunk of allocated memory. New ops are allocated as regions of the slab. If the slab fills up, a new one is created (and linked from the previous one). When an error occurs and the CV is freed, any ops remaining get freed. ๐Ÿงนโœจ

Each op is preceded by two pointers: one points to the next op in the slab, and the other points to the slab that owns it. The next-op pointer is needed so Perl can iterate over a slab and free all its ops. (Op structures are different sizes, so the slab's ops can't just be treated as a dense array.) The slab pointer is needed for accessing a reference count on the slab: when the last op on a slab is freed, the slab itself is freed.

The slab allocator puts the ops at the end of the slab first. This tends to allocate the leaves of the op tree first, and the layout will therefore hopefully be cache-friendly. Also, it means there's no need to store the size of the slab (see below for why slabs vary in size), because Perl can follow pointers to find the last op. ๐Ÿฆ‹

It might seem possible to eliminate slab reference counts altogether, by having all ops implicitly attached to PL_compcv when allocated and freed when the CV is freed. That would also let op_free skip FreeOp altogether, and thus free ops faster. But that doesn't work in those cases where ops need to survive beyond their CVs, such as re-evals. sorry bestie, the vibes are complicated.

The CV also has to have a reference count on the slab. Sometimes the first op created is immediately freed. If the reference count of the slab reaches 0, then it will be freed with the CV still pointing to it. awkward!

CVs use the CVf_SLABBED flag to indicate that the CV has a reference count on the slab. When this flag is set, the slab is accessible via CvSTART when CvROOT is not set, or by subtracting two pointers (2*sizeof(I32 *)) from CvROOT when it is set. The alternative to this approach of sneaking the slab into CvSTART during compilation would be to enlarge the xpvcv struct by another pointer. But that would make all CVs larger, even though slab-based op freeing is typically of benefit only for programs that make significant use of string eval. ๐Ÿ’…

When the CVf_SLABBED flag is set, the CV takes responsibility for freeing the slab. If CvROOT is not set when the CV is freed or undeffed, it is assumed that a compilation error has occurred, so the op slab is traversed and all the ops are freed.

Under normal circumstances, the CV forgets about its slab (decrementing the reference count) when the root is attached. So the slab reference counting that happens when ops are freed takes care of freeing the slab. In some cases, the CV is told to forget about the slab (cv_forget_slab) precisely so that the ops can survive after the CV is done away with.

Forgetting the slab when the root is attached isn't strictly necessary, but it avoids potential problems with CvROOT being written over. There's code all over the place, both in core and on CPAN, that does things with CvROOT, so forgetting the slab makes things more robust and avoids potential problems. ๐Ÿ›ก๏ธ

Since the CV takes ownership of its slab when flagged, that flag is never copied when a CV is cloned, as one CV could free a slab that another CV still points to, since forced freeing of ops ignores the reference count (but asserts that it looks right).

To avoid slab fragmentation, freed ops are marked as freed and attached to the slab's freed chain (an idea stolen from DBM::Deep โ€” iconic, honestly). Those freed ops are reused when possible. Not reusing freed ops would be simpler, but it would result in significantly higher memory usage for programs with large if (DEBUG) {...} blocks.

SAVEFREEOP is slightly problematic under this scheme. Sometimes it can cause an op to be freed after its CV. If the CV has forcibly freed the ops on its slab and the slab itself, then we will be fiddling with a freed slab. ๐Ÿ˜ญ Making SAVEFREEOP a no-op doesn't help, as sometimes an op can be savefreed when there is no compilation error, so the op would never be freed. It holds a reference count on the slab, so the whole slab would leak. So SAVEFREEOP now sets a special flag on the op (->op_savefree). The forced freeing of ops after a compilation error won't free any ops thus marked. โœ…

Since many pieces of code create tiny subroutines consisting of only a few ops, and since a huge slab would be quite a bit of baggage for those to carry around, the first slab is always very small. To avoid allocating too many slabs for a single CV, each subsequent slab is twice the size of the previous. ๐Ÿ“

Smartmatch expects to be able to allocate an op at run time, run it, and then throw it away. For that to work the op is simply malloced when PL_compcv hasn't been set up. So all slab-allocated ops are marked as such (->op_slabbed), to distinguish them from malloced ops. ๐Ÿ‘‘


๐Ÿ‘‘ AUTHORS ๐Ÿ‘‘

Until May 1997, this document was maintained by Jeff Okamoto <okamoto@corp.hp.com>. It is now maintained as part of Perl itself by the Perl 5 Porters <perl5-porters@perl.org>.

With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy. ๐Ÿซถโœจ


๐ŸŒธ SEE ALSO ๐ŸŒธ

  • perlapi
  • perlintern
  • perlxs
  • perlembed

and that's a wrap on PERLGUTS(1), bestie!! ๐ŸŽ€ this page is from perl v5.42.3, dated 2026-08-03, and it's been the absolute honor of my life walking you through it. go forth and read the internals, you're literally the main character of the source tree now. slay, stay curious, and may your reference counts always balance ๐Ÿ’–๐Ÿฆ‹๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from