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.

1722 lines
65 KiB

  1. =head1 NAME
  2. perlhack - How to hack at the Perl internals
  3. =head1 DESCRIPTION
  4. This document attempts to explain how Perl development takes place,
  5. and ends with some suggestions for people wanting to become bona fide
  6. porters.
  7. The perl5-porters mailing list is where the Perl standard distribution
  8. is maintained and developed. The list can get anywhere from 10 to 150
  9. messages a day, depending on the heatedness of the debate. Most days
  10. there are two or three patches, extensions, features, or bugs being
  11. discussed at a time.
  12. A searchable archive of the list is at:
  13. http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/
  14. The list is also archived under the usenet group name
  15. C<perl.porters-gw> at:
  16. http://www.deja.com/
  17. List subscribers (the porters themselves) come in several flavours.
  18. Some are quiet curious lurkers, who rarely pitch in and instead watch
  19. the ongoing development to ensure they're forewarned of new changes or
  20. features in Perl. Some are representatives of vendors, who are there
  21. to make sure that Perl continues to compile and work on their
  22. platforms. Some patch any reported bug that they know how to fix,
  23. some are actively patching their pet area (threads, Win32, the regexp
  24. engine), while others seem to do nothing but complain. In other
  25. words, it's your usual mix of technical people.
  26. Over this group of porters presides Larry Wall. He has the final word
  27. in what does and does not change in the Perl language. Various
  28. releases of Perl are shepherded by a ``pumpking'', a porter
  29. responsible for gathering patches, deciding on a patch-by-patch
  30. feature-by-feature basis what will and will not go into the release.
  31. For instance, Gurusamy Sarathy is the pumpking for the 5.6 release of
  32. Perl.
  33. In addition, various people are pumpkings for different things. For
  34. instance, Andy Dougherty and Jarkko Hietaniemi share the I<Configure>
  35. pumpkin, and Tom Christiansen is the documentation pumpking.
  36. Larry sees Perl development along the lines of the US government:
  37. there's the Legislature (the porters), the Executive branch (the
  38. pumpkings), and the Supreme Court (Larry). The legislature can
  39. discuss and submit patches to the executive branch all they like, but
  40. the executive branch is free to veto them. Rarely, the Supreme Court
  41. will side with the executive branch over the legislature, or the
  42. legislature over the executive branch. Mostly, however, the
  43. legislature and the executive branch are supposed to get along and
  44. work out their differences without impeachment or court cases.
  45. You might sometimes see reference to Rule 1 and Rule 2. Larry's power
  46. as Supreme Court is expressed in The Rules:
  47. =over 4
  48. =item 1
  49. Larry is always by definition right about how Perl should behave.
  50. This means he has final veto power on the core functionality.
  51. =item 2
  52. Larry is allowed to change his mind about any matter at a later date,
  53. regardless of whether he previously invoked Rule 1.
  54. =back
  55. Got that? Larry is always right, even when he was wrong. It's rare
  56. to see either Rule exercised, but they are often alluded to.
  57. New features and extensions to the language are contentious, because
  58. the criteria used by the pumpkings, Larry, and other porters to decide
  59. which features should be implemented and incorporated are not codified
  60. in a few small design goals as with some other languages. Instead,
  61. the heuristics are flexible and often difficult to fathom. Here is
  62. one person's list, roughly in decreasing order of importance, of
  63. heuristics that new features have to be weighed against:
  64. =over 4
  65. =item Does concept match the general goals of Perl?
  66. These haven't been written anywhere in stone, but one approximation
  67. is:
  68. 1. Keep it fast, simple, and useful.
  69. 2. Keep features/concepts as orthogonal as possible.
  70. 3. No arbitrary limits (platforms, data sizes, cultures).
  71. 4. Keep it open and exciting to use/patch/advocate Perl everywhere.
  72. 5. Either assimilate new technologies, or build bridges to them.
  73. =item Where is the implementation?
  74. All the talk in the world is useless without an implementation. In
  75. almost every case, the person or people who argue for a new feature
  76. will be expected to be the ones who implement it. Porters capable
  77. of coding new features have their own agendas, and are not available
  78. to implement your (possibly good) idea.
  79. =item Backwards compatibility
  80. It's a cardinal sin to break existing Perl programs. New warnings are
  81. contentious--some say that a program that emits warnings is not
  82. broken, while others say it is. Adding keywords has the potential to
  83. break programs, changing the meaning of existing token sequences or
  84. functions might break programs.
  85. =item Could it be a module instead?
  86. Perl 5 has extension mechanisms, modules and XS, specifically to avoid
  87. the need to keep changing the Perl interpreter. You can write modules
  88. that export functions, you can give those functions prototypes so they
  89. can be called like built-in functions, you can even write XS code to
  90. mess with the runtime data structures of the Perl interpreter if you
  91. want to implement really complicated things. If it can be done in a
  92. module instead of in the core, it's highly unlikely to be added.
  93. =item Is the feature generic enough?
  94. Is this something that only the submitter wants added to the language,
  95. or would it be broadly useful? Sometimes, instead of adding a feature
  96. with a tight focus, the porters might decide to wait until someone
  97. implements the more generalized feature. For instance, instead of
  98. implementing a ``delayed evaluation'' feature, the porters are waiting
  99. for a macro system that would permit delayed evaluation and much more.
  100. =item Does it potentially introduce new bugs?
  101. Radical rewrites of large chunks of the Perl interpreter have the
  102. potential to introduce new bugs. The smaller and more localized the
  103. change, the better.
  104. =item Does it preclude other desirable features?
  105. A patch is likely to be rejected if it closes off future avenues of
  106. development. For instance, a patch that placed a true and final
  107. interpretation on prototypes is likely to be rejected because there
  108. are still options for the future of prototypes that haven't been
  109. addressed.
  110. =item Is the implementation robust?
  111. Good patches (tight code, complete, correct) stand more chance of
  112. going in. Sloppy or incorrect patches might be placed on the back
  113. burner until the pumpking has time to fix, or might be discarded
  114. altogether without further notice.
  115. =item Is the implementation generic enough to be portable?
  116. The worst patches make use of a system-specific features. It's highly
  117. unlikely that nonportable additions to the Perl language will be
  118. accepted.
  119. =item Is there enough documentation?
  120. Patches without documentation are probably ill-thought out or
  121. incomplete. Nothing can be added without documentation, so submitting
  122. a patch for the appropriate manpages as well as the source code is
  123. always a good idea. If appropriate, patches should add to the test
  124. suite as well.
  125. =item Is there another way to do it?
  126. Larry said ``Although the Perl Slogan is I<There's More Than One Way
  127. to Do It>, I hesitate to make 10 ways to do something''. This is a
  128. tricky heuristic to navigate, though--one man's essential addition is
  129. another man's pointless cruft.
  130. =item Does it create too much work?
  131. Work for the pumpking, work for Perl programmers, work for module
  132. authors, ... Perl is supposed to be easy.
  133. =item Patches speak louder than words
  134. Working code is always preferred to pie-in-the-sky ideas. A patch to
  135. add a feature stands a much higher chance of making it to the language
  136. than does a random feature request, no matter how fervently argued the
  137. request might be. This ties into ``Will it be useful?'', as the fact
  138. that someone took the time to make the patch demonstrates a strong
  139. desire for the feature.
  140. =back
  141. If you're on the list, you might hear the word ``core'' bandied
  142. around. It refers to the standard distribution. ``Hacking on the
  143. core'' means you're changing the C source code to the Perl
  144. interpreter. ``A core module'' is one that ships with Perl.
  145. =head2 Keeping in sync
  146. The source code to the Perl interpreter, in its different versions, is
  147. kept in a repository managed by a revision control system (which is
  148. currently the Perforce program, see http://perforce.com/). The
  149. pumpkings and a few others have access to the repository to check in
  150. changes. Periodically the pumpking for the development version of Perl
  151. will release a new version, so the rest of the porters can see what's
  152. changed. The current state of the main trunk of repository, and patches
  153. that describe the individual changes that have happened since the last
  154. public release are available at this location:
  155. ftp://ftp.linux.activestate.com/pub/staff/gsar/APC/
  156. If you are a member of the perl5-porters mailing list, it is a good
  157. thing to keep in touch with the most recent changes. If not only to
  158. verify if what you would have posted as a bug report isn't already
  159. solved in the most recent available perl development branch, also
  160. known as perl-current, bleading edge perl, bleedperl or bleadperl.
  161. Needless to say, the source code in perl-current is usually in a perpetual
  162. state of evolution. You should expect it to be very buggy. Do B<not> use
  163. it for any purpose other than testing and development.
  164. Keeping in sync with the most recent branch can be done in several ways,
  165. but the most convenient and reliable way is using B<rsync>, available at
  166. ftp://rsync.samba.org/pub/rsync/ . (You can also get the most recent
  167. branch by FTP.)
  168. If you choose to keep in sync using rsync, there are two approaches
  169. to doing so:
  170. =over 4
  171. =item rsync'ing the source tree
  172. Presuming you are in the directory where your perl source resides
  173. and you have rsync installed and available, you can `upgrade' to
  174. the bleadperl using:
  175. # rsync -avz rsync://ftp.linux.activestate.com/perl-current/ .
  176. This takes care of updating every single item in the source tree to
  177. the latest applied patch level, creating files that are new (to your
  178. distribution) and setting date/time stamps of existing files to
  179. reflect the bleadperl status.
  180. You can than check what patch was the latest that was applied by
  181. looking in the file B<.patch>, which will show the number of the
  182. latest patch.
  183. If you have more than one machine to keep in sync, and not all of
  184. them have access to the WAN (so you are not able to rsync all the
  185. source trees to the real source), there are some ways to get around
  186. this problem.
  187. =over 4
  188. =item Using rsync over the LAN
  189. Set up a local rsync server which makes the rsynced source tree
  190. available to the LAN and sync the other machines against this
  191. directory.
  192. From http://rsync.samba.org/README.html:
  193. "Rsync uses rsh or ssh for communication. It does not need to be
  194. setuid and requires no special privileges for installation. It
  195. does not require a inetd entry or a deamon. You must, however,
  196. have a working rsh or ssh system. Using ssh is recommended for
  197. its security features."
  198. =item Using pushing over the NFS
  199. Having the other systems mounted over the NFS, you can take an
  200. active pushing approach by checking the just updated tree against
  201. the other not-yet synced trees. An example would be
  202. #!/usr/bin/perl -w
  203. use strict;
  204. use File::Copy;
  205. my %MF = map {
  206. m/(\S+)/;
  207. $1 => [ (stat $1)[2, 7, 9] ]; # mode, size, mtime
  208. } `cat MANIFEST`;
  209. my %remote = map { $_ => "/$_/pro/3gl/CPAN/perl-5.7.1" } qw(host1 host2);
  210. foreach my $host (keys %remote) {
  211. unless (-d $remote{$host}) {
  212. print STDERR "Cannot Xsync for host $host\n";
  213. next;
  214. }
  215. foreach my $file (keys %MF) {
  216. my $rfile = "$remote{$host}/$file";
  217. my ($mode, $size, $mtime) = (stat $rfile)[2, 7, 9];
  218. defined $size or ($mode, $size, $mtime) = (0, 0, 0);
  219. $size == $MF{$file}[1] && $mtime == $MF{$file}[2] and next;
  220. printf "%4s %-34s %8d %9d %8d %9d\n",
  221. $host, $file, $MF{$file}[1], $MF{$file}[2], $size, $mtime;
  222. unlink $rfile;
  223. copy ($file, $rfile);
  224. utime time, $MF{$file}[2], $rfile;
  225. chmod $MF{$file}[0], $rfile;
  226. }
  227. }
  228. though this is not perfect. It could be improved with checking
  229. file checksums before updating. Not all NFS systems support
  230. reliable utime support (when used over the NFS).
  231. =back
  232. =item rsync'ing the patches
  233. The source tree is maintained by the pumpking who applies patches to
  234. the files in the tree. These patches are either created by the
  235. pumpking himself using C<diff -c> after updating the file manually or
  236. by applying patches sent in by posters on the perl5-porters list.
  237. These patches are also saved and rsync'able, so you can apply them
  238. yourself to the source files.
  239. Presuming you are in a directory where your patches reside, you can
  240. get them in sync with
  241. # rsync -avz rsync://ftp.linux.activestate.com/perl-current-diffs/ .
  242. This makes sure the latest available patch is downloaded to your
  243. patch directory.
  244. It's then up to you to apply these patches, using something like
  245. # last=`ls -rt1 *.gz | tail -1`
  246. # rsync -avz rsync://ftp.linux.activestate.com/perl-current-diffs/ .
  247. # find . -name '*.gz' -newer $last -exec gzcat {} \; >blead.patch
  248. # cd ../perl-current
  249. # patch -p1 -N <../perl-current-diffs/blead.patch
  250. or, since this is only a hint towards how it works, use CPAN-patchaperl
  251. from Andreas K�nig to have better control over the patching process.
  252. =back
  253. =head2 Why rsync the source tree
  254. =over 4
  255. =item It's easier
  256. Since you don't have to apply the patches yourself, you are sure all
  257. files in the source tree are in the right state.
  258. =item It's more recent
  259. According to Gurusamy Sarathy:
  260. "... The rsync mirror is automatic and syncs with the repository
  261. every five minutes.
  262. "Updating the patch area still requires manual intervention
  263. (with all the goofiness that implies, which you've noted) and
  264. is typically on a daily cycle. Making this process automatic
  265. is on my tuit list, but don't ask me when."
  266. =item It's more reliable
  267. Well, since the patches are updated by hand, I don't have to say any
  268. more ... (see Sarathy's remark).
  269. =back
  270. =head2 Why rsync the patches
  271. =over 4
  272. =item It's easier
  273. If you have more than one machine that you want to keep in track with
  274. bleadperl, it's easier to rsync the patches only once and then apply
  275. them to all the source trees on the different machines.
  276. In case you try to keep in pace on 5 different machines, for which
  277. only one of them has access to the WAN, rsync'ing all the source
  278. trees should than be done 5 times over the NFS. Having
  279. rsync'ed the patches only once, I can apply them to all the source
  280. trees automatically. Need you say more ;-)
  281. =item It's a good reference
  282. If you do not only like to have the most recent development branch,
  283. but also like to B<fix> bugs, or extend features, you want to dive
  284. into the sources. If you are a seasoned perl core diver, you don't
  285. need no manuals, tips, roadmaps, perlguts.pod or other aids to find
  286. your way around. But if you are a starter, the patches may help you
  287. in finding where you should start and how to change the bits that
  288. bug you.
  289. The file B<Changes> is updated on occasions the pumpking sees as his
  290. own little sync points. On those occasions, he releases a tar-ball of
  291. the current source tree (i.e. [email protected]), which will be an
  292. excellent point to start with when choosing to use the 'rsync the
  293. patches' scheme. Starting with perl@7582, which means a set of source
  294. files on which the latest applied patch is number 7582, you apply all
  295. succeeding patches available from then on (7583, 7584, ...).
  296. You can use the patches later as a kind of search archive.
  297. =over 4
  298. =item Finding a start point
  299. If you want to fix/change the behaviour of function/feature Foo, just
  300. scan the patches for patches that mention Foo either in the subject,
  301. the comments, or the body of the fix. A good chance the patch shows
  302. you the files that are affected by that patch which are very likely
  303. to be the starting point of your journey into the guts of perl.
  304. =item Finding how to fix a bug
  305. If you've found I<where> the function/feature Foo misbehaves, but you
  306. don't know how to fix it (but you do know the change you want to
  307. make), you can, again, peruse the patches for similar changes and
  308. look how others apply the fix.
  309. =item Finding the source of misbehaviour
  310. When you keep in sync with bleadperl, the pumpking would love to
  311. I<see> that the community efforts realy work. So after each of his
  312. sync points, you are to 'make test' to check if everything is still
  313. in working order. If it is, you do 'make ok', which will send an OK
  314. report to [email protected]. (If you do not have access to a mailer
  315. from the system you just finished successfully 'make test', you can
  316. do 'make okfile', which creates the file C<perl.ok>, which you can
  317. than take to your favourite mailer and mail yourself).
  318. But of course, as always, things will not allways lead to a success
  319. path, and one or more test do not pass the 'make test'. Before
  320. sending in a bug report (using 'make nok' or 'make nokfile'), check
  321. the mailing list if someone else has reported the bug already and if
  322. so, confirm it by replying to that message. If not, you might want to
  323. trace the source of that misbehaviour B<before> sending in the bug,
  324. which will help all the other porters in finding the solution.
  325. Here the saved patches come in very handy. You can check the list of
  326. patches to see which patch changed what file and what change caused
  327. the misbehaviour. If you note that in the bug report, it saves the
  328. one trying to solve it, looking for that point.
  329. =back
  330. If searching the patches is too bothersome, you might consider using
  331. perl's bugtron to find more information about discussions and
  332. ramblings on posted bugs.
  333. =back
  334. If you want to get the best of both worlds, rsync both the source
  335. tree for convenience, reliability and ease and rsync the patches
  336. for reference.
  337. =head2 Submitting patches
  338. Always submit patches to I<[email protected]>. This lets other
  339. porters review your patch, which catches a surprising number of errors
  340. in patches. Either use the diff program (available in source code
  341. form from I<ftp://ftp.gnu.org/pub/gnu/>), or use Johan Vromans'
  342. I<makepatch> (available from I<CPAN/authors/id/JV/>). Unified diffs
  343. are preferred, but context diffs are accepted. Do not send RCS-style
  344. diffs or diffs without context lines. More information is given in
  345. the I<Porting/patching.pod> file in the Perl source distribution.
  346. Please patch against the latest B<development> version (e.g., if
  347. you're fixing a bug in the 5.005 track, patch against the latest
  348. 5.005_5x version). Only patches that survive the heat of the
  349. development branch get applied to maintenance versions.
  350. Your patch should update the documentation and test suite.
  351. To report a bug in Perl, use the program I<perlbug> which comes with
  352. Perl (if you can't get Perl to work, send mail to the address
  353. I<[email protected]> or I<[email protected]>). Reporting bugs through
  354. I<perlbug> feeds into the automated bug-tracking system, access to
  355. which is provided through the web at I<http://bugs.perl.org/>. It
  356. often pays to check the archives of the perl5-porters mailing list to
  357. see whether the bug you're reporting has been reported before, and if
  358. so whether it was considered a bug. See above for the location of
  359. the searchable archives.
  360. The CPAN testers (I<http://testers.cpan.org/>) are a group of
  361. volunteers who test CPAN modules on a variety of platforms. Perl Labs
  362. (I<http://labs.perl.org/>) automatically tests Perl source releases on
  363. platforms and gives feedback to the CPAN testers mailing list. Both
  364. efforts welcome volunteers.
  365. It's a good idea to read and lurk for a while before chipping in.
  366. That way you'll get to see the dynamic of the conversations, learn the
  367. personalities of the players, and hopefully be better prepared to make
  368. a useful contribution when do you speak up.
  369. If after all this you still think you want to join the perl5-porters
  370. mailing list, send mail to I<[email protected]>. To
  371. unsubscribe, send mail to I<[email protected]>.
  372. To hack on the Perl guts, you'll need to read the following things:
  373. =over 3
  374. =item L<perlguts>
  375. This is of paramount importance, since it's the documentation of what
  376. goes where in the Perl source. Read it over a couple of times and it
  377. might start to make sense - don't worry if it doesn't yet, because the
  378. best way to study it is to read it in conjunction with poking at Perl
  379. source, and we'll do that later on.
  380. You might also want to look at Gisle Aas's illustrated perlguts -
  381. there's no guarantee that this will be absolutely up-to-date with the
  382. latest documentation in the Perl core, but the fundamentals will be
  383. right. (http://gisle.aas.no/perl/illguts/)
  384. =item L<perlxstut> and L<perlxs>
  385. A working knowledge of XSUB programming is incredibly useful for core
  386. hacking; XSUBs use techniques drawn from the PP code, the portion of the
  387. guts that actually executes a Perl program. It's a lot gentler to learn
  388. those techniques from simple examples and explanation than from the core
  389. itself.
  390. =item L<perlapi>
  391. The documentation for the Perl API explains what some of the internal
  392. functions do, as well as the many macros used in the source.
  393. =item F<Porting/pumpkin.pod>
  394. This is a collection of words of wisdom for a Perl porter; some of it is
  395. only useful to the pumpkin holder, but most of it applies to anyone
  396. wanting to go about Perl development.
  397. =item The perl5-porters FAQ
  398. This is posted to perl5-porters at the beginning on every month, and
  399. should be available from http://perlhacker.org/p5p-faq; alternatively,
  400. you can get the FAQ emailed to you by sending mail to
  401. C<[email protected]>. It contains hints on reading
  402. perl5-porters, information on how perl5-porters works and how Perl
  403. development in general works.
  404. =back
  405. =head2 Finding Your Way Around
  406. Perl maintenance can be split into a number of areas, and certain people
  407. (pumpkins) will have responsibility for each area. These areas sometimes
  408. correspond to files or directories in the source kit. Among the areas are:
  409. =over 3
  410. =item Core modules
  411. Modules shipped as part of the Perl core live in the F<lib/> and F<ext/>
  412. subdirectories: F<lib/> is for the pure-Perl modules, and F<ext/>
  413. contains the core XS modules.
  414. =item Documentation
  415. Documentation maintenance includes looking after everything in the
  416. F<pod/> directory, (as well as contributing new documentation) and
  417. the documentation to the modules in core.
  418. =item Configure
  419. The configure process is the way we make Perl portable across the
  420. myriad of operating systems it supports. Responsibility for the
  421. configure, build and installation process, as well as the overall
  422. portability of the core code rests with the configure pumpkin - others
  423. help out with individual operating systems.
  424. The files involved are the operating system directories, (F<win32/>,
  425. F<os2/>, F<vms/> and so on) the shell scripts which generate F<config.h>
  426. and F<Makefile>, as well as the metaconfig files which generate
  427. F<Configure>. (metaconfig isn't included in the core distribution.)
  428. =item Interpreter
  429. And of course, there's the core of the Perl interpreter itself. Let's
  430. have a look at that in a little more detail.
  431. =back
  432. Before we leave looking at the layout, though, don't forget that
  433. F<MANIFEST> contains not only the file names in the Perl distribution,
  434. but short descriptions of what's in them, too. For an overview of the
  435. important files, try this:
  436. perl -lne 'print if /^[^\/]+\.[ch]\s+/' MANIFEST
  437. =head2 Elements of the interpreter
  438. The work of the interpreter has two main stages: compiling the code
  439. into the internal representation, or bytecode, and then executing it.
  440. L<perlguts/Compiled code> explains exactly how the compilation stage
  441. happens.
  442. Here is a short breakdown of perl's operation:
  443. =over 3
  444. =item Startup
  445. The action begins in F<perlmain.c>. (or F<miniperlmain.c> for miniperl)
  446. This is very high-level code, enough to fit on a single screen, and it
  447. resembles the code found in L<perlembed>; most of the real action takes
  448. place in F<perl.c>
  449. First, F<perlmain.c> allocates some memory and constructs a Perl
  450. interpreter:
  451. 1 PERL_SYS_INIT3(&argc,&argv,&env);
  452. 2
  453. 3 if (!PL_do_undump) {
  454. 4 my_perl = perl_alloc();
  455. 5 if (!my_perl)
  456. 6 exit(1);
  457. 7 perl_construct(my_perl);
  458. 8 PL_perl_destruct_level = 0;
  459. 9 }
  460. Line 1 is a macro, and its definition is dependent on your operating
  461. system. Line 3 references C<PL_do_undump>, a global variable - all
  462. global variables in Perl start with C<PL_>. This tells you whether the
  463. current running program was created with the C<-u> flag to perl and then
  464. F<undump>, which means it's going to be false in any sane context.
  465. Line 4 calls a function in F<perl.c> to allocate memory for a Perl
  466. interpreter. It's quite a simple function, and the guts of it looks like
  467. this:
  468. my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
  469. Here you see an example of Perl's system abstraction, which we'll see
  470. later: C<PerlMem_malloc> is either your system's C<malloc>, or Perl's
  471. own C<malloc> as defined in F<malloc.c> if you selected that option at
  472. configure time.
  473. Next, in line 7, we construct the interpreter; this sets up all the
  474. special variables that Perl needs, the stacks, and so on.
  475. Now we pass Perl the command line options, and tell it to go:
  476. exitstatus = perl_parse(my_perl, xs_init, argc, argv, (char **)NULL);
  477. if (!exitstatus) {
  478. exitstatus = perl_run(my_perl);
  479. }
  480. C<perl_parse> is actually a wrapper around C<S_parse_body>, as defined
  481. in F<perl.c>, which processes the command line options, sets up any
  482. statically linked XS modules, opens the program and calls C<yyparse> to
  483. parse it.
  484. =item Parsing
  485. The aim of this stage is to take the Perl source, and turn it into an op
  486. tree. We'll see what one of those looks like later. Strictly speaking,
  487. there's three things going on here.
  488. C<yyparse>, the parser, lives in F<perly.c>, although you're better off
  489. reading the original YACC input in F<perly.y>. (Yes, Virginia, there
  490. B<is> a YACC grammar for Perl!) The job of the parser is to take your
  491. code and `understand' it, splitting it into sentences, deciding which
  492. operands go with which operators and so on.
  493. The parser is nobly assisted by the lexer, which chunks up your input
  494. into tokens, and decides what type of thing each token is: a variable
  495. name, an operator, a bareword, a subroutine, a core function, and so on.
  496. The main point of entry to the lexer is C<yylex>, and that and its
  497. associated routines can be found in F<toke.c>. Perl isn't much like
  498. other computer languages; it's highly context sensitive at times, it can
  499. be tricky to work out what sort of token something is, or where a token
  500. ends. As such, there's a lot of interplay between the tokeniser and the
  501. parser, which can get pretty frightening if you're not used to it.
  502. As the parser understands a Perl program, it builds up a tree of
  503. operations for the interpreter to perform during execution. The routines
  504. which construct and link together the various operations are to be found
  505. in F<op.c>, and will be examined later.
  506. =item Optimization
  507. Now the parsing stage is complete, and the finished tree represents
  508. the operations that the Perl interpreter needs to perform to execute our
  509. program. Next, Perl does a dry run over the tree looking for
  510. optimisations: constant expressions such as C<3 + 4> will be computed
  511. now, and the optimizer will also see if any multiple operations can be
  512. replaced with a single one. For instance, to fetch the variable C<$foo>,
  513. instead of grabbing the glob C<*foo> and looking at the scalar
  514. component, the optimizer fiddles the op tree to use a function which
  515. directly looks up the scalar in question. The main optimizer is C<peep>
  516. in F<op.c>, and many ops have their own optimizing functions.
  517. =item Running
  518. Now we're finally ready to go: we have compiled Perl byte code, and all
  519. that's left to do is run it. The actual execution is done by the
  520. C<runops_standard> function in F<run.c>; more specifically, it's done by
  521. these three innocent looking lines:
  522. while ((PL_op = CALL_FPTR(PL_op->op_ppaddr)(aTHX))) {
  523. PERL_ASYNC_CHECK();
  524. }
  525. You may be more comfortable with the Perl version of that:
  526. PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op->{function}};
  527. Well, maybe not. Anyway, each op contains a function pointer, which
  528. stipulates the function which will actually carry out the operation.
  529. This function will return the next op in the sequence - this allows for
  530. things like C<if> which choose the next op dynamically at run time.
  531. The C<PERL_ASYNC_CHECK> makes sure that things like signals interrupt
  532. execution if required.
  533. The actual functions called are known as PP code, and they're spread
  534. between four files: F<pp_hot.c> contains the `hot' code, which is most
  535. often used and highly optimized, F<pp_sys.c> contains all the
  536. system-specific functions, F<pp_ctl.c> contains the functions which
  537. implement control structures (C<if>, C<while> and the like) and F<pp.c>
  538. contains everything else. These are, if you like, the C code for Perl's
  539. built-in functions and operators.
  540. =back
  541. =head2 Internal Variable Types
  542. You should by now have had a look at L<perlguts>, which tells you about
  543. Perl's internal variable types: SVs, HVs, AVs and the rest. If not, do
  544. that now.
  545. These variables are used not only to represent Perl-space variables, but
  546. also any constants in the code, as well as some structures completely
  547. internal to Perl. The symbol table, for instance, is an ordinary Perl
  548. hash. Your code is represented by an SV as it's read into the parser;
  549. any program files you call are opened via ordinary Perl filehandles, and
  550. so on.
  551. The core L<Devel::Peek|Devel::Peek> module lets us examine SVs from a
  552. Perl program. Let's see, for instance, how Perl treats the constant
  553. C<"hello">.
  554. % perl -MDevel::Peek -e 'Dump("hello")'
  555. 1 SV = PV(0xa041450) at 0xa04ecbc
  556. 2 REFCNT = 1
  557. 3 FLAGS = (POK,READONLY,pPOK)
  558. 4 PV = 0xa0484e0 "hello"\0
  559. 5 CUR = 5
  560. 6 LEN = 6
  561. Reading C<Devel::Peek> output takes a bit of practise, so let's go
  562. through it line by line.
  563. Line 1 tells us we're looking at an SV which lives at C<0xa04ecbc> in
  564. memory. SVs themselves are very simple structures, but they contain a
  565. pointer to a more complex structure. In this case, it's a PV, a
  566. structure which holds a string value, at location C<0xa041450>. Line 2
  567. is the reference count; there are no other references to this data, so
  568. it's 1.
  569. Line 3 are the flags for this SV - it's OK to use it as a PV, it's a
  570. read-only SV (because it's a constant) and the data is a PV internally.
  571. Next we've got the contents of the string, starting at location
  572. C<0xa0484e0>.
  573. Line 5 gives us the current length of the string - note that this does
  574. B<not> include the null terminator. Line 6 is not the length of the
  575. string, but the length of the currently allocated buffer; as the string
  576. grows, Perl automatically extends the available storage via a routine
  577. called C<SvGROW>.
  578. You can get at any of these quantities from C very easily; just add
  579. C<Sv> to the name of the field shown in the snippet, and you've got a
  580. macro which will return the value: C<SvCUR(sv)> returns the current
  581. length of the string, C<SvREFCOUNT(sv)> returns the reference count,
  582. C<SvPV(sv, len)> returns the string itself with its length, and so on.
  583. More macros to manipulate these properties can be found in L<perlguts>.
  584. Let's take an example of manipulating a PV, from C<sv_catpvn>, in F<sv.c>
  585. 1 void
  586. 2 Perl_sv_catpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
  587. 3 {
  588. 4 STRLEN tlen;
  589. 5 char *junk;
  590. 6 junk = SvPV_force(sv, tlen);
  591. 7 SvGROW(sv, tlen + len + 1);
  592. 8 if (ptr == junk)
  593. 9 ptr = SvPVX(sv);
  594. 10 Move(ptr,SvPVX(sv)+tlen,len,char);
  595. 11 SvCUR(sv) += len;
  596. 12 *SvEND(sv) = '\0';
  597. 13 (void)SvPOK_only_UTF8(sv); /* validate pointer */
  598. 14 SvTAINT(sv);
  599. 15 }
  600. This is a function which adds a string, C<ptr>, of length C<len> onto
  601. the end of the PV stored in C<sv>. The first thing we do in line 6 is
  602. make sure that the SV B<has> a valid PV, by calling the C<SvPV_force>
  603. macro to force a PV. As a side effect, C<tlen> gets set to the current
  604. value of the PV, and the PV itself is returned to C<junk>.
  605. In line 7, we make sure that the SV will have enough room to accommodate
  606. the old string, the new string and the null terminator. If C<LEN> isn't
  607. big enough, C<SvGROW> will reallocate space for us.
  608. Now, if C<junk> is the same as the string we're trying to add, we can
  609. grab the string directly from the SV; C<SvPVX> is the address of the PV
  610. in the SV.
  611. Line 10 does the actual catenation: the C<Move> macro moves a chunk of
  612. memory around: we move the string C<ptr> to the end of the PV - that's
  613. the start of the PV plus its current length. We're moving C<len> bytes
  614. of type C<char>. After doing so, we need to tell Perl we've extended the
  615. string, by altering C<CUR> to reflect the new length. C<SvEND> is a
  616. macro which gives us the end of the string, so that needs to be a
  617. C<"\0">.
  618. Line 13 manipulates the flags; since we've changed the PV, any IV or NV
  619. values will no longer be valid: if we have C<$a=10; $a.="6";> we don't
  620. want to use the old IV of 10. C<SvPOK_only_utf8> is a special UTF8-aware
  621. version of C<SvPOK_only>, a macro which turns off the IOK and NOK flags
  622. and turns on POK. The final C<SvTAINT> is a macro which launders tainted
  623. data if taint mode is turned on.
  624. AVs and HVs are more complicated, but SVs are by far the most common
  625. variable type being thrown around. Having seen something of how we
  626. manipulate these, let's go on and look at how the op tree is
  627. constructed.
  628. =head2 Op Trees
  629. First, what is the op tree, anyway? The op tree is the parsed
  630. representation of your program, as we saw in our section on parsing, and
  631. it's the sequence of operations that Perl goes through to execute your
  632. program, as we saw in L</Running>.
  633. An op is a fundamental operation that Perl can perform: all the built-in
  634. functions and operators are ops, and there are a series of ops which
  635. deal with concepts the interpreter needs internally - entering and
  636. leaving a block, ending a statement, fetching a variable, and so on.
  637. The op tree is connected in two ways: you can imagine that there are two
  638. "routes" through it, two orders in which you can traverse the tree.
  639. First, parse order reflects how the parser understood the code, and
  640. secondly, execution order tells perl what order to perform the
  641. operations in.
  642. The easiest way to examine the op tree is to stop Perl after it has
  643. finished parsing, and get it to dump out the tree. This is exactly what
  644. the compiler backends L<B::Terse|B::Terse> and L<B::Debug|B::Debug> do.
  645. Let's have a look at how Perl sees C<$a = $b + $c>:
  646. % perl -MO=Terse -e '$a=$b+$c'
  647. 1 LISTOP (0x8179888) leave
  648. 2 OP (0x81798b0) enter
  649. 3 COP (0x8179850) nextstate
  650. 4 BINOP (0x8179828) sassign
  651. 5 BINOP (0x8179800) add [1]
  652. 6 UNOP (0x81796e0) null [15]
  653. 7 SVOP (0x80fafe0) gvsv GV (0x80fa4cc) *b
  654. 8 UNOP (0x81797e0) null [15]
  655. 9 SVOP (0x8179700) gvsv GV (0x80efeb0) *c
  656. 10 UNOP (0x816b4f0) null [15]
  657. 11 SVOP (0x816dcf0) gvsv GV (0x80fa460) *a
  658. Let's start in the middle, at line 4. This is a BINOP, a binary
  659. operator, which is at location C<0x8179828>. The specific operator in
  660. question is C<sassign> - scalar assignment - and you can find the code
  661. which implements it in the function C<pp_sassign> in F<pp_hot.c>. As a
  662. binary operator, it has two children: the add operator, providing the
  663. result of C<$b+$c>, is uppermost on line 5, and the left hand side is on
  664. line 10.
  665. Line 10 is the null op: this does exactly nothing. What is that doing
  666. there? If you see the null op, it's a sign that something has been
  667. optimized away after parsing. As we mentioned in L</Optimization>,
  668. the optimization stage sometimes converts two operations into one, for
  669. example when fetching a scalar variable. When this happens, instead of
  670. rewriting the op tree and cleaning up the dangling pointers, it's easier
  671. just to replace the redundant operation with the null op. Originally,
  672. the tree would have looked like this:
  673. 10 SVOP (0x816b4f0) rv2sv [15]
  674. 11 SVOP (0x816dcf0) gv GV (0x80fa460) *a
  675. That is, fetch the C<a> entry from the main symbol table, and then look
  676. at the scalar component of it: C<gvsv> (C<pp_gvsv> into F<pp_hot.c>)
  677. happens to do both these things.
  678. The right hand side, starting at line 5 is similar to what we've just
  679. seen: we have the C<add> op (C<pp_add> also in F<pp_hot.c>) add together
  680. two C<gvsv>s.
  681. Now, what's this about?
  682. 1 LISTOP (0x8179888) leave
  683. 2 OP (0x81798b0) enter
  684. 3 COP (0x8179850) nextstate
  685. C<enter> and C<leave> are scoping ops, and their job is to perform any
  686. housekeeping every time you enter and leave a block: lexical variables
  687. are tidied up, unreferenced variables are destroyed, and so on. Every
  688. program will have those first three lines: C<leave> is a list, and its
  689. children are all the statements in the block. Statements are delimited
  690. by C<nextstate>, so a block is a collection of C<nextstate> ops, with
  691. the ops to be performed for each statement being the children of
  692. C<nextstate>. C<enter> is a single op which functions as a marker.
  693. That's how Perl parsed the program, from top to bottom:
  694. Program
  695. |
  696. Statement
  697. |
  698. =
  699. / \
  700. / \
  701. $a +
  702. / \
  703. $b $c
  704. However, it's impossible to B<perform> the operations in this order:
  705. you have to find the values of C<$b> and C<$c> before you add them
  706. together, for instance. So, the other thread that runs through the op
  707. tree is the execution order: each op has a field C<op_next> which points
  708. to the next op to be run, so following these pointers tells us how perl
  709. executes the code. We can traverse the tree in this order using
  710. the C<exec> option to C<B::Terse>:
  711. % perl -MO=Terse,exec -e '$a=$b+$c'
  712. 1 OP (0x8179928) enter
  713. 2 COP (0x81798c8) nextstate
  714. 3 SVOP (0x81796c8) gvsv GV (0x80fa4d4) *b
  715. 4 SVOP (0x8179798) gvsv GV (0x80efeb0) *c
  716. 5 BINOP (0x8179878) add [1]
  717. 6 SVOP (0x816dd38) gvsv GV (0x80fa468) *a
  718. 7 BINOP (0x81798a0) sassign
  719. 8 LISTOP (0x8179900) leave
  720. This probably makes more sense for a human: enter a block, start a
  721. statement. Get the values of C<$b> and C<$c>, and add them together.
  722. Find C<$a>, and assign one to the other. Then leave.
  723. The way Perl builds up these op trees in the parsing process can be
  724. unravelled by examining F<perly.y>, the YACC grammar. Let's take the
  725. piece we need to construct the tree for C<$a = $b + $c>
  726. 1 term : term ASSIGNOP term
  727. 2 { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
  728. 3 | term ADDOP term
  729. 4 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
  730. If you're not used to reading BNF grammars, this is how it works: You're
  731. fed certain things by the tokeniser, which generally end up in upper
  732. case. Here, C<ADDOP>, is provided when the tokeniser sees C<+> in your
  733. code. C<ASSIGNOP> is provided when C<=> is used for assigning. These are
  734. `terminal symbols', because you can't get any simpler than them.
  735. The grammar, lines one and three of the snippet above, tells you how to
  736. build up more complex forms. These complex forms, `non-terminal symbols'
  737. are generally placed in lower case. C<term> here is a non-terminal
  738. symbol, representing a single expression.
  739. The grammar gives you the following rule: you can make the thing on the
  740. left of the colon if you see all the things on the right in sequence.
  741. This is called a "reduction", and the aim of parsing is to completely
  742. reduce the input. There are several different ways you can perform a
  743. reduction, separated by vertical bars: so, C<term> followed by C<=>
  744. followed by C<term> makes a C<term>, and C<term> followed by C<+>
  745. followed by C<term> can also make a C<term>.
  746. So, if you see two terms with an C<=> or C<+>, between them, you can
  747. turn them into a single expression. When you do this, you execute the
  748. code in the block on the next line: if you see C<=>, you'll do the code
  749. in line 2. If you see C<+>, you'll do the code in line 4. It's this code
  750. which contributes to the op tree.
  751. | term ADDOP term
  752. { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
  753. What this does is creates a new binary op, and feeds it a number of
  754. variables. The variables refer to the tokens: C<$1> is the first token in
  755. the input, C<$2> the second, and so on - think regular expression
  756. backreferences. C<$$> is the op returned from this reduction. So, we
  757. call C<newBINOP> to create a new binary operator. The first parameter to
  758. C<newBINOP>, a function in F<op.c>, is the op type. It's an addition
  759. operator, so we want the type to be C<ADDOP>. We could specify this
  760. directly, but it's right there as the second token in the input, so we
  761. use C<$2>. The second parameter is the op's flags: 0 means `nothing
  762. special'. Then the things to add: the left and right hand side of our
  763. expression, in scalar context.
  764. =head2 Stacks
  765. When perl executes something like C<addop>, how does it pass on its
  766. results to the next op? The answer is, through the use of stacks. Perl
  767. has a number of stacks to store things it's currently working on, and
  768. we'll look at the three most important ones here.
  769. =over 3
  770. =item Argument stack
  771. Arguments are passed to PP code and returned from PP code using the
  772. argument stack, C<ST>. The typical way to handle arguments is to pop
  773. them off the stack, deal with them how you wish, and then push the result
  774. back onto the stack. This is how, for instance, the cosine operator
  775. works:
  776. NV value;
  777. value = POPn;
  778. value = Perl_cos(value);
  779. XPUSHn(value);
  780. We'll see a more tricky example of this when we consider Perl's macros
  781. below. C<POPn> gives you the NV (floating point value) of the top SV on
  782. the stack: the C<$x> in C<cos($x)>. Then we compute the cosine, and push
  783. the result back as an NV. The C<X> in C<XPUSHn> means that the stack
  784. should be extended if necessary - it can't be necessary here, because we
  785. know there's room for one more item on the stack, since we've just
  786. removed one! The C<XPUSH*> macros at least guarantee safety.
  787. Alternatively, you can fiddle with the stack directly: C<SP> gives you
  788. the first element in your portion of the stack, and C<TOP*> gives you
  789. the top SV/IV/NV/etc. on the stack. So, for instance, to do unary
  790. negation of an integer:
  791. SETi(-TOPi);
  792. Just set the integer value of the top stack entry to its negation.
  793. Argument stack manipulation in the core is exactly the same as it is in
  794. XSUBs - see L<perlxstut>, L<perlxs> and L<perlguts> for a longer
  795. description of the macros used in stack manipulation.
  796. =item Mark stack
  797. I say `your portion of the stack' above because PP code doesn't
  798. necessarily get the whole stack to itself: if your function calls
  799. another function, you'll only want to expose the arguments aimed for the
  800. called function, and not (necessarily) let it get at your own data. The
  801. way we do this is to have a `virtual' bottom-of-stack, exposed to each
  802. function. The mark stack keeps bookmarks to locations in the argument
  803. stack usable by each function. For instance, when dealing with a tied
  804. variable, (internally, something with `P' magic) Perl has to call
  805. methods for accesses to the tied variables. However, we need to separate
  806. the arguments exposed to the method to the argument exposed to the
  807. original function - the store or fetch or whatever it may be. Here's how
  808. the tied C<push> is implemented; see C<av_push> in F<av.c>:
  809. 1 PUSHMARK(SP);
  810. 2 EXTEND(SP,2);
  811. 3 PUSHs(SvTIED_obj((SV*)av, mg));
  812. 4 PUSHs(val);
  813. 5 PUTBACK;
  814. 6 ENTER;
  815. 7 call_method("PUSH", G_SCALAR|G_DISCARD);
  816. 8 LEAVE;
  817. 9 POPSTACK;
  818. The lines which concern the mark stack are the first, fifth and last
  819. lines: they save away, restore and remove the current position of the
  820. argument stack.
  821. Let's examine the whole implementation, for practice:
  822. 1 PUSHMARK(SP);
  823. Push the current state of the stack pointer onto the mark stack. This is
  824. so that when we've finished adding items to the argument stack, Perl
  825. knows how many things we've added recently.
  826. 2 EXTEND(SP,2);
  827. 3 PUSHs(SvTIED_obj((SV*)av, mg));
  828. 4 PUSHs(val);
  829. We're going to add two more items onto the argument stack: when you have
  830. a tied array, the C<PUSH> subroutine receives the object and the value
  831. to be pushed, and that's exactly what we have here - the tied object,
  832. retrieved with C<SvTIED_obj>, and the value, the SV C<val>.
  833. 5 PUTBACK;
  834. Next we tell Perl to make the change to the global stack pointer: C<dSP>
  835. only gave us a local copy, not a reference to the global.
  836. 6 ENTER;
  837. 7 call_method("PUSH", G_SCALAR|G_DISCARD);
  838. 8 LEAVE;
  839. C<ENTER> and C<LEAVE> localise a block of code - they make sure that all
  840. variables are tidied up, everything that has been localised gets
  841. its previous value returned, and so on. Think of them as the C<{> and
  842. C<}> of a Perl block.
  843. To actually do the magic method call, we have to call a subroutine in
  844. Perl space: C<call_method> takes care of that, and it's described in
  845. L<perlcall>. We call the C<PUSH> method in scalar context, and we're
  846. going to discard its return value.
  847. 9 POPSTACK;
  848. Finally, we remove the value we placed on the mark stack, since we
  849. don't need it any more.
  850. =item Save stack
  851. C doesn't have a concept of local scope, so perl provides one. We've
  852. seen that C<ENTER> and C<LEAVE> are used as scoping braces; the save
  853. stack implements the C equivalent of, for example:
  854. {
  855. local $foo = 42;
  856. ...
  857. }
  858. See L<perlguts/Localising Changes> for how to use the save stack.
  859. =back
  860. =head2 Millions of Macros
  861. One thing you'll notice about the Perl source is that it's full of
  862. macros. Some have called the pervasive use of macros the hardest thing
  863. to understand, others find it adds to clarity. Let's take an example,
  864. the code which implements the addition operator:
  865. 1 PP(pp_add)
  866. 2 {
  867. 3 dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
  868. 4 {
  869. 5 dPOPTOPnnrl_ul;
  870. 6 SETn( left + right );
  871. 7 RETURN;
  872. 8 }
  873. 9 }
  874. Every line here (apart from the braces, of course) contains a macro. The
  875. first line sets up the function declaration as Perl expects for PP code;
  876. line 3 sets up variable declarations for the argument stack and the
  877. target, the return value of the operation. Finally, it tries to see if
  878. the addition operation is overloaded; if so, the appropriate subroutine
  879. is called.
  880. Line 5 is another variable declaration - all variable declarations start
  881. with C<d> - which pops from the top of the argument stack two NVs (hence
  882. C<nn>) and puts them into the variables C<right> and C<left>, hence the
  883. C<rl>. These are the two operands to the addition operator. Next, we
  884. call C<SETn> to set the NV of the return value to the result of adding
  885. the two values. This done, we return - the C<RETURN> macro makes sure
  886. that our return value is properly handled, and we pass the next operator
  887. to run back to the main run loop.
  888. Most of these macros are explained in L<perlapi>, and some of the more
  889. important ones are explained in L<perlxs> as well. Pay special attention
  890. to L<perlguts/Background and PERL_IMPLICIT_CONTEXT> for information on
  891. the C<[pad]THX_?> macros.
  892. =head2 Poking at Perl
  893. To really poke around with Perl, you'll probably want to build Perl for
  894. debugging, like this:
  895. ./Configure -d -D optimize=-g
  896. make
  897. C<-g> is a flag to the C compiler to have it produce debugging
  898. information which will allow us to step through a running program.
  899. F<Configure> will also turn on the C<DEBUGGING> compilation symbol which
  900. enables all the internal debugging code in Perl. There are a whole bunch
  901. of things you can debug with this: L<perlrun> lists them all, and the
  902. best way to find out about them is to play about with them. The most
  903. useful options are probably
  904. l Context (loop) stack processing
  905. t Trace execution
  906. o Method and overloading resolution
  907. c String/numeric conversions
  908. Some of the functionality of the debugging code can be achieved using XS
  909. modules.
  910. -Dr => use re 'debug'
  911. -Dx => use O 'Debug'
  912. =head2 Using a source-level debugger
  913. If the debugging output of C<-D> doesn't help you, it's time to step
  914. through perl's execution with a source-level debugger.
  915. =over 3
  916. =item *
  917. We'll use C<gdb> for our examples here; the principles will apply to any
  918. debugger, but check the manual of the one you're using.
  919. =back
  920. To fire up the debugger, type
  921. gdb ./perl
  922. You'll want to do that in your Perl source tree so the debugger can read
  923. the source code. You should see the copyright message, followed by the
  924. prompt.
  925. (gdb)
  926. C<help> will get you into the documentation, but here are the most
  927. useful commands:
  928. =over 3
  929. =item run [args]
  930. Run the program with the given arguments.
  931. =item break function_name
  932. =item break source.c:xxx
  933. Tells the debugger that we'll want to pause execution when we reach
  934. either the named function (but see L<perlguts/Internal Functions>!) or the given
  935. line in the named source file.
  936. =item step
  937. Steps through the program a line at a time.
  938. =item next
  939. Steps through the program a line at a time, without descending into
  940. functions.
  941. =item continue
  942. Run until the next breakpoint.
  943. =item finish
  944. Run until the end of the current function, then stop again.
  945. =item 'enter'
  946. Just pressing Enter will do the most recent operation again - it's a
  947. blessing when stepping through miles of source code.
  948. =item print
  949. Execute the given C code and print its results. B<WARNING>: Perl makes
  950. heavy use of macros, and F<gdb> is not aware of macros. You'll have to
  951. substitute them yourself. So, for instance, you can't say
  952. print SvPV_nolen(sv)
  953. but you have to say
  954. print Perl_sv_2pv_nolen(sv)
  955. You may find it helpful to have a "macro dictionary", which you can
  956. produce by saying C<cpp -dM perl.c | sort>. Even then, F<cpp> won't
  957. recursively apply the macros for you.
  958. =back
  959. =head2 Dumping Perl Data Structures
  960. One way to get around this macro hell is to use the dumping functions in
  961. F<dump.c>; these work a little like an internal
  962. L<Devel::Peek|Devel::Peek>, but they also cover OPs and other structures
  963. that you can't get at from Perl. Let's take an example. We'll use the
  964. C<$a = $b + $c> we used before, but give it a bit of context:
  965. C<$b = "6XXXX"; $c = 2.3;>. Where's a good place to stop and poke around?
  966. What about C<pp_add>, the function we examined earlier to implement the
  967. C<+> operator:
  968. (gdb) break Perl_pp_add
  969. Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.
  970. Notice we use C<Perl_pp_add> and not C<pp_add> - see L<perlguts/Internal Functions>.
  971. With the breakpoint in place, we can run our program:
  972. (gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c'
  973. Lots of junk will go past as gdb reads in the relevant source files and
  974. libraries, and then:
  975. Breakpoint 1, Perl_pp_add () at pp_hot.c:309
  976. 309 dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
  977. (gdb) step
  978. 311 dPOPTOPnnrl_ul;
  979. (gdb)
  980. We looked at this bit of code before, and we said that C<dPOPTOPnnrl_ul>
  981. arranges for two C<NV>s to be placed into C<left> and C<right> - let's
  982. slightly expand it:
  983. #define dPOPTOPnnrl_ul NV right = POPn; \
  984. SV *leftsv = TOPs; \
  985. NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0
  986. C<POPn> takes the SV from the top of the stack and obtains its NV either
  987. directly (if C<SvNOK> is set) or by calling the C<sv_2nv> function.
  988. C<TOPs> takes the next SV from the top of the stack - yes, C<POPn> uses
  989. C<TOPs> - but doesn't remove it. We then use C<SvNV> to get the NV from
  990. C<leftsv> in the same way as before - yes, C<POPn> uses C<SvNV>.
  991. Since we don't have an NV for C<$b>, we'll have to use C<sv_2nv> to
  992. convert it. If we step again, we'll find ourselves there:
  993. Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
  994. 1669 if (!sv)
  995. (gdb)
  996. We can now use C<Perl_sv_dump> to investigate the SV:
  997. SV = PV(0xa057cc0) at 0xa0675d0
  998. REFCNT = 1
  999. FLAGS = (POK,pPOK)
  1000. PV = 0xa06a510 "6XXXX"\0
  1001. CUR = 5
  1002. LEN = 6
  1003. $1 = void
  1004. We know we're going to get C<6> from this, so let's finish the
  1005. subroutine:
  1006. (gdb) finish
  1007. Run till exit from #0 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
  1008. 0x462669 in Perl_pp_add () at pp_hot.c:311
  1009. 311 dPOPTOPnnrl_ul;
  1010. We can also dump out this op: the current op is always stored in
  1011. C<PL_op>, and we can dump it with C<Perl_op_dump>. This'll give us
  1012. similar output to L<B::Debug|B::Debug>.
  1013. {
  1014. 13 TYPE = add ===> 14
  1015. TARG = 1
  1016. FLAGS = (SCALAR,KIDS)
  1017. {
  1018. TYPE = null ===> (12)
  1019. (was rv2sv)
  1020. FLAGS = (SCALAR,KIDS)
  1021. {
  1022. 11 TYPE = gvsv ===> 12
  1023. FLAGS = (SCALAR)
  1024. GV = main::b
  1025. }
  1026. }
  1027. < finish this later >
  1028. =head2 Patching
  1029. All right, we've now had a look at how to navigate the Perl sources and
  1030. some things you'll need to know when fiddling with them. Let's now get
  1031. on and create a simple patch. Here's something Larry suggested: if a
  1032. C<U> is the first active format during a C<pack>, (for example,
  1033. C<pack "U3C8", @stuff>) then the resulting string should be treated as
  1034. UTF8 encoded.
  1035. How do we prepare to fix this up? First we locate the code in question -
  1036. the C<pack> happens at runtime, so it's going to be in one of the F<pp>
  1037. files. Sure enough, C<pp_pack> is in F<pp.c>. Since we're going to be
  1038. altering this file, let's copy it to F<pp.c~>.
  1039. Now let's look over C<pp_pack>: we take a pattern into C<pat>, and then
  1040. loop over the pattern, taking each format character in turn into
  1041. C<datum_type>. Then for each possible format character, we swallow up
  1042. the other arguments in the pattern (a field width, an asterisk, and so
  1043. on) and convert the next chunk input into the specified format, adding
  1044. it onto the output SV C<cat>.
  1045. How do we know if the C<U> is the first format in the C<pat>? Well, if
  1046. we have a pointer to the start of C<pat> then, if we see a C<U> we can
  1047. test whether we're still at the start of the string. So, here's where
  1048. C<pat> is set up:
  1049. STRLEN fromlen;
  1050. register char *pat = SvPVx(*++MARK, fromlen);
  1051. register char *patend = pat + fromlen;
  1052. register I32 len;
  1053. I32 datumtype;
  1054. SV *fromstr;
  1055. We'll have another string pointer in there:
  1056. STRLEN fromlen;
  1057. register char *pat = SvPVx(*++MARK, fromlen);
  1058. register char *patend = pat + fromlen;
  1059. + char *patcopy;
  1060. register I32 len;
  1061. I32 datumtype;
  1062. SV *fromstr;
  1063. And just before we start the loop, we'll set C<patcopy> to be the start
  1064. of C<pat>:
  1065. items = SP - MARK;
  1066. MARK++;
  1067. sv_setpvn(cat, "", 0);
  1068. + patcopy = pat;
  1069. while (pat < patend) {
  1070. Now if we see a C<U> which was at the start of the string, we turn on
  1071. the UTF8 flag for the output SV, C<cat>:
  1072. + if (datumtype == 'U' && pat==patcopy+1)
  1073. + SvUTF8_on(cat);
  1074. if (datumtype == '#') {
  1075. while (pat < patend && *pat != '\n')
  1076. pat++;
  1077. Remember that it has to be C<patcopy+1> because the first character of
  1078. the string is the C<U> which has been swallowed into C<datumtype!>
  1079. Oops, we forgot one thing: what if there are spaces at the start of the
  1080. pattern? C<pack(" U*", @stuff)> will have C<U> as the first active
  1081. character, even though it's not the first thing in the pattern. In this
  1082. case, we have to advance C<patcopy> along with C<pat> when we see spaces:
  1083. if (isSPACE(datumtype))
  1084. continue;
  1085. needs to become
  1086. if (isSPACE(datumtype)) {
  1087. patcopy++;
  1088. continue;
  1089. }
  1090. OK. That's the C part done. Now we must do two additional things before
  1091. this patch is ready to go: we've changed the behaviour of Perl, and so
  1092. we must document that change. We must also provide some more regression
  1093. tests to make sure our patch works and doesn't create a bug somewhere
  1094. else along the line.
  1095. The regression tests for each operator live in F<t/op/>, and so we make
  1096. a copy of F<t/op/pack.t> to F<t/op/pack.t~>. Now we can add our tests
  1097. to the end. First, we'll test that the C<U> does indeed create Unicode
  1098. strings:
  1099. print 'not ' unless "1.20.300.4000" eq sprintf "%vd", pack("U*",1,20,300,4000);
  1100. print "ok $test\n"; $test++;
  1101. Now we'll test that we got that space-at-the-beginning business right:
  1102. print 'not ' unless "1.20.300.4000" eq
  1103. sprintf "%vd", pack(" U*",1,20,300,4000);
  1104. print "ok $test\n"; $test++;
  1105. And finally we'll test that we don't make Unicode strings if C<U> is B<not>
  1106. the first active format:
  1107. print 'not ' unless v1.20.300.4000 ne
  1108. sprintf "%vd", pack("C0U*",1,20,300,4000);
  1109. print "ok $test\n"; $test++;
  1110. Mustn't forget to change the number of tests which appears at the top, or
  1111. else the automated tester will get confused:
  1112. -print "1..156\n";
  1113. +print "1..159\n";
  1114. We now compile up Perl, and run it through the test suite. Our new
  1115. tests pass, hooray!
  1116. Finally, the documentation. The job is never done until the paperwork is
  1117. over, so let's describe the change we've just made. The relevant place
  1118. is F<pod/perlfunc.pod>; again, we make a copy, and then we'll insert
  1119. this text in the description of C<pack>:
  1120. =item *
  1121. If the pattern begins with a C<U>, the resulting string will be treated
  1122. as Unicode-encoded. You can force UTF8 encoding on in a string with an
  1123. initial C<U0>, and the bytes that follow will be interpreted as Unicode
  1124. characters. If you don't want this to happen, you can begin your pattern
  1125. with C<C0> (or anything else) to force Perl not to UTF8 encode your
  1126. string, and then follow this with a C<U*> somewhere in your pattern.
  1127. All done. Now let's create the patch. F<Porting/patching.pod> tells us
  1128. that if we're making major changes, we should copy the entire directory
  1129. to somewhere safe before we begin fiddling, and then do
  1130. diff -ruN old new > patch
  1131. However, we know which files we've changed, and we can simply do this:
  1132. diff -u pp.c~ pp.c > patch
  1133. diff -u t/op/pack.t~ t/op/pack.t >> patch
  1134. diff -u pod/perlfunc.pod~ pod/perlfunc.pod >> patch
  1135. We end up with a patch looking a little like this:
  1136. --- pp.c~ Fri Jun 02 04:34:10 2000
  1137. +++ pp.c Fri Jun 16 11:37:25 2000
  1138. @@ -4375,6 +4375,7 @@
  1139. register I32 items;
  1140. STRLEN fromlen;
  1141. register char *pat = SvPVx(*++MARK, fromlen);
  1142. + char *patcopy;
  1143. register char *patend = pat + fromlen;
  1144. register I32 len;
  1145. I32 datumtype;
  1146. @@ -4405,6 +4406,7 @@
  1147. ...
  1148. And finally, we submit it, with our rationale, to perl5-porters. Job
  1149. done!
  1150. =head1 EXTERNAL TOOLS FOR DEBUGGING PERL
  1151. Sometimes it helps to use external tools while debugging and
  1152. testing Perl. This section tries to guide you through using
  1153. some common testing and debugging tools with Perl. This is
  1154. meant as a guide to interfacing these tools with Perl, not
  1155. as any kind of guide to the use of the tools themselves.
  1156. =head2 Rational Software's Purify
  1157. Purify is a commercial tool that is helpful in identifying
  1158. memory overruns, wild pointers, memory leaks and other such
  1159. badness. Perl must be compiled in a specific way for
  1160. optimal testing with Purify. Purify is available under
  1161. Windows NT, Solaris, HP-UX, SGI, and Siemens Unix.
  1162. The only currently known leaks happen when there are
  1163. compile-time errors within eval or require. (Fixing these
  1164. is non-trivial, unfortunately, but they must be fixed
  1165. eventually.)
  1166. =head2 Purify on Unix
  1167. On Unix, Purify creates a new Perl binary. To get the most
  1168. benefit out of Purify, you should create the perl to Purify
  1169. using:
  1170. sh Configure -Accflags=-DPURIFY -Doptimize='-g' \
  1171. -Uusemymalloc -Dusemultiplicity
  1172. where these arguments mean:
  1173. =over 4
  1174. =item -Accflags=-DPURIFY
  1175. Disables Perl's arena memory allocation functions, as well as
  1176. forcing use of memory allocation functions derived from the
  1177. system malloc.
  1178. =item -Doptimize='-g'
  1179. Adds debugging information so that you see the exact source
  1180. statements where the problem occurs. Without this flag, all
  1181. you will see is the source filename of where the error occurred.
  1182. =item -Uusemymalloc
  1183. Disable Perl's malloc so that Purify can more closely monitor
  1184. allocations and leaks. Using Perl's malloc will make Purify
  1185. report most leaks in the "potential" leaks category.
  1186. =item -Dusemultiplicity
  1187. Enabling the multiplicity option allows perl to clean up
  1188. thoroughly when the interpreter shuts down, which reduces the
  1189. number of bogus leak reports from Purify.
  1190. =back
  1191. Once you've compiled a perl suitable for Purify'ing, then you
  1192. can just:
  1193. make pureperl
  1194. which creates a binary named 'pureperl' that has been Purify'ed.
  1195. This binary is used in place of the standard 'perl' binary
  1196. when you want to debug Perl memory problems.
  1197. As an example, to show any memory leaks produced during the
  1198. standard Perl testset you would create and run the Purify'ed
  1199. perl as:
  1200. make pureperl
  1201. cd t
  1202. ../pureperl -I../lib harness
  1203. which would run Perl on test.pl and report any memory problems.
  1204. Purify outputs messages in "Viewer" windows by default. If
  1205. you don't have a windowing environment or if you simply
  1206. want the Purify output to unobtrusively go to a log file
  1207. instead of to the interactive window, use these following
  1208. options to output to the log file "perl.log":
  1209. setenv PURIFYOPTIONS "-chain-length=25 -windows=no \
  1210. -log-file=perl.log -append-logfile=yes"
  1211. If you plan to use the "Viewer" windows, then you only need this option:
  1212. setenv PURIFYOPTIONS "-chain-length=25"
  1213. =head2 Purify on NT
  1214. Purify on Windows NT instruments the Perl binary 'perl.exe'
  1215. on the fly. There are several options in the makefile you
  1216. should change to get the most use out of Purify:
  1217. =over 4
  1218. =item DEFINES
  1219. You should add -DPURIFY to the DEFINES line so the DEFINES
  1220. line looks something like:
  1221. DEFINES = -DWIN32 -D_CONSOLE -DNO_STRICT $(CRYPT_FLAG) -DPURIFY=1
  1222. to disable Perl's arena memory allocation functions, as
  1223. well as to force use of memory allocation functions derived
  1224. from the system malloc.
  1225. =item USE_MULTI = define
  1226. Enabling the multiplicity option allows perl to clean up
  1227. thoroughly when the interpreter shuts down, which reduces the
  1228. number of bogus leak reports from Purify.
  1229. =item #PERL_MALLOC = define
  1230. Disable Perl's malloc so that Purify can more closely monitor
  1231. allocations and leaks. Using Perl's malloc will make Purify
  1232. report most leaks in the "potential" leaks category.
  1233. =item CFG = Debug
  1234. Adds debugging information so that you see the exact source
  1235. statements where the problem occurs. Without this flag, all
  1236. you will see is the source filename of where the error occurred.
  1237. =back
  1238. As an example, to show any memory leaks produced during the
  1239. standard Perl testset you would create and run Purify as:
  1240. cd win32
  1241. make
  1242. cd ../t
  1243. purify ../perl -I../lib harness
  1244. which would instrument Perl in memory, run Perl on test.pl,
  1245. then finally report any memory problems.
  1246. =head2 CONCLUSION
  1247. We've had a brief look around the Perl source, an overview of the stages
  1248. F<perl> goes through when it's running your code, and how to use a
  1249. debugger to poke at the Perl guts. We took a very simple problem and
  1250. demonstrated how to solve it fully - with documentation, regression
  1251. tests, and finally a patch for submission to p5p. Finally, we talked
  1252. about how to use external tools to debug and test Perl.
  1253. I'd now suggest you read over those references again, and then, as soon
  1254. as possible, get your hands dirty. The best way to learn is by doing,
  1255. so:
  1256. =over 3
  1257. =item *
  1258. Subscribe to perl5-porters, follow the patches and try and understand
  1259. them; don't be afraid to ask if there's a portion you're not clear on -
  1260. who knows, you may unearth a bug in the patch...
  1261. =item *
  1262. Keep up to date with the bleeding edge Perl distributions and get
  1263. familiar with the changes. Try and get an idea of what areas people are
  1264. working on and the changes they're making.
  1265. =item *
  1266. Do read the README associated with your operating system, e.g. README.aix
  1267. on the IBM AIX OS. Don't hesitate to supply patches to that README if
  1268. you find anything missing or changed over a new OS release.
  1269. =item *
  1270. Find an area of Perl that seems interesting to you, and see if you can
  1271. work out how it works. Scan through the source, and step over it in the
  1272. debugger. Play, poke, investigate, fiddle! You'll probably get to
  1273. understand not just your chosen area but a much wider range of F<perl>'s
  1274. activity as well, and probably sooner than you'd think.
  1275. =back
  1276. =over 3
  1277. =item I<The Road goes ever on and on, down from the door where it began.>
  1278. =back
  1279. If you can do these things, you've started on the long road to Perl porting.
  1280. Thanks for wanting to help make Perl better - and happy hacking!
  1281. =head1 AUTHOR
  1282. This document was written by Nathan Torkington, and is maintained by
  1283. the perl5-porters mailing list.