This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl5123delta: Improve description
[perl5.git] / pod / perlhacktips.pod
CommitLineData
04c692a8
DR
1=encoding utf8
2
3=for comment
4Consistent formatting of this file is achieved with:
5 perl ./Porting/podtidy pod/perlhacktips.pod
6
7=head1 NAME
8
9perlhacktips - Tips for Perl core C code hacking
10
11=head1 DESCRIPTION
12
13This document will help you learn the best way to go about hacking on
14the Perl core C code. It covers common problems, debugging, profiling,
15and more.
16
17If you haven't read L<perlhack> and L<perlhacktut> yet, you might want
18to do that first.
19
20=head1 COMMON PROBLEMS
21
22Perl source plays by ANSI C89 rules: no C99 (or C++) extensions. In
23some cases we have to take pre-ANSI requirements into consideration.
24You don't care about some particular platform having broken Perl? I
25hear there is still a strong demand for J2EE programmers.
26
27=head2 Perl environment problems
28
29=over 4
30
31=item *
32
33Not compiling with threading
34
35Compiling with threading (-Duseithreads) completely rewrites the
36function prototypes of Perl. You better try your changes with that.
37Related to this is the difference between "Perl_-less" and "Perl_-ly"
38APIs, for example:
39
40 Perl_sv_setiv(aTHX_ ...);
41 sv_setiv(...);
42
43The first one explicitly passes in the context, which is needed for
44e.g. threaded builds. The second one does that implicitly; do not get
45them mixed. If you are not passing in a aTHX_, you will need to do a
46dTHX (or a dVAR) as the first thing in the function.
47
48See L<perlguts/"How multiple interpreters and concurrency are
49supported"> for further discussion about context.
50
51=item *
52
53Not compiling with -DDEBUGGING
54
55The DEBUGGING define exposes more code to the compiler, therefore more
56ways for things to go wrong. You should try it.
57
58=item *
59
60Introducing (non-read-only) globals
61
62Do not introduce any modifiable globals, truly global or file static.
63They are bad form and complicate multithreading and other forms of
64concurrency. The right way is to introduce them as new interpreter
65variables, see F<intrpvar.h> (at the very end for binary
66compatibility).
67
68Introducing read-only (const) globals is okay, as long as you verify
69with e.g. C<nm libperl.a|egrep -v ' [TURtr] '> (if your C<nm> has
70BSD-style output) that the data you added really is read-only. (If it
71is, it shouldn't show up in the output of that command.)
72
73If you want to have static strings, make them constant:
74
75 static const char etc[] = "...";
76
77If you want to have arrays of constant strings, note carefully the
78right combination of C<const>s:
79
80 static const char * const yippee[] =
81 {"hi", "ho", "silver"};
82
83There is a way to completely hide any modifiable globals (they are all
84moved to heap), the compilation setting
85C<-DPERL_GLOBAL_STRUCT_PRIVATE>. It is not normally used, but can be
86used for testing, read more about it in L<perlguts/"Background and
87PERL_IMPLICIT_CONTEXT">.
88
89=item *
90
91Not exporting your new function
92
93Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any
94function that is part of the public API (the shared Perl library) to be
95explicitly marked as exported. See the discussion about F<embed.pl> in
96L<perlguts>.
97
98=item *
99
100Exporting your new function
101
102The new shiny result of either genuine new functionality or your
103arduous refactoring is now ready and correctly exported. So what could
104possibly go wrong?
105
106Maybe simply that your function did not need to be exported in the
107first place. Perl has a long and not so glorious history of exporting
108functions that it should not have.
109
110If the function is used only inside one source code file, make it
111static. See the discussion about F<embed.pl> in L<perlguts>.
112
113If the function is used across several files, but intended only for
114Perl's internal use (and this should be the common case), do not export
115it to the public API. See the discussion about F<embed.pl> in
116L<perlguts>.
117
118=back
119
120=head2 Portability problems
121
122The following are common causes of compilation and/or execution
123failures, not common to Perl as such. The C FAQ is good bedtime
124reading. Please test your changes with as many C compilers and
125platforms as possible; we will, anyway, and it's nice to save oneself
126from public embarrassment.
127
128If using gcc, you can add the C<-std=c89> option which will hopefully
129catch most of these unportabilities. (However it might also catch
130incompatibilities in your system's header files.)
131
132Use the Configure C<-Dgccansipedantic> flag to enable the gcc C<-ansi
133-pedantic> flags which enforce stricter ANSI rules.
134
135If using the C<gcc -Wall> note that not all the possible warnings (like
136C<-Wunitialized>) are given unless you also compile with C<-O>.
137
138Note that if using gcc, starting from Perl 5.9.5 the Perl core source
139code files (the ones at the top level of the source code distribution,
140but not e.g. the extensions under ext/) are automatically compiled with
141as many as possible of the C<-std=c89>, C<-ansi>, C<-pedantic>, and a
142selection of C<-W> flags (see cflags.SH).
143
144Also study L<perlport> carefully to avoid any bad assumptions about the
145operating system, filesystems, and so forth.
146
147You may once in a while try a "make microperl" to see whether we can
148still compile Perl with just the bare minimum of interfaces. (See
149README.micro.)
150
151Do not assume an operating system indicates a certain compiler.
152
153=over 4
154
155=item *
156
157Casting pointers to integers or casting integers to pointers
158
159 void castaway(U8* p)
160 {
161 IV i = p;
162
163or
164
165 void castaway(U8* p)
166 {
167 IV i = (IV)p;
168
169Both are bad, and broken, and unportable. Use the PTR2IV() macro that
170does it right. (Likewise, there are PTR2UV(), PTR2NV(), INT2PTR(), and
171NUM2PTR().)
172
173=item *
174
175Casting between data function pointers and data pointers
176
177Technically speaking casting between function pointers and data
178pointers is unportable and undefined, but practically speaking it seems
179to work, but you should use the FPTR2DPTR() and DPTR2FPTR() macros.
180Sometimes you can also play games with unions.
181
182=item *
183
184Assuming sizeof(int) == sizeof(long)
185
186There are platforms where longs are 64 bits, and platforms where ints
187are 64 bits, and while we are out to shock you, even platforms where
188shorts are 64 bits. This is all legal according to the C standard. (In
189other words, "long long" is not a portable way to specify 64 bits, and
190"long long" is not even guaranteed to be any wider than "long".)
191
192Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth.
193Avoid things like I32 because they are B<not> guaranteed to be
194I<exactly> 32 bits, they are I<at least> 32 bits, nor are they
195guaranteed to be B<int> or B<long>. If you really explicitly need
19664-bit variables, use I64 and U64, but only if guarded by HAS_QUAD.
197
198=item *
199
200Assuming one can dereference any type of pointer for any type of data
201
202 char *p = ...;
203 long pony = *p; /* BAD */
204
205Many platforms, quite rightly so, will give you a core dump instead of
206a pony if the p happens not be correctly aligned.
207
208=item *
209
210Lvalue casts
211
212 (int)*p = ...; /* BAD */
213
214Simply not portable. Get your lvalue to be of the right type, or maybe
215use temporary variables, or dirty tricks with unions.
216
217=item *
218
219Assume B<anything> about structs (especially the ones you don't
220control, like the ones coming from the system headers)
221
222=over 8
223
224=item *
225
226That a certain field exists in a struct
227
228=item *
229
230That no other fields exist besides the ones you know of
231
232=item *
233
234That a field is of certain signedness, sizeof, or type
235
236=item *
237
238That the fields are in a certain order
239
240=over 8
241
242=item *
243
244While C guarantees the ordering specified in the struct definition,
245between different platforms the definitions might differ
246
247=back
248
249=item *
250
251That the sizeof(struct) or the alignments are the same everywhere
252
253=over 8
254
255=item *
256
257There might be padding bytes between the fields to align the fields -
258the bytes can be anything
259
260=item *
261
262Structs are required to be aligned to the maximum alignment required by
263the fields - which for native types is for usually equivalent to
264sizeof() of the field
265
266=back
267
268=back
269
270=item *
271
272Assuming the character set is ASCIIish
273
274Perl can compile and run under EBCDIC platforms. See L<perlebcdic>.
275This is transparent for the most part, but because the character sets
276differ, you shouldn't use numeric (decimal, octal, nor hex) constants
277to refer to characters. You can safely say 'A', but not 0x41. You can
278safely say '\n', but not \012. If a character doesn't have a trivial
279input form, you can create a #define for it in both C<utfebcdic.h> and
280C<utf8.h>, so that it resolves to different values depending on the
281character set being used. (There are three different EBCDIC character
282sets defined in C<utfebcdic.h>, so it might be best to insert the
283#define three times in that file.)
284
285Also, the range 'A' - 'Z' in ASCII is an unbroken sequence of 26 upper
286case alphabetic characters. That is not true in EBCDIC. Nor for 'a' to
287'z'. But '0' - '9' is an unbroken range in both systems. Don't assume
288anything about other ranges.
289
290Many of the comments in the existing code ignore the possibility of
291EBCDIC, and may be wrong therefore, even if the code works. This is
292actually a tribute to the successful transparent insertion of being
293able to handle EBCDIC without having to change pre-existing code.
294
295UTF-8 and UTF-EBCDIC are two different encodings used to represent
296Unicode code points as sequences of bytes. Macros with the same names
297(but different definitions) in C<utf8.h> and C<utfebcdic.h> are used to
298allow the calling code to think that there is only one such encoding.
299This is almost always referred to as C<utf8>, but it means the EBCDIC
300version as well. Again, comments in the code may well be wrong even if
301the code itself is right. For example, the concept of C<invariant
302characters> differs between ASCII and EBCDIC. On ASCII platforms, only
303characters that do not have the high-order bit set (i.e. whose ordinals
304are strict ASCII, 0 - 127) are invariant, and the documentation and
305comments in the code may assume that, often referring to something
306like, say, C<hibit>. The situation differs and is not so simple on
307EBCDIC machines, but as long as the code itself uses the
308C<NATIVE_IS_INVARIANT()> macro appropriately, it works, even if the
309comments are wrong.
310
311=item *
312
313Assuming the character set is just ASCII
314
315ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128 extra
316characters have different meanings depending on the locale. Absent a
317locale, currently these extra characters are generally considered to be
318unassigned, and this has presented some problems. This is being changed
319starting in 5.12 so that these characters will be considered to be
320Latin-1 (ISO-8859-1).
321
322=item *
323
324Mixing #define and #ifdef
325
326 #define BURGLE(x) ... \
327 #ifdef BURGLE_OLD_STYLE /* BAD */
328 ... do it the old way ... \
329 #else
330 ... do it the new way ... \
331 #endif
332
333You cannot portably "stack" cpp directives. For example in the above
334you need two separate BURGLE() #defines, one for each #ifdef branch.
335
336=item *
337
338Adding non-comment stuff after #endif or #else
339
340 #ifdef SNOSH
341 ...
342 #else !SNOSH /* BAD */
343 ...
344 #endif SNOSH /* BAD */
345
346The #endif and #else cannot portably have anything non-comment after
347them. If you want to document what is going (which is a good idea
348especially if the branches are long), use (C) comments:
349
350 #ifdef SNOSH
351 ...
352 #else /* !SNOSH */
353 ...
354 #endif /* SNOSH */
355
356The gcc option C<-Wendif-labels> warns about the bad variant (by
357default on starting from Perl 5.9.4).
358
359=item *
360
361Having a comma after the last element of an enum list
362
363 enum color {
364 CERULEAN,
365 CHARTREUSE,
366 CINNABAR, /* BAD */
367 };
368
369is not portable. Leave out the last comma.
370
371Also note that whether enums are implicitly morphable to ints varies
372between compilers, you might need to (int).
373
374=item *
375
376Using //-comments
377
378 // This function bamfoodles the zorklator. /* BAD */
379
380That is C99 or C++. Perl is C89. Using the //-comments is silently
381allowed by many C compilers but cranking up the ANSI C89 strictness
382(which we like to do) causes the compilation to fail.
383
384=item *
385
386Mixing declarations and code
387
388 void zorklator()
389 {
390 int n = 3;
391 set_zorkmids(n); /* BAD */
392 int q = 4;
393
394That is C99 or C++. Some C compilers allow that, but you shouldn't.
395
396The gcc option C<-Wdeclaration-after-statements> scans for such
397problems (by default on starting from Perl 5.9.4).
398
399=item *
400
401Introducing variables inside for()
402
403 for(int i = ...; ...; ...) { /* BAD */
404
405That is C99 or C++. While it would indeed be awfully nice to have that
406also in C89, to limit the scope of the loop variable, alas, we cannot.
407
408=item *
409
410Mixing signed char pointers with unsigned char pointers
411
412 int foo(char *s) { ... }
413 ...
414 unsigned char *t = ...; /* Or U8* t = ... */
415 foo(t); /* BAD */
416
417While this is legal practice, it is certainly dubious, and downright
418fatal in at least one platform: for example VMS cc considers this a
419fatal error. One cause for people often making this mistake is that a
420"naked char" and therefore dereferencing a "naked char pointer" have an
421undefined signedness: it depends on the compiler and the flags of the
422compiler and the underlying platform whether the result is signed or
423unsigned. For this very same reason using a 'char' as an array index is
424bad.
425
426=item *
427
428Macros that have string constants and their arguments as substrings of
429the string constants
430
431 #define FOO(n) printf("number = %d\n", n) /* BAD */
432 FOO(10);
433
434Pre-ANSI semantics for that was equivalent to
435
436 printf("10umber = %d\10");
437
438which is probably not what you were expecting. Unfortunately at least
439one reasonably common and modern C compiler does "real backward
440compatibility" here, in AIX that is what still happens even though the
441rest of the AIX compiler is very happily C89.
442
443=item *
444
445Using printf formats for non-basic C types
446
447 IV i = ...;
448 printf("i = %d\n", i); /* BAD */
449
450While this might by accident work in some platform (where IV happens to
451be an C<int>), in general it cannot. IV might be something larger. Even
452worse the situation is with more specific types (defined by Perl's
453configuration step in F<config.h>):
454
455 Uid_t who = ...;
456 printf("who = %d\n", who); /* BAD */
457
458The problem here is that Uid_t might be not only not C<int>-wide but it
459might also be unsigned, in which case large uids would be printed as
460negative values.
461
462There is no simple solution to this because of printf()'s limited
463intelligence, but for many types the right format is available as with
464either 'f' or '_f' suffix, for example:
465
466 IVdf /* IV in decimal */
467 UVxf /* UV is hexadecimal */
468
469 printf("i = %"IVdf"\n", i); /* The IVdf is a string constant. */
470
471 Uid_t_f /* Uid_t in decimal */
472
473 printf("who = %"Uid_t_f"\n", who);
474
475Or you can try casting to a "wide enough" type:
476
477 printf("i = %"IVdf"\n", (IV)something_very_small_and_signed);
478
479Also remember that the C<%p> format really does require a void pointer:
480
481 U8* p = ...;
482 printf("p = %p\n", (void*)p);
483
484The gcc option C<-Wformat> scans for such problems.
485
486=item *
487
488Blindly using variadic macros
489
490gcc has had them for a while with its own syntax, and C99 brought them
491with a standardized syntax. Don't use the former, and use the latter
492only if the HAS_C99_VARIADIC_MACROS is defined.
493
494=item *
495
496Blindly passing va_list
497
498Not all platforms support passing va_list to further varargs (stdarg)
499functions. The right thing to do is to copy the va_list using the
500Perl_va_copy() if the NEED_VA_COPY is defined.
501
502=item *
503
504Using gcc statement expressions
505
506 val = ({...;...;...}); /* BAD */
507
508While a nice extension, it's not portable. The Perl code does
509admittedly use them if available to gain some extra speed (essentially
510as a funky form of inlining), but you shouldn't.
511
512=item *
513
514Binding together several statements in a macro
515
516Use the macros STMT_START and STMT_END.
517
518 STMT_START {
519 ...
520 } STMT_END
521
522=item *
523
524Testing for operating systems or versions when should be testing for
525features
526
527 #ifdef __FOONIX__ /* BAD */
528 foo = quux();
529 #endif
530
531Unless you know with 100% certainty that quux() is only ever available
532for the "Foonix" operating system B<and> that is available B<and>
533correctly working for B<all> past, present, B<and> future versions of
534"Foonix", the above is very wrong. This is more correct (though still
535not perfect, because the below is a compile-time check):
536
537 #ifdef HAS_QUUX
538 foo = quux();
539 #endif
540
541How does the HAS_QUUX become defined where it needs to be? Well, if
542Foonix happens to be Unixy enough to be able to run the Configure
543script, and Configure has been taught about detecting and testing
544quux(), the HAS_QUUX will be correctly defined. In other platforms, the
545corresponding configuration step will hopefully do the same.
546
547In a pinch, if you cannot wait for Configure to be educated, or if you
548have a good hunch of where quux() might be available, you can
549temporarily try the following:
550
551 #if (defined(__FOONIX__) || defined(__BARNIX__))
552 # define HAS_QUUX
553 #endif
554
555 ...
556
557 #ifdef HAS_QUUX
558 foo = quux();
559 #endif
560
561But in any case, try to keep the features and operating systems
562separate.
563
564=back
565
566=head2 Problematic System Interfaces
567
568=over 4
569
570=item *
571
572malloc(0), realloc(0), calloc(0, 0) are non-portable. To be portable
573allocate at least one byte. (In general you should rarely need to work
574at this low level, but instead use the various malloc wrappers.)
575
576=item *
577
578snprintf() - the return type is unportable. Use my_snprintf() instead.
579
580=back
581
582=head2 Security problems
583
584Last but not least, here are various tips for safer coding.
585
586=over 4
587
588=item *
589
590Do not use gets()
591
592Or we will publicly ridicule you. Seriously.
593
594=item *
595
596Do not use strcpy() or strcat() or strncpy() or strncat()
597
598Use my_strlcpy() and my_strlcat() instead: they either use the native
599implementation, or Perl's own implementation (borrowed from the public
600domain implementation of INN).
601
602=item *
603
604Do not use sprintf() or vsprintf()
605
606If you really want just plain byte strings, use my_snprintf() and
607my_vsnprintf() instead, which will try to use snprintf() and
608vsnprintf() if those safer APIs are available. If you want something
609fancier than a plain byte string, use SVs and Perl_sv_catpvf().
610
611=back
612
613=head1 DEBUGGING
614
615You can compile a special debugging version of Perl, which allows you
616to use the C<-D> option of Perl to tell more about what Perl is doing.
617But sometimes there is no alternative than to dive in with a debugger,
618either to see the stack trace of a core dump (very useful in a bug
619report), or trying to figure out what went wrong before the core dump
620happened, or how did we end up having wrong or unexpected results.
621
622=head2 Poking at Perl
623
624To really poke around with Perl, you'll probably want to build Perl for
625debugging, like this:
626
627 ./Configure -d -D optimize=-g
628 make
629
630C<-g> is a flag to the C compiler to have it produce debugging
631information which will allow us to step through a running program, and
632to see in which C function we are at (without the debugging information
633we might see only the numerical addresses of the functions, which is
634not very helpful).
635
636F<Configure> will also turn on the C<DEBUGGING> compilation symbol
637which enables all the internal debugging code in Perl. There are a
638whole bunch of things you can debug with this: L<perlrun> lists them
639all, and the best way to find out about them is to play about with
640them. The most useful options are probably
641
642 l Context (loop) stack processing
643 t Trace execution
644 o Method and overloading resolution
645 c String/numeric conversions
646
647Some of the functionality of the debugging code can be achieved using
648XS modules.
649
650 -Dr => use re 'debug'
651 -Dx => use O 'Debug'
652
653=head2 Using a source-level debugger
654
655If the debugging output of C<-D> doesn't help you, it's time to step
656through perl's execution with a source-level debugger.
657
658=over 3
659
660=item *
661
662We'll use C<gdb> for our examples here; the principles will apply to
663any debugger (many vendors call their debugger C<dbx>), but check the
664manual of the one you're using.
665
666=back
667
668To fire up the debugger, type
669
670 gdb ./perl
671
672Or if you have a core dump:
673
674 gdb ./perl core
675
676You'll want to do that in your Perl source tree so the debugger can
677read the source code. You should see the copyright message, followed by
678the prompt.
679
680 (gdb)
681
682C<help> will get you into the documentation, but here are the most
683useful commands:
684
685=over 3
686
687=item * run [args]
688
689Run the program with the given arguments.
690
691=item * break function_name
692
693=item * break source.c:xxx
694
695Tells the debugger that we'll want to pause execution when we reach
696either the named function (but see L<perlguts/Internal Functions>!) or
697the given line in the named source file.
698
699=item * step
700
701Steps through the program a line at a time.
702
703=item * next
704
705Steps through the program a line at a time, without descending into
706functions.
707
708=item * continue
709
710Run until the next breakpoint.
711
712=item * finish
713
714Run until the end of the current function, then stop again.
715
716=item * 'enter'
717
718Just pressing Enter will do the most recent operation again - it's a
719blessing when stepping through miles of source code.
720
721=item * print
722
723Execute the given C code and print its results. B<WARNING>: Perl makes
724heavy use of macros, and F<gdb> does not necessarily support macros
725(see later L</"gdb macro support">). You'll have to substitute them
726yourself, or to invoke cpp on the source code files (see L</"The .i
727Targets">) So, for instance, you can't say
728
729 print SvPV_nolen(sv)
730
731but you have to say
732
733 print Perl_sv_2pv_nolen(sv)
734
735=back
736
737You may find it helpful to have a "macro dictionary", which you can
738produce by saying C<cpp -dM perl.c | sort>. Even then, F<cpp> won't
739recursively apply those macros for you.
740
741=head2 gdb macro support
742
743Recent versions of F<gdb> have fairly good macro support, but in order
744to use it you'll need to compile perl with macro definitions included
745in the debugging information. Using F<gcc> version 3.1, this means
746configuring with C<-Doptimize=-g3>. Other compilers might use a
747different switch (if they support debugging macros at all).
748
749=head2 Dumping Perl Data Structures
750
751One way to get around this macro hell is to use the dumping functions
752in F<dump.c>; these work a little like an internal
753L<Devel::Peek|Devel::Peek>, but they also cover OPs and other
754structures that you can't get at from Perl. Let's take an example.
755We'll use the C<$a = $b + $c> we used before, but give it a bit of
756context: C<$b = "6XXXX"; $c = 2.3;>. Where's a good place to stop and
757poke around?
758
759What about C<pp_add>, the function we examined earlier to implement the
760C<+> operator:
761
762 (gdb) break Perl_pp_add
763 Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.
764
765Notice we use C<Perl_pp_add> and not C<pp_add> - see
766L<perlguts/Internal Functions>. With the breakpoint in place, we can
767run our program:
768
769 (gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c'
770
771Lots of junk will go past as gdb reads in the relevant source files and
772libraries, and then:
773
774 Breakpoint 1, Perl_pp_add () at pp_hot.c:309
775 309 dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
776 (gdb) step
777 311 dPOPTOPnnrl_ul;
778 (gdb)
779
780We looked at this bit of code before, and we said that
781C<dPOPTOPnnrl_ul> arranges for two C<NV>s to be placed into C<left> and
782C<right> - let's slightly expand it:
783
784 #define dPOPTOPnnrl_ul NV right = POPn; \
785 SV *leftsv = TOPs; \
786 NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0
787
788C<POPn> takes the SV from the top of the stack and obtains its NV
789either directly (if C<SvNOK> is set) or by calling the C<sv_2nv>
790function. C<TOPs> takes the next SV from the top of the stack - yes,
791C<POPn> uses C<TOPs> - but doesn't remove it. We then use C<SvNV> to
792get the NV from C<leftsv> in the same way as before - yes, C<POPn> uses
793C<SvNV>.
794
795Since we don't have an NV for C<$b>, we'll have to use C<sv_2nv> to
796convert it. If we step again, we'll find ourselves there:
797
798 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
799 1669 if (!sv)
800 (gdb)
801
802We can now use C<Perl_sv_dump> to investigate the SV:
803
804 SV = PV(0xa057cc0) at 0xa0675d0
805 REFCNT = 1
806 FLAGS = (POK,pPOK)
807 PV = 0xa06a510 "6XXXX"\0
808 CUR = 5
809 LEN = 6
810 $1 = void
811
812We know we're going to get C<6> from this, so let's finish the
813subroutine:
814
815 (gdb) finish
816 Run till exit from #0 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
817 0x462669 in Perl_pp_add () at pp_hot.c:311
818 311 dPOPTOPnnrl_ul;
819
820We can also dump out this op: the current op is always stored in
821C<PL_op>, and we can dump it with C<Perl_op_dump>. This'll give us
822similar output to L<B::Debug|B::Debug>.
823
824 {
825 13 TYPE = add ===> 14
826 TARG = 1
827 FLAGS = (SCALAR,KIDS)
828 {
829 TYPE = null ===> (12)
830 (was rv2sv)
831 FLAGS = (SCALAR,KIDS)
832 {
833 11 TYPE = gvsv ===> 12
834 FLAGS = (SCALAR)
835 GV = main::b
836 }
837 }
838
839# finish this later #
840
841=head1 SOURCE CODE STATIC ANALYSIS
842
843Various tools exist for analysing C source code B<statically>, as
844opposed to B<dynamically>, that is, without executing the code. It is
845possible to detect resource leaks, undefined behaviour, type
846mismatches, portability problems, code paths that would cause illegal
847memory accesses, and other similar problems by just parsing the C code
848and looking at the resulting graph, what does it tell about the
849execution and data flows. As a matter of fact, this is exactly how C
850compilers know to give warnings about dubious code.
851
852=head2 lint, splint
853
854The good old C code quality inspector, C<lint>, is available in several
855platforms, but please be aware that there are several different
856implementations of it by different vendors, which means that the flags
857are not identical across different platforms.
858
859There is a lint variant called C<splint> (Secure Programming Lint)
860available from http://www.splint.org/ that should compile on any
861Unix-like platform.
862
863There are C<lint> and <splint> targets in Makefile, but you may have to
864diddle with the flags (see above).
865
866=head2 Coverity
867
868Coverity (http://www.coverity.com/) is a product similar to lint and as
869a testbed for their product they periodically check several open source
870projects, and they give out accounts to open source developers to the
871defect databases.
872
873=head2 cpd (cut-and-paste detector)
874
875The cpd tool detects cut-and-paste coding. If one instance of the
876cut-and-pasted code changes, all the other spots should probably be
877changed, too. Therefore such code should probably be turned into a
878subroutine or a macro.
879
880cpd (http://pmd.sourceforge.net/cpd.html) is part of the pmd project
881(http://pmd.sourceforge.net/). pmd was originally written for static
882analysis of Java code, but later the cpd part of it was extended to
883parse also C and C++.
884
885Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the
886pmd-X.Y.jar from it, and then run that on source code thusly:
887
888 java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files /some/where/src --language c > cpd.txt
889
890You may run into memory limits, in which case you should use the -Xmx
891option:
892
893 java -Xmx512M ...
894
895=head2 gcc warnings
896
897Though much can be written about the inconsistency and coverage
898problems of gcc warnings (like C<-Wall> not meaning "all the warnings",
899or some common portability problems not being covered by C<-Wall>, or
900C<-ansi> and C<-pedantic> both being a poorly defined collection of
901warnings, and so forth), gcc is still a useful tool in keeping our
902coding nose clean.
903
904The C<-Wall> is by default on.
905
906The C<-ansi> (and its sidekick, C<-pedantic>) would be nice to be on
907always, but unfortunately they are not safe on all platforms, they can
908for example cause fatal conflicts with the system headers (Solaris
909being a prime example). If Configure C<-Dgccansipedantic> is used, the
910C<cflags> frontend selects C<-ansi -pedantic> for the platforms where
911they are known to be safe.
912
913Starting from Perl 5.9.4 the following extra flags are added:
914
915=over 4
916
917=item *
918
919C<-Wendif-labels>
920
921=item *
922
923C<-Wextra>
924
925=item *
926
927C<-Wdeclaration-after-statement>
928
929=back
930
931The following flags would be nice to have but they would first need
932their own Augean stablemaster:
933
934=over 4
935
936=item *
937
938C<-Wpointer-arith>
939
940=item *
941
942C<-Wshadow>
943
944=item *
945
946C<-Wstrict-prototypes>
947
948=back
949
950The C<-Wtraditional> is another example of the annoying tendency of gcc
951to bundle a lot of warnings under one switch (it would be impossible to
952deploy in practice because it would complain a lot) but it does contain
953some warnings that would be beneficial to have available on their own,
954such as the warning about string constants inside macros containing the
955macro arguments: this behaved differently pre-ANSI than it does in
956ANSI, and some C compilers are still in transition, AIX being an
957example.
958
959=head2 Warnings of other C compilers
960
961Other C compilers (yes, there B<are> other C compilers than gcc) often
962have their "strict ANSI" or "strict ANSI with some portability
963extensions" modes on, like for example the Sun Workshop has its C<-Xa>
964mode on (though implicitly), or the DEC (these days, HP...) has its
965C<-std1> mode on.
966
967=head1 MEMORY DEBUGGERS
968
969B<NOTE 1>: Running under memory debuggers such as Purify, valgrind, or
970Third Degree greatly slows down the execution: seconds become minutes,
971minutes become hours. For example as of Perl 5.8.1, the
972ext/Encode/t/Unicode.t takes extraordinarily long to complete under
973e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more
974than six hours, even on a snappy computer. The said test must be doing
975something that is quite unfriendly for memory debuggers. If you don't
976feel like waiting, that you can simply kill away the perl process.
977
978B<NOTE 2>: To minimize the number of memory leak false alarms (see
979L</PERL_DESTRUCT_LEVEL> for more information), you have to set the
980environment variable PERL_DESTRUCT_LEVEL to 2.
981
982For csh-like shells:
983
984 setenv PERL_DESTRUCT_LEVEL 2
985
986For Bourne-type shells:
987
988 PERL_DESTRUCT_LEVEL=2
989 export PERL_DESTRUCT_LEVEL
990
991In Unixy environments you can also use the C<env> command:
992
993 env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ...
994
995B<NOTE 3>: There are known memory leaks when there are compile-time
996errors within eval or require, seeing C<S_doeval> in the call stack is
997a good sign of these. Fixing these leaks is non-trivial, unfortunately,
998but they must be fixed eventually.
999
1000B<NOTE 4>: L<DynaLoader> will not clean up after itself completely
1001unless Perl is built with the Configure option
1002C<-Accflags=-DDL_UNLOAD_ALL_AT_EXIT>.
1003
1004=head2 Rational Software's Purify
1005
1006Purify is a commercial tool that is helpful in identifying memory
1007overruns, wild pointers, memory leaks and other such badness. Perl must
1008be compiled in a specific way for optimal testing with Purify. Purify
1009is available under Windows NT, Solaris, HP-UX, SGI, and Siemens Unix.
1010
1011=head3 Purify on Unix
1012
1013On Unix, Purify creates a new Perl binary. To get the most benefit out
1014of Purify, you should create the perl to Purify using:
1015
1016 sh Configure -Accflags=-DPURIFY -Doptimize='-g' \
1017 -Uusemymalloc -Dusemultiplicity
1018
1019where these arguments mean:
1020
1021=over 4
1022
1023=item * -Accflags=-DPURIFY
1024
1025Disables Perl's arena memory allocation functions, as well as forcing
1026use of memory allocation functions derived from the system malloc.
1027
1028=item * -Doptimize='-g'
1029
1030Adds debugging information so that you see the exact source statements
1031where the problem occurs. Without this flag, all you will see is the
1032source filename of where the error occurred.
1033
1034=item * -Uusemymalloc
1035
1036Disable Perl's malloc so that Purify can more closely monitor
1037allocations and leaks. Using Perl's malloc will make Purify report most
1038leaks in the "potential" leaks category.
1039
1040=item * -Dusemultiplicity
1041
1042Enabling the multiplicity option allows perl to clean up thoroughly
1043when the interpreter shuts down, which reduces the number of bogus leak
1044reports from Purify.
1045
1046=back
1047
1048Once you've compiled a perl suitable for Purify'ing, then you can just:
1049
1050 make pureperl
1051
1052which creates a binary named 'pureperl' that has been Purify'ed. This
1053binary is used in place of the standard 'perl' binary when you want to
1054debug Perl memory problems.
1055
1056As an example, to show any memory leaks produced during the standard
1057Perl testset you would create and run the Purify'ed perl as:
1058
1059 make pureperl
1060 cd t
1061 ../pureperl -I../lib harness
1062
1063which would run Perl on test.pl and report any memory problems.
1064
1065Purify outputs messages in "Viewer" windows by default. If you don't
1066have a windowing environment or if you simply want the Purify output to
1067unobtrusively go to a log file instead of to the interactive window,
1068use these following options to output to the log file "perl.log":
1069
1070 setenv PURIFYOPTIONS "-chain-length=25 -windows=no \
1071 -log-file=perl.log -append-logfile=yes"
1072
1073If you plan to use the "Viewer" windows, then you only need this
1074option:
1075
1076 setenv PURIFYOPTIONS "-chain-length=25"
1077
1078In Bourne-type shells:
1079
1080 PURIFYOPTIONS="..."
1081 export PURIFYOPTIONS
1082
1083or if you have the "env" utility:
1084
1085 env PURIFYOPTIONS="..." ../pureperl ...
1086
1087=head3 Purify on NT
1088
1089Purify on Windows NT instruments the Perl binary 'perl.exe' on the fly.
1090 There are several options in the makefile you should change to get the
1091most use out of Purify:
1092
1093=over 4
1094
1095=item * DEFINES
1096
1097You should add -DPURIFY to the DEFINES line so the DEFINES line looks
1098something like:
1099
1100 DEFINES = -DWIN32 -D_CONSOLE -DNO_STRICT $(CRYPT_FLAG) -DPURIFY=1
1101
1102to disable Perl's arena memory allocation functions, as well as to
1103force use of memory allocation functions derived from the system
1104malloc.
1105
1106=item * USE_MULTI = define
1107
1108Enabling the multiplicity option allows perl to clean up thoroughly
1109when the interpreter shuts down, which reduces the number of bogus leak
1110reports from Purify.
1111
1112=item * #PERL_MALLOC = define
1113
1114Disable Perl's malloc so that Purify can more closely monitor
1115allocations and leaks. Using Perl's malloc will make Purify report most
1116leaks in the "potential" leaks category.
1117
1118=item * CFG = Debug
1119
1120Adds debugging information so that you see the exact source statements
1121where the problem occurs. Without this flag, all you will see is the
1122source filename of where the error occurred.
1123
1124=back
1125
1126As an example, to show any memory leaks produced during the standard
1127Perl testset you would create and run Purify as:
1128
1129 cd win32
1130 make
1131 cd ../t
1132 purify ../perl -I../lib harness
1133
1134which would instrument Perl in memory, run Perl on test.pl, then
1135finally report any memory problems.
1136
1137=head2 valgrind
1138
1139The excellent valgrind tool can be used to find out both memory leaks
1140and illegal memory accesses. As of version 3.3.0, Valgrind only
1141supports Linux on x86, x86-64 and PowerPC. The special "test.valgrind"
1142target can be used to run the tests under valgrind. Found errors and
1143memory leaks are logged in files named F<testfile.valgrind>.
1144
1145Valgrind also provides a cachegrind tool, invoked on perl as:
1146
1147 VG_OPTS=--tool=cachegrind make test.valgrind
1148
1149As system libraries (most notably glibc) are also triggering errors,
1150valgrind allows to suppress such errors using suppression files. The
1151default suppression file that comes with valgrind already catches a lot
1152of them. Some additional suppressions are defined in F<t/perl.supp>.
1153
1154To get valgrind and for more information see
1155
1156 http://developer.kde.org/~sewardj/
1157
1158=head1 PROFILING
1159
1160Depending on your platform there are various ways of profiling Perl.
1161
1162There are two commonly used techniques of profiling executables:
1163I<statistical time-sampling> and I<basic-block counting>.
1164
1165The first method takes periodically samples of the CPU program counter,
1166and since the program counter can be correlated with the code generated
1167for functions, we get a statistical view of in which functions the
1168program is spending its time. The caveats are that very small/fast
1169functions have lower probability of showing up in the profile, and that
1170periodically interrupting the program (this is usually done rather
1171frequently, in the scale of milliseconds) imposes an additional
1172overhead that may skew the results. The first problem can be alleviated
1173by running the code for longer (in general this is a good idea for
1174profiling), the second problem is usually kept in guard by the
1175profiling tools themselves.
1176
1177The second method divides up the generated code into I<basic blocks>.
1178Basic blocks are sections of code that are entered only in the
1179beginning and exited only at the end. For example, a conditional jump
1180starts a basic block. Basic block profiling usually works by
1181I<instrumenting> the code by adding I<enter basic block #nnnn>
1182book-keeping code to the generated code. During the execution of the
1183code the basic block counters are then updated appropriately. The
1184caveat is that the added extra code can skew the results: again, the
1185profiling tools usually try to factor their own effects out of the
1186results.
1187
1188=head2 Gprof Profiling
1189
1190gprof is a profiling tool available in many Unix platforms, it uses
1191F<statistical time-sampling>.
1192
1193You can build a profiled version of perl called "perl.gprof" by
1194invoking the make target "perl.gprof" (What is required is that Perl
1195must be compiled using the C<-pg> flag, you may need to re-Configure).
1196Running the profiled version of Perl will create an output file called
1197F<gmon.out> is created which contains the profiling data collected
1198during the execution.
1199
1200The gprof tool can then display the collected data in various ways.
1201Usually gprof understands the following options:
1202
1203=over 4
1204
1205=item * -a
1206
1207Suppress statically defined functions from the profile.
1208
1209=item * -b
1210
1211Suppress the verbose descriptions in the profile.
1212
1213=item * -e routine
1214
1215Exclude the given routine and its descendants from the profile.
1216
1217=item * -f routine
1218
1219Display only the given routine and its descendants in the profile.
1220
1221=item * -s
1222
1223Generate a summary file called F<gmon.sum> which then may be given to
1224subsequent gprof runs to accumulate data over several runs.
1225
1226=item * -z
1227
1228Display routines that have zero usage.
1229
1230=back
1231
1232For more detailed explanation of the available commands and output
1233formats, see your own local documentation of gprof.
1234
1235quick hint:
1236
1237 $ sh Configure -des -Dusedevel -Doptimize='-pg' && make perl.gprof
1238 $ ./perl.gprof someprog # creates gmon.out in current directory
1239 $ gprof ./perl.gprof > out
1240 $ view out
1241
1242=head2 GCC gcov Profiling
1243
1244Starting from GCC 3.0 I<basic block profiling> is officially available
1245for the GNU CC.
1246
1247You can build a profiled version of perl called F<perl.gcov> by
1248invoking the make target "perl.gcov" (what is required that Perl must
1249be compiled using gcc with the flags C<-fprofile-arcs -ftest-coverage>,
1250you may need to re-Configure).
1251
1252Running the profiled version of Perl will cause profile output to be
1253generated. For each source file an accompanying ".da" file will be
1254created.
1255
1256To display the results you use the "gcov" utility (which should be
1257installed if you have gcc 3.0 or newer installed). F<gcov> is run on
1258source code files, like this
1259
1260 gcov sv.c
1261
1262which will cause F<sv.c.gcov> to be created. The F<.gcov> files contain
1263the source code annotated with relative frequencies of execution
1264indicated by "#" markers.
1265
1266Useful options of F<gcov> include C<-b> which will summarise the basic
1267block, branch, and function call coverage, and C<-c> which instead of
1268relative frequencies will use the actual counts. For more information
1269on the use of F<gcov> and basic block profiling with gcc, see the
1270latest GNU CC manual, as of GCC 3.0 see
1271
1272 http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc.html
1273
1274and its section titled "8. gcov: a Test Coverage Program"
1275
1276 http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc_8.html#SEC132
1277
1278quick hint:
1279
1280 $ sh Configure -des -Dusedevel -Doptimize='-g' \
1281 -Accflags='-fprofile-arcs -ftest-coverage' \
1282 -Aldflags='-fprofile-arcs -ftest-coverage' && make perl.gcov
1283 $ rm -f regexec.c.gcov regexec.gcda
1284 $ ./perl.gcov
1285 $ gcov regexec.c
1286 $ view regexec.c.gcov
1287
1288=head1 MISCELLANEOUS TRICKS
1289
1290=head2 PERL_DESTRUCT_LEVEL
1291
1292If you want to run any of the tests yourself manually using e.g.
1293valgrind, or the pureperl or perl.third executables, please note that
1294by default perl B<does not> explicitly cleanup all the memory it has
1295allocated (such as global memory arenas) but instead lets the exit() of
1296the whole program "take care" of such allocations, also known as
1297"global destruction of objects".
1298
1299There is a way to tell perl to do complete cleanup: set the environment
1300variable PERL_DESTRUCT_LEVEL to a non-zero value. The t/TEST wrapper
1301does set this to 2, and this is what you need to do too, if you don't
1302want to see the "global leaks": For example, for "third-degreed" Perl:
1303
1304 env PERL_DESTRUCT_LEVEL=2 ./perl.third -Ilib t/foo/bar.t
1305
1306(Note: the mod_perl apache module uses also this environment variable
1307for its own purposes and extended its semantics. Refer to the mod_perl
1308documentation for more information. Also, spawned threads do the
1309equivalent of setting this variable to the value 1.)
1310
1311If, at the end of a run you get the message I<N scalars leaked>, you
1312can recompile with C<-DDEBUG_LEAKING_SCALARS>, which will cause the
1313addresses of all those leaked SVs to be dumped along with details as to
1314where each SV was originally allocated. This information is also
1315displayed by Devel::Peek. Note that the extra details recorded with
1316each SV increases memory usage, so it shouldn't be used in production
1317environments. It also converts C<new_SV()> from a macro into a real
1318function, so you can use your favourite debugger to discover where
1319those pesky SVs were allocated.
1320
1321If you see that you're leaking memory at runtime, but neither valgrind
1322nor C<-DDEBUG_LEAKING_SCALARS> will find anything, you're probably
1323leaking SVs that are still reachable and will be properly cleaned up
1324during destruction of the interpreter. In such cases, using the C<-Dm>
1325switch can point you to the source of the leak. If the executable was
1326built with C<-DDEBUG_LEAKING_SCALARS>, C<-Dm> will output SV
1327allocations in addition to memory allocations. Each SV allocation has a
1328distinct serial number that will be written on creation and destruction
1329of the SV. So if you're executing the leaking code in a loop, you need
1330to look for SVs that are created, but never destroyed between each
1331cycle. If such an SV is found, set a conditional breakpoint within
1332C<new_SV()> and make it break only when C<PL_sv_serial> is equal to the
1333serial number of the leaking SV. Then you will catch the interpreter in
1334exactly the state where the leaking SV is allocated, which is
1335sufficient in many cases to find the source of the leak.
1336
1337As C<-Dm> is using the PerlIO layer for output, it will by itself
1338allocate quite a bunch of SVs, which are hidden to avoid recursion. You
1339can bypass the PerlIO layer if you use the SV logging provided by
1340C<-DPERL_MEM_LOG> instead.
1341
1342=head2 PERL_MEM_LOG
1343
1344If compiled with C<-DPERL_MEM_LOG>, both memory and SV allocations go
1345through logging functions, which is handy for breakpoint setting.
1346
1347Unless C<-DPERL_MEM_LOG_NOIMPL> is also compiled, the logging functions
1348read $ENV{PERL_MEM_LOG} to determine whether to log the event, and if
1349so how:
1350
1351 $ENV{PERL_MEM_LOG} =~ /m/ Log all memory ops
1352 $ENV{PERL_MEM_LOG} =~ /s/ Log all SV ops
1353 $ENV{PERL_MEM_LOG} =~ /t/ include timestamp in Log
1354 $ENV{PERL_MEM_LOG} =~ /^(\d+)/ write to FD given (default is 2)
1355
1356Memory logging is somewhat similar to C<-Dm> but is independent of
1357C<-DDEBUGGING>, and at a higher level; all uses of Newx(), Renew(), and
1358Safefree() are logged with the caller's source code file and line
1359number (and C function name, if supported by the C compiler). In
1360contrast, C<-Dm> is directly at the point of C<malloc()>. SV logging is
1361similar.
1362
1363Since the logging doesn't use PerlIO, all SV allocations are logged and
1364no extra SV allocations are introduced by enabling the logging. If
1365compiled with C<-DDEBUG_LEAKING_SCALARS>, the serial number for each SV
1366allocation is also logged.
1367
1368=head2 DDD over gdb
1369
1370Those debugging perl with the DDD frontend over gdb may find the
1371following useful:
1372
1373You can extend the data conversion shortcuts menu, so for example you
1374can display an SV's IV value with one click, without doing any typing.
1375To do that simply edit ~/.ddd/init file and add after:
1376
1377 ! Display shortcuts.
1378 Ddd*gdbDisplayShortcuts: \
1379 /t () // Convert to Bin\n\
1380 /d () // Convert to Dec\n\
1381 /x () // Convert to Hex\n\
1382 /o () // Convert to Oct(\n\
1383
1384the following two lines:
1385
1386 ((XPV*) (())->sv_any )->xpv_pv // 2pvx\n\
1387 ((XPVIV*) (())->sv_any )->xiv_iv // 2ivx
1388
1389so now you can do ivx and pvx lookups or you can plug there the sv_peek
1390"conversion":
1391
1392 Perl_sv_peek(my_perl, (SV*)()) // sv_peek
1393
1394(The my_perl is for threaded builds.) Just remember that every line,
1395but the last one, should end with \n\
1396
1397Alternatively edit the init file interactively via: 3rd mouse button ->
1398New Display -> Edit Menu
1399
1400Note: you can define up to 20 conversion shortcuts in the gdb section.
1401
1402=head2 Poison
1403
1404If you see in a debugger a memory area mysteriously full of 0xABABABAB
1405or 0xEFEFEFEF, you may be seeing the effect of the Poison() macros, see
1406L<perlclib>.
1407
1408=head2 Read-only optrees
1409
1410Under ithreads the optree is read only. If you want to enforce this, to
1411check for write accesses from buggy code, compile with
1412C<-DPL_OP_SLAB_ALLOC> to enable the OP slab allocator and
1413C<-DPERL_DEBUG_READONLY_OPS> to enable code that allocates op memory
1414via C<mmap>, and sets it read-only at run time. Any write access to an
1415op results in a C<SIGBUS> and abort.
1416
1417This code is intended for development only, and may not be portable
1418even to all Unix variants. Also, it is an 80% solution, in that it
1419isn't able to make all ops read only. Specifically it
1420
1421=over
1422
1423=item * 1
1424
1425Only sets read-only on all slabs of ops at C<CHECK> time, hence ops
1426allocated later via C<require> or C<eval> will be re-write
1427
1428=item * 2
1429
1430Turns an entire slab of ops read-write if the refcount of any op in the
1431slab needs to be decreased.
1432
1433=item * 3
1434
1435Turns an entire slab of ops read-write if any op from the slab is
1436freed.
1437
1438=back
1439
1440It's not possible to turn the slabs to read-only after an action
1441requiring read-write access, as either can happen during op tree
1442building time, so there may still be legitimate write access.
1443
1444However, as an 80% solution it is still effective, as currently it
1445catches a write access during the generation of F<Config.pm>, which
1446means that we can't yet build F<perl> with this enabled.
1447
1448=head2 The .i Targets
1449
1450You can expand the macros in a F<foo.c> file by saying
1451
1452 make foo.i
1453
1454which will expand the macros using cpp. Don't be scared by the results.
1455
1456=head1 AUTHOR
1457
1458This document was originally written by Nathan Torkington, and is
1459maintained by the perl5-porters mailing list.