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