1PERLHACKTIPS(1)        Perl Programmers Reference Guide        PERLHACKTIPS(1)
2
3
4

NAME

6       perlhacktips - Tips for Perl core C code hacking
7

DESCRIPTION

9       This document will help you learn the best way to go about hacking on
10       the Perl core C code. It covers common problems, debugging, profiling,
11       and more.
12
13       If you haven't read perlhack and perlhacktut yet, you might want to do
14       that first.
15

COMMON PROBLEMS

17       Perl source plays by ANSI C89 rules: no C99 (or C++) extensions. In
18       some cases we have to take pre-ANSI requirements into consideration.
19       You don't care about some particular platform having broken Perl? I
20       hear there is still a strong demand for J2EE programmers.
21
22   Perl environment problems
23       ·   Not compiling with threading
24
25           Compiling with threading (-Duseithreads) completely rewrites the
26           function prototypes of Perl. You better try your changes with that.
27           Related to this is the difference between "Perl_-less" and
28           "Perl_-ly" APIs, for example:
29
30             Perl_sv_setiv(aTHX_ ...);
31             sv_setiv(...);
32
33           The first one explicitly passes in the context, which is needed for
34           e.g. threaded builds. The second one does that implicitly; do not
35           get them mixed. If you are not passing in a aTHX_, you will need to
36           do a dTHX (or a dVAR) as the first thing in the function.
37
38           See "How multiple interpreters and concurrency are supported" in
39           perlguts for further discussion about context.
40
41       ·   Not compiling with -DDEBUGGING
42
43           The DEBUGGING define exposes more code to the compiler, therefore
44           more ways for things to go wrong. You should try it.
45
46       ·   Introducing (non-read-only) globals
47
48           Do not introduce any modifiable globals, truly global or file
49           static.  They are bad form and complicate multithreading and other
50           forms of concurrency. The right way is to introduce them as new
51           interpreter variables, see intrpvar.h (at the very end for binary
52           compatibility).
53
54           Introducing read-only (const) globals is okay, as long as you
55           verify with e.g. "nm libperl.a|egrep -v ' [TURtr] '" (if your "nm"
56           has BSD-style output) that the data you added really is read-only.
57           (If it is, it shouldn't show up in the output of that command.)
58
59           If you want to have static strings, make them constant:
60
61             static const char etc[] = "...";
62
63           If you want to have arrays of constant strings, note carefully the
64           right combination of "const"s:
65
66               static const char * const yippee[] =
67                   {"hi", "ho", "silver"};
68
69           There is a way to completely hide any modifiable globals (they are
70           all moved to heap), the compilation setting
71           "-DPERL_GLOBAL_STRUCT_PRIVATE". It is not normally used, but can be
72           used for testing, read more about it in "Background and
73           PERL_IMPLICIT_CONTEXT" in perlguts.
74
75       ·   Not exporting your new function
76
77           Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any
78           function that is part of the public API (the shared Perl library)
79           to be explicitly marked as exported. See the discussion about
80           embed.pl in perlguts.
81
82       ·   Exporting your new function
83
84           The new shiny result of either genuine new functionality or your
85           arduous refactoring is now ready and correctly exported. So what
86           could possibly go wrong?
87
88           Maybe simply that your function did not need to be exported in the
89           first place. Perl has a long and not so glorious history of
90           exporting functions that it should not have.
91
92           If the function is used only inside one source code file, make it
93           static. See the discussion about embed.pl in perlguts.
94
95           If the function is used across several files, but intended only for
96           Perl's internal use (and this should be the common case), do not
97           export it to the public API. See the discussion about embed.pl in
98           perlguts.
99
100   Portability problems
101       The following are common causes of compilation and/or execution
102       failures, not common to Perl as such. The C FAQ is good bedtime
103       reading. Please test your changes with as many C compilers and
104       platforms as possible; we will, anyway, and it's nice to save oneself
105       from public embarrassment.
106
107       If using gcc, you can add the "-std=c89" option which will hopefully
108       catch most of these unportabilities. (However it might also catch
109       incompatibilities in your system's header files.)
110
111       Use the Configure "-Dgccansipedantic" flag to enable the gcc "-ansi
112       -pedantic" flags which enforce stricter ANSI rules.
113
114       If using the "gcc -Wall" note that not all the possible warnings (like
115       "-Wunitialized") are given unless you also compile with "-O".
116
117       Note that if using gcc, starting from Perl 5.9.5 the Perl core source
118       code files (the ones at the top level of the source code distribution,
119       but not e.g. the extensions under ext/) are automatically compiled with
120       as many as possible of the "-std=c89", "-ansi", "-pedantic", and a
121       selection of "-W" flags (see cflags.SH).
122
123       Also study perlport carefully to avoid any bad assumptions about the
124       operating system, filesystems, and so forth.
125
126       You may once in a while try a "make microperl" to see whether we can
127       still compile Perl with just the bare minimum of interfaces. (See
128       README.micro.)
129
130       Do not assume an operating system indicates a certain compiler.
131
132       ·   Casting pointers to integers or casting integers to pointers
133
134               void castaway(U8* p)
135               {
136                 IV i = p;
137
138           or
139
140               void castaway(U8* p)
141               {
142                 IV i = (IV)p;
143
144           Both are bad, and broken, and unportable. Use the PTR2IV() macro
145           that does it right. (Likewise, there are PTR2UV(), PTR2NV(),
146           INT2PTR(), and NUM2PTR().)
147
148       ·   Casting between data function pointers and data pointers
149
150           Technically speaking casting between function pointers and data
151           pointers is unportable and undefined, but practically speaking it
152           seems to work, but you should use the FPTR2DPTR() and DPTR2FPTR()
153           macros.  Sometimes you can also play games with unions.
154
155       ·   Assuming sizeof(int) == sizeof(long)
156
157           There are platforms where longs are 64 bits, and platforms where
158           ints are 64 bits, and while we are out to shock you, even platforms
159           where shorts are 64 bits. This is all legal according to the C
160           standard. (In other words, "long long" is not a portable way to
161           specify 64 bits, and "long long" is not even guaranteed to be any
162           wider than "long".)
163
164           Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth.
165           Avoid things like I32 because they are not guaranteed to be exactly
166           32 bits, they are at least 32 bits, nor are they guaranteed to be
167           int or long. If you really explicitly need 64-bit variables, use
168           I64 and U64, but only if guarded by HAS_QUAD.
169
170       ·   Assuming one can dereference any type of pointer for any type of
171           data
172
173             char *p = ...;
174             long pony = *p;    /* BAD */
175
176           Many platforms, quite rightly so, will give you a core dump instead
177           of a pony if the p happens not to be correctly aligned.
178
179       ·   Lvalue casts
180
181             (int)*p = ...;    /* BAD */
182
183           Simply not portable. Get your lvalue to be of the right type, or
184           maybe use temporary variables, or dirty tricks with unions.
185
186       ·   Assume anything about structs (especially the ones you don't
187           control, like the ones coming from the system headers)
188
189           ·       That a certain field exists in a struct
190
191           ·       That no other fields exist besides the ones you know of
192
193           ·       That a field is of certain signedness, sizeof, or type
194
195           ·       That the fields are in a certain order
196
197                   ·       While C guarantees the ordering specified in the
198                           struct definition, between different platforms the
199                           definitions might differ
200
201           ·       That the sizeof(struct) or the alignments are the same
202                   everywhere
203
204                   ·       There might be padding bytes between the fields to
205                           align the fields - the bytes can be anything
206
207                   ·       Structs are required to be aligned to the maximum
208                           alignment required by the fields - which for native
209                           types is for usually equivalent to sizeof() of the
210                           field
211
212       ·   Assuming the character set is ASCIIish
213
214           Perl can compile and run under EBCDIC platforms. See perlebcdic.
215           This is transparent for the most part, but because the character
216           sets differ, you shouldn't use numeric (decimal, octal, nor hex)
217           constants to refer to characters. You can safely say 'A', but not
218           0x41. You can safely say '\n', but not \012. If a character doesn't
219           have a trivial input form, you can create a #define for it in both
220           "utfebcdic.h" and "utf8.h", so that it resolves to different values
221           depending on the character set being used. (There are three
222           different EBCDIC character sets defined in "utfebcdic.h", so it
223           might be best to insert the #define three times in that file.)
224
225           Also, the range 'A' - 'Z' in ASCII is an unbroken sequence of 26
226           upper case alphabetic characters. That is not true in EBCDIC. Nor
227           for 'a' to 'z'. But '0' - '9' is an unbroken range in both systems.
228           Don't assume anything about other ranges.
229
230           Many of the comments in the existing code ignore the possibility of
231           EBCDIC, and may be wrong therefore, even if the code works. This is
232           actually a tribute to the successful transparent insertion of being
233           able to handle EBCDIC without having to change pre-existing code.
234
235           UTF-8 and UTF-EBCDIC are two different encodings used to represent
236           Unicode code points as sequences of bytes. Macros  with the same
237           names (but different definitions) in "utf8.h" and "utfebcdic.h" are
238           used to allow the calling code to think that there is only one such
239           encoding.  This is almost always referred to as "utf8", but it
240           means the EBCDIC version as well. Again, comments in the code may
241           well be wrong even if the code itself is right. For example, the
242           concept of "invariant characters" differs between ASCII and EBCDIC.
243           On ASCII platforms, only characters that do not have the high-order
244           bit set (i.e. whose ordinals are strict ASCII, 0 - 127) are
245           invariant, and the documentation and comments in the code may
246           assume that, often referring to something like, say, "hibit". The
247           situation differs and is not so simple on EBCDIC machines, but as
248           long as the code itself uses the "NATIVE_IS_INVARIANT()" macro
249           appropriately, it works, even if the comments are wrong.
250
251       ·   Assuming the character set is just ASCII
252
253           ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128
254           extra characters have different meanings depending on the locale.
255           Absent a locale, currently these extra characters are generally
256           considered to be unassigned, and this has presented some problems.
257           This is being changed starting in 5.12 so that these characters
258           will be considered to be Latin-1 (ISO-8859-1).
259
260       ·   Mixing #define and #ifdef
261
262             #define BURGLE(x) ... \
263             #ifdef BURGLE_OLD_STYLE        /* BAD */
264             ... do it the old way ... \
265             #else
266             ... do it the new way ... \
267             #endif
268
269           You cannot portably "stack" cpp directives. For example in the
270           above you need two separate BURGLE() #defines, one for each #ifdef
271           branch.
272
273       ·   Adding non-comment stuff after #endif or #else
274
275             #ifdef SNOSH
276             ...
277             #else !SNOSH    /* BAD */
278             ...
279             #endif SNOSH    /* BAD */
280
281           The #endif and #else cannot portably have anything non-comment
282           after them. If you want to document what is going (which is a good
283           idea especially if the branches are long), use (C) comments:
284
285             #ifdef SNOSH
286             ...
287             #else /* !SNOSH */
288             ...
289             #endif /* SNOSH */
290
291           The gcc option "-Wendif-labels" warns about the bad variant (by
292           default on starting from Perl 5.9.4).
293
294       ·   Having a comma after the last element of an enum list
295
296             enum color {
297               CERULEAN,
298               CHARTREUSE,
299               CINNABAR,     /* BAD */
300             };
301
302           is not portable. Leave out the last comma.
303
304           Also note that whether enums are implicitly morphable to ints
305           varies between compilers, you might need to (int).
306
307       ·   Using //-comments
308
309             // This function bamfoodles the zorklator.   /* BAD */
310
311           That is C99 or C++. Perl is C89. Using the //-comments is silently
312           allowed by many C compilers but cranking up the ANSI C89 strictness
313           (which we like to do) causes the compilation to fail.
314
315       ·   Mixing declarations and code
316
317             void zorklator()
318             {
319               int n = 3;
320               set_zorkmids(n);    /* BAD */
321               int q = 4;
322
323           That is C99 or C++. Some C compilers allow that, but you shouldn't.
324
325           The gcc option "-Wdeclaration-after-statements" scans for such
326           problems (by default on starting from Perl 5.9.4).
327
328       ·   Introducing variables inside for()
329
330             for(int i = ...; ...; ...) {    /* BAD */
331
332           That is C99 or C++. While it would indeed be awfully nice to have
333           that also in C89, to limit the scope of the loop variable, alas, we
334           cannot.
335
336       ·   Mixing signed char pointers with unsigned char pointers
337
338             int foo(char *s) { ... }
339             ...
340             unsigned char *t = ...; /* Or U8* t = ... */
341             foo(t);   /* BAD */
342
343           While this is legal practice, it is certainly dubious, and
344           downright fatal in at least one platform: for example VMS cc
345           considers this a fatal error. One cause for people often making
346           this mistake is that a "naked char" and therefore dereferencing a
347           "naked char pointer" have an undefined signedness: it depends on
348           the compiler and the flags of the compiler and the underlying
349           platform whether the result is signed or unsigned. For this very
350           same reason using a 'char' as an array index is bad.
351
352       ·   Macros that have string constants and their arguments as substrings
353           of the string constants
354
355             #define FOO(n) printf("number = %d\n", n)    /* BAD */
356             FOO(10);
357
358           Pre-ANSI semantics for that was equivalent to
359
360             printf("10umber = %d\10");
361
362           which is probably not what you were expecting. Unfortunately at
363           least one reasonably common and modern C compiler does "real
364           backward compatibility" here, in AIX that is what still happens
365           even though the rest of the AIX compiler is very happily C89.
366
367       ·   Using printf formats for non-basic C types
368
369              IV i = ...;
370              printf("i = %d\n", i);    /* BAD */
371
372           While this might by accident work in some platform (where IV
373           happens to be an "int"), in general it cannot. IV might be
374           something larger. Even worse the situation is with more specific
375           types (defined by Perl's configuration step in config.h):
376
377              Uid_t who = ...;
378              printf("who = %d\n", who);    /* BAD */
379
380           The problem here is that Uid_t might be not only not "int"-wide but
381           it might also be unsigned, in which case large uids would be
382           printed as negative values.
383
384           There is no simple solution to this because of printf()'s limited
385           intelligence, but for many types the right format is available as
386           with either 'f' or '_f' suffix, for example:
387
388              IVdf /* IV in decimal */
389              UVxf /* UV is hexadecimal */
390
391              printf("i = %"IVdf"\n", i); /* The IVdf is a string constant. */
392
393              Uid_t_f /* Uid_t in decimal */
394
395              printf("who = %"Uid_t_f"\n", who);
396
397           Or you can try casting to a "wide enough" type:
398
399              printf("i = %"IVdf"\n", (IV)something_very_small_and_signed);
400
401           Also remember that the %p format really does require a void
402           pointer:
403
404              U8* p = ...;
405              printf("p = %p\n", (void*)p);
406
407           The gcc option "-Wformat" scans for such problems.
408
409       ·   Blindly using variadic macros
410
411           gcc has had them for a while with its own syntax, and C99 brought
412           them with a standardized syntax. Don't use the former, and use the
413           latter only if the HAS_C99_VARIADIC_MACROS is defined.
414
415       ·   Blindly passing va_list
416
417           Not all platforms support passing va_list to further varargs
418           (stdarg) functions. The right thing to do is to copy the va_list
419           using the Perl_va_copy() if the NEED_VA_COPY is defined.
420
421       ·   Using gcc statement expressions
422
423              val = ({...;...;...});    /* BAD */
424
425           While a nice extension, it's not portable. The Perl code does
426           admittedly use them if available to gain some extra speed
427           (essentially as a funky form of inlining), but you shouldn't.
428
429       ·   Binding together several statements in a macro
430
431           Use the macros STMT_START and STMT_END.
432
433              STMT_START {
434                 ...
435              } STMT_END
436
437       ·   Testing for operating systems or versions when should be testing
438           for features
439
440             #ifdef __FOONIX__    /* BAD */
441             foo = quux();
442             #endif
443
444           Unless you know with 100% certainty that quux() is only ever
445           available for the "Foonix" operating system and that is available
446           and correctly working for all past, present, and future versions of
447           "Foonix", the above is very wrong. This is more correct (though
448           still not perfect, because the below is a compile-time check):
449
450             #ifdef HAS_QUUX
451             foo = quux();
452             #endif
453
454           How does the HAS_QUUX become defined where it needs to be?  Well,
455           if Foonix happens to be Unixy enough to be able to run the
456           Configure script, and Configure has been taught about detecting and
457           testing quux(), the HAS_QUUX will be correctly defined. In other
458           platforms, the corresponding configuration step will hopefully do
459           the same.
460
461           In a pinch, if you cannot wait for Configure to be educated, or if
462           you have a good hunch of where quux() might be available, you can
463           temporarily try the following:
464
465             #if (defined(__FOONIX__) || defined(__BARNIX__))
466             # define HAS_QUUX
467             #endif
468
469             ...
470
471             #ifdef HAS_QUUX
472             foo = quux();
473             #endif
474
475           But in any case, try to keep the features and operating systems
476           separate.
477
478   Problematic System Interfaces
479       ·   malloc(0), realloc(0), calloc(0, 0) are non-portable. To be
480           portable allocate at least one byte. (In general you should rarely
481           need to work at this low level, but instead use the various malloc
482           wrappers.)
483
484       ·   snprintf() - the return type is unportable. Use my_snprintf()
485           instead.
486
487   Security problems
488       Last but not least, here are various tips for safer coding.
489
490       ·   Do not use gets()
491
492           Or we will publicly ridicule you. Seriously.
493
494       ·   Do not use strcpy() or strcat() or strncpy() or strncat()
495
496           Use my_strlcpy() and my_strlcat() instead: they either use the
497           native implementation, or Perl's own implementation (borrowed from
498           the public domain implementation of INN).
499
500       ·   Do not use sprintf() or vsprintf()
501
502           If you really want just plain byte strings, use my_snprintf() and
503           my_vsnprintf() instead, which will try to use snprintf() and
504           vsnprintf() if those safer APIs are available. If you want
505           something fancier than a plain byte string, use SVs and
506           Perl_sv_catpvf().
507

DEBUGGING

509       You can compile a special debugging version of Perl, which allows you
510       to use the "-D" option of Perl to tell more about what Perl is doing.
511       But sometimes there is no alternative than to dive in with a debugger,
512       either to see the stack trace of a core dump (very useful in a bug
513       report), or trying to figure out what went wrong before the core dump
514       happened, or how did we end up having wrong or unexpected results.
515
516   Poking at Perl
517       To really poke around with Perl, you'll probably want to build Perl for
518       debugging, like this:
519
520           ./Configure -d -D optimize=-g
521           make
522
523       "-g" is a flag to the C compiler to have it produce debugging
524       information which will allow us to step through a running program, and
525       to see in which C function we are at (without the debugging information
526       we might see only the numerical addresses of the functions, which is
527       not very helpful).
528
529       Configure will also turn on the "DEBUGGING" compilation symbol which
530       enables all the internal debugging code in Perl. There are a whole
531       bunch of things you can debug with this: perlrun lists them all, and
532       the best way to find out about them is to play about with them. The
533       most useful options are probably
534
535           l  Context (loop) stack processing
536           t  Trace execution
537           o  Method and overloading resolution
538           c  String/numeric conversions
539
540       Some of the functionality of the debugging code can be achieved using
541       XS modules.
542
543           -Dr => use re 'debug'
544           -Dx => use O 'Debug'
545
546   Using a source-level debugger
547       If the debugging output of "-D" doesn't help you, it's time to step
548       through perl's execution with a source-level debugger.
549
550       ·  We'll use "gdb" for our examples here; the principles will apply to
551          any debugger (many vendors call their debugger "dbx"), but check the
552          manual of the one you're using.
553
554       To fire up the debugger, type
555
556           gdb ./perl
557
558       Or if you have a core dump:
559
560           gdb ./perl core
561
562       You'll want to do that in your Perl source tree so the debugger can
563       read the source code. You should see the copyright message, followed by
564       the prompt.
565
566           (gdb)
567
568       "help" will get you into the documentation, but here are the most
569       useful commands:
570
571       ·  run [args]
572
573          Run the program with the given arguments.
574
575       ·  break function_name
576
577       ·  break source.c:xxx
578
579          Tells the debugger that we'll want to pause execution when we reach
580          either the named function (but see "Internal Functions" in
581          perlguts!) or the given line in the named source file.
582
583       ·  step
584
585          Steps through the program a line at a time.
586
587       ·  next
588
589          Steps through the program a line at a time, without descending into
590          functions.
591
592       ·  continue
593
594          Run until the next breakpoint.
595
596       ·  finish
597
598          Run until the end of the current function, then stop again.
599
600       ·  'enter'
601
602          Just pressing Enter will do the most recent operation again - it's a
603          blessing when stepping through miles of source code.
604
605       ·  print
606
607          Execute the given C code and print its results. WARNING: Perl makes
608          heavy use of macros, and gdb does not necessarily support macros
609          (see later "gdb macro support"). You'll have to substitute them
610          yourself, or to invoke cpp on the source code files (see "The .i
611          Targets") So, for instance, you can't say
612
613              print SvPV_nolen(sv)
614
615          but you have to say
616
617              print Perl_sv_2pv_nolen(sv)
618
619       You may find it helpful to have a "macro dictionary", which you can
620       produce by saying "cpp -dM perl.c | sort". Even then, cpp won't
621       recursively apply those macros for you.
622
623   gdb macro support
624       Recent versions of gdb have fairly good macro support, but in order to
625       use it you'll need to compile perl with macro definitions included in
626       the debugging information. Using gcc version 3.1, this means
627       configuring with "-Doptimize=-g3". Other compilers might use a
628       different switch (if they support debugging macros at all).
629
630   Dumping Perl Data Structures
631       One way to get around this macro hell is to use the dumping functions
632       in dump.c; these work a little like an internal Devel::Peek, but they
633       also cover OPs and other structures that you can't get at from Perl.
634       Let's take an example.  We'll use the "$a = $b + $c" we used before,
635       but give it a bit of context: "$b = "6XXXX"; $c = 2.3;". Where's a good
636       place to stop and poke around?
637
638       What about "pp_add", the function we examined earlier to implement the
639       "+" operator:
640
641           (gdb) break Perl_pp_add
642           Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.
643
644       Notice we use "Perl_pp_add" and not "pp_add" - see "Internal Functions"
645       in perlguts. With the breakpoint in place, we can run our program:
646
647           (gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c'
648
649       Lots of junk will go past as gdb reads in the relevant source files and
650       libraries, and then:
651
652           Breakpoint 1, Perl_pp_add () at pp_hot.c:309
653           309         dSP; dATARGET; tryAMAGICbin(add,opASSIGN);
654           (gdb) step
655           311           dPOPTOPnnrl_ul;
656           (gdb)
657
658       We looked at this bit of code before, and we said that "dPOPTOPnnrl_ul"
659       arranges for two "NV"s to be placed into "left" and "right" - let's
660       slightly expand it:
661
662        #define dPOPTOPnnrl_ul  NV right = POPn; \
663                                SV *leftsv = TOPs; \
664                                NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0
665
666       "POPn" takes the SV from the top of the stack and obtains its NV either
667       directly (if "SvNOK" is set) or by calling the "sv_2nv" function.
668       "TOPs" takes the next SV from the top of the stack - yes, "POPn" uses
669       "TOPs" - but doesn't remove it. We then use "SvNV" to get the NV from
670       "leftsv" in the same way as before - yes, "POPn" uses "SvNV".
671
672       Since we don't have an NV for $b, we'll have to use "sv_2nv" to convert
673       it. If we step again, we'll find ourselves there:
674
675           Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
676           1669        if (!sv)
677           (gdb)
678
679       We can now use "Perl_sv_dump" to investigate the SV:
680
681           SV = PV(0xa057cc0) at 0xa0675d0
682           REFCNT = 1
683           FLAGS = (POK,pPOK)
684           PV = 0xa06a510 "6XXXX"\0
685           CUR = 5
686           LEN = 6
687           $1 = void
688
689       We know we're going to get 6 from this, so let's finish the subroutine:
690
691           (gdb) finish
692           Run till exit from #0  Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
693           0x462669 in Perl_pp_add () at pp_hot.c:311
694           311           dPOPTOPnnrl_ul;
695
696       We can also dump out this op: the current op is always stored in
697       "PL_op", and we can dump it with "Perl_op_dump". This'll give us
698       similar output to B::Debug.
699
700           {
701           13  TYPE = add  ===> 14
702               TARG = 1
703               FLAGS = (SCALAR,KIDS)
704               {
705                   TYPE = null  ===> (12)
706                     (was rv2sv)
707                   FLAGS = (SCALAR,KIDS)
708                   {
709           11          TYPE = gvsv  ===> 12
710                       FLAGS = (SCALAR)
711                       GV = main::b
712                   }
713               }
714
715       # finish this later #
716

SOURCE CODE STATIC ANALYSIS

718       Various tools exist for analysing C source code statically, as opposed
719       to dynamically, that is, without executing the code. It is possible to
720       detect resource leaks, undefined behaviour, type mismatches,
721       portability problems, code paths that would cause illegal memory
722       accesses, and other similar problems by just parsing the C code and
723       looking at the resulting graph, what does it tell about the execution
724       and data flows. As a matter of fact, this is exactly how C compilers
725       know to give warnings about dubious code.
726
727   lint, splint
728       The good old C code quality inspector, "lint", is available in several
729       platforms, but please be aware that there are several different
730       implementations of it by different vendors, which means that the flags
731       are not identical across different platforms.
732
733       There is a lint variant called "splint" (Secure Programming Lint)
734       available from http://www.splint.org/ that should compile on any Unix-
735       like platform.
736
737       There are "lint" and <splint> targets in Makefile, but you may have to
738       diddle with the flags (see above).
739
740   Coverity
741       Coverity (http://www.coverity.com/) is a product similar to lint and as
742       a testbed for their product they periodically check several open source
743       projects, and they give out accounts to open source developers to the
744       defect databases.
745
746   cpd (cut-and-paste detector)
747       The cpd tool detects cut-and-paste coding. If one instance of the cut-
748       and-pasted code changes, all the other spots should probably be
749       changed, too. Therefore such code should probably be turned into a
750       subroutine or a macro.
751
752       cpd (http://pmd.sourceforge.net/cpd.html) is part of the pmd project
753       (http://pmd.sourceforge.net/). pmd was originally written for static
754       analysis of Java code, but later the cpd part of it was extended to
755       parse also C and C++.
756
757       Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the
758       pmd-X.Y.jar from it, and then run that on source code thusly:
759
760         java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files /some/where/src --language c > cpd.txt
761
762       You may run into memory limits, in which case you should use the -Xmx
763       option:
764
765         java -Xmx512M ...
766
767   gcc warnings
768       Though much can be written about the inconsistency and coverage
769       problems of gcc warnings (like "-Wall" not meaning "all the warnings",
770       or some common portability problems not being covered by "-Wall", or
771       "-ansi" and "-pedantic" both being a poorly defined collection of
772       warnings, and so forth), gcc is still a useful tool in keeping our
773       coding nose clean.
774
775       The "-Wall" is by default on.
776
777       The "-ansi" (and its sidekick, "-pedantic") would be nice to be on
778       always, but unfortunately they are not safe on all platforms, they can
779       for example cause fatal conflicts with the system headers (Solaris
780       being a prime example). If Configure "-Dgccansipedantic" is used, the
781       "cflags" frontend selects "-ansi -pedantic" for the platforms where
782       they are known to be safe.
783
784       Starting from Perl 5.9.4 the following extra flags are added:
785
786       ·   "-Wendif-labels"
787
788       ·   "-Wextra"
789
790       ·   "-Wdeclaration-after-statement"
791
792       The following flags would be nice to have but they would first need
793       their own Augean stablemaster:
794
795       ·   "-Wpointer-arith"
796
797       ·   "-Wshadow"
798
799       ·   "-Wstrict-prototypes"
800
801       The "-Wtraditional" is another example of the annoying tendency of gcc
802       to bundle a lot of warnings under one switch (it would be impossible to
803       deploy in practice because it would complain a lot) but it does contain
804       some warnings that would be beneficial to have available on their own,
805       such as the warning about string constants inside macros containing the
806       macro arguments: this behaved differently pre-ANSI than it does in
807       ANSI, and some C compilers are still in transition, AIX being an
808       example.
809
810   Warnings of other C compilers
811       Other C compilers (yes, there are other C compilers than gcc) often
812       have their "strict ANSI" or "strict ANSI with some portability
813       extensions" modes on, like for example the Sun Workshop has its "-Xa"
814       mode on (though implicitly), or the DEC (these days, HP...) has its
815       "-std1" mode on.
816

MEMORY DEBUGGERS

818       NOTE 1: Running under memory debuggers such as Purify, valgrind, or
819       Third Degree greatly slows down the execution: seconds become minutes,
820       minutes become hours. For example as of Perl 5.8.1, the
821       ext/Encode/t/Unicode.t takes extraordinarily long to complete under
822       e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more
823       than six hours, even on a snappy computer. The said test must be doing
824       something that is quite unfriendly for memory debuggers. If you don't
825       feel like waiting, that you can simply kill away the perl process.
826
827       NOTE 2: To minimize the number of memory leak false alarms (see
828       "PERL_DESTRUCT_LEVEL" for more information), you have to set the
829       environment variable PERL_DESTRUCT_LEVEL to 2.
830
831       For csh-like shells:
832
833           setenv PERL_DESTRUCT_LEVEL 2
834
835       For Bourne-type shells:
836
837           PERL_DESTRUCT_LEVEL=2
838           export PERL_DESTRUCT_LEVEL
839
840       In Unixy environments you can also use the "env" command:
841
842           env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ...
843
844       NOTE 3: There are known memory leaks when there are compile-time errors
845       within eval or require, seeing "S_doeval" in the call stack is a good
846       sign of these. Fixing these leaks is non-trivial, unfortunately, but
847       they must be fixed eventually.
848
849       NOTE 4: DynaLoader will not clean up after itself completely unless
850       Perl is built with the Configure option
851       "-Accflags=-DDL_UNLOAD_ALL_AT_EXIT".
852
853   Rational Software's Purify
854       Purify is a commercial tool that is helpful in identifying memory
855       overruns, wild pointers, memory leaks and other such badness. Perl must
856       be compiled in a specific way for optimal testing with Purify.  Purify
857       is available under Windows NT, Solaris, HP-UX, SGI, and Siemens Unix.
858
859       Purify on Unix
860
861       On Unix, Purify creates a new Perl binary. To get the most benefit out
862       of Purify, you should create the perl to Purify using:
863
864           sh Configure -Accflags=-DPURIFY -Doptimize='-g' \
865            -Uusemymalloc -Dusemultiplicity
866
867       where these arguments mean:
868
869       ·   -Accflags=-DPURIFY
870
871           Disables Perl's arena memory allocation functions, as well as
872           forcing use of memory allocation functions derived from the system
873           malloc.
874
875       ·   -Doptimize='-g'
876
877           Adds debugging information so that you see the exact source
878           statements where the problem occurs. Without this flag, all you
879           will see is the source filename of where the error occurred.
880
881       ·   -Uusemymalloc
882
883           Disable Perl's malloc so that Purify can more closely monitor
884           allocations and leaks. Using Perl's malloc will make Purify report
885           most leaks in the "potential" leaks category.
886
887       ·   -Dusemultiplicity
888
889           Enabling the multiplicity option allows perl to clean up thoroughly
890           when the interpreter shuts down, which reduces the number of bogus
891           leak reports from Purify.
892
893       Once you've compiled a perl suitable for Purify'ing, then you can just:
894
895           make pureperl
896
897       which creates a binary named 'pureperl' that has been Purify'ed. This
898       binary is used in place of the standard 'perl' binary when you want to
899       debug Perl memory problems.
900
901       As an example, to show any memory leaks produced during the standard
902       Perl testset you would create and run the Purify'ed perl as:
903
904           make pureperl
905           cd t
906           ../pureperl -I../lib harness
907
908       which would run Perl on test.pl and report any memory problems.
909
910       Purify outputs messages in "Viewer" windows by default. If you don't
911       have a windowing environment or if you simply want the Purify output to
912       unobtrusively go to a log file instead of to the interactive window,
913       use these following options to output to the log file "perl.log":
914
915           setenv PURIFYOPTIONS "-chain-length=25 -windows=no \
916            -log-file=perl.log -append-logfile=yes"
917
918       If you plan to use the "Viewer" windows, then you only need this
919       option:
920
921           setenv PURIFYOPTIONS "-chain-length=25"
922
923       In Bourne-type shells:
924
925           PURIFYOPTIONS="..."
926           export PURIFYOPTIONS
927
928       or if you have the "env" utility:
929
930           env PURIFYOPTIONS="..." ../pureperl ...
931
932       Purify on NT
933
934       Purify on Windows NT instruments the Perl binary 'perl.exe' on the fly.
935        There are several options in the makefile you should change to get the
936       most use out of Purify:
937
938       ·   DEFINES
939
940           You should add -DPURIFY to the DEFINES line so the DEFINES line
941           looks something like:
942
943              DEFINES = -DWIN32 -D_CONSOLE -DNO_STRICT $(CRYPT_FLAG) -DPURIFY=1
944
945           to disable Perl's arena memory allocation functions, as well as to
946           force use of memory allocation functions derived from the system
947           malloc.
948
949       ·   USE_MULTI = define
950
951           Enabling the multiplicity option allows perl to clean up thoroughly
952           when the interpreter shuts down, which reduces the number of bogus
953           leak reports from Purify.
954
955       ·   #PERL_MALLOC = define
956
957           Disable Perl's malloc so that Purify can more closely monitor
958           allocations and leaks. Using Perl's malloc will make Purify report
959           most leaks in the "potential" leaks category.
960
961       ·   CFG = Debug
962
963           Adds debugging information so that you see the exact source
964           statements where the problem occurs. Without this flag, all you
965           will see is the source filename of where the error occurred.
966
967       As an example, to show any memory leaks produced during the standard
968       Perl testset you would create and run Purify as:
969
970           cd win32
971           make
972           cd ../t
973           purify ../perl -I../lib harness
974
975       which would instrument Perl in memory, run Perl on test.pl, then
976       finally report any memory problems.
977
978   valgrind
979       The excellent valgrind tool can be used to find out both memory leaks
980       and illegal memory accesses. As of version 3.3.0, Valgrind only
981       supports Linux on x86, x86-64 and PowerPC and Darwin (OS X) on x86 and
982       x86-64). The special "test.valgrind" target can be used to run the
983       tests under valgrind. Found errors and memory leaks are logged in files
984       named testfile.valgrind.
985
986       Valgrind also provides a cachegrind tool, invoked on perl as:
987
988           VG_OPTS=--tool=cachegrind make test.valgrind
989
990       As system libraries (most notably glibc) are also triggering errors,
991       valgrind allows to suppress such errors using suppression files. The
992       default suppression file that comes with valgrind already catches a lot
993       of them. Some additional suppressions are defined in t/perl.supp.
994
995       To get valgrind and for more information see
996
997           http://valgrind.org/
998

PROFILING

1000       Depending on your platform there are various ways of profiling Perl.
1001
1002       There are two commonly used techniques of profiling executables:
1003       statistical time-sampling and basic-block counting.
1004
1005       The first method takes periodically samples of the CPU program counter,
1006       and since the program counter can be correlated with the code generated
1007       for functions, we get a statistical view of in which functions the
1008       program is spending its time. The caveats are that very small/fast
1009       functions have lower probability of showing up in the profile, and that
1010       periodically interrupting the program (this is usually done rather
1011       frequently, in the scale of milliseconds) imposes an additional
1012       overhead that may skew the results. The first problem can be alleviated
1013       by running the code for longer (in general this is a good idea for
1014       profiling), the second problem is usually kept in guard by the
1015       profiling tools themselves.
1016
1017       The second method divides up the generated code into basic blocks.
1018       Basic blocks are sections of code that are entered only in the
1019       beginning and exited only at the end. For example, a conditional jump
1020       starts a basic block. Basic block profiling usually works by
1021       instrumenting the code by adding enter basic block #nnnn book-keeping
1022       code to the generated code. During the execution of the code the basic
1023       block counters are then updated appropriately. The caveat is that the
1024       added extra code can skew the results: again, the profiling tools
1025       usually try to factor their own effects out of the results.
1026
1027   Gprof Profiling
1028       gprof is a profiling tool available in many Unix platforms, it uses
1029       statistical time-sampling.
1030
1031       You can build a profiled version of perl called "perl.gprof" by
1032       invoking the make target "perl.gprof"  (What is required is that Perl
1033       must be compiled using the "-pg" flag, you may need to re-Configure).
1034       Running the profiled version of Perl will create an output file called
1035       gmon.out is created which contains the profiling data collected during
1036       the execution.
1037
1038       The gprof tool can then display the collected data in various ways.
1039       Usually gprof understands the following options:
1040
1041       ·   -a
1042
1043           Suppress statically defined functions from the profile.
1044
1045       ·   -b
1046
1047           Suppress the verbose descriptions in the profile.
1048
1049       ·   -e routine
1050
1051           Exclude the given routine and its descendants from the profile.
1052
1053       ·   -f routine
1054
1055           Display only the given routine and its descendants in the profile.
1056
1057       ·   -s
1058
1059           Generate a summary file called gmon.sum which then may be given to
1060           subsequent gprof runs to accumulate data over several runs.
1061
1062       ·   -z
1063
1064           Display routines that have zero usage.
1065
1066       For more detailed explanation of the available commands and output
1067       formats, see your own local documentation of gprof.
1068
1069       quick hint:
1070
1071           $ sh Configure -des -Dusedevel -Doptimize='-pg' && make perl.gprof
1072           $ ./perl.gprof someprog # creates gmon.out in current directory
1073           $ gprof ./perl.gprof > out
1074           $ view out
1075
1076   GCC gcov Profiling
1077       Starting from GCC 3.0 basic block profiling is officially available for
1078       the GNU CC.
1079
1080       You can build a profiled version of perl called perl.gcov by invoking
1081       the make target "perl.gcov" (what is required that Perl must be
1082       compiled using gcc with the flags "-fprofile-arcs -ftest-coverage", you
1083       may need to re-Configure).
1084
1085       Running the profiled version of Perl will cause profile output to be
1086       generated. For each source file an accompanying ".da" file will be
1087       created.
1088
1089       To display the results you use the "gcov" utility (which should be
1090       installed if you have gcc 3.0 or newer installed). gcov is run on
1091       source code files, like this
1092
1093           gcov sv.c
1094
1095       which will cause sv.c.gcov to be created. The .gcov files contain the
1096       source code annotated with relative frequencies of execution indicated
1097       by "#" markers.
1098
1099       Useful options of gcov include "-b" which will summarise the basic
1100       block, branch, and function call coverage, and "-c" which instead of
1101       relative frequencies will use the actual counts. For more information
1102       on the use of gcov and basic block profiling with gcc, see the latest
1103       GNU CC manual, as of GCC 3.0 see
1104
1105           http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc.html
1106
1107       and its section titled "8. gcov: a Test Coverage Program"
1108
1109           http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc_8.html#SEC132
1110
1111       quick hint:
1112
1113           $ sh Configure -des -Dusedevel -Doptimize='-g' \
1114               -Accflags='-fprofile-arcs -ftest-coverage' \
1115               -Aldflags='-fprofile-arcs -ftest-coverage' && make perl.gcov
1116           $ rm -f regexec.c.gcov regexec.gcda
1117           $ ./perl.gcov
1118           $ gcov regexec.c
1119           $ view regexec.c.gcov
1120

MISCELLANEOUS TRICKS

1122   PERL_DESTRUCT_LEVEL
1123       If you want to run any of the tests yourself manually using e.g.
1124       valgrind, or the pureperl or perl.third executables, please note that
1125       by default perl does not explicitly cleanup all the memory it has
1126       allocated (such as global memory arenas) but instead lets the exit() of
1127       the whole program "take care" of such allocations, also known as
1128       "global destruction of objects".
1129
1130       There is a way to tell perl to do complete cleanup: set the environment
1131       variable PERL_DESTRUCT_LEVEL to a non-zero value. The t/TEST wrapper
1132       does set this to 2, and this is what you need to do too, if you don't
1133       want to see the "global leaks": For example, for "third-degreed" Perl:
1134
1135               env PERL_DESTRUCT_LEVEL=2 ./perl.third -Ilib t/foo/bar.t
1136
1137       (Note: the mod_perl apache module uses also this environment variable
1138       for its own purposes and extended its semantics. Refer to the mod_perl
1139       documentation for more information. Also, spawned threads do the
1140       equivalent of setting this variable to the value 1.)
1141
1142       If, at the end of a run you get the message N scalars leaked, you can
1143       recompile with "-DDEBUG_LEAKING_SCALARS", which will cause the
1144       addresses of all those leaked SVs to be dumped along with details as to
1145       where each SV was originally allocated. This information is also
1146       displayed by Devel::Peek. Note that the extra details recorded with
1147       each SV increases memory usage, so it shouldn't be used in production
1148       environments. It also converts "new_SV()" from a macro into a real
1149       function, so you can use your favourite debugger to discover where
1150       those pesky SVs were allocated.
1151
1152       If you see that you're leaking memory at runtime, but neither valgrind
1153       nor "-DDEBUG_LEAKING_SCALARS" will find anything, you're probably
1154       leaking SVs that are still reachable and will be properly cleaned up
1155       during destruction of the interpreter. In such cases, using the "-Dm"
1156       switch can point you to the source of the leak. If the executable was
1157       built with "-DDEBUG_LEAKING_SCALARS", "-Dm" will output SV allocations
1158       in addition to memory allocations. Each SV allocation has a distinct
1159       serial number that will be written on creation and destruction of the
1160       SV. So if you're executing the leaking code in a loop, you need to look
1161       for SVs that are created, but never destroyed between each cycle. If
1162       such an SV is found, set a conditional breakpoint within "new_SV()" and
1163       make it break only when "PL_sv_serial" is equal to the serial number of
1164       the leaking SV. Then you will catch the interpreter in exactly the
1165       state where the leaking SV is allocated, which is sufficient in many
1166       cases to find the source of the leak.
1167
1168       As "-Dm" is using the PerlIO layer for output, it will by itself
1169       allocate quite a bunch of SVs, which are hidden to avoid recursion. You
1170       can bypass the PerlIO layer if you use the SV logging provided by
1171       "-DPERL_MEM_LOG" instead.
1172
1173   PERL_MEM_LOG
1174       If compiled with "-DPERL_MEM_LOG", both memory and SV allocations go
1175       through logging functions, which is handy for breakpoint setting.
1176
1177       Unless "-DPERL_MEM_LOG_NOIMPL" is also compiled, the logging functions
1178       read $ENV{PERL_MEM_LOG} to determine whether to log the event, and if
1179       so how:
1180
1181           $ENV{PERL_MEM_LOG} =~ /m/           Log all memory ops
1182           $ENV{PERL_MEM_LOG} =~ /s/           Log all SV ops
1183           $ENV{PERL_MEM_LOG} =~ /t/           include timestamp in Log
1184           $ENV{PERL_MEM_LOG} =~ /^(\d+)/      write to FD given (default is 2)
1185
1186       Memory logging is somewhat similar to "-Dm" but is independent of
1187       "-DDEBUGGING", and at a higher level; all uses of Newx(), Renew(), and
1188       Safefree() are logged with the caller's source code file and line
1189       number (and C function name, if supported by the C compiler). In
1190       contrast, "-Dm" is directly at the point of "malloc()". SV logging is
1191       similar.
1192
1193       Since the logging doesn't use PerlIO, all SV allocations are logged and
1194       no extra SV allocations are introduced by enabling the logging. If
1195       compiled with "-DDEBUG_LEAKING_SCALARS", the serial number for each SV
1196       allocation is also logged.
1197
1198   DDD over gdb
1199       Those debugging perl with the DDD frontend over gdb may find the
1200       following useful:
1201
1202       You can extend the data conversion shortcuts menu, so for example you
1203       can display an SV's IV value with one click, without doing any typing.
1204       To do that simply edit ~/.ddd/init file and add after:
1205
1206         ! Display shortcuts.
1207         Ddd*gdbDisplayShortcuts: \
1208         /t ()   // Convert to Bin\n\
1209         /d ()   // Convert to Dec\n\
1210         /x ()   // Convert to Hex\n\
1211         /o ()   // Convert to Oct(\n\
1212
1213       the following two lines:
1214
1215         ((XPV*) (())->sv_any )->xpv_pv  // 2pvx\n\
1216         ((XPVIV*) (())->sv_any )->xiv_iv // 2ivx
1217
1218       so now you can do ivx and pvx lookups or you can plug there the sv_peek
1219       "conversion":
1220
1221         Perl_sv_peek(my_perl, (SV*)()) // sv_peek
1222
1223       (The my_perl is for threaded builds.) Just remember that every line,
1224       but the last one, should end with \n\
1225
1226       Alternatively edit the init file interactively via: 3rd mouse button ->
1227       New Display -> Edit Menu
1228
1229       Note: you can define up to 20 conversion shortcuts in the gdb section.
1230
1231   Poison
1232       If you see in a debugger a memory area mysteriously full of 0xABABABAB
1233       or 0xEFEFEFEF, you may be seeing the effect of the Poison() macros, see
1234       perlclib.
1235
1236   Read-only optrees
1237       Under ithreads the optree is read only. If you want to enforce this, to
1238       check for write accesses from buggy code, compile with
1239       "-DPL_OP_SLAB_ALLOC" to enable the OP slab allocator and
1240       "-DPERL_DEBUG_READONLY_OPS" to enable code that allocates op memory via
1241       "mmap", and sets it read-only at run time. Any write access to an op
1242       results in a "SIGBUS" and abort.
1243
1244       This code is intended for development only, and may not be portable
1245       even to all Unix variants. Also, it is an 80% solution, in that it
1246       isn't able to make all ops read only. Specifically it
1247
1248       ·   1
1249
1250           Only sets read-only on all slabs of ops at "CHECK" time, hence ops
1251           allocated later via "require" or "eval" will be re-write
1252
1253       ·   2
1254
1255           Turns an entire slab of ops read-write if the refcount of any op in
1256           the slab needs to be decreased.
1257
1258       ·   3
1259
1260           Turns an entire slab of ops read-write if any op from the slab is
1261           freed.
1262
1263       It's not possible to turn the slabs to read-only after an action
1264       requiring read-write access, as either can happen during op tree
1265       building time, so there may still be legitimate write access.
1266
1267       However, as an 80% solution it is still effective, as currently it
1268       catches a write access during the generation of Config.pm, which means
1269       that we can't yet build perl with this enabled.
1270
1271   The .i Targets
1272       You can expand the macros in a foo.c file by saying
1273
1274           make foo.i
1275
1276       which will expand the macros using cpp.  Don't be scared by the
1277       results.
1278

AUTHOR

1280       This document was originally written by Nathan Torkington, and is
1281       maintained by the perl5-porters mailing list.
1282
1283
1284
1285perl v5.16.3                      2013-03-04                   PERLHACKTIPS(1)
Impressum