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