This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
(perl #127384)(CVE-2016-1238) port forward changes from maint
[perl5.git] / regen / embed.pl
1 #!/usr/bin/perl -w
2
3 # Regenerate (overwriting only if changed):
4 #
5 #    embed.h
6 #    embedvar.h
7 #    perlapi.c
8 #    perlapi.h
9 #    proto.h
10 #
11 # from information stored in
12 #
13 #    embed.fnc
14 #    intrpvar.h
15 #    perlvars.h
16 #    regen/opcodes
17 #
18 # Accepts the standard regen_lib -q and -v args.
19 #
20 # This script is normally invoked from regen.pl.
21
22 require 5.004;  # keep this compatible, an old perl is all we may have before
23                 # we build the new one
24
25 use strict;
26
27 BEGIN {
28     # Get function prototypes
29     require 'regen/regen_lib.pl';
30     require 'regen/embed_lib.pl';
31 }
32
33 my $SPLINT = 0; # Turn true for experimental splint support http://www.splint.org
34 my $unflagged_pointers;
35
36 #
37 # See database of global and static function prototypes in embed.fnc
38 # This is used to generate prototype headers under various configurations,
39 # export symbols lists for different platforms, and macros to provide an
40 # implicit interpreter context argument.
41 #
42
43 sub full_name ($$) { # Returns the function name with potentially the
44                      # prefixes 'S_' or 'Perl_'
45     my ($func, $flags) = @_;
46
47     return "S_$func" if $flags =~ /[si]/;
48     return "Perl_$func" if $flags =~ /p/;
49     return $func;
50 }
51
52 sub open_print_header {
53     my ($file, $quote) = @_;
54
55     return open_new($file, '>',
56                     { file => $file, style => '*', by => 'regen/embed.pl',
57                       from => ['data in embed.fnc', 'regen/embed.pl',
58                                'regen/opcodes', 'intrpvar.h', 'perlvars.h'],
59                       final => "\nEdit those files and run 'make regen_headers' to effect changes.\n",
60                       copyright => [1993 .. 2009], quote => $quote });
61 }
62
63 my ($embed, $core, $ext, $api) = setup_embed();
64
65 # generate proto.h
66 {
67     my $pr = open_print_header("proto.h");
68     print $pr "START_EXTERN_C\n";
69     my $ret;
70
71     foreach (@$embed) {
72         if (@$_ == 1) {
73             print $pr "$_->[0]\n";
74             next;
75         }
76
77         my ($flags,$retval,$plain_func,@args) = @$_;
78         if ($flags =~ / ( [^AabDdEfiMmnOoPpRrsUXx] ) /x) {
79             warn "flag $1 is not legal (for function $plain_func)";
80         }
81         my @nonnull;
82         my $has_context = ( $flags !~ /n/ );
83         my $never_returns = ( $flags =~ /r/ );
84         my $binarycompat = ( $flags =~ /b/ );
85         my $commented_out = ( ! $binarycompat && $flags =~ /m/ );
86         my $is_malloc = ( $flags =~ /a/ );
87         my $can_ignore = ( $flags !~ /R/ ) && !$is_malloc;
88         my @names_of_nn;
89         my $func;
90
91         if (! $can_ignore && $retval eq 'void') {
92             warn "It is nonsensical to require the return value of a void function ($plain_func) to be checked";
93         }
94
95         my $scope_type_flag_count = 0;
96         $scope_type_flag_count++ if $flags =~ /s/;
97         $scope_type_flag_count++ if $flags =~ /i/;
98         $scope_type_flag_count++ if $flags =~ /p/;
99         warn "$plain_func: i, p, and s flags are all mutually exclusive"
100                                                    if $scope_type_flag_count > 1;
101         my $splint_flags = "";
102         if ( $SPLINT && !$commented_out ) {
103             $splint_flags .= '/*@noreturn@*/ ' if $never_returns;
104             if ($can_ignore && ($retval ne 'void') && ($retval !~ /\*/)) {
105                 $retval .= " /*\@alt void\@*/";
106             }
107         }
108
109         if ($flags =~ /([si])/) {
110             my $type;
111             if ($never_returns) {
112                 $type = $1 eq 's' ? "PERL_STATIC_NO_RET" : "PERL_STATIC_INLINE_NO_RET";
113             }
114             else {
115                 $type = $1 eq 's' ? "STATIC" : "PERL_STATIC_INLINE";
116             }
117             $retval = "$type $splint_flags$retval";
118         }
119         else {
120             if ($never_returns) {
121                 $retval = "PERL_CALLCONV_NO_RET $splint_flags$retval";
122             }
123             else {
124                 $retval = "PERL_CALLCONV $splint_flags$retval";
125             }
126         }
127         $func = full_name($plain_func, $flags);
128         $ret = "";
129         $ret .= "#ifndef NO_MATHOMS\n" if $binarycompat;
130         $ret .= "$retval\t$func(";
131         if ( $has_context ) {
132             $ret .= @args ? "pTHX_ " : "pTHX";
133         }
134         if (@args) {
135             my $n;
136             for my $arg ( @args ) {
137                 ++$n;
138                 if ( $arg =~ /\*/ && $arg !~ /\b(NN|NULLOK)\b/ ) {
139                     warn "$func: $arg needs NN or NULLOK\n";
140                     ++$unflagged_pointers;
141                 }
142                 my $nn = ( $arg =~ s/\s*\bNN\b\s+// );
143                 push( @nonnull, $n ) if $nn;
144
145                 my $nullok = ( $arg =~ s/\s*\bNULLOK\b\s+// ); # strip NULLOK with no effect
146
147                 # Make sure each arg has at least a type and a var name.
148                 # An arg of "int" is valid C, but want it to be "int foo".
149                 my $temp_arg = $arg;
150                 $temp_arg =~ s/\*//g;
151                 $temp_arg =~ s/\s*\bstruct\b\s*/ /g;
152                 if ( ($temp_arg ne "...")
153                      && ($temp_arg !~ /\w+\s+(\w+)(?:\[\d+\])?\s*$/) ) {
154                     warn "$func: $arg ($n) doesn't have a name\n";
155                 }
156                 if ( $SPLINT && $nullok && !$commented_out ) {
157                     $arg = '/*@null@*/ ' . $arg;
158                 }
159                 if (defined $1 && $nn && !($commented_out && !$binarycompat)) {
160                     push @names_of_nn, $1;
161                 }
162             }
163             $ret .= join ", ", @args;
164         }
165         else {
166             $ret .= "void" if !$has_context;
167         }
168         $ret .= ")";
169         my @attrs;
170         if ( $flags =~ /r/ ) {
171             push @attrs, "__attribute__noreturn__";
172         }
173         if ( $flags =~ /D/ ) {
174             push @attrs, "__attribute__deprecated__";
175         }
176         if ( $is_malloc ) {
177             push @attrs, "__attribute__malloc__";
178         }
179         if ( !$can_ignore ) {
180             push @attrs, "__attribute__warn_unused_result__";
181         }
182         if ( $flags =~ /P/ ) {
183             push @attrs, "__attribute__pure__";
184         }
185         if( $flags =~ /f/ ) {
186             my $prefix  = $has_context ? 'pTHX_' : '';
187             my ($args, $pat);
188             if ($args[-1] eq '...') {
189                 $args   = scalar @args;
190                 $pat    = $args - 1;
191                 $args   = $prefix . $args;
192             }
193             else {
194                 # don't check args, and guess which arg is the pattern
195                 # (one of 'fmt', 'pat', 'f'),
196                 $args = 0;
197                 my @fmts = grep $args[$_] =~ /\b(f|pat|fmt)$/, 0..$#args;
198                 if (@fmts != 1) {
199                     die "embed.pl: '$plain_func': can't determine pattern arg\n";
200                 }
201                 $pat = $fmts[0] + 1;
202             }
203             my $macro   = grep($_ == $pat, @nonnull)
204                                 ? '__attribute__format__'
205                                 : '__attribute__format__null_ok__';
206             if ($plain_func =~ /strftime/) {
207                 push @attrs, sprintf "%s(__strftime__,%s1,0)", $macro, $prefix;
208             }
209             else {
210                 push @attrs, sprintf "%s(__printf__,%s%d,%s)", $macro,
211                                     $prefix, $pat, $args;
212             }
213         }
214         if ( @attrs ) {
215             $ret .= "\n";
216             $ret .= join( "\n", map { "\t\t\t$_" } @attrs );
217         }
218         $ret .= ";";
219         $ret = "/* $ret */" if $commented_out;
220         if (@names_of_nn) {
221             $ret .= "\n#define PERL_ARGS_ASSERT_\U$plain_func\E\t\\\n\t"
222                 . join '; ', map "assert($_)", @names_of_nn;
223         }
224         $ret .= "\n#endif" if $binarycompat;
225         $ret .= @attrs ? "\n\n" : "\n";
226
227         print $pr $ret;
228     }
229
230     print $pr <<'EOF';
231 #ifdef PERL_CORE
232 #  include "pp_proto.h"
233 #endif
234 END_EXTERN_C
235 EOF
236
237     read_only_bottom_close_and_rename($pr);
238 }
239
240 warn "$unflagged_pointers pointer arguments to clean up\n" if $unflagged_pointers;
241
242 sub readvars {
243     my ($file, $pre) = @_;
244     local (*FILE, $_);
245     my %seen;
246     open(FILE, "< $file")
247         or die "embed.pl: Can't open $file: $!\n";
248     while (<FILE>) {
249         s/[ \t]*#.*//;          # Delete comments.
250         if (/PERLVARA?I?C?\($pre,\s*(\w+)/) {
251             warn "duplicate symbol $1 while processing $file line $.\n"
252                 if $seen{$1}++;
253         }
254     }
255     close(FILE);
256     return sort keys %seen;
257 }
258
259 my @intrp = readvars 'intrpvar.h','I';
260 my @globvar = readvars 'perlvars.h','G';
261
262 sub hide {
263     my ($from, $to, $indent) = @_;
264     $indent = '' unless defined $indent;
265     my $t = int(length("$indent$from") / 8);
266     "#${indent}define $from" . "\t" x ($t < 3 ? 3 - $t : 1) . "$to\n";
267 }
268
269 sub multon ($$$) {
270     my ($sym,$pre,$ptr) = @_;
271     hide("PL_$sym", "($ptr$pre$sym)");
272 }
273
274 my $em = open_print_header('embed.h');
275
276 print $em <<'END';
277 /* (Doing namespace management portably in C is really gross.) */
278
279 /* By defining PERL_NO_SHORT_NAMES (not done by default) the short forms
280  * (like warn instead of Perl_warn) for the API are not defined.
281  * Not defining the short forms is a good thing for cleaner embedding. */
282
283 #ifndef PERL_NO_SHORT_NAMES
284
285 /* Hide global symbols */
286
287 END
288
289 my @az = ('a'..'z');
290
291 sub embed_h {
292     my ($guard, $funcs) = @_;
293     print $em "$guard\n" if $guard;
294
295     my $lines;
296     foreach (@$funcs) {
297         if (@$_ == 1) {
298             my $cond = $_->[0];
299             # Indent the conditionals if we are wrapped in an #if/#endif pair.
300             $cond =~ s/#(.*)/#  $1/ if $guard;
301             $lines .= "$cond\n";
302             next;
303         }
304         my $ret = "";
305         my ($flags,$retval,$func,@args) = @$_;
306         unless ($flags =~ /[om]/) {
307             my $args = scalar @args;
308             if ($flags =~ /n/) {
309                 my $full_name = full_name($func, $flags);
310                 next if $full_name eq $func;    # Don't output a no-op.
311                 $ret = hide($func, $full_name);
312             }
313             elsif ($args and $args[$args-1] =~ /\.\.\./) {
314                 if ($flags =~ /p/) {
315                     # we're out of luck for varargs functions under CPP
316                     # So we can only do these macros for no implicit context:
317                     $ret = "#ifndef PERL_IMPLICIT_CONTEXT\n"
318                         . hide($func, full_name($func, $flags)) . "#endif\n";
319                 }
320             }
321             else {
322                 my $alist = join(",", @az[0..$args-1]);
323                 $ret = "#define $func($alist)";
324                 my $t = int(length($ret) / 8);
325                 $ret .=  "\t" x ($t < 4 ? 4 - $t : 1);
326                 $ret .= full_name($func, $flags) . "(aTHX";
327                 $ret .= "_ " if $alist;
328                 $ret .= $alist . ")\n";
329             }
330             $ret = "#ifndef NO_MATHOMS\n$ret#endif\n" if $flags =~ /b/;
331         }
332         $lines .= $ret;
333     }
334     # Prune empty #if/#endif pairs.
335     while ($lines =~ s/#\s*if[^\n]+\n#\s*endif\n//) {
336     }
337     # Merge adjacent blocks.
338     while ($lines =~ s/(#ifndef PERL_IMPLICIT_CONTEXT
339 [^\n]+
340 )#endif
341 #ifndef PERL_IMPLICIT_CONTEXT
342 /$1/) {
343     }
344
345     print $em $lines;
346     print $em "#endif\n" if $guard;
347 }
348
349 embed_h('', $api);
350 embed_h('#if defined(PERL_CORE) || defined(PERL_EXT)', $ext);
351 embed_h('#ifdef PERL_CORE', $core);
352
353 print $em <<'END';
354
355 #endif  /* #ifndef PERL_NO_SHORT_NAMES */
356
357 /* Compatibility stubs.  Compile extensions with -DPERL_NOCOMPAT to
358    disable them.
359  */
360
361 #if !defined(PERL_CORE)
362 #  define sv_setptrobj(rv,ptr,name)     sv_setref_iv(rv,name,PTR2IV(ptr))
363 #  define sv_setptrref(rv,ptr)          sv_setref_iv(rv,NULL,PTR2IV(ptr))
364 #endif
365
366 #if !defined(PERL_CORE) && !defined(PERL_NOCOMPAT)
367
368 /* Compatibility for various misnamed functions.  All functions
369    in the API that begin with "perl_" (not "Perl_") take an explicit
370    interpreter context pointer.
371    The following are not like that, but since they had a "perl_"
372    prefix in previous versions, we provide compatibility macros.
373  */
374 #  define perl_atexit(a,b)              call_atexit(a,b)
375 END
376
377 foreach (@$embed) {
378     my ($flags, $retval, $func, @args) = @$_;
379     next unless $func;
380     next unless $flags =~ /O/;
381
382     my $alist = join ",", @az[0..$#args];
383     my $ret = "#  define perl_$func($alist)";
384     my $t = (length $ret) >> 3;
385     $ret .=  "\t" x ($t < 5 ? 5 - $t : 1);
386     print $em "$ret$func($alist)\n";
387 }
388
389 my @nocontext;
390 {
391     my (%has_va, %has_nocontext);
392     foreach (@$embed) {
393         next unless @$_ > 1;
394         ++$has_va{$_->[2]} if $_->[-1] =~ /\.\.\./;
395         ++$has_nocontext{$1} if $_->[2] =~ /(.*)_nocontext/;
396     }
397
398     @nocontext = sort grep {
399         $has_nocontext{$_}
400             && !/printf/ # Not clear to me why these are skipped but they are.
401     } keys %has_va;
402 }
403
404 print $em <<'END';
405
406 /* varargs functions can't be handled with CPP macros. :-(
407    This provides a set of compatibility functions that don't take
408    an extra argument but grab the context pointer using the macro
409    dTHX.
410  */
411 #if defined(PERL_IMPLICIT_CONTEXT) && !defined(PERL_NO_SHORT_NAMES)
412 END
413
414 foreach (@nocontext) {
415     print $em hide($_, "Perl_${_}_nocontext", "  ");
416 }
417
418 print $em <<'END';
419 #endif
420
421 #endif /* !defined(PERL_CORE) && !defined(PERL_NOCOMPAT) */
422
423 #if !defined(PERL_IMPLICIT_CONTEXT)
424 /* undefined symbols, point them back at the usual ones */
425 END
426
427 foreach (@nocontext) {
428     print $em hide("Perl_${_}_nocontext", "Perl_$_", "  ");
429 }
430
431 print $em <<'END';
432 #endif
433 END
434
435 read_only_bottom_close_and_rename($em);
436
437 $em = open_print_header('embedvar.h');
438
439 print $em <<'END';
440 /* (Doing namespace management portably in C is really gross.) */
441
442 /*
443    The following combinations of MULTIPLICITY and PERL_IMPLICIT_CONTEXT
444    are supported:
445      1) none
446      2) MULTIPLICITY    # supported for compatibility
447      3) MULTIPLICITY && PERL_IMPLICIT_CONTEXT
448
449    All other combinations of these flags are errors.
450
451    only #3 is supported directly, while #2 is a special
452    case of #3 (supported by redefining vTHX appropriately).
453 */
454
455 #if defined(MULTIPLICITY)
456 /* cases 2 and 3 above */
457
458 #  if defined(PERL_IMPLICIT_CONTEXT)
459 #    define vTHX        aTHX
460 #  else
461 #    define vTHX        PERL_GET_INTERP
462 #  endif
463
464 END
465
466 my $sym;
467
468 for $sym (@intrp) {
469     if ($sym eq 'sawampersand') {
470         print $em "#ifndef PL_sawampersand\n";
471     }
472     print $em multon($sym,'I','vTHX->');
473     if ($sym eq 'sawampersand') {
474         print $em "#endif\n";
475     }
476 }
477
478 print $em <<'END';
479
480 #endif  /* MULTIPLICITY */
481
482 #if defined(PERL_GLOBAL_STRUCT)
483
484 END
485
486 for $sym (@globvar) {
487     print $em "#ifdef OS2\n" if $sym eq 'sh_path';
488     print $em multon($sym,   'G','my_vars->');
489     print $em multon("G$sym",'', 'my_vars->');
490     print $em "#endif\n" if $sym eq 'sh_path';
491 }
492
493 print $em <<'END';
494
495 #endif /* PERL_GLOBAL_STRUCT */
496 END
497
498 read_only_bottom_close_and_rename($em);
499
500 my $capih = open_print_header('perlapi.h');
501
502 print $capih <<'EOT';
503 /* declare accessor functions for Perl variables */
504 #ifndef __perlapi_h__
505 #define __perlapi_h__
506
507 #if defined (MULTIPLICITY) && defined (PERL_GLOBAL_STRUCT)
508
509 START_EXTERN_C
510
511 #undef PERLVAR
512 #undef PERLVARA
513 #undef PERLVARI
514 #undef PERLVARIC
515 #define PERLVAR(p,v,t)  EXTERN_C t* Perl_##p##v##_ptr(pTHX);
516 #define PERLVARA(p,v,n,t)       typedef t PL_##v##_t[n];                \
517                         EXTERN_C PL_##v##_t* Perl_##p##v##_ptr(pTHX);
518 #define PERLVARI(p,v,t,i)       PERLVAR(p,v,t)
519 #define PERLVARIC(p,v,t,i) PERLVAR(p,v, const t)
520
521 #include "perlvars.h"
522
523 #undef PERLVAR
524 #undef PERLVARA
525 #undef PERLVARI
526 #undef PERLVARIC
527
528 END_EXTERN_C
529
530 #if defined(PERL_CORE)
531
532 /* accessor functions for Perl "global" variables */
533
534 /* these need to be mentioned here, or most linkers won't put them in
535    the perl executable */
536
537 #ifndef PERL_NO_FORCE_LINK
538
539 START_EXTERN_C
540
541 #ifndef DOINIT
542 EXTCONST void * const PL_force_link_funcs[];
543 #else
544 EXTCONST void * const PL_force_link_funcs[] = {
545 #undef PERLVAR
546 #undef PERLVARA
547 #undef PERLVARI
548 #undef PERLVARIC
549 #define PERLVAR(p,v,t)          (void*)Perl_##p##v##_ptr,
550 #define PERLVARA(p,v,n,t)       PERLVAR(p,v,t)
551 #define PERLVARI(p,v,t,i)       PERLVAR(p,v,t)
552 #define PERLVARIC(p,v,t,i)      PERLVAR(p,v,t)
553
554 /* In Tru64 (__DEC && __osf__) the cc option -std1 causes that one
555  * cannot cast between void pointers and function pointers without
556  * info level warnings.  The PL_force_link_funcs[] would cause a few
557  * hundred of those warnings.  In code one can circumnavigate this by using
558  * unions that overlay the different pointers, but in declarations one
559  * cannot use this trick.  Therefore we just disable the warning here
560  * for the duration of the PL_force_link_funcs[] declaration. */
561
562 #if defined(__DECC) && defined(__osf__)
563 #pragma message save
564 #pragma message disable (nonstandcast)
565 #endif
566
567 #include "perlvars.h"
568
569 #if defined(__DECC) && defined(__osf__)
570 #pragma message restore
571 #endif
572
573 #undef PERLVAR
574 #undef PERLVARA
575 #undef PERLVARI
576 #undef PERLVARIC
577 };
578 #endif  /* DOINIT */
579
580 END_EXTERN_C
581
582 #endif  /* PERL_NO_FORCE_LINK */
583
584 #else   /* !PERL_CORE */
585
586 EOT
587
588 foreach $sym (@globvar) {
589     print $capih
590         "#undef  PL_$sym\n" . hide("PL_$sym", "(*Perl_G${sym}_ptr(NULL))");
591 }
592
593 print $capih <<'EOT';
594
595 #endif /* !PERL_CORE */
596 #endif /* MULTIPLICITY && PERL_GLOBAL_STRUCT */
597
598 #endif /* __perlapi_h__ */
599 EOT
600
601 read_only_bottom_close_and_rename($capih);
602
603 my $capi = open_print_header('perlapi.c', <<'EOQ');
604  *
605  *
606  * Up to the threshold of the door there mounted a flight of twenty-seven
607  * broad stairs, hewn by some unknown art of the same black stone.  This
608  * was the only entrance to the tower; ...
609  *
610  *     [p.577 of _The Lord of the Rings_, III/x: "The Voice of Saruman"]
611  *
612  */
613 EOQ
614
615 print $capi <<'EOT';
616 #include "EXTERN.h"
617 #include "perl.h"
618 #include "perlapi.h"
619
620 #if defined (MULTIPLICITY) && defined (PERL_GLOBAL_STRUCT)
621
622 /* accessor functions for Perl "global" variables */
623 START_EXTERN_C
624
625 #undef PERLVARI
626 #define PERLVARI(p,v,t,i) PERLVAR(p,v,t)
627
628 #undef PERLVAR
629 #undef PERLVARA
630 #define PERLVAR(p,v,t)          t* Perl_##p##v##_ptr(pTHX)              \
631                         { dVAR; PERL_UNUSED_CONTEXT; return &(PL_##v); }
632 #define PERLVARA(p,v,n,t)       PL_##v##_t* Perl_##p##v##_ptr(pTHX)     \
633                         { dVAR; PERL_UNUSED_CONTEXT; return &(PL_##v); }
634 #undef PERLVARIC
635 #define PERLVARIC(p,v,t,i)      \
636                         const t* Perl_##p##v##_ptr(pTHX)                \
637                         { PERL_UNUSED_CONTEXT; return (const t *)&(PL_##v); }
638 #include "perlvars.h"
639
640 #undef PERLVAR
641 #undef PERLVARA
642 #undef PERLVARI
643 #undef PERLVARIC
644
645 END_EXTERN_C
646
647 #endif /* MULTIPLICITY && PERL_GLOBAL_STRUCT */
648 EOT
649
650 read_only_bottom_close_and_rename($capi);
651
652 # ex: set ts=8 sts=4 sw=4 noet: