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