This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Have more fallbacks for our signbit() emulation.
[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              IS_WIN32 => $^O eq 'MSWin32',
7              IS_VMS   => $^O eq 'VMS',
8              IS_UNIX  => $^O ne 'MSWin32' && $^O ne 'VMS',
9 };
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, $verbose);
55
56 foreach (@ARGV) {
57     if (/^!(.*)$/) {
58         $excl{$1} = 1;
59     } elsif (/^\+(.*)$/) {
60         $incl{$1} = 1;
61     } elsif (/^--verbose$/ or /^-v$/) {
62         $verbose = 1;
63     } elsif (/^--([\w\-]+)$/) {
64         $opts{$1} = 1;
65     } elsif (/^--([\w\-]+)=(.*)$/) {
66         push @{$opts{$1}}, $2;
67     } elsif (/=/) {
68         push @pass_through, $_;
69     } elsif (length) {
70         push @extspec, $_;
71     }
72 }
73
74 my $static = $opts{static} || $opts{all};
75 my $dynamic = $opts{dynamic} || $opts{all};
76 my $nonxs = $opts{nonxs} || $opts{all};
77 my $dynaloader = $opts{dynaloader} || $opts{all};
78
79 # The Perl Makefile.SH will expand all extensions to
80 #       lib/auto/X/X.a  (or lib/auto/X/Y/Y.a if nested)
81 # A user wishing to run make_ext might use
82 #       X (or X/Y or X::Y if nested)
83
84 # canonise into X/Y form (pname)
85
86 foreach (@extspec) {
87     if (s{^lib/auto/}{}) {
88         # Remove lib/auto prefix and /*.* suffix
89         s{/[^/]+\.[^/]+$}{};
90     } elsif (s{^$ext_dirs_re/}{}) {
91         # Remove ext/ prefix and /pm_to_blib suffix
92         s{/pm_to_blib$}{};
93         # Targets are given as files on disk, but the extension spec is still
94         # written using /s for each ::
95         tr!-!/!;
96     } elsif (s{::}{\/}g) {
97         # Convert :: to /
98     } else {
99         s/\..*o//;
100     }
101 }
102
103 my $makecmd  = shift @pass_through; # Should be something like MAKE=make
104 unshift @pass_through, 'PERL_CORE=1';
105
106 my @dirs  = @{$opts{dir} || \@ext_dirs};
107 my $target   = $opts{target}[0];
108 $target = 'all' unless defined $target;
109
110 # Previously, $make was taken from config.sh.  However, the user might
111 # instead be running a possibly incompatible make.  This might happen if
112 # the user types "gmake" instead of a plain "make", for example.  The
113 # correct current value of MAKE will come through from the main perl
114 # makefile as MAKE=/whatever/make in $makecmd.  We'll be cautious in
115 # case third party users of this script (are there any?) don't have the
116 # MAKE=$(MAKE) argument, which was added after 5.004_03.
117 unless(defined $makecmd and $makecmd =~ /^MAKE=(.*)$/) {
118     die "$0:  WARNING:  Please include MAKE=\$(MAKE) in \@ARGV\n";
119 }
120
121 # This isn't going to cope with anything fancy, such as spaces inside command
122 # names, but neither did what it replaced. Once there is a use case that needs
123 # it, please supply patches. Until then, I'm sticking to KISS
124 my @make = split ' ', $1 || $Config{make} || $ENV{MAKE};
125
126
127 if ($target eq '') {
128     die "make_ext: no make target specified (eg all or clean)\n";
129 } elsif ($target !~ /^(?:all|clean|distclean|realclean|veryclean)$/) {
130     # we are strict about what make_ext is used for because we emulate these
131     # targets for simple modules:
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" if $verbose;
159         system(@args) unless IS_CROSS;
160     }
161
162     print "In $build" if $verbose;
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($_ ne 'DynaLoader' && 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 $ENV{PERL_CORE} = 1;
224
225 foreach my $spec (@extspec)  {
226     my $mname = $spec;
227     $mname =~ s!/!::!g;
228     my $ext_pathname;
229
230     # Try new style ext/Data-Dumper/ first
231     my $copy = $spec;
232     $copy =~ tr!/!-!;
233
234     # List/Util.xs lives in Scalar-List-Utils, Cwd.xs lives in PathTools
235     $copy = 'Scalar-List-Utils' if $copy eq 'List-Util';
236     $copy = 'PathTools'         if $copy eq 'Cwd';
237
238     foreach my $dir (@ext_dirs) {
239         if (-d "$dir/$copy") {
240             $ext_pathname = "$dir/$copy";
241             last;
242         }
243     }
244
245     if (!defined $ext_pathname) {
246         if (-d "ext/$spec") {
247             # Old style ext/Data/Dumper/
248             $ext_pathname = "ext/$spec";
249         } else {
250             warn "Can't find extension $spec in any of @ext_dirs";
251             next;
252         }
253     }
254
255     print "\tMaking $mname ($target)\n" if $verbose;
256
257     build_extension($ext_pathname, $perl, $mname, $target,
258                     [@pass_through, @{$extra_passthrough{$spec} || []}]);
259 }
260
261 sub build_extension {
262     my ($ext_dir, $perl, $mname, $target, $pass_through) = @_;
263
264     unless (chdir "$ext_dir") {
265         warn "Cannot cd to $ext_dir: $!";
266         return;
267     }
268
269     my $up = $ext_dir;
270     $up =~ s![^/]+!..!g;
271
272     $perl ||= "$up/miniperl";
273     my $return_dir = $up;
274     my $lib_dir = "$up/lib";
275
276     my ($makefile, $makefile_no_minus_f);
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         $makefile_no_minus_f = 0;
290         open my $mfh, $makefile or die "Cannot open $makefile: $!";
291         while (<$mfh>) {
292             # Plagiarised from CPAN::Distribution
293             last if /MakeMaker post_initialize section/;
294             next unless /^#\s+VERSION_FROM\s+=>\s+(.+)/;
295             my $vmod = eval $1;
296             my $oldv;
297             while (<$mfh>) {
298                 next unless /^XS_VERSION = (\S+)/;
299                 $oldv = $1;
300                 last;
301             }
302             last unless defined $oldv;
303             require ExtUtils::MM_Unix;
304             defined (my $newv = parse_version MM $vmod) or last;
305             if ($newv ne $oldv) {
306                 close $mfh or die "close $makefile: $!";
307                 _unlink($makefile);
308                 {
309                     no warnings 'deprecated';
310                     goto NO_MAKEFILE;
311                 }
312             }
313         }
314
315         if (IS_CROSS) {
316             # If we're cross-compiling, it's possible that the host's
317             # Makefiles are around.
318             seek($mfh, 0, 0) or die "Cannot seek $makefile: $!";
319             
320             my $cross_makefile;
321             while (<$mfh>) {
322                 # XXX This might not be throughout enough.
323                 # For example, it's possible to cause a false-positive
324                 # if cross compiling on and for the Raspberry Pi,
325                 # which is insane but plausible.
326                 # False positives are really not troublesome, though;
327                 # all they mean is that the module gets rebuilt.
328                 if (/^CC = \Q$Config{cc}\E/) {
329                     $cross_makefile = 1;
330                     last;
331                 }
332             }
333             
334             if (!$cross_makefile) {
335                 print "Deleting non-Cross makefile\n";
336                 close $mfh or die "close $makefile: $!";
337                 _unlink($makefile);
338             }
339         }
340     } else {
341         $makefile_no_minus_f = 1;
342     }
343
344     if ($makefile_no_minus_f || !-f $makefile) {
345         NO_MAKEFILE:
346         if (!-f 'Makefile.PL') {
347             unless (just_pm_to_blib($target, $ext_dir, $mname, $return_dir)) {
348                 # No problems returned, so it has faked everything for us. :-)
349                 chdir $return_dir || die "Cannot cd to $return_dir: $!";
350                 return;
351             }
352
353             print "\nCreating Makefile.PL in $ext_dir for $mname\n" if $verbose;
354             my ($fromname, $key, $value);
355             if ($mname eq 'podlators') {
356                 # We need to special case this somewhere, and this is fewer
357                 # lines of code than a core-only Makefile.PL, and no more
358                 # complex
359                 $fromname = 'VERSION';
360                 $key = 'DISTNAME';
361                 $value = 'podlators';
362                 $mname = 'Pod';
363             } else {
364                 $key = 'ABSTRACT_FROM';
365                 # We need to cope well with various possible layouts
366                 my @dirs = split /::/, $mname;
367                 my $leaf = pop @dirs;
368                 my $leafname = "$leaf.pm";
369                 my $pathname = join '/', @dirs, $leafname;
370                 my @locations = ($leafname, $pathname, "lib/$pathname");
371                 foreach (@locations) {
372                     if (-f $_) {
373                         $fromname = $_;
374                         last;
375                     }
376                 }
377
378                 unless ($fromname) {
379                     die "For $mname tried @locations in $ext_dir but can't find source";
380                 }
381                 ($value = $fromname) =~ s/\.pm\z/.pod/;
382                 $value = $fromname unless -e $value;
383             }
384
385             if ($mname eq 'Pod::Checker') {
386                 # the abstract in the .pm file is unparseable by MM,
387                 # so special-case it. We can't use the package's own
388                 # Makefile.PL, as it doesn't handle the executable scripts
389                 # right.
390                 $key = 'ABSTRACT';
391                 # this is copied from the CPAN Makefile.PL v 1.171
392                 $value = 'Pod::Checker verifies POD documentation contents for compliance with the POD format specifications';
393             }
394
395             open my $fh, '>', 'Makefile.PL'
396                 or die "Can't open Makefile.PL for writing: $!";
397             printf $fh <<'EOM', $0, $mname, $fromname, $key, $value;
398 #-*- buffer-read-only: t -*-
399
400 # This Makefile.PL was written by %s.
401 # It will be deleted automatically by make realclean
402
403 use strict;
404 use ExtUtils::MakeMaker;
405
406 # This is what the .PL extracts to. Not the ultimate file that is installed.
407 # (ie Win32 runs pl2bat after this)
408
409 # Doing this here avoids all sort of quoting issues that would come from
410 # attempting to write out perl source with literals to generate the arrays and
411 # hash.
412 my @temps = 'Makefile.PL';
413 foreach (glob('scripts/pod*.PL')) {
414     # The various pod*.PL extractors change directory. Doing that with relative
415     # paths in @INC breaks. It seems the lesser of two evils to copy (to avoid)
416     # the chdir doing anything, than to attempt to convert lib paths to
417     # absolute, and potentially run into problems with quoting special
418     # characters in the path to our build dir (such as spaces)
419     require File::Copy;
420
421     my $temp = $_;
422     $temp =~ s!scripts/!!;
423     File::Copy::copy($_, $temp) or die "Can't copy $temp to $_: $!";
424     push @temps, $temp;
425 }
426
427 my $script_ext = $^O eq 'VMS' ? '.com' : '';
428 my %%pod_scripts;
429 foreach (glob('pod*.PL')) {
430     my $script = $_;
431     s/.PL$/$script_ext/i;
432     $pod_scripts{$script} = $_;
433 }
434 my @exe_files = values %%pod_scripts;
435
436 WriteMakefile(
437     NAME          => '%s',
438     VERSION_FROM  => '%s',
439     %-13s => '%s',
440     realclean     => { FILES => "@temps" },
441     (%%pod_scripts ? (
442         PL_FILES  => \%%pod_scripts,
443         EXE_FILES => \@exe_files,
444         clean     => { FILES => "@exe_files" },
445     ) : ()),
446 );
447
448 # ex: set ro:
449 EOM
450             close $fh or die "Can't close Makefile.PL: $!";
451             # As described in commit 23525070d6c0e51f:
452             # Push the atime and mtime of generated Makefile.PLs back 4
453             # seconds. In certain circumstances ( on virtual machines ) the
454             # generated Makefile.PL can produce a Makefile that is older than
455             # the Makefile.PL. Altering the atime and mtime backwards by 4
456             # seconds seems to resolve the issue.
457             eval {
458         my $ftime = (stat('Makefile.PL'))[9] - 4;
459         utime $ftime, $ftime, 'Makefile.PL';
460             };
461         } elsif ($mname =~ /\A(?:Carp
462                             |ExtUtils::CBuilder
463                             |Safe
464                             |Search::Dict)\z/x) {
465             # An explicit list of dual-life extensions that have a Makefile.PL
466             # for CPAN, but we have verified can also be built using the fakery.
467             my ($problem) = just_pm_to_blib($target, $ext_dir, $mname, $return_dir);
468             # We really need to sanity test that we can fake it.
469             # Otherwise "skips" will go undetected, and the build slow down for
470             # everyone, defeating the purpose.
471             if (defined $problem) {
472                 if (-d "$return_dir/.git") {
473                     # Get the list of files that git isn't ignoring:
474                     my @files = `git ls-files --cached --others --exclude-standard 2>/dev/null`;
475                     # on error (eg no git) we get nothing, but that's not a
476                     # problem. The goal is to see if git thinks that the problem
477                     # file is interesting, by getting a positive match with
478                     # something git told us about, and if so bail out:
479                     foreach (@files) {
480                         chomp;
481                         # We really need to sanity test that we can fake it.
482                         # The intent is that this should only fail because
483                         # you've just added a file to the dual-life dist that
484                         # we can't handle. In which case you should either
485                         # 1) remove the dist from the regex a few lines above.
486                         # or
487                         # 2) add the file to regex of "safe" filenames earlier
488                         #    in this function, that starts with ChangeLog
489                         die "FATAL - $0 has $mname in the list of simple extensions, but it now contains file '$problem' which we can't handle"
490                             if $problem eq $_;
491                     }
492                     # There's an unexpected file, but it seems to be something
493                     # that git will ignore. So fall through to the regular
494                     # Makefile.PL handling code below, on the assumption that
495                     # we won't get here for a clean build.
496                 }
497                 warn "WARNING - $0 is building $mname using EU::MM, as it found file '$problem'";
498             } else {
499                 # It faked everything for us.
500                 chdir $return_dir || die "Cannot cd to $return_dir: $!";
501                 return;
502             }
503         }
504
505         # We are going to have to use Makefile.PL:
506         print "\nRunning Makefile.PL in $ext_dir\n" if $verbose;
507
508         my @args = ("-I$lib_dir", 'Makefile.PL');
509         if (IS_VMS) {
510             my $libd = VMS::Filespec::vmspath($lib_dir);
511             push @args, "INST_LIB=$libd", "INST_ARCHLIB=$libd";
512         } else {
513             push @args, 'INSTALLDIRS=perl', 'INSTALLMAN1DIR=none',
514                 'INSTALLMAN3DIR=none';
515         }
516         push @args, @$pass_through;
517         _quote_args(\@args) if IS_VMS;
518         print join(' ', $perl, @args), "\n" if $verbose;
519         my $code = do {
520            local $ENV{PERL_MM_USE_DEFAULT} = 1;
521             system $perl, @args;
522         };
523         if($code != 0){
524             #make sure next build attempt/run of make_ext.pl doesn't succeed
525             _unlink($makefile);
526             die "Unsuccessful Makefile.PL($ext_dir): code=$code";
527         }
528
529         # Right. The reason for this little hack is that we're sitting inside
530         # a program run by ./miniperl, but there are tasks we need to perform
531         # when the 'realclean', 'distclean' or 'veryclean' targets are run.
532         # Unfortunately, they can be run *after* 'clean', which deletes
533         # ./miniperl
534         # So we do our best to leave a set of instructions identical to what
535         # we would do if we are run directly as 'realclean' etc
536         # Whilst we're perfect, unfortunately the targets we call are not, as
537         # some of them rely on a $(PERL) for their own distclean targets.
538         # But this always used to be a problem with the old /bin/sh version of
539         # this.
540         if (IS_UNIX) {
541             foreach my $clean_target ('realclean', 'veryclean') {
542                 fallback_cleanup($return_dir, $clean_target, <<"EOS");
543 cd $ext_dir
544 if test ! -f Makefile -a -f Makefile.old; then
545     echo "Note: Using Makefile.old"
546     make -f Makefile.old $clean_target MAKE='@make' @pass_through
547 else
548     if test ! -f Makefile ; then
549         echo "Warning: No Makefile!"
550     fi
551     @make $clean_target MAKE='@make' @pass_through
552 fi
553 cd $return_dir
554 EOS
555             }
556         }
557     }
558
559     if (not -f $makefile) {
560         print "Warning: No Makefile!\n";
561     }
562
563     if (IS_VMS) {
564         _quote_args($pass_through);
565         @$pass_through = (
566                           "/DESCRIPTION=$makefile",
567                           '/MACRO=(' . join(',',@$pass_through) . ')'
568                          );
569     }
570
571     my @targ = ($target, @$pass_through);
572     print "Making $target in $ext_dir\n@make @targ\n" if $verbose;
573     local $ENV{PERL_INSTALL_QUIET} = 1;
574     my $code = system(@make, @targ);
575     if($code >> 8 != 0){ # probably cleaned itself, try again once more time
576         $code = system(@make, @targ);
577     }
578     die "Unsuccessful make($ext_dir): code=$code" if $code != 0;
579
580     chdir $return_dir || die "Cannot cd to $return_dir: $!";
581 }
582
583 sub _quote_args {
584     my $args = shift; # must be array reference
585
586     # Do not quote qualifiers that begin with '/'.
587     map { if (!/^\//) {
588           $_ =~ s/\"/""/g;     # escape C<"> by doubling
589           $_ = q(").$_.q(");
590         }
591     } @{$args}
592     ;
593 }
594
595 #guarentee that a file is deleted or die, void _unlink($filename)
596 #xxx replace with _unlink_or_rename from EU::Install?
597 sub _unlink {
598     1 while unlink $_[0];
599     my $err = $!;
600     die "Can't unlink $_[0]: $err" if -f $_[0];
601 }
602
603 # Figure out if this extension is simple enough that it would only use
604 # ExtUtils::MakeMaker's pm_to_blib target. If we're confident that it would,
605 # then do all the work ourselves (returning an empty list), else return the
606 # name of a file that we identified as beyond our ability to handle.
607 #
608 # While this is clearly quite a bit more work than just letting
609 # ExtUtils::MakeMaker do it, and effectively is some code duplication, the time
610 # savings are impressive.
611
612 sub just_pm_to_blib {
613     my ($target, $ext_dir, $mname, $return_dir) = @_;
614     my ($has_lib, $has_top, $has_topdir);
615     my ($last) = $mname =~ /([^:]+)$/;
616     my ($first) = $mname =~ /^([^:]+)/;
617
618     my $pm_to_blib = IS_VMS ? 'pm_to_blib.ts' : 'pm_to_blib';
619     my $silent = defined $ENV{MAKEFLAGS} && $ENV{MAKEFLAGS} =~ /\b(s|silent|quiet)\b/;
620
621     foreach my $leaf (<*>) {
622         if (-d $leaf) {
623             $leaf =~ s/\.DIR\z//i
624                 if IS_VMS;
625             next if $leaf =~ /\A(?:\.|\.\.|t|demo)\z/;
626             if ($leaf eq 'lib') {
627                 ++$has_lib;
628                 next;
629             }
630             if ($leaf eq $first) {
631                 ++$has_topdir;
632                 next;
633             }
634         }
635         return $leaf
636             unless -f _;
637         $leaf =~ s/\.\z//
638             if IS_VMS;
639         # Makefile.PL is "safe" to ignore because we will only be called for
640         # directories that hold a Makefile.PL if they are in the exception list.
641         next
642             if $leaf =~ /\A(ChangeLog
643                             |Changes
644                             |LICENSE
645                             |Makefile\.PL
646                             |MANIFEST
647                             |META\.yml
648                             |\Q$pm_to_blib\E
649                             |README
650                             |README\.patching
651                             |README\.release
652                             )\z/xi; # /i to deal with case munging systems.
653         if ($leaf eq "$last.pm") {
654             ++$has_top;
655             next;
656         }
657         return $leaf;
658     }
659     return 'no lib/'
660         unless $has_lib || $has_top;
661     die "Inconsistent module $mname has both lib/ and $first/"
662         if $has_lib && $has_topdir;
663
664     print "\nRunning pm_to_blib for $ext_dir directly\n"
665       unless $silent;
666
667     my %pm;
668     if ($has_top) {
669         my $to = $mname =~ s!::!/!gr;
670         $pm{"$last.pm"} = "../../lib/$to.pm";
671     }
672     if ($has_lib || $has_topdir) {
673         # strictly ExtUtils::MakeMaker uses the pm_to_blib target to install
674         # .pm, pod and .pl files. We're just going to do it for .pm and .pod
675         # files, to avoid problems on case munging file systems. Specifically,
676         # _pm.PL which ExtUtils::MakeMaker should run munges to _PM.PL, and
677         # looks a lot like a regular foo.pl (ie FOO.PL)
678         my @found;
679         require File::Find;
680         unless (eval {
681             File::Find::find({
682                               no_chdir => 1,
683                               wanted => sub {
684                                   return if -d $_;
685                                   # Bail out immediately with the problem file:
686                                   die \$_
687                                       unless -f _;
688                                   die \$_
689                                       unless /\A[^.]+\.(?:pm|pod)\z/i;
690                                   push @found, $_;
691                               }
692                              }, $has_lib ? 'lib' : $first);
693             1;
694         }) {
695             # Problem files aren't really errors:
696             return ${$@}
697                 if ref $@ eq 'SCALAR';
698             # But anything else is:
699             die $@;
700         }
701         if ($has_lib) {
702             $pm{$_} = "../../$_"
703                 foreach @found;
704         } else {
705             $pm{$_} = "../../lib/$_"
706                 foreach @found;
707         }
708     }
709     # This is running under miniperl, so no autodie
710     if ($target eq 'all') {
711         local $ENV{PERL_INSTALL_QUIET} = 1;
712         require ExtUtils::Install;
713         ExtUtils::Install::pm_to_blib(\%pm, '../../lib/auto');
714         open my $fh, '>', $pm_to_blib
715             or die "Can't open '$pm_to_blib': $!";
716         print $fh "$0 has handled pm_to_blib directly\n";
717         close $fh
718             or die "Can't close '$pm_to_blib': $!";
719         if (IS_UNIX) {
720             # Fake the fallback cleanup
721             my $fallback
722                 = join '', map {s!^\.\./\.\./!!; "rm -f $_\n"} sort values %pm;
723             foreach my $clean_target ('realclean', 'veryclean') {
724                 fallback_cleanup($return_dir, $clean_target, $fallback);
725             }
726         }
727     } else {
728         # A clean target.
729         # For now, make the targets behave the same way as ExtUtils::MakeMaker
730         # does
731         _unlink($pm_to_blib);
732         unless ($target eq 'clean') {
733             # but cheat a bit, by relying on the top level Makefile clean target
734             # to take out our directory lib/auto/...
735             # (which it has to deal with, as cpan/foo/bar creates
736             # lib/auto/foo/bar, but the EU::MM rule will only
737             # rmdir lib/auto/foo/bar, leaving lib/auto/foo
738             _unlink($_)
739                 foreach sort values %pm;
740         }
741     }
742     return;
743 }
744
745 sub fallback_cleanup {
746     my ($dir, $clean_target, $contents) = @_;
747     my $file = "$dir/$clean_target.sh";
748     open my $fh, '>>', $file or die "open $file: $!";
749     # Quite possible that we're being run in parallel here.
750     # Can't use Fcntl this early to get the LOCK_EX
751     flock $fh, 2 or warn "flock $file: $!";
752     print $fh $contents or die "print $file: $!";
753     close $fh or die "close $file: $!";
754 }