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