This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Correct code-like snippet in documentation
[perl5.git] / configpm
1 #!./miniperl -w
2 # vim: syntax=perl
3 #
4 # configpm
5 #
6 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
7 # 2002, 2003, 2004, 2005, 2006, 2007 Larry Wall and others.
8 #
9 #
10 # Regenerate the files
11 #
12 #    lib/Config.pm
13 #    lib/Config_heavy.pl
14 #    lib/Config.pod
15 #
16 #
17 # from the contents of the static files
18 #
19 #    Porting/Glossary
20 #    myconfig.SH
21 #
22 # and from the contents of the Configure-generated file
23 #
24 #    config.sh
25 #
26 #
27 # It will only update Config.pm and Config_heavy.pl if the contents of
28 # either file would be different. Note that *both* files are updated in
29 # this case, since for example an extension makefile that has a dependency
30 # on Config.pm should trigger even if only Config_heavy.pl has changed.
31
32 sub usage { die <<EOF }
33 usage: $0  [ options ]
34     --no-glossary       don't include Porting/Glossary in lib/Config.pod
35     --chdir=dir         change directory before writing files
36 EOF
37
38 use strict;
39 our (%Config, $Config_SH_expanded);
40
41 my $how_many_common = 22;
42
43 # commonly used names to precache (and hence lookup fastest)
44 my %Common;
45
46 while ($how_many_common--) {
47     $_ = <DATA>;
48     chomp;
49     /^(\S+):\s*(\d+)$/ or die "Malformed line '$_'";
50     $Common{$1} = $1;
51 }
52
53 # Post 37589e1eefb1bd62 DynaLoader defaults to reading these at runtime.
54 # Ideally we're redo the data below, but Fotango's build system made it
55 # wonderfully easy to instrument, and no longer exists.
56 $Common{$_} = $_ foreach qw(dlext so);
57
58 # names of things which may need to have slashes changed to double-colons
59 my %Extensions = map {($_,$_)}
60                  qw(dynamic_ext static_ext extensions known_extensions);
61
62 # The plan is that this information is used by ExtUtils::MakeMaker to generate
63 # Makefile dependencies, rather than hardcoding a list, which has become out
64 # of date. However, currently, MM_Unix.pm and MM_VMS.pm have *different* lists,
65 # *and* descrip_mms.template doesn't actually install all the headers.
66 # The "Unix" list seems to (attempt to) avoid the generated headers, which I'm
67 # not sure is the right thing to do. Also, not certain whether it would be
68 # easier to parse MANIFEST to get these (adding config.h, and potentially
69 # removing others), but for now, stick to a hard coded list.
70
71 # Could use a map to add ".h", but I suspect that it's easier to use literals,
72 # so that anyone using grep will find them
73 # This is the list from MM_VMS, plus pad.h, parser.h, utf8.h
74 # which it installs. It *doesn't* install perliol.h - FIXME.
75 my @header_files = qw(EXTERN.h INTERN.h XSUB.h av.h config.h cop.h cv.h
76                       embed.h embedvar.h form.h gv.h handy.h hv.h hv_func.h intrpvar.h
77                       iperlsys.h keywords.h mg.h nostdio.h op.h opcode.h
78                       pad.h parser.h patchlevel.h perl.h perlio.h perlsdio.h
79                       perlvars.h perly.h pp.h pp_proto.h proto.h
80                       regcomp.h regexp.h regnodes.h scope.h sv.h thread.h utf8.h
81                       util.h);
82
83 push @header_files,
84     $^O eq 'VMS' ? 'vmsish.h' : qw(dosish.h perliol.h time64.h unixish.h);
85
86 my $header_files = '    return qw(' . join(' ', sort @header_files) . ');';
87 $header_files =~ s/(?=.{64})   # If line is still overlength
88                    (.{1,64})\  # Split at the last convenient space
89                   /$1\n              /gx;
90
91 # allowed opts as well as specifies default and initial values
92 my %Allowed_Opts = (
93     'glossary' => 1,  # --no-glossary  - no glossary file inclusion,
94                       #                  for compactness
95     'chdir'    => '', # --chdir=dir    - change directory before writing files
96 );
97
98 sub opts {
99     # user specified options
100     my %given_opts = (
101         # --opt=smth
102         (map {/^--([\-_\w]+)=(.*)$/} @ARGV),
103         # --opt --no-opt --noopt
104         (map {/^no-?(.*)$/i?($1=>0):($_=>1)} map {/^--([\-_\w]+)$/} @ARGV),
105     );
106
107     my %opts = (%Allowed_Opts, %given_opts);
108
109     for my $opt (grep {!exists $Allowed_Opts{$_}} keys %given_opts) {
110         warn "option '$opt' is not recognized";
111         usage;
112     }
113     @ARGV = grep {!/^--/} @ARGV;
114
115     return %opts;
116 }
117
118
119 my %Opts = opts();
120
121 if ($Opts{chdir}) {
122     chdir $Opts{chdir} or die "$0: could not chdir $Opts{chdir}: $!"
123 }
124
125 my ($Config_SH, $Config_PM, $Config_heavy, $Config_POD);
126 my $Glossary = 'Porting/Glossary';
127
128 $Config_PM = "lib/Config.pm";
129 $Config_POD = "lib/Config.pod";
130 $Config_SH = "config.sh";
131
132 ($Config_heavy = $Config_PM) =~ s/\.pm$/_heavy.pl/;
133 die "Can't automatically determine name for Config_heavy.pl from '$Config_PM'"
134   if $Config_heavy eq $Config_PM;
135
136 my $config_txt;
137 my $heavy_txt;
138
139 my $export_funcs = <<'EOT';
140 my %Export_Cache = (myconfig => 1, config_sh => 1, config_vars => 1,
141                     config_re => 1, compile_date => 1, local_patches => 1,
142                     bincompat_options => 1, non_bincompat_options => 1,
143                     header_files => 1);
144 EOT
145
146 my %export_ok = eval $export_funcs or die;
147
148 $config_txt .= sprintf << 'EOT', $], $export_funcs;
149 # This file was created by configpm when Perl was built. Any changes
150 # made to this file will be lost the next time perl is built.
151
152 # for a description of the variables, please have a look at the
153 # Glossary file, as written in the Porting folder, or use the url:
154 # https://github.com/Perl/perl5/blob/blead/Porting/Glossary
155
156 package Config;
157 use strict;
158 use warnings;
159 our ( %%Config, $VERSION );
160
161 $VERSION = "%s";
162
163 # Skip @Config::EXPORT because it only contains %%Config, which we special
164 # case below as it's not a function. @Config::EXPORT won't change in the
165 # lifetime of Perl 5.
166 %s
167 @Config::EXPORT = qw(%%Config);
168 @Config::EXPORT_OK = keys %%Export_Cache;
169
170 # Need to stub all the functions to make code such as print Config::config_sh
171 # keep working
172
173 EOT
174
175 $config_txt .= "sub $_;\n" foreach sort keys %export_ok;
176
177 my $myver = sprintf "%vd", $^V;
178
179 $config_txt .= sprintf <<'ENDOFBEG', ($myver) x 3;
180
181 # Define our own import method to avoid pulling in the full Exporter:
182 sub import {
183     shift;
184     @_ = @Config::EXPORT unless @_;
185
186     my @funcs = grep $_ ne '%%Config', @_;
187     my $export_Config = @funcs < @_ ? 1 : 0;
188
189     no strict 'refs';
190     my $callpkg = caller(0);
191     foreach my $func (@funcs) {
192         die qq{"$func" is not exported by the Config module\n}
193             unless $Export_Cache{$func};
194         *{$callpkg.'::'.$func} = \&{$func};
195     }
196
197     *{"$callpkg\::Config"} = \%%Config if $export_Config;
198     return;
199 }
200
201 die "$0: Perl lib version (%s) doesn't match executable '$^X' version ($])"
202     unless $^V;
203
204 $^V eq %s
205     or die sprintf "%%s: Perl lib version (%s) doesn't match executable '$^X' version (%%vd)", $0, $^V;
206
207 ENDOFBEG
208
209
210 my @non_v    = ();
211 my @v_others = ();
212 my $in_v     = 0;
213 my %Data     = ();
214 my $quote;
215
216 # These variables were set in older versions of Perl, but are no longer needed
217 # by the core. However, some CPAN modules may rely on them; in particular, Tk
218 # (at least up to version 804.034) fails to build without them. We force them
219 # to be emitted to Config_heavy.pl for backcompat with such modules (and we may
220 # find that this set needs to be extended in future). See RT#132347.
221 my @v_forced = map "$_\n", split /\n+/, <<'EOT';
222 i_limits='define'
223 i_stdlib='define'
224 i_string='define'
225 i_time='define'
226 prototype='define'
227 EOT
228
229
230 my %seen_quotes;
231 {
232   my ($name, $val);
233   open(CONFIG_SH, '<', $Config_SH) || die "Can't open $Config_SH: $!";
234   while (<CONFIG_SH>) {
235     next if m:^#!/bin/sh:;
236
237     # Catch PERL_CONFIG_SH=true and PERL_VERSION=n line from Configure.
238     s/^(\w+)=(true|\d+)\s*$/$1='$2'\n/ or m/^(\w+)='(.*)'$/;
239     my($k, $v) = ($1, $2);
240
241     # grandfather PATCHLEVEL and SUBVERSION and CONFIG
242     if ($k) {
243         if ($k eq 'PERL_VERSION') {
244             push @v_others, "PATCHLEVEL='$v'\n";
245         }
246         elsif ($k eq 'PERL_SUBVERSION') {
247             push @v_others, "SUBVERSION='$v'\n";
248         }
249         elsif ($k eq 'PERL_CONFIG_SH') {
250             push @v_others, "CONFIG='$v'\n";
251         }
252     }
253
254     # We can delimit things in config.sh with either ' or ". 
255     unless ($in_v or m/^(\w+)=(['"])(.*\n)/){
256         push(@non_v, "#$_"); # not a name='value' line
257         next;
258     }
259     if ($in_v) { 
260         $val .= $_;
261     }
262     else { 
263         $quote = $2;
264         ($name,$val) = ($1,$3); 
265         if ($name eq 'cc') {
266             $val =~ s{^(['"]?+).*\bccache\s+}{$1};
267         }
268     }
269     $in_v = $val !~ /$quote\n/;
270     next if $in_v;
271
272     s,/,::,g if $Extensions{$name};
273
274     $val =~ s/$quote\n?\z//;
275
276     my $line = "$name=$quote$val$quote\n";
277     push(@v_others, $line);
278     $seen_quotes{$quote}++;
279   }
280   close CONFIG_SH;
281 }
282
283 # This is somewhat grim, but I want the code for parsing config.sh here and
284 # now so that I can expand $Config{ivsize} and $Config{ivtype}
285
286 my $fetch_string = <<'EOT';
287
288 # Search for it in the big string
289 sub fetch_string {
290     my($self, $key) = @_;
291
292 EOT
293
294 if ($seen_quotes{'"'}) {
295     # We need the full ' and " code
296
297 $fetch_string .= <<'EOT';
298     return undef unless my ($quote_type, $value) = $Config_SH_expanded =~ /\n$key=(['"])(.*?)\1\n/s;
299
300     # If we had a double-quote, we'd better eval it so escape
301     # sequences and such can be interpolated. Since the incoming
302     # value is supposed to follow shell rules and not perl rules,
303     # we escape any perl variable markers
304
305     # Historically, since " 'support' was added in change 1409, the
306     # interpolation was done before the undef. Stick to this arguably buggy
307     # behaviour as we're refactoring.
308     if ($quote_type eq '"') {
309         $value =~ s/\$/\\\$/g;
310         $value =~ s/\@/\\\@/g;
311         eval "\$value = \"$value\"";
312     }
313
314     # So we can say "if $Config{'foo'}".
315     $self->{$key} = $value eq 'undef' ? undef : $value; # cache it
316 }
317 EOT
318
319 } else {
320     # We only have ' delimited.
321
322 $fetch_string .= <<'EOT';
323     return undef unless $Config_SH_expanded =~ /\n$key=\'(.*?)\'\n/s;
324     # So we can say "if $Config{'foo'}".
325     $self->{$key} = $1 eq 'undef' ? undef : $1;
326 }
327 EOT
328
329 }
330
331 eval $fetch_string;
332 die if $@;
333
334 # Calculation for the keys for byteorder
335 # This is somewhat grim, but I need to run fetch_string here.
336 $Config_SH_expanded = join "\n", '', @v_others;
337
338 my $t = fetch_string ({}, 'ivtype');
339 my $s = fetch_string ({}, 'ivsize');
340
341 # byteorder does exist on its own but we overlay a virtual
342 # dynamically recomputed value.
343
344 # However, ivtype and ivsize will not vary for sane fat binaries
345
346 my $f = $t eq 'long' ? 'L!' : $s == 8 ? 'Q': 'I';
347
348 my $byteorder_code;
349 if ($s == 4 || $s == 8) {
350     my $list = join ',', reverse(1..$s-1);
351     my $format = 'a'x$s;
352     $byteorder_code = <<"EOT";
353
354 my \$i = ord($s);
355 foreach my \$c ($list) { \$i <<= 8; \$i |= ord(\$c); }
356 our \$byteorder = join('', unpack('$format', pack('$f', \$i)));
357 EOT
358 } else {
359     $byteorder_code = "our \$byteorder = '?'x$s;\n";
360 }
361
362 my @need_relocation;
363
364 if (fetch_string({},'userelocatableinc')) {
365     foreach my $what (qw(prefixexp
366
367                          archlibexp
368                          html1direxp
369                          html3direxp
370                          man1direxp
371                          man3direxp
372                          privlibexp
373                          scriptdirexp
374                          sitearchexp
375                          sitebinexp
376                          sitehtml1direxp
377                          sitehtml3direxp
378                          sitelibexp
379                          siteman1direxp
380                          siteman3direxp
381                          sitescriptexp
382                          vendorarchexp
383                          vendorbinexp
384                          vendorhtml1direxp
385                          vendorhtml3direxp
386                          vendorlibexp
387                          vendorman1direxp
388                          vendorman3direxp
389                          vendorscriptexp
390
391                          siteprefixexp
392                          sitelib_stem
393                          vendorlib_stem
394
395                          installarchlib
396                          installhtml1dir
397                          installhtml3dir
398                          installman1dir
399                          installman3dir
400                          installprefix
401                          installprefixexp
402                          installprivlib
403                          installscript
404                          installsitearch
405                          installsitebin
406                          installsitehtml1dir
407                          installsitehtml3dir
408                          installsitelib
409                          installsiteman1dir
410                          installsiteman3dir
411                          installsitescript
412                          installvendorarch
413                          installvendorbin
414                          installvendorhtml1dir
415                          installvendorhtml3dir
416                          installvendorlib
417                          installvendorman1dir
418                          installvendorman3dir
419                          installvendorscript
420                          )) {
421         push @need_relocation, $what if fetch_string({}, $what) =~ m!^\.\.\./!;
422     }
423 }
424
425 my %need_relocation;
426 @need_relocation{@need_relocation} = @need_relocation;
427
428 # This can have .../ anywhere:
429 if (fetch_string({}, 'otherlibdirs') =~ m!\.\.\./!) {
430     $need_relocation{otherlibdirs} = 'otherlibdirs';
431 }
432
433 my $relocation_code = <<'EOT';
434
435 sub relocate_inc {
436   my $libdir = shift;
437   return $libdir unless $libdir =~ s!^\.\.\./!!;
438   my $prefix = $^X;
439   if ($prefix =~ s!/[^/]*$!!) {
440     while ($libdir =~ m!^\.\./!) {
441       # Loop while $libdir starts "../" and $prefix still has a trailing
442       # directory
443       last unless $prefix =~ s!/([^/]+)$!!;
444       # but bail out if the directory we picked off the end of $prefix is .
445       # or ..
446       if ($1 eq '.' or $1 eq '..') {
447         # Undo! This should be rare, hence code it this way rather than a
448         # check each time before the s!!! above.
449         $prefix = "$prefix/$1";
450         last;
451       }
452       # Remove that leading ../ and loop again
453       substr ($libdir, 0, 3, '');
454     }
455     $libdir = "$prefix/$libdir";
456   }
457   $libdir;
458 }
459 EOT
460
461 my $osname = fetch_string({}, 'osname');
462 my $from = $osname eq 'VMS' ? 'PERLSHR image' : 'binary (from libperl)';
463 my $env_cygwin = $osname eq 'cygwin'
464     ? 'push @env, "CYGWIN=\"$ENV{CYGWIN}\"" if $ENV{CYGWIN};' . "\n" : "";
465
466 $heavy_txt .= sprintf <<'ENDOFBEG', $osname, $osname, $from, $osname, $env_cygwin;
467 # This file was created by configpm when Perl was built. Any changes
468 # made to this file will be lost the next time perl is built.
469
470 package Config;
471 use strict;
472 use warnings;
473 our %%Config;
474
475 sub bincompat_options {
476     return split ' ', (Internals::V())[0];
477 }
478
479 sub non_bincompat_options {
480     return split ' ', (Internals::V())[1];
481 }
482
483 sub compile_date {
484     return (Internals::V())[2]
485 }
486
487 sub local_patches {
488     my (undef, undef, undef, @patches) = Internals::V();
489     return @patches;
490 }
491
492 sub _V {
493     die "Perl lib was built for '%s' but is being run on '$^O'"
494         unless "%s" eq $^O;
495
496     my ($bincompat, $non_bincompat, $date, @patches) = Internals::V();
497
498     my @opts = sort split ' ', "$bincompat $non_bincompat";
499
500     print Config::myconfig();
501     print "\nCharacteristics of this %s: \n";
502
503     print "  Compile-time options:\n";
504     print "    $_\n" for @opts;
505
506     if (@patches) {
507         print "  Locally applied patches:\n";
508         print "    $_\n" foreach @patches;
509     }
510
511     print "  Built under %s\n";
512
513     print "  $date\n" if defined $date;
514
515     my @env = map { "$_=\"$ENV{$_}\"" } sort grep {/^PERL/} keys %%ENV;
516 %s
517     if (@env) {
518         print "  \%%ENV:\n";
519         print "    $_\n" foreach @env;
520     }
521     print "  \@INC:\n";
522     print "    $_\n" foreach @INC;
523 }
524
525 sub header_files {
526 ENDOFBEG
527
528 $heavy_txt .= $header_files . "\n}\n\n";
529
530 if (%need_relocation) {
531   my $relocations_in_common;
532   # otherlibdirs only features in the hash
533   foreach (keys %need_relocation) {
534     $relocations_in_common++ if $Common{$_};
535   }
536   if ($relocations_in_common) {
537     $config_txt .= $relocation_code;
538   } else {
539     $heavy_txt .= $relocation_code;
540   }
541 }
542
543 $heavy_txt .= join('', @non_v) . "\n";
544
545 # copy config summary format from the myconfig.SH script
546 $heavy_txt .= "our \$summary = <<'!END!';\n";
547 open(MYCONFIG,'<','myconfig.SH') || die "open myconfig.SH failed: $!";
548 1 while defined($_ = <MYCONFIG>) && !/^Summary of/;
549 do { $heavy_txt .= $_ } until !defined($_ = <MYCONFIG>) || /^\s*$/;
550 close(MYCONFIG);
551
552 $heavy_txt .= "\n!END!\n" . <<'EOT';
553 my $summary_expanded;
554
555 sub myconfig {
556     return $summary_expanded if $summary_expanded;
557     ($summary_expanded = $summary) =~ s{\$(\w+)}
558                  { 
559                         my $c;
560                         if ($1 eq 'git_ancestor_line') {
561                                 if ($Config::Config{git_ancestor}) {
562                                         $c= "\n  Ancestor: $Config::Config{git_ancestor}";
563                                 } else {
564                                         $c= "";
565                                 }
566                         } else {
567                                 $c = $Config::Config{$1}; 
568                         }
569                         defined($c) ? $c : 'undef' 
570                 }ge;
571     $summary_expanded;
572 }
573
574 local *_ = \my $a;
575 $_ = <<'!END!';
576 EOT
577 #proper lexicographical order of the keys
578 my %seen_var;
579 $heavy_txt .= join('',
580     map { $_->[-1] }
581     sort {$a->[0] cmp $b->[0] }
582     grep { !$seen_var{ $_->[0] }++ }
583     map {
584         /^([^=]+)/ ? [ $1, $_ ]
585                    : [ $_, $_ ] # shouldnt happen
586     } @v_others, @v_forced
587 ) . "!END!\n";
588
589 # Only need the dynamic byteorder code in Config.pm if 'byteorder' is one of
590 # the precached keys
591 if ($Common{byteorder}) {
592     $config_txt .= $byteorder_code;
593 } else {
594     $heavy_txt .= $byteorder_code;
595 }
596
597 if (@need_relocation) {
598 $heavy_txt .= 'foreach my $what (qw(' . join (' ', @need_relocation) .
599       ")) {\n" . <<'EOT';
600     s/^($what=)(['"])(.*?)\2/$1 . $2 . relocate_inc($3) . $2/me;
601 }
602 EOT
603 # Currently it only makes sense to do the ... relocation on Unix, so there's
604 # no need to emulate the "which separator for this platform" logic in perl.c -
605 # ':' will always be applicable
606 if ($need_relocation{otherlibdirs}) {
607 $heavy_txt .= << 'EOT';
608 s{^(otherlibdirs=)(['"])(.*?)\2}
609  {$1 . $2 . join ':', map {relocate_inc($_)} split ':', $3 . $2}me;
610 EOT
611 }
612 }
613
614 $heavy_txt .= <<'EOT';
615 s/(byteorder=)(['"]).*?\2/$1$2$Config::byteorder$2/m;
616
617 my $config_sh_len = length $_;
618
619 our $Config_SH_expanded = "\n$_" . << 'EOVIRTUAL';
620 EOT
621
622 foreach my $prefix (qw(ccflags ldflags)) {
623     my $value = fetch_string ({}, $prefix);
624     my $withlargefiles = fetch_string ({}, $prefix . "_uselargefiles");
625     if (defined $withlargefiles) {
626         $value =~ s/\Q$withlargefiles\E\b//;
627         $heavy_txt .= "${prefix}_nolargefiles='$value'\n";
628     }
629 }
630
631 foreach my $prefix (qw(libs libswanted)) {
632     my $value = fetch_string ({}, $prefix);
633     my $withlf = fetch_string ({}, 'libswanted_uselargefiles');
634     next unless defined $withlf;
635     my @lflibswanted
636        = split(' ', fetch_string ({}, 'libswanted_uselargefiles'));
637     if (@lflibswanted) {
638         my %lflibswanted;
639         @lflibswanted{@lflibswanted} = ();
640         if ($prefix eq 'libs') {
641             my @libs = grep { /^-l(.+)/ &&
642                             not exists $lflibswanted{$1} }
643                                     split(' ', fetch_string ({}, 'libs'));
644             $value = join(' ', @libs);
645         } else {
646             my @libswanted = grep { not exists $lflibswanted{$_} }
647                                   split(' ', fetch_string ({}, 'libswanted'));
648             $value = join(' ', @libswanted);
649         }
650     }
651     $heavy_txt .= "${prefix}_nolargefiles='$value'\n";
652 }
653
654 if (open(my $fh, '<', 'cflags')) {
655     my $ccwarnflags;
656     my $ccstdflags;
657     while (<$fh>) {
658         if (/^warn="(.+)"$/) {
659             $ccwarnflags = $1;
660         } elsif (/^stdflags="(.+)"$/) {
661             $ccstdflags = $1;
662         }
663     }
664     if (defined $ccwarnflags) {
665       $heavy_txt .= "ccwarnflags='$ccwarnflags'\n";
666     }
667     if (defined $ccstdflags) {
668       $heavy_txt .= "ccstdflags='$ccstdflags'\n";
669     }
670 }
671
672 $heavy_txt .= "EOVIRTUAL\n";
673
674 $heavy_txt .= <<'ENDOFGIT';
675 eval {
676         # do not have hairy conniptions if this isnt available
677         require 'Config_git.pl';
678         $Config_SH_expanded .= $Config::Git_Data;
679         1;
680 } or warn "Warning: failed to load Config_git.pl, something strange about this perl...\n";
681 ENDOFGIT
682
683 $heavy_txt .= $fetch_string;
684
685 $config_txt .= <<'ENDOFEND';
686
687 sub FETCH {
688     my($self, $key) = @_;
689
690     # check for cached value (which may be undef so we use exists not defined)
691     return exists $self->{$key} ? $self->{$key} : $self->fetch_string($key);
692 }
693
694 ENDOFEND
695
696 $heavy_txt .= <<'ENDOFEND';
697
698 my $prevpos = 0;
699
700 sub FIRSTKEY {
701     $prevpos = 0;
702     substr($Config_SH_expanded, 1, index($Config_SH_expanded, '=') - 1 );
703 }
704
705 sub NEXTKEY {
706 ENDOFEND
707 if ($seen_quotes{'"'}) {
708 $heavy_txt .= <<'ENDOFEND';
709     # Find out how the current key's quoted so we can skip to its end.
710     my $quote = substr($Config_SH_expanded,
711                        index($Config_SH_expanded, "=", $prevpos)+1, 1);
712     my $pos = index($Config_SH_expanded, qq($quote\n), $prevpos) + 2;
713 ENDOFEND
714 } else {
715     # Just ' quotes, so it's much easier.
716 $heavy_txt .= <<'ENDOFEND';
717     my $pos = index($Config_SH_expanded, qq('\n), $prevpos) + 2;
718 ENDOFEND
719 }
720 $heavy_txt .= <<'ENDOFEND';
721     my $len = index($Config_SH_expanded, "=", $pos) - $pos;
722     $prevpos = $pos;
723     $len > 0 ? substr($Config_SH_expanded, $pos, $len) : undef;
724 }
725
726 sub EXISTS {
727     return 1 if exists($_[0]->{$_[1]});
728
729     return(index($Config_SH_expanded, "\n$_[1]='") != -1
730 ENDOFEND
731 if ($seen_quotes{'"'}) {
732 $heavy_txt .= <<'ENDOFEND';
733            or index($Config_SH_expanded, "\n$_[1]=\"") != -1
734 ENDOFEND
735 }
736 $heavy_txt .= <<'ENDOFEND';
737           );
738 }
739
740 sub STORE  { die "\%Config::Config is read-only\n" }
741 *DELETE = *CLEAR = \*STORE; # Typeglob aliasing uses less space
742
743 sub config_sh {
744     substr $Config_SH_expanded, 1, $config_sh_len;
745 }
746
747 sub config_re {
748     my $re = shift;
749     return map { chomp; $_ } grep eval{ /^(?:$re)=/ }, split /^/,
750     $Config_SH_expanded;
751 }
752
753 sub config_vars {
754     # implements -V:cfgvar option (see perlrun -V:)
755     foreach (@_) {
756         # find optional leading, trailing colons; and query-spec
757         my ($notag,$qry,$lncont) = m/^(:)?(.*?)(:)?$/;  # flags fore and aft, 
758         # map colon-flags to print decorations
759         my $prfx = $notag ? '': "$qry=";                # tag-prefix for print
760         my $lnend = $lncont ? ' ' : ";\n";              # line ending for print
761
762         # all config-vars are by definition \w only, any \W means regex
763         if ($qry =~ /\W/) {
764             my @matches = config_re($qry);
765             print map "$_$lnend", @matches ? @matches : "$qry: not found"               if !$notag;
766             print map { s/\w+=//; "$_$lnend" } @matches ? @matches : "$qry: not found"  if  $notag;
767         } else {
768             my $v = (exists $Config::Config{$qry}) ? $Config::Config{$qry}
769                                                    : 'UNKNOWN';
770             $v = 'undef' unless defined $v;
771             print "${prfx}'${v}'$lnend";
772         }
773     }
774 }
775
776 # Called by the real AUTOLOAD
777 sub launcher {
778     undef &AUTOLOAD;
779     goto \&$Config::AUTOLOAD;
780 }
781
782 1;
783 ENDOFEND
784
785 if ($^O eq 'os2') {
786     $config_txt .= <<'ENDOFSET';
787 my %preconfig;
788 if ($OS2::is_aout) {
789     my ($value, $v) = $Config_SH_expanded =~ m/^used_aout='(.*)'\s*$/m;
790     for (split ' ', $value) {
791         ($v) = $Config_SH_expanded =~ m/^aout_$_='(.*)'\s*$/m;
792         $preconfig{$_} = $v eq 'undef' ? undef : $v;
793     }
794 }
795 $preconfig{d_fork} = undef unless $OS2::can_fork; # Some funny cases can't
796 sub TIEHASH { bless {%preconfig} }
797 ENDOFSET
798     # Extract the name of the DLL from the makefile to avoid duplication
799     my ($f) = grep -r, qw(GNUMakefile Makefile);
800     my $dll;
801     if (open my $fh, '<', $f) {
802         while (<$fh>) {
803             $dll = $1, last if /^PERL_DLL_BASE\s*=\s*(\S*)\s*$/;
804         }
805     }
806     $config_txt .= <<ENDOFSET if $dll;
807 \$preconfig{dll_name} = '$dll';
808 ENDOFSET
809 } else {
810     $config_txt .= <<'ENDOFSET';
811 sub TIEHASH {
812     bless $_[1], $_[0];
813 }
814 ENDOFSET
815 }
816
817 foreach my $key (keys %Common) {
818     my $value = fetch_string ({}, $key);
819     # Is it safe on the LHS of => ?
820     my $qkey = $key =~ /^[A-Za-z_][A-Za-z0-9_]*$/ ? $key : "'$key'";
821     if (defined $value) {
822         # Quote things for a '' string
823         $value =~ s!\\!\\\\!g;
824         $value =~ s!'!\\'!g;
825         $value = "'$value'";
826         if ($key eq 'otherlibdirs') {
827             $value = "join (':', map {relocate_inc(\$_)} split (':', $value))";
828         } elsif ($need_relocation{$key}) {
829             $value = "relocate_inc($value)";
830         }
831     } else {
832         $value = "undef";
833     }
834     $Common{$key} = "$qkey => $value";
835 }
836
837 if ($Common{byteorder}) {
838     $Common{byteorder} = 'byteorder => $byteorder';
839 }
840 my $fast_config = join '', map { "    $_,\n" } sort values %Common;
841
842 # Sanity check needed to stop an infinite loop if Config_heavy.pl fails to
843 # define &launcher for some reason (eg it got truncated)
844 $config_txt .= sprintf <<'ENDOFTIE', $fast_config;
845
846 sub DESTROY { }
847
848 sub AUTOLOAD {
849     require 'Config_heavy.pl';
850     goto \&launcher unless $Config::AUTOLOAD =~ /launcher$/;
851     die "&Config::AUTOLOAD failed on $Config::AUTOLOAD";
852 }
853
854 # tie returns the object, so the value returned to require will be true.
855 tie %%Config, 'Config', {
856 %s};
857 ENDOFTIE
858
859
860 open(CONFIG_POD, '>:raw', $Config_POD) or die "Can't open $Config_POD: $!";
861 print CONFIG_POD <<'ENDOFTAIL';
862 =head1 NAME
863
864 =for comment  Generated by configpm.  Any changes made here will be lost!
865
866 Config - access Perl configuration information
867
868 =head1 SYNOPSIS
869
870     use Config;
871     if ($Config{usethreads}) {
872         print "has thread support\n"
873     } 
874
875     use Config qw(myconfig config_sh config_vars config_re);
876
877     print myconfig();
878
879     print config_sh();
880
881     print config_re();
882
883     config_vars(qw(osname archname));
884
885
886 =head1 DESCRIPTION
887
888 The Config module contains all the information that was available to
889 the F<Configure> program at Perl build time (over 900 values).
890
891 Shell variables from the F<config.sh> file (written by Configure) are
892 stored in the readonly-variable C<%Config>, indexed by their names.
893
894 Values stored in config.sh as 'undef' are returned as undefined
895 values.  The perl C<exists> function can be used to check if a
896 named variable exists.
897
898 For a description of the variables, please have a look at the
899 Glossary file, as written in the Porting folder, or use the url:
900 https://github.com/Perl/perl5/blob/blead/Porting/Glossary
901
902 =over 4
903
904 =item myconfig()
905
906 Returns a textual summary of the major perl configuration values.
907 See also C<-V> in L<perlrun/Command Switches>.
908
909 =item config_sh()
910
911 Returns the entire perl configuration information in the form of the
912 original config.sh shell variable assignment script.
913
914 =item config_re($regex)
915
916 Like config_sh() but returns, as a list, only the config entries who's
917 names match the $regex.
918
919 =item config_vars(@names)
920
921 Prints to STDOUT the values of the named configuration variable. Each is
922 printed on a separate line in the form:
923
924   name='value';
925
926 Names which are unknown are output as C<name='UNKNOWN';>.
927 See also C<-V:name> in L<perlrun/Command Switches>.
928
929 =item bincompat_options()
930
931 Returns a list of C pre-processor options used when compiling this F<perl>
932 binary, which affect its binary compatibility with extensions.
933 C<bincompat_options()> and C<non_bincompat_options()> are shown together in
934 the output of C<perl -V> as I<Compile-time options>.
935
936 =item non_bincompat_options()
937
938 Returns a list of C pre-processor options used when compiling this F<perl>
939 binary, which do not affect binary compatibility with extensions.
940
941 =item compile_date()
942
943 Returns the compile date (as a string), equivalent to what is shown by
944 C<perl -V>
945
946 =item local_patches()
947
948 Returns a list of the names of locally applied patches, equivalent to what
949 is shown by C<perl -V>.
950
951 =item header_files()
952
953 Returns a list of the header files that should be used as dependencies for
954 XS code, for this version of Perl on this platform.
955
956 =back
957
958 =head1 EXAMPLE
959
960 Here's a more sophisticated example of using %Config:
961
962     use Config;
963     use strict;
964
965     my %sig_num;
966     my @sig_name;
967     unless($Config{sig_name} && $Config{sig_num}) {
968         die "No sigs?";
969     } else {
970         my @names = split ' ', $Config{sig_name};
971         @sig_num{@names} = split ' ', $Config{sig_num};
972         foreach (@names) {
973             $sig_name[$sig_num{$_}] ||= $_;
974         }   
975     }
976
977     print "signal #17 = $sig_name[17]\n";
978     if ($sig_num{ALRM}) { 
979         print "SIGALRM is $sig_num{ALRM}\n";
980     }   
981
982 =head1 WARNING
983
984 Because this information is not stored within the perl executable
985 itself it is possible (but unlikely) that the information does not
986 relate to the actual perl binary which is being used to access it.
987
988 The Config module is installed into the architecture and version
989 specific library directory ($Config{installarchlib}) and it checks the
990 perl version number when loaded.
991
992 The values stored in config.sh may be either single-quoted or
993 double-quoted. Double-quoted strings are handy for those cases where you
994 need to include escape sequences in the strings. To avoid runtime variable
995 interpolation, any C<$> and C<@> characters are replaced by C<\$> and
996 C<\@>, respectively. This isn't foolproof, of course, so don't embed C<\$>
997 or C<\@> in double-quoted strings unless you're willing to deal with the
998 consequences. (The slashes will end up escaped and the C<$> or C<@> will
999 trigger variable interpolation)
1000
1001 =head1 GLOSSARY
1002
1003 Most C<Config> variables are determined by the C<Configure> script
1004 on platforms supported by it (which is most UNIX platforms).  Some
1005 platforms have custom-made C<Config> variables, and may thus not have
1006 some of the variables described below, or may have extraneous variables
1007 specific to that particular port.  See the port specific documentation
1008 in such cases.
1009
1010 =cut
1011
1012 ENDOFTAIL
1013
1014 if ($Opts{glossary}) {
1015   open(GLOS, '<', $Glossary) or die "Can't open $Glossary: $!";
1016 }
1017 my %seen = ();
1018 my $text = 0;
1019 $/ = '';
1020 my $errors= 0;
1021
1022 sub process {
1023   if (s/\A(\w*)\s+\(([\w.]+)\):\s*\n(\t?)/=item C<$1>\n\nFrom F<$2>:\n\n/m) {
1024     my $c = substr $1, 0, 1;
1025     unless ($seen{$c}++) {
1026       print CONFIG_POD <<EOF if $text;
1027 =back
1028
1029 EOF
1030       print CONFIG_POD <<EOF;
1031 =head2 $c
1032
1033 =over 4
1034
1035 EOF
1036      $text = 1;
1037     }
1038   }
1039   elsif (!$text || !/\A\t/) {
1040     warn "Expected a Configure variable header",
1041       ($text ? " or another paragraph of description" : () ),
1042       ", instead we got:\n$_";
1043     $errors++;
1044   }
1045   s/n't/n\00t/g;                # leave can't, won't etc untouched
1046   s/^\t\s+(.*)/\n$1/gm;         # Indented lines ===> new paragraph
1047   s/^(?<!\n\n)\t(.*)/$1/gm;     # Not indented lines ===> text
1048   s{([\'\"])(?=[^\'\"\s]*[./][^\'\"\s]*\1)([^\'\"\s]+)\1}(F<$2>)g; # '.o'
1049   s{([\'\"])([^\'\"\s]+)\1}(C<$2>)g; # "date" command
1050   s{\'([A-Za-z_\- *=/]+)\'}(C<$1>)g; # 'ln -s'
1051   s{
1052      (?<! [\w./<\'\"\$] )               # Only standalone file names
1053      (?! e \. g \. )            # Not e.g.
1054      (?! \. \. \. )             # Not ...
1055      (?! \d )                   # Not 5.004
1056      (?! read/ )                # Not read/write
1057      (?! etc\. )                # Not etc.
1058      (?! I/O )                  # Not I/O
1059      (
1060         \$ ?                    # Allow leading $
1061         [\w./]* [./] [\w./]*    # Require . or / inside
1062      )
1063      (?<! \. (?= [\s)] ) )      # Do not include trailing dot
1064      (?! [\w/] )                # Include all of it
1065    }
1066    (F<$1>)xg;                   # /usr/local
1067   s/((?<=\s)~\w*)/F<$1>/g;      # ~name
1068   s/(?<![.<\'\"])\b([A-Z_]{2,})\b(?![\'\"])/C<$1>/g;    # UNISTD
1069   s/(?<![.<\'\"])\b(?!the\b)(\w+)\s+macro\b/C<$1> macro/g; # FILE_cnt macro
1070   s/n[\0]t/n't/g;               # undo can't, won't damage
1071 }
1072
1073 if ($Opts{glossary}) {
1074     <GLOS>;                             # Skip the "DO NOT EDIT"
1075     <GLOS>;                             # Skip the preamble
1076   while (<GLOS>) {
1077     process;
1078     print CONFIG_POD;
1079   }
1080   if ($errors) {
1081     die "Errors encountered while processing $Glossary. ",
1082         "Header lines are expected to be of the form:\n",
1083         "NAME (CLASS):\n",
1084         "Maybe there is a malformed header?\n",
1085     ;
1086   }
1087 }
1088
1089 print CONFIG_POD <<'ENDOFTAIL';
1090
1091 =back
1092
1093 =head1 GIT DATA
1094
1095 Information on the git commit from which the current perl binary was compiled
1096 can be found in the variable C<$Config::Git_Data>.  The variable is a
1097 structured string that looks something like this:
1098
1099   git_commit_id='ea0c2dbd5f5ac6845ecc7ec6696415bf8e27bd52'
1100   git_describe='GitLive-blead-1076-gea0c2db'
1101   git_branch='smartmatch'
1102   git_uncommitted_changes=''
1103   git_commit_id_title='Commit id:'
1104   git_commit_date='2009-05-09 17:47:31 +0200'
1105
1106 Its format is not guaranteed not to change over time.
1107
1108 =head1 NOTE
1109
1110 This module contains a good example of how to use tie to implement a
1111 cache and an example of how to make a tied variable readonly to those
1112 outside of it.
1113
1114 =cut
1115
1116 ENDOFTAIL
1117
1118 close(GLOS) if $Opts{glossary};
1119 close(CONFIG_POD);
1120 print "written $Config_POD\n";
1121
1122 my $orig_config_txt = "";
1123 my $orig_heavy_txt = "";
1124 {
1125     local $/;
1126     my $fh;
1127     $orig_config_txt = <$fh> if open $fh, "<", $Config_PM;
1128     $orig_heavy_txt  = <$fh> if open $fh, "<", $Config_heavy;
1129 }
1130
1131 if ($orig_config_txt ne $config_txt or $orig_heavy_txt ne $heavy_txt) {
1132     open CONFIG, ">", $Config_PM or die "Can't open $Config_PM: $!\n";
1133     open CONFIG_HEAVY, ">", $Config_heavy or die "Can't open $Config_heavy: $!\n";
1134     print CONFIG $config_txt;
1135     print CONFIG_HEAVY $heavy_txt;
1136     close(CONFIG_HEAVY);
1137     close(CONFIG);
1138     print "updated $Config_PM\n";
1139     print "updated $Config_heavy\n";
1140 }
1141
1142 # Now do some simple tests on the Config.pm file we have created
1143 unshift(@INC,'lib');
1144 require $Config_PM;
1145 require $Config_heavy;
1146 import Config;
1147
1148 die "$0: $Config_PM not valid"
1149         unless $Config{'PERL_CONFIG_SH'} eq 'true';
1150
1151 die "$0: error processing $Config_PM"
1152         if defined($Config{'an impossible name'})
1153         or $Config{'PERL_CONFIG_SH'} ne 'true' # test cache
1154         ;
1155
1156 die "$0: error processing $Config_PM"
1157         if eval '$Config{"cc"} = 1'
1158         or eval 'delete $Config{"cc"}'
1159         ;
1160
1161
1162 exit 0;
1163 # Popularity of various entries in %Config, based on a large build and test
1164 # run of code in the Fotango build system:
1165 __DATA__
1166 path_sep:       8490
1167 d_readlink:     7101
1168 d_symlink:      7101
1169 archlibexp:     4318
1170 sitearchexp:    4305
1171 sitelibexp:     4305
1172 privlibexp:     4163
1173 ldlibpthname:   4041
1174 libpth: 2134
1175 archname:       1591
1176 exe_ext:        1256
1177 scriptdir:      1155
1178 version:        1116
1179 useithreads:    1002
1180 osvers: 982
1181 osname: 851
1182 inc_version_list:       783
1183 dont_use_nlink: 779
1184 intsize:        759
1185 usevendorprefix:        642
1186 dlsrc:  624
1187 cc:     541
1188 lib_ext:        520
1189 so:     512
1190 ld:     501
1191 ccdlflags:      500
1192 ldflags:        495
1193 obj_ext:        495
1194 cccdlflags:     493
1195 lddlflags:      493
1196 ar:     492
1197 dlext:  492
1198 libc:   492
1199 ranlib: 492
1200 full_ar:        491
1201 vendorarchexp:  491
1202 vendorlibexp:   491
1203 installman1dir: 489
1204 installman3dir: 489
1205 installsitebin: 489
1206 installsiteman1dir:     489
1207 installsiteman3dir:     489
1208 installvendorman1dir:   489
1209 installvendorman3dir:   489
1210 d_flexfnam:     474
1211 eunicefix:      360
1212 d_link: 347
1213 installsitearch:        344
1214 installscript:  341
1215 installprivlib: 337
1216 binexp: 336
1217 installarchlib: 336
1218 installprefixexp:       336
1219 installsitelib: 336
1220 installstyle:   336
1221 installvendorarch:      336
1222 installvendorbin:       336
1223 installvendorlib:       336
1224 man1ext:        336
1225 man3ext:        336
1226 sh:     336
1227 siteprefixexp:  336
1228 installbin:     335
1229 usedl:  332
1230 ccflags:        285
1231 startperl:      232
1232 optimize:       231
1233 usemymalloc:    229
1234 cpprun: 228
1235 sharpbang:      228
1236 perllibs:       225
1237 usesfio:        224
1238 usethreads:     220
1239 perlpath:       218
1240 extensions:     217
1241 usesocks:       208
1242 shellflags:     198
1243 make:   191
1244 d_pwage:        189
1245 d_pwchange:     189
1246 d_pwclass:      189
1247 d_pwcomment:    189
1248 d_pwexpire:     189
1249 d_pwgecos:      189
1250 d_pwpasswd:     189
1251 d_pwquota:      189
1252 gccversion:     189
1253 libs:   186
1254 useshrplib:     186
1255 cppflags:       185
1256 ptrsize:        185
1257 shrpenv:        185
1258 static_ext:     185
1259 uselargefiles:  185
1260 alignbytes:     184
1261 byteorder:      184
1262 ccversion:      184
1263 config_args:    184
1264 cppminus:       184