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