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