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