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