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