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