Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2318 lines
90 KiB

  1. =head1 NAME
  2. perlguts - Introduction to the Perl API
  3. =head1 DESCRIPTION
  4. This document attempts to describe how to use the Perl API, as well as
  5. containing some info on the basic workings of the Perl core. It is far
  6. from complete and probably contains many errors. Please refer any
  7. questions or comments to the author below.
  8. =head1 Variables
  9. =head2 Datatypes
  10. Perl has three typedefs that handle Perl's three main data types:
  11. SV Scalar Value
  12. AV Array Value
  13. HV Hash Value
  14. Each typedef has specific routines that manipulate the various data types.
  15. =head2 What is an "IV"?
  16. Perl uses a special typedef IV which is a simple signed integer type that is
  17. guaranteed to be large enough to hold a pointer (as well as an integer).
  18. Additionally, there is the UV, which is simply an unsigned IV.
  19. Perl also uses two special typedefs, I32 and I16, which will always be at
  20. least 32-bits and 16-bits long, respectively. (Again, there are U32 and U16,
  21. as well.)
  22. =head2 Working with SVs
  23. An SV can be created and loaded with one command. There are four types of
  24. values that can be loaded: an integer value (IV), a double (NV),
  25. a string (PV), and another scalar (SV).
  26. The six routines are:
  27. SV* newSViv(IV);
  28. SV* newSVnv(double);
  29. SV* newSVpv(const char*, int);
  30. SV* newSVpvn(const char*, int);
  31. SV* newSVpvf(const char*, ...);
  32. SV* newSVsv(SV*);
  33. To change the value of an *already-existing* SV, there are seven routines:
  34. void sv_setiv(SV*, IV);
  35. void sv_setuv(SV*, UV);
  36. void sv_setnv(SV*, double);
  37. void sv_setpv(SV*, const char*);
  38. void sv_setpvn(SV*, const char*, int)
  39. void sv_setpvf(SV*, const char*, ...);
  40. void sv_setpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
  41. void sv_setsv(SV*, SV*);
  42. Notice that you can choose to specify the length of the string to be
  43. assigned by using C<sv_setpvn>, C<newSVpvn>, or C<newSVpv>, or you may
  44. allow Perl to calculate the length by using C<sv_setpv> or by specifying
  45. 0 as the second argument to C<newSVpv>. Be warned, though, that Perl will
  46. determine the string's length by using C<strlen>, which depends on the
  47. string terminating with a NUL character.
  48. The arguments of C<sv_setpvf> are processed like C<sprintf>, and the
  49. formatted output becomes the value.
  50. C<sv_setpvfn> is an analogue of C<vsprintf>, but it allows you to specify
  51. either a pointer to a variable argument list or the address and length of
  52. an array of SVs. The last argument points to a boolean; on return, if that
  53. boolean is true, then locale-specific information has been used to format
  54. the string, and the string's contents are therefore untrustworthy (see
  55. L<perlsec>). This pointer may be NULL if that information is not
  56. important. Note that this function requires you to specify the length of
  57. the format.
  58. STRLEN is an integer type (Size_t, usually defined as size_t in
  59. config.h) guaranteed to be large enough to represent the size of
  60. any string that perl can handle.
  61. The C<sv_set*()> functions are not generic enough to operate on values
  62. that have "magic". See L<Magic Virtual Tables> later in this document.
  63. All SVs that contain strings should be terminated with a NUL character.
  64. If it is not NUL-terminated there is a risk of
  65. core dumps and corruptions from code which passes the string to C
  66. functions or system calls which expect a NUL-terminated string.
  67. Perl's own functions typically add a trailing NUL for this reason.
  68. Nevertheless, you should be very careful when you pass a string stored
  69. in an SV to a C function or system call.
  70. To access the actual value that an SV points to, you can use the macros:
  71. SvIV(SV*)
  72. SvUV(SV*)
  73. SvNV(SV*)
  74. SvPV(SV*, STRLEN len)
  75. SvPV_nolen(SV*)
  76. which will automatically coerce the actual scalar type into an IV, UV, double,
  77. or string.
  78. In the C<SvPV> macro, the length of the string returned is placed into the
  79. variable C<len> (this is a macro, so you do I<not> use C<&len>). If you do
  80. not care what the length of the data is, use the C<SvPV_nolen> macro.
  81. Historically the C<SvPV> macro with the global variable C<PL_na> has been
  82. used in this case. But that can be quite inefficient because C<PL_na> must
  83. be accessed in thread-local storage in threaded Perl. In any case, remember
  84. that Perl allows arbitrary strings of data that may both contain NULs and
  85. might not be terminated by a NUL.
  86. Also remember that C doesn't allow you to safely say C<foo(SvPV(s, len),
  87. len);>. It might work with your compiler, but it won't work for everyone.
  88. Break this sort of statement up into separate assignments:
  89. SV *s;
  90. STRLEN len;
  91. char * ptr;
  92. ptr = SvPV(s, len);
  93. foo(ptr, len);
  94. If you want to know if the scalar value is TRUE, you can use:
  95. SvTRUE(SV*)
  96. Although Perl will automatically grow strings for you, if you need to force
  97. Perl to allocate more memory for your SV, you can use the macro
  98. SvGROW(SV*, STRLEN newlen)
  99. which will determine if more memory needs to be allocated. If so, it will
  100. call the function C<sv_grow>. Note that C<SvGROW> can only increase, not
  101. decrease, the allocated memory of an SV and that it does not automatically
  102. add a byte for the a trailing NUL (perl's own string functions typically do
  103. C<SvGROW(sv, len + 1)>).
  104. If you have an SV and want to know what kind of data Perl thinks is stored
  105. in it, you can use the following macros to check the type of SV you have.
  106. SvIOK(SV*)
  107. SvNOK(SV*)
  108. SvPOK(SV*)
  109. You can get and set the current length of the string stored in an SV with
  110. the following macros:
  111. SvCUR(SV*)
  112. SvCUR_set(SV*, I32 val)
  113. You can also get a pointer to the end of the string stored in the SV
  114. with the macro:
  115. SvEND(SV*)
  116. But note that these last three macros are valid only if C<SvPOK()> is true.
  117. If you want to append something to the end of string stored in an C<SV*>,
  118. you can use the following functions:
  119. void sv_catpv(SV*, const char*);
  120. void sv_catpvn(SV*, const char*, STRLEN);
  121. void sv_catpvf(SV*, const char*, ...);
  122. void sv_catpvfn(SV*, const char*, STRLEN, va_list *, SV **, I32, bool);
  123. void sv_catsv(SV*, SV*);
  124. The first function calculates the length of the string to be appended by
  125. using C<strlen>. In the second, you specify the length of the string
  126. yourself. The third function processes its arguments like C<sprintf> and
  127. appends the formatted output. The fourth function works like C<vsprintf>.
  128. You can specify the address and length of an array of SVs instead of the
  129. va_list argument. The fifth function extends the string stored in the first
  130. SV with the string stored in the second SV. It also forces the second SV
  131. to be interpreted as a string.
  132. The C<sv_cat*()> functions are not generic enough to operate on values that
  133. have "magic". See L<Magic Virtual Tables> later in this document.
  134. If you know the name of a scalar variable, you can get a pointer to its SV
  135. by using the following:
  136. SV* get_sv("package::varname", FALSE);
  137. This returns NULL if the variable does not exist.
  138. If you want to know if this variable (or any other SV) is actually C<defined>,
  139. you can call:
  140. SvOK(SV*)
  141. The scalar C<undef> value is stored in an SV instance called C<PL_sv_undef>. Its
  142. address can be used whenever an C<SV*> is needed.
  143. There are also the two values C<PL_sv_yes> and C<PL_sv_no>, which contain Boolean
  144. TRUE and FALSE values, respectively. Like C<PL_sv_undef>, their addresses can
  145. be used whenever an C<SV*> is needed.
  146. Do not be fooled into thinking that C<(SV *) 0> is the same as C<&PL_sv_undef>.
  147. Take this code:
  148. SV* sv = (SV*) 0;
  149. if (I-am-to-return-a-real-value) {
  150. sv = sv_2mortal(newSViv(42));
  151. }
  152. sv_setsv(ST(0), sv);
  153. This code tries to return a new SV (which contains the value 42) if it should
  154. return a real value, or undef otherwise. Instead it has returned a NULL
  155. pointer which, somewhere down the line, will cause a segmentation violation,
  156. bus error, or just weird results. Change the zero to C<&PL_sv_undef> in the first
  157. line and all will be well.
  158. To free an SV that you've created, call C<SvREFCNT_dec(SV*)>. Normally this
  159. call is not necessary (see L<Reference Counts and Mortality>).
  160. =head2 Offsets
  161. Perl provides the function C<sv_chop> to efficiently remove characters
  162. from the beginning of a string; you give it an SV and a pointer to
  163. somewhere inside the the PV, and it discards everything before the
  164. pointer. The efficiency comes by means of a little hack: instead of
  165. actually removing the characters, C<sv_chop> sets the flag C<OOK>
  166. (offset OK) to signal to other functions that the offset hack is in
  167. effect, and it puts the number of bytes chopped off into the IV field
  168. of the SV. It then moves the PV pointer (called C<SvPVX>) forward that
  169. many bytes, and adjusts C<SvCUR> and C<SvLEN>.
  170. Hence, at this point, the start of the buffer that we allocated lives
  171. at C<SvPVX(sv) - SvIV(sv)> in memory and the PV pointer is pointing
  172. into the middle of this allocated storage.
  173. This is best demonstrated by example:
  174. % ./perl -Ilib -MDevel::Peek -le '$a="12345"; $a=~s/.//; Dump($a)'
  175. SV = PVIV(0x8128450) at 0x81340f0
  176. REFCNT = 1
  177. FLAGS = (POK,OOK,pPOK)
  178. IV = 1 (OFFSET)
  179. PV = 0x8135781 ( "1" . ) "2345"\0
  180. CUR = 4
  181. LEN = 5
  182. Here the number of bytes chopped off (1) is put into IV, and
  183. C<Devel::Peek::Dump> helpfully reminds us that this is an offset. The
  184. portion of the string between the "real" and the "fake" beginnings is
  185. shown in parentheses, and the values of C<SvCUR> and C<SvLEN> reflect
  186. the fake beginning, not the real one.
  187. Something similar to the offset hack is perfomed on AVs to enable
  188. efficient shifting and splicing off the beginning of the array; while
  189. C<AvARRAY> points to the first element in the array that is visible from
  190. Perl, C<AvALLOC> points to the real start of the C array. These are
  191. usually the same, but a C<shift> operation can be carried out by
  192. increasing C<AvARRAY> by one and decreasing C<AvFILL> and C<AvLEN>.
  193. Again, the location of the real start of the C array only comes into
  194. play when freeing the array. See C<av_shift> in F<av.c>.
  195. =head2 What's Really Stored in an SV?
  196. Recall that the usual method of determining the type of scalar you have is
  197. to use C<Sv*OK> macros. Because a scalar can be both a number and a string,
  198. usually these macros will always return TRUE and calling the C<Sv*V>
  199. macros will do the appropriate conversion of string to integer/double or
  200. integer/double to string.
  201. If you I<really> need to know if you have an integer, double, or string
  202. pointer in an SV, you can use the following three macros instead:
  203. SvIOKp(SV*)
  204. SvNOKp(SV*)
  205. SvPOKp(SV*)
  206. These will tell you if you truly have an integer, double, or string pointer
  207. stored in your SV. The "p" stands for private.
  208. In general, though, it's best to use the C<Sv*V> macros.
  209. =head2 Working with AVs
  210. There are two ways to create and load an AV. The first method creates an
  211. empty AV:
  212. AV* newAV();
  213. The second method both creates the AV and initially populates it with SVs:
  214. AV* av_make(I32 num, SV **ptr);
  215. The second argument points to an array containing C<num> C<SV*>'s. Once the
  216. AV has been created, the SVs can be destroyed, if so desired.
  217. Once the AV has been created, the following operations are possible on AVs:
  218. void av_push(AV*, SV*);
  219. SV* av_pop(AV*);
  220. SV* av_shift(AV*);
  221. void av_unshift(AV*, I32 num);
  222. These should be familiar operations, with the exception of C<av_unshift>.
  223. This routine adds C<num> elements at the front of the array with the C<undef>
  224. value. You must then use C<av_store> (described below) to assign values
  225. to these new elements.
  226. Here are some other functions:
  227. I32 av_len(AV*);
  228. SV** av_fetch(AV*, I32 key, I32 lval);
  229. SV** av_store(AV*, I32 key, SV* val);
  230. The C<av_len> function returns the highest index value in array (just
  231. like $#array in Perl). If the array is empty, -1 is returned. The
  232. C<av_fetch> function returns the value at index C<key>, but if C<lval>
  233. is non-zero, then C<av_fetch> will store an undef value at that index.
  234. The C<av_store> function stores the value C<val> at index C<key>, and does
  235. not increment the reference count of C<val>. Thus the caller is responsible
  236. for taking care of that, and if C<av_store> returns NULL, the caller will
  237. have to decrement the reference count to avoid a memory leak. Note that
  238. C<av_fetch> and C<av_store> both return C<SV**>'s, not C<SV*>'s as their
  239. return value.
  240. void av_clear(AV*);
  241. void av_undef(AV*);
  242. void av_extend(AV*, I32 key);
  243. The C<av_clear> function deletes all the elements in the AV* array, but
  244. does not actually delete the array itself. The C<av_undef> function will
  245. delete all the elements in the array plus the array itself. The
  246. C<av_extend> function extends the array so that it contains at least C<key+1>
  247. elements. If C<key+1> is less than the currently allocated length of the array,
  248. then nothing is done.
  249. If you know the name of an array variable, you can get a pointer to its AV
  250. by using the following:
  251. AV* get_av("package::varname", FALSE);
  252. This returns NULL if the variable does not exist.
  253. See L<Understanding the Magic of Tied Hashes and Arrays> for more
  254. information on how to use the array access functions on tied arrays.
  255. =head2 Working with HVs
  256. To create an HV, you use the following routine:
  257. HV* newHV();
  258. Once the HV has been created, the following operations are possible on HVs:
  259. SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
  260. SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
  261. The C<klen> parameter is the length of the key being passed in (Note that
  262. you cannot pass 0 in as a value of C<klen> to tell Perl to measure the
  263. length of the key). The C<val> argument contains the SV pointer to the
  264. scalar being stored, and C<hash> is the precomputed hash value (zero if
  265. you want C<hv_store> to calculate it for you). The C<lval> parameter
  266. indicates whether this fetch is actually a part of a store operation, in
  267. which case a new undefined value will be added to the HV with the supplied
  268. key and C<hv_fetch> will return as if the value had already existed.
  269. Remember that C<hv_store> and C<hv_fetch> return C<SV**>'s and not just
  270. C<SV*>. To access the scalar value, you must first dereference the return
  271. value. However, you should check to make sure that the return value is
  272. not NULL before dereferencing it.
  273. These two functions check if a hash table entry exists, and deletes it.
  274. bool hv_exists(HV*, const char* key, U32 klen);
  275. SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
  276. If C<flags> does not include the C<G_DISCARD> flag then C<hv_delete> will
  277. create and return a mortal copy of the deleted value.
  278. And more miscellaneous functions:
  279. void hv_clear(HV*);
  280. void hv_undef(HV*);
  281. Like their AV counterparts, C<hv_clear> deletes all the entries in the hash
  282. table but does not actually delete the hash table. The C<hv_undef> deletes
  283. both the entries and the hash table itself.
  284. Perl keeps the actual data in linked list of structures with a typedef of HE.
  285. These contain the actual key and value pointers (plus extra administrative
  286. overhead). The key is a string pointer; the value is an C<SV*>. However,
  287. once you have an C<HE*>, to get the actual key and value, use the routines
  288. specified below.
  289. I32 hv_iterinit(HV*);
  290. /* Prepares starting point to traverse hash table */
  291. HE* hv_iternext(HV*);
  292. /* Get the next entry, and return a pointer to a
  293. structure that has both the key and value */
  294. char* hv_iterkey(HE* entry, I32* retlen);
  295. /* Get the key from an HE structure and also return
  296. the length of the key string */
  297. SV* hv_iterval(HV*, HE* entry);
  298. /* Return a SV pointer to the value of the HE
  299. structure */
  300. SV* hv_iternextsv(HV*, char** key, I32* retlen);
  301. /* This convenience routine combines hv_iternext,
  302. hv_iterkey, and hv_iterval. The key and retlen
  303. arguments are return values for the key and its
  304. length. The value is returned in the SV* argument */
  305. If you know the name of a hash variable, you can get a pointer to its HV
  306. by using the following:
  307. HV* get_hv("package::varname", FALSE);
  308. This returns NULL if the variable does not exist.
  309. The hash algorithm is defined in the C<PERL_HASH(hash, key, klen)> macro:
  310. hash = 0;
  311. while (klen--)
  312. hash = (hash * 33) + *key++;
  313. hash = hash + (hash >> 5); /* after 5.6 */
  314. The last step was added in version 5.6 to improve distribution of
  315. lower bits in the resulting hash value.
  316. See L<Understanding the Magic of Tied Hashes and Arrays> for more
  317. information on how to use the hash access functions on tied hashes.
  318. =head2 Hash API Extensions
  319. Beginning with version 5.004, the following functions are also supported:
  320. HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
  321. HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
  322. bool hv_exists_ent (HV* tb, SV* key, U32 hash);
  323. SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
  324. SV* hv_iterkeysv (HE* entry);
  325. Note that these functions take C<SV*> keys, which simplifies writing
  326. of extension code that deals with hash structures. These functions
  327. also allow passing of C<SV*> keys to C<tie> functions without forcing
  328. you to stringify the keys (unlike the previous set of functions).
  329. They also return and accept whole hash entries (C<HE*>), making their
  330. use more efficient (since the hash number for a particular string
  331. doesn't have to be recomputed every time). See L<perlapi> for detailed
  332. descriptions.
  333. The following macros must always be used to access the contents of hash
  334. entries. Note that the arguments to these macros must be simple
  335. variables, since they may get evaluated more than once. See
  336. L<perlapi> for detailed descriptions of these macros.
  337. HePV(HE* he, STRLEN len)
  338. HeVAL(HE* he)
  339. HeHASH(HE* he)
  340. HeSVKEY(HE* he)
  341. HeSVKEY_force(HE* he)
  342. HeSVKEY_set(HE* he, SV* sv)
  343. These two lower level macros are defined, but must only be used when
  344. dealing with keys that are not C<SV*>s:
  345. HeKEY(HE* he)
  346. HeKLEN(HE* he)
  347. Note that both C<hv_store> and C<hv_store_ent> do not increment the
  348. reference count of the stored C<val>, which is the caller's responsibility.
  349. If these functions return a NULL value, the caller will usually have to
  350. decrement the reference count of C<val> to avoid a memory leak.
  351. =head2 References
  352. References are a special type of scalar that point to other data types
  353. (including references).
  354. To create a reference, use either of the following functions:
  355. SV* newRV_inc((SV*) thing);
  356. SV* newRV_noinc((SV*) thing);
  357. The C<thing> argument can be any of an C<SV*>, C<AV*>, or C<HV*>. The
  358. functions are identical except that C<newRV_inc> increments the reference
  359. count of the C<thing>, while C<newRV_noinc> does not. For historical
  360. reasons, C<newRV> is a synonym for C<newRV_inc>.
  361. Once you have a reference, you can use the following macro to dereference
  362. the reference:
  363. SvRV(SV*)
  364. then call the appropriate routines, casting the returned C<SV*> to either an
  365. C<AV*> or C<HV*>, if required.
  366. To determine if an SV is a reference, you can use the following macro:
  367. SvROK(SV*)
  368. To discover what type of value the reference refers to, use the following
  369. macro and then check the return value.
  370. SvTYPE(SvRV(SV*))
  371. The most useful types that will be returned are:
  372. SVt_IV Scalar
  373. SVt_NV Scalar
  374. SVt_PV Scalar
  375. SVt_RV Scalar
  376. SVt_PVAV Array
  377. SVt_PVHV Hash
  378. SVt_PVCV Code
  379. SVt_PVGV Glob (possible a file handle)
  380. SVt_PVMG Blessed or Magical Scalar
  381. See the sv.h header file for more details.
  382. =head2 Blessed References and Class Objects
  383. References are also used to support object-oriented programming. In the
  384. OO lexicon, an object is simply a reference that has been blessed into a
  385. package (or class). Once blessed, the programmer may now use the reference
  386. to access the various methods in the class.
  387. A reference can be blessed into a package with the following function:
  388. SV* sv_bless(SV* sv, HV* stash);
  389. The C<sv> argument must be a reference. The C<stash> argument specifies
  390. which class the reference will belong to. See
  391. L<Stashes and Globs> for information on converting class names into stashes.
  392. /* Still under construction */
  393. Upgrades rv to reference if not already one. Creates new SV for rv to
  394. point to. If C<classname> is non-null, the SV is blessed into the specified
  395. class. SV is returned.
  396. SV* newSVrv(SV* rv, const char* classname);
  397. Copies integer or double into an SV whose reference is C<rv>. SV is blessed
  398. if C<classname> is non-null.
  399. SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
  400. SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
  401. Copies the pointer value (I<the address, not the string!>) into an SV whose
  402. reference is rv. SV is blessed if C<classname> is non-null.
  403. SV* sv_setref_pv(SV* rv, const char* classname, PV iv);
  404. Copies string into an SV whose reference is C<rv>. Set length to 0 to let
  405. Perl calculate the string length. SV is blessed if C<classname> is non-null.
  406. SV* sv_setref_pvn(SV* rv, const char* classname, PV iv, STRLEN length);
  407. Tests whether the SV is blessed into the specified class. It does not
  408. check inheritance relationships.
  409. int sv_isa(SV* sv, const char* name);
  410. Tests whether the SV is a reference to a blessed object.
  411. int sv_isobject(SV* sv);
  412. Tests whether the SV is derived from the specified class. SV can be either
  413. a reference to a blessed object or a string containing a class name. This
  414. is the function implementing the C<UNIVERSAL::isa> functionality.
  415. bool sv_derived_from(SV* sv, const char* name);
  416. To check if you've got an object derived from a specific class you have
  417. to write:
  418. if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
  419. =head2 Creating New Variables
  420. To create a new Perl variable with an undef value which can be accessed from
  421. your Perl script, use the following routines, depending on the variable type.
  422. SV* get_sv("package::varname", TRUE);
  423. AV* get_av("package::varname", TRUE);
  424. HV* get_hv("package::varname", TRUE);
  425. Notice the use of TRUE as the second parameter. The new variable can now
  426. be set, using the routines appropriate to the data type.
  427. There are additional macros whose values may be bitwise OR'ed with the
  428. C<TRUE> argument to enable certain extra features. Those bits are:
  429. GV_ADDMULTI Marks the variable as multiply defined, thus preventing the
  430. "Name <varname> used only once: possible typo" warning.
  431. GV_ADDWARN Issues the warning "Had to create <varname> unexpectedly" if
  432. the variable did not exist before the function was called.
  433. If you do not specify a package name, the variable is created in the current
  434. package.
  435. =head2 Reference Counts and Mortality
  436. Perl uses an reference count-driven garbage collection mechanism. SVs,
  437. AVs, or HVs (xV for short in the following) start their life with a
  438. reference count of 1. If the reference count of an xV ever drops to 0,
  439. then it will be destroyed and its memory made available for reuse.
  440. This normally doesn't happen at the Perl level unless a variable is
  441. undef'ed or the last variable holding a reference to it is changed or
  442. overwritten. At the internal level, however, reference counts can be
  443. manipulated with the following macros:
  444. int SvREFCNT(SV* sv);
  445. SV* SvREFCNT_inc(SV* sv);
  446. void SvREFCNT_dec(SV* sv);
  447. However, there is one other function which manipulates the reference
  448. count of its argument. The C<newRV_inc> function, you will recall,
  449. creates a reference to the specified argument. As a side effect,
  450. it increments the argument's reference count. If this is not what
  451. you want, use C<newRV_noinc> instead.
  452. For example, imagine you want to return a reference from an XSUB function.
  453. Inside the XSUB routine, you create an SV which initially has a reference
  454. count of one. Then you call C<newRV_inc>, passing it the just-created SV.
  455. This returns the reference as a new SV, but the reference count of the
  456. SV you passed to C<newRV_inc> has been incremented to two. Now you
  457. return the reference from the XSUB routine and forget about the SV.
  458. But Perl hasn't! Whenever the returned reference is destroyed, the
  459. reference count of the original SV is decreased to one and nothing happens.
  460. The SV will hang around without any way to access it until Perl itself
  461. terminates. This is a memory leak.
  462. The correct procedure, then, is to use C<newRV_noinc> instead of
  463. C<newRV_inc>. Then, if and when the last reference is destroyed,
  464. the reference count of the SV will go to zero and it will be destroyed,
  465. stopping any memory leak.
  466. There are some convenience functions available that can help with the
  467. destruction of xVs. These functions introduce the concept of "mortality".
  468. An xV that is mortal has had its reference count marked to be decremented,
  469. but not actually decremented, until "a short time later". Generally the
  470. term "short time later" means a single Perl statement, such as a call to
  471. an XSUB function. The actual determinant for when mortal xVs have their
  472. reference count decremented depends on two macros, SAVETMPS and FREETMPS.
  473. See L<perlcall> and L<perlxs> for more details on these macros.
  474. "Mortalization" then is at its simplest a deferred C<SvREFCNT_dec>.
  475. However, if you mortalize a variable twice, the reference count will
  476. later be decremented twice.
  477. You should be careful about creating mortal variables. Strange things
  478. can happen if you make the same value mortal within multiple contexts,
  479. or if you make a variable mortal multiple times.
  480. To create a mortal variable, use the functions:
  481. SV* sv_newmortal()
  482. SV* sv_2mortal(SV*)
  483. SV* sv_mortalcopy(SV*)
  484. The first call creates a mortal SV, the second converts an existing
  485. SV to a mortal SV (and thus defers a call to C<SvREFCNT_dec>), and the
  486. third creates a mortal copy of an existing SV.
  487. The mortal routines are not just for SVs -- AVs and HVs can be
  488. made mortal by passing their address (type-casted to C<SV*>) to the
  489. C<sv_2mortal> or C<sv_mortalcopy> routines.
  490. =head2 Stashes and Globs
  491. A "stash" is a hash that contains all of the different objects that
  492. are contained within a package. Each key of the stash is a symbol
  493. name (shared by all the different types of objects that have the same
  494. name), and each value in the hash table is a GV (Glob Value). This GV
  495. in turn contains references to the various objects of that name,
  496. including (but not limited to) the following:
  497. Scalar Value
  498. Array Value
  499. Hash Value
  500. I/O Handle
  501. Format
  502. Subroutine
  503. There is a single stash called "PL_defstash" that holds the items that exist
  504. in the "main" package. To get at the items in other packages, append the
  505. string "::" to the package name. The items in the "Foo" package are in
  506. the stash "Foo::" in PL_defstash. The items in the "Bar::Baz" package are
  507. in the stash "Baz::" in "Bar::"'s stash.
  508. To get the stash pointer for a particular package, use the function:
  509. HV* gv_stashpv(const char* name, I32 create)
  510. HV* gv_stashsv(SV*, I32 create)
  511. The first function takes a literal string, the second uses the string stored
  512. in the SV. Remember that a stash is just a hash table, so you get back an
  513. C<HV*>. The C<create> flag will create a new package if it is set.
  514. The name that C<gv_stash*v> wants is the name of the package whose symbol table
  515. you want. The default package is called C<main>. If you have multiply nested
  516. packages, pass their names to C<gv_stash*v>, separated by C<::> as in the Perl
  517. language itself.
  518. Alternately, if you have an SV that is a blessed reference, you can find
  519. out the stash pointer by using:
  520. HV* SvSTASH(SvRV(SV*));
  521. then use the following to get the package name itself:
  522. char* HvNAME(HV* stash);
  523. If you need to bless or re-bless an object you can use the following
  524. function:
  525. SV* sv_bless(SV*, HV* stash)
  526. where the first argument, an C<SV*>, must be a reference, and the second
  527. argument is a stash. The returned C<SV*> can now be used in the same way
  528. as any other SV.
  529. For more information on references and blessings, consult L<perlref>.
  530. =head2 Double-Typed SVs
  531. Scalar variables normally contain only one type of value, an integer,
  532. double, pointer, or reference. Perl will automatically convert the
  533. actual scalar data from the stored type into the requested type.
  534. Some scalar variables contain more than one type of scalar data. For
  535. example, the variable C<$!> contains either the numeric value of C<errno>
  536. or its string equivalent from either C<strerror> or C<sys_errlist[]>.
  537. To force multiple data values into an SV, you must do two things: use the
  538. C<sv_set*v> routines to add the additional scalar type, then set a flag
  539. so that Perl will believe it contains more than one type of data. The
  540. four macros to set the flags are:
  541. SvIOK_on
  542. SvNOK_on
  543. SvPOK_on
  544. SvROK_on
  545. The particular macro you must use depends on which C<sv_set*v> routine
  546. you called first. This is because every C<sv_set*v> routine turns on
  547. only the bit for the particular type of data being set, and turns off
  548. all the rest.
  549. For example, to create a new Perl variable called "dberror" that contains
  550. both the numeric and descriptive string error values, you could use the
  551. following code:
  552. extern int dberror;
  553. extern char *dberror_list;
  554. SV* sv = get_sv("dberror", TRUE);
  555. sv_setiv(sv, (IV) dberror);
  556. sv_setpv(sv, dberror_list[dberror]);
  557. SvIOK_on(sv);
  558. If the order of C<sv_setiv> and C<sv_setpv> had been reversed, then the
  559. macro C<SvPOK_on> would need to be called instead of C<SvIOK_on>.
  560. =head2 Magic Variables
  561. [This section still under construction. Ignore everything here. Post no
  562. bills. Everything not permitted is forbidden.]
  563. Any SV may be magical, that is, it has special features that a normal
  564. SV does not have. These features are stored in the SV structure in a
  565. linked list of C<struct magic>'s, typedef'ed to C<MAGIC>.
  566. struct magic {
  567. MAGIC* mg_moremagic;
  568. MGVTBL* mg_virtual;
  569. U16 mg_private;
  570. char mg_type;
  571. U8 mg_flags;
  572. SV* mg_obj;
  573. char* mg_ptr;
  574. I32 mg_len;
  575. };
  576. Note this is current as of patchlevel 0, and could change at any time.
  577. =head2 Assigning Magic
  578. Perl adds magic to an SV using the sv_magic function:
  579. void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
  580. The C<sv> argument is a pointer to the SV that is to acquire a new magical
  581. feature.
  582. If C<sv> is not already magical, Perl uses the C<SvUPGRADE> macro to
  583. set the C<SVt_PVMG> flag for the C<sv>. Perl then continues by adding
  584. it to the beginning of the linked list of magical features. Any prior
  585. entry of the same type of magic is deleted. Note that this can be
  586. overridden, and multiple instances of the same type of magic can be
  587. associated with an SV.
  588. The C<name> and C<namlen> arguments are used to associate a string with
  589. the magic, typically the name of a variable. C<namlen> is stored in the
  590. C<mg_len> field and if C<name> is non-null and C<namlen> >= 0 a malloc'd
  591. copy of the name is stored in C<mg_ptr> field.
  592. The sv_magic function uses C<how> to determine which, if any, predefined
  593. "Magic Virtual Table" should be assigned to the C<mg_virtual> field.
  594. See the "Magic Virtual Table" section below. The C<how> argument is also
  595. stored in the C<mg_type> field.
  596. The C<obj> argument is stored in the C<mg_obj> field of the C<MAGIC>
  597. structure. If it is not the same as the C<sv> argument, the reference
  598. count of the C<obj> object is incremented. If it is the same, or if
  599. the C<how> argument is "#", or if it is a NULL pointer, then C<obj> is
  600. merely stored, without the reference count being incremented.
  601. There is also a function to add magic to an C<HV>:
  602. void hv_magic(HV *hv, GV *gv, int how);
  603. This simply calls C<sv_magic> and coerces the C<gv> argument into an C<SV>.
  604. To remove the magic from an SV, call the function sv_unmagic:
  605. void sv_unmagic(SV *sv, int type);
  606. The C<type> argument should be equal to the C<how> value when the C<SV>
  607. was initially made magical.
  608. =head2 Magic Virtual Tables
  609. The C<mg_virtual> field in the C<MAGIC> structure is a pointer to a
  610. C<MGVTBL>, which is a structure of function pointers and stands for
  611. "Magic Virtual Table" to handle the various operations that might be
  612. applied to that variable.
  613. The C<MGVTBL> has five pointers to the following routine types:
  614. int (*svt_get)(SV* sv, MAGIC* mg);
  615. int (*svt_set)(SV* sv, MAGIC* mg);
  616. U32 (*svt_len)(SV* sv, MAGIC* mg);
  617. int (*svt_clear)(SV* sv, MAGIC* mg);
  618. int (*svt_free)(SV* sv, MAGIC* mg);
  619. This MGVTBL structure is set at compile-time in C<perl.h> and there are
  620. currently 19 types (or 21 with overloading turned on). These different
  621. structures contain pointers to various routines that perform additional
  622. actions depending on which function is being called.
  623. Function pointer Action taken
  624. ---------------- ------------
  625. svt_get Do something after the value of the SV is retrieved.
  626. svt_set Do something after the SV is assigned a value.
  627. svt_len Report on the SV's length.
  628. svt_clear Clear something the SV represents.
  629. svt_free Free any extra storage associated with the SV.
  630. For instance, the MGVTBL structure called C<vtbl_sv> (which corresponds
  631. to an C<mg_type> of '\0') contains:
  632. { magic_get, magic_set, magic_len, 0, 0 }
  633. Thus, when an SV is determined to be magical and of type '\0', if a get
  634. operation is being performed, the routine C<magic_get> is called. All
  635. the various routines for the various magical types begin with C<magic_>.
  636. NOTE: the magic routines are not considered part of the Perl API, and may
  637. not be exported by the Perl library.
  638. The current kinds of Magic Virtual Tables are:
  639. mg_type MGVTBL Type of magic
  640. ------- ------ ----------------------------
  641. \0 vtbl_sv Special scalar variable
  642. A vtbl_amagic %OVERLOAD hash
  643. a vtbl_amagicelem %OVERLOAD hash element
  644. c (none) Holds overload table (AMT) on stash
  645. B vtbl_bm Boyer-Moore (fast string search)
  646. D vtbl_regdata Regex match position data (@+ and @- vars)
  647. d vtbl_regdatum Regex match position data element
  648. E vtbl_env %ENV hash
  649. e vtbl_envelem %ENV hash element
  650. f vtbl_fm Formline ('compiled' format)
  651. g vtbl_mglob m//g target / study()ed string
  652. I vtbl_isa @ISA array
  653. i vtbl_isaelem @ISA array element
  654. k vtbl_nkeys scalar(keys()) lvalue
  655. L (none) Debugger %_<filename
  656. l vtbl_dbline Debugger %_<filename element
  657. o vtbl_collxfrm Locale transformation
  658. P vtbl_pack Tied array or hash
  659. p vtbl_packelem Tied array or hash element
  660. q vtbl_packelem Tied scalar or handle
  661. S vtbl_sig %SIG hash
  662. s vtbl_sigelem %SIG hash element
  663. t vtbl_taint Taintedness
  664. U vtbl_uvar Available for use by extensions
  665. v vtbl_vec vec() lvalue
  666. x vtbl_substr substr() lvalue
  667. y vtbl_defelem Shadow "foreach" iterator variable /
  668. smart parameter vivification
  669. * vtbl_glob GV (typeglob)
  670. # vtbl_arylen Array length ($#ary)
  671. . vtbl_pos pos() lvalue
  672. ~ (none) Available for use by extensions
  673. When an uppercase and lowercase letter both exist in the table, then the
  674. uppercase letter is used to represent some kind of composite type (a list
  675. or a hash), and the lowercase letter is used to represent an element of
  676. that composite type.
  677. The '~' and 'U' magic types are defined specifically for use by
  678. extensions and will not be used by perl itself. Extensions can use
  679. '~' magic to 'attach' private information to variables (typically
  680. objects). This is especially useful because there is no way for
  681. normal perl code to corrupt this private information (unlike using
  682. extra elements of a hash object).
  683. Similarly, 'U' magic can be used much like tie() to call a C function
  684. any time a scalar's value is used or changed. The C<MAGIC>'s
  685. C<mg_ptr> field points to a C<ufuncs> structure:
  686. struct ufuncs {
  687. I32 (*uf_val)(IV, SV*);
  688. I32 (*uf_set)(IV, SV*);
  689. IV uf_index;
  690. };
  691. When the SV is read from or written to, the C<uf_val> or C<uf_set>
  692. function will be called with C<uf_index> as the first arg and a
  693. pointer to the SV as the second. A simple example of how to add 'U'
  694. magic is shown below. Note that the ufuncs structure is copied by
  695. sv_magic, so you can safely allocate it on the stack.
  696. void
  697. Umagic(sv)
  698. SV *sv;
  699. PREINIT:
  700. struct ufuncs uf;
  701. CODE:
  702. uf.uf_val = &my_get_fn;
  703. uf.uf_set = &my_set_fn;
  704. uf.uf_index = 0;
  705. sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
  706. Note that because multiple extensions may be using '~' or 'U' magic,
  707. it is important for extensions to take extra care to avoid conflict.
  708. Typically only using the magic on objects blessed into the same class
  709. as the extension is sufficient. For '~' magic, it may also be
  710. appropriate to add an I32 'signature' at the top of the private data
  711. area and check that.
  712. Also note that the C<sv_set*()> and C<sv_cat*()> functions described
  713. earlier do B<not> invoke 'set' magic on their targets. This must
  714. be done by the user either by calling the C<SvSETMAGIC()> macro after
  715. calling these functions, or by using one of the C<sv_set*_mg()> or
  716. C<sv_cat*_mg()> functions. Similarly, generic C code must call the
  717. C<SvGETMAGIC()> macro to invoke any 'get' magic if they use an SV
  718. obtained from external sources in functions that don't handle magic.
  719. See L<perlapi> for a description of these functions.
  720. For example, calls to the C<sv_cat*()> functions typically need to be
  721. followed by C<SvSETMAGIC()>, but they don't need a prior C<SvGETMAGIC()>
  722. since their implementation handles 'get' magic.
  723. =head2 Finding Magic
  724. MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
  725. This routine returns a pointer to the C<MAGIC> structure stored in the SV.
  726. If the SV does not have that magical feature, C<NULL> is returned. Also,
  727. if the SV is not of type SVt_PVMG, Perl may core dump.
  728. int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
  729. This routine checks to see what types of magic C<sv> has. If the mg_type
  730. field is an uppercase letter, then the mg_obj is copied to C<nsv>, but
  731. the mg_type field is changed to be the lowercase letter.
  732. =head2 Understanding the Magic of Tied Hashes and Arrays
  733. Tied hashes and arrays are magical beasts of the 'P' magic type.
  734. WARNING: As of the 5.004 release, proper usage of the array and hash
  735. access functions requires understanding a few caveats. Some
  736. of these caveats are actually considered bugs in the API, to be fixed
  737. in later releases, and are bracketed with [MAYCHANGE] below. If
  738. you find yourself actually applying such information in this section, be
  739. aware that the behavior may change in the future, umm, without warning.
  740. The perl tie function associates a variable with an object that implements
  741. the various GET, SET etc methods. To perform the equivalent of the perl
  742. tie function from an XSUB, you must mimic this behaviour. The code below
  743. carries out the necessary steps - firstly it creates a new hash, and then
  744. creates a second hash which it blesses into the class which will implement
  745. the tie methods. Lastly it ties the two hashes together, and returns a
  746. reference to the new tied hash. Note that the code below does NOT call the
  747. TIEHASH method in the MyTie class -
  748. see L<Calling Perl Routines from within C Programs> for details on how
  749. to do this.
  750. SV*
  751. mytie()
  752. PREINIT:
  753. HV *hash;
  754. HV *stash;
  755. SV *tie;
  756. CODE:
  757. hash = newHV();
  758. tie = newRV_noinc((SV*)newHV());
  759. stash = gv_stashpv("MyTie", TRUE);
  760. sv_bless(tie, stash);
  761. hv_magic(hash, tie, 'P');
  762. RETVAL = newRV_noinc(hash);
  763. OUTPUT:
  764. RETVAL
  765. The C<av_store> function, when given a tied array argument, merely
  766. copies the magic of the array onto the value to be "stored", using
  767. C<mg_copy>. It may also return NULL, indicating that the value did not
  768. actually need to be stored in the array. [MAYCHANGE] After a call to
  769. C<av_store> on a tied array, the caller will usually need to call
  770. C<mg_set(val)> to actually invoke the perl level "STORE" method on the
  771. TIEARRAY object. If C<av_store> did return NULL, a call to
  772. C<SvREFCNT_dec(val)> will also be usually necessary to avoid a memory
  773. leak. [/MAYCHANGE]
  774. The previous paragraph is applicable verbatim to tied hash access using the
  775. C<hv_store> and C<hv_store_ent> functions as well.
  776. C<av_fetch> and the corresponding hash functions C<hv_fetch> and
  777. C<hv_fetch_ent> actually return an undefined mortal value whose magic
  778. has been initialized using C<mg_copy>. Note the value so returned does not
  779. need to be deallocated, as it is already mortal. [MAYCHANGE] But you will
  780. need to call C<mg_get()> on the returned value in order to actually invoke
  781. the perl level "FETCH" method on the underlying TIE object. Similarly,
  782. you may also call C<mg_set()> on the return value after possibly assigning
  783. a suitable value to it using C<sv_setsv>, which will invoke the "STORE"
  784. method on the TIE object. [/MAYCHANGE]
  785. [MAYCHANGE]
  786. In other words, the array or hash fetch/store functions don't really
  787. fetch and store actual values in the case of tied arrays and hashes. They
  788. merely call C<mg_copy> to attach magic to the values that were meant to be
  789. "stored" or "fetched". Later calls to C<mg_get> and C<mg_set> actually
  790. do the job of invoking the TIE methods on the underlying objects. Thus
  791. the magic mechanism currently implements a kind of lazy access to arrays
  792. and hashes.
  793. Currently (as of perl version 5.004), use of the hash and array access
  794. functions requires the user to be aware of whether they are operating on
  795. "normal" hashes and arrays, or on their tied variants. The API may be
  796. changed to provide more transparent access to both tied and normal data
  797. types in future versions.
  798. [/MAYCHANGE]
  799. You would do well to understand that the TIEARRAY and TIEHASH interfaces
  800. are mere sugar to invoke some perl method calls while using the uniform hash
  801. and array syntax. The use of this sugar imposes some overhead (typically
  802. about two to four extra opcodes per FETCH/STORE operation, in addition to
  803. the creation of all the mortal variables required to invoke the methods).
  804. This overhead will be comparatively small if the TIE methods are themselves
  805. substantial, but if they are only a few statements long, the overhead
  806. will not be insignificant.
  807. =head2 Localizing changes
  808. Perl has a very handy construction
  809. {
  810. local $var = 2;
  811. ...
  812. }
  813. This construction is I<approximately> equivalent to
  814. {
  815. my $oldvar = $var;
  816. $var = 2;
  817. ...
  818. $var = $oldvar;
  819. }
  820. The biggest difference is that the first construction would
  821. reinstate the initial value of $var, irrespective of how control exits
  822. the block: C<goto>, C<return>, C<die>/C<eval> etc. It is a little bit
  823. more efficient as well.
  824. There is a way to achieve a similar task from C via Perl API: create a
  825. I<pseudo-block>, and arrange for some changes to be automatically
  826. undone at the end of it, either explicit, or via a non-local exit (via
  827. die()). A I<block>-like construct is created by a pair of
  828. C<ENTER>/C<LEAVE> macros (see L<perlcall/"Returning a Scalar">).
  829. Such a construct may be created specially for some important localized
  830. task, or an existing one (like boundaries of enclosing Perl
  831. subroutine/block, or an existing pair for freeing TMPs) may be
  832. used. (In the second case the overhead of additional localization must
  833. be almost negligible.) Note that any XSUB is automatically enclosed in
  834. an C<ENTER>/C<LEAVE> pair.
  835. Inside such a I<pseudo-block> the following service is available:
  836. =over 4
  837. =item C<SAVEINT(int i)>
  838. =item C<SAVEIV(IV i)>
  839. =item C<SAVEI32(I32 i)>
  840. =item C<SAVELONG(long i)>
  841. These macros arrange things to restore the value of integer variable
  842. C<i> at the end of enclosing I<pseudo-block>.
  843. =item C<SAVESPTR(s)>
  844. =item C<SAVEPPTR(p)>
  845. These macros arrange things to restore the value of pointers C<s> and
  846. C<p>. C<s> must be a pointer of a type which survives conversion to
  847. C<SV*> and back, C<p> should be able to survive conversion to C<char*>
  848. and back.
  849. =item C<SAVEFREESV(SV *sv)>
  850. The refcount of C<sv> would be decremented at the end of
  851. I<pseudo-block>. This is similar to C<sv_2mortal> in that it is also a
  852. mechanism for doing a delayed C<SvREFCNT_dec>. However, while C<sv_2mortal>
  853. extends the lifetime of C<sv> until the beginning of the next statement,
  854. C<SAVEFREESV> extends it until the end of the enclosing scope. These
  855. lifetimes can be wildly different.
  856. Also compare C<SAVEMORTALIZESV>.
  857. =item C<SAVEMORTALIZESV(SV *sv)>
  858. Just like C<SAVEFREESV>, but mortalizes C<sv> at the end of the current
  859. scope instead of decrementing its reference count. This usually has the
  860. effect of keeping C<sv> alive until the statement that called the currently
  861. live scope has finished executing.
  862. =item C<SAVEFREEOP(OP *op)>
  863. The C<OP *> is op_free()ed at the end of I<pseudo-block>.
  864. =item C<SAVEFREEPV(p)>
  865. The chunk of memory which is pointed to by C<p> is Safefree()ed at the
  866. end of I<pseudo-block>.
  867. =item C<SAVECLEARSV(SV *sv)>
  868. Clears a slot in the current scratchpad which corresponds to C<sv> at
  869. the end of I<pseudo-block>.
  870. =item C<SAVEDELETE(HV *hv, char *key, I32 length)>
  871. The key C<key> of C<hv> is deleted at the end of I<pseudo-block>. The
  872. string pointed to by C<key> is Safefree()ed. If one has a I<key> in
  873. short-lived storage, the corresponding string may be reallocated like
  874. this:
  875. SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
  876. =item C<SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)>
  877. At the end of I<pseudo-block> the function C<f> is called with the
  878. only argument C<p>.
  879. =item C<SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)>
  880. At the end of I<pseudo-block> the function C<f> is called with the
  881. implicit context argument (if any), and C<p>.
  882. =item C<SAVESTACK_POS()>
  883. The current offset on the Perl internal stack (cf. C<SP>) is restored
  884. at the end of I<pseudo-block>.
  885. =back
  886. The following API list contains functions, thus one needs to
  887. provide pointers to the modifiable data explicitly (either C pointers,
  888. or Perlish C<GV *>s). Where the above macros take C<int>, a similar
  889. function takes C<int *>.
  890. =over 4
  891. =item C<SV* save_scalar(GV *gv)>
  892. Equivalent to Perl code C<local $gv>.
  893. =item C<AV* save_ary(GV *gv)>
  894. =item C<HV* save_hash(GV *gv)>
  895. Similar to C<save_scalar>, but localize C<@gv> and C<%gv>.
  896. =item C<void save_item(SV *item)>
  897. Duplicates the current value of C<SV>, on the exit from the current
  898. C<ENTER>/C<LEAVE> I<pseudo-block> will restore the value of C<SV>
  899. using the stored value.
  900. =item C<void save_list(SV **sarg, I32 maxsarg)>
  901. A variant of C<save_item> which takes multiple arguments via an array
  902. C<sarg> of C<SV*> of length C<maxsarg>.
  903. =item C<SV* save_svref(SV **sptr)>
  904. Similar to C<save_scalar>, but will reinstate a C<SV *>.
  905. =item C<void save_aptr(AV **aptr)>
  906. =item C<void save_hptr(HV **hptr)>
  907. Similar to C<save_svref>, but localize C<AV *> and C<HV *>.
  908. =back
  909. The C<Alias> module implements localization of the basic types within the
  910. I<caller's scope>. People who are interested in how to localize things in
  911. the containing scope should take a look there too.
  912. =head1 Subroutines
  913. =head2 XSUBs and the Argument Stack
  914. The XSUB mechanism is a simple way for Perl programs to access C subroutines.
  915. An XSUB routine will have a stack that contains the arguments from the Perl
  916. program, and a way to map from the Perl data structures to a C equivalent.
  917. The stack arguments are accessible through the C<ST(n)> macro, which returns
  918. the C<n>'th stack argument. Argument 0 is the first argument passed in the
  919. Perl subroutine call. These arguments are C<SV*>, and can be used anywhere
  920. an C<SV*> is used.
  921. Most of the time, output from the C routine can be handled through use of
  922. the RETVAL and OUTPUT directives. However, there are some cases where the
  923. argument stack is not already long enough to handle all the return values.
  924. An example is the POSIX tzname() call, which takes no arguments, but returns
  925. two, the local time zone's standard and summer time abbreviations.
  926. To handle this situation, the PPCODE directive is used and the stack is
  927. extended using the macro:
  928. EXTEND(SP, num);
  929. where C<SP> is the macro that represents the local copy of the stack pointer,
  930. and C<num> is the number of elements the stack should be extended by.
  931. Now that there is room on the stack, values can be pushed on it using the
  932. macros to push IVs, doubles, strings, and SV pointers respectively:
  933. PUSHi(IV)
  934. PUSHn(double)
  935. PUSHp(char*, I32)
  936. PUSHs(SV*)
  937. And now the Perl program calling C<tzname>, the two values will be assigned
  938. as in:
  939. ($standard_abbrev, $summer_abbrev) = POSIX::tzname;
  940. An alternate (and possibly simpler) method to pushing values on the stack is
  941. to use the macros:
  942. XPUSHi(IV)
  943. XPUSHn(double)
  944. XPUSHp(char*, I32)
  945. XPUSHs(SV*)
  946. These macros automatically adjust the stack for you, if needed. Thus, you
  947. do not need to call C<EXTEND> to extend the stack.
  948. However, see L</Putting a C value on Perl stack>
  949. For more information, consult L<perlxs> and L<perlxstut>.
  950. =head2 Calling Perl Routines from within C Programs
  951. There are four routines that can be used to call a Perl subroutine from
  952. within a C program. These four are:
  953. I32 call_sv(SV*, I32);
  954. I32 call_pv(const char*, I32);
  955. I32 call_method(const char*, I32);
  956. I32 call_argv(const char*, I32, register char**);
  957. The routine most often used is C<call_sv>. The C<SV*> argument
  958. contains either the name of the Perl subroutine to be called, or a
  959. reference to the subroutine. The second argument consists of flags
  960. that control the context in which the subroutine is called, whether
  961. or not the subroutine is being passed arguments, how errors should be
  962. trapped, and how to treat return values.
  963. All four routines return the number of arguments that the subroutine returned
  964. on the Perl stack.
  965. These routines used to be called C<perl_call_sv> etc., before Perl v5.6.0,
  966. but those names are now deprecated; macros of the same name are provided for
  967. compatibility.
  968. When using any of these routines (except C<call_argv>), the programmer
  969. must manipulate the Perl stack. These include the following macros and
  970. functions:
  971. dSP
  972. SP
  973. PUSHMARK()
  974. PUTBACK
  975. SPAGAIN
  976. ENTER
  977. SAVETMPS
  978. FREETMPS
  979. LEAVE
  980. XPUSH*()
  981. POP*()
  982. For a detailed description of calling conventions from C to Perl,
  983. consult L<perlcall>.
  984. =head2 Memory Allocation
  985. All memory meant to be used with the Perl API functions should be manipulated
  986. using the macros described in this section. The macros provide the necessary
  987. transparency between differences in the actual malloc implementation that is
  988. used within perl.
  989. It is suggested that you enable the version of malloc that is distributed
  990. with Perl. It keeps pools of various sizes of unallocated memory in
  991. order to satisfy allocation requests more quickly. However, on some
  992. platforms, it may cause spurious malloc or free errors.
  993. New(x, pointer, number, type);
  994. Newc(x, pointer, number, type, cast);
  995. Newz(x, pointer, number, type);
  996. These three macros are used to initially allocate memory.
  997. The first argument C<x> was a "magic cookie" that was used to keep track
  998. of who called the macro, to help when debugging memory problems. However,
  999. the current code makes no use of this feature (most Perl developers now
  1000. use run-time memory checkers), so this argument can be any number.
  1001. The second argument C<pointer> should be the name of a variable that will
  1002. point to the newly allocated memory.
  1003. The third and fourth arguments C<number> and C<type> specify how many of
  1004. the specified type of data structure should be allocated. The argument
  1005. C<type> is passed to C<sizeof>. The final argument to C<Newc>, C<cast>,
  1006. should be used if the C<pointer> argument is different from the C<type>
  1007. argument.
  1008. Unlike the C<New> and C<Newc> macros, the C<Newz> macro calls C<memzero>
  1009. to zero out all the newly allocated memory.
  1010. Renew(pointer, number, type);
  1011. Renewc(pointer, number, type, cast);
  1012. Safefree(pointer)
  1013. These three macros are used to change a memory buffer size or to free a
  1014. piece of memory no longer needed. The arguments to C<Renew> and C<Renewc>
  1015. match those of C<New> and C<Newc> with the exception of not needing the
  1016. "magic cookie" argument.
  1017. Move(source, dest, number, type);
  1018. Copy(source, dest, number, type);
  1019. Zero(dest, number, type);
  1020. These three macros are used to move, copy, or zero out previously allocated
  1021. memory. The C<source> and C<dest> arguments point to the source and
  1022. destination starting points. Perl will move, copy, or zero out C<number>
  1023. instances of the size of the C<type> data structure (using the C<sizeof>
  1024. function).
  1025. =head2 PerlIO
  1026. The most recent development releases of Perl has been experimenting with
  1027. removing Perl's dependency on the "normal" standard I/O suite and allowing
  1028. other stdio implementations to be used. This involves creating a new
  1029. abstraction layer that then calls whichever implementation of stdio Perl
  1030. was compiled with. All XSUBs should now use the functions in the PerlIO
  1031. abstraction layer and not make any assumptions about what kind of stdio
  1032. is being used.
  1033. For a complete description of the PerlIO abstraction, consult L<perlapio>.
  1034. =head2 Putting a C value on Perl stack
  1035. A lot of opcodes (this is an elementary operation in the internal perl
  1036. stack machine) put an SV* on the stack. However, as an optimization
  1037. the corresponding SV is (usually) not recreated each time. The opcodes
  1038. reuse specially assigned SVs (I<target>s) which are (as a corollary)
  1039. not constantly freed/created.
  1040. Each of the targets is created only once (but see
  1041. L<Scratchpads and recursion> below), and when an opcode needs to put
  1042. an integer, a double, or a string on stack, it just sets the
  1043. corresponding parts of its I<target> and puts the I<target> on stack.
  1044. The macro to put this target on stack is C<PUSHTARG>, and it is
  1045. directly used in some opcodes, as well as indirectly in zillions of
  1046. others, which use it via C<(X)PUSH[pni]>.
  1047. Because the target is reused, you must be careful when pushing multiple
  1048. values on the stack. The following code will not do what you think:
  1049. XPUSHi(10);
  1050. XPUSHi(20);
  1051. This translates as "set C<TARG> to 10, push a pointer to C<TARG> onto
  1052. the stack; set C<TARG> to 20, push a pointer to C<TARG> onto the stack".
  1053. At the end of the operation, the stack does not contain the values 10
  1054. and 20, but actually contains two pointers to C<TARG>, which we have set
  1055. to 20. If you need to push multiple different values, use C<XPUSHs>,
  1056. which bypasses C<TARG>.
  1057. On a related note, if you do use C<(X)PUSH[npi]>, then you're going to
  1058. need a C<dTARG> in your variable declarations so that the C<*PUSH*>
  1059. macros can make use of the local variable C<TARG>.
  1060. =head2 Scratchpads
  1061. The question remains on when the SVs which are I<target>s for opcodes
  1062. are created. The answer is that they are created when the current unit --
  1063. a subroutine or a file (for opcodes for statements outside of
  1064. subroutines) -- is compiled. During this time a special anonymous Perl
  1065. array is created, which is called a scratchpad for the current
  1066. unit.
  1067. A scratchpad keeps SVs which are lexicals for the current unit and are
  1068. targets for opcodes. One can deduce that an SV lives on a scratchpad
  1069. by looking on its flags: lexicals have C<SVs_PADMY> set, and
  1070. I<target>s have C<SVs_PADTMP> set.
  1071. The correspondence between OPs and I<target>s is not 1-to-1. Different
  1072. OPs in the compile tree of the unit can use the same target, if this
  1073. would not conflict with the expected life of the temporary.
  1074. =head2 Scratchpads and recursion
  1075. In fact it is not 100% true that a compiled unit contains a pointer to
  1076. the scratchpad AV. In fact it contains a pointer to an AV of
  1077. (initially) one element, and this element is the scratchpad AV. Why do
  1078. we need an extra level of indirection?
  1079. The answer is B<recursion>, and maybe (sometime soon) B<threads>. Both
  1080. these can create several execution pointers going into the same
  1081. subroutine. For the subroutine-child not write over the temporaries
  1082. for the subroutine-parent (lifespan of which covers the call to the
  1083. child), the parent and the child should have different
  1084. scratchpads. (I<And> the lexicals should be separate anyway!)
  1085. So each subroutine is born with an array of scratchpads (of length 1).
  1086. On each entry to the subroutine it is checked that the current
  1087. depth of the recursion is not more than the length of this array, and
  1088. if it is, new scratchpad is created and pushed into the array.
  1089. The I<target>s on this scratchpad are C<undef>s, but they are already
  1090. marked with correct flags.
  1091. =head1 Compiled code
  1092. =head2 Code tree
  1093. Here we describe the internal form your code is converted to by
  1094. Perl. Start with a simple example:
  1095. $a = $b + $c;
  1096. This is converted to a tree similar to this one:
  1097. assign-to
  1098. / \
  1099. + $a
  1100. / \
  1101. $b $c
  1102. (but slightly more complicated). This tree reflects the way Perl
  1103. parsed your code, but has nothing to do with the execution order.
  1104. There is an additional "thread" going through the nodes of the tree
  1105. which shows the order of execution of the nodes. In our simplified
  1106. example above it looks like:
  1107. $b ---> $c ---> + ---> $a ---> assign-to
  1108. But with the actual compile tree for C<$a = $b + $c> it is different:
  1109. some nodes I<optimized away>. As a corollary, though the actual tree
  1110. contains more nodes than our simplified example, the execution order
  1111. is the same as in our example.
  1112. =head2 Examining the tree
  1113. If you have your perl compiled for debugging (usually done with C<-D
  1114. optimize=-g> on C<Configure> command line), you may examine the
  1115. compiled tree by specifying C<-Dx> on the Perl command line. The
  1116. output takes several lines per node, and for C<$b+$c> it looks like
  1117. this:
  1118. 5 TYPE = add ===> 6
  1119. TARG = 1
  1120. FLAGS = (SCALAR,KIDS)
  1121. {
  1122. TYPE = null ===> (4)
  1123. (was rv2sv)
  1124. FLAGS = (SCALAR,KIDS)
  1125. {
  1126. 3 TYPE = gvsv ===> 4
  1127. FLAGS = (SCALAR)
  1128. GV = main::b
  1129. }
  1130. }
  1131. {
  1132. TYPE = null ===> (5)
  1133. (was rv2sv)
  1134. FLAGS = (SCALAR,KIDS)
  1135. {
  1136. 4 TYPE = gvsv ===> 5
  1137. FLAGS = (SCALAR)
  1138. GV = main::c
  1139. }
  1140. }
  1141. This tree has 5 nodes (one per C<TYPE> specifier), only 3 of them are
  1142. not optimized away (one per number in the left column). The immediate
  1143. children of the given node correspond to C<{}> pairs on the same level
  1144. of indentation, thus this listing corresponds to the tree:
  1145. add
  1146. / \
  1147. null null
  1148. | |
  1149. gvsv gvsv
  1150. The execution order is indicated by C<===E<gt>> marks, thus it is C<3
  1151. 4 5 6> (node C<6> is not included into above listing), i.e.,
  1152. C<gvsv gvsv add whatever>.
  1153. Each of these nodes represents an op, a fundamental operation inside the
  1154. Perl core. The code which implements each operation can be found in the
  1155. F<pp*.c> files; the function which implements the op with type C<gvsv>
  1156. is C<pp_gvsv>, and so on. As the tree above shows, different ops have
  1157. different numbers of children: C<add> is a binary operator, as one would
  1158. expect, and so has two children. To accommodate the various different
  1159. numbers of children, there are various types of op data structure, and
  1160. they link together in different ways.
  1161. The simplest type of op structure is C<OP>: this has no children. Unary
  1162. operators, C<UNOP>s, have one child, and this is pointed to by the
  1163. C<op_first> field. Binary operators (C<BINOP>s) have not only an
  1164. C<op_first> field but also an C<op_last> field. The most complex type of
  1165. op is a C<LISTOP>, which has any number of children. In this case, the
  1166. first child is pointed to by C<op_first> and the last child by
  1167. C<op_last>. The children in between can be found by iteratively
  1168. following the C<op_sibling> pointer from the first child to the last.
  1169. There are also two other op types: a C<PMOP> holds a regular expression,
  1170. and has no children, and a C<LOOP> may or may not have children. If the
  1171. C<op_children> field is non-zero, it behaves like a C<LISTOP>. To
  1172. complicate matters, if a C<UNOP> is actually a C<null> op after
  1173. optimization (see L</Compile pass 2: context propagation>) it will still
  1174. have children in accordance with its former type.
  1175. =head2 Compile pass 1: check routines
  1176. The tree is created by the compiler while I<yacc> code feeds it
  1177. the constructions it recognizes. Since I<yacc> works bottom-up, so does
  1178. the first pass of perl compilation.
  1179. What makes this pass interesting for perl developers is that some
  1180. optimization may be performed on this pass. This is optimization by
  1181. so-called "check routines". The correspondence between node names
  1182. and corresponding check routines is described in F<opcode.pl> (do not
  1183. forget to run C<make regen_headers> if you modify this file).
  1184. A check routine is called when the node is fully constructed except
  1185. for the execution-order thread. Since at this time there are no
  1186. back-links to the currently constructed node, one can do most any
  1187. operation to the top-level node, including freeing it and/or creating
  1188. new nodes above/below it.
  1189. The check routine returns the node which should be inserted into the
  1190. tree (if the top-level node was not modified, check routine returns
  1191. its argument).
  1192. By convention, check routines have names C<ck_*>. They are usually
  1193. called from C<new*OP> subroutines (or C<convert>) (which in turn are
  1194. called from F<perly.y>).
  1195. =head2 Compile pass 1a: constant folding
  1196. Immediately after the check routine is called the returned node is
  1197. checked for being compile-time executable. If it is (the value is
  1198. judged to be constant) it is immediately executed, and a I<constant>
  1199. node with the "return value" of the corresponding subtree is
  1200. substituted instead. The subtree is deleted.
  1201. If constant folding was not performed, the execution-order thread is
  1202. created.
  1203. =head2 Compile pass 2: context propagation
  1204. When a context for a part of compile tree is known, it is propagated
  1205. down through the tree. At this time the context can have 5 values
  1206. (instead of 2 for runtime context): void, boolean, scalar, list, and
  1207. lvalue. In contrast with the pass 1 this pass is processed from top
  1208. to bottom: a node's context determines the context for its children.
  1209. Additional context-dependent optimizations are performed at this time.
  1210. Since at this moment the compile tree contains back-references (via
  1211. "thread" pointers), nodes cannot be free()d now. To allow
  1212. optimized-away nodes at this stage, such nodes are null()ified instead
  1213. of free()ing (i.e. their type is changed to OP_NULL).
  1214. =head2 Compile pass 3: peephole optimization
  1215. After the compile tree for a subroutine (or for an C<eval> or a file)
  1216. is created, an additional pass over the code is performed. This pass
  1217. is neither top-down or bottom-up, but in the execution order (with
  1218. additional complications for conditionals). These optimizations are
  1219. done in the subroutine peep(). Optimizations performed at this stage
  1220. are subject to the same restrictions as in the pass 2.
  1221. =head1 Examining internal data structures with the C<dump> functions
  1222. To aid debugging, the source file F<dump.c> contains a number of
  1223. functions which produce formatted output of internal data structures.
  1224. The most commonly used of these functions is C<Perl_sv_dump>; it's used
  1225. for dumping SVs, AVs, HVs, and CVs. The C<Devel::Peek> module calls
  1226. C<sv_dump> to produce debugging output from Perl-space, so users of that
  1227. module should already be familiar with its format.
  1228. C<Perl_op_dump> can be used to dump an C<OP> structure or any of its
  1229. derivatives, and produces output similiar to C<perl -Dx>; in fact,
  1230. C<Perl_dump_eval> will dump the main root of the code being evaluated,
  1231. exactly like C<-Dx>.
  1232. Other useful functions are C<Perl_dump_sub>, which turns a C<GV> into an
  1233. op tree, C<Perl_dump_packsubs> which calls C<Perl_dump_sub> on all the
  1234. subroutines in a package like so: (Thankfully, these are all xsubs, so
  1235. there is no op tree)
  1236. (gdb) print Perl_dump_packsubs(PL_defstash)
  1237. SUB attributes::bootstrap = (xsub 0x811fedc 0)
  1238. SUB UNIVERSAL::can = (xsub 0x811f50c 0)
  1239. SUB UNIVERSAL::isa = (xsub 0x811f304 0)
  1240. SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
  1241. SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
  1242. and C<Perl_dump_all>, which dumps all the subroutines in the stash and
  1243. the op tree of the main root.
  1244. =head1 How multiple interpreters and concurrency are supported
  1245. =head2 Background and PERL_IMPLICIT_CONTEXT
  1246. The Perl interpreter can be regarded as a closed box: it has an API
  1247. for feeding it code or otherwise making it do things, but it also has
  1248. functions for its own use. This smells a lot like an object, and
  1249. there are ways for you to build Perl so that you can have multiple
  1250. interpreters, with one interpreter represented either as a C++ object,
  1251. a C structure, or inside a thread. The thread, the C structure, or
  1252. the C++ object will contain all the context, the state of that
  1253. interpreter.
  1254. Three macros control the major Perl build flavors: MULTIPLICITY,
  1255. USE_THREADS and PERL_OBJECT. The MULTIPLICITY build has a C structure
  1256. that packages all the interpreter state, there is a similar thread-specific
  1257. data structure under USE_THREADS, and the (now deprecated) PERL_OBJECT
  1258. build has a C++ class to maintain interpreter state. In all three cases,
  1259. PERL_IMPLICIT_CONTEXT is also normally defined, and enables the
  1260. support for passing in a "hidden" first argument that represents all three
  1261. data structures.
  1262. All this obviously requires a way for the Perl internal functions to be
  1263. C++ methods, subroutines taking some kind of structure as the first
  1264. argument, or subroutines taking nothing as the first argument. To
  1265. enable these three very different ways of building the interpreter,
  1266. the Perl source (as it does in so many other situations) makes heavy
  1267. use of macros and subroutine naming conventions.
  1268. First problem: deciding which functions will be public API functions and
  1269. which will be private. All functions whose names begin C<S_> are private
  1270. (think "S" for "secret" or "static"). All other functions begin with
  1271. "Perl_", but just because a function begins with "Perl_" does not mean it is
  1272. part of the API. (See L</Internal Functions>.) The easiest way to be B<sure> a
  1273. function is part of the API is to find its entry in L<perlapi>.
  1274. If it exists in L<perlapi>, it's part of the API. If it doesn't, and you
  1275. think it should be (i.e., you need it for your extension), send mail via
  1276. L<perlbug> explaining why you think it should be.
  1277. Second problem: there must be a syntax so that the same subroutine
  1278. declarations and calls can pass a structure as their first argument,
  1279. or pass nothing. To solve this, the subroutines are named and
  1280. declared in a particular way. Here's a typical start of a static
  1281. function used within the Perl guts:
  1282. STATIC void
  1283. S_incline(pTHX_ char *s)
  1284. STATIC becomes "static" in C, and is #define'd to nothing in C++.
  1285. A public function (i.e. part of the internal API, but not necessarily
  1286. sanctioned for use in extensions) begins like this:
  1287. void
  1288. Perl_sv_setsv(pTHX_ SV* dsv, SV* ssv)
  1289. C<pTHX_> is one of a number of macros (in perl.h) that hide the
  1290. details of the interpreter's context. THX stands for "thread", "this",
  1291. or "thingy", as the case may be. (And no, George Lucas is not involved. :-)
  1292. The first character could be 'p' for a B<p>rototype, 'a' for B<a>rgument,
  1293. or 'd' for B<d>eclaration, so we have C<pTHX>, C<aTHX> and C<dTHX>, and
  1294. their variants.
  1295. When Perl is built without options that set PERL_IMPLICIT_CONTEXT, there is no
  1296. first argument containing the interpreter's context. The trailing underscore
  1297. in the pTHX_ macro indicates that the macro expansion needs a comma
  1298. after the context argument because other arguments follow it. If
  1299. PERL_IMPLICIT_CONTEXT is not defined, pTHX_ will be ignored, and the
  1300. subroutine is not prototyped to take the extra argument. The form of the
  1301. macro without the trailing underscore is used when there are no additional
  1302. explicit arguments.
  1303. When a core function calls another, it must pass the context. This
  1304. is normally hidden via macros. Consider C<sv_setsv>. It expands into
  1305. something like this:
  1306. ifdef PERL_IMPLICIT_CONTEXT
  1307. define sv_setsv(a,b) Perl_sv_setsv(aTHX_ a, b)
  1308. /* can't do this for vararg functions, see below */
  1309. else
  1310. define sv_setsv Perl_sv_setsv
  1311. endif
  1312. This works well, and means that XS authors can gleefully write:
  1313. sv_setsv(foo, bar);
  1314. and still have it work under all the modes Perl could have been
  1315. compiled with.
  1316. Under PERL_OBJECT in the core, that will translate to either:
  1317. CPerlObj::Perl_sv_setsv(foo,bar); # in CPerlObj functions,
  1318. # C++ takes care of 'this'
  1319. or
  1320. pPerl->Perl_sv_setsv(foo,bar); # in truly static functions,
  1321. # see objXSUB.h
  1322. Under PERL_OBJECT in extensions (aka PERL_CAPI), or under
  1323. MULTIPLICITY/USE_THREADS with PERL_IMPLICIT_CONTEXT in both core
  1324. and extensions, it will become:
  1325. Perl_sv_setsv(aTHX_ foo, bar); # the canonical Perl "API"
  1326. # for all build flavors
  1327. This doesn't work so cleanly for varargs functions, though, as macros
  1328. imply that the number of arguments is known in advance. Instead we
  1329. either need to spell them out fully, passing C<aTHX_> as the first
  1330. argument (the Perl core tends to do this with functions like
  1331. Perl_warner), or use a context-free version.
  1332. The context-free version of Perl_warner is called
  1333. Perl_warner_nocontext, and does not take the extra argument. Instead
  1334. it does dTHX; to get the context from thread-local storage. We
  1335. C<#define warner Perl_warner_nocontext> so that extensions get source
  1336. compatibility at the expense of performance. (Passing an arg is
  1337. cheaper than grabbing it from thread-local storage.)
  1338. You can ignore [pad]THX[xo] when browsing the Perl headers/sources.
  1339. Those are strictly for use within the core. Extensions and embedders
  1340. need only be aware of [pad]THX.
  1341. =head2 So what happened to dTHR?
  1342. C<dTHR> was introduced in perl 5.005 to support the older thread model.
  1343. The older thread model now uses the C<THX> mechanism to pass context
  1344. pointers around, so C<dTHR> is not useful any more. Perl 5.6.0 and
  1345. later still have it for backward source compatibility, but it is defined
  1346. to be a no-op.
  1347. =head2 How do I use all this in extensions?
  1348. When Perl is built with PERL_IMPLICIT_CONTEXT, extensions that call
  1349. any functions in the Perl API will need to pass the initial context
  1350. argument somehow. The kicker is that you will need to write it in
  1351. such a way that the extension still compiles when Perl hasn't been
  1352. built with PERL_IMPLICIT_CONTEXT enabled.
  1353. There are three ways to do this. First, the easy but inefficient way,
  1354. which is also the default, in order to maintain source compatibility
  1355. with extensions: whenever XSUB.h is #included, it redefines the aTHX
  1356. and aTHX_ macros to call a function that will return the context.
  1357. Thus, something like:
  1358. sv_setsv(asv, bsv);
  1359. in your extension will translate to this when PERL_IMPLICIT_CONTEXT is
  1360. in effect:
  1361. Perl_sv_setsv(Perl_get_context(), asv, bsv);
  1362. or to this otherwise:
  1363. Perl_sv_setsv(asv, bsv);
  1364. You have to do nothing new in your extension to get this; since
  1365. the Perl library provides Perl_get_context(), it will all just
  1366. work.
  1367. The second, more efficient way is to use the following template for
  1368. your Foo.xs:
  1369. #define PERL_NO_GET_CONTEXT /* we want efficiency */
  1370. #include "EXTERN.h"
  1371. #include "perl.h"
  1372. #include "XSUB.h"
  1373. static my_private_function(int arg1, int arg2);
  1374. static SV *
  1375. my_private_function(int arg1, int arg2)
  1376. {
  1377. dTHX; /* fetch context */
  1378. ... call many Perl API functions ...
  1379. }
  1380. [... etc ...]
  1381. MODULE = Foo PACKAGE = Foo
  1382. /* typical XSUB */
  1383. void
  1384. my_xsub(arg)
  1385. int arg
  1386. CODE:
  1387. my_private_function(arg, 10);
  1388. Note that the only two changes from the normal way of writing an
  1389. extension is the addition of a C<#define PERL_NO_GET_CONTEXT> before
  1390. including the Perl headers, followed by a C<dTHX;> declaration at
  1391. the start of every function that will call the Perl API. (You'll
  1392. know which functions need this, because the C compiler will complain
  1393. that there's an undeclared identifier in those functions.) No changes
  1394. are needed for the XSUBs themselves, because the XS() macro is
  1395. correctly defined to pass in the implicit context if needed.
  1396. The third, even more efficient way is to ape how it is done within
  1397. the Perl guts:
  1398. #define PERL_NO_GET_CONTEXT /* we want efficiency */
  1399. #include "EXTERN.h"
  1400. #include "perl.h"
  1401. #include "XSUB.h"
  1402. /* pTHX_ only needed for functions that call Perl API */
  1403. static my_private_function(pTHX_ int arg1, int arg2);
  1404. static SV *
  1405. my_private_function(pTHX_ int arg1, int arg2)
  1406. {
  1407. /* dTHX; not needed here, because THX is an argument */
  1408. ... call Perl API functions ...
  1409. }
  1410. [... etc ...]
  1411. MODULE = Foo PACKAGE = Foo
  1412. /* typical XSUB */
  1413. void
  1414. my_xsub(arg)
  1415. int arg
  1416. CODE:
  1417. my_private_function(aTHX_ arg, 10);
  1418. This implementation never has to fetch the context using a function
  1419. call, since it is always passed as an extra argument. Depending on
  1420. your needs for simplicity or efficiency, you may mix the previous
  1421. two approaches freely.
  1422. Never add a comma after C<pTHX> yourself--always use the form of the
  1423. macro with the underscore for functions that take explicit arguments,
  1424. or the form without the argument for functions with no explicit arguments.
  1425. =head2 Should I do anything special if I call perl from multiple threads?
  1426. If you create interpreters in one thread and then proceed to call them in
  1427. another, you need to make sure perl's own Thread Local Storage (TLS) slot is
  1428. initialized correctly in each of those threads.
  1429. The C<perl_alloc> and C<perl_clone> API functions will automatically set
  1430. the TLS slot to the interpreter they created, so that there is no need to do
  1431. anything special if the interpreter is always accessed in the same thread that
  1432. created it, and that thread did not create or call any other interpreters
  1433. afterwards. If that is not the case, you have to set the TLS slot of the
  1434. thread before calling any functions in the Perl API on that particular
  1435. interpreter. This is done by calling the C<PERL_SET_CONTEXT> macro in that
  1436. thread as the first thing you do:
  1437. /* do this before doing anything else with some_perl */
  1438. PERL_SET_CONTEXT(some_perl);
  1439. ... other Perl API calls on some_perl go here ...
  1440. =head2 Future Plans and PERL_IMPLICIT_SYS
  1441. Just as PERL_IMPLICIT_CONTEXT provides a way to bundle up everything
  1442. that the interpreter knows about itself and pass it around, so too are
  1443. there plans to allow the interpreter to bundle up everything it knows
  1444. about the environment it's running on. This is enabled with the
  1445. PERL_IMPLICIT_SYS macro. Currently it only works with PERL_OBJECT
  1446. and USE_THREADS on Windows (see inside iperlsys.h).
  1447. This allows the ability to provide an extra pointer (called the "host"
  1448. environment) for all the system calls. This makes it possible for
  1449. all the system stuff to maintain their own state, broken down into
  1450. seven C structures. These are thin wrappers around the usual system
  1451. calls (see win32/perllib.c) for the default perl executable, but for a
  1452. more ambitious host (like the one that would do fork() emulation) all
  1453. the extra work needed to pretend that different interpreters are
  1454. actually different "processes", would be done here.
  1455. The Perl engine/interpreter and the host are orthogonal entities.
  1456. There could be one or more interpreters in a process, and one or
  1457. more "hosts", with free association between them.
  1458. =head1 Internal Functions
  1459. All of Perl's internal functions which will be exposed to the outside
  1460. world are be prefixed by C<Perl_> so that they will not conflict with XS
  1461. functions or functions used in a program in which Perl is embedded.
  1462. Similarly, all global variables begin with C<PL_>. (By convention,
  1463. static functions start with C<S_>)
  1464. Inside the Perl core, you can get at the functions either with or
  1465. without the C<Perl_> prefix, thanks to a bunch of defines that live in
  1466. F<embed.h>. This header file is generated automatically from
  1467. F<embed.pl>. F<embed.pl> also creates the prototyping header files for
  1468. the internal functions, generates the documentation and a lot of other
  1469. bits and pieces. It's important that when you add a new function to the
  1470. core or change an existing one, you change the data in the table at the
  1471. end of F<embed.pl> as well. Here's a sample entry from that table:
  1472. Apd |SV** |av_fetch |AV* ar|I32 key|I32 lval
  1473. The second column is the return type, the third column the name. Columns
  1474. after that are the arguments. The first column is a set of flags:
  1475. =over 3
  1476. =item A
  1477. This function is a part of the public API.
  1478. =item p
  1479. This function has a C<Perl_> prefix; ie, it is defined as C<Perl_av_fetch>
  1480. =item d
  1481. This function has documentation using the C<apidoc> feature which we'll
  1482. look at in a second.
  1483. =back
  1484. Other available flags are:
  1485. =over 3
  1486. =item s
  1487. This is a static function and is defined as C<S_whatever>, and usually
  1488. called within the sources as C<whatever(...)>.
  1489. =item n
  1490. This does not use C<aTHX_> and C<pTHX> to pass interpreter context. (See
  1491. L<perlguts/Background and PERL_IMPLICIT_CONTEXT>.)
  1492. =item r
  1493. This function never returns; C<croak>, C<exit> and friends.
  1494. =item f
  1495. This function takes a variable number of arguments, C<printf> style.
  1496. The argument list should end with C<...>, like this:
  1497. Afprd |void |croak |const char* pat|...
  1498. =item M
  1499. This function is part of the experimental development API, and may change
  1500. or disappear without notice.
  1501. =item o
  1502. This function should not have a compatibility macro to define, say,
  1503. C<Perl_parse> to C<parse>. It must be called as C<Perl_parse>.
  1504. =item j
  1505. This function is not a member of C<CPerlObj>. If you don't know
  1506. what this means, don't use it.
  1507. =item x
  1508. This function isn't exported out of the Perl core.
  1509. =back
  1510. If you edit F<embed.pl>, you will need to run C<make regen_headers> to
  1511. force a rebuild of F<embed.h> and other auto-generated files.
  1512. =head2 Formatted Printing of IVs, UVs, and NVs
  1513. If you are printing IVs, UVs, or NVS instead of the stdio(3) style
  1514. formatting codes like C<%d>, C<%ld>, C<%f>, you should use the
  1515. following macros for portability
  1516. IVdf IV in decimal
  1517. UVuf UV in decimal
  1518. UVof UV in octal
  1519. UVxf UV in hexadecimal
  1520. NVef NV %e-like
  1521. NVff NV %f-like
  1522. NVgf NV %g-like
  1523. These will take care of 64-bit integers and long doubles.
  1524. For example:
  1525. printf("IV is %"IVdf"\n", iv);
  1526. The IVdf will expand to whatever is the correct format for the IVs.
  1527. If you are printing addresses of pointers, use UVxf combined
  1528. with PTR2UV(), do not use %lx or %p.
  1529. =head2 Pointer-To-Integer and Integer-To-Pointer
  1530. Because pointer size does not necessarily equal integer size,
  1531. use the follow macros to do it right.
  1532. PTR2UV(pointer)
  1533. PTR2IV(pointer)
  1534. PTR2NV(pointer)
  1535. INT2PTR(pointertotype, integer)
  1536. For example:
  1537. IV iv = ...;
  1538. SV *sv = INT2PTR(SV*, iv);
  1539. and
  1540. AV *av = ...;
  1541. UV uv = PTR2UV(av);
  1542. =head2 Source Documentation
  1543. There's an effort going on to document the internal functions and
  1544. automatically produce reference manuals from them - L<perlapi> is one
  1545. such manual which details all the functions which are available to XS
  1546. writers. L<perlintern> is the autogenerated manual for the functions
  1547. which are not part of the API and are supposedly for internal use only.
  1548. Source documentation is created by putting POD comments into the C
  1549. source, like this:
  1550. /*
  1551. =for apidoc sv_setiv
  1552. Copies an integer into the given SV. Does not handle 'set' magic. See
  1553. C<sv_setiv_mg>.
  1554. =cut
  1555. */
  1556. Please try and supply some documentation if you add functions to the
  1557. Perl core.
  1558. =head1 Unicode Support
  1559. Perl 5.6.0 introduced Unicode support. It's important for porters and XS
  1560. writers to understand this support and make sure that the code they
  1561. write does not corrupt Unicode data.
  1562. =head2 What B<is> Unicode, anyway?
  1563. In the olden, less enlightened times, we all used to use ASCII. Most of
  1564. us did, anyway. The big problem with ASCII is that it's American. Well,
  1565. no, that's not actually the problem; the problem is that it's not
  1566. particularly useful for people who don't use the Roman alphabet. What
  1567. used to happen was that particular languages would stick their own
  1568. alphabet in the upper range of the sequence, between 128 and 255. Of
  1569. course, we then ended up with plenty of variants that weren't quite
  1570. ASCII, and the whole point of it being a standard was lost.
  1571. Worse still, if you've got a language like Chinese or
  1572. Japanese that has hundreds or thousands of characters, then you really
  1573. can't fit them into a mere 256, so they had to forget about ASCII
  1574. altogether, and build their own systems using pairs of numbers to refer
  1575. to one character.
  1576. To fix this, some people formed Unicode, Inc. and
  1577. produced a new character set containing all the characters you can
  1578. possibly think of and more. There are several ways of representing these
  1579. characters, and the one Perl uses is called UTF8. UTF8 uses
  1580. a variable number of bytes to represent a character, instead of just
  1581. one. You can learn more about Unicode at http://www.unicode.org/
  1582. =head2 How can I recognise a UTF8 string?
  1583. You can't. This is because UTF8 data is stored in bytes just like
  1584. non-UTF8 data. The Unicode character 200, (C<0xC8> for you hex types)
  1585. capital E with a grave accent, is represented by the two bytes
  1586. C<v196.172>. Unfortunately, the non-Unicode string C<chr(196).chr(172)>
  1587. has that byte sequence as well. So you can't tell just by looking - this
  1588. is what makes Unicode input an interesting problem.
  1589. The API function C<is_utf8_string> can help; it'll tell you if a string
  1590. contains only valid UTF8 characters. However, it can't do the work for
  1591. you. On a character-by-character basis, C<is_utf8_char> will tell you
  1592. whether the current character in a string is valid UTF8.
  1593. =head2 How does UTF8 represent Unicode characters?
  1594. As mentioned above, UTF8 uses a variable number of bytes to store a
  1595. character. Characters with values 1...128 are stored in one byte, just
  1596. like good ol' ASCII. Character 129 is stored as C<v194.129>; this
  1597. continues up to character 191, which is C<v194.191>. Now we've run out of
  1598. bits (191 is binary C<10111111>) so we move on; 192 is C<v195.128>. And
  1599. so it goes on, moving to three bytes at character 2048.
  1600. Assuming you know you're dealing with a UTF8 string, you can find out
  1601. how long the first character in it is with the C<UTF8SKIP> macro:
  1602. char *utf = "\305\233\340\240\201";
  1603. I32 len;
  1604. len = UTF8SKIP(utf); /* len is 2 here */
  1605. utf += len;
  1606. len = UTF8SKIP(utf); /* len is 3 here */
  1607. Another way to skip over characters in a UTF8 string is to use
  1608. C<utf8_hop>, which takes a string and a number of characters to skip
  1609. over. You're on your own about bounds checking, though, so don't use it
  1610. lightly.
  1611. All bytes in a multi-byte UTF8 character will have the high bit set, so
  1612. you can test if you need to do something special with this character
  1613. like this:
  1614. UV uv;
  1615. if (utf & 0x80)
  1616. /* Must treat this as UTF8 */
  1617. uv = utf8_to_uv(utf);
  1618. else
  1619. /* OK to treat this character as a byte */
  1620. uv = *utf;
  1621. You can also see in that example that we use C<utf8_to_uv> to get the
  1622. value of the character; the inverse function C<uv_to_utf8> is available
  1623. for putting a UV into UTF8:
  1624. if (uv > 0x80)
  1625. /* Must treat this as UTF8 */
  1626. utf8 = uv_to_utf8(utf8, uv);
  1627. else
  1628. /* OK to treat this character as a byte */
  1629. *utf8++ = uv;
  1630. You B<must> convert characters to UVs using the above functions if
  1631. you're ever in a situation where you have to match UTF8 and non-UTF8
  1632. characters. You may not skip over UTF8 characters in this case. If you
  1633. do this, you'll lose the ability to match hi-bit non-UTF8 characters;
  1634. for instance, if your UTF8 string contains C<v196.172>, and you skip
  1635. that character, you can never match a C<chr(200)> in a non-UTF8 string.
  1636. So don't do that!
  1637. =head2 How does Perl store UTF8 strings?
  1638. Currently, Perl deals with Unicode strings and non-Unicode strings
  1639. slightly differently. If a string has been identified as being UTF-8
  1640. encoded, Perl will set a flag in the SV, C<SVf_UTF8>. You can check and
  1641. manipulate this flag with the following macros:
  1642. SvUTF8(sv)
  1643. SvUTF8_on(sv)
  1644. SvUTF8_off(sv)
  1645. This flag has an important effect on Perl's treatment of the string: if
  1646. Unicode data is not properly distinguished, regular expressions,
  1647. C<length>, C<substr> and other string handling operations will have
  1648. undesirable results.
  1649. The problem comes when you have, for instance, a string that isn't
  1650. flagged is UTF8, and contains a byte sequence that could be UTF8 -
  1651. especially when combining non-UTF8 and UTF8 strings.
  1652. Never forget that the C<SVf_UTF8> flag is separate to the PV value; you
  1653. need be sure you don't accidentally knock it off while you're
  1654. manipulating SVs. More specifically, you cannot expect to do this:
  1655. SV *sv;
  1656. SV *nsv;
  1657. STRLEN len;
  1658. char *p;
  1659. p = SvPV(sv, len);
  1660. frobnicate(p);
  1661. nsv = newSVpvn(p, len);
  1662. The C<char*> string does not tell you the whole story, and you can't
  1663. copy or reconstruct an SV just by copying the string value. Check if the
  1664. old SV has the UTF8 flag set, and act accordingly:
  1665. p = SvPV(sv, len);
  1666. frobnicate(p);
  1667. nsv = newSVpvn(p, len);
  1668. if (SvUTF8(sv))
  1669. SvUTF8_on(nsv);
  1670. In fact, your C<frobnicate> function should be made aware of whether or
  1671. not it's dealing with UTF8 data, so that it can handle the string
  1672. appropriately.
  1673. =head2 How do I convert a string to UTF8?
  1674. If you're mixing UTF8 and non-UTF8 strings, you might find it necessary
  1675. to upgrade one of the strings to UTF8. If you've got an SV, the easiest
  1676. way to do this is:
  1677. sv_utf8_upgrade(sv);
  1678. However, you must not do this, for example:
  1679. if (!SvUTF8(left))
  1680. sv_utf8_upgrade(left);
  1681. If you do this in a binary operator, you will actually change one of the
  1682. strings that came into the operator, and, while it shouldn't be noticeable
  1683. by the end user, it can cause problems.
  1684. Instead, C<bytes_to_utf8> will give you a UTF8-encoded B<copy> of its
  1685. string argument. This is useful for having the data available for
  1686. comparisons and so on, without harming the original SV. There's also
  1687. C<utf8_to_bytes> to go the other way, but naturally, this will fail if
  1688. the string contains any characters above 255 that can't be represented
  1689. in a single byte.
  1690. =head2 Is there anything else I need to know?
  1691. Not really. Just remember these things:
  1692. =over 3
  1693. =item *
  1694. There's no way to tell if a string is UTF8 or not. You can tell if an SV
  1695. is UTF8 by looking at is C<SvUTF8> flag. Don't forget to set the flag if
  1696. something should be UTF8. Treat the flag as part of the PV, even though
  1697. it's not - if you pass on the PV to somewhere, pass on the flag too.
  1698. =item *
  1699. If a string is UTF8, B<always> use C<utf8_to_uv> to get at the value,
  1700. unless C<!(*s & 0x80)> in which case you can use C<*s>.
  1701. =item *
  1702. When writing to a UTF8 string, B<always> use C<uv_to_utf8>, unless
  1703. C<uv < 0x80> in which case you can use C<*s = uv>.
  1704. =item *
  1705. Mixing UTF8 and non-UTF8 strings is tricky. Use C<bytes_to_utf8> to get
  1706. a new string which is UTF8 encoded. There are tricks you can use to
  1707. delay deciding whether you need to use a UTF8 string until you get to a
  1708. high character - C<HALF_UPGRADE> is one of those.
  1709. =back
  1710. =head1 AUTHORS
  1711. Until May 1997, this document was maintained by Jeff Okamoto
  1712. <[email protected]>. It is now maintained as part of Perl itself
  1713. by the Perl 5 Porters <[email protected]>.
  1714. With lots of help and suggestions from Dean Roehrich, Malcolm Beattie,
  1715. Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil
  1716. Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer,
  1717. Stephen McCamant, and Gurusamy Sarathy.
  1718. API Listing originally by Dean Roehrich <[email protected]>.
  1719. Modifications to autogenerate the API listing (L<perlapi>) by Benjamin
  1720. Stuhl.
  1721. =head1 SEE ALSO
  1722. perlapi(1), perlintern(1), perlxs(1), perlembed(1)