1PERLGUTS(1) Perl Programmers Reference Guide PERLGUTS(1)
2
3
4
6 perlguts - Introduction to the Perl API
7
9 This document attempts to describe how to use the Perl API, as well as
10 to provide some info on the basic workings of the Perl core. It is far
11 from complete and probably contains many errors. Please refer any
12 questions or comments to the author below.
13
15 Datatypes
16 Perl has three typedefs that handle Perl's three main data types:
17
18 SV Scalar Value
19 AV Array Value
20 HV Hash Value
21
22 Each typedef has specific routines that manipulate the various data
23 types.
24
25 What is an "IV"?
26 Perl uses a special typedef IV which is a simple signed integer type
27 that is guaranteed to be large enough to hold a pointer (as well as an
28 integer). Additionally, there is the UV, which is simply an unsigned
29 IV.
30
31 Perl also uses two special typedefs, I32 and I16, which will always be
32 at least 32-bits and 16-bits long, respectively. (Again, there are U32
33 and U16, as well.) They will usually be exactly 32 and 16 bits long,
34 but on Crays they will both be 64 bits.
35
36 Working with SVs
37 An SV can be created and loaded with one command. There are five types
38 of values that can be loaded: an integer value (IV), an unsigned
39 integer value (UV), a double (NV), a string (PV), and another scalar
40 (SV). ("PV" stands for "Pointer Value". You might think that it is
41 misnamed because it is described as pointing only to strings. However,
42 it is possible to have it point to other things. For example, it could
43 point to an array of UVs. But, using it for non-strings requires care,
44 as the underlying assumption of much of the internals is that PVs are
45 just for strings. Often, for example, a trailing "NUL" is tacked on
46 automatically. The non-string use is documented only in this
47 paragraph.)
48
49 The seven routines are:
50
51 SV* newSViv(IV);
52 SV* newSVuv(UV);
53 SV* newSVnv(double);
54 SV* newSVpv(const char*, STRLEN);
55 SV* newSVpvn(const char*, STRLEN);
56 SV* newSVpvf(const char*, ...);
57 SV* newSVsv(SV*);
58
59 "STRLEN" is an integer type ("Size_t", usually defined as "size_t" in
60 config.h) guaranteed to be large enough to represent the size of any
61 string that perl can handle.
62
63 In the unlikely case of a SV requiring more complex initialization, you
64 can create an empty SV with newSV(len). If "len" is 0 an empty SV of
65 type NULL is returned, else an SV of type PV is returned with len + 1
66 (for the "NUL") bytes of storage allocated, accessible via SvPVX. In
67 both cases the SV has the undef value.
68
69 SV *sv = newSV(0); /* no storage allocated */
70 SV *sv = newSV(10); /* 10 (+1) bytes of uninitialised storage
71 * allocated */
72
73 To change the value of an already-existing SV, there are eight
74 routines:
75
76 void sv_setiv(SV*, IV);
77 void sv_setuv(SV*, UV);
78 void sv_setnv(SV*, double);
79 void sv_setpv(SV*, const char*);
80 void sv_setpvn(SV*, const char*, STRLEN)
81 void sv_setpvf(SV*, const char*, ...);
82 void sv_vsetpvfn(SV*, const char*, STRLEN, va_list *,
83 SV **, Size_t, bool *);
84 void sv_setsv(SV*, SV*);
85
86 Notice that you can choose to specify the length of the string to be
87 assigned by using "sv_setpvn", "newSVpvn", or "newSVpv", or you may
88 allow Perl to calculate the length by using "sv_setpv" or by specifying
89 0 as the second argument to "newSVpv". Be warned, though, that Perl
90 will determine the string's length by using "strlen", which depends on
91 the string terminating with a "NUL" character, and not otherwise
92 containing NULs.
93
94 The arguments of "sv_setpvf" are processed like "sprintf", and the
95 formatted output becomes the value.
96
97 "sv_vsetpvfn" is an analogue of "vsprintf", but it allows you to
98 specify either a pointer to a variable argument list or the address and
99 length of an array of SVs. The last argument points to a boolean; on
100 return, if that boolean is true, then locale-specific information has
101 been used to format the string, and the string's contents are therefore
102 untrustworthy (see perlsec). This pointer may be NULL if that
103 information is not important. Note that this function requires you to
104 specify the length of the format.
105
106 The "sv_set*()" functions are not generic enough to operate on values
107 that have "magic". See "Magic Virtual Tables" later in this document.
108
109 All SVs that contain strings should be terminated with a "NUL"
110 character. If it is not "NUL"-terminated there is a risk of core dumps
111 and corruptions from code which passes the string to C functions or
112 system calls which expect a "NUL"-terminated string. Perl's own
113 functions typically add a trailing "NUL" for this reason.
114 Nevertheless, you should be very careful when you pass a string stored
115 in an SV to a C function or system call.
116
117 To access the actual value that an SV points to, you can use the
118 macros:
119
120 SvIV(SV*)
121 SvUV(SV*)
122 SvNV(SV*)
123 SvPV(SV*, STRLEN len)
124 SvPV_nolen(SV*)
125
126 which will automatically coerce the actual scalar type into an IV, UV,
127 double, or string.
128
129 In the "SvPV" macro, the length of the string returned is placed into
130 the variable "len" (this is a macro, so you do not use &len). If you
131 do not care what the length of the data is, use the "SvPV_nolen" macro.
132 Historically the "SvPV" macro with the global variable "PL_na" has been
133 used in this case. But that can be quite inefficient because "PL_na"
134 must be accessed in thread-local storage in threaded Perl. In any
135 case, remember that Perl allows arbitrary strings of data that may both
136 contain NULs and might not be terminated by a "NUL".
137
138 Also remember that C doesn't allow you to safely say "foo(SvPV(s, len),
139 len);". It might work with your compiler, but it won't work for
140 everyone. Break this sort of statement up into separate assignments:
141
142 SV *s;
143 STRLEN len;
144 char *ptr;
145 ptr = SvPV(s, len);
146 foo(ptr, len);
147
148 If you want to know if the scalar value is TRUE, you can use:
149
150 SvTRUE(SV*)
151
152 Although Perl will automatically grow strings for you, if you need to
153 force Perl to allocate more memory for your SV, you can use the macro
154
155 SvGROW(SV*, STRLEN newlen)
156
157 which will determine if more memory needs to be allocated. If so, it
158 will call the function "sv_grow". Note that "SvGROW" can only
159 increase, not decrease, the allocated memory of an SV and that it does
160 not automatically add space for the trailing "NUL" byte (perl's own
161 string functions typically do "SvGROW(sv, len + 1)").
162
163 If you want to write to an existing SV's buffer and set its value to a
164 string, use SvPV_force() or one of its variants to force the SV to be a
165 PV. This will remove any of various types of non-stringness from the
166 SV while preserving the content of the SV in the PV. This can be used,
167 for example, to append data from an API function to a buffer without
168 extra copying:
169
170 (void)SvPVbyte_force(sv, len);
171 s = SvGROW(sv, len + needlen + 1);
172 /* something that modifies up to needlen bytes at s+len, but
173 modifies newlen bytes
174 eg. newlen = read(fd, s + len, needlen);
175 ignoring errors for these examples
176 */
177 s[len + newlen] = '\0';
178 SvCUR_set(sv, len + newlen);
179 SvUTF8_off(sv);
180 SvSETMAGIC(sv);
181
182 If you already have the data in memory or if you want to keep your code
183 simple, you can use one of the sv_cat*() variants, such as sv_catpvn().
184 If you want to insert anywhere in the string you can use sv_insert() or
185 sv_insert_flags().
186
187 If you don't need the existing content of the SV, you can avoid some
188 copying with:
189
190 SvPVCLEAR(sv);
191 s = SvGROW(sv, needlen + 1);
192 /* something that modifies up to needlen bytes at s, but modifies
193 newlen bytes
194 eg. newlen = read(fd, s. needlen);
195 */
196 s[newlen] = '\0';
197 SvCUR_set(sv, newlen);
198 SvPOK_only(sv); /* also clears SVf_UTF8 */
199 SvSETMAGIC(sv);
200
201 Again, if you already have the data in memory or want to avoid the
202 complexity of the above, you can use sv_setpvn().
203
204 If you have a buffer allocated with Newx() and want to set that as the
205 SV's value, you can use sv_usepvn_flags(). That has some requirements
206 if you want to avoid perl re-allocating the buffer to fit the trailing
207 NUL:
208
209 Newx(buf, somesize+1, char);
210 /* ... fill in buf ... */
211 buf[somesize] = '\0';
212 sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_NUL);
213 /* buf now belongs to perl, don't release it */
214
215 If you have an SV and want to know what kind of data Perl thinks is
216 stored in it, you can use the following macros to check the type of SV
217 you have.
218
219 SvIOK(SV*)
220 SvNOK(SV*)
221 SvPOK(SV*)
222
223 You can get and set the current length of the string stored in an SV
224 with the following macros:
225
226 SvCUR(SV*)
227 SvCUR_set(SV*, I32 val)
228
229 You can also get a pointer to the end of the string stored in the SV
230 with the macro:
231
232 SvEND(SV*)
233
234 But note that these last three macros are valid only if "SvPOK()" is
235 true.
236
237 If you want to append something to the end of string stored in an
238 "SV*", you can use the following functions:
239
240 void sv_catpv(SV*, const char*);
241 void sv_catpvn(SV*, const char*, STRLEN);
242 void sv_catpvf(SV*, const char*, ...);
243 void sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **,
244 I32, bool);
245 void sv_catsv(SV*, SV*);
246
247 The first function calculates the length of the string to be appended
248 by using "strlen". In the second, you specify the length of the string
249 yourself. The third function processes its arguments like "sprintf"
250 and appends the formatted output. The fourth function works like
251 "vsprintf". You can specify the address and length of an array of SVs
252 instead of the va_list argument. The fifth function extends the string
253 stored in the first SV with the string stored in the second SV. It
254 also forces the second SV to be interpreted as a string.
255
256 The "sv_cat*()" functions are not generic enough to operate on values
257 that have "magic". See "Magic Virtual Tables" later in this document.
258
259 If you know the name of a scalar variable, you can get a pointer to its
260 SV by using the following:
261
262 SV* get_sv("package::varname", 0);
263
264 This returns NULL if the variable does not exist.
265
266 If you want to know if this variable (or any other SV) is actually
267 "defined", you can call:
268
269 SvOK(SV*)
270
271 The scalar "undef" value is stored in an SV instance called
272 "PL_sv_undef".
273
274 Its address can be used whenever an "SV*" is needed. Make sure that
275 you don't try to compare a random sv with &PL_sv_undef. For example
276 when interfacing Perl code, it'll work correctly for:
277
278 foo(undef);
279
280 But won't work when called as:
281
282 $x = undef;
283 foo($x);
284
285 So to repeat always use SvOK() to check whether an sv is defined.
286
287 Also you have to be careful when using &PL_sv_undef as a value in AVs
288 or HVs (see "AVs, HVs and undefined values").
289
290 There are also the two values "PL_sv_yes" and "PL_sv_no", which contain
291 boolean TRUE and FALSE values, respectively. Like "PL_sv_undef", their
292 addresses can be used whenever an "SV*" is needed.
293
294 Do not be fooled into thinking that "(SV *) 0" is the same as
295 &PL_sv_undef. Take this code:
296
297 SV* sv = (SV*) 0;
298 if (I-am-to-return-a-real-value) {
299 sv = sv_2mortal(newSViv(42));
300 }
301 sv_setsv(ST(0), sv);
302
303 This code tries to return a new SV (which contains the value 42) if it
304 should return a real value, or undef otherwise. Instead it has
305 returned a NULL pointer which, somewhere down the line, will cause a
306 segmentation violation, bus error, or just weird results. Change the
307 zero to &PL_sv_undef in the first line and all will be well.
308
309 To free an SV that you've created, call "SvREFCNT_dec(SV*)". Normally
310 this call is not necessary (see "Reference Counts and Mortality").
311
312 Offsets
313 Perl provides the function "sv_chop" to efficiently remove characters
314 from the beginning of a string; you give it an SV and a pointer to
315 somewhere inside the PV, and it discards everything before the pointer.
316 The efficiency comes by means of a little hack: instead of actually
317 removing the characters, "sv_chop" sets the flag "OOK" (offset OK) to
318 signal to other functions that the offset hack is in effect, and it
319 moves the PV pointer (called "SvPVX") forward by the number of bytes
320 chopped off, and adjusts "SvCUR" and "SvLEN" accordingly. (A portion
321 of the space between the old and new PV pointers is used to store the
322 count of chopped bytes.)
323
324 Hence, at this point, the start of the buffer that we allocated lives
325 at "SvPVX(sv) - SvIV(sv)" in memory and the PV pointer is pointing into
326 the middle of this allocated storage.
327
328 This is best demonstrated by example. Normally copy-on-write will
329 prevent the substitution from operator from using this hack, but if you
330 can craft a string for which copy-on-write is not possible, you can see
331 it in play. In the current implementation, the final byte of a string
332 buffer is used as a copy-on-write reference count. If the buffer is
333 not big enough, then copy-on-write is skipped. First have a look at an
334 empty string:
335
336 % ./perl -Ilib -MDevel::Peek -le '$a=""; $a .= ""; Dump $a'
337 SV = PV(0x7ffb7c008a70) at 0x7ffb7c030390
338 REFCNT = 1
339 FLAGS = (POK,pPOK)
340 PV = 0x7ffb7bc05b50 ""\0
341 CUR = 0
342 LEN = 10
343
344 Notice here the LEN is 10. (It may differ on your platform.) Extend
345 the length of the string to one less than 10, and do a substitution:
346
347 % ./perl -Ilib -MDevel::Peek -le '$a=""; $a.="123456789"; $a=~s/.//; \
348 Dump($a)'
349 SV = PV(0x7ffa04008a70) at 0x7ffa04030390
350 REFCNT = 1
351 FLAGS = (POK,OOK,pPOK)
352 OFFSET = 1
353 PV = 0x7ffa03c05b61 ( "\1" . ) "23456789"\0
354 CUR = 8
355 LEN = 9
356
357 Here the number of bytes chopped off (1) is shown next as the OFFSET.
358 The portion of the string between the "real" and the "fake" beginnings
359 is shown in parentheses, and the values of "SvCUR" and "SvLEN" reflect
360 the fake beginning, not the real one. (The first character of the
361 string buffer happens to have changed to "\1" here, not "1", because
362 the current implementation stores the offset count in the string
363 buffer. This is subject to change.)
364
365 Something similar to the offset hack is performed on AVs to enable
366 efficient shifting and splicing off the beginning of the array; while
367 "AvARRAY" points to the first element in the array that is visible from
368 Perl, "AvALLOC" points to the real start of the C array. These are
369 usually the same, but a "shift" operation can be carried out by
370 increasing "AvARRAY" by one and decreasing "AvFILL" and "AvMAX".
371 Again, the location of the real start of the C array only comes into
372 play when freeing the array. See "av_shift" in av.c.
373
374 What's Really Stored in an SV?
375 Recall that the usual method of determining the type of scalar you have
376 is to use "Sv*OK" macros. Because a scalar can be both a number and a
377 string, usually these macros will always return TRUE and calling the
378 "Sv*V" macros will do the appropriate conversion of string to
379 integer/double or integer/double to string.
380
381 If you really need to know if you have an integer, double, or string
382 pointer in an SV, you can use the following three macros instead:
383
384 SvIOKp(SV*)
385 SvNOKp(SV*)
386 SvPOKp(SV*)
387
388 These will tell you if you truly have an integer, double, or string
389 pointer stored in your SV. The "p" stands for private.
390
391 There are various ways in which the private and public flags may
392 differ. For example, in perl 5.16 and earlier a tied SV may have a
393 valid underlying value in the IV slot (so SvIOKp is true), but the data
394 should be accessed via the FETCH routine rather than directly, so SvIOK
395 is false. (In perl 5.18 onwards, tied scalars use the flags the same
396 way as untied scalars.) Another is when numeric conversion has
397 occurred and precision has been lost: only the private flag is set on
398 'lossy' values. So when an NV is converted to an IV with loss, SvIOKp,
399 SvNOKp and SvNOK will be set, while SvIOK wont be.
400
401 In general, though, it's best to use the "Sv*V" macros.
402
403 Working with AVs
404 There are two ways to create and load an AV. The first method creates
405 an empty AV:
406
407 AV* newAV();
408
409 The second method both creates the AV and initially populates it with
410 SVs:
411
412 AV* av_make(SSize_t num, SV **ptr);
413
414 The second argument points to an array containing "num" "SV*"'s. Once
415 the AV has been created, the SVs can be destroyed, if so desired.
416
417 Once the AV has been created, the following operations are possible on
418 it:
419
420 void av_push(AV*, SV*);
421 SV* av_pop(AV*);
422 SV* av_shift(AV*);
423 void av_unshift(AV*, SSize_t num);
424
425 These should be familiar operations, with the exception of
426 "av_unshift". This routine adds "num" elements at the front of the
427 array with the "undef" value. You must then use "av_store" (described
428 below) to assign values to these new elements.
429
430 Here are some other functions:
431
432 SSize_t av_top_index(AV*);
433 SV** av_fetch(AV*, SSize_t key, I32 lval);
434 SV** av_store(AV*, SSize_t key, SV* val);
435
436 The "av_top_index" function returns the highest index value in an array
437 (just like $#array in Perl). If the array is empty, -1 is returned.
438 The "av_fetch" function returns the value at index "key", but if "lval"
439 is non-zero, then "av_fetch" will store an undef value at that index.
440 The "av_store" function stores the value "val" at index "key", and does
441 not increment the reference count of "val". Thus the caller is
442 responsible for taking care of that, and if "av_store" returns NULL,
443 the caller will have to decrement the reference count to avoid a memory
444 leak. Note that "av_fetch" and "av_store" both return "SV**"'s, not
445 "SV*"'s as their return value.
446
447 A few more:
448
449 void av_clear(AV*);
450 void av_undef(AV*);
451 void av_extend(AV*, SSize_t key);
452
453 The "av_clear" function deletes all the elements in the AV* array, but
454 does not actually delete the array itself. The "av_undef" function
455 will delete all the elements in the array plus the array itself. The
456 "av_extend" function extends the array so that it contains at least
457 "key+1" elements. If "key+1" is less than the currently allocated
458 length of the array, then nothing is done.
459
460 If you know the name of an array variable, you can get a pointer to its
461 AV by using the following:
462
463 AV* get_av("package::varname", 0);
464
465 This returns NULL if the variable does not exist.
466
467 See "Understanding the Magic of Tied Hashes and Arrays" for more
468 information on how to use the array access functions on tied arrays.
469
470 Working with HVs
471 To create an HV, you use the following routine:
472
473 HV* newHV();
474
475 Once the HV has been created, the following operations are possible on
476 it:
477
478 SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
479 SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
480
481 The "klen" parameter is the length of the key being passed in (Note
482 that you cannot pass 0 in as a value of "klen" to tell Perl to measure
483 the length of the key). The "val" argument contains the SV pointer to
484 the scalar being stored, and "hash" is the precomputed hash value (zero
485 if you want "hv_store" to calculate it for you). The "lval" parameter
486 indicates whether this fetch is actually a part of a store operation,
487 in which case a new undefined value will be added to the HV with the
488 supplied key and "hv_fetch" will return as if the value had already
489 existed.
490
491 Remember that "hv_store" and "hv_fetch" return "SV**"'s and not just
492 "SV*". To access the scalar value, you must first dereference the
493 return value. However, you should check to make sure that the return
494 value is not NULL before dereferencing it.
495
496 The first of these two functions checks if a hash table entry exists,
497 and the second deletes it.
498
499 bool hv_exists(HV*, const char* key, U32 klen);
500 SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
501
502 If "flags" does not include the "G_DISCARD" flag then "hv_delete" will
503 create and return a mortal copy of the deleted value.
504
505 And more miscellaneous functions:
506
507 void hv_clear(HV*);
508 void hv_undef(HV*);
509
510 Like their AV counterparts, "hv_clear" deletes all the entries in the
511 hash table but does not actually delete the hash table. The "hv_undef"
512 deletes both the entries and the hash table itself.
513
514 Perl keeps the actual data in a linked list of structures with a
515 typedef of HE. These contain the actual key and value pointers (plus
516 extra administrative overhead). The key is a string pointer; the value
517 is an "SV*". However, once you have an "HE*", to get the actual key
518 and value, use the routines specified below.
519
520 I32 hv_iterinit(HV*);
521 /* Prepares starting point to traverse hash table */
522 HE* hv_iternext(HV*);
523 /* Get the next entry, and return a pointer to a
524 structure that has both the key and value */
525 char* hv_iterkey(HE* entry, I32* retlen);
526 /* Get the key from an HE structure and also return
527 the length of the key string */
528 SV* hv_iterval(HV*, HE* entry);
529 /* Return an SV pointer to the value of the HE
530 structure */
531 SV* hv_iternextsv(HV*, char** key, I32* retlen);
532 /* This convenience routine combines hv_iternext,
533 hv_iterkey, and hv_iterval. The key and retlen
534 arguments are return values for the key and its
535 length. The value is returned in the SV* argument */
536
537 If you know the name of a hash variable, you can get a pointer to its
538 HV by using the following:
539
540 HV* get_hv("package::varname", 0);
541
542 This returns NULL if the variable does not exist.
543
544 The hash algorithm is defined in the "PERL_HASH" macro:
545
546 PERL_HASH(hash, key, klen)
547
548 The exact implementation of this macro varies by architecture and
549 version of perl, and the return value may change per invocation, so the
550 value is only valid for the duration of a single perl process.
551
552 See "Understanding the Magic of Tied Hashes and Arrays" for more
553 information on how to use the hash access functions on tied hashes.
554
555 Hash API Extensions
556 Beginning with version 5.004, the following functions are also
557 supported:
558
559 HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
560 HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
561
562 bool hv_exists_ent (HV* tb, SV* key, U32 hash);
563 SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
564
565 SV* hv_iterkeysv (HE* entry);
566
567 Note that these functions take "SV*" keys, which simplifies writing of
568 extension code that deals with hash structures. These functions also
569 allow passing of "SV*" keys to "tie" functions without forcing you to
570 stringify the keys (unlike the previous set of functions).
571
572 They also return and accept whole hash entries ("HE*"), making their
573 use more efficient (since the hash number for a particular string
574 doesn't have to be recomputed every time). See perlapi for detailed
575 descriptions.
576
577 The following macros must always be used to access the contents of hash
578 entries. Note that the arguments to these macros must be simple
579 variables, since they may get evaluated more than once. See perlapi
580 for detailed descriptions of these macros.
581
582 HePV(HE* he, STRLEN len)
583 HeVAL(HE* he)
584 HeHASH(HE* he)
585 HeSVKEY(HE* he)
586 HeSVKEY_force(HE* he)
587 HeSVKEY_set(HE* he, SV* sv)
588
589 These two lower level macros are defined, but must only be used when
590 dealing with keys that are not "SV*"s:
591
592 HeKEY(HE* he)
593 HeKLEN(HE* he)
594
595 Note that both "hv_store" and "hv_store_ent" do not increment the
596 reference count of the stored "val", which is the caller's
597 responsibility. If these functions return a NULL value, the caller
598 will usually have to decrement the reference count of "val" to avoid a
599 memory leak.
600
601 AVs, HVs and undefined values
602 Sometimes you have to store undefined values in AVs or HVs. Although
603 this may be a rare case, it can be tricky. That's because you're used
604 to using &PL_sv_undef if you need an undefined SV.
605
606 For example, intuition tells you that this XS code:
607
608 AV *av = newAV();
609 av_store( av, 0, &PL_sv_undef );
610
611 is equivalent to this Perl code:
612
613 my @av;
614 $av[0] = undef;
615
616 Unfortunately, this isn't true. In perl 5.18 and earlier, AVs use
617 &PL_sv_undef as a marker for indicating that an array element has not
618 yet been initialized. Thus, "exists $av[0]" would be true for the
619 above Perl code, but false for the array generated by the XS code. In
620 perl 5.20, storing &PL_sv_undef will create a read-only element,
621 because the scalar &PL_sv_undef itself is stored, not a copy.
622
623 Similar problems can occur when storing &PL_sv_undef in HVs:
624
625 hv_store( hv, "key", 3, &PL_sv_undef, 0 );
626
627 This will indeed make the value "undef", but if you try to modify the
628 value of "key", you'll get the following error:
629
630 Modification of non-creatable hash value attempted
631
632 In perl 5.8.0, &PL_sv_undef was also used to mark placeholders in
633 restricted hashes. This caused such hash entries not to appear when
634 iterating over the hash or when checking for the keys with the
635 "hv_exists" function.
636
637 You can run into similar problems when you store &PL_sv_yes or
638 &PL_sv_no into AVs or HVs. Trying to modify such elements will give
639 you the following error:
640
641 Modification of a read-only value attempted
642
643 To make a long story short, you can use the special variables
644 &PL_sv_undef, &PL_sv_yes and &PL_sv_no with AVs and HVs, but you have
645 to make sure you know what you're doing.
646
647 Generally, if you want to store an undefined value in an AV or HV, you
648 should not use &PL_sv_undef, but rather create a new undefined value
649 using the "newSV" function, for example:
650
651 av_store( av, 42, newSV(0) );
652 hv_store( hv, "foo", 3, newSV(0), 0 );
653
654 References
655 References are a special type of scalar that point to other data types
656 (including other references).
657
658 To create a reference, use either of the following functions:
659
660 SV* newRV_inc((SV*) thing);
661 SV* newRV_noinc((SV*) thing);
662
663 The "thing" argument can be any of an "SV*", "AV*", or "HV*". The
664 functions are identical except that "newRV_inc" increments the
665 reference count of the "thing", while "newRV_noinc" does not. For
666 historical reasons, "newRV" is a synonym for "newRV_inc".
667
668 Once you have a reference, you can use the following macro to
669 dereference the reference:
670
671 SvRV(SV*)
672
673 then call the appropriate routines, casting the returned "SV*" to
674 either an "AV*" or "HV*", if required.
675
676 To determine if an SV is a reference, you can use the following macro:
677
678 SvROK(SV*)
679
680 To discover what type of value the reference refers to, use the
681 following macro and then check the return value.
682
683 SvTYPE(SvRV(SV*))
684
685 The most useful types that will be returned are:
686
687 SVt_PVAV Array
688 SVt_PVHV Hash
689 SVt_PVCV Code
690 SVt_PVGV Glob (possibly a file handle)
691
692 Any numerical value returned which is less than SVt_PVAV will be a
693 scalar of some form.
694
695 See "svtype" in perlapi for more details.
696
697 Blessed References and Class Objects
698 References are also used to support object-oriented programming. In
699 perl's OO lexicon, an object is simply a reference that has been
700 blessed into a package (or class). Once blessed, the programmer may
701 now use the reference to access the various methods in the class.
702
703 A reference can be blessed into a package with the following function:
704
705 SV* sv_bless(SV* sv, HV* stash);
706
707 The "sv" argument must be a reference value. The "stash" argument
708 specifies which class the reference will belong to. See "Stashes and
709 Globs" for information on converting class names into stashes.
710
711 /* Still under construction */
712
713 The following function upgrades rv to reference if not already one.
714 Creates a new SV for rv to point to. If "classname" is non-null, the
715 SV is blessed into the specified class. SV is returned.
716
717 SV* newSVrv(SV* rv, const char* classname);
718
719 The following three functions copy integer, unsigned integer or double
720 into an SV whose reference is "rv". SV is blessed if "classname" is
721 non-null.
722
723 SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
724 SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
725 SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
726
727 The following function copies the pointer value (the address, not the
728 string!) into an SV whose reference is rv. SV is blessed if
729 "classname" is non-null.
730
731 SV* sv_setref_pv(SV* rv, const char* classname, void* pv);
732
733 The following function copies a string into an SV whose reference is
734 "rv". Set length to 0 to let Perl calculate the string length. SV is
735 blessed if "classname" is non-null.
736
737 SV* sv_setref_pvn(SV* rv, const char* classname, char* pv,
738 STRLEN length);
739
740 The following function tests whether the SV is blessed into the
741 specified class. It does not check inheritance relationships.
742
743 int sv_isa(SV* sv, const char* name);
744
745 The following function tests whether the SV is a reference to a blessed
746 object.
747
748 int sv_isobject(SV* sv);
749
750 The following function tests whether the SV is derived from the
751 specified class. SV can be either a reference to a blessed object or a
752 string containing a class name. This is the function implementing the
753 "UNIVERSAL::isa" functionality.
754
755 bool sv_derived_from(SV* sv, const char* name);
756
757 To check if you've got an object derived from a specific class you have
758 to write:
759
760 if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
761
762 Creating New Variables
763 To create a new Perl variable with an undef value which can be accessed
764 from your Perl script, use the following routines, depending on the
765 variable type.
766
767 SV* get_sv("package::varname", GV_ADD);
768 AV* get_av("package::varname", GV_ADD);
769 HV* get_hv("package::varname", GV_ADD);
770
771 Notice the use of GV_ADD as the second parameter. The new variable can
772 now be set, using the routines appropriate to the data type.
773
774 There are additional macros whose values may be bitwise OR'ed with the
775 "GV_ADD" argument to enable certain extra features. Those bits are:
776
777 GV_ADDMULTI
778 Marks the variable as multiply defined, thus preventing the:
779
780 Name <varname> used only once: possible typo
781
782 warning.
783
784 GV_ADDWARN
785 Issues the warning:
786
787 Had to create <varname> unexpectedly
788
789 if the variable did not exist before the function was called.
790
791 If you do not specify a package name, the variable is created in the
792 current package.
793
794 Reference Counts and Mortality
795 Perl uses a reference count-driven garbage collection mechanism. SVs,
796 AVs, or HVs (xV for short in the following) start their life with a
797 reference count of 1. If the reference count of an xV ever drops to 0,
798 then it will be destroyed and its memory made available for reuse. At
799 the most basic internal level, reference counts can be manipulated with
800 the following macros:
801
802 int SvREFCNT(SV* sv);
803 SV* SvREFCNT_inc(SV* sv);
804 void SvREFCNT_dec(SV* sv);
805
806 (There are also suffixed versions of the increment and decrement
807 macros, for situations where the full generality of these basic macros
808 can be exchanged for some performance.)
809
810 However, the way a programmer should think about references is not so
811 much in terms of the bare reference count, but in terms of ownership of
812 references. A reference to an xV can be owned by any of a variety of
813 entities: another xV, the Perl interpreter, an XS data structure, a
814 piece of running code, or a dynamic scope. An xV generally does not
815 know what entities own the references to it; it only knows how many
816 references there are, which is the reference count.
817
818 To correctly maintain reference counts, it is essential to keep track
819 of what references the XS code is manipulating. The programmer should
820 always know where a reference has come from and who owns it, and be
821 aware of any creation or destruction of references, and any transfers
822 of ownership. Because ownership isn't represented explicitly in the xV
823 data structures, only the reference count need be actually maintained
824 by the code, and that means that this understanding of ownership is not
825 actually evident in the code. For example, transferring ownership of a
826 reference from one owner to another doesn't change the reference count
827 at all, so may be achieved with no actual code. (The transferring code
828 doesn't touch the referenced object, but does need to ensure that the
829 former owner knows that it no longer owns the reference, and that the
830 new owner knows that it now does.)
831
832 An xV that is visible at the Perl level should not become unreferenced
833 and thus be destroyed. Normally, an object will only become
834 unreferenced when it is no longer visible, often by the same means that
835 makes it invisible. For example, a Perl reference value (RV) owns a
836 reference to its referent, so if the RV is overwritten that reference
837 gets destroyed, and the no-longer-reachable referent may be destroyed
838 as a result.
839
840 Many functions have some kind of reference manipulation as part of
841 their purpose. Sometimes this is documented in terms of ownership of
842 references, and sometimes it is (less helpfully) documented in terms of
843 changes to reference counts. For example, the newRV_inc() function is
844 documented to create a new RV (with reference count 1) and increment
845 the reference count of the referent that was supplied by the caller.
846 This is best understood as creating a new reference to the referent,
847 which is owned by the created RV, and returning to the caller ownership
848 of the sole reference to the RV. The newRV_noinc() function instead
849 does not increment the reference count of the referent, but the RV
850 nevertheless ends up owning a reference to the referent. It is
851 therefore implied that the caller of "newRV_noinc()" is relinquishing a
852 reference to the referent, making this conceptually a more complicated
853 operation even though it does less to the data structures.
854
855 For example, imagine you want to return a reference from an XSUB
856 function. Inside the XSUB routine, you create an SV which initially
857 has just a single reference, owned by the XSUB routine. This reference
858 needs to be disposed of before the routine is complete, otherwise it
859 will leak, preventing the SV from ever being destroyed. So to create
860 an RV referencing the SV, it is most convenient to pass the SV to
861 "newRV_noinc()", which consumes that reference. Now the XSUB routine
862 no longer owns a reference to the SV, but does own a reference to the
863 RV, which in turn owns a reference to the SV. The ownership of the
864 reference to the RV is then transferred by the process of returning the
865 RV from the XSUB.
866
867 There are some convenience functions available that can help with the
868 destruction of xVs. These functions introduce the concept of
869 "mortality". Much documentation speaks of an xV itself being mortal,
870 but this is misleading. It is really a reference to an xV that is
871 mortal, and it is possible for there to be more than one mortal
872 reference to a single xV. For a reference to be mortal means that it
873 is owned by the temps stack, one of perl's many internal stacks, which
874 will destroy that reference "a short time later". Usually the "short
875 time later" is the end of the current Perl statement. However, it gets
876 more complicated around dynamic scopes: there can be multiple sets of
877 mortal references hanging around at the same time, with different death
878 dates. Internally, the actual determinant for when mortal xV
879 references are destroyed depends on two macros, SAVETMPS and FREETMPS.
880 See perlcall and perlxs and "Temporaries Stack" below for more details
881 on these macros.
882
883 Mortal references are mainly used for xVs that are placed on perl's
884 main stack. The stack is problematic for reference tracking, because
885 it contains a lot of xV references, but doesn't own those references:
886 they are not counted. Currently, there are many bugs resulting from
887 xVs being destroyed while referenced by the stack, because the stack's
888 uncounted references aren't enough to keep the xVs alive. So when
889 putting an (uncounted) reference on the stack, it is vitally important
890 to ensure that there will be a counted reference to the same xV that
891 will last at least as long as the uncounted reference. But it's also
892 important that that counted reference be cleaned up at an appropriate
893 time, and not unduly prolong the xV's life. For there to be a mortal
894 reference is often the best way to satisfy this requirement, especially
895 if the xV was created especially to be put on the stack and would
896 otherwise be unreferenced.
897
898 To create a mortal reference, use the functions:
899
900 SV* sv_newmortal()
901 SV* sv_mortalcopy(SV*)
902 SV* sv_2mortal(SV*)
903
904 "sv_newmortal()" creates an SV (with the undefined value) whose sole
905 reference is mortal. "sv_mortalcopy()" creates an xV whose value is a
906 copy of a supplied xV and whose sole reference is mortal.
907 "sv_2mortal()" mortalises an existing xV reference: it transfers
908 ownership of a reference from the caller to the temps stack. Because
909 "sv_newmortal" gives the new SV no value, it must normally be given one
910 via "sv_setpv", "sv_setiv", etc. :
911
912 SV *tmp = sv_newmortal();
913 sv_setiv(tmp, an_integer);
914
915 As that is multiple C statements it is quite common so see this idiom
916 instead:
917
918 SV *tmp = sv_2mortal(newSViv(an_integer));
919
920 The mortal routines are not just for SVs; AVs and HVs can be made
921 mortal by passing their address (type-casted to "SV*") to the
922 "sv_2mortal" or "sv_mortalcopy" routines.
923
924 Stashes and Globs
925 A stash is a hash that contains all variables that are defined within a
926 package. Each key of the stash is a symbol name (shared by all the
927 different types of objects that have the same name), and each value in
928 the hash table is a GV (Glob Value). This GV in turn contains
929 references to the various objects of that name, including (but not
930 limited to) the following:
931
932 Scalar Value
933 Array Value
934 Hash Value
935 I/O Handle
936 Format
937 Subroutine
938
939 There is a single stash called "PL_defstash" that holds the items that
940 exist in the "main" package. To get at the items in other packages,
941 append the string "::" to the package name. The items in the "Foo"
942 package are in the stash "Foo::" in PL_defstash. The items in the
943 "Bar::Baz" package are in the stash "Baz::" in "Bar::"'s stash.
944
945 To get the stash pointer for a particular package, use the function:
946
947 HV* gv_stashpv(const char* name, I32 flags)
948 HV* gv_stashsv(SV*, I32 flags)
949
950 The first function takes a literal string, the second uses the string
951 stored in the SV. Remember that a stash is just a hash table, so you
952 get back an "HV*". The "flags" flag will create a new package if it is
953 set to GV_ADD.
954
955 The name that "gv_stash*v" wants is the name of the package whose
956 symbol table you want. The default package is called "main". If you
957 have multiply nested packages, pass their names to "gv_stash*v",
958 separated by "::" as in the Perl language itself.
959
960 Alternately, if you have an SV that is a blessed reference, you can
961 find out the stash pointer by using:
962
963 HV* SvSTASH(SvRV(SV*));
964
965 then use the following to get the package name itself:
966
967 char* HvNAME(HV* stash);
968
969 If you need to bless or re-bless an object you can use the following
970 function:
971
972 SV* sv_bless(SV*, HV* stash)
973
974 where the first argument, an "SV*", must be a reference, and the second
975 argument is a stash. The returned "SV*" can now be used in the same
976 way as any other SV.
977
978 For more information on references and blessings, consult perlref.
979
980 Double-Typed SVs
981 Scalar variables normally contain only one type of value, an integer,
982 double, pointer, or reference. Perl will automatically convert the
983 actual scalar data from the stored type into the requested type.
984
985 Some scalar variables contain more than one type of scalar data. For
986 example, the variable $! contains either the numeric value of "errno"
987 or its string equivalent from either "strerror" or "sys_errlist[]".
988
989 To force multiple data values into an SV, you must do two things: use
990 the "sv_set*v" routines to add the additional scalar type, then set a
991 flag so that Perl will believe it contains more than one type of data.
992 The four macros to set the flags are:
993
994 SvIOK_on
995 SvNOK_on
996 SvPOK_on
997 SvROK_on
998
999 The particular macro you must use depends on which "sv_set*v" routine
1000 you called first. This is because every "sv_set*v" routine turns on
1001 only the bit for the particular type of data being set, and turns off
1002 all the rest.
1003
1004 For example, to create a new Perl variable called "dberror" that
1005 contains both the numeric and descriptive string error values, you
1006 could use the following code:
1007
1008 extern int dberror;
1009 extern char *dberror_list;
1010
1011 SV* sv = get_sv("dberror", GV_ADD);
1012 sv_setiv(sv, (IV) dberror);
1013 sv_setpv(sv, dberror_list[dberror]);
1014 SvIOK_on(sv);
1015
1016 If the order of "sv_setiv" and "sv_setpv" had been reversed, then the
1017 macro "SvPOK_on" would need to be called instead of "SvIOK_on".
1018
1019 Read-Only Values
1020 In Perl 5.16 and earlier, copy-on-write (see the next section) shared a
1021 flag bit with read-only scalars. So the only way to test whether
1022 "sv_setsv", etc., will raise a "Modification of a read-only value"
1023 error in those versions is:
1024
1025 SvREADONLY(sv) && !SvIsCOW(sv)
1026
1027 Under Perl 5.18 and later, SvREADONLY only applies to read-only
1028 variables, and, under 5.20, copy-on-write scalars can also be read-
1029 only, so the above check is incorrect. You just want:
1030
1031 SvREADONLY(sv)
1032
1033 If you need to do this check often, define your own macro like this:
1034
1035 #if PERL_VERSION >= 18
1036 # define SvTRULYREADONLY(sv) SvREADONLY(sv)
1037 #else
1038 # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
1039 #endif
1040
1041 Copy on Write
1042 Perl implements a copy-on-write (COW) mechanism for scalars, in which
1043 string copies are not immediately made when requested, but are deferred
1044 until made necessary by one or the other scalar changing. This is
1045 mostly transparent, but one must take care not to modify string buffers
1046 that are shared by multiple SVs.
1047
1048 You can test whether an SV is using copy-on-write with "SvIsCOW(sv)".
1049
1050 You can force an SV to make its own copy of its string buffer by
1051 calling "sv_force_normal(sv)" or SvPV_force_nolen(sv).
1052
1053 If you want to make the SV drop its string buffer, use
1054 "sv_force_normal_flags(sv, SV_COW_DROP_PV)" or simply "sv_setsv(sv,
1055 NULL)".
1056
1057 All of these functions will croak on read-only scalars (see the
1058 previous section for more on those).
1059
1060 To test that your code is behaving correctly and not modifying COW
1061 buffers, on systems that support mmap(2) (i.e., Unix) you can configure
1062 perl with "-Accflags=-DPERL_DEBUG_READONLY_COW" and it will turn buffer
1063 violations into crashes. You will find it to be marvellously slow, so
1064 you may want to skip perl's own tests.
1065
1066 Magic Variables
1067 [This section still under construction. Ignore everything here. Post
1068 no bills. Everything not permitted is forbidden.]
1069
1070 Any SV may be magical, that is, it has special features that a normal
1071 SV does not have. These features are stored in the SV structure in a
1072 linked list of "struct magic"'s, typedef'ed to "MAGIC".
1073
1074 struct magic {
1075 MAGIC* mg_moremagic;
1076 MGVTBL* mg_virtual;
1077 U16 mg_private;
1078 char mg_type;
1079 U8 mg_flags;
1080 I32 mg_len;
1081 SV* mg_obj;
1082 char* mg_ptr;
1083 };
1084
1085 Note this is current as of patchlevel 0, and could change at any time.
1086
1087 Assigning Magic
1088 Perl adds magic to an SV using the sv_magic function:
1089
1090 void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
1091
1092 The "sv" argument is a pointer to the SV that is to acquire a new
1093 magical feature.
1094
1095 If "sv" is not already magical, Perl uses the "SvUPGRADE" macro to
1096 convert "sv" to type "SVt_PVMG". Perl then continues by adding new
1097 magic to the beginning of the linked list of magical features. Any
1098 prior entry of the same type of magic is deleted. Note that this can
1099 be overridden, and multiple instances of the same type of magic can be
1100 associated with an SV.
1101
1102 The "name" and "namlen" arguments are used to associate a string with
1103 the magic, typically the name of a variable. "namlen" is stored in the
1104 "mg_len" field and if "name" is non-null then either a "savepvn" copy
1105 of "name" or "name" itself is stored in the "mg_ptr" field, depending
1106 on whether "namlen" is greater than zero or equal to zero respectively.
1107 As a special case, if "(name && namlen == HEf_SVKEY)" then "name" is
1108 assumed to contain an "SV*" and is stored as-is with its REFCNT
1109 incremented.
1110
1111 The sv_magic function uses "how" to determine which, if any, predefined
1112 "Magic Virtual Table" should be assigned to the "mg_virtual" field.
1113 See the "Magic Virtual Tables" section below. The "how" argument is
1114 also stored in the "mg_type" field. The value of "how" should be
1115 chosen from the set of macros "PERL_MAGIC_foo" found in perl.h. Note
1116 that before these macros were added, Perl internals used to directly
1117 use character literals, so you may occasionally come across old code or
1118 documentation referring to 'U' magic rather than "PERL_MAGIC_uvar" for
1119 example.
1120
1121 The "obj" argument is stored in the "mg_obj" field of the "MAGIC"
1122 structure. If it is not the same as the "sv" argument, the reference
1123 count of the "obj" object is incremented. If it is the same, or if the
1124 "how" argument is "PERL_MAGIC_arylen", "PERL_MAGIC_regdatum",
1125 "PERL_MAGIC_regdata", or if it is a NULL pointer, then "obj" is merely
1126 stored, without the reference count being incremented.
1127
1128 See also "sv_magicext" in perlapi for a more flexible way to add magic
1129 to an SV.
1130
1131 There is also a function to add magic to an "HV":
1132
1133 void hv_magic(HV *hv, GV *gv, int how);
1134
1135 This simply calls "sv_magic" and coerces the "gv" argument into an
1136 "SV".
1137
1138 To remove the magic from an SV, call the function sv_unmagic:
1139
1140 int sv_unmagic(SV *sv, int type);
1141
1142 The "type" argument should be equal to the "how" value when the "SV"
1143 was initially made magical.
1144
1145 However, note that "sv_unmagic" removes all magic of a certain "type"
1146 from the "SV". If you want to remove only certain magic of a "type"
1147 based on the magic virtual table, use "sv_unmagicext" instead:
1148
1149 int sv_unmagicext(SV *sv, int type, MGVTBL *vtbl);
1150
1151 Magic Virtual Tables
1152 The "mg_virtual" field in the "MAGIC" structure is a pointer to an
1153 "MGVTBL", which is a structure of function pointers and stands for
1154 "Magic Virtual Table" to handle the various operations that might be
1155 applied to that variable.
1156
1157 The "MGVTBL" has five (or sometimes eight) pointers to the following
1158 routine types:
1159
1160 int (*svt_get) (pTHX_ SV* sv, MAGIC* mg);
1161 int (*svt_set) (pTHX_ SV* sv, MAGIC* mg);
1162 U32 (*svt_len) (pTHX_ SV* sv, MAGIC* mg);
1163 int (*svt_clear)(pTHX_ SV* sv, MAGIC* mg);
1164 int (*svt_free) (pTHX_ SV* sv, MAGIC* mg);
1165
1166 int (*svt_copy) (pTHX_ SV *sv, MAGIC* mg, SV *nsv,
1167 const char *name, I32 namlen);
1168 int (*svt_dup) (pTHX_ MAGIC *mg, CLONE_PARAMS *param);
1169 int (*svt_local)(pTHX_ SV *nsv, MAGIC *mg);
1170
1171 This MGVTBL structure is set at compile-time in perl.h and there are
1172 currently 32 types. These different structures contain pointers to
1173 various routines that perform additional actions depending on which
1174 function is being called.
1175
1176 Function pointer Action taken
1177 ---------------- ------------
1178 svt_get Do something before the value of the SV is
1179 retrieved.
1180 svt_set Do something after the SV is assigned a value.
1181 svt_len Report on the SV's length.
1182 svt_clear Clear something the SV represents.
1183 svt_free Free any extra storage associated with the SV.
1184
1185 svt_copy copy tied variable magic to a tied element
1186 svt_dup duplicate a magic structure during thread cloning
1187 svt_local copy magic to local value during 'local'
1188
1189 For instance, the MGVTBL structure called "vtbl_sv" (which corresponds
1190 to an "mg_type" of "PERL_MAGIC_sv") contains:
1191
1192 { magic_get, magic_set, magic_len, 0, 0 }
1193
1194 Thus, when an SV is determined to be magical and of type
1195 "PERL_MAGIC_sv", if a get operation is being performed, the routine
1196 "magic_get" is called. All the various routines for the various
1197 magical types begin with "magic_". NOTE: the magic routines are not
1198 considered part of the Perl API, and may not be exported by the Perl
1199 library.
1200
1201 The last three slots are a recent addition, and for source code
1202 compatibility they are only checked for if one of the three flags
1203 MGf_COPY, MGf_DUP or MGf_LOCAL is set in mg_flags. This means that
1204 most code can continue declaring a vtable as a 5-element value. These
1205 three are currently used exclusively by the threading code, and are
1206 highly subject to change.
1207
1208 The current kinds of Magic Virtual Tables are:
1209
1210 mg_type
1211 (old-style char and macro) MGVTBL Type of magic
1212 -------------------------- ------ -------------
1213 \0 PERL_MAGIC_sv vtbl_sv Special scalar variable
1214 # PERL_MAGIC_arylen vtbl_arylen Array length ($#ary)
1215 % PERL_MAGIC_rhash (none) Extra data for restricted
1216 hashes
1217 * PERL_MAGIC_debugvar vtbl_debugvar $DB::single, signal, trace
1218 vars
1219 . PERL_MAGIC_pos vtbl_pos pos() lvalue
1220 : PERL_MAGIC_symtab (none) Extra data for symbol
1221 tables
1222 < PERL_MAGIC_backref vtbl_backref For weak ref data
1223 @ PERL_MAGIC_arylen_p (none) To move arylen out of XPVAV
1224 B PERL_MAGIC_bm vtbl_regexp Boyer-Moore
1225 (fast string search)
1226 c PERL_MAGIC_overload_table vtbl_ovrld Holds overload table
1227 (AMT) on stash
1228 D PERL_MAGIC_regdata vtbl_regdata Regex match position data
1229 (@+ and @- vars)
1230 d PERL_MAGIC_regdatum vtbl_regdatum Regex match position data
1231 element
1232 E PERL_MAGIC_env vtbl_env %ENV hash
1233 e PERL_MAGIC_envelem vtbl_envelem %ENV hash element
1234 f PERL_MAGIC_fm vtbl_regexp Formline
1235 ('compiled' format)
1236 g PERL_MAGIC_regex_global vtbl_mglob m//g target
1237 H PERL_MAGIC_hints vtbl_hints %^H hash
1238 h PERL_MAGIC_hintselem vtbl_hintselem %^H hash element
1239 I PERL_MAGIC_isa vtbl_isa @ISA array
1240 i PERL_MAGIC_isaelem vtbl_isaelem @ISA array element
1241 k PERL_MAGIC_nkeys vtbl_nkeys scalar(keys()) lvalue
1242 L PERL_MAGIC_dbfile (none) Debugger %_<filename
1243 l PERL_MAGIC_dbline vtbl_dbline Debugger %_<filename
1244 element
1245 N PERL_MAGIC_shared (none) Shared between threads
1246 n PERL_MAGIC_shared_scalar (none) Shared between threads
1247 o PERL_MAGIC_collxfrm vtbl_collxfrm Locale transformation
1248 P PERL_MAGIC_tied vtbl_pack Tied array or hash
1249 p PERL_MAGIC_tiedelem vtbl_packelem Tied array or hash element
1250 q PERL_MAGIC_tiedscalar vtbl_packelem Tied scalar or handle
1251 r PERL_MAGIC_qr vtbl_regexp Precompiled qr// regex
1252 S PERL_MAGIC_sig (none) %SIG hash
1253 s PERL_MAGIC_sigelem vtbl_sigelem %SIG hash element
1254 t PERL_MAGIC_taint vtbl_taint Taintedness
1255 U PERL_MAGIC_uvar vtbl_uvar Available for use by
1256 extensions
1257 u PERL_MAGIC_uvar_elem (none) Reserved for use by
1258 extensions
1259 V PERL_MAGIC_vstring (none) SV was vstring literal
1260 v PERL_MAGIC_vec vtbl_vec vec() lvalue
1261 w PERL_MAGIC_utf8 vtbl_utf8 Cached UTF-8 information
1262 x PERL_MAGIC_substr vtbl_substr substr() lvalue
1263 Y PERL_MAGIC_nonelem vtbl_nonelem Array element that does not
1264 exist
1265 y PERL_MAGIC_defelem vtbl_defelem Shadow "foreach" iterator
1266 variable / smart parameter
1267 vivification
1268 \ PERL_MAGIC_lvref vtbl_lvref Lvalue reference
1269 constructor
1270 ] PERL_MAGIC_checkcall vtbl_checkcall Inlining/mutation of call
1271 to this CV
1272 ~ PERL_MAGIC_ext (none) Available for use by
1273 extensions
1274
1275 When an uppercase and lowercase letter both exist in the table, then
1276 the uppercase letter is typically used to represent some kind of
1277 composite type (a list or a hash), and the lowercase letter is used to
1278 represent an element of that composite type. Some internals code makes
1279 use of this case relationship. However, 'v' and 'V' (vec and v-string)
1280 are in no way related.
1281
1282 The "PERL_MAGIC_ext" and "PERL_MAGIC_uvar" magic types are defined
1283 specifically for use by extensions and will not be used by perl itself.
1284 Extensions can use "PERL_MAGIC_ext" magic to 'attach' private
1285 information to variables (typically objects). This is especially
1286 useful because there is no way for normal perl code to corrupt this
1287 private information (unlike using extra elements of a hash object).
1288
1289 Similarly, "PERL_MAGIC_uvar" magic can be used much like tie() to call
1290 a C function any time a scalar's value is used or changed. The
1291 "MAGIC"'s "mg_ptr" field points to a "ufuncs" structure:
1292
1293 struct ufuncs {
1294 I32 (*uf_val)(pTHX_ IV, SV*);
1295 I32 (*uf_set)(pTHX_ IV, SV*);
1296 IV uf_index;
1297 };
1298
1299 When the SV is read from or written to, the "uf_val" or "uf_set"
1300 function will be called with "uf_index" as the first arg and a pointer
1301 to the SV as the second. A simple example of how to add
1302 "PERL_MAGIC_uvar" magic is shown below. Note that the ufuncs structure
1303 is copied by sv_magic, so you can safely allocate it on the stack.
1304
1305 void
1306 Umagic(sv)
1307 SV *sv;
1308 PREINIT:
1309 struct ufuncs uf;
1310 CODE:
1311 uf.uf_val = &my_get_fn;
1312 uf.uf_set = &my_set_fn;
1313 uf.uf_index = 0;
1314 sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
1315
1316 Attaching "PERL_MAGIC_uvar" to arrays is permissible but has no effect.
1317
1318 For hashes there is a specialized hook that gives control over hash
1319 keys (but not values). This hook calls "PERL_MAGIC_uvar" 'get' magic
1320 if the "set" function in the "ufuncs" structure is NULL. The hook is
1321 activated whenever the hash is accessed with a key specified as an "SV"
1322 through the functions "hv_store_ent", "hv_fetch_ent", "hv_delete_ent",
1323 and "hv_exists_ent". Accessing the key as a string through the
1324 functions without the "..._ent" suffix circumvents the hook. See
1325 "GUTS" in Hash::Util::FieldHash for a detailed description.
1326
1327 Note that because multiple extensions may be using "PERL_MAGIC_ext" or
1328 "PERL_MAGIC_uvar" magic, it is important for extensions to take extra
1329 care to avoid conflict. Typically only using the magic on objects
1330 blessed into the same class as the extension is sufficient. For
1331 "PERL_MAGIC_ext" magic, it is usually a good idea to define an
1332 "MGVTBL", even if all its fields will be 0, so that individual "MAGIC"
1333 pointers can be identified as a particular kind of magic using their
1334 magic virtual table. "mg_findext" provides an easy way to do that:
1335
1336 STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };
1337
1338 MAGIC *mg;
1339 if ((mg = mg_findext(sv, PERL_MAGIC_ext, &my_vtbl))) {
1340 /* this is really ours, not another module's PERL_MAGIC_ext */
1341 my_priv_data_t *priv = (my_priv_data_t *)mg->mg_ptr;
1342 ...
1343 }
1344
1345 Also note that the "sv_set*()" and "sv_cat*()" functions described
1346 earlier do not invoke 'set' magic on their targets. This must be done
1347 by the user either by calling the "SvSETMAGIC()" macro after calling
1348 these functions, or by using one of the "sv_set*_mg()" or
1349 "sv_cat*_mg()" functions. Similarly, generic C code must call the
1350 "SvGETMAGIC()" macro to invoke any 'get' magic if they use an SV
1351 obtained from external sources in functions that don't handle magic.
1352 See perlapi for a description of these functions. For example, calls
1353 to the "sv_cat*()" functions typically need to be followed by
1354 "SvSETMAGIC()", but they don't need a prior "SvGETMAGIC()" since their
1355 implementation handles 'get' magic.
1356
1357 Finding Magic
1358 MAGIC *mg_find(SV *sv, int type); /* Finds the magic pointer of that
1359 * type */
1360
1361 This routine returns a pointer to a "MAGIC" structure stored in the SV.
1362 If the SV does not have that magical feature, "NULL" is returned. If
1363 the SV has multiple instances of that magical feature, the first one
1364 will be returned. "mg_findext" can be used to find a "MAGIC" structure
1365 of an SV based on both its magic type and its magic virtual table:
1366
1367 MAGIC *mg_findext(SV *sv, int type, MGVTBL *vtbl);
1368
1369 Also, if the SV passed to "mg_find" or "mg_findext" is not of type
1370 SVt_PVMG, Perl may core dump.
1371
1372 int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
1373
1374 This routine checks to see what types of magic "sv" has. If the
1375 mg_type field is an uppercase letter, then the mg_obj is copied to
1376 "nsv", but the mg_type field is changed to be the lowercase letter.
1377
1378 Understanding the Magic of Tied Hashes and Arrays
1379 Tied hashes and arrays are magical beasts of the "PERL_MAGIC_tied"
1380 magic type.
1381
1382 WARNING: As of the 5.004 release, proper usage of the array and hash
1383 access functions requires understanding a few caveats. Some of these
1384 caveats are actually considered bugs in the API, to be fixed in later
1385 releases, and are bracketed with [MAYCHANGE] below. If you find
1386 yourself actually applying such information in this section, be aware
1387 that the behavior may change in the future, umm, without warning.
1388
1389 The perl tie function associates a variable with an object that
1390 implements the various GET, SET, etc methods. To perform the
1391 equivalent of the perl tie function from an XSUB, you must mimic this
1392 behaviour. The code below carries out the necessary steps -- firstly
1393 it creates a new hash, and then creates a second hash which it blesses
1394 into the class which will implement the tie methods. Lastly it ties
1395 the two hashes together, and returns a reference to the new tied hash.
1396 Note that the code below does NOT call the TIEHASH method in the MyTie
1397 class - see "Calling Perl Routines from within C Programs" for details
1398 on how to do this.
1399
1400 SV*
1401 mytie()
1402 PREINIT:
1403 HV *hash;
1404 HV *stash;
1405 SV *tie;
1406 CODE:
1407 hash = newHV();
1408 tie = newRV_noinc((SV*)newHV());
1409 stash = gv_stashpv("MyTie", GV_ADD);
1410 sv_bless(tie, stash);
1411 hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
1412 RETVAL = newRV_noinc(hash);
1413 OUTPUT:
1414 RETVAL
1415
1416 The "av_store" function, when given a tied array argument, merely
1417 copies the magic of the array onto the value to be "stored", using
1418 "mg_copy". It may also return NULL, indicating that the value did not
1419 actually need to be stored in the array. [MAYCHANGE] After a call to
1420 "av_store" on a tied array, the caller will usually need to call
1421 "mg_set(val)" to actually invoke the perl level "STORE" method on the
1422 TIEARRAY object. If "av_store" did return NULL, a call to
1423 "SvREFCNT_dec(val)" will also be usually necessary to avoid a memory
1424 leak. [/MAYCHANGE]
1425
1426 The previous paragraph is applicable verbatim to tied hash access using
1427 the "hv_store" and "hv_store_ent" functions as well.
1428
1429 "av_fetch" and the corresponding hash functions "hv_fetch" and
1430 "hv_fetch_ent" actually return an undefined mortal value whose magic
1431 has been initialized using "mg_copy". Note the value so returned does
1432 not need to be deallocated, as it is already mortal. [MAYCHANGE] But
1433 you will need to call "mg_get()" on the returned value in order to
1434 actually invoke the perl level "FETCH" method on the underlying TIE
1435 object. Similarly, you may also call "mg_set()" on the return value
1436 after possibly assigning a suitable value to it using "sv_setsv",
1437 which will invoke the "STORE" method on the TIE object. [/MAYCHANGE]
1438
1439 [MAYCHANGE] In other words, the array or hash fetch/store functions
1440 don't really fetch and store actual values in the case of tied arrays
1441 and hashes. They merely call "mg_copy" to attach magic to the values
1442 that were meant to be "stored" or "fetched". Later calls to "mg_get"
1443 and "mg_set" actually do the job of invoking the TIE methods on the
1444 underlying objects. Thus the magic mechanism currently implements a
1445 kind of lazy access to arrays and hashes.
1446
1447 Currently (as of perl version 5.004), use of the hash and array access
1448 functions requires the user to be aware of whether they are operating
1449 on "normal" hashes and arrays, or on their tied variants. The API may
1450 be changed to provide more transparent access to both tied and normal
1451 data types in future versions. [/MAYCHANGE]
1452
1453 You would do well to understand that the TIEARRAY and TIEHASH
1454 interfaces are mere sugar to invoke some perl method calls while using
1455 the uniform hash and array syntax. The use of this sugar imposes some
1456 overhead (typically about two to four extra opcodes per FETCH/STORE
1457 operation, in addition to the creation of all the mortal variables
1458 required to invoke the methods). This overhead will be comparatively
1459 small if the TIE methods are themselves substantial, but if they are
1460 only a few statements long, the overhead will not be insignificant.
1461
1462 Localizing changes
1463 Perl has a very handy construction
1464
1465 {
1466 local $var = 2;
1467 ...
1468 }
1469
1470 This construction is approximately equivalent to
1471
1472 {
1473 my $oldvar = $var;
1474 $var = 2;
1475 ...
1476 $var = $oldvar;
1477 }
1478
1479 The biggest difference is that the first construction would reinstate
1480 the initial value of $var, irrespective of how control exits the block:
1481 "goto", "return", "die"/"eval", etc. It is a little bit more efficient
1482 as well.
1483
1484 There is a way to achieve a similar task from C via Perl API: create a
1485 pseudo-block, and arrange for some changes to be automatically undone
1486 at the end of it, either explicit, or via a non-local exit (via die()).
1487 A block-like construct is created by a pair of "ENTER"/"LEAVE" macros
1488 (see "Returning a Scalar" in perlcall). Such a construct may be
1489 created specially for some important localized task, or an existing one
1490 (like boundaries of enclosing Perl subroutine/block, or an existing
1491 pair for freeing TMPs) may be used. (In the second case the overhead
1492 of additional localization must be almost negligible.) Note that any
1493 XSUB is automatically enclosed in an "ENTER"/"LEAVE" pair.
1494
1495 Inside such a pseudo-block the following service is available:
1496
1497 "SAVEINT(int i)"
1498 "SAVEIV(IV i)"
1499 "SAVEI32(I32 i)"
1500 "SAVELONG(long i)"
1501 These macros arrange things to restore the value of integer
1502 variable "i" at the end of enclosing pseudo-block.
1503
1504 SAVESPTR(s)
1505 SAVEPPTR(p)
1506 These macros arrange things to restore the value of pointers "s"
1507 and "p". "s" must be a pointer of a type which survives conversion
1508 to "SV*" and back, "p" should be able to survive conversion to
1509 "char*" and back.
1510
1511 "SAVEFREESV(SV *sv)"
1512 The refcount of "sv" will be decremented at the end of pseudo-
1513 block. This is similar to "sv_2mortal" in that it is also a
1514 mechanism for doing a delayed "SvREFCNT_dec". However, while
1515 "sv_2mortal" extends the lifetime of "sv" until the beginning of
1516 the next statement, "SAVEFREESV" extends it until the end of the
1517 enclosing scope. These lifetimes can be wildly different.
1518
1519 Also compare "SAVEMORTALIZESV".
1520
1521 "SAVEMORTALIZESV(SV *sv)"
1522 Just like "SAVEFREESV", but mortalizes "sv" at the end of the
1523 current scope instead of decrementing its reference count. This
1524 usually has the effect of keeping "sv" alive until the statement
1525 that called the currently live scope has finished executing.
1526
1527 "SAVEFREEOP(OP *op)"
1528 The "OP *" is op_free()ed at the end of pseudo-block.
1529
1530 SAVEFREEPV(p)
1531 The chunk of memory which is pointed to by "p" is Safefree()ed at
1532 the end of pseudo-block.
1533
1534 "SAVECLEARSV(SV *sv)"
1535 Clears a slot in the current scratchpad which corresponds to "sv"
1536 at the end of pseudo-block.
1537
1538 "SAVEDELETE(HV *hv, char *key, I32 length)"
1539 The key "key" of "hv" is deleted at the end of pseudo-block. The
1540 string pointed to by "key" is Safefree()ed. If one has a key in
1541 short-lived storage, the corresponding string may be reallocated
1542 like this:
1543
1544 SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
1545
1546 "SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)"
1547 At the end of pseudo-block the function "f" is called with the only
1548 argument "p".
1549
1550 "SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)"
1551 At the end of pseudo-block the function "f" is called with the
1552 implicit context argument (if any), and "p".
1553
1554 "SAVESTACK_POS()"
1555 The current offset on the Perl internal stack (cf. "SP") is
1556 restored at the end of pseudo-block.
1557
1558 The following API list contains functions, thus one needs to provide
1559 pointers to the modifiable data explicitly (either C pointers, or
1560 Perlish "GV *"s). Where the above macros take "int", a similar
1561 function takes "int *".
1562
1563 "SV* save_scalar(GV *gv)"
1564 Equivalent to Perl code "local $gv".
1565
1566 "AV* save_ary(GV *gv)"
1567 "HV* save_hash(GV *gv)"
1568 Similar to "save_scalar", but localize @gv and %gv.
1569
1570 "void save_item(SV *item)"
1571 Duplicates the current value of "SV". On the exit from the current
1572 "ENTER"/"LEAVE" pseudo-block the value of "SV" will be restored
1573 using the stored value. It doesn't handle magic. Use
1574 "save_scalar" if magic is affected.
1575
1576 "void save_list(SV **sarg, I32 maxsarg)"
1577 A variant of "save_item" which takes multiple arguments via an
1578 array "sarg" of "SV*" of length "maxsarg".
1579
1580 "SV* save_svref(SV **sptr)"
1581 Similar to "save_scalar", but will reinstate an "SV *".
1582
1583 "void save_aptr(AV **aptr)"
1584 "void save_hptr(HV **hptr)"
1585 Similar to "save_svref", but localize "AV *" and "HV *".
1586
1587 The "Alias" module implements localization of the basic types within
1588 the caller's scope. People who are interested in how to localize
1589 things in the containing scope should take a look there too.
1590
1592 XSUBs and the Argument Stack
1593 The XSUB mechanism is a simple way for Perl programs to access C
1594 subroutines. An XSUB routine will have a stack that contains the
1595 arguments from the Perl program, and a way to map from the Perl data
1596 structures to a C equivalent.
1597
1598 The stack arguments are accessible through the ST(n) macro, which
1599 returns the "n"'th stack argument. Argument 0 is the first argument
1600 passed in the Perl subroutine call. These arguments are "SV*", and can
1601 be used anywhere an "SV*" is used.
1602
1603 Most of the time, output from the C routine can be handled through use
1604 of the RETVAL and OUTPUT directives. However, there are some cases
1605 where the argument stack is not already long enough to handle all the
1606 return values. An example is the POSIX tzname() call, which takes no
1607 arguments, but returns two, the local time zone's standard and summer
1608 time abbreviations.
1609
1610 To handle this situation, the PPCODE directive is used and the stack is
1611 extended using the macro:
1612
1613 EXTEND(SP, num);
1614
1615 where "SP" is the macro that represents the local copy of the stack
1616 pointer, and "num" is the number of elements the stack should be
1617 extended by.
1618
1619 Now that there is room on the stack, values can be pushed on it using
1620 "PUSHs" macro. The pushed values will often need to be "mortal" (See
1621 "Reference Counts and Mortality"):
1622
1623 PUSHs(sv_2mortal(newSViv(an_integer)))
1624 PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
1625 PUSHs(sv_2mortal(newSVnv(a_double)))
1626 PUSHs(sv_2mortal(newSVpv("Some String",0)))
1627 /* Although the last example is better written as the more
1628 * efficient: */
1629 PUSHs(newSVpvs_flags("Some String", SVs_TEMP))
1630
1631 And now the Perl program calling "tzname", the two values will be
1632 assigned as in:
1633
1634 ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
1635
1636 An alternate (and possibly simpler) method to pushing values on the
1637 stack is to use the macro:
1638
1639 XPUSHs(SV*)
1640
1641 This macro automatically adjusts the stack for you, if needed. Thus,
1642 you do not need to call "EXTEND" to extend the stack.
1643
1644 Despite their suggestions in earlier versions of this document the
1645 macros "(X)PUSH[iunp]" are not suited to XSUBs which return multiple
1646 results. For that, either stick to the "(X)PUSHs" macros shown above,
1647 or use the new "m(X)PUSH[iunp]" macros instead; see "Putting a C value
1648 on Perl stack".
1649
1650 For more information, consult perlxs and perlxstut.
1651
1652 Autoloading with XSUBs
1653 If an AUTOLOAD routine is an XSUB, as with Perl subroutines, Perl puts
1654 the fully-qualified name of the autoloaded subroutine in the $AUTOLOAD
1655 variable of the XSUB's package.
1656
1657 But it also puts the same information in certain fields of the XSUB
1658 itself:
1659
1660 HV *stash = CvSTASH(cv);
1661 const char *subname = SvPVX(cv);
1662 STRLEN name_length = SvCUR(cv); /* in bytes */
1663 U32 is_utf8 = SvUTF8(cv);
1664
1665 "SvPVX(cv)" contains just the sub name itself, not including the
1666 package. For an AUTOLOAD routine in UNIVERSAL or one of its
1667 superclasses, "CvSTASH(cv)" returns NULL during a method call on a
1668 nonexistent package.
1669
1670 Note: Setting $AUTOLOAD stopped working in 5.6.1, which did not support
1671 XS AUTOLOAD subs at all. Perl 5.8.0 introduced the use of fields in
1672 the XSUB itself. Perl 5.16.0 restored the setting of $AUTOLOAD. If
1673 you need to support 5.8-5.14, use the XSUB's fields.
1674
1675 Calling Perl Routines from within C Programs
1676 There are four routines that can be used to call a Perl subroutine from
1677 within a C program. These four are:
1678
1679 I32 call_sv(SV*, I32);
1680 I32 call_pv(const char*, I32);
1681 I32 call_method(const char*, I32);
1682 I32 call_argv(const char*, I32, char**);
1683
1684 The routine most often used is "call_sv". The "SV*" argument contains
1685 either the name of the Perl subroutine to be called, or a reference to
1686 the subroutine. The second argument consists of flags that control the
1687 context in which the subroutine is called, whether or not the
1688 subroutine is being passed arguments, how errors should be trapped, and
1689 how to treat return values.
1690
1691 All four routines return the number of arguments that the subroutine
1692 returned on the Perl stack.
1693
1694 These routines used to be called "perl_call_sv", etc., before Perl
1695 v5.6.0, but those names are now deprecated; macros of the same name are
1696 provided for compatibility.
1697
1698 When using any of these routines (except "call_argv"), the programmer
1699 must manipulate the Perl stack. These include the following macros and
1700 functions:
1701
1702 dSP
1703 SP
1704 PUSHMARK()
1705 PUTBACK
1706 SPAGAIN
1707 ENTER
1708 SAVETMPS
1709 FREETMPS
1710 LEAVE
1711 XPUSH*()
1712 POP*()
1713
1714 For a detailed description of calling conventions from C to Perl,
1715 consult perlcall.
1716
1717 Putting a C value on Perl stack
1718 A lot of opcodes (this is an elementary operation in the internal perl
1719 stack machine) put an SV* on the stack. However, as an optimization
1720 the corresponding SV is (usually) not recreated each time. The opcodes
1721 reuse specially assigned SVs (targets) which are (as a corollary) not
1722 constantly freed/created.
1723
1724 Each of the targets is created only once (but see "Scratchpads and
1725 recursion" below), and when an opcode needs to put an integer, a
1726 double, or a string on stack, it just sets the corresponding parts of
1727 its target and puts the target on stack.
1728
1729 The macro to put this target on stack is "PUSHTARG", and it is directly
1730 used in some opcodes, as well as indirectly in zillions of others,
1731 which use it via "(X)PUSH[iunp]".
1732
1733 Because the target is reused, you must be careful when pushing multiple
1734 values on the stack. The following code will not do what you think:
1735
1736 XPUSHi(10);
1737 XPUSHi(20);
1738
1739 This translates as "set "TARG" to 10, push a pointer to "TARG" onto the
1740 stack; set "TARG" to 20, push a pointer to "TARG" onto the stack". At
1741 the end of the operation, the stack does not contain the values 10 and
1742 20, but actually contains two pointers to "TARG", which we have set to
1743 20.
1744
1745 If you need to push multiple different values then you should either
1746 use the "(X)PUSHs" macros, or else use the new "m(X)PUSH[iunp]" macros,
1747 none of which make use of "TARG". The "(X)PUSHs" macros simply push an
1748 SV* on the stack, which, as noted under "XSUBs and the Argument Stack",
1749 will often need to be "mortal". The new "m(X)PUSH[iunp]" macros make
1750 this a little easier to achieve by creating a new mortal for you (via
1751 "(X)PUSHmortal"), pushing that onto the stack (extending it if
1752 necessary in the case of the "mXPUSH[iunp]" macros), and then setting
1753 its value. Thus, instead of writing this to "fix" the example above:
1754
1755 XPUSHs(sv_2mortal(newSViv(10)))
1756 XPUSHs(sv_2mortal(newSViv(20)))
1757
1758 you can simply write:
1759
1760 mXPUSHi(10)
1761 mXPUSHi(20)
1762
1763 On a related note, if you do use "(X)PUSH[iunp]", then you're going to
1764 need a "dTARG" in your variable declarations so that the "*PUSH*"
1765 macros can make use of the local variable "TARG". See also "dTARGET"
1766 and "dXSTARG".
1767
1768 Scratchpads
1769 The question remains on when the SVs which are targets for opcodes are
1770 created. The answer is that they are created when the current unit--a
1771 subroutine or a file (for opcodes for statements outside of
1772 subroutines)--is compiled. During this time a special anonymous Perl
1773 array is created, which is called a scratchpad for the current unit.
1774
1775 A scratchpad keeps SVs which are lexicals for the current unit and are
1776 targets for opcodes. A previous version of this document stated that
1777 one can deduce that an SV lives on a scratchpad by looking on its
1778 flags: lexicals have "SVs_PADMY" set, and targets have "SVs_PADTMP"
1779 set. But this has never been fully true. "SVs_PADMY" could be set on
1780 a variable that no longer resides in any pad. While targets do have
1781 "SVs_PADTMP" set, it can also be set on variables that have never
1782 resided in a pad, but nonetheless act like targets. As of perl 5.21.5,
1783 the "SVs_PADMY" flag is no longer used and is defined as 0.
1784 "SvPADMY()" now returns true for anything without "SVs_PADTMP".
1785
1786 The correspondence between OPs and targets is not 1-to-1. Different
1787 OPs in the compile tree of the unit can use the same target, if this
1788 would not conflict with the expected life of the temporary.
1789
1790 Scratchpads and recursion
1791 In fact it is not 100% true that a compiled unit contains a pointer to
1792 the scratchpad AV. In fact it contains a pointer to an AV of
1793 (initially) one element, and this element is the scratchpad AV. Why do
1794 we need an extra level of indirection?
1795
1796 The answer is recursion, and maybe threads. Both these can create
1797 several execution pointers going into the same subroutine. For the
1798 subroutine-child not write over the temporaries for the subroutine-
1799 parent (lifespan of which covers the call to the child), the parent and
1800 the child should have different scratchpads. (And the lexicals should
1801 be separate anyway!)
1802
1803 So each subroutine is born with an array of scratchpads (of length 1).
1804 On each entry to the subroutine it is checked that the current depth of
1805 the recursion is not more than the length of this array, and if it is,
1806 new scratchpad is created and pushed into the array.
1807
1808 The targets on this scratchpad are "undef"s, but they are already
1809 marked with correct flags.
1810
1812 Allocation
1813 All memory meant to be used with the Perl API functions should be
1814 manipulated using the macros described in this section. The macros
1815 provide the necessary transparency between differences in the actual
1816 malloc implementation that is used within perl.
1817
1818 The following three macros are used to initially allocate memory :
1819
1820 Newx(pointer, number, type);
1821 Newxc(pointer, number, type, cast);
1822 Newxz(pointer, number, type);
1823
1824 The first argument "pointer" should be the name of a variable that will
1825 point to the newly allocated memory.
1826
1827 The second and third arguments "number" and "type" specify how many of
1828 the specified type of data structure should be allocated. The argument
1829 "type" is passed to "sizeof". The final argument to "Newxc", "cast",
1830 should be used if the "pointer" argument is different from the "type"
1831 argument.
1832
1833 Unlike the "Newx" and "Newxc" macros, the "Newxz" macro calls "memzero"
1834 to zero out all the newly allocated memory.
1835
1836 Reallocation
1837 Renew(pointer, number, type);
1838 Renewc(pointer, number, type, cast);
1839 Safefree(pointer)
1840
1841 These three macros are used to change a memory buffer size or to free a
1842 piece of memory no longer needed. The arguments to "Renew" and
1843 "Renewc" match those of "New" and "Newc" with the exception of not
1844 needing the "magic cookie" argument.
1845
1846 Moving
1847 Move(source, dest, number, type);
1848 Copy(source, dest, number, type);
1849 Zero(dest, number, type);
1850
1851 These three macros are used to move, copy, or zero out previously
1852 allocated memory. The "source" and "dest" arguments point to the
1853 source and destination starting points. Perl will move, copy, or zero
1854 out "number" instances of the size of the "type" data structure (using
1855 the "sizeof" function).
1856
1858 The most recent development releases of Perl have been experimenting
1859 with removing Perl's dependency on the "normal" standard I/O suite and
1860 allowing other stdio implementations to be used. This involves
1861 creating a new abstraction layer that then calls whichever
1862 implementation of stdio Perl was compiled with. All XSUBs should now
1863 use the functions in the PerlIO abstraction layer and not make any
1864 assumptions about what kind of stdio is being used.
1865
1866 For a complete description of the PerlIO abstraction, consult perlapio.
1867
1869 Code tree
1870 Here we describe the internal form your code is converted to by Perl.
1871 Start with a simple example:
1872
1873 $a = $b + $c;
1874
1875 This is converted to a tree similar to this one:
1876
1877 assign-to
1878 / \
1879 + $a
1880 / \
1881 $b $c
1882
1883 (but slightly more complicated). This tree reflects the way Perl
1884 parsed your code, but has nothing to do with the execution order.
1885 There is an additional "thread" going through the nodes of the tree
1886 which shows the order of execution of the nodes. In our simplified
1887 example above it looks like:
1888
1889 $b ---> $c ---> + ---> $a ---> assign-to
1890
1891 But with the actual compile tree for "$a = $b + $c" it is different:
1892 some nodes optimized away. As a corollary, though the actual tree
1893 contains more nodes than our simplified example, the execution order is
1894 the same as in our example.
1895
1896 Examining the tree
1897 If you have your perl compiled for debugging (usually done with
1898 "-DDEBUGGING" on the "Configure" command line), you may examine the
1899 compiled tree by specifying "-Dx" on the Perl command line. The output
1900 takes several lines per node, and for "$b+$c" it looks like this:
1901
1902 5 TYPE = add ===> 6
1903 TARG = 1
1904 FLAGS = (SCALAR,KIDS)
1905 {
1906 TYPE = null ===> (4)
1907 (was rv2sv)
1908 FLAGS = (SCALAR,KIDS)
1909 {
1910 3 TYPE = gvsv ===> 4
1911 FLAGS = (SCALAR)
1912 GV = main::b
1913 }
1914 }
1915 {
1916 TYPE = null ===> (5)
1917 (was rv2sv)
1918 FLAGS = (SCALAR,KIDS)
1919 {
1920 4 TYPE = gvsv ===> 5
1921 FLAGS = (SCALAR)
1922 GV = main::c
1923 }
1924 }
1925
1926 This tree has 5 nodes (one per "TYPE" specifier), only 3 of them are
1927 not optimized away (one per number in the left column). The immediate
1928 children of the given node correspond to "{}" pairs on the same level
1929 of indentation, thus this listing corresponds to the tree:
1930
1931 add
1932 / \
1933 null null
1934 | |
1935 gvsv gvsv
1936
1937 The execution order is indicated by "===>" marks, thus it is "3 4 5 6"
1938 (node 6 is not included into above listing), i.e., "gvsv gvsv add
1939 whatever".
1940
1941 Each of these nodes represents an op, a fundamental operation inside
1942 the Perl core. The code which implements each operation can be found
1943 in the pp*.c files; the function which implements the op with type
1944 "gvsv" is "pp_gvsv", and so on. As the tree above shows, different ops
1945 have different numbers of children: "add" is a binary operator, as one
1946 would expect, and so has two children. To accommodate the various
1947 different numbers of children, there are various types of op data
1948 structure, and they link together in different ways.
1949
1950 The simplest type of op structure is "OP": this has no children. Unary
1951 operators, "UNOP"s, have one child, and this is pointed to by the
1952 "op_first" field. Binary operators ("BINOP"s) have not only an
1953 "op_first" field but also an "op_last" field. The most complex type of
1954 op is a "LISTOP", which has any number of children. In this case, the
1955 first child is pointed to by "op_first" and the last child by
1956 "op_last". The children in between can be found by iteratively
1957 following the "OpSIBLING" pointer from the first child to the last (but
1958 see below).
1959
1960 There are also some other op types: a "PMOP" holds a regular
1961 expression, and has no children, and a "LOOP" may or may not have
1962 children. If the "op_children" field is non-zero, it behaves like a
1963 "LISTOP". To complicate matters, if a "UNOP" is actually a "null" op
1964 after optimization (see "Compile pass 2: context propagation") it will
1965 still have children in accordance with its former type.
1966
1967 Finally, there is a "LOGOP", or logic op. Like a "LISTOP", this has one
1968 or more children, but it doesn't have an "op_last" field: so you have
1969 to follow "op_first" and then the "OpSIBLING" chain itself to find the
1970 last child. Instead it has an "op_other" field, which is comparable to
1971 the "op_next" field described below, and represents an alternate
1972 execution path. Operators like "and", "or" and "?" are "LOGOP"s. Note
1973 that in general, "op_other" may not point to any of the direct children
1974 of the "LOGOP".
1975
1976 Starting in version 5.21.2, perls built with the experimental define
1977 "-DPERL_OP_PARENT" add an extra boolean flag for each op, "op_moresib".
1978 When not set, this indicates that this is the last op in an "OpSIBLING"
1979 chain. This frees up the "op_sibling" field on the last sibling to
1980 point back to the parent op. Under this build, that field is also
1981 renamed "op_sibparent" to reflect its joint role. The macro
1982 OpSIBLING(o) wraps this special behaviour, and always returns NULL on
1983 the last sibling. With this build the op_parent(o) function can be
1984 used to find the parent of any op. Thus for forward compatibility, you
1985 should always use the OpSIBLING(o) macro rather than accessing
1986 "op_sibling" directly.
1987
1988 Another way to examine the tree is to use a compiler back-end module,
1989 such as B::Concise.
1990
1991 Compile pass 1: check routines
1992 The tree is created by the compiler while yacc code feeds it the
1993 constructions it recognizes. Since yacc works bottom-up, so does the
1994 first pass of perl compilation.
1995
1996 What makes this pass interesting for perl developers is that some
1997 optimization may be performed on this pass. This is optimization by
1998 so-called "check routines". The correspondence between node names and
1999 corresponding check routines is described in opcode.pl (do not forget
2000 to run "make regen_headers" if you modify this file).
2001
2002 A check routine is called when the node is fully constructed except for
2003 the execution-order thread. Since at this time there are no back-links
2004 to the currently constructed node, one can do most any operation to the
2005 top-level node, including freeing it and/or creating new nodes
2006 above/below it.
2007
2008 The check routine returns the node which should be inserted into the
2009 tree (if the top-level node was not modified, check routine returns its
2010 argument).
2011
2012 By convention, check routines have names "ck_*". They are usually
2013 called from "new*OP" subroutines (or "convert") (which in turn are
2014 called from perly.y).
2015
2016 Compile pass 1a: constant folding
2017 Immediately after the check routine is called the returned node is
2018 checked for being compile-time executable. If it is (the value is
2019 judged to be constant) it is immediately executed, and a constant node
2020 with the "return value" of the corresponding subtree is substituted
2021 instead. The subtree is deleted.
2022
2023 If constant folding was not performed, the execution-order thread is
2024 created.
2025
2026 Compile pass 2: context propagation
2027 When a context for a part of compile tree is known, it is propagated
2028 down through the tree. At this time the context can have 5 values
2029 (instead of 2 for runtime context): void, boolean, scalar, list, and
2030 lvalue. In contrast with the pass 1 this pass is processed from top to
2031 bottom: a node's context determines the context for its children.
2032
2033 Additional context-dependent optimizations are performed at this time.
2034 Since at this moment the compile tree contains back-references (via
2035 "thread" pointers), nodes cannot be free()d now. To allow optimized-
2036 away nodes at this stage, such nodes are null()ified instead of
2037 free()ing (i.e. their type is changed to OP_NULL).
2038
2039 Compile pass 3: peephole optimization
2040 After the compile tree for a subroutine (or for an "eval" or a file) is
2041 created, an additional pass over the code is performed. This pass is
2042 neither top-down or bottom-up, but in the execution order (with
2043 additional complications for conditionals). Optimizations performed at
2044 this stage are subject to the same restrictions as in the pass 2.
2045
2046 Peephole optimizations are done by calling the function pointed to by
2047 the global variable "PL_peepp". By default, "PL_peepp" just calls the
2048 function pointed to by the global variable "PL_rpeepp". By default,
2049 that performs some basic op fixups and optimisations along the
2050 execution-order op chain, and recursively calls "PL_rpeepp" for each
2051 side chain of ops (resulting from conditionals). Extensions may
2052 provide additional optimisations or fixups, hooking into either the
2053 per-subroutine or recursive stage, like this:
2054
2055 static peep_t prev_peepp;
2056 static void my_peep(pTHX_ OP *o)
2057 {
2058 /* custom per-subroutine optimisation goes here */
2059 prev_peepp(aTHX_ o);
2060 /* custom per-subroutine optimisation may also go here */
2061 }
2062 BOOT:
2063 prev_peepp = PL_peepp;
2064 PL_peepp = my_peep;
2065
2066 static peep_t prev_rpeepp;
2067 static void my_rpeep(pTHX_ OP *o)
2068 {
2069 OP *orig_o = o;
2070 for(; o; o = o->op_next) {
2071 /* custom per-op optimisation goes here */
2072 }
2073 prev_rpeepp(aTHX_ orig_o);
2074 }
2075 BOOT:
2076 prev_rpeepp = PL_rpeepp;
2077 PL_rpeepp = my_rpeep;
2078
2079 Pluggable runops
2080 The compile tree is executed in a runops function. There are two
2081 runops functions, in run.c and in dump.c. "Perl_runops_debug" is used
2082 with DEBUGGING and "Perl_runops_standard" is used otherwise. For fine
2083 control over the execution of the compile tree it is possible to
2084 provide your own runops function.
2085
2086 It's probably best to copy one of the existing runops functions and
2087 change it to suit your needs. Then, in the BOOT section of your XS
2088 file, add the line:
2089
2090 PL_runops = my_runops;
2091
2092 This function should be as efficient as possible to keep your programs
2093 running as fast as possible.
2094
2095 Compile-time scope hooks
2096 As of perl 5.14 it is possible to hook into the compile-time lexical
2097 scope mechanism using "Perl_blockhook_register". This is used like
2098 this:
2099
2100 STATIC void my_start_hook(pTHX_ int full);
2101 STATIC BHK my_hooks;
2102
2103 BOOT:
2104 BhkENTRY_set(&my_hooks, bhk_start, my_start_hook);
2105 Perl_blockhook_register(aTHX_ &my_hooks);
2106
2107 This will arrange to have "my_start_hook" called at the start of
2108 compiling every lexical scope. The available hooks are:
2109
2110 "void bhk_start(pTHX_ int full)"
2111 This is called just after starting a new lexical scope. Note that
2112 Perl code like
2113
2114 if ($x) { ... }
2115
2116 creates two scopes: the first starts at the "(" and has "full ==
2117 1", the second starts at the "{" and has "full == 0". Both end at
2118 the "}", so calls to "start" and "pre"/"post_end" will match.
2119 Anything pushed onto the save stack by this hook will be popped
2120 just before the scope ends (between the "pre_" and "post_end"
2121 hooks, in fact).
2122
2123 "void bhk_pre_end(pTHX_ OP **o)"
2124 This is called at the end of a lexical scope, just before unwinding
2125 the stack. o is the root of the optree representing the scope; it
2126 is a double pointer so you can replace the OP if you need to.
2127
2128 "void bhk_post_end(pTHX_ OP **o)"
2129 This is called at the end of a lexical scope, just after unwinding
2130 the stack. o is as above. Note that it is possible for calls to
2131 "pre_" and "post_end" to nest, if there is something on the save
2132 stack that calls string eval.
2133
2134 "void bhk_eval(pTHX_ OP *const o)"
2135 This is called just before starting to compile an "eval STRING",
2136 "do FILE", "require" or "use", after the eval has been set up. o
2137 is the OP that requested the eval, and will normally be an
2138 "OP_ENTEREVAL", "OP_DOFILE" or "OP_REQUIRE".
2139
2140 Once you have your hook functions, you need a "BHK" structure to put
2141 them in. It's best to allocate it statically, since there is no way to
2142 free it once it's registered. The function pointers should be inserted
2143 into this structure using the "BhkENTRY_set" macro, which will also set
2144 flags indicating which entries are valid. If you do need to allocate
2145 your "BHK" dynamically for some reason, be sure to zero it before you
2146 start.
2147
2148 Once registered, there is no mechanism to switch these hooks off, so if
2149 that is necessary you will need to do this yourself. An entry in "%^H"
2150 is probably the best way, so the effect is lexically scoped; however it
2151 is also possible to use the "BhkDISABLE" and "BhkENABLE" macros to
2152 temporarily switch entries on and off. You should also be aware that
2153 generally speaking at least one scope will have opened before your
2154 extension is loaded, so you will see some "pre"/"post_end" pairs that
2155 didn't have a matching "start".
2156
2158 To aid debugging, the source file dump.c contains a number of functions
2159 which produce formatted output of internal data structures.
2160
2161 The most commonly used of these functions is "Perl_sv_dump"; it's used
2162 for dumping SVs, AVs, HVs, and CVs. The "Devel::Peek" module calls
2163 "sv_dump" to produce debugging output from Perl-space, so users of that
2164 module should already be familiar with its format.
2165
2166 "Perl_op_dump" can be used to dump an "OP" structure or any of its
2167 derivatives, and produces output similar to "perl -Dx"; in fact,
2168 "Perl_dump_eval" will dump the main root of the code being evaluated,
2169 exactly like "-Dx".
2170
2171 Other useful functions are "Perl_dump_sub", which turns a "GV" into an
2172 op tree, "Perl_dump_packsubs" which calls "Perl_dump_sub" on all the
2173 subroutines in a package like so: (Thankfully, these are all xsubs, so
2174 there is no op tree)
2175
2176 (gdb) print Perl_dump_packsubs(PL_defstash)
2177
2178 SUB attributes::bootstrap = (xsub 0x811fedc 0)
2179
2180 SUB UNIVERSAL::can = (xsub 0x811f50c 0)
2181
2182 SUB UNIVERSAL::isa = (xsub 0x811f304 0)
2183
2184 SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
2185
2186 SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
2187
2188 and "Perl_dump_all", which dumps all the subroutines in the stash and
2189 the op tree of the main root.
2190
2192 Background and PERL_IMPLICIT_CONTEXT
2193 The Perl interpreter can be regarded as a closed box: it has an API for
2194 feeding it code or otherwise making it do things, but it also has
2195 functions for its own use. This smells a lot like an object, and there
2196 are ways for you to build Perl so that you can have multiple
2197 interpreters, with one interpreter represented either as a C structure,
2198 or inside a thread-specific structure. These structures contain all
2199 the context, the state of that interpreter.
2200
2201 One macro controls the major Perl build flavor: MULTIPLICITY. The
2202 MULTIPLICITY build has a C structure that packages all the interpreter
2203 state. With multiplicity-enabled perls, PERL_IMPLICIT_CONTEXT is also
2204 normally defined, and enables the support for passing in a "hidden"
2205 first argument that represents all three data structures. MULTIPLICITY
2206 makes multi-threaded perls possible (with the ithreads threading model,
2207 related to the macro USE_ITHREADS.)
2208
2209 Two other "encapsulation" macros are the PERL_GLOBAL_STRUCT and
2210 PERL_GLOBAL_STRUCT_PRIVATE (the latter turns on the former, and the
2211 former turns on MULTIPLICITY.) The PERL_GLOBAL_STRUCT causes all the
2212 internal variables of Perl to be wrapped inside a single global struct,
2213 struct perl_vars, accessible as (globals) &PL_Vars or PL_VarsPtr or the
2214 function Perl_GetVars(). The PERL_GLOBAL_STRUCT_PRIVATE goes one step
2215 further, there is still a single struct (allocated in main() either
2216 from heap or from stack) but there are no global data symbols pointing
2217 to it. In either case the global struct should be initialized as the
2218 very first thing in main() using Perl_init_global_struct() and
2219 correspondingly tear it down after perl_free() using
2220 Perl_free_global_struct(), please see miniperlmain.c for usage details.
2221 You may also need to use "dVAR" in your coding to "declare the global
2222 variables" when you are using them. dTHX does this for you
2223 automatically.
2224
2225 To see whether you have non-const data you can use a BSD (or GNU)
2226 compatible "nm":
2227
2228 nm libperl.a | grep -v ' [TURtr] '
2229
2230 If this displays any "D" or "d" symbols (or possibly "C" or "c"), you
2231 have non-const data. The symbols the "grep" removed are as follows:
2232 "Tt" are text, or code, the "Rr" are read-only (const) data, and the
2233 "U" is <undefined>, external symbols referred to.
2234
2235 The test t/porting/libperl.t does this kind of symbol sanity checking
2236 on "libperl.a".
2237
2238 For backward compatibility reasons defining just PERL_GLOBAL_STRUCT
2239 doesn't actually hide all symbols inside a big global struct: some
2240 PerlIO_xxx vtables are left visible. The PERL_GLOBAL_STRUCT_PRIVATE
2241 then hides everything (see how the PERLIO_FUNCS_DECL is used).
2242
2243 All this obviously requires a way for the Perl internal functions to be
2244 either subroutines taking some kind of structure as the first argument,
2245 or subroutines taking nothing as the first argument. To enable these
2246 two very different ways of building the interpreter, the Perl source
2247 (as it does in so many other situations) makes heavy use of macros and
2248 subroutine naming conventions.
2249
2250 First problem: deciding which functions will be public API functions
2251 and which will be private. All functions whose names begin "S_" are
2252 private (think "S" for "secret" or "static"). All other functions
2253 begin with "Perl_", but just because a function begins with "Perl_"
2254 does not mean it is part of the API. (See "Internal Functions".) The
2255 easiest way to be sure a function is part of the API is to find its
2256 entry in perlapi. If it exists in perlapi, it's part of the API. If
2257 it doesn't, and you think it should be (i.e., you need it for your
2258 extension), submit an issue at <https://github.com/Perl/perl5/issues>
2259 explaining why you think it should be.
2260
2261 Second problem: there must be a syntax so that the same subroutine
2262 declarations and calls can pass a structure as their first argument, or
2263 pass nothing. To solve this, the subroutines are named and declared in
2264 a particular way. Here's a typical start of a static function used
2265 within the Perl guts:
2266
2267 STATIC void
2268 S_incline(pTHX_ char *s)
2269
2270 STATIC becomes "static" in C, and may be #define'd to nothing in some
2271 configurations in the future.
2272
2273 A public function (i.e. part of the internal API, but not necessarily
2274 sanctioned for use in extensions) begins like this:
2275
2276 void
2277 Perl_sv_setiv(pTHX_ SV* dsv, IV num)
2278
2279 "pTHX_" is one of a number of macros (in perl.h) that hide the details
2280 of the interpreter's context. THX stands for "thread", "this", or
2281 "thingy", as the case may be. (And no, George Lucas is not involved.
2282 :-) The first character could be 'p' for a prototype, 'a' for argument,
2283 or 'd' for declaration, so we have "pTHX", "aTHX" and "dTHX", and their
2284 variants.
2285
2286 When Perl is built without options that set PERL_IMPLICIT_CONTEXT,
2287 there is no first argument containing the interpreter's context. The
2288 trailing underscore in the pTHX_ macro indicates that the macro
2289 expansion needs a comma after the context argument because other
2290 arguments follow it. If PERL_IMPLICIT_CONTEXT is not defined, pTHX_
2291 will be ignored, and the subroutine is not prototyped to take the extra
2292 argument. The form of the macro without the trailing underscore is
2293 used when there are no additional explicit arguments.
2294
2295 When a core function calls another, it must pass the context. This is
2296 normally hidden via macros. Consider "sv_setiv". It expands into
2297 something like this:
2298
2299 #ifdef PERL_IMPLICIT_CONTEXT
2300 #define sv_setiv(a,b) Perl_sv_setiv(aTHX_ a, b)
2301 /* can't do this for vararg functions, see below */
2302 #else
2303 #define sv_setiv Perl_sv_setiv
2304 #endif
2305
2306 This works well, and means that XS authors can gleefully write:
2307
2308 sv_setiv(foo, bar);
2309
2310 and still have it work under all the modes Perl could have been
2311 compiled with.
2312
2313 This doesn't work so cleanly for varargs functions, though, as macros
2314 imply that the number of arguments is known in advance. Instead we
2315 either need to spell them out fully, passing "aTHX_" as the first
2316 argument (the Perl core tends to do this with functions like
2317 Perl_warner), or use a context-free version.
2318
2319 The context-free version of Perl_warner is called
2320 Perl_warner_nocontext, and does not take the extra argument. Instead
2321 it does "dTHX;" to get the context from thread-local storage. We
2322 "#define warner Perl_warner_nocontext" so that extensions get source
2323 compatibility at the expense of performance. (Passing an arg is
2324 cheaper than grabbing it from thread-local storage.)
2325
2326 You can ignore [pad]THXx when browsing the Perl headers/sources. Those
2327 are strictly for use within the core. Extensions and embedders need
2328 only be aware of [pad]THX.
2329
2330 So what happened to dTHR?
2331 "dTHR" was introduced in perl 5.005 to support the older thread model.
2332 The older thread model now uses the "THX" mechanism to pass context
2333 pointers around, so "dTHR" is not useful any more. Perl 5.6.0 and
2334 later still have it for backward source compatibility, but it is
2335 defined to be a no-op.
2336
2337 How do I use all this in extensions?
2338 When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call any
2339 functions in the Perl API will need to pass the initial context
2340 argument somehow. The kicker is that you will need to write it in such
2341 a way that the extension still compiles when Perl hasn't been built
2342 with PERL_IMPLICIT_CONTEXT enabled.
2343
2344 There are three ways to do this. First, the easy but inefficient way,
2345 which is also the default, in order to maintain source compatibility
2346 with extensions: whenever XSUB.h is #included, it redefines the aTHX
2347 and aTHX_ macros to call a function that will return the context.
2348 Thus, something like:
2349
2350 sv_setiv(sv, num);
2351
2352 in your extension will translate to this when PERL_IMPLICIT_CONTEXT is
2353 in effect:
2354
2355 Perl_sv_setiv(Perl_get_context(), sv, num);
2356
2357 or to this otherwise:
2358
2359 Perl_sv_setiv(sv, num);
2360
2361 You don't have to do anything new in your extension to get this; since
2362 the Perl library provides Perl_get_context(), it will all just work.
2363
2364 The second, more efficient way is to use the following template for
2365 your Foo.xs:
2366
2367 #define PERL_NO_GET_CONTEXT /* we want efficiency */
2368 #include "EXTERN.h"
2369 #include "perl.h"
2370 #include "XSUB.h"
2371
2372 STATIC void my_private_function(int arg1, int arg2);
2373
2374 STATIC void
2375 my_private_function(int arg1, int arg2)
2376 {
2377 dTHX; /* fetch context */
2378 ... call many Perl API functions ...
2379 }
2380
2381 [... etc ...]
2382
2383 MODULE = Foo PACKAGE = Foo
2384
2385 /* typical XSUB */
2386
2387 void
2388 my_xsub(arg)
2389 int arg
2390 CODE:
2391 my_private_function(arg, 10);
2392
2393 Note that the only two changes from the normal way of writing an
2394 extension is the addition of a "#define PERL_NO_GET_CONTEXT" before
2395 including the Perl headers, followed by a "dTHX;" declaration at the
2396 start of every function that will call the Perl API. (You'll know
2397 which functions need this, because the C compiler will complain that
2398 there's an undeclared identifier in those functions.) No changes are
2399 needed for the XSUBs themselves, because the XS() macro is correctly
2400 defined to pass in the implicit context if needed.
2401
2402 The third, even more efficient way is to ape how it is done within the
2403 Perl guts:
2404
2405 #define PERL_NO_GET_CONTEXT /* we want efficiency */
2406 #include "EXTERN.h"
2407 #include "perl.h"
2408 #include "XSUB.h"
2409
2410 /* pTHX_ only needed for functions that call Perl API */
2411 STATIC void my_private_function(pTHX_ int arg1, int arg2);
2412
2413 STATIC void
2414 my_private_function(pTHX_ int arg1, int arg2)
2415 {
2416 /* dTHX; not needed here, because THX is an argument */
2417 ... call Perl API functions ...
2418 }
2419
2420 [... etc ...]
2421
2422 MODULE = Foo PACKAGE = Foo
2423
2424 /* typical XSUB */
2425
2426 void
2427 my_xsub(arg)
2428 int arg
2429 CODE:
2430 my_private_function(aTHX_ arg, 10);
2431
2432 This implementation never has to fetch the context using a function
2433 call, since it is always passed as an extra argument. Depending on
2434 your needs for simplicity or efficiency, you may mix the previous two
2435 approaches freely.
2436
2437 Never add a comma after "pTHX" yourself--always use the form of the
2438 macro with the underscore for functions that take explicit arguments,
2439 or the form without the argument for functions with no explicit
2440 arguments.
2441
2442 If one is compiling Perl with the "-DPERL_GLOBAL_STRUCT" the "dVAR"
2443 definition is needed if the Perl global variables (see perlvars.h or
2444 globvar.sym) are accessed in the function and "dTHX" is not used (the
2445 "dTHX" includes the "dVAR" if necessary). One notices the need for
2446 "dVAR" only with the said compile-time define, because otherwise the
2447 Perl global variables are visible as-is.
2448
2449 Should I do anything special if I call perl from multiple threads?
2450 If you create interpreters in one thread and then proceed to call them
2451 in another, you need to make sure perl's own Thread Local Storage (TLS)
2452 slot is initialized correctly in each of those threads.
2453
2454 The "perl_alloc" and "perl_clone" API functions will automatically set
2455 the TLS slot to the interpreter they created, so that there is no need
2456 to do anything special if the interpreter is always accessed in the
2457 same thread that created it, and that thread did not create or call any
2458 other interpreters afterwards. If that is not the case, you have to
2459 set the TLS slot of the thread before calling any functions in the Perl
2460 API on that particular interpreter. This is done by calling the
2461 "PERL_SET_CONTEXT" macro in that thread as the first thing you do:
2462
2463 /* do this before doing anything else with some_perl */
2464 PERL_SET_CONTEXT(some_perl);
2465
2466 ... other Perl API calls on some_perl go here ...
2467
2468 Future Plans and PERL_IMPLICIT_SYS
2469 Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything
2470 that the interpreter knows about itself and pass it around, so too are
2471 there plans to allow the interpreter to bundle up everything it knows
2472 about the environment it's running on. This is enabled with the
2473 PERL_IMPLICIT_SYS macro. Currently it only works with USE_ITHREADS on
2474 Windows.
2475
2476 This allows the ability to provide an extra pointer (called the "host"
2477 environment) for all the system calls. This makes it possible for all
2478 the system stuff to maintain their own state, broken down into seven C
2479 structures. These are thin wrappers around the usual system calls (see
2480 win32/perllib.c) for the default perl executable, but for a more
2481 ambitious host (like the one that would do fork() emulation) all the
2482 extra work needed to pretend that different interpreters are actually
2483 different "processes", would be done here.
2484
2485 The Perl engine/interpreter and the host are orthogonal entities.
2486 There could be one or more interpreters in a process, and one or more
2487 "hosts", with free association between them.
2488
2490 All of Perl's internal functions which will be exposed to the outside
2491 world are prefixed by "Perl_" so that they will not conflict with XS
2492 functions or functions used in a program in which Perl is embedded.
2493 Similarly, all global variables begin with "PL_". (By convention,
2494 static functions start with "S_".)
2495
2496 Inside the Perl core ("PERL_CORE" defined), you can get at the
2497 functions either with or without the "Perl_" prefix, thanks to a bunch
2498 of defines that live in embed.h. Note that extension code should not
2499 set "PERL_CORE"; this exposes the full perl internals, and is likely to
2500 cause breakage of the XS in each new perl release.
2501
2502 The file embed.h is generated automatically from embed.pl and
2503 embed.fnc. embed.pl also creates the prototyping header files for the
2504 internal functions, generates the documentation and a lot of other bits
2505 and pieces. It's important that when you add a new function to the
2506 core or change an existing one, you change the data in the table in
2507 embed.fnc as well. Here's a sample entry from that table:
2508
2509 Apd |SV** |av_fetch |AV* ar|I32 key|I32 lval
2510
2511 The first column is a set of flags, the second column the return type,
2512 the third column the name. Columns after that are the arguments. The
2513 flags are documented at the top of embed.fnc.
2514
2515 If you edit embed.pl or embed.fnc, you will need to run "make
2516 regen_headers" to force a rebuild of embed.h and other auto-generated
2517 files.
2518
2519 Formatted Printing of IVs, UVs, and NVs
2520 If you are printing IVs, UVs, or NVS instead of the stdio(3) style
2521 formatting codes like %d, %ld, %f, you should use the following macros
2522 for portability
2523
2524 IVdf IV in decimal
2525 UVuf UV in decimal
2526 UVof UV in octal
2527 UVxf UV in hexadecimal
2528 NVef NV %e-like
2529 NVff NV %f-like
2530 NVgf NV %g-like
2531
2532 These will take care of 64-bit integers and long doubles. For example:
2533
2534 printf("IV is %" IVdf "\n", iv);
2535
2536 The "IVdf" will expand to whatever is the correct format for the IVs.
2537 Note that the spaces are required around the format in case the code is
2538 compiled with C++, to maintain compliance with its standard.
2539
2540 Note that there are different "long doubles": Perl will use whatever
2541 the compiler has.
2542
2543 If you are printing addresses of pointers, use %p or UVxf combined with
2544 PTR2UV().
2545
2546 Formatted Printing of SVs
2547 The contents of SVs may be printed using the "SVf" format, like so:
2548
2549 Perl_croak(aTHX_ "This croaked because: %" SVf "\n", SvfARG(err_msg))
2550
2551 where "err_msg" is an SV.
2552
2553 Not all scalar types are printable. Simple values certainly are: one
2554 of IV, UV, NV, or PV. Also, if the SV is a reference to some value,
2555 either it will be dereferenced and the value printed, or information
2556 about the type of that value and its address are displayed. The
2557 results of printing any other type of SV are undefined and likely to
2558 lead to an interpreter crash. NVs are printed using a %g-ish format.
2559
2560 Note that the spaces are required around the "SVf" in case the code is
2561 compiled with C++, to maintain compliance with its standard.
2562
2563 Note that any filehandle being printed to under UTF-8 must be expecting
2564 UTF-8 in order to get good results and avoid Wide-character warnings.
2565 One way to do this for typical filehandles is to invoke perl with the
2566 "-C"> parameter. (See "-C [number/list]" in perlrun.
2567
2568 You can use this to concatenate two scalars:
2569
2570 SV *var1 = get_sv("var1", GV_ADD);
2571 SV *var2 = get_sv("var2", GV_ADD);
2572 SV *var3 = newSVpvf("var1=%" SVf " and var2=%" SVf,
2573 SVfARG(var1), SVfARG(var2));
2574
2575 Formatted Printing of Strings
2576 If you just want the bytes printed in a 7bit NUL-terminated string, you
2577 can just use %s (assuming they are all really only 7bit). But if there
2578 is a possibility the value will be encoded as UTF-8 or contains bytes
2579 above 0x7F (and therefore 8bit), you should instead use the "UTF8f"
2580 format. And as its parameter, use the "UTF8fARG()" macro:
2581
2582 chr * msg;
2583
2584 /* U+2018: \xE2\x80\x98 LEFT SINGLE QUOTATION MARK
2585 U+2019: \xE2\x80\x99 RIGHT SINGLE QUOTATION MARK */
2586 if (can_utf8)
2587 msg = "\xE2\x80\x98Uses fancy quotes\xE2\x80\x99";
2588 else
2589 msg = "'Uses simple quotes'";
2590
2591 Perl_croak(aTHX_ "The message is: %" UTF8f "\n",
2592 UTF8fARG(can_utf8, strlen(msg), msg));
2593
2594 The first parameter to "UTF8fARG" is a boolean: 1 if the string is in
2595 UTF-8; 0 if string is in native byte encoding (Latin1). The second
2596 parameter is the number of bytes in the string to print. And the third
2597 and final parameter is a pointer to the first byte in the string.
2598
2599 Note that any filehandle being printed to under UTF-8 must be expecting
2600 UTF-8 in order to get good results and avoid Wide-character warnings.
2601 One way to do this for typical filehandles is to invoke perl with the
2602 "-C"> parameter. (See "-C [number/list]" in perlrun.
2603
2604 Formatted Printing of "Size_t" and "SSize_t"
2605 The most general way to do this is to cast them to a UV or IV, and
2606 print as in the previous section.
2607
2608 But if you're using "PerlIO_printf()", it's less typing and visual
2609 clutter to use the %z length modifier (for siZe):
2610
2611 PerlIO_printf("STRLEN is %zu\n", len);
2612
2613 This modifier is not portable, so its use should be restricted to
2614 "PerlIO_printf()".
2615
2616 Pointer-To-Integer and Integer-To-Pointer
2617 Because pointer size does not necessarily equal integer size, use the
2618 follow macros to do it right.
2619
2620 PTR2UV(pointer)
2621 PTR2IV(pointer)
2622 PTR2NV(pointer)
2623 INT2PTR(pointertotype, integer)
2624
2625 For example:
2626
2627 IV iv = ...;
2628 SV *sv = INT2PTR(SV*, iv);
2629
2630 and
2631
2632 AV *av = ...;
2633 UV uv = PTR2UV(av);
2634
2635 Exception Handling
2636 There are a couple of macros to do very basic exception handling in XS
2637 modules. You have to define "NO_XSLOCKS" before including XSUB.h to be
2638 able to use these macros:
2639
2640 #define NO_XSLOCKS
2641 #include "XSUB.h"
2642
2643 You can use these macros if you call code that may croak, but you need
2644 to do some cleanup before giving control back to Perl. For example:
2645
2646 dXCPT; /* set up necessary variables */
2647
2648 XCPT_TRY_START {
2649 code_that_may_croak();
2650 } XCPT_TRY_END
2651
2652 XCPT_CATCH
2653 {
2654 /* do cleanup here */
2655 XCPT_RETHROW;
2656 }
2657
2658 Note that you always have to rethrow an exception that has been caught.
2659 Using these macros, it is not possible to just catch the exception and
2660 ignore it. If you have to ignore the exception, you have to use the
2661 "call_*" function.
2662
2663 The advantage of using the above macros is that you don't have to setup
2664 an extra function for "call_*", and that using these macros is faster
2665 than using "call_*".
2666
2667 Source Documentation
2668 There's an effort going on to document the internal functions and
2669 automatically produce reference manuals from them -- perlapi is one
2670 such manual which details all the functions which are available to XS
2671 writers. perlintern is the autogenerated manual for the functions
2672 which are not part of the API and are supposedly for internal use only.
2673
2674 Source documentation is created by putting POD comments into the C
2675 source, like this:
2676
2677 /*
2678 =for apidoc sv_setiv
2679
2680 Copies an integer into the given SV. Does not handle 'set' magic. See
2681 L<perlapi/sv_setiv_mg>.
2682
2683 =cut
2684 */
2685
2686 Please try and supply some documentation if you add functions to the
2687 Perl core.
2688
2689 Backwards compatibility
2690 The Perl API changes over time. New functions are added or the
2691 interfaces of existing functions are changed. The "Devel::PPPort"
2692 module tries to provide compatibility code for some of these changes,
2693 so XS writers don't have to code it themselves when supporting multiple
2694 versions of Perl.
2695
2696 "Devel::PPPort" generates a C header file ppport.h that can also be run
2697 as a Perl script. To generate ppport.h, run:
2698
2699 perl -MDevel::PPPort -eDevel::PPPort::WriteFile
2700
2701 Besides checking existing XS code, the script can also be used to
2702 retrieve compatibility information for various API calls using the
2703 "--api-info" command line switch. For example:
2704
2705 % perl ppport.h --api-info=sv_magicext
2706
2707 For details, see "perldoc ppport.h".
2708
2710 Perl 5.6.0 introduced Unicode support. It's important for porters and
2711 XS writers to understand this support and make sure that the code they
2712 write does not corrupt Unicode data.
2713
2714 What is Unicode, anyway?
2715 In the olden, less enlightened times, we all used to use ASCII. Most
2716 of us did, anyway. The big problem with ASCII is that it's American.
2717 Well, no, that's not actually the problem; the problem is that it's not
2718 particularly useful for people who don't use the Roman alphabet. What
2719 used to happen was that particular languages would stick their own
2720 alphabet in the upper range of the sequence, between 128 and 255. Of
2721 course, we then ended up with plenty of variants that weren't quite
2722 ASCII, and the whole point of it being a standard was lost.
2723
2724 Worse still, if you've got a language like Chinese or Japanese that has
2725 hundreds or thousands of characters, then you really can't fit them
2726 into a mere 256, so they had to forget about ASCII altogether, and
2727 build their own systems using pairs of numbers to refer to one
2728 character.
2729
2730 To fix this, some people formed Unicode, Inc. and produced a new
2731 character set containing all the characters you can possibly think of
2732 and more. There are several ways of representing these characters, and
2733 the one Perl uses is called UTF-8. UTF-8 uses a variable number of
2734 bytes to represent a character. You can learn more about Unicode and
2735 Perl's Unicode model in perlunicode.
2736
2737 (On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of
2738 UTF-8 adapted for EBCDIC platforms. Below, we just talk about UTF-8.
2739 UTF-EBCDIC is like UTF-8, but the details are different. The macros
2740 hide the differences from you, just remember that the particular
2741 numbers and bit patterns presented below will differ in UTF-EBCDIC.)
2742
2743 How can I recognise a UTF-8 string?
2744 You can't. This is because UTF-8 data is stored in bytes just like
2745 non-UTF-8 data. The Unicode character 200, (0xC8 for you hex types)
2746 capital E with a grave accent, is represented by the two bytes
2747 "v196.172". Unfortunately, the non-Unicode string "chr(196).chr(172)"
2748 has that byte sequence as well. So you can't tell just by looking --
2749 this is what makes Unicode input an interesting problem.
2750
2751 In general, you either have to know what you're dealing with, or you
2752 have to guess. The API function "is_utf8_string" can help; it'll tell
2753 you if a string contains only valid UTF-8 characters, and the chances
2754 of a non-UTF-8 string looking like valid UTF-8 become very small very
2755 quickly with increasing string length. On a character-by-character
2756 basis, "isUTF8_CHAR" will tell you whether the current character in a
2757 string is valid UTF-8.
2758
2759 How does UTF-8 represent Unicode characters?
2760 As mentioned above, UTF-8 uses a variable number of bytes to store a
2761 character. Characters with values 0...127 are stored in one byte, just
2762 like good ol' ASCII. Character 128 is stored as "v194.128"; this
2763 continues up to character 191, which is "v194.191". Now we've run out
2764 of bits (191 is binary 10111111) so we move on; character 192 is
2765 "v195.128". And so it goes on, moving to three bytes at character
2766 2048. "Unicode Encodings" in perlunicode has pictures of how this
2767 works.
2768
2769 Assuming you know you're dealing with a UTF-8 string, you can find out
2770 how long the first character in it is with the "UTF8SKIP" macro:
2771
2772 char *utf = "\305\233\340\240\201";
2773 I32 len;
2774
2775 len = UTF8SKIP(utf); /* len is 2 here */
2776 utf += len;
2777 len = UTF8SKIP(utf); /* len is 3 here */
2778
2779 Another way to skip over characters in a UTF-8 string is to use
2780 "utf8_hop", which takes a string and a number of characters to skip
2781 over. You're on your own about bounds checking, though, so don't use
2782 it lightly.
2783
2784 All bytes in a multi-byte UTF-8 character will have the high bit set,
2785 so you can test if you need to do something special with this character
2786 like this (the "UTF8_IS_INVARIANT()" is a macro that tests whether the
2787 byte is encoded as a single byte even in UTF-8):
2788
2789 U8 *utf; /* Initialize this to point to the beginning of the
2790 sequence to convert */
2791 U8 *utf_end; /* Initialize this to 1 beyond the end of the sequence
2792 pointed to by 'utf' */
2793 UV uv; /* Returned code point; note: a UV, not a U8, not a
2794 char */
2795 STRLEN len; /* Returned length of character in bytes */
2796
2797 if (!UTF8_IS_INVARIANT(*utf))
2798 /* Must treat this as UTF-8 */
2799 uv = utf8_to_uvchr_buf(utf, utf_end, &len);
2800 else
2801 /* OK to treat this character as a byte */
2802 uv = *utf;
2803
2804 You can also see in that example that we use "utf8_to_uvchr_buf" to get
2805 the value of the character; the inverse function "uvchr_to_utf8" is
2806 available for putting a UV into UTF-8:
2807
2808 if (!UVCHR_IS_INVARIANT(uv))
2809 /* Must treat this as UTF8 */
2810 utf8 = uvchr_to_utf8(utf8, uv);
2811 else
2812 /* OK to treat this character as a byte */
2813 *utf8++ = uv;
2814
2815 You must convert characters to UVs using the above functions if you're
2816 ever in a situation where you have to match UTF-8 and non-UTF-8
2817 characters. You may not skip over UTF-8 characters in this case. If
2818 you do this, you'll lose the ability to match hi-bit non-UTF-8
2819 characters; for instance, if your UTF-8 string contains "v196.172", and
2820 you skip that character, you can never match a "chr(200)" in a
2821 non-UTF-8 string. So don't do that!
2822
2823 (Note that we don't have to test for invariant characters in the
2824 examples above. The functions work on any well-formed UTF-8 input.
2825 It's just that its faster to avoid the function overhead when it's not
2826 needed.)
2827
2828 How does Perl store UTF-8 strings?
2829 Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly
2830 differently. A flag in the SV, "SVf_UTF8", indicates that the string
2831 is internally encoded as UTF-8. Without it, the byte value is the
2832 codepoint number and vice versa. This flag is only meaningful if the
2833 SV is "SvPOK" or immediately after stringification via "SvPV" or a
2834 similar macro. You can check and manipulate this flag with the
2835 following macros:
2836
2837 SvUTF8(sv)
2838 SvUTF8_on(sv)
2839 SvUTF8_off(sv)
2840
2841 This flag has an important effect on Perl's treatment of the string: if
2842 UTF-8 data is not properly distinguished, regular expressions,
2843 "length", "substr" and other string handling operations will have
2844 undesirable (wrong) results.
2845
2846 The problem comes when you have, for instance, a string that isn't
2847 flagged as UTF-8, and contains a byte sequence that could be UTF-8 --
2848 especially when combining non-UTF-8 and UTF-8 strings.
2849
2850 Never forget that the "SVf_UTF8" flag is separate from the PV value;
2851 you need to be sure you don't accidentally knock it off while you're
2852 manipulating SVs. More specifically, you cannot expect to do this:
2853
2854 SV *sv;
2855 SV *nsv;
2856 STRLEN len;
2857 char *p;
2858
2859 p = SvPV(sv, len);
2860 frobnicate(p);
2861 nsv = newSVpvn(p, len);
2862
2863 The "char*" string does not tell you the whole story, and you can't
2864 copy or reconstruct an SV just by copying the string value. Check if
2865 the old SV has the UTF8 flag set (after the "SvPV" call), and act
2866 accordingly:
2867
2868 p = SvPV(sv, len);
2869 is_utf8 = SvUTF8(sv);
2870 frobnicate(p, is_utf8);
2871 nsv = newSVpvn(p, len);
2872 if (is_utf8)
2873 SvUTF8_on(nsv);
2874
2875 In the above, your "frobnicate" function has been changed to be made
2876 aware of whether or not it's dealing with UTF-8 data, so that it can
2877 handle the string appropriately.
2878
2879 Since just passing an SV to an XS function and copying the data of the
2880 SV is not enough to copy the UTF8 flags, even less right is just
2881 passing a "char *" to an XS function.
2882
2883 For full generality, use the "DO_UTF8" macro to see if the string in an
2884 SV is to be treated as UTF-8. This takes into account if the call to
2885 the XS function is being made from within the scope of "use bytes". If
2886 so, the underlying bytes that comprise the UTF-8 string are to be
2887 exposed, rather than the character they represent. But this pragma
2888 should only really be used for debugging and perhaps low-level testing
2889 at the byte level. Hence most XS code need not concern itself with
2890 this, but various areas of the perl core do need to support it.
2891
2892 And this isn't the whole story. Starting in Perl v5.12, strings that
2893 aren't encoded in UTF-8 may also be treated as Unicode under various
2894 conditions (see "ASCII Rules versus Unicode Rules" in perlunicode).
2895 This is only really a problem for characters whose ordinals are between
2896 128 and 255, and their behavior varies under ASCII versus Unicode rules
2897 in ways that your code cares about (see "The "Unicode Bug"" in
2898 perlunicode). There is no published API for dealing with this, as it
2899 is subject to change, but you can look at the code for "pp_lc" in pp.c
2900 for an example as to how it's currently done.
2901
2902 How do I convert a string to UTF-8?
2903 If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to
2904 upgrade the non-UTF-8 strings to UTF-8. If you've got an SV, the
2905 easiest way to do this is:
2906
2907 sv_utf8_upgrade(sv);
2908
2909 However, you must not do this, for example:
2910
2911 if (!SvUTF8(left))
2912 sv_utf8_upgrade(left);
2913
2914 If you do this in a binary operator, you will actually change one of
2915 the strings that came into the operator, and, while it shouldn't be
2916 noticeable by the end user, it can cause problems in deficient code.
2917
2918 Instead, "bytes_to_utf8" will give you a UTF-8-encoded copy of its
2919 string argument. This is useful for having the data available for
2920 comparisons and so on, without harming the original SV. There's also
2921 "utf8_to_bytes" to go the other way, but naturally, this will fail if
2922 the string contains any characters above 255 that can't be represented
2923 in a single byte.
2924
2925 How do I compare strings?
2926 "sv_cmp" in perlapi and "sv_cmp_flags" in perlapi do a lexigraphic
2927 comparison of two SV's, and handle UTF-8ness properly. Note, however,
2928 that Unicode specifies a much fancier mechanism for collation,
2929 available via the Unicode::Collate module.
2930
2931 To just compare two strings for equality/non-equality, you can just use
2932 "memEQ()" and "memNE()" as usual, except the strings must be both UTF-8
2933 or not UTF-8 encoded.
2934
2935 To compare two strings case-insensitively, use "foldEQ_utf8()" (the
2936 strings don't have to have the same UTF-8ness).
2937
2938 Is there anything else I need to know?
2939 Not really. Just remember these things:
2940
2941 • There's no way to tell if a "char *" or "U8 *" string is UTF-8 or
2942 not. But you can tell if an SV is to be treated as UTF-8 by calling
2943 "DO_UTF8" on it, after stringifying it with "SvPV" or a similar
2944 macro. And, you can tell if SV is actually UTF-8 (even if it is not
2945 to be treated as such) by looking at its "SvUTF8" flag (again after
2946 stringifying it). Don't forget to set the flag if something should
2947 be UTF-8. Treat the flag as part of the PV, even though it's not --
2948 if you pass on the PV to somewhere, pass on the flag too.
2949
2950 • If a string is UTF-8, always use "utf8_to_uvchr_buf" to get at the
2951 value, unless "UTF8_IS_INVARIANT(*s)" in which case you can use *s.
2952
2953 • When writing a character UV to a UTF-8 string, always use
2954 "uvchr_to_utf8", unless "UVCHR_IS_INVARIANT(uv))" in which case you
2955 can use "*s = uv".
2956
2957 • Mixing UTF-8 and non-UTF-8 strings is tricky. Use "bytes_to_utf8"
2958 to get a new string which is UTF-8 encoded, and then combine them.
2959
2961 Custom operator support is an experimental feature that allows you to
2962 define your own ops. This is primarily to allow the building of
2963 interpreters for other languages in the Perl core, but it also allows
2964 optimizations through the creation of "macro-ops" (ops which perform
2965 the functions of multiple ops which are usually executed together, such
2966 as "gvsv, gvsv, add".)
2967
2968 This feature is implemented as a new op type, "OP_CUSTOM". The Perl
2969 core does not "know" anything special about this op type, and so it
2970 will not be involved in any optimizations. This also means that you
2971 can define your custom ops to be any op structure -- unary, binary,
2972 list and so on -- you like.
2973
2974 It's important to know what custom operators won't do for you. They
2975 won't let you add new syntax to Perl, directly. They won't even let
2976 you add new keywords, directly. In fact, they won't change the way
2977 Perl compiles a program at all. You have to do those changes yourself,
2978 after Perl has compiled the program. You do this either by
2979 manipulating the op tree using a "CHECK" block and the "B::Generate"
2980 module, or by adding a custom peephole optimizer with the "optimize"
2981 module.
2982
2983 When you do this, you replace ordinary Perl ops with custom ops by
2984 creating ops with the type "OP_CUSTOM" and the "op_ppaddr" of your own
2985 PP function. This should be defined in XS code, and should look like
2986 the PP ops in "pp_*.c". You are responsible for ensuring that your op
2987 takes the appropriate number of values from the stack, and you are
2988 responsible for adding stack marks if necessary.
2989
2990 You should also "register" your op with the Perl interpreter so that it
2991 can produce sensible error and warning messages. Since it is possible
2992 to have multiple custom ops within the one "logical" op type
2993 "OP_CUSTOM", Perl uses the value of "o->op_ppaddr" to determine which
2994 custom op it is dealing with. You should create an "XOP" structure for
2995 each ppaddr you use, set the properties of the custom op with
2996 "XopENTRY_set", and register the structure against the ppaddr using
2997 "Perl_custom_op_register". A trivial example might look like:
2998
2999 static XOP my_xop;
3000 static OP *my_pp(pTHX);
3001
3002 BOOT:
3003 XopENTRY_set(&my_xop, xop_name, "myxop");
3004 XopENTRY_set(&my_xop, xop_desc, "Useless custom op");
3005 Perl_custom_op_register(aTHX_ my_pp, &my_xop);
3006
3007 The available fields in the structure are:
3008
3009 xop_name
3010 A short name for your op. This will be included in some error
3011 messages, and will also be returned as "$op->name" by the B module,
3012 so it will appear in the output of module like B::Concise.
3013
3014 xop_desc
3015 A short description of the function of the op.
3016
3017 xop_class
3018 Which of the various *OP structures this op uses. This should be
3019 one of the "OA_*" constants from op.h, namely
3020
3021 OA_BASEOP
3022 OA_UNOP
3023 OA_BINOP
3024 OA_LOGOP
3025 OA_LISTOP
3026 OA_PMOP
3027 OA_SVOP
3028 OA_PADOP
3029 OA_PVOP_OR_SVOP
3030 This should be interpreted as '"PVOP"' only. The "_OR_SVOP" is
3031 because the only core "PVOP", "OP_TRANS", can sometimes be a
3032 "SVOP" instead.
3033
3034 OA_LOOP
3035 OA_COP
3036
3037 The other "OA_*" constants should not be used.
3038
3039 xop_peep
3040 This member is of type "Perl_cpeep_t", which expands to "void
3041 (*Perl_cpeep_t)(aTHX_ OP *o, OP *oldop)". If it is set, this
3042 function will be called from "Perl_rpeep" when ops of this type are
3043 encountered by the peephole optimizer. o is the OP that needs
3044 optimizing; oldop is the previous OP optimized, whose "op_next"
3045 points to o.
3046
3047 "B::Generate" directly supports the creation of custom ops by name.
3048
3050 Descriptions above occasionally refer to "the stack", but there are in
3051 fact many stack-like data structures within the perl interpreter. When
3052 otherwise unqualified, "the stack" usually refers to the value stack.
3053
3054 The various stacks have different purposes, and operate in slightly
3055 different ways. Their differences are noted below.
3056
3057 Value Stack
3058 This stack stores the values that regular perl code is operating on,
3059 usually intermediate values of expressions within a statement. The
3060 stack itself is formed of an array of SV pointers.
3061
3062 The base of this stack is pointed to by the interpreter variable
3063 "PL_stack_base", of type "SV **".
3064
3065 The head of the stack is "PL_stack_sp", and points to the most
3066 recently-pushed item.
3067
3068 Items are pushed to the stack by using the "PUSHs()" macro or its
3069 variants described above; "XPUSHs()", "mPUSHs()", "mXPUSHs()" and the
3070 typed versions. Note carefully that the non-"X" versions of these
3071 macros do not check the size of the stack and assume it to be big
3072 enough. These must be paired with a suitable check of the stack's size,
3073 such as the "EXTEND" macro to ensure it is large enough. For example
3074
3075 EXTEND(SP, 4);
3076 mPUSHi(10);
3077 mPUSHi(20);
3078 mPUSHi(30);
3079 mPUSHi(40);
3080
3081 This is slightly more performant than making four separate checks in
3082 four separate "mXPUSHi()" calls.
3083
3084 As a further performance optimisation, the various "PUSH" macros all
3085 operate using a local variable "SP", rather than the interpreter-global
3086 variable "PL_stack_sp". This variable is declared by the "dSP" macro -
3087 though it is normally implied by XSUBs and similar so it is rare you
3088 have to consider it directly. Once declared, the "PUSH" macros will
3089 operate only on this local variable, so before invoking any other perl
3090 core functions you must use the "PUTBACK" macro to return the value
3091 from the local "SP" variable back to the interpreter variable.
3092 Similarly, after calling a perl core function which may have had reason
3093 to move the stack or push/pop values to it, you must use the "SPAGAIN"
3094 macro which refreshes the local "SP" value back from the interpreter
3095 one.
3096
3097 Items are popped from the stack by using the "POPs" macro or its typed
3098 versions, There is also a macro "TOPs" that inspects the topmost item
3099 without removing it.
3100
3101 Note specifically that SV pointers on the value stack do not contribute
3102 to the overall reference count of the xVs being referred to. If newly-
3103 created xVs are being pushed to the stack you must arrange for them to
3104 be destroyed at a suitable time; usually by using one of the "mPUSH*"
3105 macros or "sv_2mortal()" to mortalise the xV.
3106
3107 Mark Stack
3108 The value stack stores individual perl scalar values as temporaries
3109 between expressions. Some perl expressions operate on entire lists; for
3110 that purpose we need to know where on the stack each list begins. This
3111 is the purpose of the mark stack.
3112
3113 The mark stack stores integers as I32 values, which are the height of
3114 the value stack at the time before the list began; thus the mark itself
3115 actually points to the value stack entry one before the list. The list
3116 itself starts at "mark + 1".
3117
3118 The base of this stack is pointed to by the interpreter variable
3119 "PL_markstack", of type "I32 *".
3120
3121 The head of the stack is "PL_markstack_ptr", and points to the most
3122 recently-pushed item.
3123
3124 Items are pushed to the stack by using the "PUSHMARK()" macro. Even
3125 though the stack itself stores (value) stack indices as integers, the
3126 "PUSHMARK" macro should be given a stack pointer directly; it will
3127 calculate the index offset by comparing to the "PL_stack_sp" variable.
3128 Thus almost always the code to perform this is
3129
3130 PUSHMARK(SP);
3131
3132 Items are popped from the stack by the "POPMARK" macro. There is also a
3133 macro "TOPMARK" that inspects the topmost item without removing it.
3134 These macros return I32 index values directly. There is also the
3135 "dMARK" macro which declares a new SV double-pointer variable, called
3136 "mark", which points at the marked stack slot; this is the usual macro
3137 that C code will use when operating on lists given on the stack.
3138
3139 As noted above, the "mark" variable itself will point at the most
3140 recently pushed value on the value stack before the list begins, and so
3141 the list itself starts at "mark + 1". The values of the list may be
3142 iterated by code such as
3143
3144 for(SV **svp = mark + 1; svp <= PL_stack_sp; svp++) {
3145 SV *item = *svp;
3146 ...
3147 }
3148
3149 Note specifically in the case that the list is already empty, "mark"
3150 will equal "PL_stack_sp".
3151
3152 Because the "mark" variable is converted to a pointer on the value
3153 stack, extra care must be taken if "EXTEND" or any of the "XPUSH"
3154 macros are invoked within the function, because the stack may need to
3155 be moved to extend it and so the existing pointer will now be invalid.
3156 If this may be a problem, a possible solution is to track the mark
3157 offset as an integer and track the mark itself later on after the stack
3158 had been moved.
3159
3160 I32 markoff = POPMARK;
3161
3162 ...
3163
3164 SP **mark = PL_stack_base + markoff;
3165
3166 Temporaries Stack
3167 As noted above, xV references on the main value stack do not contribute
3168 to the reference count of an xV, and so another mechanism is used to
3169 track when temporary values which live on the stack must be released.
3170 This is the job of the temporaries stack.
3171
3172 The temporaries stack stores pointers to xVs whose reference counts
3173 will be decremented soon.
3174
3175 The base of this stack is pointed to by the interpreter variable
3176 "PL_tmps_stack", of type "SV **".
3177
3178 The head of the stack is indexed by "PL_tmps_ix", an integer which
3179 stores the index in the array of the most recently-pushed item.
3180
3181 There is no public API to directly push items to the temporaries stack.
3182 Instead, the API function "sv_2mortal()" is used to mortalize an xV,
3183 adding its address to the temporaries stack.
3184
3185 Likewise, there is no public API to read values from the temporaries
3186 stack. Instead. the macros "SAVETMPS" and "FREETPMS" are used. The
3187 "SAVETMPS" macro establishes the base levels of the temporaries stack,
3188 by capturing the current value of "PL_tmps_ix" into "PL_tmps_floor" and
3189 saving the previous value to the save stack. Thereafter, whenever
3190 "FREETMPS" is invoked all of the temporaries that have been pushed
3191 since that level are reclaimed.
3192
3193 While it is common to see these two macros in pairs within an "ENTER"/
3194 "LEAVE" pair, it is not necessary to match them. It is permitted to
3195 invoke "FREETMPS" multiple times since the most recent "SAVETMPS"; for
3196 example in a loop iterating over elements of a list. While you can
3197 invoke "SAVETMPS" multiple times within a scope pair, it is unlikely to
3198 be useful. Subsequent invocations will move the temporaries floor
3199 further up, thus effectively trapping the existing temporaries to only
3200 be released at the end of the scope.
3201
3202 Save Stack
3203 The save stack is used by perl to implement the "local" keyword and
3204 other similar behaviours; any cleanup operations that need to be
3205 performed when leaving the current scope. Items pushed to this stack
3206 generally capture the current value of some internal variable or state,
3207 which will be restored when the scope is unwound due to leaving,
3208 "return", "die", "goto" or other reasons.
3209
3210 Whereas other perl internal stacks store individual items all of the
3211 same type (usually SV pointers or integers), the items pushed to the
3212 save stack are formed of many different types, having multiple fields
3213 to them. For example, the "SAVEt_INT" type needs to store both the
3214 address of the "int" variable to restore, and the value to restore it
3215 to. This information could have been stored using fields of a "struct",
3216 but would have to be large enough to store three pointers in the
3217 largest case, which would waste a lot of space in most of the smaller
3218 cases.
3219
3220 Instead, the stack stores information in a variable-length encoding of
3221 "ANY" structures. The final value pushed is stored in the "UV" field
3222 which encodes the kind of item held by the preceeding items; the count
3223 and types of which will depend on what kind of item is being stored.
3224 The kind field is pushed last because that will be the first field to
3225 be popped when unwinding items from the stack.
3226
3227 The base of this stack is pointed to by the interpreter variable
3228 "PL_savestack", of type "ANY *".
3229
3230 The head of the stack is indexed by "PL_savestack_ix", an integer which
3231 stores the index in the array at which the next item should be pushed.
3232 (Note that this is different to most other stacks, which reference the
3233 most recently-pushed item).
3234
3235 Items are pushed to the save stack by using the various "SAVE...()"
3236 macros. Many of these macros take a variable and store both its
3237 address and current value on the save stack, ensuring that value gets
3238 restored on scope exit.
3239
3240 SAVEI8(i8)
3241 SAVEI16(i16)
3242 SAVEI32(i32)
3243 SAVEINT(i)
3244 ...
3245
3246 There are also a variety of other special-purpose macros which save
3247 particular types or values of interest. "SAVETMPS" has already been
3248 mentioned above. Others include "SAVEFREEPV" which arranges for a PV
3249 (i.e. a string buffer) to be freed, or "SAVEDESTRUCTOR" which arranges
3250 for a given function pointer to be invoked on scope exit. A full list
3251 of such macros can be found in scope.h.
3252
3253 There is no public API for popping individual values or items from the
3254 save stack. Instead, via the scope stack, the "ENTER" and "LEAVE" pair
3255 form a way to start and stop nested scopes. Leaving a nested scope via
3256 "LEAVE" will restore all of the saved values that had been pushed since
3257 the most recent "ENTER".
3258
3259 Scope Stack
3260 As with the mark stack to the value stack, the scope stack forms a pair
3261 with the save stack. The scope stack stores the height of the save
3262 stack at which nested scopes begin, and allows the save stack to be
3263 unwound back to that point when the scope is left.
3264
3265 When perl is built with debugging enabled, there is a second part to
3266 this stack storing human-readable string names describing the type of
3267 stack context. Each push operation saves the name as well as the height
3268 of the save stack, and each pop operation checks the topmost name with
3269 what is expected, causing an assertion failure if the name does not
3270 match.
3271
3272 The base of this stack is pointed to by the interpreter variable
3273 "PL_scopestack", of type "I32 *". If enabled, the scope stack names are
3274 stored in a separate array pointed to by "PL_scopestack_name", of type
3275 "const char **".
3276
3277 The head of the stack is indexed by "PL_scopestack_ix", an integer
3278 which stores the index of the array or arrays at which the next item
3279 should be pushed. (Note that this is different to most other stacks,
3280 which reference the most recently-pushed item).
3281
3282 Values are pushed to the scope stack using the "ENTER" macro, which
3283 begins a new nested scope. Any items pushed to the save stack are then
3284 restored at the next nested invocation of the "LEAVE" macro.
3285
3287 Note: this section describes a non-public internal API that is subject
3288 to change without notice.
3289
3290 Introduction to the context stack
3291 In Perl, dynamic scoping refers to the runtime nesting of things like
3292 subroutine calls, evals etc, as well as the entering and exiting of
3293 block scopes. For example, the restoring of a "local"ised variable is
3294 determined by the dynamic scope.
3295
3296 Perl tracks the dynamic scope by a data structure called the context
3297 stack, which is an array of "PERL_CONTEXT" structures, and which is
3298 itself a big union for all the types of context. Whenever a new scope
3299 is entered (such as a block, a "for" loop, or a subroutine call), a new
3300 context entry is pushed onto the stack. Similarly when leaving a block
3301 or returning from a subroutine call etc. a context is popped. Since the
3302 context stack represents the current dynamic scope, it can be searched.
3303 For example, "next LABEL" searches back through the stack looking for a
3304 loop context that matches the label; "return" pops contexts until it
3305 finds a sub or eval context or similar; "caller" examines sub contexts
3306 on the stack.
3307
3308 Each context entry is labelled with a context type, "cx_type". Typical
3309 context types are "CXt_SUB", "CXt_EVAL" etc., as well as "CXt_BLOCK"
3310 and "CXt_NULL" which represent a basic scope (as pushed by "pp_enter")
3311 and a sort block. The type determines which part of the context union
3312 are valid.
3313
3314 The main division in the context struct is between a substitution scope
3315 ("CXt_SUBST") and block scopes, which are everything else. The former
3316 is just used while executing "s///e", and won't be discussed further
3317 here.
3318
3319 All the block scope types share a common base, which corresponds to
3320 "CXt_BLOCK". This stores the old values of various scope-related
3321 variables like "PL_curpm", as well as information about the current
3322 scope, such as "gimme". On scope exit, the old variables are restored.
3323
3324 Particular block scope types store extra per-type information. For
3325 example, "CXt_SUB" stores the currently executing CV, while the various
3326 for loop types might hold the original loop variable SV. On scope exit,
3327 the per-type data is processed; for example the CV has its reference
3328 count decremented, and the original loop variable is restored.
3329
3330 The macro "cxstack" returns the base of the current context stack,
3331 while "cxstack_ix" is the index of the current frame within that stack.
3332
3333 In fact, the context stack is actually part of a stack-of-stacks
3334 system; whenever something unusual is done such as calling a "DESTROY"
3335 or tie handler, a new stack is pushed, then popped at the end.
3336
3337 Note that the API described here changed considerably in perl 5.24;
3338 prior to that, big macros like "PUSHBLOCK" and "POPSUB" were used; in
3339 5.24 they were replaced by the inline static functions described below.
3340 In addition, the ordering and detail of how these macros/function work
3341 changed in many ways, often subtly. In particular they didn't handle
3342 saving the savestack and temps stack positions, and required additional
3343 "ENTER", "SAVETMPS" and "LEAVE" compared to the new functions. The old-
3344 style macros will not be described further.
3345
3346 Pushing contexts
3347 For pushing a new context, the two basic functions are "cx =
3348 cx_pushblock()", which pushes a new basic context block and returns its
3349 address, and a family of similar functions with names like
3350 "cx_pushsub(cx)" which populate the additional type-dependent fields in
3351 the "cx" struct. Note that "CXt_NULL" and "CXt_BLOCK" don't have their
3352 own push functions, as they don't store any data beyond that pushed by
3353 "cx_pushblock".
3354
3355 The fields of the context struct and the arguments to the "cx_*"
3356 functions are subject to change between perl releases, representing
3357 whatever is convenient or efficient for that release.
3358
3359 A typical context stack pushing can be found in "pp_entersub"; the
3360 following shows a simplified and stripped-down example of a non-XS
3361 call, along with comments showing roughly what each function does.
3362
3363 dMARK;
3364 U8 gimme = GIMME_V;
3365 bool hasargs = cBOOL(PL_op->op_flags & OPf_STACKED);
3366 OP *retop = PL_op->op_next;
3367 I32 old_ss_ix = PL_savestack_ix;
3368 CV *cv = ....;
3369
3370 /* ... make mortal copies of stack args which are PADTMPs here ... */
3371
3372 /* ... do any additional savestack pushes here ... */
3373
3374 /* Now push a new context entry of type 'CXt_SUB'; initially just
3375 * doing the actions common to all block types: */
3376
3377 cx = cx_pushblock(CXt_SUB, gimme, MARK, old_ss_ix);
3378
3379 /* this does (approximately):
3380 CXINC; /* cxstack_ix++ (grow if necessary) */
3381 cx = CX_CUR(); /* and get the address of new frame */
3382 cx->cx_type = CXt_SUB;
3383 cx->blk_gimme = gimme;
3384 cx->blk_oldsp = MARK - PL_stack_base;
3385 cx->blk_oldsaveix = old_ss_ix;
3386 cx->blk_oldcop = PL_curcop;
3387 cx->blk_oldmarksp = PL_markstack_ptr - PL_markstack;
3388 cx->blk_oldscopesp = PL_scopestack_ix;
3389 cx->blk_oldpm = PL_curpm;
3390 cx->blk_old_tmpsfloor = PL_tmps_floor;
3391
3392 PL_tmps_floor = PL_tmps_ix;
3393 */
3394
3395
3396 /* then update the new context frame with subroutine-specific info,
3397 * such as the CV about to be executed: */
3398
3399 cx_pushsub(cx, cv, retop, hasargs);
3400
3401 /* this does (approximately):
3402 cx->blk_sub.cv = cv;
3403 cx->blk_sub.olddepth = CvDEPTH(cv);
3404 cx->blk_sub.prevcomppad = PL_comppad;
3405 cx->cx_type |= (hasargs) ? CXp_HASARGS : 0;
3406 cx->blk_sub.retop = retop;
3407 SvREFCNT_inc_simple_void_NN(cv);
3408 */
3409
3410 Note that "cx_pushblock()" sets two new floors: for the args stack (to
3411 "MARK") and the temps stack (to "PL_tmps_ix"). While executing at this
3412 scope level, every "nextstate" (amongst others) will reset the args and
3413 tmps stack levels to these floors. Note that since "cx_pushblock" uses
3414 the current value of "PL_tmps_ix" rather than it being passed as an
3415 arg, this dictates at what point "cx_pushblock" should be called. In
3416 particular, any new mortals which should be freed only on scope exit
3417 (rather than at the next "nextstate") should be created first.
3418
3419 Most callers of "cx_pushblock" simply set the new args stack floor to
3420 the top of the previous stack frame, but for "CXt_LOOP_LIST" it stores
3421 the items being iterated over on the stack, and so sets "blk_oldsp" to
3422 the top of these items instead. Note that, contrary to its name,
3423 "blk_oldsp" doesn't always represent the value to restore "PL_stack_sp"
3424 to on scope exit.
3425
3426 Note the early capture of "PL_savestack_ix" to "old_ss_ix", which is
3427 later passed as an arg to "cx_pushblock". In the case of "pp_entersub",
3428 this is because, although most values needing saving are stored in
3429 fields of the context struct, an extra value needs saving only when the
3430 debugger is running, and it doesn't make sense to bloat the struct for
3431 this rare case. So instead it is saved on the savestack. Since this
3432 value gets calculated and saved before the context is pushed, it is
3433 necessary to pass the old value of "PL_savestack_ix" to "cx_pushblock",
3434 to ensure that the saved value gets freed during scope exit. For most
3435 users of "cx_pushblock", where nothing needs pushing on the save stack,
3436 "PL_savestack_ix" is just passed directly as an arg to "cx_pushblock".
3437
3438 Note that where possible, values should be saved in the context struct
3439 rather than on the save stack; it's much faster that way.
3440
3441 Normally "cx_pushblock" should be immediately followed by the
3442 appropriate "cx_pushfoo", with nothing between them; this is because if
3443 code in-between could die (e.g. a warning upgraded to fatal), then the
3444 context stack unwinding code in "dounwind" would see (in the example
3445 above) a "CXt_SUB" context frame, but without all the subroutine-
3446 specific fields set, and crashes would soon ensue.
3447
3448 Where the two must be separate, initially set the type to "CXt_NULL" or
3449 "CXt_BLOCK", and later change it to "CXt_foo" when doing the
3450 "cx_pushfoo". This is exactly what "pp_enteriter" does, once it's
3451 determined which type of loop it's pushing.
3452
3453 Popping contexts
3454 Contexts are popped using "cx_popsub()" etc. and "cx_popblock()". Note
3455 however, that unlike "cx_pushblock", neither of these functions
3456 actually decrement the current context stack index; this is done
3457 separately using "CX_POP()".
3458
3459 There are two main ways that contexts are popped. During normal
3460 execution as scopes are exited, functions like "pp_leave",
3461 "pp_leaveloop" and "pp_leavesub" process and pop just one context using
3462 "cx_popfoo" and "cx_popblock". On the other hand, things like
3463 "pp_return" and "next" may have to pop back several scopes until a sub
3464 or loop context is found, and exceptions (such as "die") need to pop
3465 back contexts until an eval context is found. Both of these are
3466 accomplished by "dounwind()", which is capable of processing and
3467 popping all contexts above the target one.
3468
3469 Here is a typical example of context popping, as found in "pp_leavesub"
3470 (simplified slightly):
3471
3472 U8 gimme;
3473 PERL_CONTEXT *cx;
3474 SV **oldsp;
3475 OP *retop;
3476
3477 cx = CX_CUR();
3478
3479 gimme = cx->blk_gimme;
3480 oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
3481
3482 if (gimme == G_VOID)
3483 PL_stack_sp = oldsp;
3484 else
3485 leave_adjust_stacks(oldsp, oldsp, gimme, 0);
3486
3487 CX_LEAVE_SCOPE(cx);
3488 cx_popsub(cx);
3489 cx_popblock(cx);
3490 retop = cx->blk_sub.retop;
3491 CX_POP(cx);
3492
3493 return retop;
3494
3495 The steps above are in a very specific order, designed to be the
3496 reverse order of when the context was pushed. The first thing to do is
3497 to copy and/or protect any return arguments and free any temps in the
3498 current scope. Scope exits like an rvalue sub normally return a mortal
3499 copy of their return args (as opposed to lvalue subs). It is important
3500 to make this copy before the save stack is popped or variables are
3501 restored, or bad things like the following can happen:
3502
3503 sub f { my $x =...; $x } # $x freed before we get to copy it
3504 sub f { /(...)/; $1 } # PL_curpm restored before $1 copied
3505
3506 Although we wish to free any temps at the same time, we have to be
3507 careful not to free any temps which are keeping return args alive; nor
3508 to free the temps we have just created while mortal copying return
3509 args. Fortunately, "leave_adjust_stacks()" is capable of making mortal
3510 copies of return args, shifting args down the stack, and only
3511 processing those entries on the temps stack that are safe to do so.
3512
3513 In void context no args are returned, so it's more efficient to skip
3514 calling "leave_adjust_stacks()". Also in void context, a "nextstate" op
3515 is likely to be imminently called which will do a "FREETMPS", so
3516 there's no need to do that either.
3517
3518 The next step is to pop savestack entries: "CX_LEAVE_SCOPE(cx)" is just
3519 defined as "LEAVE_SCOPE(cx->blk_oldsaveix)". Note that during the
3520 popping, it's possible for perl to call destructors, call "STORE" to
3521 undo localisations of tied vars, and so on. Any of these can die or
3522 call "exit()". In this case, "dounwind()" will be called, and the
3523 current context stack frame will be re-processed. Thus it is vital that
3524 all steps in popping a context are done in such a way to support
3525 reentrancy. The other alternative, of decrementing "cxstack_ix" before
3526 processing the frame, would lead to leaks and the like if something
3527 died halfway through, or overwriting of the current frame.
3528
3529 "CX_LEAVE_SCOPE" itself is safely re-entrant: if only half the
3530 savestack items have been popped before dying and getting trapped by
3531 eval, then the "CX_LEAVE_SCOPE"s in "dounwind" or "pp_leaveeval" will
3532 continue where the first one left off.
3533
3534 The next step is the type-specific context processing; in this case
3535 "cx_popsub". In part, this looks like:
3536
3537 cv = cx->blk_sub.cv;
3538 CvDEPTH(cv) = cx->blk_sub.olddepth;
3539 cx->blk_sub.cv = NULL;
3540 SvREFCNT_dec(cv);
3541
3542 where its processing the just-executed CV. Note that before it
3543 decrements the CV's reference count, it nulls the "blk_sub.cv". This
3544 means that if it re-enters, the CV won't be freed twice. It also means
3545 that you can't rely on such type-specific fields having useful values
3546 after the return from "cx_popfoo".
3547
3548 Next, "cx_popblock" restores all the various interpreter vars to their
3549 previous values or previous high water marks; it expands to:
3550
3551 PL_markstack_ptr = PL_markstack + cx->blk_oldmarksp;
3552 PL_scopestack_ix = cx->blk_oldscopesp;
3553 PL_curpm = cx->blk_oldpm;
3554 PL_curcop = cx->blk_oldcop;
3555 PL_tmps_floor = cx->blk_old_tmpsfloor;
3556
3557 Note that it doesn't restore "PL_stack_sp"; as mentioned earlier, which
3558 value to restore it to depends on the context type (specifically "for
3559 (list) {}"), and what args (if any) it returns; and that will already
3560 have been sorted out earlier by "leave_adjust_stacks()".
3561
3562 Finally, the context stack pointer is actually decremented by
3563 "CX_POP(cx)". After this point, it's possible that that the current
3564 context frame could be overwritten by other contexts being pushed.
3565 Although things like ties and "DESTROY" are supposed to work within a
3566 new context stack, it's best not to assume this. Indeed on debugging
3567 builds, "CX_POP(cx)" deliberately sets "cx" to null to detect code that
3568 is still relying on the field values in that context frame. Note in the
3569 "pp_leavesub()" example above, we grab "blk_sub.retop" before calling
3570 "CX_POP".
3571
3572 Redoing contexts
3573 Finally, there is "cx_topblock(cx)", which acts like a
3574 super-"nextstate" as regards to resetting various vars to their base
3575 values. It is used in places like "pp_next", "pp_redo" and "pp_goto"
3576 where rather than exiting a scope, we want to re-initialise the scope.
3577 As well as resetting "PL_stack_sp" like "nextstate", it also resets
3578 "PL_markstack_ptr", "PL_scopestack_ix" and "PL_curpm". Note that it
3579 doesn't do a "FREETMPS".
3580
3582 Note: this section describes a non-public internal API that is subject
3583 to change without notice.
3584
3585 Perl's internal error-handling mechanisms implement "die" (and its
3586 internal equivalents) using longjmp. If this occurs during lexing,
3587 parsing or compilation, we must ensure that any ops allocated as part
3588 of the compilation process are freed. (Older Perl versions did not
3589 adequately handle this situation: when failing a parse, they would leak
3590 ops that were stored in C "auto" variables and not linked anywhere
3591 else.)
3592
3593 To handle this situation, Perl uses op slabs that are attached to the
3594 currently-compiling CV. A slab is a chunk of allocated memory. New ops
3595 are allocated as regions of the slab. If the slab fills up, a new one
3596 is created (and linked from the previous one). When an error occurs and
3597 the CV is freed, any ops remaining are freed.
3598
3599 Each op is preceded by two pointers: one points to the next op in the
3600 slab, and the other points to the slab that owns it. The next-op
3601 pointer is needed so that Perl can iterate over a slab and free all its
3602 ops. (Op structures are of different sizes, so the slab's ops can't
3603 merely be treated as a dense array.) The slab pointer is needed for
3604 accessing a reference count on the slab: when the last op on a slab is
3605 freed, the slab itself is freed.
3606
3607 The slab allocator puts the ops at the end of the slab first. This will
3608 tend to allocate the leaves of the op tree first, and the layout will
3609 therefore hopefully be cache-friendly. In addition, this means that
3610 there's no need to store the size of the slab (see below on why slabs
3611 vary in size), because Perl can follow pointers to find the last op.
3612
3613 It might seem possible eliminate slab reference counts altogether, by
3614 having all ops implicitly attached to "PL_compcv" when allocated and
3615 freed when the CV is freed. That would also allow "op_free" to skip
3616 "FreeOp" altogether, and thus free ops faster. But that doesn't work in
3617 those cases where ops need to survive beyond their CVs, such as re-
3618 evals.
3619
3620 The CV also has to have a reference count on the slab. Sometimes the
3621 first op created is immediately freed. If the reference count of the
3622 slab reaches 0, then it will be freed with the CV still pointing to it.
3623
3624 CVs use the "CVf_SLABBED" flag to indicate that the CV has a reference
3625 count on the slab. When this flag is set, the slab is accessible via
3626 "CvSTART" when "CvROOT" is not set, or by subtracting two pointers
3627 "(2*sizeof(I32 *))" from "CvROOT" when it is set. The alternative to
3628 this approach of sneaking the slab into "CvSTART" during compilation
3629 would be to enlarge the "xpvcv" struct by another pointer. But that
3630 would make all CVs larger, even though slab-based op freeing is
3631 typically of benefit only for programs that make significant use of
3632 string eval.
3633
3634 When the "CVf_SLABBED" flag is set, the CV takes responsibility for
3635 freeing the slab. If "CvROOT" is not set when the CV is freed or
3636 undeffed, it is assumed that a compilation error has occurred, so the
3637 op slab is traversed and all the ops are freed.
3638
3639 Under normal circumstances, the CV forgets about its slab (decrementing
3640 the reference count) when the root is attached. So the slab reference
3641 counting that happens when ops are freed takes care of freeing the
3642 slab. In some cases, the CV is told to forget about the slab
3643 ("cv_forget_slab") precisely so that the ops can survive after the CV
3644 is done away with.
3645
3646 Forgetting the slab when the root is attached is not strictly
3647 necessary, but avoids potential problems with "CvROOT" being written
3648 over. There is code all over the place, both in core and on CPAN, that
3649 does things with "CvROOT", so forgetting the slab makes things more
3650 robust and avoids potential problems.
3651
3652 Since the CV takes ownership of its slab when flagged, that flag is
3653 never copied when a CV is cloned, as one CV could free a slab that
3654 another CV still points to, since forced freeing of ops ignores the
3655 reference count (but asserts that it looks right).
3656
3657 To avoid slab fragmentation, freed ops are marked as freed and attached
3658 to the slab's freed chain (an idea stolen from DBM::Deep). Those freed
3659 ops are reused when possible. Not reusing freed ops would be simpler,
3660 but it would result in significantly higher memory usage for programs
3661 with large "if (DEBUG) {...}" blocks.
3662
3663 "SAVEFREEOP" is slightly problematic under this scheme. Sometimes it
3664 can cause an op to be freed after its CV. If the CV has forcibly freed
3665 the ops on its slab and the slab itself, then we will be fiddling with
3666 a freed slab. Making "SAVEFREEOP" a no-op doesn't help, as sometimes an
3667 op can be savefreed when there is no compilation error, so the op would
3668 never be freed. It holds a reference count on the slab, so the whole
3669 slab would leak. So "SAVEFREEOP" now sets a special flag on the op
3670 ("->op_savefree"). The forced freeing of ops after a compilation error
3671 won't free any ops thus marked.
3672
3673 Since many pieces of code create tiny subroutines consisting of only a
3674 few ops, and since a huge slab would be quite a bit of baggage for
3675 those to carry around, the first slab is always very small. To avoid
3676 allocating too many slabs for a single CV, each subsequent slab is
3677 twice the size of the previous.
3678
3679 Smartmatch expects to be able to allocate an op at run time, run it,
3680 and then throw it away. For that to work the op is simply malloced when
3681 PL_compcv hasn't been set up. So all slab-allocated ops are marked as
3682 such ("->op_slabbed"), to distinguish them from malloced ops.
3683
3685 Until May 1997, this document was maintained by Jeff Okamoto
3686 <okamoto@corp.hp.com>. It is now maintained as part of Perl itself by
3687 the Perl 5 Porters <perl5-porters@perl.org>.
3688
3689 With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
3690 Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
3691 Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
3692 Stephen McCamant, and Gurusamy Sarathy.
3693
3695 perlapi, perlintern, perlxs, perlembed
3696
3697
3698
3699perl v5.32.1 2021-05-31 PERLGUTS(1)