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