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