ee L. =head2 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 apidoc_section $casting =for apidoc Amh|type|INT2PTR|type|int value =for apidoc Amh|UV|PTR2UV|void * ptr =for apidoc Amh|IV|PTR2IV|void * ptr =for apidoc Amh|NV|PTR2NV|void * ptr 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 */ =for apidoc Amh|IV|PTR2nat|void * =for apidoc Amh|unsigned long|PTR2ul|void * And C which gives the native type for an integer the same size as pointers, such as C or C. =for apidoc Ayh|type|PTRV =head2 Exception Handling There are a couple of macros to do very basic exception handling in XS modules. You have to define C before including F 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 C function. The advantage of using the above macros is that you don't have to setup an extra function for C, and that using these macros is faster than using C. =head2 Source Documentation There's an effort going on to document the internal functions and automatically produce reference manuals from them -- L is one such manual which details all the functions which are available to XS writers. L 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. =cut */ Please try and supply some documentation if you add functions to the Perl core. =head2 Backwards compatibility The Perl API changes over time. New functions are added or the interfaces of existing functions are changed. The C 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. C generates a C header file F that can also be run as a Perl script. To generate F, 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 C<--api-info> command line switch. For example: % perl ppport.h --api-info=sv_magicext For details, see S>. =head1 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. =head2 What B 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 this, some people formed Unicode, Inc. and produced a 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 L. (On EBCDIC platforms, Perl uses instead UTF-EBCDIC, 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.) =head2 How can I recognise a UTF-8 string? You can't. This is because UTF-8 data is stored in bytes just like non-UTF-8 data. The Unicode character 200, (C<0xC8> for you hex types) capital E with a grave accent, is represented by the two bytes C. Unfortunately, the non-Unicode string C 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 C 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, C will tell you whether the current character in a string is valid UTF-8. =head2 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 C; this continues up to character 191, which is C. Now we've run out of bits (191 is binary C<10111111>) so we move on; character 192 is C. And so it goes on, moving to three bytes at character 2048. L 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 C 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 C, 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 C 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 C to get the value of the character; the inverse function C 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 B 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 C, and you skip that character, you can never match a C 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 its faster to avoid the function overhead when it's not needed.) =head2 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, C, 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 C or immediately after stringification via C 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, C, C 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 C 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 C 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 (I the C 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 C 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 S> to an XS function. For full generality, use the L|perlapi/DO_UTF8> macro to see if the string in an SV is to be I as UTF-8. This takes into account if the call to the XS function is being made from within the scope of L>|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 L). 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 L). There is no published API for dealing with this, as it is subject to change, but you can look at the code for C in F for an example as to how it's currently done. =head2 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, C 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 C and related macros. This has the same effect as encoding to UTF-8 then calling the corresponding C-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 C, 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. =head3 What about C, C, etc.? Consider a 3-character Perl string C<$foo = "\x64\x78\x8c">. Perl can store these 3 characters either of two ways: =over =item * bytes: 0x64 0x78 0x8c =item * UTF-8: 0x64 0x78 0xc2 0x8c =back Now let's say you convert C<$foo> to a C string thus: STRLEN strlen; char *str = SvPV(foo_sv, strlen); At this point C could point to a 3-byte C string or a 4-byte one. Generally speaking, we want C to be the same regardless of how Perl stores C<$foo>, so the ambiguity here is undesirable. C and C solve that by giving predictable output: use C if your C library expects byte strings, or C if it expects UTF-8. If your C library happens to support both encodings, then C--always in tandem with lookups to C!--may be safe and (slightly) more efficient. B B Use L's C and C functions in your tests to ensure consistent handling regardless of Perl's internal encoding. =head2 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, C will give you a UTF-8-encoded B of its string argument. This is useful for having the data available for comparisons and so on, without harming the original SV. There's also C to go the other way, but naturally, this will fail if the string contains any characters above 255 that can't be represented in a single byte. =head2 How do I compare strings? L and L do a lexigraphic comparison of two SV's, and handle UTF-8ness properly. Note, however, that Unicode specifies a much fancier mechanism for collation, available via the L module. To just compare two strings for equality/non-equality, you can just use L|perlapi/memEQ> and L|perlapi/memEQ> as usual, except the strings must be both UTF-8 or not UTF-8 encoded. To compare two strings case-insensitively, use L|perlapi/foldEQ_utf8> (the strings don't have to have the same UTF-8ness). =head2 Is there anything else I need to know? Not really. Just remember these things: =over 3 =item * There's no way to tell if a S> or S> string is UTF-8 or not. But you can tell if an SV is to be treated as UTF-8 by calling C on it, after stringifying it with C or a similar macro. And, you can tell if SV is actually UTF-8 (even if it is not to be treated as such) by looking at its C 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. =item * If a string is UTF-8, B use C to get at the value, unless C in which case you can use C<*s>. =item * When writing a character UV to a UTF-8 string, B use C, unless C in which case you can use C<*s = uv>. =item * Mixing UTF-8 and non-UTF-8 strings is tricky. Use C to get a new string which is UTF-8 encoded, and then combine them. =back =head1 Custom Operators Custom operator support is an experimental feature that allows you to define your own ops. This is primarily to allow 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 C.) This feature is implemented as a new op type, C. The Perl core does not "know" anything special about this op type, and so it will not be involved in any optimizations. This also means that you can define your custom ops to be any op structure -- unary, binary, list and so on -- you like. It's important to know what custom operators won't do for you. 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 C block and the C module, or by adding a custom peephole optimizer with the C module. When you do this, you replace ordinary Perl ops with custom ops by creating ops with the type C and the C of your own PP function. This should be defined in XS code, and should look like the PP ops in 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 is possible to have multiple custom ops within the one "logical" op type C, Perl uses the value of C<< o->op_ppaddr >> to determine which custom op it is dealing with. You should create an C structure for each ppaddr you use, set the properties of the custom op with C, and register the structure against the ppaddr using C. A trivial example might look like: =for apidoc_section $optree_manipulation =for apidoc Ayh||XOP 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: =over 4 =item xop_name A short name for your op. This will be included in some error messages, and will also be returned as C<< $op->name >> by the L module, so it will appear in the output of module like L. =item xop_desc A short description of the function of the op. =item xop_class Which of the various C<*OP> structures this op uses. This should be one of the C constants from F, namely =over 4 =item OA_BASEOP =item OA_UNOP =item OA_BINOP =item OA_LOGOP =item OA_LISTOP =item OA_PMOP =item OA_SVOP =item OA_PADOP =item OA_PVOP_OR_SVOP This should be interpreted as 'C' only. The C<_OR_SVOP> is because the only core C, C, can sometimes be a C instead. =item OA_LOOP =item OA_COP =for apidoc_section $optree_manipulation =for apidoc Amnh||OA_BASEOP =for apidoc_item OA_BINOP =for apidoc_item OA_COP =for apidoc_item OA_LISTOP =for apidoc_item OA_LOGOP =for apidoc_item OA_LOOP =for apidoc_item OA_PADOP =for apidoc_item OA_PMOP =for apidoc_item OA_PVOP_OR_SVOP =for apidoc_item OA_SVOP =for apidoc_item OA_UNOP =back The other C constants should not be used. =item xop_peep This member is of type C, which expands to C. If it is set, this function will be called from C when ops of this type are encountered by the peephole optimizer. I is the OP that needs optimizing; I is the previous OP optimized, whose C points to I. =for apidoc_section $optree_manipulation =for apidoc Ayh||Perl_cpeep_t =back C directly supports the creation of custom ops by name. =head1 Stacks Descriptions above occasionally refer to "the stack", but there are in fact 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. =head2 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 C, of type C. =for apidoc_section $stack =for apidoc Amnh||PL_stack_base The head of the stack is C, and points to the most recently-pushed item. =for apidoc Amnh||PL_stack_sp Items are pushed to the stack by using the C macro or its variants described above; C, C, C and the typed versions. Note carefully that the non-C versions of these macros do not check the size of the stack and assume it to be big enough. These must be paired with a suitable check of the stack's size, such as the C macro to ensure it is 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 C calls. As a further performance optimisation, the various C macros all operate using a local variable C, rather than the interpreter-global variable C. This variable is declared by the C macro - though it is normally implied by XSUBs and similar so it is rare you have to consider it directly. Once declared, the C macros will operate only on this local variable, so before invoking any other perl core functions you must use the C macro to return the value from the local C 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 C macro which refreshes the local C value back from the interpreter one. Items are popped from the stack by using the C macro or its typed versions, There is also a macro C that inspects the topmost item without removing it. =for apidoc_section $stack =for apidoc Amnh||TOPs 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 C macros or C to mortalise the xV. =head2 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. This is the 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 C. The base of this stack is pointed to by the interpreter variable C, of type C. =for apidoc_section $stack =for apidoc Amnh||PL_markstack The head of the stack is C, and points to the most recently-pushed item. =for apidoc Amnh||PL_markstack_ptr Items are pushed to the stack by using the C macro. Even though the stack itself stores (value) stack indices as integers, the C macro should be given a stack pointer directly; it will calculate the index offset by comparing to the C variable. Thus almost always the code to perform this is PUSHMARK(SP); Items are popped from the stack by the C macro. There is also a macro C that inspects the topmost item without removing it. These macros return I32 index values directly. There is also the C macro which declares a new SV double-pointer variable, called C, 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 C 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 C. 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, C will equal C. Because the C variable is converted to a pointer on the value stack, extra care must be taken if C or any of the C macros are invoked within the function, because the stack may need to be moved to extend it and so the existing pointer will now be invalid. If this may be a problem, a possible solution is to track the mark offset as an integer and track the mark itself later on after the stack had been moved. I32 markoff = POPMARK; ... SP **mark = PL_stack_base + markoff; =head2 Temporaries Stack As noted above, xV references on the main value stack do not contribute to the reference count of an xV, and so another mechanism is used to track when temporary values which live on the stack must be released. This is the job of the temporaries stack. The temporaries stack stores pointers to xVs whose reference counts will be decremented soon. The base of this stack is pointed to by the interpreter variable C, of type C. =for apidoc_section $stack =for apidoc Amnh||PL_tmps_stack The head of the stack is indexed by C, an integer which stores the index in the array of the most recently-pushed item. =for apidoc Amnh||PL_tmps_ix There is no public API to directly push items to the temporaries stack. Instead, the API function C is used to mortalize an xV, adding its address to the temporaries stack. Likewise, there is no public API to read values from the temporaries stack. Instead, the macros C and C are used. The C macro establishes the base levels of the temporaries stack, by capturing the current value of C into C and saving the previous value to the save stack. Thereafter, whenever C is invoked all of the temporaries that have been pushed since that level are reclaimed. =for apidoc_section $stack =for apidoc Amnh||PL_tmps_floor While it is common to see these two macros in pairs within an C/ C pair, it is not necessary to match them. It is permitted to invoke C multiple times since the most recent C; for example in a loop iterating over elements of a list. While you can invoke C multiple times within a scope pair, it is unlikely to be useful. Subsequent invocations will move the temporaries floor further up, thus effectively trapping the existing temporaries to only be released at the end of the scope. =head2 Save Stack The save stack is used by perl to implement the C keyword and other similar behaviours; 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, C, C, C or other reasons. Whereas other perl internal stacks store individual items all of the same type (usually SV pointers or integers), the items pushed to the save stack are formed of many different types, having multiple fields to them. For example, the C type needs to store both the address of the C variable to restore, and the value to restore it to. This information could have been stored using fields of a C, but would have to be large enough to store three pointers in the largest case, which would waste a lot of space in most of the smaller cases. =for apidoc_section $stack =for apidoc Amnh||SAVEt_INT Instead, the stack stores information in a variable-length encoding of C structures. The final value pushed is stored in the C field which encodes the kind of item held by the preceding items; the count and types of which will depend on what kind of item is being stored. The kind field is pushed last because that will be the first field to be popped when unwinding items from the stack. The base of this stack is pointed to by the interpreter variable C, of type C. =for apidoc_section $stack =for apidoc Amnh||PL_savestack The head of the stack is indexed by C, 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). =for apidoc_section $stack =for apidoc Amnh||PL_savestack_ix Items are pushed to the save stack by using the various C macros. Many of these macros take a variable and store both its address and current value on the save stack, ensuring that value gets restored on scope exit. SAVEI8(i8) SAVEI16(i16) SAVEI32(i32) SAVEINT(i) ... There are also a variety of other special-purpose macros which save particular types or values of interest. C has already been mentioned above. Others include C which arranges for a PV (i.e. a string buffer) to be freed, or C which arranges for a given function pointer to be invoked on scope exit. A full list of such macros can be found in F. There is no public API for popping individual values or items from the save stack. Instead, via the scope stack, the C and C pair form a way to start and stop nested scopes. Leaving a nested scope via C will restore all of the saved values that had been pushed since the most recent C. =head2 Scope Stack As with the mark stack to 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 allows the save stack to be unwound back to that point when the scope is left. When perl is built with debugging enabled, there is 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 with 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 C, of type C. If enabled, the scope stack names are stored in a separate array pointed to by C, of type C. =for apidoc_section $stack =for apidoc Amnh||PL_scopestack =for apidoc Amnh||PL_scopestack_name The head of the stack is indexed by C, 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). =for apidoc_section $stack =for apidoc Amnh||PL_scopestack_ix Values are pushed to the scope stack using the C macro, which begins a new nested scope. Any items pushed to the save stack are then restored at the next nested invocation of the C macro. =head1 Dynamic Scope and the Context Stack B this section describes a non-public internal API that is subject to change without notice. =head2 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 Cised variable is determined by the dynamic scope. Perl tracks the dynamic scope by a data structure called the context stack, which is an array of C structures, and which is itself a big union for all the types of context. Whenever a new scope is entered (such as a block, a C loop, or a subroutine call), a new context entry is pushed onto the stack. Similarly when leaving a block or returning from a subroutine call etc. a context is popped. Since the context stack represents the current dynamic scope, it can be searched. For example, C searches back through the stack looking for a loop context that matches the label; C pops contexts until it finds a sub or eval context or similar; C examines sub contexts on the stack. =for apidoc_section $concurrency =for apidoc Cyh||PERL_CONTEXT Each context entry is labelled with a context type, C. Typical context types are C, C etc., as well as C and C which represent a basic scope (as pushed by C) and a sort block. The type determines which part of the context union are valid. =for apidoc Cyh ||cx_type =for apidoc Cmnh||CXt_BLOCK =for apidoc_item ||CXt_EVAL =for apidoc_item ||CXt_FORMAT =for apidoc_item ||CXt_GIVEN =for apidoc_item ||CXt_LOOP_ARY =for apidoc_item ||CXt_LOOP_LAZYIV =for apidoc_item ||CXt_LOOP_LAZYSV =for apidoc_item ||CXt_LOOP_LIST =for apidoc_item ||CXt_LOOP_PLAIN =for apidoc_item ||CXt_NULL =for apidoc_item ||CXt_SUB =for apidoc_item ||CXt_SUBST =for apidoc_item ||CXt_WHEN The main division in the context struct is between a substitution scope (C) and block scopes, which are everything else. The former is just used while executing C, and won't be discussed further here. All the block scope types share a common base, which corresponds to C. This stores the old values of various scope-related variables like C, as well as information about the current scope, such as C. On scope exit, the old variables are restored. Particular block scope types store extra per-type information. For example, C 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 is processed; for example the CV has its reference count decremented, and the original loop variable is restored. The macro C returns the base of the current context stack, while C is the index of the current frame within that stack. =for apidoc_section $concurrency =for apidoc Cmnh|PERL_CONTEXT *|cxstack =for apidoc Cmnh|I32|cxstack_ix In fact, the context stack is actually part of a stack-of-stacks system; whenever something unusual is done such as calling a C 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 C and C were used; in 5.24 they were replaced by the inline static functions described below. In addition, 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 C, C and C compared to the new functions. The old-style macros will not be described further. =head2 Pushing contexts For pushing a new context, the two basic functions are C, which pushes a new basic context block and returns its address, and a family of similar functions with names like C which populate the additional type-dependent fields in the C struct. Note that C and C don't have their own push functions, as they don't store any data beyond that pushed by C. The fields of the context struct and the arguments to the C 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 C; 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 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); */ =for apidoc_section $concurrency =for apidoc Cmnh||CXINC Note that C sets two new floors: for the args stack (to C) and the temps stack (to C). While executing at this scope level, every C (amongst others) will reset the args and tmps stack levels to these floors. Note that since C uses the current value of C rather than it being passed as an arg, this dictates at what point C should be called. In particular, any new mortals which should be freed only on scope exit (rather than at the next C) should be created first. Most callers of C simply set the new args stack floor to the top of the previous stack frame, but for C it stores the items being iterated over on the stack, and so sets C to the top of these items instead. Note that, contrary to its name, C doesn't always represent the value to restore C to on scope exit. Note the early capture of C to C, which is later passed as an arg to C. In the case of C, this is because, although most values needing saving are stored in fields of the context struct, an extra value needs saving only when the debugger is running, and it doesn't make sense to bloat the struct for this rare case. So instead it is saved on the savestack. Since this value gets calculated and saved before the context is pushed, it is necessary to pass the old value of C to C, to ensure that the saved value gets freed during scope exit. For most users of C, where nothing needs pushing on the save stack, C is just passed directly as an arg to C. Note that where possible, values should be saved in the context struct rather than on the save stack; it's much faster that way. Normally C should be immediately followed by the appropriate C, with nothing between them; this is because if code in-between could die (e.g. a warning upgraded to fatal), then the context stack unwinding code in C would see (in the example above) a C context frame, but without all the subroutine-specific fields set, and crashes would soon ensue. =for apidoc dounwind Where the two must be separate, initially set the type to C or C, and later change it to C when doing the C. This is exactly what C does, once it's determined which type of loop it's pushing. =head2 Popping contexts Contexts are popped using C etc. and C. Note however, that unlike C, neither of these functions actually decrement the current context stack index; this is done separately using C. =for apidoc_section $concurrency =for apidoc Cmh|void|CX_POP|PERL_CONTEXT* cx There are two main ways that contexts are popped. During normal execution as scopes are exited, functions like C, C and C process and pop just one context using C and C. On the other hand, things like C and C may have to pop back several scopes until a sub or loop context is found, and exceptions (such as C) need to pop back contexts until an eval context is found. Both of these are accomplished by C, which is capable of processing and popping all contexts above the target one. Here is a typical example of context popping, as found in C (simplified slightly): 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; =for apidoc_section $concurrency =for apidoc Cmh||CX_CUR The steps above are in a very specific order, designed to be the reverse order of when the context was pushed. The first thing to do is to 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 (as opposed to lvalue subs). It is important to make this copy before the save stack is popped or variables are restored, or bad things like the following can happen: sub f { my $x =...; $x } # $x freed before we get to copy it sub f { /(...)/; $1 } # PL_curpm restored before $1 copied Although we wish to free any temps at the same time, we have to be careful not to free any temps which are keeping return args alive; nor to free the temps we have just created while mortal copying return args. Fortunately, C is capable of making mortal copies of return args, shifting args down the stack, and only processing those entries on the temps stack that are safe to do so. In void context no args are returned, so it's more efficient to skip calling C. Also in void context, a C op is likely to be imminently called which will do a C, so there's no need to do that either. The next step is to pop savestack entries: C is just defined as C<< LEAVE_SCOPE(cx->blk_oldsaveix) >>. Note that during the popping, it's possible for perl to call destructors, call C to undo localisations of tied vars, and so on. Any of these can die or call C. In this case, C will be called, and the current context stack frame will be re-processed. Thus it is vital that all steps in popping a context are done in such a way to support reentrancy. The other alternative, of decrementing C I processing the frame, would lead to leaks and the like if something died halfway through, or overwriting of the current frame. =for apidoc_section $concurrency =for apidoc Cmh|void|CX_LEAVE_SCOPE|PERL_CONTEXT* cx C itself is safely re-entrant: if only half the savestack items have been popped before dying and getting trapped by eval, then the Cs in C or C will continue where the first one left off. The next step is the type-specific context processing; in this case C. In part, this looks like: cv = cx->blk_sub.cv; CvDEPTH(cv) = cx->blk_sub.olddepth; cx->blk_sub.cv = NULL; SvREFCNT_dec(cv); where its processing the just-executed CV. Note that before it decrements the CV's reference count, it nulls the C. This means that if it re-enters, the CV won't be freed twice. It also means that you can't rely on such type-specific fields having useful values after the return from C. Next, C restores all the various interpreter vars 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; Note that it I restore C; as mentioned earlier, which value to restore it to depends on the context type (specifically C), and what args (if any) it returns; and that will already have been sorted out earlier by C. Finally, the context stack pointer is actually decremented by C. After this point, it's possible that that the current context frame could be overwritten by other contexts being pushed. Although things like ties and C are supposed to work within a new context stack, it's best not to assume this. Indeed on debugging builds, C deliberately sets C to null to detect code that is still relying on the field values in that context frame. Note in the C example above, we grab C I calling C. =head2 Redoing contexts Finally, there is C, which acts like a super-C as regards to resetting various vars to their base values. It is used in places like C, C and C where rather than exiting a scope, we want to re-initialise the scope. As well as resetting C like C, it also resets C, C and C. Note that it doesn't do a C. =head1 Slab-based operator allocation B this section describes a non-public internal API that is subject to change without notice. Perl's internal error-handling mechanisms implement C (and its internal equivalents) using longjmp. If this occurs during lexing, parsing or compilation, we must ensure that any ops allocated as part of the compilation process are freed. (Older Perl versions did not adequately handle this situation: when failing a parse, they would leak ops that were stored in C C variables and not linked anywhere else.) To handle this situation, Perl uses I 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 are 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 that Perl can iterate over a slab and free all its ops. (Op structures are of different sizes, so the slab's ops can't merely 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 will tend to allocate the leaves of the op tree first, and the layout will therefore hopefully be cache-friendly. In addition, this means that there's no need to store the size of the slab (see below on 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 C when allocated and freed when the CV is freed. That would also allow C to skip C 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. 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. CVs use the C flag to indicate that the CV has a reference count on the slab. When this flag is set, the slab is accessible via C when C is not set, or by subtracting two pointers C<(2*sizeof(I32 *))> from C when it is set. The alternative to this approach of sneaking the slab into C during compilation would be to enlarge the C 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. =for apidoc_section $concurrency =for apidoc Cmnh| |CVf_SLABBED =for apidoc_item |OP *|CvROOT|CV * sv =for apidoc_item |OP *|CvSTART|CV * sv When the C flag is set, the CV takes responsibility for freeing the slab. If C 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 (C) precisely so that the ops can survive after the CV is done away with. Forgetting the slab when the root is attached is not strictly necessary, but avoids potential problems with C being written over. There is code all over the place, both in core and on CPAN, that does things with C, 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). 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 C blocks. C 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 C 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 C now sets a special flag on the op (C<< ->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 C hasn't been set up. So all slab-allocated ops are marked as such (C<< ->op_slabbed >>), to distinguish them from malloced ops. =head1 AUTHORS Until May 1997, this document was maintained by Jeff Okamoto Eokamoto@corp.hp.comE. It is now maintained as part of Perl itself by the Perl 5 Porters Eperl5-porters@perl.orgE. 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. =head1 SEE ALSO L, L, L, L