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