This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Another perldelta typo
[perl5.git] / make_ext.pl
1 #!./miniperl
2 use strict;
3 use warnings;
4 use Config;
5 use constant IS_CROSS => defined $Config::Config{usecrosscompile} ? 1 : 0;
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
124
125 if ($target eq '') {
126     die "make_ext: no make target specified (eg all or clean)\n";
127 } elsif ($target !~ /(?:^all|clean)$/) {
128     # for the time being we are strict about what make_ext is used for
129     die "$0: unknown make target '$target'\n";
130 }
131
132 if (!@extspec and !$static and !$dynamic and !$nonxs and !$dynaloader)  {
133     die "$0: no extension specified\n";
134 }
135
136 my $perl;
137 my %extra_passthrough;
138
139 if ($is_Win32) {
140     require Cwd;
141     require FindExt;
142     my $build = Cwd::getcwd();
143     $perl = $^X;
144     if ($perl =~ m#^\.\.#) {
145         my $here = $build;
146         $here =~ s{/}{\\}g;
147         $perl = "$here\\$perl";
148     }
149     (my $topdir = $perl) =~ s/\\[^\\]+$//;
150     # miniperl needs to find perlglob and pl2bat
151     $ENV{PATH} = "$topdir;$topdir\\win32\\bin;$ENV{PATH}";
152     my $pl2bat = "$topdir\\win32\\bin\\pl2bat";
153     unless (-f "$pl2bat.bat") {
154         my @args = ($perl, "-I$topdir\\lib", ("$pl2bat.pl") x 2);
155         print "@args\n";
156         system(@args) unless IS_CROSS;
157     }
158
159     print "In $build";
160     foreach my $dir (@dirs) {
161         chdir($dir) or die "Cannot cd to $dir: $!\n";
162         (my $ext = Cwd::getcwd()) =~ s{/}{\\}g;
163         FindExt::scan_ext($ext);
164         FindExt::set_static_extensions(split ' ', $Config{static_ext});
165         chdir $build
166             or die "Couldn't chdir to '$build': $!"; # restore our start directory
167     }
168
169     my @ext;
170     push @ext, FindExt::static_ext() if $static;
171     push @ext, FindExt::dynamic_ext() if $dynamic;
172     push @ext, FindExt::nonxs_ext() if $nonxs;
173     push @ext, 'DynaLoader' if $dynaloader;
174
175     foreach (sort @ext) {
176         if (%incl and !exists $incl{$_}) {
177             #warn "Skipping extension $_, not in inclusion list\n";
178             next;
179         }
180         if (exists $excl{$_}) {
181             warn "Skipping extension $_, not ported to current platform";
182             next;
183         }
184         push @extspec, $_;
185         if($_ eq 'DynaLoader' and $target !~ /clean$/) {
186             # No, we don't know why nmake can't work out the dependency chain
187             push @{$extra_passthrough{$_}}, 'DynaLoader.c';
188         } elsif(FindExt::is_static($_)) {
189             push @{$extra_passthrough{$_}}, 'LINKTYPE=static';
190         }
191     }
192
193     chdir '..'
194         or die "Couldn't chdir to build directory: $!"; # now in the Perl build
195 }
196 elsif ($is_VMS) {
197     $perl = $^X;
198     push @extspec, (split ' ', $Config{static_ext}) if $static;
199     push @extspec, (split ' ', $Config{dynamic_ext}) if $dynamic;
200     push @extspec, (split ' ', $Config{nonxs_ext}) if $nonxs;
201     push @extspec, 'DynaLoader' if $dynaloader;
202 }
203
204 {
205     # Cwd needs to be built before Encode recurses into subdirectories.
206     # Pod::Simple needs to be built before Pod::Functions
207     # This seems to be the simplest way to ensure this ordering:
208     my (@first, @other);
209     foreach (@extspec) {
210         if ($_ eq 'Cwd' || $_ eq 'Pod/Simple') {
211             push @first, $_;
212         } else {
213             push @other, $_;
214         }
215     }
216     @extspec = (@first, @other);
217 }
218
219 if ($Config{osname} eq 'catamount' and @extspec) {
220     # Snowball's chance of building extensions.
221     die "This is $Config{osname}, not building $extspec[0], sorry.\n";
222 }
223
224 foreach my $spec (@extspec)  {
225     my $mname = $spec;
226     $mname =~ s!/!::!g;
227     my $ext_pathname;
228
229     # Try new style ext/Data-Dumper/ first
230     my $copy = $spec;
231     $copy =~ tr!/!-!;
232
233     # List/Util.xs lives in Scalar-List-Utils, Cwd.xs lives in PathTools
234     $copy = 'Scalar-List-Utils' if $copy eq 'List-Util';
235     $copy = 'PathTools'         if $copy eq 'Cwd';
236
237     foreach my $dir (@ext_dirs) {
238         if (-d "$dir/$copy") {
239             $ext_pathname = "$dir/$copy";
240             last;
241         }
242     }
243
244     if (!defined $ext_pathname) {
245         if (-d "ext/$spec") {
246             # Old style ext/Data/Dumper/
247             $ext_pathname = "ext/$spec";
248         } else {
249             warn "Can't find extension $spec in any of @ext_dirs";
250             next;
251         }
252     }
253
254     print "\tMaking $mname ($target)\n";
255
256     build_extension($ext_pathname, $perl, $mname,
257                     [@pass_through, @{$extra_passthrough{$spec} || []}]);
258 }
259
260 sub build_extension {
261     my ($ext_dir, $perl, $mname, $pass_through) = @_;
262
263     unless (chdir "$ext_dir") {
264         warn "Cannot cd to $ext_dir: $!";
265         return;
266     }
267
268     my $up = $ext_dir;
269     $up =~ s![^/]+!..!g;
270
271     $perl ||= "$up/miniperl";
272     my $return_dir = $up;
273     my $lib_dir = "$up/lib";
274     $ENV{PERL_CORE} = 1;
275
276     my $makefile;
277     if ($is_VMS) {
278         $makefile = 'descrip.mms';
279         if ($target =~ /clean$/
280             && !-f $makefile
281             && -f "${makefile}_old") {
282             $makefile = "${makefile}_old";
283         }
284     } else {
285         $makefile = 'Makefile';
286     }
287     
288     if (-f $makefile) {
289         open my $mfh, $makefile or die "Cannot open $makefile: $!";
290         while (<$mfh>) {
291             # Plagiarised from CPAN::Distribution
292             last if /MakeMaker post_initialize section/;
293             next unless /^#\s+VERSION_FROM\s+=>\s+(.+)/;
294             my $vmod = eval $1;
295             my $oldv;
296             while (<$mfh>) {
297                 next unless /^XS_VERSION = (\S+)/;
298                 $oldv = $1;
299                 last;
300             }
301             last unless defined $oldv;
302             require ExtUtils::MM_Unix;
303             defined (my $newv = parse_version MM $vmod) or last;
304             if ($newv ne $oldv) {
305                 close $mfh or die "close $makefile: $!";
306                 _unlink($makefile);
307                 {
308                     no warnings 'deprecated';
309                     goto NO_MAKEFILE;
310                 }
311             }
312         }
313
314         if (IS_CROSS) {
315             # If we're cross-compiling, it's possible that the host's
316             # Makefiles are around.
317             seek($mfh, 0, 0) or die "Cannot seek $makefile: $!";
318             
319             my $cross_makefile;
320             while (<$mfh>) {
321                 # XXX This might not be throughout enough.
322                 # For example, it's possible to cause a false-positive
323                 # if cross compiling on and for the Raspberry Pi,
324                 # which is insane but plausible.
325                 # False positives are really not troublesome, though;
326                 # all they mean is that the module gets rebuilt.
327                 if (/^CC = \Q$Config{cc}\E/) {
328                     $cross_makefile = 1;
329                     last;
330                 }
331             }
332             
333             if (!$cross_makefile) {
334                 print "Deleting non-Cross makefile\n";
335                 close $mfh or die "close $makefile: $!";
336                 _unlink($makefile);
337             }
338         }
339     }
340
341     if (!-f $makefile) {
342         NO_MAKEFILE:
343         if (!-f 'Makefile.PL') {
344             print "\nCreating Makefile.PL in $ext_dir for $mname\n";
345             my ($fromname, $key, $value);
346             if ($mname eq 'podlators') {
347                 # We need to special case this somewhere, and this is fewer
348                 # lines of code than a core-only Makefile.PL, and no more
349                 # complex
350                 $fromname = 'VERSION';
351                 $key = 'DISTNAME';
352                 $value = 'podlators';
353                 $mname = 'Pod';
354             } else {
355                 $key = 'ABSTRACT_FROM';
356                 # We need to cope well with various possible layouts
357                 my @dirs = split /::/, $mname;
358                 my $leaf = pop @dirs;
359                 my $leafname = "$leaf.pm";
360                 my $pathname = join '/', @dirs, $leafname;
361                 my @locations = ($leafname, $pathname, "lib/$pathname");
362                 unshift @locations, 'lib/IO/Compress/Base.pm' if $mname eq 'IO::Compress';
363                 foreach (@locations) {
364                     if (-f $_) {
365                         $fromname = $_;
366                         last;
367                     }
368                 }
369
370                 unless ($fromname) {
371                     die "For $mname tried @locations in in $ext_dir but can't find source";
372                 }
373                 ($value = $fromname) =~ s/\.pm\z/.pod/;
374                 $value = $fromname unless -e $value;
375             }
376             open my $fh, '>', 'Makefile.PL'
377                 or die "Can't open Makefile.PL for writing: $!";
378             printf $fh <<'EOM', $0, $mname, $fromname, $key, $value;
379 #-*- buffer-read-only: t -*-
380
381 # This Makefile.PL was written by %s.
382 # It will be deleted automatically by make realclean
383
384 use strict;
385 use ExtUtils::MakeMaker;
386
387 # This is what the .PL extracts to. Not the ultimate file that is installed.
388 # (ie Win32 runs pl2bat after this)
389
390 # Doing this here avoids all sort of quoting issues that would come from
391 # attempting to write out perl source with literals to generate the arrays and
392 # hash.
393 my @temps = 'Makefile.PL';
394 foreach (glob('scripts/pod*.PL')) {
395     # The various pod*.PL extractors change directory. Doing that with relative
396     # paths in @INC breaks. It seems the lesser of two evils to copy (to avoid)
397     # the chdir doing anything, than to attempt to convert lib paths to
398     # absolute, and potentially run into problems with quoting special
399     # characters in the path to our build dir (such as spaces)
400     require File::Copy;
401
402     my $temp = $_;
403     $temp =~ s!scripts/!!;
404     File::Copy::copy($_, $temp) or die "Can't copy $temp to $_: $!";
405     push @temps, $temp;
406 }
407
408 my $script_ext = $^O eq 'VMS' ? '.com' : '';
409 my %%pod_scripts;
410 foreach (glob('pod*.PL')) {
411     my $script = $_;
412     s/.PL$/$script_ext/i;
413     $pod_scripts{$script} = $_;
414 }
415 my @exe_files = values %%pod_scripts;
416
417 WriteMakefile(
418     NAME          => '%s',
419     VERSION_FROM  => '%s',
420     %-13s => '%s',
421     realclean     => { FILES => "@temps" },
422     (%%pod_scripts ? (
423         PL_FILES  => \%%pod_scripts,
424         EXE_FILES => \@exe_files,
425         clean     => { FILES => "@exe_files" },
426     ) : ()),
427 );
428
429 # ex: set ro:
430 EOM
431             close $fh or die "Can't close Makefile.PL: $!";
432             # As described in commit 23525070d6c0e51f:
433             # Push the atime and mtime of generated Makefile.PLs back 4
434             # seconds. In certain circumstances ( on virtual machines ) the
435             # generated Makefile.PL can produce a Makefile that is older than
436             # the Makefile.PL. Altering the atime and mtime backwards by 4
437             # seconds seems to resolve the issue.
438             eval {
439                 my $ftime = time - 4;
440                 utime $ftime, $ftime, 'Makefile.PL';
441             };
442         }
443         print "\nRunning Makefile.PL in $ext_dir\n";
444
445         my @args = ("-I$lib_dir", 'Makefile.PL');
446         if ($is_VMS) {
447             my $libd = VMS::Filespec::vmspath($lib_dir);
448             push @args, "INST_LIB=$libd", "INST_ARCHLIB=$libd";
449         } else {
450             push @args, 'INSTALLDIRS=perl', 'INSTALLMAN1DIR=none',
451                 'INSTALLMAN3DIR=none';
452         }
453         push @args, @$pass_through;
454         _quote_args(\@args) if $is_VMS;
455         print join(' ', $perl, @args), "\n";
456         my $code = system $perl, @args;
457         warn "$code from $ext_dir\'s Makefile.PL" if $code;
458
459         # Right. The reason for this little hack is that we're sitting inside
460         # a program run by ./miniperl, but there are tasks we need to perform
461         # when the 'realclean', 'distclean' or 'veryclean' targets are run.
462         # Unfortunately, they can be run *after* 'clean', which deletes
463         # ./miniperl
464         # So we do our best to leave a set of instructions identical to what
465         # we would do if we are run directly as 'realclean' etc
466         # Whilst we're perfect, unfortunately the targets we call are not, as
467         # some of them rely on a $(PERL) for their own distclean targets.
468         # But this always used to be a problem with the old /bin/sh version of
469         # this.
470         if ($is_Unix) {
471             my $suffix = '.sh';
472             foreach my $clean_target ('realclean', 'veryclean') {
473                 my $file = "$return_dir/$clean_target$suffix";
474                 open my $fh, '>>', $file or die "open $file: $!";
475                 # Quite possible that we're being run in parallel here.
476                 # Can't use Fcntl this early to get the LOCK_EX
477                 flock $fh, 2 or warn "flock $file: $!";
478                 print $fh <<"EOS";
479 cd $ext_dir
480 if test ! -f Makefile -a -f Makefile.old; then
481     echo "Note: Using Makefile.old"
482     make -f Makefile.old $clean_target MAKE='@make' @pass_through
483 else
484     if test ! -f Makefile ; then
485         echo "Warning: No Makefile!"
486     fi
487     make $clean_target MAKE='@make' @pass_through
488 fi
489 cd $return_dir
490 EOS
491                 close $fh or die "close $file: $!";
492             }
493         }
494     }
495
496     if (not -f $makefile) {
497         print "Warning: No Makefile!\n";
498     }
499
500     if ($is_VMS) {
501         _quote_args($pass_through);
502         @$pass_through = (
503                           "/DESCRIPTION=$makefile",
504                           '/MACRO=(' . join(',',@$pass_through) . ')'
505                          );
506     }
507
508     if (!$target or $target !~ /clean$/) {
509         # Give makefile an opportunity to rewrite itself.
510         # reassure users that life goes on...
511         my @args = ('config', @$pass_through);
512         system(@make, @args) and print "@make @args failed, continuing anyway...\n";
513     }
514     my @targ = ($target, @$pass_through);
515     print "Making $target in $ext_dir\n@make @targ\n";
516     my $code = system(@make, @targ);
517     die "Unsuccessful make($ext_dir): code=$code" if $code != 0;
518
519     chdir $return_dir || die "Cannot cd to $return_dir: $!";
520 }
521
522 sub _quote_args {
523     my $args = shift; # must be array reference
524
525     # Do not quote qualifiers that begin with '/'.
526     map { if (!/^\//) {
527           $_ =~ s/\"/""/g;     # escape C<"> by doubling
528           $_ = q(").$_.q(");
529         }
530     } @{$args}
531     ;
532 }
533
534 #guarentee that a file is deleted or die, void _unlink($filename)
535 #xxx replace with _unlink_or_rename from EU::Install?
536 sub _unlink {
537     1 while unlink $_[0];
538     my $err = $!;
539     die "Can't unlink $_[0]: $err" if -f $_[0];
540 }