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