1PERLHACK(1) Perl Programmers Reference Guide PERLHACK(1)
2
3
4
6 perlhack - How to hack at the Perl internals
7
9 This document attempts to explain how Perl development takes place, and
10 ends with some suggestions for people wanting to become bona fide
11 porters.
12
13 The perl5-porters mailing list is where the Perl standard distribution
14 is maintained and developed. The list can get anywhere from 10 to 150
15 messages a day, depending on the heatedness of the debate. Most days
16 there are two or three patches, extensions, features, or bugs being
17 discussed at a time.
18
19 A searchable archive of the list is at either:
20
21 http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/
22
23 or
24
25 http://archive.develooper.com/perl5-porters@perl.org/
26
27 List subscribers (the porters themselves) come in several flavours.
28 Some are quiet curious lurkers, who rarely pitch in and instead watch
29 the ongoing development to ensure they're forewarned of new changes or
30 features in Perl. Some are representatives of vendors, who are there
31 to make sure that Perl continues to compile and work on their
32 platforms. Some patch any reported bug that they know how to fix, some
33 are actively patching their pet area (threads, Win32, the regexp
34 engine), while others seem to do nothing but complain. In other words,
35 it's your usual mix of technical people.
36
37 Over this group of porters presides Larry Wall. He has the final word
38 in what does and does not change in the Perl language. Various
39 releases of Perl are shepherded by a "pumpking", a porter responsible
40 for gathering patches, deciding on a patch-by-patch, feature-by-feature
41 basis what will and will not go into the release. For instance,
42 Gurusamy Sarathy was the pumpking for the 5.6 release of Perl, and
43 Jarkko Hietaniemi was the pumpking for the 5.8 release, and Rafael
44 Garcia-Suarez holds the pumpking crown for the 5.10 release.
45
46 In addition, various people are pumpkings for different things. For
47 instance, Andy Dougherty and Jarkko Hietaniemi did a grand job as the
48 Configure pumpkin up till the 5.8 release. For the 5.10 release
49 H.Merijn Brand took over.
50
51 Larry sees Perl development along the lines of the US government:
52 there's the Legislature (the porters), the Executive branch (the
53 pumpkings), and the Supreme Court (Larry). The legislature can discuss
54 and submit patches to the executive branch all they like, but the
55 executive branch is free to veto them. Rarely, the Supreme Court will
56 side with the executive branch over the legislature, or the legislature
57 over the executive branch. Mostly, however, the legislature and the
58 executive branch are supposed to get along and work out their
59 differences without impeachment or court cases.
60
61 You might sometimes see reference to Rule 1 and Rule 2. Larry's power
62 as Supreme Court is expressed in The Rules:
63
64 1. Larry is always by definition right about how Perl should behave.
65 This means he has final veto power on the core functionality.
66
67 2. Larry is allowed to change his mind about any matter at a later
68 date, regardless of whether he previously invoked Rule 1.
69
70 Got that? Larry is always right, even when he was wrong. It's rare to
71 see either Rule exercised, but they are often alluded to.
72
73 New features and extensions to the language are contentious, because
74 the criteria used by the pumpkings, Larry, and other porters to decide
75 which features should be implemented and incorporated are not codified
76 in a few small design goals as with some other languages. Instead, the
77 heuristics are flexible and often difficult to fathom. Here is one
78 person's list, roughly in decreasing order of importance, of heuristics
79 that new features have to be weighed against:
80
81 Does concept match the general goals of Perl?
82 These haven't been written anywhere in stone, but one approximation
83 is:
84
85 1. Keep it fast, simple, and useful.
86 2. Keep features/concepts as orthogonal as possible.
87 3. No arbitrary limits (platforms, data sizes, cultures).
88 4. Keep it open and exciting to use/patch/advocate Perl everywhere.
89 5. Either assimilate new technologies, or build bridges to them.
90
91 Where is the implementation?
92 All the talk in the world is useless without an implementation. In
93 almost every case, the person or people who argue for a new feature
94 will be expected to be the ones who implement it. Porters capable
95 of coding new features have their own agendas, and are not
96 available to implement your (possibly good) idea.
97
98 Backwards compatibility
99 It's a cardinal sin to break existing Perl programs. New warnings
100 are contentious--some say that a program that emits warnings is not
101 broken, while others say it is. Adding keywords has the potential
102 to break programs, changing the meaning of existing token sequences
103 or functions might break programs.
104
105 Could it be a module instead?
106 Perl 5 has extension mechanisms, modules and XS, specifically to
107 avoid the need to keep changing the Perl interpreter. You can
108 write modules that export functions, you can give those functions
109 prototypes so they can be called like built-in functions, you can
110 even write XS code to mess with the runtime data structures of the
111 Perl interpreter if you want to implement really complicated
112 things. If it can be done in a module instead of in the core, it's
113 highly unlikely to be added.
114
115 Is the feature generic enough?
116 Is this something that only the submitter wants added to the
117 language, or would it be broadly useful? Sometimes, instead of
118 adding a feature with a tight focus, the porters might decide to
119 wait until someone implements the more generalized feature. For
120 instance, instead of implementing a "delayed evaluation" feature,
121 the porters are waiting for a macro system that would permit
122 delayed evaluation and much more.
123
124 Does it potentially introduce new bugs?
125 Radical rewrites of large chunks of the Perl interpreter have the
126 potential to introduce new bugs. The smaller and more localized
127 the change, the better.
128
129 Does it preclude other desirable features?
130 A patch is likely to be rejected if it closes off future avenues of
131 development. For instance, a patch that placed a true and final
132 interpretation on prototypes is likely to be rejected because there
133 are still options for the future of prototypes that haven't been
134 addressed.
135
136 Is the implementation robust?
137 Good patches (tight code, complete, correct) stand more chance of
138 going in. Sloppy or incorrect patches might be placed on the back
139 burner until the pumpking has time to fix, or might be discarded
140 altogether without further notice.
141
142 Is the implementation generic enough to be portable?
143 The worst patches make use of a system-specific features. It's
144 highly unlikely that non-portable additions to the Perl language
145 will be accepted.
146
147 Is the implementation tested?
148 Patches which change behaviour (fixing bugs or introducing new
149 features) must include regression tests to verify that everything
150 works as expected. Without tests provided by the original author,
151 how can anyone else changing perl in the future be sure that they
152 haven't unwittingly broken the behaviour the patch implements? And
153 without tests, how can the patch's author be confident that his/her
154 hard work put into the patch won't be accidentally thrown away by
155 someone in the future?
156
157 Is there enough documentation?
158 Patches without documentation are probably ill-thought out or
159 incomplete. Nothing can be added without documentation, so
160 submitting a patch for the appropriate manpages as well as the
161 source code is always a good idea.
162
163 Is there another way to do it?
164 Larry said "Although the Perl Slogan is There's More Than One Way
165 to Do It, I hesitate to make 10 ways to do something". This is a
166 tricky heuristic to navigate, though--one man's essential addition
167 is another man's pointless cruft.
168
169 Does it create too much work?
170 Work for the pumpking, work for Perl programmers, work for module
171 authors, ... Perl is supposed to be easy.
172
173 Patches speak louder than words
174 Working code is always preferred to pie-in-the-sky ideas. A patch
175 to add a feature stands a much higher chance of making it to the
176 language than does a random feature request, no matter how
177 fervently argued the request might be. This ties into "Will it be
178 useful?", as the fact that someone took the time to make the patch
179 demonstrates a strong desire for the feature.
180
181 If you're on the list, you might hear the word "core" bandied around.
182 It refers to the standard distribution. "Hacking on the core" means
183 you're changing the C source code to the Perl interpreter. "A core
184 module" is one that ships with Perl.
185
186 Keeping in sync
187 The source code to the Perl interpreter, in its different versions, is
188 kept in a repository managed by the git revision control system. The
189 pumpkings and a few others have write access to the repository to check
190 in changes.
191
192 How to clone and use the git perl repository is described in
193 perlrepository.
194
195 You can also choose to use rsync to get a copy of the current source
196 tree for the bleadperl branch and all maintenance branches :
197
198 $ rsync -avz rsync://perl5.git.perl.org/APC/perl-current .
199 $ rsync -avz rsync://perl5.git.perl.org/APC/perl-5.10.x .
200 $ rsync -avz rsync://perl5.git.perl.org/APC/perl-5.8.x .
201 $ rsync -avz rsync://perl5.git.perl.org/APC/perl-5.6.x .
202 $ rsync -avz rsync://perl5.git.perl.org/APC/perl-5.005xx .
203
204 (Add the "--delete" option to remove leftover files)
205
206 You may also want to subscribe to the perl5-changes mailing list to
207 receive a copy of each patch that gets submitted to the maintenance and
208 development "branches" of the perl repository. See
209 http://lists.perl.org/ for subscription information.
210
211 If you are a member of the perl5-porters mailing list, it is a good
212 thing to keep in touch with the most recent changes. If not only to
213 verify if what you would have posted as a bug report isn't already
214 solved in the most recent available perl development branch, also known
215 as perl-current, bleading edge perl, bleedperl or bleadperl.
216
217 Needless to say, the source code in perl-current is usually in a
218 perpetual state of evolution. You should expect it to be very buggy.
219 Do not use it for any purpose other than testing and development.
220
221 Perlbug administration
222 There is a single remote administrative interface for modifying bug
223 status, category, open issues etc. using the RT bugtracker system,
224 maintained by Robert Spier. Become an administrator, and close any
225 bugs you can get your sticky mitts on:
226
227 http://bugs.perl.org/
228
229 To email the bug system administrators:
230
231 "perlbug-admin" <perlbug-admin@perl.org>
232
233 Submitting patches
234 Always submit patches to perl5-porters@perl.org. If you're patching a
235 core module and there's an author listed, send the author a copy (see
236 "Patching a core module"). This lets other porters review your patch,
237 which catches a surprising number of errors in patches. Please patch
238 against the latest development version. (e.g., even if you're fixing a
239 bug in the 5.8 track, patch against the "blead" branch in the git
240 repository.)
241
242 If changes are accepted, they are applied to the development branch.
243 Then the maintenance pumpking decides which of those patches is to be
244 backported to the maint branch. Only patches that survive the heat of
245 the development branch get applied to maintenance versions.
246
247 Your patch should update the documentation and test suite. See
248 "Writing a test". If you have added or removed files in the
249 distribution, edit the MANIFEST file accordingly, sort the MANIFEST
250 file using "make manisort", and include those changes as part of your
251 patch.
252
253 Patching documentation also follows the same order: if accepted, a
254 patch is first applied to development, and if relevant then it's
255 backported to maintenance. (With an exception for some patches that
256 document behaviour that only appears in the maintenance branch, but
257 which has changed in the development version.)
258
259 To report a bug in Perl, use the program perlbug which comes with Perl
260 (if you can't get Perl to work, send mail to the address
261 perlbug@perl.org or perlbug@perl.com). Reporting bugs through perlbug
262 feeds into the automated bug-tracking system, access to which is
263 provided through the web at http://rt.perl.org/rt3/ . It often pays to
264 check the archives of the perl5-porters mailing list to see whether the
265 bug you're reporting has been reported before, and if so whether it was
266 considered a bug. See above for the location of the searchable
267 archives.
268
269 The CPAN testers ( http://testers.cpan.org/ ) are a group of volunteers
270 who test CPAN modules on a variety of platforms. Perl Smokers (
271 http://www.nntp.perl.org/group/perl.daily-build and
272 http://www.nntp.perl.org/group/perl.daily-build.reports/ )
273 automatically test Perl source releases on platforms with various
274 configurations. Both efforts welcome volunteers. In order to get
275 involved in smoke testing of the perl itself visit
276 <http://search.cpan.org/dist/Test-Smoke>. In order to start smoke
277 testing CPAN modules visit <http://search.cpan.org/dist/CPAN-YACSmoke/>
278 or <http://search.cpan.org/dist/POE-Component-CPAN-YACSmoke/> or
279 <http://search.cpan.org/dist/CPAN-Reporter/>.
280
281 It's a good idea to read and lurk for a while before chipping in. That
282 way you'll get to see the dynamic of the conversations, learn the
283 personalities of the players, and hopefully be better prepared to make
284 a useful contribution when do you speak up.
285
286 If after all this you still think you want to join the perl5-porters
287 mailing list, send mail to perl5-porters-subscribe@perl.org. To
288 unsubscribe, send mail to perl5-porters-unsubscribe@perl.org.
289
290 To hack on the Perl guts, you'll need to read the following things:
291
292 perlguts
293 This is of paramount importance, since it's the documentation of
294 what goes where in the Perl source. Read it over a couple of times
295 and it might start to make sense - don't worry if it doesn't yet,
296 because the best way to study it is to read it in conjunction with
297 poking at Perl source, and we'll do that later on.
298
299 Gisle Aas's illustrated perlguts (aka: illguts) is wonderful,
300 although a little out of date wrt some size details; the various SV
301 structures have since been reworked for smaller memory footprint.
302 The fundamentals are right however, and the pictures are very
303 helpful.
304
305 http://www.perl.org/tpc/1998/Perl_Language_and_Modules/Perl%20Illustrated/
306
307 perlxstut and perlxs
308 A working knowledge of XSUB programming is incredibly useful for
309 core hacking; XSUBs use techniques drawn from the PP code, the
310 portion of the guts that actually executes a Perl program. It's a
311 lot gentler to learn those techniques from simple examples and
312 explanation than from the core itself.
313
314 perlapi
315 The documentation for the Perl API explains what some of the
316 internal functions do, as well as the many macros used in the
317 source.
318
319 Porting/pumpkin.pod
320 This is a collection of words of wisdom for a Perl porter; some of
321 it is only useful to the pumpkin holder, but most of it applies to
322 anyone wanting to go about Perl development.
323
324 The perl5-porters FAQ
325 This should be available from
326 http://dev.perl.org/perl5/docs/p5p-faq.html . It contains hints on
327 reading perl5-porters, information on how perl5-porters works and
328 how Perl development in general works.
329
330 Finding Your Way Around
331 Perl maintenance can be split into a number of areas, and certain
332 people (pumpkins) will have responsibility for each area. These areas
333 sometimes correspond to files or directories in the source kit. Among
334 the areas are:
335
336 Core modules
337 Modules shipped as part of the Perl core live in the lib/ and ext/
338 subdirectories: lib/ is for the pure-Perl modules, and ext/ contains
339 the core XS modules.
340
341 Tests
342 There are tests for nearly all the modules, built-ins and major bits
343 of functionality. Test files all have a .t suffix. Module tests
344 live in the lib/ and ext/ directories next to the module being
345 tested. Others live in t/. See "Writing a test"
346
347 Documentation
348 Documentation maintenance includes looking after everything in the
349 pod/ directory, (as well as contributing new documentation) and the
350 documentation to the modules in core.
351
352 Configure
353 The configure process is the way we make Perl portable across the
354 myriad of operating systems it supports. Responsibility for the
355 configure, build and installation process, as well as the overall
356 portability of the core code rests with the configure pumpkin -
357 others help out with individual operating systems.
358
359 The files involved are the operating system directories, (win32/,
360 os2/, vms/ and so on) the shell scripts which generate config.h and
361 Makefile, as well as the metaconfig files which generate Configure.
362 (metaconfig isn't included in the core distribution.)
363
364 Interpreter
365 And of course, there's the core of the Perl interpreter itself.
366 Let's have a look at that in a little more detail.
367
368 Before we leave looking at the layout, though, don't forget that
369 MANIFEST contains not only the file names in the Perl distribution, but
370 short descriptions of what's in them, too. For an overview of the
371 important files, try this:
372
373 perl -lne 'print if /^[^\/]+\.[ch]\s+/' MANIFEST
374
375 Elements of the interpreter
376 The work of the interpreter has two main stages: compiling the code
377 into the internal representation, or bytecode, and then executing it.
378 "Compiled code" in perlguts explains exactly how the compilation stage
379 happens.
380
381 Here is a short breakdown of perl's operation:
382
383 Startup
384 The action begins in perlmain.c. (or miniperlmain.c for miniperl)
385 This is very high-level code, enough to fit on a single screen, and
386 it resembles the code found in perlembed; most of the real action
387 takes place in perl.c
388
389 perlmain.c is generated by writemain from miniperlmain.c at make
390 time, so you should make perl to follow this along.
391
392 First, perlmain.c allocates some memory and constructs a Perl
393 interpreter, along these lines:
394
395 1 PERL_SYS_INIT3(&argc,&argv,&env);
396 2
397 3 if (!PL_do_undump) {
398 4 my_perl = perl_alloc();
399 5 if (!my_perl)
400 6 exit(1);
401 7 perl_construct(my_perl);
402 8 PL_perl_destruct_level = 0;
403 9 }
404
405 Line 1 is a macro, and its definition is dependent on your operating
406 system. Line 3 references "PL_do_undump", a global variable - all
407 global variables in Perl start with "PL_". This tells you whether
408 the current running program was created with the "-u" flag to perl
409 and then undump, which means it's going to be false in any sane
410 context.
411
412 Line 4 calls a function in perl.c to allocate memory for a Perl
413 interpreter. It's quite a simple function, and the guts of it looks
414 like this:
415
416 my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
417
418 Here you see an example of Perl's system abstraction, which we'll
419 see later: "PerlMem_malloc" is either your system's "malloc", or
420 Perl's own "malloc" as defined in malloc.c if you selected that
421 option at configure time.
422
423 Next, in line 7, we construct the interpreter using perl_construct,
424 also in perl.c; this sets up all the special variables that Perl
425 needs, the stacks, and so on.
426
427 Now we pass Perl the command line options, and tell it to go:
428
429 exitstatus = perl_parse(my_perl, xs_init, argc, argv, (char **)NULL);
430 if (!exitstatus)
431 perl_run(my_perl);
432
433 exitstatus = perl_destruct(my_perl);
434
435 perl_free(my_perl);
436
437 "perl_parse" is actually a wrapper around "S_parse_body", as defined
438 in perl.c, which processes the command line options, sets up any
439 statically linked XS modules, opens the program and calls "yyparse"
440 to parse it.
441
442 Parsing
443 The aim of this stage is to take the Perl source, and turn it into
444 an op tree. We'll see what one of those looks like later. Strictly
445 speaking, there's three things going on here.
446
447 "yyparse", the parser, lives in perly.c, although you're better off
448 reading the original YACC input in perly.y. (Yes, Virginia, there is
449 a YACC grammar for Perl!) The job of the parser is to take your code
450 and "understand" it, splitting it into sentences, deciding which
451 operands go with which operators and so on.
452
453 The parser is nobly assisted by the lexer, which chunks up your
454 input into tokens, and decides what type of thing each token is: a
455 variable name, an operator, a bareword, a subroutine, a core
456 function, and so on. The main point of entry to the lexer is
457 "yylex", and that and its associated routines can be found in
458 toke.c. Perl isn't much like other computer languages; it's highly
459 context sensitive at times, it can be tricky to work out what sort
460 of token something is, or where a token ends. As such, there's a lot
461 of interplay between the tokeniser and the parser, which can get
462 pretty frightening if you're not used to it.
463
464 As the parser understands a Perl program, it builds up a tree of
465 operations for the interpreter to perform during execution. The
466 routines which construct and link together the various operations
467 are to be found in op.c, and will be examined later.
468
469 Optimization
470 Now the parsing stage is complete, and the finished tree represents
471 the operations that the Perl interpreter needs to perform to execute
472 our program. Next, Perl does a dry run over the tree looking for
473 optimisations: constant expressions such as "3 + 4" will be computed
474 now, and the optimizer will also see if any multiple operations can
475 be replaced with a single one. For instance, to fetch the variable
476 $foo, instead of grabbing the glob *foo and looking at the scalar
477 component, the optimizer fiddles the op tree to use a function which
478 directly looks up the scalar in question. The main optimizer is
479 "peep" in op.c, and many ops have their own optimizing functions.
480
481 Running
482 Now we're finally ready to go: we have compiled Perl byte code, and
483 all that's left to do is run it. The actual execution is done by the
484 "runops_standard" function in run.c; more specifically, it's done by
485 these three innocent looking lines:
486
487 while ((PL_op = CALL_FPTR(PL_op->op_ppaddr)(aTHX))) {
488 PERL_ASYNC_CHECK();
489 }
490
491 You may be more comfortable with the Perl version of that:
492
493 PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op->{function}};
494
495 Well, maybe not. Anyway, each op contains a function pointer, which
496 stipulates the function which will actually carry out the operation.
497 This function will return the next op in the sequence - this allows
498 for things like "if" which choose the next op dynamically at run
499 time. The "PERL_ASYNC_CHECK" makes sure that things like signals
500 interrupt execution if required.
501
502 The actual functions called are known as PP code, and they're spread
503 between four files: pp_hot.c contains the "hot" code, which is most
504 often used and highly optimized, pp_sys.c contains all the system-
505 specific functions, pp_ctl.c contains the functions which implement
506 control structures ("if", "while" and the like) and pp.c contains
507 everything else. These are, if you like, the C code for Perl's
508 built-in functions and operators.
509
510 Note that each "pp_" function is expected to return a pointer to the
511 next op. Calls to perl subs (and eval blocks) are handled within the
512 same runops loop, and do not consume extra space on the C stack. For
513 example, "pp_entersub" and "pp_entertry" just push a "CxSUB" or
514 "CxEVAL" block struct onto the context stack which contain the
515 address of the op following the sub call or eval. They then return
516 the first op of that sub or eval block, and so execution continues
517 of that sub or block. Later, a "pp_leavesub" or "pp_leavetry" op
518 pops the "CxSUB" or "CxEVAL", retrieves the return op from it, and
519 returns it.
520
521 Exception handing
522 Perl's exception handing (i.e. "die" etc.) is built on top of the
523 low-level "setjmp()"/"longjmp()" C-library functions. These
524 basically provide a way to capture the current PC and SP registers
525 and later restore them; i.e. a "longjmp()" continues at the point
526 in code where a previous "setjmp()" was done, with anything further
527 up on the C stack being lost. This is why code should always save
528 values using "SAVE_FOO" rather than in auto variables.
529
530 The perl core wraps "setjmp()" etc in the macros "JMPENV_PUSH" and
531 "JMPENV_JUMP". The basic rule of perl exceptions is that "exit", and
532 "die" (in the absence of "eval") perform a JMPENV_JUMP(2), while
533 "die" within "eval" does a JMPENV_JUMP(3).
534
535 At entry points to perl, such as "perl_parse()", "perl_run()" and
536 "call_sv(cv, G_EVAL)" each does a "JMPENV_PUSH", then enter a runops
537 loop or whatever, and handle possible exception returns. For a 2
538 return, final cleanup is performed, such as popping stacks and
539 calling "CHECK" or "END" blocks. Amongst other things, this is how
540 scope cleanup still occurs during an "exit".
541
542 If a "die" can find a "CxEVAL" block on the context stack, then the
543 stack is popped to that level and the return op in that block is
544 assigned to "PL_restartop"; then a JMPENV_JUMP(3) is performed.
545 This normally passes control back to the guard. In the case of
546 "perl_run" and "call_sv", a non-null "PL_restartop" triggers re-
547 entry to the runops loop. The is the normal way that "die" or
548 "croak" is handled within an "eval".
549
550 Sometimes ops are executed within an inner runops loop, such as tie,
551 sort or overload code. In this case, something like
552
553 sub FETCH { eval { die } }
554
555 would cause a longjmp right back to the guard in "perl_run", popping
556 both runops loops, which is clearly incorrect. One way to avoid this
557 is for the tie code to do a "JMPENV_PUSH" before executing "FETCH"
558 in the inner runops loop, but for efficiency reasons, perl in fact
559 just sets a flag, using "CATCH_SET(TRUE)". The "pp_require",
560 "pp_entereval" and "pp_entertry" ops check this flag, and if true,
561 they call "docatch", which does a "JMPENV_PUSH" and starts a new
562 runops level to execute the code, rather than doing it on the
563 current loop.
564
565 As a further optimisation, on exit from the eval block in the
566 "FETCH", execution of the code following the block is still carried
567 on in the inner loop. When an exception is raised, "docatch"
568 compares the "JMPENV" level of the "CxEVAL" with "PL_top_env" and if
569 they differ, just re-throws the exception. In this way any inner
570 loops get popped.
571
572 Here's an example.
573
574 1: eval { tie @a, 'A' };
575 2: sub A::TIEARRAY {
576 3: eval { die };
577 4: die;
578 5: }
579
580 To run this code, "perl_run" is called, which does a "JMPENV_PUSH"
581 then enters a runops loop. This loop executes the eval and tie ops
582 on line 1, with the eval pushing a "CxEVAL" onto the context stack.
583
584 The "pp_tie" does a "CATCH_SET(TRUE)", then starts a second runops
585 loop to execute the body of "TIEARRAY". When it executes the
586 entertry op on line 3, "CATCH_GET" is true, so "pp_entertry" calls
587 "docatch" which does a "JMPENV_PUSH" and starts a third runops loop,
588 which then executes the die op. At this point the C call stack looks
589 like this:
590
591 Perl_pp_die
592 Perl_runops # third loop
593 S_docatch_body
594 S_docatch
595 Perl_pp_entertry
596 Perl_runops # second loop
597 S_call_body
598 Perl_call_sv
599 Perl_pp_tie
600 Perl_runops # first loop
601 S_run_body
602 perl_run
603 main
604
605 and the context and data stacks, as shown by "-Dstv", look like:
606
607 STACK 0: MAIN
608 CX 0: BLOCK =>
609 CX 1: EVAL => AV() PV("A"\0)
610 retop=leave
611 STACK 1: MAGIC
612 CX 0: SUB =>
613 retop=(null)
614 CX 1: EVAL => *
615 retop=nextstate
616
617 The die pops the first "CxEVAL" off the context stack, sets
618 "PL_restartop" from it, does a JMPENV_JUMP(3), and control returns
619 to the top "docatch". This then starts another third-level runops
620 level, which executes the nextstate, pushmark and die ops on line 4.
621 At the point that the second "pp_die" is called, the C call stack
622 looks exactly like that above, even though we are no longer within
623 an inner eval; this is because of the optimization mentioned
624 earlier. However, the context stack now looks like this, ie with the
625 top CxEVAL popped:
626
627 STACK 0: MAIN
628 CX 0: BLOCK =>
629 CX 1: EVAL => AV() PV("A"\0)
630 retop=leave
631 STACK 1: MAGIC
632 CX 0: SUB =>
633 retop=(null)
634
635 The die on line 4 pops the context stack back down to the CxEVAL,
636 leaving it as:
637
638 STACK 0: MAIN
639 CX 0: BLOCK =>
640
641 As usual, "PL_restartop" is extracted from the "CxEVAL", and a
642 JMPENV_JUMP(3) done, which pops the C stack back to the docatch:
643
644 S_docatch
645 Perl_pp_entertry
646 Perl_runops # second loop
647 S_call_body
648 Perl_call_sv
649 Perl_pp_tie
650 Perl_runops # first loop
651 S_run_body
652 perl_run
653 main
654
655 In this case, because the "JMPENV" level recorded in the "CxEVAL"
656 differs from the current one, "docatch" just does a JMPENV_JUMP(3)
657 and the C stack unwinds to:
658
659 perl_run
660 main
661
662 Because "PL_restartop" is non-null, "run_body" starts a new runops
663 loop and execution continues.
664
665 Internal Variable Types
666 You should by now have had a look at perlguts, which tells you about
667 Perl's internal variable types: SVs, HVs, AVs and the rest. If not, do
668 that now.
669
670 These variables are used not only to represent Perl-space variables,
671 but also any constants in the code, as well as some structures
672 completely internal to Perl. The symbol table, for instance, is an
673 ordinary Perl hash. Your code is represented by an SV as it's read into
674 the parser; any program files you call are opened via ordinary Perl
675 filehandles, and so on.
676
677 The core Devel::Peek module lets us examine SVs from a Perl program.
678 Let's see, for instance, how Perl treats the constant "hello".
679
680 % perl -MDevel::Peek -e 'Dump("hello")'
681 1 SV = PV(0xa041450) at 0xa04ecbc
682 2 REFCNT = 1
683 3 FLAGS = (POK,READONLY,pPOK)
684 4 PV = 0xa0484e0 "hello"\0
685 5 CUR = 5
686 6 LEN = 6
687
688 Reading "Devel::Peek" output takes a bit of practise, so let's go
689 through it line by line.
690
691 Line 1 tells us we're looking at an SV which lives at 0xa04ecbc in
692 memory. SVs themselves are very simple structures, but they contain a
693 pointer to a more complex structure. In this case, it's a PV, a
694 structure which holds a string value, at location 0xa041450. Line 2 is
695 the reference count; there are no other references to this data, so
696 it's 1.
697
698 Line 3 are the flags for this SV - it's OK to use it as a PV, it's a
699 read-only SV (because it's a constant) and the data is a PV internally.
700 Next we've got the contents of the string, starting at location
701 0xa0484e0.
702
703 Line 5 gives us the current length of the string - note that this does
704 not include the null terminator. Line 6 is not the length of the
705 string, but the length of the currently allocated buffer; as the string
706 grows, Perl automatically extends the available storage via a routine
707 called "SvGROW".
708
709 You can get at any of these quantities from C very easily; just add
710 "Sv" to the name of the field shown in the snippet, and you've got a
711 macro which will return the value: "SvCUR(sv)" returns the current
712 length of the string, "SvREFCOUNT(sv)" returns the reference count,
713 "SvPV(sv, len)" returns the string itself with its length, and so on.
714 More macros to manipulate these properties can be found in perlguts.
715
716 Let's take an example of manipulating a PV, from "sv_catpvn", in sv.c
717
718 1 void
719 2 Perl_sv_catpvn(pTHX_ register SV *sv, register const char *ptr, register STRLEN len)
720 3 {
721 4 STRLEN tlen;
722 5 char *junk;
723
724 6 junk = SvPV_force(sv, tlen);
725 7 SvGROW(sv, tlen + len + 1);
726 8 if (ptr == junk)
727 9 ptr = SvPVX(sv);
728 10 Move(ptr,SvPVX(sv)+tlen,len,char);
729 11 SvCUR(sv) += len;
730 12 *SvEND(sv) = '\0';
731 13 (void)SvPOK_only_UTF8(sv); /* validate pointer */
732 14 SvTAINT(sv);
733 15 }
734
735 This is a function which adds a string, "ptr", of length "len" onto the
736 end of the PV stored in "sv". The first thing we do in line 6 is make
737 sure that the SV has a valid PV, by calling the "SvPV_force" macro to
738 force a PV. As a side effect, "tlen" gets set to the current value of
739 the PV, and the PV itself is returned to "junk".
740
741 In line 7, we make sure that the SV will have enough room to
742 accommodate the old string, the new string and the null terminator. If
743 "LEN" isn't big enough, "SvGROW" will reallocate space for us.
744
745 Now, if "junk" is the same as the string we're trying to add, we can
746 grab the string directly from the SV; "SvPVX" is the address of the PV
747 in the SV.
748
749 Line 10 does the actual catenation: the "Move" macro moves a chunk of
750 memory around: we move the string "ptr" to the end of the PV - that's
751 the start of the PV plus its current length. We're moving "len" bytes
752 of type "char". After doing so, we need to tell Perl we've extended the
753 string, by altering "CUR" to reflect the new length. "SvEND" is a macro
754 which gives us the end of the string, so that needs to be a "\0".
755
756 Line 13 manipulates the flags; since we've changed the PV, any IV or NV
757 values will no longer be valid: if we have "$a=10; $a.="6";" we don't
758 want to use the old IV of 10. "SvPOK_only_utf8" is a special
759 UTF-8-aware version of "SvPOK_only", a macro which turns off the IOK
760 and NOK flags and turns on POK. The final "SvTAINT" is a macro which
761 launders tainted data if taint mode is turned on.
762
763 AVs and HVs are more complicated, but SVs are by far the most common
764 variable type being thrown around. Having seen something of how we
765 manipulate these, let's go on and look at how the op tree is
766 constructed.
767
768 Op Trees
769 First, what is the op tree, anyway? The op tree is the parsed
770 representation of your program, as we saw in our section on parsing,
771 and it's the sequence of operations that Perl goes through to execute
772 your program, as we saw in "Running".
773
774 An op is a fundamental operation that Perl can perform: all the built-
775 in functions and operators are ops, and there are a series of ops which
776 deal with concepts the interpreter needs internally - entering and
777 leaving a block, ending a statement, fetching a variable, and so on.
778
779 The op tree is connected in two ways: you can imagine that there are
780 two "routes" through it, two orders in which you can traverse the tree.
781 First, parse order reflects how the parser understood the code, and
782 secondly, execution order tells perl what order to perform the
783 operations in.
784
785 The easiest way to examine the op tree is to stop Perl after it has
786 finished parsing, and get it to dump out the tree. This is exactly what
787 the compiler backends B::Terse, B::Concise and B::Debug do.
788
789 Let's have a look at how Perl sees "$a = $b + $c":
790
791 % perl -MO=Terse -e '$a=$b+$c'
792 1 LISTOP (0x8179888) leave
793 2 OP (0x81798b0) enter
794 3 COP (0x8179850) nextstate
795 4 BINOP (0x8179828) sassign
796 5 BINOP (0x8179800) add [1]
797 6 UNOP (0x81796e0) null [15]
798 7 SVOP (0x80fafe0) gvsv GV (0x80fa4cc) *b
799 8 UNOP (0x81797e0) null [15]
800 9 SVOP (0x8179700) gvsv GV (0x80efeb0) *c
801 10 UNOP (0x816b4f0) null [15]
802 11 SVOP (0x816dcf0) gvsv GV (0x80fa460) *a
803
804 Let's start in the middle, at line 4. This is a BINOP, a binary
805 operator, which is at location 0x8179828. The specific operator in
806 question is "sassign" - scalar assignment - and you can find the code
807 which implements it in the function "pp_sassign" in pp_hot.c. As a
808 binary operator, it has two children: the add operator, providing the
809 result of "$b+$c", is uppermost on line 5, and the left hand side is on
810 line 10.
811
812 Line 10 is the null op: this does exactly nothing. What is that doing
813 there? If you see the null op, it's a sign that something has been
814 optimized away after parsing. As we mentioned in "Optimization", the
815 optimization stage sometimes converts two operations into one, for
816 example when fetching a scalar variable. When this happens, instead of
817 rewriting the op tree and cleaning up the dangling pointers, it's
818 easier just to replace the redundant operation with the null op.
819 Originally, the tree would have looked like this:
820
821 10 SVOP (0x816b4f0) rv2sv [15]
822 11 SVOP (0x816dcf0) gv GV (0x80fa460) *a
823
824 That is, fetch the "a" entry from the main symbol table, and then look
825 at the scalar component of it: "gvsv" ("pp_gvsv" into pp_hot.c) happens
826 to do both these things.
827
828 The right hand side, starting at line 5 is similar to what we've just
829 seen: we have the "add" op ("pp_add" also in pp_hot.c) add together two
830 "gvsv"s.
831
832 Now, what's this about?
833
834 1 LISTOP (0x8179888) leave
835 2 OP (0x81798b0) enter
836 3 COP (0x8179850) nextstate
837
838 "enter" and "leave" are scoping ops, and their job is to perform any
839 housekeeping every time you enter and leave a block: lexical variables
840 are tidied up, unreferenced variables are destroyed, and so on. Every
841 program will have those first three lines: "leave" is a list, and its
842 children are all the statements in the block. Statements are delimited
843 by "nextstate", so a block is a collection of "nextstate" ops, with the
844 ops to be performed for each statement being the children of
845 "nextstate". "enter" is a single op which functions as a marker.
846
847 That's how Perl parsed the program, from top to bottom:
848
849 Program
850 |
851 Statement
852 |
853 =
854 / \
855 / \
856 $a +
857 / \
858 $b $c
859
860 However, it's impossible to perform the operations in this order: you
861 have to find the values of $b and $c before you add them together, for
862 instance. So, the other thread that runs through the op tree is the
863 execution order: each op has a field "op_next" which points to the next
864 op to be run, so following these pointers tells us how perl executes
865 the code. We can traverse the tree in this order using the "exec"
866 option to "B::Terse":
867
868 % perl -MO=Terse,exec -e '$a=$b+$c'
869 1 OP (0x8179928) enter
870 2 COP (0x81798c8) nextstate
871 3 SVOP (0x81796c8) gvsv GV (0x80fa4d4) *b
872 4 SVOP (0x8179798) gvsv GV (0x80efeb0) *c
873 5 BINOP (0x8179878) add [1]
874 6 SVOP (0x816dd38) gvsv GV (0x80fa468) *a
875 7 BINOP (0x81798a0) sassign
876 8 LISTOP (0x8179900) leave
877
878 This probably makes more sense for a human: enter a block, start a
879 statement. Get the values of $b and $c, and add them together. Find
880 $a, and assign one to the other. Then leave.
881
882 The way Perl builds up these op trees in the parsing process can be
883 unravelled by examining perly.y, the YACC grammar. Let's take the piece
884 we need to construct the tree for "$a = $b + $c"
885
886 1 term : term ASSIGNOP term
887 2 { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
888 3 | term ADDOP term
889 4 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
890
891 If you're not used to reading BNF grammars, this is how it works:
892 You're fed certain things by the tokeniser, which generally end up in
893 upper case. Here, "ADDOP", is provided when the tokeniser sees "+" in
894 your code. "ASSIGNOP" is provided when "=" is used for assigning. These
895 are "terminal symbols", because you can't get any simpler than them.
896
897 The grammar, lines one and three of the snippet above, tells you how to
898 build up more complex forms. These complex forms, "non-terminal
899 symbols" are generally placed in lower case. "term" here is a non-
900 terminal symbol, representing a single expression.
901
902 The grammar gives you the following rule: you can make the thing on the
903 left of the colon if you see all the things on the right in sequence.
904 This is called a "reduction", and the aim of parsing is to completely
905 reduce the input. There are several different ways you can perform a
906 reduction, separated by vertical bars: so, "term" followed by "="
907 followed by "term" makes a "term", and "term" followed by "+" followed
908 by "term" can also make a "term".
909
910 So, if you see two terms with an "=" or "+", between them, you can turn
911 them into a single expression. When you do this, you execute the code
912 in the block on the next line: if you see "=", you'll do the code in
913 line 2. If you see "+", you'll do the code in line 4. It's this code
914 which contributes to the op tree.
915
916 | term ADDOP term
917 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
918
919 What this does is creates a new binary op, and feeds it a number of
920 variables. The variables refer to the tokens: $1 is the first token in
921 the input, $2 the second, and so on - think regular expression
922 backreferences. $$ is the op returned from this reduction. So, we call
923 "newBINOP" to create a new binary operator. The first parameter to
924 "newBINOP", a function in op.c, is the op type. It's an addition
925 operator, so we want the type to be "ADDOP". We could specify this
926 directly, but it's right there as the second token in the input, so we
927 use $2. The second parameter is the op's flags: 0 means "nothing
928 special". Then the things to add: the left and right hand side of our
929 expression, in scalar context.
930
931 Stacks
932 When perl executes something like "addop", how does it pass on its
933 results to the next op? The answer is, through the use of stacks. Perl
934 has a number of stacks to store things it's currently working on, and
935 we'll look at the three most important ones here.
936
937 Argument stack
938 Arguments are passed to PP code and returned from PP code using the
939 argument stack, "ST". The typical way to handle arguments is to pop
940 them off the stack, deal with them how you wish, and then push the
941 result back onto the stack. This is how, for instance, the cosine
942 operator works:
943
944 NV value;
945 value = POPn;
946 value = Perl_cos(value);
947 XPUSHn(value);
948
949 We'll see a more tricky example of this when we consider Perl's
950 macros below. "POPn" gives you the NV (floating point value) of the
951 top SV on the stack: the $x in "cos($x)". Then we compute the
952 cosine, and push the result back as an NV. The "X" in "XPUSHn" means
953 that the stack should be extended if necessary - it can't be
954 necessary here, because we know there's room for one more item on
955 the stack, since we've just removed one! The "XPUSH*" macros at
956 least guarantee safety.
957
958 Alternatively, you can fiddle with the stack directly: "SP" gives
959 you the first element in your portion of the stack, and "TOP*" gives
960 you the top SV/IV/NV/etc. on the stack. So, for instance, to do
961 unary negation of an integer:
962
963 SETi(-TOPi);
964
965 Just set the integer value of the top stack entry to its negation.
966
967 Argument stack manipulation in the core is exactly the same as it is
968 in XSUBs - see perlxstut, perlxs and perlguts for a longer
969 description of the macros used in stack manipulation.
970
971 Mark stack
972 I say "your portion of the stack" above because PP code doesn't
973 necessarily get the whole stack to itself: if your function calls
974 another function, you'll only want to expose the arguments aimed for
975 the called function, and not (necessarily) let it get at your own
976 data. The way we do this is to have a "virtual" bottom-of-stack,
977 exposed to each function. The mark stack keeps bookmarks to
978 locations in the argument stack usable by each function. For
979 instance, when dealing with a tied variable, (internally, something
980 with "P" magic) Perl has to call methods for accesses to the tied
981 variables. However, we need to separate the arguments exposed to the
982 method to the argument exposed to the original function - the store
983 or fetch or whatever it may be. Here's roughly how the tied "push"
984 is implemented; see "av_push" in av.c:
985
986 1 PUSHMARK(SP);
987 2 EXTEND(SP,2);
988 3 PUSHs(SvTIED_obj((SV*)av, mg));
989 4 PUSHs(val);
990 5 PUTBACK;
991 6 ENTER;
992 7 call_method("PUSH", G_SCALAR|G_DISCARD);
993 8 LEAVE;
994
995 Let's examine the whole implementation, for practice:
996
997 1 PUSHMARK(SP);
998
999 Push the current state of the stack pointer onto the mark stack.
1000 This is so that when we've finished adding items to the argument
1001 stack, Perl knows how many things we've added recently.
1002
1003 2 EXTEND(SP,2);
1004 3 PUSHs(SvTIED_obj((SV*)av, mg));
1005 4 PUSHs(val);
1006
1007 We're going to add two more items onto the argument stack: when you
1008 have a tied array, the "PUSH" subroutine receives the object and the
1009 value to be pushed, and that's exactly what we have here - the tied
1010 object, retrieved with "SvTIED_obj", and the value, the SV "val".
1011
1012 5 PUTBACK;
1013
1014 Next we tell Perl to update the global stack pointer from our
1015 internal variable: "dSP" only gave us a local copy, not a reference
1016 to the global.
1017
1018 6 ENTER;
1019 7 call_method("PUSH", G_SCALAR|G_DISCARD);
1020 8 LEAVE;
1021
1022 "ENTER" and "LEAVE" localise a block of code - they make sure that
1023 all variables are tidied up, everything that has been localised gets
1024 its previous value returned, and so on. Think of them as the "{" and
1025 "}" of a Perl block.
1026
1027 To actually do the magic method call, we have to call a subroutine
1028 in Perl space: "call_method" takes care of that, and it's described
1029 in perlcall. We call the "PUSH" method in scalar context, and we're
1030 going to discard its return value. The call_method() function
1031 removes the top element of the mark stack, so there is nothing for
1032 the caller to clean up.
1033
1034 Save stack
1035 C doesn't have a concept of local scope, so perl provides one. We've
1036 seen that "ENTER" and "LEAVE" are used as scoping braces; the save
1037 stack implements the C equivalent of, for example:
1038
1039 {
1040 local $foo = 42;
1041 ...
1042 }
1043
1044 See "Localising Changes" in perlguts for how to use the save stack.
1045
1046 Millions of Macros
1047 One thing you'll notice about the Perl source is that it's full of
1048 macros. Some have called the pervasive use of macros the hardest thing
1049 to understand, others find it adds to clarity. Let's take an example,
1050 the code which implements the addition operator:
1051
1052 1 PP(pp_add)
1053 2 {
1054 3 dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
1055 4 {
1056 5 dPOPTOPnnrl_ul;
1057 6 SETn( left + right );
1058 7 RETURN;
1059 8 }
1060 9 }
1061
1062 Every line here (apart from the braces, of course) contains a macro.
1063 The first line sets up the function declaration as Perl expects for PP
1064 code; line 3 sets up variable declarations for the argument stack and
1065 the target, the return value of the operation. Finally, it tries to see
1066 if the addition operation is overloaded; if so, the appropriate
1067 subroutine is called.
1068
1069 Line 5 is another variable declaration - all variable declarations
1070 start with "d" - which pops from the top of the argument stack two NVs
1071 (hence "nn") and puts them into the variables "right" and "left", hence
1072 the "rl". These are the two operands to the addition operator. Next, we
1073 call "SETn" to set the NV of the return value to the result of adding
1074 the two values. This done, we return - the "RETURN" macro makes sure
1075 that our return value is properly handled, and we pass the next
1076 operator to run back to the main run loop.
1077
1078 Most of these macros are explained in perlapi, and some of the more
1079 important ones are explained in perlxs as well. Pay special attention
1080 to "Background and PERL_IMPLICIT_CONTEXT" in perlguts for information
1081 on the "[pad]THX_?" macros.
1082
1083 The .i Targets
1084 You can expand the macros in a foo.c file by saying
1085
1086 make foo.i
1087
1088 which will expand the macros using cpp. Don't be scared by the
1089 results.
1090
1092 Various tools exist for analysing C source code statically, as opposed
1093 to dynamically, that is, without executing the code. It is possible to
1094 detect resource leaks, undefined behaviour, type mismatches,
1095 portability problems, code paths that would cause illegal memory
1096 accesses, and other similar problems by just parsing the C code and
1097 looking at the resulting graph, what does it tell about the execution
1098 and data flows. As a matter of fact, this is exactly how C compilers
1099 know to give warnings about dubious code.
1100
1101 lint, splint
1102 The good old C code quality inspector, "lint", is available in several
1103 platforms, but please be aware that there are several different
1104 implementations of it by different vendors, which means that the flags
1105 are not identical across different platforms.
1106
1107 There is a lint variant called "splint" (Secure Programming Lint)
1108 available from http://www.splint.org/ that should compile on any Unix-
1109 like platform.
1110
1111 There are "lint" and <splint> targets in Makefile, but you may have to
1112 diddle with the flags (see above).
1113
1114 Coverity
1115 Coverity (http://www.coverity.com/) is a product similar to lint and as
1116 a testbed for their product they periodically check several open source
1117 projects, and they give out accounts to open source developers to the
1118 defect databases.
1119
1120 cpd (cut-and-paste detector)
1121 The cpd tool detects cut-and-paste coding. If one instance of the cut-
1122 and-pasted code changes, all the other spots should probably be
1123 changed, too. Therefore such code should probably be turned into a
1124 subroutine or a macro.
1125
1126 cpd (http://pmd.sourceforge.net/cpd.html) is part of the pmd project
1127 (http://pmd.sourceforge.net/). pmd was originally written for static
1128 analysis of Java code, but later the cpd part of it was extended to
1129 parse also C and C++.
1130
1131 Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the
1132 pmd-X.Y.jar from it, and then run that on source code thusly:
1133
1134 java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files /some/where/src --language c > cpd.txt
1135
1136 You may run into memory limits, in which case you should use the -Xmx
1137 option:
1138
1139 java -Xmx512M ...
1140
1141 gcc warnings
1142 Though much can be written about the inconsistency and coverage
1143 problems of gcc warnings (like "-Wall" not meaning "all the warnings",
1144 or some common portability problems not being covered by "-Wall", or
1145 "-ansi" and "-pedantic" both being a poorly defined collection of
1146 warnings, and so forth), gcc is still a useful tool in keeping our
1147 coding nose clean.
1148
1149 The "-Wall" is by default on.
1150
1151 The "-ansi" (and its sidekick, "-pedantic") would be nice to be on
1152 always, but unfortunately they are not safe on all platforms, they can
1153 for example cause fatal conflicts with the system headers (Solaris
1154 being a prime example). If Configure "-Dgccansipedantic" is used, the
1155 "cflags" frontend selects "-ansi -pedantic" for the platforms where
1156 they are known to be safe.
1157
1158 Starting from Perl 5.9.4 the following extra flags are added:
1159
1160 · "-Wendif-labels"
1161
1162 · "-Wextra"
1163
1164 · "-Wdeclaration-after-statement"
1165
1166 The following flags would be nice to have but they would first need
1167 their own Augean stablemaster:
1168
1169 · "-Wpointer-arith"
1170
1171 · "-Wshadow"
1172
1173 · "-Wstrict-prototypes"
1174
1175 The "-Wtraditional" is another example of the annoying tendency of gcc
1176 to bundle a lot of warnings under one switch -- it would be impossible
1177 to deploy in practice because it would complain a lot -- but it does
1178 contain some warnings that would be beneficial to have available on
1179 their own, such as the warning about string constants inside macros
1180 containing the macro arguments: this behaved differently pre-ANSI than
1181 it does in ANSI, and some C compilers are still in transition, AIX
1182 being an example.
1183
1184 Warnings of other C compilers
1185 Other C compilers (yes, there are other C compilers than gcc) often
1186 have their "strict ANSI" or "strict ANSI with some portability
1187 extensions" modes on, like for example the Sun Workshop has its "-Xa"
1188 mode on (though implicitly), or the DEC (these days, HP...) has its
1189 "-std1" mode on.
1190
1191 DEBUGGING
1192 You can compile a special debugging version of Perl, which allows you
1193 to use the "-D" option of Perl to tell more about what Perl is doing.
1194 But sometimes there is no alternative than to dive in with a debugger,
1195 either to see the stack trace of a core dump (very useful in a bug
1196 report), or trying to figure out what went wrong before the core dump
1197 happened, or how did we end up having wrong or unexpected results.
1198
1199 Poking at Perl
1200 To really poke around with Perl, you'll probably want to build Perl for
1201 debugging, like this:
1202
1203 ./Configure -d -D optimize=-g
1204 make
1205
1206 "-g" is a flag to the C compiler to have it produce debugging
1207 information which will allow us to step through a running program, and
1208 to see in which C function we are at (without the debugging information
1209 we might see only the numerical addresses of the functions, which is
1210 not very helpful).
1211
1212 Configure will also turn on the "DEBUGGING" compilation symbol which
1213 enables all the internal debugging code in Perl. There are a whole
1214 bunch of things you can debug with this: perlrun lists them all, and
1215 the best way to find out about them is to play about with them. The
1216 most useful options are probably
1217
1218 l Context (loop) stack processing
1219 t Trace execution
1220 o Method and overloading resolution
1221 c String/numeric conversions
1222
1223 Some of the functionality of the debugging code can be achieved using
1224 XS modules.
1225
1226 -Dr => use re 'debug'
1227 -Dx => use O 'Debug'
1228
1229 Using a source-level debugger
1230 If the debugging output of "-D" doesn't help you, it's time to step
1231 through perl's execution with a source-level debugger.
1232
1233 · We'll use "gdb" for our examples here; the principles will apply to
1234 any debugger (many vendors call their debugger "dbx"), but check the
1235 manual of the one you're using.
1236
1237 To fire up the debugger, type
1238
1239 gdb ./perl
1240
1241 Or if you have a core dump:
1242
1243 gdb ./perl core
1244
1245 You'll want to do that in your Perl source tree so the debugger can
1246 read the source code. You should see the copyright message, followed by
1247 the prompt.
1248
1249 (gdb)
1250
1251 "help" will get you into the documentation, but here are the most
1252 useful commands:
1253
1254 run [args]
1255 Run the program with the given arguments.
1256
1257 break function_name
1258 break source.c:xxx
1259 Tells the debugger that we'll want to pause execution when we reach
1260 either the named function (but see "Internal Functions" in
1261 perlguts!) or the given line in the named source file.
1262
1263 step
1264 Steps through the program a line at a time.
1265
1266 next
1267 Steps through the program a line at a time, without descending into
1268 functions.
1269
1270 continue
1271 Run until the next breakpoint.
1272
1273 finish
1274 Run until the end of the current function, then stop again.
1275
1276 'enter'
1277 Just pressing Enter will do the most recent operation again - it's a
1278 blessing when stepping through miles of source code.
1279
1280 print
1281 Execute the given C code and print its results. WARNING: Perl makes
1282 heavy use of macros, and gdb does not necessarily support macros
1283 (see later "gdb macro support"). You'll have to substitute them
1284 yourself, or to invoke cpp on the source code files (see "The .i
1285 Targets") So, for instance, you can't say
1286
1287 print SvPV_nolen(sv)
1288
1289 but you have to say
1290
1291 print Perl_sv_2pv_nolen(sv)
1292
1293 You may find it helpful to have a "macro dictionary", which you can
1294 produce by saying "cpp -dM perl.c | sort". Even then, cpp won't
1295 recursively apply those macros for you.
1296
1297 gdb macro support
1298 Recent versions of gdb have fairly good macro support, but in order to
1299 use it you'll need to compile perl with macro definitions included in
1300 the debugging information. Using gcc version 3.1, this means
1301 configuring with "-Doptimize=-g3". Other compilers might use a
1302 different switch (if they support debugging macros at all).
1303
1304 Dumping Perl Data Structures
1305 One way to get around this macro hell is to use the dumping functions
1306 in dump.c; these work a little like an internal Devel::Peek, but they
1307 also cover OPs and other structures that you can't get at from Perl.
1308 Let's take an example. We'll use the "$a = $b + $c" we used before, but
1309 give it a bit of context: "$b = "6XXXX"; $c = 2.3;". Where's a good
1310 place to stop and poke around?
1311
1312 What about "pp_add", the function we examined earlier to implement the
1313 "+" operator:
1314
1315 (gdb) break Perl_pp_add
1316 Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.
1317
1318 Notice we use "Perl_pp_add" and not "pp_add" - see "Internal Functions"
1319 in perlguts. With the breakpoint in place, we can run our program:
1320
1321 (gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c'
1322
1323 Lots of junk will go past as gdb reads in the relevant source files and
1324 libraries, and then:
1325
1326 Breakpoint 1, Perl_pp_add () at pp_hot.c:309
1327 309 dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
1328 (gdb) step
1329 311 dPOPTOPnnrl_ul;
1330 (gdb)
1331
1332 We looked at this bit of code before, and we said that "dPOPTOPnnrl_ul"
1333 arranges for two "NV"s to be placed into "left" and "right" - let's
1334 slightly expand it:
1335
1336 #define dPOPTOPnnrl_ul NV right = POPn; \
1337 SV *leftsv = TOPs; \
1338 NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0
1339
1340 "POPn" takes the SV from the top of the stack and obtains its NV either
1341 directly (if "SvNOK" is set) or by calling the "sv_2nv" function.
1342 "TOPs" takes the next SV from the top of the stack - yes, "POPn" uses
1343 "TOPs" - but doesn't remove it. We then use "SvNV" to get the NV from
1344 "leftsv" in the same way as before - yes, "POPn" uses "SvNV".
1345
1346 Since we don't have an NV for $b, we'll have to use "sv_2nv" to convert
1347 it. If we step again, we'll find ourselves there:
1348
1349 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
1350 1669 if (!sv)
1351 (gdb)
1352
1353 We can now use "Perl_sv_dump" to investigate the SV:
1354
1355 SV = PV(0xa057cc0) at 0xa0675d0
1356 REFCNT = 1
1357 FLAGS = (POK,pPOK)
1358 PV = 0xa06a510 "6XXXX"\0
1359 CUR = 5
1360 LEN = 6
1361 $1 = void
1362
1363 We know we're going to get 6 from this, so let's finish the subroutine:
1364
1365 (gdb) finish
1366 Run till exit from #0 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
1367 0x462669 in Perl_pp_add () at pp_hot.c:311
1368 311 dPOPTOPnnrl_ul;
1369
1370 We can also dump out this op: the current op is always stored in
1371 "PL_op", and we can dump it with "Perl_op_dump". This'll give us
1372 similar output to B::Debug.
1373
1374 {
1375 13 TYPE = add ===> 14
1376 TARG = 1
1377 FLAGS = (SCALAR,KIDS)
1378 {
1379 TYPE = null ===> (12)
1380 (was rv2sv)
1381 FLAGS = (SCALAR,KIDS)
1382 {
1383 11 TYPE = gvsv ===> 12
1384 FLAGS = (SCALAR)
1385 GV = main::b
1386 }
1387 }
1388
1389 # finish this later #
1390
1391 Patching
1392 All right, we've now had a look at how to navigate the Perl sources and
1393 some things you'll need to know when fiddling with them. Let's now get
1394 on and create a simple patch. Here's something Larry suggested: if a
1395 "U" is the first active format during a "pack", (for example, "pack
1396 "U3C8", @stuff") then the resulting string should be treated as UTF-8
1397 encoded.
1398
1399 How do we prepare to fix this up? First we locate the code in question
1400 - the "pack" happens at runtime, so it's going to be in one of the pp
1401 files. Sure enough, "pp_pack" is in pp.c. Since we're going to be
1402 altering this file, let's copy it to pp.c~.
1403
1404 [Well, it was in pp.c when this tutorial was written. It has now been
1405 split off with "pp_unpack" to its own file, pp_pack.c]
1406
1407 Now let's look over "pp_pack": we take a pattern into "pat", and then
1408 loop over the pattern, taking each format character in turn into
1409 "datum_type". Then for each possible format character, we swallow up
1410 the other arguments in the pattern (a field width, an asterisk, and so
1411 on) and convert the next chunk input into the specified format, adding
1412 it onto the output SV "cat".
1413
1414 How do we know if the "U" is the first format in the "pat"? Well, if we
1415 have a pointer to the start of "pat" then, if we see a "U" we can test
1416 whether we're still at the start of the string. So, here's where "pat"
1417 is set up:
1418
1419 STRLEN fromlen;
1420 register char *pat = SvPVx(*++MARK, fromlen);
1421 register char *patend = pat + fromlen;
1422 register I32 len;
1423 I32 datumtype;
1424 SV *fromstr;
1425
1426 We'll have another string pointer in there:
1427
1428 STRLEN fromlen;
1429 register char *pat = SvPVx(*++MARK, fromlen);
1430 register char *patend = pat + fromlen;
1431 + char *patcopy;
1432 register I32 len;
1433 I32 datumtype;
1434 SV *fromstr;
1435
1436 And just before we start the loop, we'll set "patcopy" to be the start
1437 of "pat":
1438
1439 items = SP - MARK;
1440 MARK++;
1441 sv_setpvn(cat, "", 0);
1442 + patcopy = pat;
1443 while (pat < patend) {
1444
1445 Now if we see a "U" which was at the start of the string, we turn on
1446 the "UTF8" flag for the output SV, "cat":
1447
1448 + if (datumtype == 'U' && pat==patcopy+1)
1449 + SvUTF8_on(cat);
1450 if (datumtype == '#') {
1451 while (pat < patend && *pat != '\n')
1452 pat++;
1453
1454 Remember that it has to be "patcopy+1" because the first character of
1455 the string is the "U" which has been swallowed into "datumtype!"
1456
1457 Oops, we forgot one thing: what if there are spaces at the start of the
1458 pattern? "pack(" U*", @stuff)" will have "U" as the first active
1459 character, even though it's not the first thing in the pattern. In this
1460 case, we have to advance "patcopy" along with "pat" when we see spaces:
1461
1462 if (isSPACE(datumtype))
1463 continue;
1464
1465 needs to become
1466
1467 if (isSPACE(datumtype)) {
1468 patcopy++;
1469 continue;
1470 }
1471
1472 OK. That's the C part done. Now we must do two additional things before
1473 this patch is ready to go: we've changed the behaviour of Perl, and so
1474 we must document that change. We must also provide some more regression
1475 tests to make sure our patch works and doesn't create a bug somewhere
1476 else along the line.
1477
1478 The regression tests for each operator live in t/op/, and so we make a
1479 copy of t/op/pack.t to t/op/pack.t~. Now we can add our tests to the
1480 end. First, we'll test that the "U" does indeed create Unicode strings.
1481
1482 t/op/pack.t has a sensible ok() function, but if it didn't we could use
1483 the one from t/test.pl.
1484
1485 require './test.pl';
1486 plan( tests => 159 );
1487
1488 so instead of this:
1489
1490 print 'not ' unless "1.20.300.4000" eq sprintf "%vd", pack("U*",1,20,300,4000);
1491 print "ok $test\n"; $test++;
1492
1493 we can write the more sensible (see Test::More for a full explanation
1494 of is() and other testing functions).
1495
1496 is( "1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000),
1497 "U* produces Unicode" );
1498
1499 Now we'll test that we got that space-at-the-beginning business right:
1500
1501 is( "1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000),
1502 " with spaces at the beginning" );
1503
1504 And finally we'll test that we don't make Unicode strings if "U" is not
1505 the first active format:
1506
1507 isnt( v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000),
1508 "U* not first isn't Unicode" );
1509
1510 Mustn't forget to change the number of tests which appears at the top,
1511 or else the automated tester will get confused. This will either look
1512 like this:
1513
1514 print "1..156\n";
1515
1516 or this:
1517
1518 plan( tests => 156 );
1519
1520 We now compile up Perl, and run it through the test suite. Our new
1521 tests pass, hooray!
1522
1523 Finally, the documentation. The job is never done until the paperwork
1524 is over, so let's describe the change we've just made. The relevant
1525 place is pod/perlfunc.pod; again, we make a copy, and then we'll insert
1526 this text in the description of "pack":
1527
1528 =item *
1529
1530 If the pattern begins with a C<U>, the resulting string will be treated
1531 as UTF-8-encoded Unicode. You can force UTF-8 encoding on in a string
1532 with an initial C<U0>, and the bytes that follow will be interpreted as
1533 Unicode characters. If you don't want this to happen, you can begin your
1534 pattern with C<C0> (or anything else) to force Perl not to UTF-8 encode your
1535 string, and then follow this with a C<U*> somewhere in your pattern.
1536
1537 All done. Now let's create the patch. Porting/patching.pod tells us
1538 that if we're making major changes, we should copy the entire directory
1539 to somewhere safe before we begin fiddling, and then do
1540
1541 diff -ruN old new > patch
1542
1543 However, we know which files we've changed, and we can simply do this:
1544
1545 diff -u pp.c~ pp.c > patch
1546 diff -u t/op/pack.t~ t/op/pack.t >> patch
1547 diff -u pod/perlfunc.pod~ pod/perlfunc.pod >> patch
1548
1549 We end up with a patch looking a little like this:
1550
1551 --- pp.c~ Fri Jun 02 04:34:10 2000
1552 +++ pp.c Fri Jun 16 11:37:25 2000
1553 @@ -4375,6 +4375,7 @@
1554 register I32 items;
1555 STRLEN fromlen;
1556 register char *pat = SvPVx(*++MARK, fromlen);
1557 + char *patcopy;
1558 register char *patend = pat + fromlen;
1559 register I32 len;
1560 I32 datumtype;
1561 @@ -4405,6 +4406,7 @@
1562 ...
1563
1564 And finally, we submit it, with our rationale, to perl5-porters. Job
1565 done!
1566
1567 Patching a core module
1568 This works just like patching anything else, with an extra
1569 consideration. Many core modules also live on CPAN. If this is so,
1570 patch the CPAN version instead of the core and send the patch off to
1571 the module maintainer (with a copy to p5p). This will help the module
1572 maintainer keep the CPAN version in sync with the core version without
1573 constantly scanning p5p.
1574
1575 The list of maintainers of core modules is usefully documented in
1576 Porting/Maintainers.pl.
1577
1578 Adding a new function to the core
1579 If, as part of a patch to fix a bug, or just because you have an
1580 especially good idea, you decide to add a new function to the core,
1581 discuss your ideas on p5p well before you start work. It may be that
1582 someone else has already attempted to do what you are considering and
1583 can give lots of good advice or even provide you with bits of code that
1584 they already started (but never finished).
1585
1586 You have to follow all of the advice given above for patching. It is
1587 extremely important to test any addition thoroughly and add new tests
1588 to explore all boundary conditions that your new function is expected
1589 to handle. If your new function is used only by one module (e.g.
1590 toke), then it should probably be named S_your_function (for static);
1591 on the other hand, if you expect it to accessible from other functions
1592 in Perl, you should name it Perl_your_function. See "Internal
1593 Functions" in perlguts for more details.
1594
1595 The location of any new code is also an important consideration. Don't
1596 just create a new top level .c file and put your code there; you would
1597 have to make changes to Configure (so the Makefile is created
1598 properly), as well as possibly lots of include files. This is strictly
1599 pumpking business.
1600
1601 It is better to add your function to one of the existing top level
1602 source code files, but your choice is complicated by the nature of the
1603 Perl distribution. Only the files that are marked as compiled static
1604 are located in the perl executable. Everything else is located in the
1605 shared library (or DLL if you are running under WIN32). So, for
1606 example, if a function was only used by functions located in toke.c,
1607 then your code can go in toke.c. If, however, you want to call the
1608 function from universal.c, then you should put your code in another
1609 location, for example util.c.
1610
1611 In addition to writing your c-code, you will need to create an
1612 appropriate entry in embed.pl describing your function, then run 'make
1613 regen_headers' to create the entries in the numerous header files that
1614 perl needs to compile correctly. See "Internal Functions" in perlguts
1615 for information on the various options that you can set in embed.pl.
1616 You will forget to do this a few (or many) times and you will get
1617 warnings during the compilation phase. Make sure that you mention this
1618 when you post your patch to P5P; the pumpking needs to know this.
1619
1620 When you write your new code, please be conscious of existing code
1621 conventions used in the perl source files. See perlstyle for details.
1622 Although most of the guidelines discussed seem to focus on Perl code,
1623 rather than c, they all apply (except when they don't ;). See also
1624 Porting/patching.pod file in the Perl source distribution for lots of
1625 details about both formatting and submitting patches of your changes.
1626
1627 Lastly, TEST TEST TEST TEST TEST any code before posting to p5p. Test
1628 on as many platforms as you can find. Test as many perl Configure
1629 options as you can (e.g. MULTIPLICITY). If you have profiling or
1630 memory tools, see "EXTERNAL TOOLS FOR DEBUGGING PERL" below for how to
1631 use them to further test your code. Remember that most of the people
1632 on P5P are doing this on their own time and don't have the time to
1633 debug your code.
1634
1635 Writing a test
1636 Every module and built-in function has an associated test file (or
1637 should...). If you add or change functionality, you have to write a
1638 test. If you fix a bug, you have to write a test so that bug never
1639 comes back. If you alter the docs, it would be nice to test what the
1640 new documentation says.
1641
1642 In short, if you submit a patch you probably also have to patch the
1643 tests.
1644
1645 For modules, the test file is right next to the module itself.
1646 lib/strict.t tests lib/strict.pm. This is a recent innovation, so
1647 there are some snags (and it would be wonderful for you to brush them
1648 out), but it basically works that way. Everything else lives in t/.
1649
1650 If you add a new test directory under t/, it is imperative that you add
1651 that directory to t/HARNESS and t/TEST.
1652
1653 t/base/
1654 Testing of the absolute basic functionality of Perl. Things like
1655 "if", basic file reads and writes, simple regexes, etc. These are
1656 run first in the test suite and if any of them fail, something is
1657 really broken.
1658
1659 t/cmd/
1660 These test the basic control structures, "if/else", "while",
1661 subroutines, etc.
1662
1663 t/comp/
1664 Tests basic issues of how Perl parses and compiles itself.
1665
1666 t/io/
1667 Tests for built-in IO functions, including command line arguments.
1668
1669 t/lib/
1670 The old home for the module tests, you shouldn't put anything new in
1671 here. There are still some bits and pieces hanging around in here
1672 that need to be moved. Perhaps you could move them? Thanks!
1673
1674 t/mro/
1675 Tests for perl's method resolution order implementations (see mro).
1676
1677 t/op/
1678 Tests for perl's built in functions that don't fit into any of the
1679 other directories.
1680
1681 t/pod/
1682 Tests for POD directives. There are still some tests for the Pod
1683 modules hanging around in here that need to be moved out into lib/.
1684
1685 t/run/
1686 Testing features of how perl actually runs, including exit codes and
1687 handling of PERL* environment variables.
1688
1689 t/uni/
1690 Tests for the core support of Unicode.
1691
1692 t/win32/
1693 Windows-specific tests.
1694
1695 t/x2p
1696 A test suite for the s2p converter.
1697
1698 The core uses the same testing style as the rest of Perl, a simple
1699 "ok/not ok" run through Test::Harness, but there are a few special
1700 considerations.
1701
1702 There are three ways to write a test in the core. Test::More,
1703 t/test.pl and ad hoc "print $test ? "ok 42\n" : "not ok 42\n"". The
1704 decision of which to use depends on what part of the test suite you're
1705 working on. This is a measure to prevent a high-level failure (such as
1706 Config.pm breaking) from causing basic functionality tests to fail.
1707
1708 t/base t/comp
1709 Since we don't know if require works, or even subroutines, use ad
1710 hoc tests for these two. Step carefully to avoid using the feature
1711 being tested.
1712
1713 t/cmd t/run t/io t/op
1714 Now that basic require() and subroutines are tested, you can use
1715 the t/test.pl library which emulates the important features of
1716 Test::More while using a minimum of core features.
1717
1718 You can also conditionally use certain libraries like Config, but
1719 be sure to skip the test gracefully if it's not there.
1720
1721 t/lib ext lib
1722 Now that the core of Perl is tested, Test::More can be used. You
1723 can also use the full suite of core modules in the tests.
1724
1725 When you say "make test" Perl uses the t/TEST program to run the test
1726 suite (except under Win32 where it uses t/harness instead.) All tests
1727 are run from the t/ directory, not the directory which contains the
1728 test. This causes some problems with the tests in lib/, so here's some
1729 opportunity for some patching.
1730
1731 You must be triply conscious of cross-platform concerns. This usually
1732 boils down to using File::Spec and avoiding things like "fork()" and
1733 "system()" unless absolutely necessary.
1734
1735 Special Make Test Targets
1736 There are various special make targets that can be used to test Perl
1737 slightly differently than the standard "test" target. Not all them are
1738 expected to give a 100% success rate. Many of them have several
1739 aliases, and many of them are not available on certain operating
1740 systems.
1741
1742 coretest
1743 Run perl on all core tests (t/* and lib/[a-z]* pragma tests).
1744
1745 (Not available on Win32)
1746
1747 test.deparse
1748 Run all the tests through B::Deparse. Not all tests will succeed.
1749
1750 (Not available on Win32)
1751
1752 test.taintwarn
1753 Run all tests with the -t command-line switch. Not all tests are
1754 expected to succeed (until they're specifically fixed, of course).
1755
1756 (Not available on Win32)
1757
1758 minitest
1759 Run miniperl on t/base, t/comp, t/cmd, t/run, t/io, t/op, t/uni and
1760 t/mro tests.
1761
1762 test.valgrind check.valgrind utest.valgrind ucheck.valgrind
1763 (Only in Linux) Run all the tests using the memory leak + naughty
1764 memory access tool "valgrind". The log files will be named
1765 testname.valgrind.
1766
1767 test.third check.third utest.third ucheck.third
1768 (Only in Tru64) Run all the tests using the memory leak + naughty
1769 memory access tool "Third Degree". The log files will be named
1770 perl.3log.testname.
1771
1772 test.torture torturetest
1773 Run all the usual tests and some extra tests. As of Perl 5.8.0 the
1774 only extra tests are Abigail's JAPHs, t/japh/abigail.t.
1775
1776 You can also run the torture test with t/harness by giving
1777 "-torture" argument to t/harness.
1778
1779 utest ucheck test.utf8 check.utf8
1780 Run all the tests with -Mutf8. Not all tests will succeed.
1781
1782 (Not available on Win32)
1783
1784 minitest.utf16 test.utf16
1785 Runs the tests with UTF-16 encoded scripts, encoded with different
1786 versions of this encoding.
1787
1788 "make utest.utf16" runs the test suite with a combination of
1789 "-utf8" and "-utf16" arguments to t/TEST.
1790
1791 (Not available on Win32)
1792
1793 test_harness
1794 Run the test suite with the t/harness controlling program, instead
1795 of t/TEST. t/harness is more sophisticated, and uses the
1796 Test::Harness module, thus using this test target supposes that
1797 perl mostly works. The main advantage for our purposes is that it
1798 prints a detailed summary of failed tests at the end. Also, unlike
1799 t/TEST, it doesn't redirect stderr to stdout.
1800
1801 Note that under Win32 t/harness is always used instead of t/TEST,
1802 so there is no special "test_harness" target.
1803
1804 Under Win32's "test" target you may use the TEST_SWITCHES and
1805 TEST_FILES environment variables to control the behaviour of
1806 t/harness. This means you can say
1807
1808 nmake test TEST_FILES="op/*.t"
1809 nmake test TEST_SWITCHES="-torture" TEST_FILES="op/*.t"
1810
1811 test-notty test_notty
1812 Sets PERL_SKIP_TTY_TEST to true before running normal test.
1813
1814 Running tests by hand
1815 You can run part of the test suite by hand by using one the following
1816 commands from the t/ directory :
1817
1818 ./perl -I../lib TEST list-of-.t-files
1819
1820 or
1821
1822 ./perl -I../lib harness list-of-.t-files
1823
1824 (if you don't specify test scripts, the whole test suite will be run.)
1825
1826 Using t/harness for testing
1827
1828 If you use "harness" for testing you have several command line options
1829 available to you. The arguments are as follows, and are in the order
1830 that they must appear if used together.
1831
1832 harness -v -torture -re=pattern LIST OF FILES TO TEST
1833 harness -v -torture -re LIST OF PATTERNS TO MATCH
1834
1835 If "LIST OF FILES TO TEST" is omitted the file list is obtained from
1836 the manifest. The file list may include shell wildcards which will be
1837 expanded out.
1838
1839 -v Run the tests under verbose mode so you can see what tests were
1840 run, and debug output.
1841
1842 -torture
1843 Run the torture tests as well as the normal set.
1844
1845 -re=PATTERN
1846 Filter the file list so that all the test files run match PATTERN.
1847 Note that this form is distinct from the -re LIST OF PATTERNS form
1848 below in that it allows the file list to be provided as well.
1849
1850 -re LIST OF PATTERNS
1851 Filter the file list so that all the test files run match
1852 /(LIST|OF|PATTERNS)/. Note that with this form the patterns are
1853 joined by '|' and you cannot supply a list of files, instead the
1854 test files are obtained from the MANIFEST.
1855
1856 You can run an individual test by a command similar to
1857
1858 ./perl -I../lib patho/to/foo.t
1859
1860 except that the harnesses set up some environment variables that may
1861 affect the execution of the test :
1862
1863 PERL_CORE=1
1864 indicates that we're running this test part of the perl core test
1865 suite. This is useful for modules that have a dual life on CPAN.
1866
1867 PERL_DESTRUCT_LEVEL=2
1868 is set to 2 if it isn't set already (see "PERL_DESTRUCT_LEVEL")
1869
1870 PERL
1871 (used only by t/TEST) if set, overrides the path to the perl
1872 executable that should be used to run the tests (the default being
1873 ./perl).
1874
1875 PERL_SKIP_TTY_TEST
1876 if set, tells to skip the tests that need a terminal. It's actually
1877 set automatically by the Makefile, but can also be forced
1878 artificially by running 'make test_notty'.
1879
1880 Other environment variables that may influence tests
1881
1882 PERL_TEST_Net_Ping
1883 Setting this variable runs all the Net::Ping modules tests,
1884 otherwise some tests that interact with the outside world are
1885 skipped. See perl58delta.
1886
1887 PERL_TEST_NOVREXX
1888 Setting this variable skips the vrexx.t tests for OS2::REXX.
1889
1890 PERL_TEST_NUMCONVERTS
1891 This sets a variable in op/numconvert.t.
1892
1893 See also the documentation for the Test and Test::Harness modules, for
1894 more environment variables that affect testing.
1895
1896 Common problems when patching Perl source code
1897 Perl source plays by ANSI C89 rules: no C99 (or C++) extensions. In
1898 some cases we have to take pre-ANSI requirements into consideration.
1899 You don't care about some particular platform having broken Perl? I
1900 hear there is still a strong demand for J2EE programmers.
1901
1902 Perl environment problems
1903 · Not compiling with threading
1904
1905 Compiling with threading (-Duseithreads) completely rewrites the
1906 function prototypes of Perl. You better try your changes with
1907 that. Related to this is the difference between "Perl_-less" and
1908 "Perl_-ly" APIs, for example:
1909
1910 Perl_sv_setiv(aTHX_ ...);
1911 sv_setiv(...);
1912
1913 The first one explicitly passes in the context, which is needed for
1914 e.g. threaded builds. The second one does that implicitly; do not
1915 get them mixed. If you are not passing in a aTHX_, you will need
1916 to do a dTHX (or a dVAR) as the first thing in the function.
1917
1918 See "How multiple interpreters and concurrency are supported" in
1919 perlguts for further discussion about context.
1920
1921 · Not compiling with -DDEBUGGING
1922
1923 The DEBUGGING define exposes more code to the compiler, therefore
1924 more ways for things to go wrong. You should try it.
1925
1926 · Introducing (non-read-only) globals
1927
1928 Do not introduce any modifiable globals, truly global or file
1929 static. They are bad form and complicate multithreading and other
1930 forms of concurrency. The right way is to introduce them as new
1931 interpreter variables, see intrpvar.h (at the very end for binary
1932 compatibility).
1933
1934 Introducing read-only (const) globals is okay, as long as you
1935 verify with e.g. "nm libperl.a|egrep -v ' [TURtr] '" (if your "nm"
1936 has BSD-style output) that the data you added really is read-only.
1937 (If it is, it shouldn't show up in the output of that command.)
1938
1939 If you want to have static strings, make them constant:
1940
1941 static const char etc[] = "...";
1942
1943 If you want to have arrays of constant strings, note carefully the
1944 right combination of "const"s:
1945
1946 static const char * const yippee[] =
1947 {"hi", "ho", "silver"};
1948
1949 There is a way to completely hide any modifiable globals (they are
1950 all moved to heap), the compilation setting
1951 "-DPERL_GLOBAL_STRUCT_PRIVATE". It is not normally used, but can
1952 be used for testing, read more about it in "Background and
1953 PERL_IMPLICIT_CONTEXT" in perlguts.
1954
1955 · Not exporting your new function
1956
1957 Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any
1958 function that is part of the public API (the shared Perl library)
1959 to be explicitly marked as exported. See the discussion about
1960 embed.pl in perlguts.
1961
1962 · Exporting your new function
1963
1964 The new shiny result of either genuine new functionality or your
1965 arduous refactoring is now ready and correctly exported. So what
1966 could possibly go wrong?
1967
1968 Maybe simply that your function did not need to be exported in the
1969 first place. Perl has a long and not so glorious history of
1970 exporting functions that it should not have.
1971
1972 If the function is used only inside one source code file, make it
1973 static. See the discussion about embed.pl in perlguts.
1974
1975 If the function is used across several files, but intended only for
1976 Perl's internal use (and this should be the common case), do not
1977 export it to the public API. See the discussion about embed.pl in
1978 perlguts.
1979
1980 Portability problems
1981 The following are common causes of compilation and/or execution
1982 failures, not common to Perl as such. The C FAQ is good bedtime
1983 reading. Please test your changes with as many C compilers and
1984 platforms as possible -- we will, anyway, and it's nice to save oneself
1985 from public embarrassment.
1986
1987 If using gcc, you can add the "-std=c89" option which will hopefully
1988 catch most of these unportabilities. (However it might also catch
1989 incompatibilities in your system's header files.)
1990
1991 Use the Configure "-Dgccansipedantic" flag to enable the gcc "-ansi
1992 -pedantic" flags which enforce stricter ANSI rules.
1993
1994 If using the "gcc -Wall" note that not all the possible warnings (like
1995 "-Wunitialized") are given unless you also compile with "-O".
1996
1997 Note that if using gcc, starting from Perl 5.9.5 the Perl core source
1998 code files (the ones at the top level of the source code distribution,
1999 but not e.g. the extensions under ext/) are automatically compiled with
2000 as many as possible of the "-std=c89", "-ansi", "-pedantic", and a
2001 selection of "-W" flags (see cflags.SH).
2002
2003 Also study perlport carefully to avoid any bad assumptions about the
2004 operating system, filesystems, and so forth.
2005
2006 You may once in a while try a "make microperl" to see whether we can
2007 still compile Perl with just the bare minimum of interfaces. (See
2008 README.micro.)
2009
2010 Do not assume an operating system indicates a certain compiler.
2011
2012 · Casting pointers to integers or casting integers to pointers
2013
2014 void castaway(U8* p)
2015 {
2016 IV i = p;
2017
2018 or
2019
2020 void castaway(U8* p)
2021 {
2022 IV i = (IV)p;
2023
2024 Both are bad, and broken, and unportable. Use the PTR2IV() macro
2025 that does it right. (Likewise, there are PTR2UV(), PTR2NV(),
2026 INT2PTR(), and NUM2PTR().)
2027
2028 · Casting between data function pointers and data pointers
2029
2030 Technically speaking casting between function pointers and data
2031 pointers is unportable and undefined, but practically speaking it
2032 seems to work, but you should use the FPTR2DPTR() and DPTR2FPTR()
2033 macros. Sometimes you can also play games with unions.
2034
2035 · Assuming sizeof(int) == sizeof(long)
2036
2037 There are platforms where longs are 64 bits, and platforms where
2038 ints are 64 bits, and while we are out to shock you, even platforms
2039 where shorts are 64 bits. This is all legal according to the C
2040 standard. (In other words, "long long" is not a portable way to
2041 specify 64 bits, and "long long" is not even guaranteed to be any
2042 wider than "long".)
2043
2044 Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth.
2045 Avoid things like I32 because they are not guaranteed to be exactly
2046 32 bits, they are at least 32 bits, nor are they guaranteed to be
2047 int or long. If you really explicitly need 64-bit variables, use
2048 I64 and U64, but only if guarded by HAS_QUAD.
2049
2050 · Assuming one can dereference any type of pointer for any type of
2051 data
2052
2053 char *p = ...;
2054 long pony = *p; /* BAD */
2055
2056 Many platforms, quite rightly so, will give you a core dump instead
2057 of a pony if the p happens not be correctly aligned.
2058
2059 · Lvalue casts
2060
2061 (int)*p = ...; /* BAD */
2062
2063 Simply not portable. Get your lvalue to be of the right type, or
2064 maybe use temporary variables, or dirty tricks with unions.
2065
2066 · Assume anything about structs (especially the ones you don't
2067 control, like the ones coming from the system headers)
2068
2069 · That a certain field exists in a struct
2070
2071 · That no other fields exist besides the ones you know of
2072
2073 · That a field is of certain signedness, sizeof, or type
2074
2075 · That the fields are in a certain order
2076
2077 · While C guarantees the ordering specified in the
2078 struct definition, between different platforms the
2079 definitions might differ
2080
2081 · That the sizeof(struct) or the alignments are the same
2082 everywhere
2083
2084 · There might be padding bytes between the fields to
2085 align the fields - the bytes can be anything
2086
2087 · Structs are required to be aligned to the maximum
2088 alignment required by the fields - which for native
2089 types is for usually equivalent to sizeof() of the
2090 field
2091
2092 · Assuming the character set is ASCIIish
2093
2094 Perl can compile and run under EBCDIC platforms. See perlebcdic.
2095 This is transparent for the most part, but because the character
2096 sets differ, you shouldn't use numeric (decimal, octal, nor hex)
2097 constants to refer to characters. You can safely say 'A', but not
2098 0x41. You can safely say '\n', but not \012. If a character
2099 doesn't have a trivial input form, you can create a #define for it
2100 in both "utfebcdic.h" and "utf8.h", so that it resolves to
2101 different values depending on the character set being used. (There
2102 are three different EBCDIC character sets defined in "utfebcdic.h",
2103 so it might be best to insert the #define three times in that
2104 file.)
2105
2106 Also, the range 'A' - 'Z' in ASCII is an unbroken sequence of 26
2107 upper case alphabetic characters. That is not true in EBCDIC. Nor
2108 for 'a' to 'z'. But '0' - '9' is an unbroken range in both
2109 systems. Don't assume anything about other ranges.
2110
2111 Many of the comments in the existing code ignore the possibility of
2112 EBCDIC, and may be wrong therefore, even if the code works. This
2113 is actually a tribute to the successful transparent insertion of
2114 being able to handle EBCDIC without having to change pre-existing
2115 code.
2116
2117 UTF-8 and UTF-EBCDIC are two different encodings used to represent
2118 Unicode code points as sequences of bytes. Macros with the same
2119 names (but different definitions) in "utf8.h" and "utfebcdic.h" are
2120 used to allow the calling code to think that there is only one such
2121 encoding. This is almost always referred to as "utf8", but it
2122 means the EBCDIC version as well. Again, comments in the code may
2123 well be wrong even if the code itself is right. For example, the
2124 concept of "invariant characters" differs between ASCII and EBCDIC.
2125 On ASCII platforms, only characters that do not have the high-order
2126 bit set (i.e. whose ordinals are strict ASCII, 0 - 127) are
2127 invariant, and the documentation and comments in the code may
2128 assume that, often referring to something like, say, "hibit". The
2129 situation differs and is not so simple on EBCDIC machines, but as
2130 long as the code itself uses the "NATIVE_IS_INVARIANT()" macro
2131 appropriately, it works, even if the comments are wrong.
2132
2133 · Assuming the character set is just ASCII
2134
2135 ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128
2136 extra characters have different meanings depending on the locale.
2137 Absent a locale, currently these extra characters are generally
2138 considered to be unassigned, and this has presented some problems.
2139 This is scheduled to be changed in 5.12 so that these characters
2140 will be considered to be Latin-1 (ISO-8859-1).
2141
2142 · Mixing #define and #ifdef
2143
2144 #define BURGLE(x) ... \
2145 #ifdef BURGLE_OLD_STYLE /* BAD */
2146 ... do it the old way ... \
2147 #else
2148 ... do it the new way ... \
2149 #endif
2150
2151 You cannot portably "stack" cpp directives. For example in the
2152 above you need two separate BURGLE() #defines, one for each #ifdef
2153 branch.
2154
2155 · Adding non-comment stuff after #endif or #else
2156
2157 #ifdef SNOSH
2158 ...
2159 #else !SNOSH /* BAD */
2160 ...
2161 #endif SNOSH /* BAD */
2162
2163 The #endif and #else cannot portably have anything non-comment
2164 after them. If you want to document what is going (which is a good
2165 idea especially if the branches are long), use (C) comments:
2166
2167 #ifdef SNOSH
2168 ...
2169 #else /* !SNOSH */
2170 ...
2171 #endif /* SNOSH */
2172
2173 The gcc option "-Wendif-labels" warns about the bad variant (by
2174 default on starting from Perl 5.9.4).
2175
2176 · Having a comma after the last element of an enum list
2177
2178 enum color {
2179 CERULEAN,
2180 CHARTREUSE,
2181 CINNABAR, /* BAD */
2182 };
2183
2184 is not portable. Leave out the last comma.
2185
2186 Also note that whether enums are implicitly morphable to ints
2187 varies between compilers, you might need to (int).
2188
2189 · Using //-comments
2190
2191 // This function bamfoodles the zorklator. /* BAD */
2192
2193 That is C99 or C++. Perl is C89. Using the //-comments is
2194 silently allowed by many C compilers but cranking up the ANSI C89
2195 strictness (which we like to do) causes the compilation to fail.
2196
2197 · Mixing declarations and code
2198
2199 void zorklator()
2200 {
2201 int n = 3;
2202 set_zorkmids(n); /* BAD */
2203 int q = 4;
2204
2205 That is C99 or C++. Some C compilers allow that, but you
2206 shouldn't.
2207
2208 The gcc option "-Wdeclaration-after-statements" scans for such
2209 problems (by default on starting from Perl 5.9.4).
2210
2211 · Introducing variables inside for()
2212
2213 for(int i = ...; ...; ...) { /* BAD */
2214
2215 That is C99 or C++. While it would indeed be awfully nice to have
2216 that also in C89, to limit the scope of the loop variable, alas, we
2217 cannot.
2218
2219 · Mixing signed char pointers with unsigned char pointers
2220
2221 int foo(char *s) { ... }
2222 ...
2223 unsigned char *t = ...; /* Or U8* t = ... */
2224 foo(t); /* BAD */
2225
2226 While this is legal practice, it is certainly dubious, and
2227 downright fatal in at least one platform: for example VMS cc
2228 considers this a fatal error. One cause for people often making
2229 this mistake is that a "naked char" and therefore dereferencing a
2230 "naked char pointer" have an undefined signedness: it depends on
2231 the compiler and the flags of the compiler and the underlying
2232 platform whether the result is signed or unsigned. For this very
2233 same reason using a 'char' as an array index is bad.
2234
2235 · Macros that have string constants and their arguments as substrings
2236 of the string constants
2237
2238 #define FOO(n) printf("number = %d\n", n) /* BAD */
2239 FOO(10);
2240
2241 Pre-ANSI semantics for that was equivalent to
2242
2243 printf("10umber = %d\10");
2244
2245 which is probably not what you were expecting. Unfortunately at
2246 least one reasonably common and modern C compiler does "real
2247 backward compatibility" here, in AIX that is what still happens
2248 even though the rest of the AIX compiler is very happily C89.
2249
2250 · Using printf formats for non-basic C types
2251
2252 IV i = ...;
2253 printf("i = %d\n", i); /* BAD */
2254
2255 While this might by accident work in some platform (where IV
2256 happens to be an "int"), in general it cannot. IV might be
2257 something larger. Even worse the situation is with more specific
2258 types (defined by Perl's configuration step in config.h):
2259
2260 Uid_t who = ...;
2261 printf("who = %d\n", who); /* BAD */
2262
2263 The problem here is that Uid_t might be not only not "int"-wide but
2264 it might also be unsigned, in which case large uids would be
2265 printed as negative values.
2266
2267 There is no simple solution to this because of printf()'s limited
2268 intelligence, but for many types the right format is available as
2269 with either 'f' or '_f' suffix, for example:
2270
2271 IVdf /* IV in decimal */
2272 UVxf /* UV is hexadecimal */
2273
2274 printf("i = %"IVdf"\n", i); /* The IVdf is a string constant. */
2275
2276 Uid_t_f /* Uid_t in decimal */
2277
2278 printf("who = %"Uid_t_f"\n", who);
2279
2280 Or you can try casting to a "wide enough" type:
2281
2282 printf("i = %"IVdf"\n", (IV)something_very_small_and_signed);
2283
2284 Also remember that the %p format really does require a void
2285 pointer:
2286
2287 U8* p = ...;
2288 printf("p = %p\n", (void*)p);
2289
2290 The gcc option "-Wformat" scans for such problems.
2291
2292 · Blindly using variadic macros
2293
2294 gcc has had them for a while with its own syntax, and C99 brought
2295 them with a standardized syntax. Don't use the former, and use the
2296 latter only if the HAS_C99_VARIADIC_MACROS is defined.
2297
2298 · Blindly passing va_list
2299
2300 Not all platforms support passing va_list to further varargs
2301 (stdarg) functions. The right thing to do is to copy the va_list
2302 using the Perl_va_copy() if the NEED_VA_COPY is defined.
2303
2304 · Using gcc statement expressions
2305
2306 val = ({...;...;...}); /* BAD */
2307
2308 While a nice extension, it's not portable. The Perl code does
2309 admittedly use them if available to gain some extra speed
2310 (essentially as a funky form of inlining), but you shouldn't.
2311
2312 · Binding together several statements in a macro
2313
2314 Use the macros STMT_START and STMT_END.
2315
2316 STMT_START {
2317 ...
2318 } STMT_END
2319
2320 · Testing for operating systems or versions when should be testing
2321 for features
2322
2323 #ifdef __FOONIX__ /* BAD */
2324 foo = quux();
2325 #endif
2326
2327 Unless you know with 100% certainty that quux() is only ever
2328 available for the "Foonix" operating system and that is available
2329 and correctly working for all past, present, and future versions of
2330 "Foonix", the above is very wrong. This is more correct (though
2331 still not perfect, because the below is a compile-time check):
2332
2333 #ifdef HAS_QUUX
2334 foo = quux();
2335 #endif
2336
2337 How does the HAS_QUUX become defined where it needs to be? Well,
2338 if Foonix happens to be UNIXy enough to be able to run the
2339 Configure script, and Configure has been taught about detecting and
2340 testing quux(), the HAS_QUUX will be correctly defined. In other
2341 platforms, the corresponding configuration step will hopefully do
2342 the same.
2343
2344 In a pinch, if you cannot wait for Configure to be educated, or if
2345 you have a good hunch of where quux() might be available, you can
2346 temporarily try the following:
2347
2348 #if (defined(__FOONIX__) || defined(__BARNIX__))
2349 # define HAS_QUUX
2350 #endif
2351
2352 ...
2353
2354 #ifdef HAS_QUUX
2355 foo = quux();
2356 #endif
2357
2358 But in any case, try to keep the features and operating systems
2359 separate.
2360
2361 Problematic System Interfaces
2362 · malloc(0), realloc(0), calloc(0, 0) are non-portable. To be
2363 portable allocate at least one byte. (In general you should rarely
2364 need to work at this low level, but instead use the various malloc
2365 wrappers.)
2366
2367 · snprintf() - the return type is unportable. Use my_snprintf()
2368 instead.
2369
2370 Security problems
2371 Last but not least, here are various tips for safer coding.
2372
2373 · Do not use gets()
2374
2375 Or we will publicly ridicule you. Seriously.
2376
2377 · Do not use strcpy() or strcat() or strncpy() or strncat()
2378
2379 Use my_strlcpy() and my_strlcat() instead: they either use the
2380 native implementation, or Perl's own implementation (borrowed from
2381 the public domain implementation of INN).
2382
2383 · Do not use sprintf() or vsprintf()
2384
2385 If you really want just plain byte strings, use my_snprintf() and
2386 my_vsnprintf() instead, which will try to use snprintf() and
2387 vsnprintf() if those safer APIs are available. If you want
2388 something fancier than a plain byte string, use SVs and
2389 Perl_sv_catpvf().
2390
2392 Sometimes it helps to use external tools while debugging and testing
2393 Perl. This section tries to guide you through using some common
2394 testing and debugging tools with Perl. This is meant as a guide to
2395 interfacing these tools with Perl, not as any kind of guide to the use
2396 of the tools themselves.
2397
2398 NOTE 1: Running under memory debuggers such as Purify, valgrind, or
2399 Third Degree greatly slows down the execution: seconds become minutes,
2400 minutes become hours. For example as of Perl 5.8.1, the
2401 ext/Encode/t/Unicode.t takes extraordinarily long to complete under
2402 e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more
2403 than six hours, even on a snappy computer-- the said test must be doing
2404 something that is quite unfriendly for memory debuggers. If you don't
2405 feel like waiting, that you can simply kill away the perl process.
2406
2407 NOTE 2: To minimize the number of memory leak false alarms (see
2408 "PERL_DESTRUCT_LEVEL" for more information), you have to have
2409 environment variable PERL_DESTRUCT_LEVEL set to 2. The TEST and
2410 harness scripts do that automatically. But if you are running some of
2411 the tests manually-- for csh-like shells:
2412
2413 setenv PERL_DESTRUCT_LEVEL 2
2414
2415 and for Bourne-type shells:
2416
2417 PERL_DESTRUCT_LEVEL=2
2418 export PERL_DESTRUCT_LEVEL
2419
2420 or in UNIXy environments you can also use the "env" command:
2421
2422 env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ...
2423
2424 NOTE 3: There are known memory leaks when there are compile-time errors
2425 within eval or require, seeing "S_doeval" in the call stack is a good
2426 sign of these. Fixing these leaks is non-trivial, unfortunately, but
2427 they must be fixed eventually.
2428
2429 NOTE 4: DynaLoader will not clean up after itself completely unless
2430 Perl is built with the Configure option
2431 "-Accflags=-DDL_UNLOAD_ALL_AT_EXIT".
2432
2433 Rational Software's Purify
2434 Purify is a commercial tool that is helpful in identifying memory
2435 overruns, wild pointers, memory leaks and other such badness. Perl
2436 must be compiled in a specific way for optimal testing with Purify.
2437 Purify is available under Windows NT, Solaris, HP-UX, SGI, and Siemens
2438 Unix.
2439
2440 Purify on Unix
2441 On Unix, Purify creates a new Perl binary. To get the most benefit out
2442 of Purify, you should create the perl to Purify using:
2443
2444 sh Configure -Accflags=-DPURIFY -Doptimize='-g' \
2445 -Uusemymalloc -Dusemultiplicity
2446
2447 where these arguments mean:
2448
2449 -Accflags=-DPURIFY
2450 Disables Perl's arena memory allocation functions, as well as
2451 forcing use of memory allocation functions derived from the system
2452 malloc.
2453
2454 -Doptimize='-g'
2455 Adds debugging information so that you see the exact source
2456 statements where the problem occurs. Without this flag, all you
2457 will see is the source filename of where the error occurred.
2458
2459 -Uusemymalloc
2460 Disable Perl's malloc so that Purify can more closely monitor
2461 allocations and leaks. Using Perl's malloc will make Purify report
2462 most leaks in the "potential" leaks category.
2463
2464 -Dusemultiplicity
2465 Enabling the multiplicity option allows perl to clean up thoroughly
2466 when the interpreter shuts down, which reduces the number of bogus
2467 leak reports from Purify.
2468
2469 Once you've compiled a perl suitable for Purify'ing, then you can just:
2470
2471 make pureperl
2472
2473 which creates a binary named 'pureperl' that has been Purify'ed. This
2474 binary is used in place of the standard 'perl' binary when you want to
2475 debug Perl memory problems.
2476
2477 As an example, to show any memory leaks produced during the standard
2478 Perl testset you would create and run the Purify'ed perl as:
2479
2480 make pureperl
2481 cd t
2482 ../pureperl -I../lib harness
2483
2484 which would run Perl on test.pl and report any memory problems.
2485
2486 Purify outputs messages in "Viewer" windows by default. If you don't
2487 have a windowing environment or if you simply want the Purify output to
2488 unobtrusively go to a log file instead of to the interactive window,
2489 use these following options to output to the log file "perl.log":
2490
2491 setenv PURIFYOPTIONS "-chain-length=25 -windows=no \
2492 -log-file=perl.log -append-logfile=yes"
2493
2494 If you plan to use the "Viewer" windows, then you only need this
2495 option:
2496
2497 setenv PURIFYOPTIONS "-chain-length=25"
2498
2499 In Bourne-type shells:
2500
2501 PURIFYOPTIONS="..."
2502 export PURIFYOPTIONS
2503
2504 or if you have the "env" utility:
2505
2506 env PURIFYOPTIONS="..." ../pureperl ...
2507
2508 Purify on NT
2509 Purify on Windows NT instruments the Perl binary 'perl.exe' on the fly.
2510 There are several options in the makefile you should change to get the
2511 most use out of Purify:
2512
2513 DEFINES
2514 You should add -DPURIFY to the DEFINES line so the DEFINES line
2515 looks something like:
2516
2517 DEFINES = -DWIN32 -D_CONSOLE -DNO_STRICT $(CRYPT_FLAG) -DPURIFY=1
2518
2519 to disable Perl's arena memory allocation functions, as well as to
2520 force use of memory allocation functions derived from the system
2521 malloc.
2522
2523 USE_MULTI = define
2524 Enabling the multiplicity option allows perl to clean up thoroughly
2525 when the interpreter shuts down, which reduces the number of bogus
2526 leak reports from Purify.
2527
2528 #PERL_MALLOC = define
2529 Disable Perl's malloc so that Purify can more closely monitor
2530 allocations and leaks. Using Perl's malloc will make Purify report
2531 most leaks in the "potential" leaks category.
2532
2533 CFG = Debug
2534 Adds debugging information so that you see the exact source
2535 statements where the problem occurs. Without this flag, all you
2536 will see is the source filename of where the error occurred.
2537
2538 As an example, to show any memory leaks produced during the standard
2539 Perl testset you would create and run Purify as:
2540
2541 cd win32
2542 make
2543 cd ../t
2544 purify ../perl -I../lib harness
2545
2546 which would instrument Perl in memory, run Perl on test.pl, then
2547 finally report any memory problems.
2548
2549 valgrind
2550 The excellent valgrind tool can be used to find out both memory leaks
2551 and illegal memory accesses. As of version 3.3.0, Valgrind only
2552 supports Linux on x86, x86-64 and PowerPC. The special "test.valgrind"
2553 target can be used to run the tests under valgrind. Found errors and
2554 memory leaks are logged in files named testfile.valgrind.
2555
2556 Valgrind also provides a cachegrind tool, invoked on perl as:
2557
2558 VG_OPTS=--tool=cachegrind make test.valgrind
2559
2560 As system libraries (most notably glibc) are also triggering errors,
2561 valgrind allows to suppress such errors using suppression files. The
2562 default suppression file that comes with valgrind already catches a lot
2563 of them. Some additional suppressions are defined in t/perl.supp.
2564
2565 To get valgrind and for more information see
2566
2567 http://developer.kde.org/~sewardj/
2568
2569 Compaq's/Digital's/HP's Third Degree
2570 Third Degree is a tool for memory leak detection and memory access
2571 checks. It is one of the many tools in the ATOM toolkit. The toolkit
2572 is only available on Tru64 (formerly known as Digital UNIX formerly
2573 known as DEC OSF/1).
2574
2575 When building Perl, you must first run Configure with -Doptimize=-g and
2576 -Uusemymalloc flags, after that you can use the make targets
2577 "perl.third" and "test.third". (What is required is that Perl must be
2578 compiled using the "-g" flag, you may need to re-Configure.)
2579
2580 The short story is that with "atom" you can instrument the Perl
2581 executable to create a new executable called perl.third. When the
2582 instrumented executable is run, it creates a log of dubious memory
2583 traffic in file called perl.3log. See the manual pages of atom and
2584 third for more information. The most extensive Third Degree
2585 documentation is available in the Compaq "Tru64 UNIX Programmer's
2586 Guide", chapter "Debugging Programs with Third Degree".
2587
2588 The "test.third" leaves a lot of files named foo_bar.3log in the t/
2589 subdirectory. There is a problem with these files: Third Degree is so
2590 effective that it finds problems also in the system libraries.
2591 Therefore you should used the Porting/thirdclean script to cleanup the
2592 *.3log files.
2593
2594 There are also leaks that for given certain definition of a leak,
2595 aren't. See "PERL_DESTRUCT_LEVEL" for more information.
2596
2597 PERL_DESTRUCT_LEVEL
2598 If you want to run any of the tests yourself manually using e.g.
2599 valgrind, or the pureperl or perl.third executables, please note that
2600 by default perl does not explicitly cleanup all the memory it has
2601 allocated (such as global memory arenas) but instead lets the exit() of
2602 the whole program "take care" of such allocations, also known as
2603 "global destruction of objects".
2604
2605 There is a way to tell perl to do complete cleanup: set the environment
2606 variable PERL_DESTRUCT_LEVEL to a non-zero value. The t/TEST wrapper
2607 does set this to 2, and this is what you need to do too, if you don't
2608 want to see the "global leaks": For example, for "third-degreed" Perl:
2609
2610 env PERL_DESTRUCT_LEVEL=2 ./perl.third -Ilib t/foo/bar.t
2611
2612 (Note: the mod_perl apache module uses also this environment variable
2613 for its own purposes and extended its semantics. Refer to the mod_perl
2614 documentation for more information. Also, spawned threads do the
2615 equivalent of setting this variable to the value 1.)
2616
2617 If, at the end of a run you get the message N scalars leaked, you can
2618 recompile with "-DDEBUG_LEAKING_SCALARS", which will cause the
2619 addresses of all those leaked SVs to be dumped along with details as to
2620 where each SV was originally allocated. This information is also
2621 displayed by Devel::Peek. Note that the extra details recorded with
2622 each SV increases memory usage, so it shouldn't be used in production
2623 environments. It also converts "new_SV()" from a macro into a real
2624 function, so you can use your favourite debugger to discover where
2625 those pesky SVs were allocated.
2626
2627 If you see that you're leaking memory at runtime, but neither valgrind
2628 nor "-DDEBUG_LEAKING_SCALARS" will find anything, you're probably
2629 leaking SVs that are still reachable and will be properly cleaned up
2630 during destruction of the interpreter. In such cases, using the "-Dm"
2631 switch can point you to the source of the leak. If the executable was
2632 built with "-DDEBUG_LEAKING_SCALARS", "-Dm" will output SV allocations
2633 in addition to memory allocations. Each SV allocation has a distinct
2634 serial number that will be written on creation and destruction of the
2635 SV. So if you're executing the leaking code in a loop, you need to
2636 look for SVs that are created, but never destroyed between each cycle.
2637 If such an SV is found, set a conditional breakpoint within "new_SV()"
2638 and make it break only when "PL_sv_serial" is equal to the serial
2639 number of the leaking SV. Then you will catch the interpreter in
2640 exactly the state where the leaking SV is allocated, which is
2641 sufficient in many cases to find the source of the leak.
2642
2643 As "-Dm" is using the PerlIO layer for output, it will by itself
2644 allocate quite a bunch of SVs, which are hidden to avoid recursion.
2645 You can bypass the PerlIO layer if you use the SV logging provided by
2646 "-DPERL_MEM_LOG" instead.
2647
2648 PERL_MEM_LOG
2649 If compiled with "-DPERL_MEM_LOG", all Newx() and Renew() allocations
2650 and Safefree() in the Perl core go through logging functions, which is
2651 handy for breakpoint setting. If also compiled with
2652 "-DPERL_MEM_LOG_STDERR", the allocations and frees are logged to STDERR
2653 (or more precisely, to the file descriptor 2) in these logging
2654 functions, with the calling source code file and line number (and C
2655 function name, if supported by the C compiler).
2656
2657 This logging is somewhat similar to "-Dm" but independent of
2658 "-DDEBUGGING", and at a higher level (the "-Dm" is directly at the
2659 point of "malloc()", while the "PERL_MEM_LOG" is at the level of
2660 "New()").
2661
2662 In addition to memory allocations, SV allocations will be logged, just
2663 as with "-Dm". However, since the logging doesn't use PerlIO, all SV
2664 allocations are logged and no extra SV allocations are introduced by
2665 enabling the logging. If compiled with "-DDEBUG_LEAKING_SCALARS", the
2666 serial number for each SV allocation is also logged.
2667
2668 You can control the logging from your environment if you compile with
2669 "-DPERL_MEM_LOG_ENV". Then you need to explicitly set "PERL_MEM_LOG"
2670 and/or "PERL_SV_LOG" to a non-zero value to enable logging of memory
2671 and/or SV allocations.
2672
2673 Profiling
2674 Depending on your platform there are various of profiling Perl.
2675
2676 There are two commonly used techniques of profiling executables:
2677 statistical time-sampling and basic-block counting.
2678
2679 The first method takes periodically samples of the CPU program counter,
2680 and since the program counter can be correlated with the code generated
2681 for functions, we get a statistical view of in which functions the
2682 program is spending its time. The caveats are that very small/fast
2683 functions have lower probability of showing up in the profile, and that
2684 periodically interrupting the program (this is usually done rather
2685 frequently, in the scale of milliseconds) imposes an additional
2686 overhead that may skew the results. The first problem can be
2687 alleviated by running the code for longer (in general this is a good
2688 idea for profiling), the second problem is usually kept in guard by the
2689 profiling tools themselves.
2690
2691 The second method divides up the generated code into basic blocks.
2692 Basic blocks are sections of code that are entered only in the
2693 beginning and exited only at the end. For example, a conditional jump
2694 starts a basic block. Basic block profiling usually works by
2695 instrumenting the code by adding enter basic block #nnnn book-keeping
2696 code to the generated code. During the execution of the code the basic
2697 block counters are then updated appropriately. The caveat is that the
2698 added extra code can skew the results: again, the profiling tools
2699 usually try to factor their own effects out of the results.
2700
2701 Gprof Profiling
2702 gprof is a profiling tool available in many UNIX platforms, it uses
2703 statistical time-sampling.
2704
2705 You can build a profiled version of perl called "perl.gprof" by
2706 invoking the make target "perl.gprof" (What is required is that Perl
2707 must be compiled using the "-pg" flag, you may need to re-Configure).
2708 Running the profiled version of Perl will create an output file called
2709 gmon.out is created which contains the profiling data collected during
2710 the execution.
2711
2712 The gprof tool can then display the collected data in various ways.
2713 Usually gprof understands the following options:
2714
2715 -a Suppress statically defined functions from the profile.
2716
2717 -b Suppress the verbose descriptions in the profile.
2718
2719 -e routine
2720 Exclude the given routine and its descendants from the profile.
2721
2722 -f routine
2723 Display only the given routine and its descendants in the profile.
2724
2725 -s Generate a summary file called gmon.sum which then may be given to
2726 subsequent gprof runs to accumulate data over several runs.
2727
2728 -z Display routines that have zero usage.
2729
2730 For more detailed explanation of the available commands and output
2731 formats, see your own local documentation of gprof.
2732
2733 quick hint:
2734
2735 $ sh Configure -des -Dusedevel -Doptimize='-g' -Accflags='-pg' -Aldflags='-pg' && make
2736 $ ./perl someprog # creates gmon.out in current directory
2737 $ gprof perl > out
2738 $ view out
2739
2740 GCC gcov Profiling
2741 Starting from GCC 3.0 basic block profiling is officially available for
2742 the GNU CC.
2743
2744 You can build a profiled version of perl called perl.gcov by invoking
2745 the make target "perl.gcov" (what is required that Perl must be
2746 compiled using gcc with the flags "-fprofile-arcs -ftest-coverage", you
2747 may need to re-Configure).
2748
2749 Running the profiled version of Perl will cause profile output to be
2750 generated. For each source file an accompanying ".da" file will be
2751 created.
2752
2753 To display the results you use the "gcov" utility (which should be
2754 installed if you have gcc 3.0 or newer installed). gcov is run on
2755 source code files, like this
2756
2757 gcov sv.c
2758
2759 which will cause sv.c.gcov to be created. The .gcov files contain the
2760 source code annotated with relative frequencies of execution indicated
2761 by "#" markers.
2762
2763 Useful options of gcov include "-b" which will summarise the basic
2764 block, branch, and function call coverage, and "-c" which instead of
2765 relative frequencies will use the actual counts. For more information
2766 on the use of gcov and basic block profiling with gcc, see the latest
2767 GNU CC manual, as of GCC 3.0 see
2768
2769 http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc.html
2770
2771 and its section titled "8. gcov: a Test Coverage Program"
2772
2773 http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc_8.html#SEC132
2774
2775 quick hint:
2776
2777 $ sh Configure -des -Doptimize='-g' -Accflags='-fprofile-arcs -ftest-coverage' \
2778 -Aldflags='-fprofile-arcs -ftest-coverage' && make perl.gcov
2779 $ rm -f regexec.c.gcov regexec.gcda
2780 $ ./perl.gcov
2781 $ gcov regexec.c
2782 $ view regexec.c.gcov
2783
2784 Pixie Profiling
2785 Pixie is a profiling tool available on IRIX and Tru64 (aka Digital UNIX
2786 aka DEC OSF/1) platforms. Pixie does its profiling using basic-block
2787 counting.
2788
2789 You can build a profiled version of perl called perl.pixie by invoking
2790 the make target "perl.pixie" (what is required is that Perl must be
2791 compiled using the "-g" flag, you may need to re-Configure).
2792
2793 In Tru64 a file called perl.Addrs will also be silently created, this
2794 file contains the addresses of the basic blocks. Running the profiled
2795 version of Perl will create a new file called "perl.Counts" which
2796 contains the counts for the basic block for that particular program
2797 execution.
2798
2799 To display the results you use the prof utility. The exact incantation
2800 depends on your operating system, "prof perl.Counts" in IRIX, and "prof
2801 -pixie -all -L. perl" in Tru64.
2802
2803 In IRIX the following prof options are available:
2804
2805 -h Reports the most heavily used lines in descending order of use.
2806 Useful for finding the hotspot lines.
2807
2808 -l Groups lines by procedure, with procedures sorted in descending
2809 order of use. Within a procedure, lines are listed in source
2810 order. Useful for finding the hotspots of procedures.
2811
2812 In Tru64 the following options are available:
2813
2814 -p[rocedures]
2815 Procedures sorted in descending order by the number of cycles
2816 executed in each procedure. Useful for finding the hotspot
2817 procedures. (This is the default option.)
2818
2819 -h[eavy]
2820 Lines sorted in descending order by the number of cycles executed
2821 in each line. Useful for finding the hotspot lines.
2822
2823 -i[nvocations]
2824 The called procedures are sorted in descending order by number of
2825 calls made to the procedures. Useful for finding the most used
2826 procedures.
2827
2828 -l[ines]
2829 Grouped by procedure, sorted by cycles executed per procedure.
2830 Useful for finding the hotspots of procedures.
2831
2832 -testcoverage
2833 The compiler emitted code for these lines, but the code was
2834 unexecuted.
2835
2836 -z[ero]
2837 Unexecuted procedures.
2838
2839 For further information, see your system's manual pages for pixie and
2840 prof.
2841
2842 Miscellaneous tricks
2843 · Those debugging perl with the DDD frontend over gdb may find the
2844 following useful:
2845
2846 You can extend the data conversion shortcuts menu, so for example
2847 you can display an SV's IV value with one click, without doing any
2848 typing. To do that simply edit ~/.ddd/init file and add after:
2849
2850 ! Display shortcuts.
2851 Ddd*gdbDisplayShortcuts: \
2852 /t () // Convert to Bin\n\
2853 /d () // Convert to Dec\n\
2854 /x () // Convert to Hex\n\
2855 /o () // Convert to Oct(\n\
2856
2857 the following two lines:
2858
2859 ((XPV*) (())->sv_any )->xpv_pv // 2pvx\n\
2860 ((XPVIV*) (())->sv_any )->xiv_iv // 2ivx
2861
2862 so now you can do ivx and pvx lookups or you can plug there the
2863 sv_peek "conversion":
2864
2865 Perl_sv_peek(my_perl, (SV*)()) // sv_peek
2866
2867 (The my_perl is for threaded builds.) Just remember that every
2868 line, but the last one, should end with \n\
2869
2870 Alternatively edit the init file interactively via: 3rd mouse
2871 button -> New Display -> Edit Menu
2872
2873 Note: you can define up to 20 conversion shortcuts in the gdb
2874 section.
2875
2876 · If you see in a debugger a memory area mysteriously full of
2877 0xABABABAB or 0xEFEFEFEF, you may be seeing the effect of the
2878 Poison() macros, see perlclib.
2879
2880 · Under ithreads the optree is read only. If you want to enforce
2881 this, to check for write accesses from buggy code, compile with
2882 "-DPL_OP_SLAB_ALLOC" to enable the OP slab allocator and
2883 "-DPERL_DEBUG_READONLY_OPS" to enable code that allocates op memory
2884 via "mmap", and sets it read-only at run time. Any write access to
2885 an op results in a "SIGBUS" and abort.
2886
2887 This code is intended for development only, and may not be portable
2888 even to all Unix variants. Also, it is an 80% solution, in that it
2889 isn't able to make all ops read only. Specifically it
2890
2891 1. Only sets read-only on all slabs of ops at "CHECK" time, hence
2892 ops allocated later via "require" or "eval" will be re-write
2893
2894 2. Turns an entire slab of ops read-write if the refcount of any
2895 op in the slab needs to be decreased.
2896
2897 3. Turns an entire slab of ops read-write if any op from the slab
2898 is freed.
2899
2900 It's not possible to turn the slabs to read-only after an action
2901 requiring read-write access, as either can happen during op tree
2902 building time, so there may still be legitimate write access.
2903
2904 However, as an 80% solution it is still effective, as currently it
2905 catches a write access during the generation of Config.pm, which
2906 means that we can't yet build perl with this enabled.
2907
2909 We've had a brief look around the Perl source, how to maintain quality
2910 of the source code, an overview of the stages perl goes through when
2911 it's running your code, how to use debuggers to poke at the Perl guts,
2912 and finally how to analyse the execution of Perl. We took a very simple
2913 problem and demonstrated how to solve it fully - with documentation,
2914 regression tests, and finally a patch for submission to p5p. Finally,
2915 we talked about how to use external tools to debug and test Perl.
2916
2917 I'd now suggest you read over those references again, and then, as soon
2918 as possible, get your hands dirty. The best way to learn is by doing,
2919 so:
2920
2921 · Subscribe to perl5-porters, follow the patches and try and
2922 understand them; don't be afraid to ask if there's a portion you're
2923 not clear on - who knows, you may unearth a bug in the patch...
2924
2925 · Keep up to date with the bleeding edge Perl distributions and get
2926 familiar with the changes. Try and get an idea of what areas people
2927 are working on and the changes they're making.
2928
2929 · Do read the README associated with your operating system, e.g.
2930 README.aix on the IBM AIX OS. Don't hesitate to supply patches to
2931 that README if you find anything missing or changed over a new OS
2932 release.
2933
2934 · Find an area of Perl that seems interesting to you, and see if you
2935 can work out how it works. Scan through the source, and step over it
2936 in the debugger. Play, poke, investigate, fiddle! You'll probably
2937 get to understand not just your chosen area but a much wider range
2938 of perl's activity as well, and probably sooner than you'd think.
2939
2940 The Road goes ever on and on, down from the door where it began.
2941
2942 If you can do these things, you've started on the long road to Perl
2943 porting. Thanks for wanting to help make Perl better - and happy
2944 hacking!
2945
2946 Metaphoric Quotations
2947 If you recognized the quote about the Road above, you're in luck.
2948
2949 Most software projects begin each file with a literal description of
2950 each file's purpose. Perl instead begins each with a literary allusion
2951 to that file's purpose.
2952
2953 Like chapters in many books, all top-level Perl source files (along
2954 with a few others here and there) begin with an epigramic inscription
2955 that alludes, indirectly and metaphorically, to the material you're
2956 about to read.
2957
2958 Quotations are taken from writings of J.R.R Tolkien pertaining to his
2959 Legendarium, almost always from The Lord of the Rings. Chapters and
2960 page numbers are given using the following editions:
2961
2962 · The Hobbit, by J.R.R. Tolkien. The hardcover, 70th-anniversary
2963 edition of 2007 was used, published in the UK by Harper Collins
2964 Publishers and in the US by the Houghton Mifflin Company.
2965
2966 · The Lord of the Rings, by J.R.R. Tolkien. The hardcover,
2967 50th-anniversary edition of 2004 was used, published in the UK by
2968 Harper Collins Publishers and in the US by the Houghton Mifflin
2969 Company.
2970
2971 · The Lays of Beleriand, by J.R.R. Tolkien and published posthumously
2972 by his son and literary executor, C.J.R. Tolkien, being the 3rd of
2973 the 12 volumes in Christopher's mammoth History of Middle Earth.
2974 Page numbers derive from the hardcover edition, first published in
2975 1983 by George Allen & Unwin; no page numbers changed for the
2976 special 3-volume omnibus edition of 2002 or the various trade-paper
2977 editions, all again now by Harper Collins or Houghton Mifflin.
2978
2979 Other JRRT books fair game for quotes would thus include The Adventures
2980 of Tom Bombadil, The Silmarillion, Unfinished Tales, and The Tale of
2981 the Children of Hurin, all but the first posthumously assembled by
2982 CJRT. But The Lord of the Rings itself is perfectly fine and probably
2983 best to quote from, provided you can find a suitable quote there.
2984
2985 So if you were to supply a new, complete, top-level source file to add
2986 to Perl, you should conform to this peculiar practice by yourself
2987 selecting an appropriate quotation from Tolkien, retaining the original
2988 spelling and punctuation and using the same format the rest of the
2989 quotes are in. Indirect and oblique is just fine; remember, it's a
2990 metaphor, so being meta is, after all, what it's for.
2991
2993 This document was written by Nathan Torkington, and is maintained by
2994 the perl5-porters mailing list.
2995
2997 perlrepository
2998
2999
3000
3001perl v5.10.1 2009-08-03 PERLHACK(1)