This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update Unicode-Collate to CPAN version 1.01
[perl5.git] / make_ext.pl
1 #!./miniperl
2 use strict;
3 use warnings;
4 use constant IS_CROSS => defined $::Cross::platform ? 1 : 0;
5 use Config;
6
7 my $is_Win32 = $^O eq 'MSWin32';
8 my $is_VMS = $^O eq 'VMS';
9 my $is_Unix = !$is_Win32 && !$is_VMS;
10
11 my @ext_dirs = qw(cpan dist ext);
12 my $ext_dirs_re = '(?:' . join('|', @ext_dirs) . ')';
13
14 # This script acts as a simple interface for building extensions.
15
16 # It's actually a cut and shut of the Unix version ext/utils/makeext and the
17 # Windows version win32/build_ext.pl hence the two invocation styles.
18
19 # On Unix, it primarily used by the perl Makefile one extension at a time:
20 #
21 # d_dummy $(dynamic_ext): miniperl preplibrary FORCE
22 #       @$(RUN) ./miniperl make_ext.pl --target=dynamic $@ MAKE=$(MAKE) LIBPERL_A=$(LIBPERL)
23 #
24 # On Windows or VMS,
25 # If '--static' is specified, static extensions will be built.
26 # If '--dynamic' is specified, dynamic extensions will be built.
27 # If '--nonxs' is specified, nonxs extensions will be built.
28 # If '--dynaloader' is specified, DynaLoader will be built.
29 # If '--all' is specified, all extensions will be built.
30 #
31 #    make_ext.pl "MAKE=make [-make_opts]" --dir=directory [--target=target] [--static|--dynamic|--all] +ext2 !ext1
32 #
33 # E.g.
34
35 #     make_ext.pl "MAKE=nmake -nologo" --dir=..\ext
36
37 #     make_ext.pl "MAKE=nmake -nologo" --dir=..\ext --target=clean
38
39 #     make_ext.pl MAKE=dmake --dir=..\ext
40
41 #     make_ext.pl MAKE=dmake --dir=..\ext --target=clean
42
43 # Will skip building extensions which are marked with an '!' char.
44 # Mostly because they still not ported to specified platform.
45
46 # If any extensions are listed with a '+' char then only those
47 # extensions will be built, but only if they aren't countermanded
48 # by an '!ext' and are appropriate to the type of building being done.
49 # An extensions follows the format of Foo/Bar, which would be extension Foo::Bar
50
51 # It may be deleted in a later release of perl so try to
52 # avoid using it for other purposes.
53
54 my (%excl, %incl, %opts, @extspec, @pass_through);
55
56 foreach (@ARGV) {
57     if (/^!(.*)$/) {
58         $excl{$1} = 1;
59     } elsif (/^\+(.*)$/) {
60         $incl{$1} = 1;
61     } elsif (/^--([\w\-]+)$/) {
62         $opts{$1} = 1;
63     } elsif (/^--([\w\-]+)=(.*)$/) {
64         push @{$opts{$1}}, $2;
65     } elsif (/=/) {
66         push @pass_through, $_;
67     } elsif (length) {
68         push @extspec, $_;
69     }
70 }
71
72 my $static = $opts{static} || $opts{all};
73 my $dynamic = $opts{dynamic} || $opts{all};
74 my $nonxs = $opts{nonxs} || $opts{all};
75 my $dynaloader = $opts{dynaloader} || $opts{all};
76
77 # The Perl Makefile.SH will expand all extensions to
78 #       lib/auto/X/X.a  (or lib/auto/X/Y/Y.a if nested)
79 # A user wishing to run make_ext might use
80 #       X (or X/Y or X::Y if nested)
81
82 # canonise into X/Y form (pname)
83
84 foreach (@extspec) {
85     if (s{^lib/auto/}{}) {
86         # Remove lib/auto prefix and /*.* suffix
87         s{/[^/]+\.[^/]+$}{};
88     } elsif (s{^$ext_dirs_re/}{}) {
89         # Remove ext/ prefix and /pm_to_blib suffix
90         s{/pm_to_blib$}{};
91         # Targets are given as files on disk, but the extension spec is still
92         # written using /s for each ::
93         tr!-!/!;
94     } elsif (s{::}{\/}g) {
95         # Convert :: to /
96     } else {
97         s/\..*o//;
98     }
99 }
100
101 my $makecmd  = shift @pass_through; # Should be something like MAKE=make
102 unshift @pass_through, 'PERL_CORE=1';
103
104 my @dirs  = @{$opts{dir} || \@ext_dirs};
105 my $target   = $opts{target}[0];
106 $target = 'all' unless defined $target;
107
108 # Previously, $make was taken from config.sh.  However, the user might
109 # instead be running a possibly incompatible make.  This might happen if
110 # the user types "gmake" instead of a plain "make", for example.  The
111 # correct current value of MAKE will come through from the main perl
112 # makefile as MAKE=/whatever/make in $makecmd.  We'll be cautious in
113 # case third party users of this script (are there any?) don't have the
114 # MAKE=$(MAKE) argument, which was added after 5.004_03.
115 unless(defined $makecmd and $makecmd =~ /^MAKE=(.*)$/) {
116     die "$0:  WARNING:  Please include MAKE=\$(MAKE) in \@ARGV\n";
117 }
118
119 # This isn't going to cope with anything fancy, such as spaces inside command
120 # names, but neither did what it replaced. Once there is a use case that needs
121 # it, please supply patches. Until then, I'm sticking to KISS
122 my @make = split ' ', $1 || $Config{make} || $ENV{MAKE};
123 # Using an array of 0 or 1 elements makes the subsequent code simpler.
124 my @run = $Config{run};
125 @run = () if not defined $run[0] or $run[0] eq '';
126
127
128 if ($target eq '') {
129     die "make_ext: no make target specified (eg all or clean)\n";
130 } elsif ($target !~ /(?:^all|clean)$/) {
131     # for the time being we are strict about what make_ext is used for
132     die "$0: unknown make target '$target'\n";
133 }
134
135 if (!@extspec and !$static and !$dynamic and !$nonxs and !$dynaloader)  {
136     die "$0: no extension specified\n";
137 }
138
139 my $perl;
140 my %extra_passthrough;
141
142 if ($is_Win32) {
143     require Cwd;
144     require FindExt;
145     my $build = Cwd::getcwd();
146     $perl = $^X;
147     if ($perl =~ m#^\.\.#) {
148         my $here = $build;
149         $here =~ s{/}{\\}g;
150         $perl = "$here\\$perl";
151     }
152     (my $topdir = $perl) =~ s/\\[^\\]+$//;
153     # miniperl needs to find perlglob and pl2bat
154     $ENV{PATH} = "$topdir;$topdir\\win32\\bin;$ENV{PATH}";
155     my $pl2bat = "$topdir\\win32\\bin\\pl2bat";
156     unless (-f "$pl2bat.bat") {
157         my @args = ($perl, "-I$topdir\\lib", ("$pl2bat.pl") x 2);
158         print "@args\n";
159         system(@args) unless IS_CROSS;
160     }
161
162     print "In $build";
163     foreach my $dir (@dirs) {
164         chdir($dir) or die "Cannot cd to $dir: $!\n";
165         (my $ext = Cwd::getcwd()) =~ s{/}{\\}g;
166         FindExt::scan_ext($ext);
167         FindExt::set_static_extensions(split ' ', $Config{static_ext});
168         chdir $build
169             or die "Couldn't chdir to '$build': $!"; # restore our start directory
170     }
171
172     my @ext;
173     push @ext, FindExt::static_ext() if $static;
174     push @ext, FindExt::dynamic_ext() if $dynamic;
175     push @ext, FindExt::nonxs_ext() if $nonxs;
176     push @ext, 'DynaLoader' if $dynaloader;
177
178     foreach (sort @ext) {
179         if (%incl and !exists $incl{$_}) {
180             #warn "Skipping extension $_, not in inclusion list\n";
181             next;
182         }
183         if (exists $excl{$_}) {
184             warn "Skipping extension $_, not ported to current platform";
185             next;
186         }
187         push @extspec, $_;
188         if($_ eq 'DynaLoader' and $target !~ /clean$/) {
189             # No, we don't know why nmake can't work out the dependency chain
190             push @{$extra_passthrough{$_}}, 'DynaLoader.c';
191         } elsif(FindExt::is_static($_)) {
192             push @{$extra_passthrough{$_}}, 'LINKTYPE=static';
193         }
194     }
195
196     chdir '..'
197         or die "Couldn't chdir to build directory: $!"; # now in the Perl build
198 }
199 elsif ($is_VMS) {
200     $perl = $^X;
201     push @extspec, (split ' ', $Config{static_ext}) if $static;
202     push @extspec, (split ' ', $Config{dynamic_ext}) if $dynamic;
203     push @extspec, (split ' ', $Config{nonxs_ext}) if $nonxs;
204     push @extspec, 'DynaLoader' if $dynaloader;
205 }
206
207 {
208     # Cwd needs to be built before Encode recurses into subdirectories.
209     # Pod::Simple needs to be built before Pod::Functions
210     # This seems to be the simplest way to ensure this ordering:
211     my (@first, @other);
212     foreach (@extspec) {
213         if ($_ eq 'Cwd' || $_ eq 'Pod/Simple') {
214             push @first, $_;
215         } else {
216             push @other, $_;
217         }
218     }
219     @extspec = (@first, @other);
220 }
221
222 if ($Config{osname} eq 'catamount' and @extspec) {
223     # Snowball's chance of building extensions.
224     die "This is $Config{osname}, not building $extspec[0], sorry.\n";
225 }
226
227 foreach my $spec (@extspec)  {
228     my $mname = $spec;
229     $mname =~ s!/!::!g;
230     my $ext_pathname;
231
232     # Try new style ext/Data-Dumper/ first
233     my $copy = $spec;
234     $copy =~ tr!/!-!;
235     foreach my $dir (@ext_dirs) {
236         if (-d "$dir/$copy") {
237             $ext_pathname = "$dir/$copy";
238             last;
239         }
240     }
241
242     if (!defined $ext_pathname) {
243         if (-d "ext/$spec") {
244             # Old style ext/Data/Dumper/
245             $ext_pathname = "ext/$spec";
246         } else {
247             warn "Can't find extension $spec in any of @ext_dirs";
248             next;
249         }
250     }
251
252     print "\tMaking $mname ($target)\n";
253
254     build_extension($ext_pathname, $perl, $mname,
255                     [@pass_through, @{$extra_passthrough{$spec} || []}]);
256 }
257
258 sub build_extension {
259     my ($ext_dir, $perl, $mname, $pass_through) = @_;
260
261     unless (chdir "$ext_dir") {
262         warn "Cannot cd to $ext_dir: $!";
263         return;
264     }
265
266     my $up = $ext_dir;
267     $up =~ s![^/]+!..!g;
268
269     $perl ||= "$up/miniperl";
270     my $return_dir = $up;
271     my $lib_dir = "$up/lib";
272     $ENV{PERL_CORE} = 1;
273
274     my $makefile;
275     if ($is_VMS) {
276         $makefile = 'descrip.mms';
277         if ($target =~ /clean$/
278             && !-f $makefile
279             && -f "${makefile}_old") {
280             $makefile = "${makefile}_old";
281         }
282     } else {
283         $makefile = 'Makefile';
284     }
285     
286     if (-f $makefile) {
287         open my $mfh, $makefile or die "Cannot open $makefile: $!";
288         while (<$mfh>) {
289             # Plagiarised from CPAN::Distribution
290             last if /MakeMaker post_initialize section/;
291             next unless /^#\s+VERSION_FROM\s+=>\s+(.+)/;
292             my $vmod = eval $1;
293             my $oldv;
294             while (<$mfh>) {
295                 next unless /^XS_VERSION = (\S+)/;
296                 $oldv = $1;
297                 last;
298             }
299             last unless defined $oldv;
300             require ExtUtils::MM_Unix;
301             defined (my $newv = parse_version MM $vmod) or last;
302             if ($newv ne $oldv) {
303                 close $mfh or die "close $makefile: $!";
304                 _unlink($makefile);
305                 {
306                     no warnings 'deprecated';
307                     goto NO_MAKEFILE;
308                 }
309             }
310         }
311         if(IS_CROSS){
312             seek($mfh, 0, 0) or die "Cannot seek $makefile: $!";
313             while (<$mfh>) {
314                 #this is used to stop the while loop early for efficiency when
315                 #the line is reached, and possibly match a cross build
316                 my $header = quotemeta '# These definitions are from config.sh (via ';
317                 if(/^$header.+?
318                     (xlib[\/\\]
319                     $::Cross::platform\Q\/Config.pm\E)?\)\./x) {
320                     unless (defined $1){
321                         print "Deleting non-Cross makefile\n";
322                         close $mfh or die "close $makefile: $!";
323                         _unlink($makefile);
324                         {
325                             no warnings 'deprecated';
326                             goto NO_MAKEFILE;
327                         }
328                     } else { #have a cross makefile
329                         goto CROSS_OK_MF;
330                     }
331                 }
332             } #catch breakage from future changes
333             die "non-standard makefile found in $mname";
334             CROSS_OK_MF:
335         }
336     }
337
338     if (!-f $makefile) {
339         NO_MAKEFILE:
340         if (!-f 'Makefile.PL') {
341             print "\nCreating Makefile.PL in $ext_dir for $mname\n";
342             my ($fromname, $key, $value);
343             if ($mname eq 'podlators') {
344                 # We need to special case this somewhere, and this is fewer
345                 # lines of code than a core-only Makefile.PL, and no more
346                 # complex
347                 $fromname = 'VERSION';
348                 $key = 'DISTNAME';
349                 $value = 'podlators';
350                 $mname = 'Pod';
351             } else {
352                 $key = 'ABSTRACT_FROM';
353                 # We need to cope well with various possible layouts
354                 my @dirs = split /::/, $mname;
355                 my $leaf = pop @dirs;
356                 my $leafname = "$leaf.pm";
357                 my $pathname = join '/', @dirs, $leafname;
358                 my @locations = ($leafname, $pathname, "lib/$pathname");
359                 unshift @locations, 'lib/IO/Compress/Base.pm' if $mname eq 'IO::Compress';
360                 foreach (@locations) {
361                     if (-f $_) {
362                         $fromname = $_;
363                         last;
364                     }
365                 }
366
367                 unless ($fromname) {
368                     die "For $mname tried @locations in in $ext_dir but can't find source";
369                 }
370                 ($value = $fromname) =~ s/\.pm\z/.pod/;
371                 $value = $fromname unless -e $value;
372             }
373             open my $fh, '>', 'Makefile.PL'
374                 or die "Can't open Makefile.PL for writing: $!";
375             printf $fh <<'EOM', $0, $mname, $fromname, $key, $value;
376 #-*- buffer-read-only: t -*-
377
378 # This Makefile.PL was written by %s.
379 # It will be deleted automatically by make realclean
380
381 use strict;
382 use ExtUtils::MakeMaker;
383
384 # This is what the .PL extracts to. Not the ultimate file that is installed.
385 # (ie Win32 runs pl2bat after this)
386
387 # Doing this here avoids all sort of quoting issues that would come from
388 # attempting to write out perl source with literals to generate the arrays and
389 # hash.
390 my @temps = 'Makefile.PL';
391 foreach (glob('scripts/pod*.PL')) {
392     # The various pod*.PL extractors change directory. Doing that with relative
393     # paths in @INC breaks. It seems the lesser of two evils to copy (to avoid)
394     # the chdir doing anything, than to attempt to convert lib paths to
395     # absolute, and potentially run into problems with quoting special
396     # characters in the path to our build dir (such as spaces)
397     require File::Copy;
398
399     my $temp = $_;
400     $temp =~ s!scripts/!!;
401     File::Copy::copy($_, $temp) or die "Can't copy $temp to $_: $!";
402     push @temps, $temp;
403 }
404
405 my $script_ext = $^O eq 'VMS' ? '.com' : '';
406 my %%pod_scripts;
407 foreach (glob('pod*.PL')) {
408     my $script = $_;
409     s/.PL$/$script_ext/i;
410     $pod_scripts{$script} = $_;
411 }
412 my @exe_files = values %%pod_scripts;
413
414 WriteMakefile(
415     NAME          => '%s',
416     VERSION_FROM  => '%s',
417     %-13s => '%s',
418     realclean     => { FILES => "@temps" },
419     (%%pod_scripts ? (
420         PL_FILES  => \%%pod_scripts,
421         EXE_FILES => \@exe_files,
422         clean     => { FILES => "@exe_files" },
423     ) : ()),
424 );
425
426 # ex: set ro:
427 EOM
428             close $fh or die "Can't close Makefile.PL: $!";
429             # As described in commit 23525070d6c0e51f:
430             # Push the atime and mtime of generated Makefile.PLs back 4
431             # seconds. In certain circumstances ( on virtual machines ) the
432             # generated Makefile.PL can produce a Makefile that is older than
433             # the Makefile.PL. Altering the atime and mtime backwards by 4
434             # seconds seems to resolve the issue.
435             eval {
436                 my $ftime = time - 4;
437                 utime $ftime, $ftime, 'Makefile.PL';
438             };
439         }
440         print "\nRunning Makefile.PL in $ext_dir\n";
441
442         # Presumably this can be simplified
443         my @cross;
444         if (IS_CROSS) {
445             # Inherited from win32/buildext.pl
446             @cross = "-MCross=$::Cross::platform";
447         } elsif ($opts{cross}) {
448             # Inherited from make_ext.pl
449             @cross = '-MCross';
450         }
451
452         my @args = ("-I$lib_dir", @cross, 'Makefile.PL');
453         if ($is_VMS) {
454             my $libd = VMS::Filespec::vmspath($lib_dir);
455             push @args, "INST_LIB=$libd", "INST_ARCHLIB=$libd";
456         } else {
457             push @args, 'INSTALLDIRS=perl', 'INSTALLMAN1DIR=none',
458                 'INSTALLMAN3DIR=none';
459         }
460         push @args, @$pass_through;
461         _quote_args(\@args) if $is_VMS;
462         print join(' ', @run, $perl, @args), "\n";
463         my $code = system @run, $perl, @args;
464         warn "$code from $ext_dir\'s Makefile.PL" if $code;
465
466         # Right. The reason for this little hack is that we're sitting inside
467         # a program run by ./miniperl, but there are tasks we need to perform
468         # when the 'realclean', 'distclean' or 'veryclean' targets are run.
469         # Unfortunately, they can be run *after* 'clean', which deletes
470         # ./miniperl
471         # So we do our best to leave a set of instructions identical to what
472         # we would do if we are run directly as 'realclean' etc
473         # Whilst we're perfect, unfortunately the targets we call are not, as
474         # some of them rely on a $(PERL) for their own distclean targets.
475         # But this always used to be a problem with the old /bin/sh version of
476         # this.
477         if ($is_Unix) {
478             my $suffix = '.sh';
479             foreach my $clean_target ('realclean', 'veryclean') {
480                 my $file = "$return_dir/$clean_target$suffix";
481                 open my $fh, '>>', $file or die "open $file: $!";
482                 # Quite possible that we're being run in parallel here.
483                 # Can't use Fcntl this early to get the LOCK_EX
484                 flock $fh, 2 or warn "flock $file: $!";
485                 print $fh <<"EOS";
486 cd $ext_dir
487 if test ! -f Makefile -a -f Makefile.old; then
488     echo "Note: Using Makefile.old"
489     make -f Makefile.old $clean_target MAKE='@make' @pass_through
490 else
491     if test ! -f Makefile ; then
492         echo "Warning: No Makefile!"
493     fi
494     make $clean_target MAKE='@make' @pass_through
495 fi
496 cd $return_dir
497 EOS
498                 close $fh or die "close $file: $!";
499             }
500         }
501     }
502
503     if (not -f $makefile) {
504         print "Warning: No Makefile!\n";
505     }
506
507     if ($is_VMS) {
508         _quote_args($pass_through);
509         @$pass_through = (
510                           "/DESCRIPTION=$makefile",
511                           '/MACRO=(' . join(',',@$pass_through) . ')'
512                          );
513     }
514
515     if (!$target or $target !~ /clean$/) {
516         # Give makefile an opportunity to rewrite itself.
517         # reassure users that life goes on...
518         my @args = ('config', @$pass_through);
519         system(@run, @make, @args) and print "@run @make @args failed, continuing anyway...\n";
520     }
521     my @targ = ($target, @$pass_through);
522     print "Making $target in $ext_dir\n@run @make @targ\n";
523     my $code = system(@run, @make, @targ);
524     die "Unsuccessful make($ext_dir): code=$code" if $code != 0;
525
526     chdir $return_dir || die "Cannot cd to $return_dir: $!";
527 }
528
529 sub _quote_args {
530     my $args = shift; # must be array reference
531
532     # Do not quote qualifiers that begin with '/'.
533     map { if (!/^\//) {
534           $_ =~ s/\"/""/g;     # escape C<"> by doubling
535           $_ = q(").$_.q(");
536         }
537     } @{$args}
538     ;
539 }
540
541 #guarentee that a file is deleted or die, void _unlink($filename)
542 #xxx replace with _unlink_or_rename from EU::Install?
543 sub _unlink {
544     1 while unlink $_[0];
545     my $err = $!;
546     die "Can't unlink $_[0]: $err" if -f $_[0];
547 }