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