This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Introduce EXAMPLES section of documentation
[perl5.git] / Porting / bisect-runner.pl
1 #!/usr/bin/perl -w
2 use strict;
3
4 use Getopt::Long qw(:config bundling no_auto_abbrev);
5 use Pod::Usage;
6 use Config;
7 use File::Temp qw(tempdir);
8 use File::Spec;
9
10 my @targets
11     = qw(none config.sh config.h miniperl lib/Config.pm Fcntl perl test_prep);
12
13 my %options =
14     (
15      'expect-pass' => 1,
16      clean => 1, # mostly for debugging this
17     );
18
19 # We accept #!./miniperl and #!./perl
20 # We don't accept #!miniperl and #!perl as their intent is ambiguous
21 my $run_with_our_perl = qr{\A#!(\./(?:mini)?perl)\b};
22
23 my $linux64 = `uname -sm` eq "Linux x86_64\n" ? '64' : '';
24
25 my @paths;
26
27 if ($^O eq 'linux') {
28     # This is the search logic for a multi-arch library layout
29     # added to linux.sh in commits 40f026236b9959b7 and dcffd848632af2c7.
30     my $gcc = -x '/usr/bin/gcc' ? '/usr/bin/gcc' : 'gcc';
31
32     foreach (`$gcc -print-search-dirs`) {
33         next unless /^libraries: =(.*)/;
34         foreach (split ':', $1) {
35             next if m/gcc/;
36             next unless -d $_;
37             s!/$!!;
38             push @paths, $_;
39         }
40     }
41     push @paths, map {$_ . $linux64} qw(/usr/local/lib /lib /usr/lib)
42         if $linux64;
43 }
44
45 my %defines =
46     (
47      usedevel => '',
48      optimize => '-g',
49      ld => 'cc',
50      (@paths ? (libpth => \@paths) : ()),
51     );
52
53 # Needed for the 'ignore_versioned_solibs' emulation below.
54 push @paths, qw(/usr/local/lib /lib /usr/lib)
55         unless $linux64;
56
57 unless(GetOptions(\%options,
58                   'target=s', 'make=s', 'jobs|j=i', 'crash', 'expect-pass=i',
59                   'expect-fail' => sub { $options{'expect-pass'} = 0; },
60                   'clean!', 'one-liner|e=s@', 'c', 'l', 'w', 'match=s',
61                   'no-match=s' => sub {
62                       $options{match} = $_[1];
63                       $options{'expect-pass'} = 0;
64                   },
65                   'force-manifest', 'force-regen', 'setpgrp!', 'timeout=i',
66                   'test-build', 'validate',
67                   'all-fixups', 'early-fixup=s@', 'late-fixup=s@', 'valgrind',
68                   'check-args', 'check-shebang!', 'usage|help|?', 'gold=s',
69                   'module=s', 'with-module=s', 'cpan-config-dir=s',
70                   'test-module=s', 'no-module-tests',
71                   'A=s@',
72                   'D=s@' => sub {
73                       my (undef, $val) = @_;
74                       if ($val =~ /\A([^=]+)=(.*)/s) {
75                           $defines{$1} = length $2 ? $2 : "\0";
76                       } else {
77                           $defines{$val} = '';
78                       }
79                   },
80                   'U=s@' => sub {
81                       $defines{$_[1]} = undef;
82                   },
83                  )) {
84     pod2usage(exitval => 255, verbose => 1);
85 }
86
87 my ($target, $match) = @options{qw(target match)};
88
89 @ARGV = ('sh', '-c', 'cd t && ./perl TEST base/*.t')
90     if $options{validate} && !@ARGV;
91
92 pod2usage(exitval => 0, verbose => 2) if $options{usage};
93
94 # This needs to be done before the next arguments check, as it's populating
95 # @ARGV
96 if (defined $target && $target =~ /\.t\z/) {
97     # t/TEST don't have a reliable way to run the test script under valgrind
98     # The $ENV{VALGRIND} code was only added after v5.8.0, and is more
99     # geared to logging than to exiting on failure if errors are found.
100     # I guess one could fudge things by replacing the symlink t/perl with a
101     # wrapper script which invokes valgrind, but leave doing that until
102     # someone needs it. (If that's you, then patches welcome.)
103     foreach (qw(valgrind match validate test-build one-liner)) {
104         die_255("$0: Test-case targets can't be run with --$_")
105             if $options{$_};
106     }
107     die_255("$0: Test-case targets can't be combined with an explicit test")
108         if @ARGV;
109
110     # Needing this unless is a smell suggesting that this implementation of
111     # test-case targets is not really in the right place.
112     unless ($options{'check-args'}) {
113         # The top level sanity tests refuse to start or end a test run at a
114         # revision which skips, hence this test ensures reasonable sanity at
115         # automatically picking a suitable start point for both normal operation
116         # and --expect-fail
117         skip("Test case $target is not a readable file")
118             unless -f $target && -r _;
119     }
120
121     # t/TEST runs from and takes pathnames relative to t/, so need to strip
122     # out a leading t, or add ../ otherwise
123     unless ($target =~ s!\At/!!) {
124         $target = "../$target";
125     }
126     @ARGV = ('sh', '-c', "cd t && ./perl TEST " . quotemeta $target);
127     $target = 'test_prep';
128 }
129
130 pod2usage(exitval => 255, verbose => 1)
131     unless @ARGV || $match || $options{'test-build'}
132         || defined $options{'one-liner'} || defined $options{module}
133         || defined $options{'test-module'};
134 pod2usage(exitval => 255, verbose => 1)
135     if !$options{'one-liner'} && ($options{l} || $options{w});
136 if ($options{'no-module-tests'} && $options{module}) {
137     print STDERR "--module and --no-module-tests are exclusive.\n\n";
138     pod2usage(exitval => 255, verbose => 1)
139 }
140 if ($options{'no-module-tests'} && $options{'test-module'}) {
141     print STDERR "--test-module and --no-module-tests are exclusive.\n\n";
142     pod2usage(exitval => 255, verbose => 1)
143 }
144 if ($options{module} && $options{'test-module'}) {
145     print STDERR "--module and --test-module are exclusive.\n\n";
146     pod2usage(exitval => 255, verbose => 1)
147 }
148
149 check_shebang($ARGV[0])
150     if $options{'check-shebang'} && @ARGV && !$options{match};
151
152 exit 0 if $options{'check-args'};
153
154 =head1 NAME
155
156 bisect.pl - use git bisect to pinpoint changes
157
158 =head1 SYNOPSIS
159
160  # When did this become an error?
161  .../Porting/bisect.pl -e 'my $a := 2;'
162  # When did this stop being an error?
163  .../Porting/bisect.pl --expect-fail -e '1 // 2'
164  # When did this test start failing?
165  .../Porting/bisect.pl --target t/op/sort.t
166  # When were all lines matching this pattern removed from all files?
167  .../Porting/bisect.pl --match '\b(?:PL_)hash_seed_set\b'
168  # When was some line matching this pattern added to some file?
169  .../Porting/bisect.pl --expect-fail --match '\buseithreads\b'
170  # When did this test program stop exiting 0?
171  .../Porting/bisect.pl -- ./perl -Ilib ../test_prog.pl
172  # When did this test program start crashing (any signal or coredump)?
173  .../Porting/bisect.pl --crash -- ./perl -Ilib ../test_prog.pl
174  # When did this first become valid syntax?
175  .../Porting/bisect.pl --target=miniperl --end=v5.10.0 \
176       --expect-fail -e 'my $a := 2;'
177  # What was the last revision to build with these options?
178  .../Porting/bisect.pl --test-build -Dd_dosuid
179  # When did this test program start generating errors from valgrind?
180  .../Porting/bisect.pl --valgrind ../test_prog.pl
181  # When did these cpan modules start failing to compile/pass tests?
182  .../Porting/bisect.pl --module=autobox,Moose
183  # When did this code stop working in blead with these modules?
184  .../Porting/bisect.pl --with-module=Moose,Moo -e 'use Moose; 1;'
185  # Like the above 2 but with custom CPAN::MyConfig
186  .../Porting/bisect.pl --module=Moo --cpan-config-dir=/home/blah/custom/
187
188 =head1 DESCRIPTION
189
190 Together F<bisect.pl> and F<bisect-runner.pl> attempt to automate the use
191 of C<git bisect> as much as possible. With one command (and no other files)
192 it's easy to find out
193
194 =over 4
195
196 =item *
197
198 Which commit caused this example code to break?
199
200 =item *
201
202 Which commit caused this example code to start working?
203
204 =item *
205
206 Which commit added the first file to match this regex?
207
208 =item *
209
210 Which commit removed the last file to match this regex?
211
212 =back
213
214 usually without needing to know which versions of perl to use as start and
215 end revisions.
216
217 By default F<bisect.pl> will process all options, then use the rest of the
218 command line as arguments to list C<system> to run a test case. By default,
219 the test case should pass (exit with 0) on earlier perls, and fail (exit
220 non-zero) on I<blead>. F<bisect.pl> will use F<bisect-runner.pl> to find the
221 earliest stable perl version on which the test case passes, check that it
222 fails on blead, and then use F<bisect-runner.pl> with C<git bisect run> to
223 find the commit which caused the failure.
224
225 Many of perl's own test scripts exit 0 even if their TAP reports test
226 failures, and some need particular setup (such as running from the right
227 directory, or adding C<-T> to the command line). Hence if you want to bisect
228 a test script, you can specify it with the I<--target> option, and it will
229 be invoked using F<t/TEST> which performs all the setup, and exits non-zero
230 if the TAP reports failures. This works for any file ending C<.t>, so you can
231 use it with a file outside of the working checkout, for example to test a
232 particular version of a test script, as a path inside the repository will
233 (of course) be testing the version of the script checked out for the current
234 revision, which may be too early to have the test you are interested in.
235
236 Because the test case is the complete argument to C<system>, it is easy to
237 run something other than the F<perl> built, if necessary. If you need to run
238 the perl built, you'll probably need to invoke it as C<./perl -Ilib ...>.
239 As a special case, if the first argument of the test case is a readable file
240 (whether executable or not), matching C<qr{\A#!./(?:mini)?perl\b}> then it
241 will have C<./perl> <-Ilib> (or C<./miniperl>) prepended to it.
242
243 You need a clean checkout to run a bisect. You can use the checkout
244 containing F<Porting/bisect.pl> if you wish - in this case
245 F<Porting/bisect.pl> will copy F<Porting/bisect-runner.pl> to a temporary
246 file generated by C<File::Temp::tempfile()>. If doing this, beware that when
247 the bisect ends (or you abort it) then your checkout is no longer at
248 C<blead>, so you will need to C<git checkout blead> before restarting, to
249 get the current version of F<Porting/bisect.pl> again. It's often easier
250 either to copy F<Porting/bisect.pl> and F<Porting/bisect-runner.pl> to
251 another directory (I<e.g.> F<~/bin>, if you have one), or to create a second
252 git repository for running bisect. To create a second local repository, if
253 your working checkout is called F<perl>, a simple solution is to make a
254 local clone, and run from that. I<i.e.>:
255
256     cd ..
257     git clone perl perl2
258     cd perl2
259     ../perl/Porting/bisect.pl ...
260
261 By default, F<bisect-runner.pl> will automatically disable the build of
262 L<DB_File> for commits earlier than ccb44e3bf3be2c30, as it's not practical
263 to patch DB_File 1.70 and earlier to build with current Berkeley DB headers.
264 (ccb44e3bf3be2c30 was in September 1999, between 5.005_62 and 5.005_63.)
265 If your F<db.h> is old enough you can override this with C<-Unoextensions>.
266
267 =head1 OPTIONS
268
269 =over 4
270
271 =item *
272
273 --start I<commit-ish>
274
275 Earliest revision to test, as a I<commit-ish> (a tag, commit or anything
276 else C<git> understands as a revision). If not specified, F<bisect.pl> will
277 search stable .0 perl releases until it finds one where the test case
278 passes. The default is to search from 5.002 to the most recent tagged stable
279 release (v5.18.0 at the time of writing). If F<bisect.pl> detects that the
280 checkout is on a case insensitive file system, it will search from 5.005 to
281 the most recent tagged stable release. Only .0 stable releases are used
282 because these are the only stable releases that are parents of blead, and
283 hence suitable for a bisect run.
284
285 =item *
286
287 --end I<commit-ish>
288
289 Most recent revision to test, as a I<commit-ish>. If not specified, defaults
290 to I<blead>.
291
292 =item *
293
294 --target I<target>
295
296 F<Makefile> target (or equivalent) needed, to run the test case. If specified,
297 this should be one of
298
299 =over 4
300
301 =item *
302
303 I<none>
304
305 Don't build anything - just run the user test case against a clean checkout.
306 Using this gives a couple of features that a plain C<git bisect run> can't
307 offer - automatic start revision detection, and test case C<--timeout>.
308
309 =item *
310
311 I<config.sh>
312
313 Just run F<./Configure>
314
315 =item *
316
317 I<config.h>
318
319 Run the various F<*.SH> files to generate F<Makefile>, F<config.h>, I<etc>.
320
321 =item *
322
323 I<miniperl>
324
325 Build F<miniperl>.
326
327 =item *
328
329 I<lib/Config.pm>
330
331 Use F<miniperl> to build F<lib/Config.pm>
332
333 =item *
334
335 I<Fcntl>
336
337 Build F<lib/auto/Fcntl/Fnctl.so> (strictly, C<.$Config{so}>). As L<Fcntl>
338 is simple XS module present since 5.000, this provides a fast test of
339 whether XS modules can be built. Note, XS modules are built by F<miniperl>,
340 hence this target will not build F<perl>.
341
342 =item *
343
344 I<perl>
345
346 Build F<perl>. This also builds pure-Perl modules in F<cpan>, F<dist> and
347 F<ext>. XS modules (such as L<Fcntl>) are not built.
348
349 =item *
350
351 I<test_prep>
352
353 Build everything needed to run the tests. This is the default if we're
354 running test code, but is time consuming, as it means building all
355 XS modules. For older F<Makefile>s, the previous name of C<test-prep>
356 is automatically substituted. For very old F<Makefile>s, C<make test> is
357 run, as there is no target provided to just get things ready, and for 5.004
358 and earlier the tests run very quickly.
359
360 =item *
361
362 A file ending C<.t>
363
364 Build everything needed to run the tests, and then run this test script using
365 F<t/TEST>. This is actually implemented internally by using the target
366 I<test_prep>, and setting the test case to "sh", "-c", "cd t && ./TEST ..."
367
368 =back
369
370 =item *
371
372 --one-liner 'code to run'
373
374 =item *
375
376 -e 'code to run'
377
378 Example code to run, just like you'd use with C<perl -e>.
379
380 This prepends C<./perl -Ilib -e 'code to run'> to the test case given,
381 or F<./miniperl> if I<target> is C<miniperl>.
382
383 (Usually you'll use C<-e> instead of providing a test case in the
384 non-option arguments to F<bisect.pl>. You can repeat C<-e> on the command
385 line, just like you can with C<perl>)
386
387 C<-E> intentionally isn't supported, as it's an error in 5.8.0 and earlier,
388 which interferes with detecting errors in the example code itself.
389
390 =item *
391
392 -c
393
394 Add C<-c> to the command line, to cause perl to exit after syntax checking.
395
396 =item *
397
398 -l
399
400 Add C<-l> to the command line with C<-e>
401
402 This will automatically append a newline to every output line of your testcase.
403 Note that you can't specify an argument to F<perl>'s C<-l> with this, as it's
404 not feasible to emulate F<perl>'s somewhat quirky switch parsing with
405 L<Getopt::Long>. If you need the full flexibility of C<-l>, you need to write
406 a full test case, instead of using C<bisect.pl>'s C<-e> shortcut.
407
408 =item *
409
410 -w
411
412 Add C<-w> to the command line with C<-e>
413
414 It's not valid to pass C<-c>,  C<-l> or C<-w> to C<bisect.pl> unless you are
415 also using C<-e>
416
417 =item *
418
419 --expect-fail
420
421 The test case should fail for the I<start> revision, and pass for the I<end>
422 revision. The bisect run will find the first commit where it passes.
423
424 =item *
425
426 --crash
427
428 Treat any non-crash as success, any crash as failure. (Crashing defined
429 as exiting with a signal or a core dump.)
430
431 =item *
432
433 -D I<config_arg=value>
434
435 =item *
436
437 -U I<config_arg>
438
439 =item *
440
441 -A I<config_arg=value>
442
443 Arguments (C<-A>, C<-D>, C<-U>) to pass to F<Configure>.  The C<-D>, C<-A> and
444 C<-U> switches should be spelled as if you were normally giving them to
445 F<./Configure>.  For example,
446
447     -Dnoextensions=Encode
448     -Uusedevel
449     -Accflags=-DNO_MATHOMS
450
451 Repeated C<-A> arguments are passed
452 through as is. C<-D> and C<-U> are processed in order, and override
453 previous settings for the same parameter. F<bisect-runner.pl> emulates
454 C<-Dnoextensions> when F<Configure> itself does not provide it, as it's
455 often very useful to be able to disable some XS extensions.
456
457 =item *
458
459 --make I<make-prog>
460
461 The C<make> command to use. If this not set, F<make> is used. If this is
462 set, it also adds a C<-Dmake=...> else some recursive make invocations
463 in extensions may fail. Typically one would use this as C<--make gmake>
464 to use F<gmake> in place of the system F<make>.
465
466 =item *
467
468 --jobs I<jobs>
469
470 =item *
471
472 -j I<jobs>
473
474 Number of C<make> jobs to run in parallel. A value of 0 suppresses
475 parallelism. If F</proc/cpuinfo> exists and can be parsed, or F</sbin/sysctl>
476 exists and reports C<hw.ncpu>, or F</usr/bin/getconf> exists and reports
477 C<_NPROCESSORS_ONLN> defaults to 1 + I<number of CPUs>. On HP-UX with the
478 system make defaults to 0, otherwise defaults to 2.
479
480 =item *
481
482 --match pattern
483
484 =item *
485
486 --no-match pattern
487
488 Instead of running a test program to determine I<pass> or I<fail>,
489 C<--match> will pass if the given regex matches, and hence search for the
490 commit that removes the last matching file. C<--no-match> inverts the test,
491 to search for the first commit that adds files that match.
492
493 The remaining command line arguments are treated as glob patterns for files
494 to match against. If none are specified, then they default as follows:
495
496 =over 4
497
498 =item *
499
500 If no I<target> is specified, the match is against all files in the
501 repository (which is fast).
502
503 =item *
504
505 If a I<target> is specified, that target is built, and the match is against
506 only the built files.
507
508 =back
509
510 Treating the command line arguments as glob patterns should not cause
511 problems, as the perl distribution has never shipped or built files with
512 names that contain characters which are globbing metacharacters.
513
514 Anything which is not a readable file is ignored, instead of generating an
515 error. (If you want an error, run C<grep> or C<ack> as a test case). This
516 permits one to easily search in a file that changed its name. For example:
517
518     .../Porting/bisect.pl --match 'Pod.*Functions' 'pod/buildtoc*'
519
520 C<--no-match ...> is implemented as C<--expect-fail --match ...>
521
522 =item *
523
524 --valgrind
525
526 Run the test program under C<valgrind>. If you need to test for memory
527 errors when parsing invalid programs, the default parser fail exit code of
528 255 will always override C<valgrind>, so try putting the test case invalid
529 code inside a I<string> C<eval>, so that the perl interpreter will exit with 0.
530 (Be sure to check the output of $@, to avoid missing mistakes such as
531 unintended C<eval> failures due to incorrect C<@INC>)
532
533 Specifically, this option prepends C<valgrind> C<--error-exitcode=124> to
534 the command line that runs the testcase, to cause valgrind to exit non-zero
535 if it detects errors, with the assumption that the test program itself
536 always exits with zero. If you require more flexibility than this, either
537 specify your C<valgrind> invocation explicitly as part of the test case, or
538 use a wrapper script to control the command line or massage the exit codes.
539
540 In order for the test program to be seen as a perl script to valgrind
541 (rather than a shell script), the first line must be one of the following
542
543   #!./perl
544   #!./miniperl
545
546 =item *
547
548 --test-build
549
550 Test that the build completes, without running any test case.
551
552 By default, if the build for the desired I<target> fails to complete,
553 F<bisect-runner.pl> reports a I<skip> back to C<git bisect>, the assumption
554 being that one wants to find a commit which changed state "builds && passes"
555 to "builds && fails". If instead one is interested in which commit broke the
556 build (possibly for particular F<Configure> options), use I<--test-build>
557 to treat a build failure as a failure, not a "skip".
558
559 Often this option isn't as useful as it first seems, because I<any> build
560 failure will be reported to C<git bisect> as a failure, not just the failure
561 that you're interested in. Generally, to debug a particular problem, it's
562 more useful to use a I<target> that builds properly at the point of interest,
563 and then a test case that runs C<make>. For example:
564
565     .../Porting/bisect.pl --start=perl-5.000 --end=perl-5.002 \
566         --expect-fail --force-manifest --target=miniperl make perl
567
568 will find the first revision capable of building L<DynaLoader> and then
569 F<perl>, without becoming confused by revisions where F<miniperl> won't
570 even link.
571
572 =item *
573
574 --module module1,module2,...
575
576 Install this (or these) module(s), die when it (the last of those)
577 cannot be updated to the current version.
578
579 Misnomer. the argument can be any argument that can be passed to CPAN
580 shell's install command. B<But>: since we only have the uptodate
581 command to verify that an install has taken place, we are unable to
582 determine success for arguments like
583 MSCHWERN/Test-Simple-1.005000_005.tar.gz.
584
585 In so far, it is not such a misnomer.
586
587 Note that this and I<--with-module> will both require a C<CPAN::MyConfig>.
588 If F<$ENV{HOME}/.cpan/CPAN/MyConfig.pm> does not exist, a CPAN shell will
589 be started up for you so you can configure one. Feel free to let
590 CPAN pick defaults for you. Enter 'quit' when you are done, and
591 then everything should be all set. Alternatively, you may
592 specify a custom C<CPAN::MyConfig> by using I<--cpan-config-dir>.
593
594 Also, if you want to bisect a module that needs a display (like
595 TK) and you don't want random screens appearing and disappearing
596 on your computer while you're working, you can do something like
597 this:
598
599 In a terminal:
600
601  $ while true; do date ; if ! ps auxww | grep -v grep \
602    | grep -q Xvfb; then Xvfb :121 & fi; echo -n 'sleeping 60 '; \
603    sleep 60; done
604
605 And then:
606
607   DISPLAY=":121" .../Porting/bisect.pl --module=TK
608
609 (Some display alternatives are vncserver and Xnest.)
610
611 =item *
612
613 --with-module module1,module2,...
614
615 Like I<--module> above, except this simply installs the requested
616 modules and they can then be used in other tests.
617
618 For example:
619
620   .../Porting/bisect.pl --with-module=Moose -e 'use Moose; ...'
621
622 =item *
623
624 --no-module-tests
625
626 Use in conjunction with I<--with-module> to install the modules without
627 running their tests. This can be a big time saver.
628
629 For example:
630
631   .../Porting/bisect.pl --with-module=Moose --no-module-tests \
632        -e 'use Moose; ...'
633
634 =item *
635
636 --test-module
637
638 This is like I<--module>, but just runs the module's tests, instead of
639 installing it.
640
641 WARNING: This is a somewhat experimental option, known to work on recent
642 CPAN shell versions.  If you use this option and strange things happen,
643 please report them.
644
645 Usually, you can just use I<--module>, but if you are getting inconsistent
646 installation failures and you just want to see when the tests started
647 failing, you might find this option useful.
648
649 =item *
650
651 --cpan-config-dir /home/blah/custom
652
653 If defined, this will cause L<CPAN> to look for F<CPAN/MyConfig.pm> inside of
654 the specified directory, instead of using the default config of
655 F<$ENV{HOME}/.cpan/>.
656
657 If no default config exists, a L<CPAN> shell will be fired up for you to
658 configure things. Letting L<CPAN> automatically configure things for you
659 should work well enough. You probably want to choose I<manual> instead of
660 I<local::lib> if it asks. When you're finished with configuration, just
661 type I<q> and hit I<ENTER> and the bisect should continue.
662
663 =item *
664
665 --force-manifest
666
667 By default, a build will "skip" if any files listed in F<MANIFEST> are not
668 present. Usually this is useful, as it avoids false-failures. However, there
669 are some long ranges of commits where listed files are missing, which can
670 cause a bisect to abort because all that remain are skipped revisions.
671
672 In these cases, particularly if the test case uses F<miniperl> and no modules,
673 it may be more useful to force the build to continue, even if files
674 F<MANIFEST> are missing.
675
676 =item *
677
678 --force-regen
679
680 Run C<make regen_headers> before building F<miniperl>. This may fix a build
681 that otherwise would skip because the generated headers at that revision
682 are stale. It's not the default because it conceals this error in the true
683 state of such revisions.
684
685 =item *
686
687 --expect-pass [0|1]
688
689 C<--expect-pass=0> is equivalent to C<--expect-fail>. I<1> is the default.
690
691 =item *
692
693 --timeout I<seconds>
694
695 Run the testcase with the given timeout. If this is exceeded, kill it (and
696 by default all its children), and treat it as a failure.
697
698 =item *
699
700 --setpgrp
701
702 Run the testcase in its own process group. Specifically, call C<setpgrp 0, 0>
703 just before C<exec>-ing the user testcase. The default is not to set the
704 process group, unless a timeout is used.
705
706 =item *
707
708 --all-fixups
709
710 F<bisect-runner.pl> will minimally patch various files on a platform and
711 version dependent basis to get the build to complete. Normally it defers
712 doing this as long as possible - C<.SH> files aren't patched until after
713 F<Configure> is run, and C<C> and C<XS> code isn't patched until after
714 F<miniperl> is built. If C<--all-fixups> is specified, all the fixups are
715 done before running C<Configure>. In rare cases adding this may cause a
716 bisect to abort, because an inapplicable patch or other fixup is attempted
717 for a revision which would usually have already I<skip>ped. If this happens,
718 please report it as a bug, giving the OS and problem revision.
719
720 =item *
721
722 --early-fixup file
723
724 =item *
725
726 --late-fixup file
727
728 Specify a file containing a patch or other fixup for the source code. The
729 action to take depends on the first line of the fixup file
730
731 =over 4
732
733 =item *
734
735 C<#!perl>
736
737 If the first line starts C<#!perl> then the file is run using C<$^X>
738
739 =item *
740
741 C<#!/absolute/path>
742
743 If a shebang line is present the file is executed using C<system>
744
745 =item *
746
747 C<I<filename> =~ /I<pattern>/>
748
749 =item *
750
751 C<I<filename> !~ /I<pattern>/>
752
753 If I<filename> does not exist then the fixup file's contents are ignored.
754 Otherwise, for C<=~>, if it contains a line matching I<pattern>, then the
755 file is fed to C<patch -p1> on standard input. For C<=~>, the patch is
756 applied if no lines match the pattern.
757
758 As the empty pattern in Perl is a special case (it matches the most recent
759 successful match) which is not useful here, the treatment of an empty pattern
760 is special-cased. C<I<filename> =~ //> applies the patch if filename is
761 present. C<I<filename> !~ //> applies the patch if filename missing. This
762 makes it easy to unconditionally apply patches to files, and to use a patch
763 as a way of creating a new file.
764
765 =item *
766
767 Otherwise, the file is assumed to be a patch, and always applied.
768
769 =back
770
771 I<early-fixup>s are applied before F<./Configure> is run. I<late-fixup>s are
772 applied just after F<./Configure> is run.
773
774 These options can be specified more than once. I<file> is actually expanded
775 as a glob pattern. Globs that do not match are errors, as are missing files.
776
777 =item *
778
779 --no-clean
780
781 Tell F<bisect-runner.pl> not to clean up after the build. This allows one
782 to use F<bisect-runner.pl> to build the current particular perl revision for
783 interactive testing, or for debugging F<bisect-runner.pl>.
784
785 Passing this to F<bisect.pl> will likely cause the bisect to fail badly.
786
787 =item *
788
789 --validate
790
791 Test that all stable (.0) revisions can be built. By default, attempts to
792 build I<blead>, then tagged stable releases in reverse order down to
793 I<perl-5.002> (or I<perl5.005> on a case insensitive file system). Stops at
794 the first failure, without cleaning the checkout. Use I<--start> to specify
795 the earliest revision to test, I<--end> to specify the most recent. Useful
796 for validating a new OS/CPU/compiler combination. For example
797
798     ../perl/Porting/bisect.pl --validate -le 'print "Hello from $]"'
799
800 If no testcase is specified, the default is to use F<t/TEST> to run
801 F<t/base/*.t>
802
803 =item *
804
805 --check-args
806
807 Validate the options and arguments, and exit silently if they are valid.
808
809 =item *
810
811 --check-shebang
812
813 Validate that the test case isn't an executable file with a
814 C<#!/usr/bin/perl> line (or similar). As F<bisect-runner.pl> does B<not>
815 automatically prepend C<./perl> to the test case, a I<#!> line specifying an
816 external F<perl> binary will cause the test case to always run with I<that>
817 F<perl>, not the F<perl> built by the bisect runner. Likely this is not what
818 you wanted. If your test case is actually a wrapper script to run other
819 commands, you should run it with an explicit interpreter, to be clear. For
820 example, instead of C<../perl/Porting/bisect.pl ~/test/testcase.pl> you'd
821 run C<../perl/Porting/bisect.pl /usr/bin/perl ~/test/testcase.pl>
822
823 =item *
824
825 --gold
826
827 Revision to use when checking out known-good recent versions of files,
828 such as F<makedepend.SH>. F<bisect-runner.pl> defaults this to I<blead>,
829 but F<bisect.pl> will default it to the most recent stable release.
830
831 =item *
832
833 --usage
834
835 =item *
836
837 --help
838
839 =item *
840
841 -?
842
843 Display the usage information and exit.
844
845 =back
846
847 =head1 EXAMPLES
848
849 =head2 Code has started to crash under C<miniperl>
850
851 =over 4
852
853 =item * Problem
854
855 Under C<make minitest> (but not under C<make test_harness>), F<t/re/pat.t> was
856 failing to compile.  What was the first commit at which that compilation
857 failure could be observed?
858
859 =item * Solution
860
861 Extract code from the test file at the point where C<./miniperl -Ilib -c> was
862 showing a compilation failure.  Use that in bisection with the C<miniperl>
863 target.
864
865     .../Porting/bisect.pl --target=miniperl --start=2ec4590e \
866         -e 'q|ace| =~ /c(?=.$)/; $#{^CAPTURE} == -1); exit 0;'
867
868 =item * Reference
869
870 L<GH issue 17293|https://github.com/Perl/perl5/issues/17293>
871
872 =back
873
874 =head2 Blead breaks CPAN on threaded builds only
875
876 =over 4
877
878 =item * Problem
879
880 Tests in CPAN module XML::Parser's test suite had begun to fail when tested
881 against blead in threaded builds only.
882
883 =item * Solution
884
885 Provide F<Configure>-style switch to bisection program.  Straightforward use
886 of the C<--module> switch.
887
888     .../Porting/bisect.pl -Duseithreads \
889         --start=6256cf2c \
890         --end=f6f85064 \
891         --module=XML::Parser
892
893 =item * Reference
894
895 L<GH issue 16918|https://github.com/Perl/perl5/issues/16918>
896
897 =back
898
899 =head2 Point in time where code started to segfault is unknown
900
901 =over 4
902
903 =item * Problem
904
905 User submitted code sample which when run caused F<perl> to segfault, but did
906 not claim that this was a recent change.
907
908 =item * Solution
909
910 Used locally installed production releases of perl (previously created by
911 F<perlbrew>) to identify the first production release at which the code would
912 not compile.  Used that information to shorten bisection time.
913
914     .../perl Porting/bisect.pl \
915         --start=v5.14.4 \
916         --end=v5.16.3 \
917         --crash -- ./perl -Ilib /tmp/gh-17333-map.pl
918
919     $ cat gh-17333-map.pl
920
921     @N = 1..5;
922     map { pop @N } @N;
923
924 =item * Reference
925
926 L<GH issue 17333|https://github.com/Perl/perl5/issues/17333>
927
928 =back
929
930 =head2 When did perl start failing to build on a certain platform using C<g++> as the C-compiler?
931
932 =over 4
933
934 =item * Problem
935
936 On NetBSD-8.0, C<perl> had never been smoke-tested using C<g++> as the
937 C-compiler.  Once this was done, it became evident that changes in that
938 version of the operating system's code were incompatible with some C<perl>
939 source written long before that OS version was ever released!
940
941 =item * Solution
942
943 Bisection range was first narrowed using existing builds at release tags.
944 Then, bisection specified the C-compiler via C<Configure>-style switch and
945 used C<--test-build> to identify the commit which "broke" the build.
946
947     .../perl Porting/bisect.pl \
948         -Dcc=g++ \
949         --test-build \
950         --start=v5.21.6 \
951         --end=v5.21.7
952
953 Then, problem was discussed with knowledgeable NetBSD user.
954
955 =item * Reference
956
957 L<GH issue 17381|https://github.com/Perl/perl5/issues/17381>
958
959 =back
960
961 =cut
962
963 # Ensure we always exit with 255, to cause git bisect to abort.
964 sub croak_255 {
965     my $message = join '', @_;
966     if ($message =~ /\n\z/) {
967         print STDERR $message;
968     } else {
969         my (undef, $file, $line) = caller 1;
970         print STDERR "@_ at $file line $line\n";
971     }
972     exit 255;
973 }
974
975 sub die_255 {
976     croak_255(@_);
977 }
978
979 die_255("$0: Can't build $target")
980     if defined $target && !grep {@targets} $target;
981
982 foreach my $phase (qw(early late)) {
983     next unless $options{"$phase-fixup"};
984     my $bail_out;
985     require File::Glob;
986     my @expanded;
987     foreach my $glob (@{$options{"$phase-fixup"}}) {
988         my @got = File::Glob::bsd_glob($glob);
989         push @expanded, @got ? @got : $glob;
990     }
991     @expanded = sort @expanded;
992     $options{"$phase-fixup"} = \@expanded;
993     foreach (@expanded) {
994         unless (-f $_) {
995             print STDERR "$phase-fixup '$_' is not a readable file\n";
996             ++$bail_out;
997         }
998     }
999     exit 255 if $bail_out;
1000 }
1001
1002 unless (exists $defines{cc}) {
1003     # If it fails, the heuristic of 63f9ec3008baf7d6 is noisy, and hence
1004     # confusing.
1005     # FIXME - really it should be replaced with a proper test of
1006     # "can we build something?" and a helpful diagnostic if we can't.
1007     # For now, simply move it here.
1008     $defines{cc} = (`ccache -V`, $?) ? 'cc' : 'ccache cc';
1009 }
1010
1011 my $j = $options{jobs} ? "-j$options{jobs}" : '';
1012
1013 if (exists $options{make}) {
1014     if (!exists $defines{make}) {
1015         $defines{make} = $options{make};
1016     }
1017 } else {
1018     $options{make} = 'make';
1019 }
1020
1021 # Sadly, however hard we try, I don't think that it will be possible to build
1022 # modules in ext/ on x86_64 Linux before commit e1666bf5602ae794 on 1999/12/29,
1023 # which updated to MakeMaker 3.7, which changed from using a hard coded ld
1024 # in the Makefile to $(LD). On x86_64 Linux the "linker" is gcc.
1025
1026 sub open_or_die {
1027     my $file = shift;
1028     my $mode = @_ ? shift : '<';
1029     open my $fh, $mode, $file or croak_255("Can't open $file: $!");
1030     ${*$fh{SCALAR}} = $file;
1031     return $fh;
1032 }
1033
1034 sub close_or_die {
1035     my $fh = shift;
1036     return if close $fh;
1037     croak_255("Can't close: $!") unless ref $fh eq 'GLOB';
1038     croak_255("Can't close ${*$fh{SCALAR}}: $!");
1039 }
1040
1041 sub system_or_die {
1042     my $command = '</dev/null ' . shift;
1043     system($command) and croak_255("'$command' failed, \$!=$!, \$?=$?");
1044 }
1045
1046 sub run_with_options {
1047     my $options = shift;
1048     my $name = $options->{name};
1049     $name = "@_" unless defined $name;
1050
1051     my $setgrp = $options->{setpgrp};
1052     if ($options->{timeout}) {
1053         # Unless you explicitly disabled it on the commandline, set it:
1054         $setgrp = 1 unless defined $setgrp;
1055     }
1056     my $pid = fork;
1057     die_255("Can't fork: $!") unless defined $pid;
1058     if (!$pid) {
1059         if (exists $options->{stdin}) {
1060             open STDIN, '<', $options->{stdin}
1061               or die "Can't open STDIN from $options->{stdin}: $!";
1062         }
1063         if ($setgrp) {
1064             setpgrp 0, 0
1065                 or die "Can't setpgrp 0, 0: $!";
1066         }
1067         { exec @_ };
1068         die_255("Failed to start $name: $!");
1069     }
1070     my $start;
1071     if ($options->{timeout}) {
1072         require Errno;
1073         require POSIX;
1074         die_255("No POSIX::WNOHANG")
1075             unless &POSIX::WNOHANG;
1076         $start = time;
1077         $SIG{ALRM} = sub {
1078             my $victim = $setgrp ? -$pid : $pid;
1079             my $delay = 1;
1080             kill 'TERM', $victim;
1081             waitpid(-1, &POSIX::WNOHANG);
1082             while (kill 0, $victim) {
1083                 sleep $delay;
1084                 waitpid(-1, &POSIX::WNOHANG);
1085                 $delay *= 2;
1086                 if ($delay > 8) {
1087                     if (kill 'KILL', $victim) {
1088                         print STDERR "$0: Had to kill 'KILL', $victim\n"
1089                     } elsif (! $!{ESRCH}) {
1090                         print STDERR "$0: kill 'KILL', $victim failed: $!\n";
1091                     }
1092                     last;
1093                 }
1094             }
1095             report_and_exit(0, 'No timeout', 'Timeout', "when running $name");
1096         };
1097         alarm $options->{timeout};
1098     }
1099     waitpid $pid, 0
1100       or die_255("wait for $name, pid $pid failed: $!");
1101     alarm 0;
1102     if ($options->{timeout}) {
1103         my $elapsed = time - $start;
1104         if ($elapsed / $options->{timeout} > 0.8) {
1105             print STDERR "$0: Beware, took $elapsed seconds of $options->{timeout} permitted to run $name\n";
1106         }
1107     }
1108     return $?;
1109 }
1110
1111 sub extract_from_file {
1112     my ($file, $rx, $default) = @_;
1113     my $fh = open_or_die($file);
1114     while (<$fh>) {
1115         my @got = $_ =~ $rx;
1116         return wantarray ? @got : $got[0]
1117             if @got;
1118     }
1119     return $default if defined $default;
1120     return;
1121 }
1122
1123 sub edit_file {
1124     my ($file, $munger) = @_;
1125     local $/;
1126     my $fh = open_or_die($file);
1127     my $orig = <$fh>;
1128     die_255("Can't read $file: $!") unless defined $orig && close $fh;
1129     my $new = $munger->($orig);
1130     return if $new eq $orig;
1131     $fh = open_or_die($file, '>');
1132     print $fh $new or die_255("Can't print to $file: $!");
1133     close_or_die($fh);
1134 }
1135
1136 # AIX supplies a pre-historic patch program, which certainly predates Linux
1137 # and is probably older than NT. It can't cope with unified diffs. Meanwhile,
1138 # it's hard enough to get git diff to output context diffs, let alone git show,
1139 # and nearly all the patches embedded here are unified. So it seems that the
1140 # path of least resistance is to convert unified diffs to context diffs:
1141
1142 sub process_hunk {
1143     my ($from_out, $to_out, $has_from, $has_to, $delete, $add) = @_;
1144     ++$$has_from if $delete;
1145     ++$$has_to if $add;
1146
1147     if ($delete && $add) {
1148         $$from_out .= "! $_\n" foreach @$delete;
1149         $$to_out .= "! $_\n" foreach @$add;
1150     } elsif ($delete) {
1151         $$from_out .= "- $_\n" foreach @$delete;
1152     } elsif ($add) {
1153          $$to_out .= "+ $_\n" foreach @$add;
1154     }
1155 }
1156
1157 # This isn't quite general purpose, as it can't cope with
1158 # '\ No newline at end of file'
1159 sub ud2cd {
1160     my $diff_in = shift;
1161     my $diff_out = '';
1162
1163     # Stuff before the diff
1164     while ($diff_in =~ s/\A(?!\*\*\* )(?!--- )([^\n]*\n?)//ms && length $1) {
1165         $diff_out .= $1;
1166     }
1167
1168     if (!length $diff_in) {
1169         die_255("That didn't seem to be a diff");
1170     }
1171
1172     if ($diff_in =~ /\A\*\*\* /ms) {
1173         warn "Seems to be a context diff already\n";
1174         return $diff_out . $diff_in;
1175     }
1176
1177     # Loop for files
1178  FILE: while (1) {
1179         if ($diff_in =~ s/\A((?:diff |index )[^\n]+\n)//ms) {
1180             $diff_out .= $1;
1181             next;
1182         }
1183         if ($diff_in !~ /\A--- /ms) {
1184             # Stuff after the diff;
1185             return $diff_out . $diff_in;
1186         }
1187         $diff_in =~ s/\A([^\n]+\n?)//ms;
1188         my $line = $1;
1189         die_255("Can't parse '$line'") unless $line =~ s/\A--- /*** /ms;
1190         $diff_out .= $line;
1191         $diff_in =~ s/\A([^\n]+\n?)//ms;
1192         $line = $1;
1193         die_255("Can't parse '$line'") unless $line =~ s/\A\+\+\+ /--- /ms;
1194         $diff_out .= $line;
1195
1196         # Loop for hunks
1197         while (1) {
1198             next FILE
1199                 unless $diff_in =~ s/\A\@\@ (-([0-9]+),([0-9]+) \+([0-9]+),([0-9]+)) \@\@[^\n]*\n?//;
1200             my ($hunk, $from_start, $from_count, $to_start, $to_count)
1201                 = ($1, $2, $3, $4, $5);
1202             my $from_end = $from_start + $from_count - 1;
1203             my $to_end = $to_start + $to_count - 1;
1204             my ($from_out, $to_out, $has_from, $has_to, $add, $delete);
1205             while (length $diff_in && ($from_count || $to_count)) {
1206                 die_255("Confused in $hunk")
1207                     unless $diff_in =~ s/\A([^\n]*)\n//ms;
1208                 my $line = $1;
1209                 $line = ' ' unless length $line;
1210                 if ($line =~ /^ .*/) {
1211                     process_hunk(\$from_out, \$to_out, \$has_from, \$has_to,
1212                                  $delete, $add);
1213                     undef $delete;
1214                     undef $add;
1215                     $from_out .= " $line\n";
1216                     $to_out .= " $line\n";
1217                     --$from_count;
1218                     --$to_count;
1219                 } elsif ($line =~ /^-(.*)/) {
1220                     push @$delete, $1;
1221                     --$from_count;
1222                 } elsif ($line =~ /^\+(.*)/) {
1223                     push @$add, $1;
1224                     --$to_count;
1225                 } else {
1226                     die_255("Can't parse '$line' as part of hunk $hunk");
1227                 }
1228             }
1229             process_hunk(\$from_out, \$to_out, \$has_from, \$has_to,
1230                          $delete, $add);
1231             die_255("No lines in hunk $hunk")
1232                 unless length $from_out || length $to_out;
1233             die_255("No changes in hunk $hunk")
1234                 unless $has_from || $has_to;
1235             $diff_out .= "***************\n";
1236             $diff_out .= "*** $from_start,$from_end ****\n";
1237             $diff_out .= $from_out if $has_from;
1238             $diff_out .= "--- $to_start,$to_end ----\n";
1239             $diff_out .= $to_out if $has_to;
1240         }
1241     }
1242 }
1243
1244 {
1245     my $use_context;
1246
1247     sub placate_patch_prog {
1248         my $patch = shift;
1249
1250         if (!defined $use_context) {
1251             my $version = `patch -v 2>&1`;
1252             die_255("Can't run `patch -v`, \$?=$?, bailing out")
1253                 unless defined $version;
1254             if ($version =~ /Free Software Foundation/) {
1255                 $use_context = 0;
1256             } elsif ($version =~ /Header: patch\.c,v.*\blwall\b/) {
1257                 # The system patch is older than Linux, and probably older than
1258                 # Windows NT.
1259                 $use_context = 1;
1260             } elsif ($version =~ /Header: patch\.c,v.*\babhinav\b/) {
1261                 # Thank you HP. No, we have no idea *which* version this is:
1262                 # $Header: patch.c,v 76.1.1.2.1.3 2001/12/03 12:24:52 abhinav Exp $
1263                 $use_context = 1;
1264             } else {
1265                 # Don't know.
1266                 $use_context = 0;
1267             }
1268         }
1269
1270         return $use_context ? ud2cd($patch) : $patch;
1271     }
1272 }
1273
1274 sub apply_patch {
1275     my ($patch, $what, $files) = @_;
1276     $what = 'patch' unless defined $what;
1277     unless (defined $files) {
1278         $patch =~ m!^--- [ab]/(\S+)\n\+\+\+ [ba]/\1!sm;
1279         $files = " $1";
1280     }
1281     my $patch_to_use = placate_patch_prog($patch);
1282     open my $fh, '|-', 'patch', '-p1' or die_255("Can't run patch: $!");
1283     print $fh $patch_to_use;
1284     return if close $fh;
1285     print STDERR "Patch is <<'EOPATCH'\n${patch}EOPATCH\n";
1286     print STDERR "\nConverted to a context diff <<'EOCONTEXT'\n${patch_to_use}EOCONTEXT\n"
1287         if $patch_to_use ne $patch;
1288     die_255("Can't $what$files: $?, $!");
1289 }
1290
1291 sub apply_commit {
1292     my ($commit, @files) = @_;
1293     my $patch = `git show $commit @files`;
1294     if (!defined $patch) {
1295         die_255("Can't get commit $commit for @files: $?") if @files;
1296         die_255("Can't get commit $commit: $?");
1297     }
1298     apply_patch($patch, "patch $commit", @files ? " for @files" : '');
1299 }
1300
1301 sub revert_commit {
1302     my ($commit, @files) = @_;
1303     my $patch = `git show -R $commit @files`;
1304     if (!defined $patch) {
1305         die_255("Can't get revert commit $commit for @files: $?") if @files;
1306         die_255("Can't get revert commit $commit: $?");
1307     }
1308     apply_patch($patch, "revert $commit", @files ? " for @files" : '');
1309 }
1310
1311 sub checkout_file {
1312     my ($file, $commit) = @_;
1313     $commit ||= $options{gold} || 'blead';
1314     system "git show $commit:$file > $file </dev/null"
1315         and die_255("Could not extract $file at revision $commit");
1316 }
1317
1318 sub check_shebang {
1319     my $file = shift;
1320     return unless -e $file;
1321     my $fh = open_or_die($file);
1322     my $line = <$fh>;
1323     return if $line =~ $run_with_our_perl;
1324     if (!-x $file) {
1325         die_255("$file is not executable.
1326 system($file, ...) is always going to fail.
1327
1328 Bailing out");
1329     }
1330     return unless $line =~ m{\A#!(/\S+/perl\S*)\s};
1331     die_255("$file will always be run by $1
1332 It won't be tested by the ./perl we build.
1333 If you intended to run it with that perl binary, please change your
1334 test case to
1335
1336     $1 @ARGV
1337
1338 If you intended to test it with the ./perl we build, please change your
1339 test case to
1340
1341     ./perl -Ilib @ARGV
1342
1343 [You may also need to add -- before ./perl to prevent that -Ilib as being
1344 parsed as an argument to bisect.pl]
1345
1346 Bailing out");
1347 }
1348
1349 sub clean {
1350     if ($options{clean}) {
1351         # Needed, because files that are build products in this checked out
1352         # version might be in git in the next desired version.
1353         system 'git clean -qdxf </dev/null';
1354         # Needed, because at some revisions the build alters checked out files.
1355         # (eg pod/perlapi.pod). Also undoes any changes to makedepend.SH
1356         system 'git reset --hard HEAD </dev/null';
1357     }
1358 }
1359
1360 sub skip {
1361     my $reason = shift;
1362     clean();
1363     warn "skipping - $reason";
1364     exit 125;
1365 }
1366
1367 sub report_and_exit {
1368     my ($good, $pass, $fail, $desc) = @_;
1369
1370     clean();
1371
1372     my $got = ($options{'expect-pass'} ? $good : !$good) ? 'good' : 'bad';
1373     if ($good) {
1374         print "$got - $pass $desc\n";
1375     } else {
1376         print "$got - $fail $desc\n";
1377     }
1378
1379     exit($got eq 'bad');
1380 }
1381
1382 sub run_report_and_exit {
1383     my $ret = run_with_options({setprgp => $options{setpgrp},
1384                                 timeout => $options{timeout},
1385                                }, @_);
1386     $ret &= 0xff if $options{crash};
1387     report_and_exit(!$ret, 'zero exit from', 'non-zero exit from', "@_");
1388 }
1389
1390 sub match_and_exit {
1391     my ($target, @globs) = @_;
1392     my $matches = 0;
1393     my $re = qr/$match/;
1394     my @files;
1395
1396     if (@globs) {
1397         require File::Glob;
1398         foreach (sort map { File::Glob::bsd_glob($_)} @globs) {
1399             if (!-f $_ || !-r _) {
1400                 warn "Skipping matching '$_' as it is not a readable file\n";
1401             } else {
1402                 push @files, $_;
1403             }
1404         }
1405     } else {
1406         local $/ = "\0";
1407         @files = defined $target ? `git ls-files -o -z`: `git ls-files -z`;
1408         chomp @files;
1409     }
1410
1411     foreach my $file (@files) {
1412         my $fh = open_or_die($file);
1413         while (<$fh>) {
1414             if ($_ =~ $re) {
1415                 ++$matches;
1416                 if (/[^[:^cntrl:]\h\v]/) { # Matches non-spacing non-C1 controls
1417                     print "Binary file $file matches\n";
1418                 } else {
1419                     $_ .= "\n" unless /\n\z/;
1420                     print "$file: $_";
1421                 }
1422             }
1423         }
1424         close_or_die($fh);
1425     }
1426     report_and_exit($matches,
1427                     $matches == 1 ? '1 match for' : "$matches matches for",
1428                     'no matches for', $match);
1429 }
1430
1431 # Not going to assume that system perl is yet new enough to have autodie
1432 system_or_die('git clean -dxf');
1433
1434 if (!defined $target) {
1435     match_and_exit(undef, @ARGV) if $match;
1436     $target = 'test_prep';
1437 } elsif ($target eq 'none') {
1438     match_and_exit(undef, @ARGV) if $match;
1439     run_report_and_exit(@ARGV);
1440 }
1441
1442 skip('no Configure - is this the //depot/perlext/Compiler branch?')
1443     unless -f 'Configure';
1444
1445 my $case_insensitive;
1446 {
1447     my ($dev_C, $ino_C) = stat 'Configure';
1448     die_255("Could not stat Configure: $!") unless defined $dev_C;
1449     my ($dev_c, $ino_c) = stat 'configure';
1450     ++$case_insensitive
1451         if defined $dev_c && $dev_C == $dev_c && $ino_C == $ino_c;
1452 }
1453
1454 # This changes to PERL_VERSION in 4d8076ea25903dcb in 1999
1455 my $major
1456     = extract_from_file('patchlevel.h',
1457                         qr/^#define\s+(?:PERL_VERSION|PATCHLEVEL)\s+(\d+)\s/,
1458                         0);
1459
1460 my $unfixable_db_file;
1461
1462 if ($major < 10
1463     && !extract_from_file('ext/DB_File/DB_File.xs',
1464                           qr!^#else /\* Berkeley DB Version > 2 \*/$!)) {
1465     # This DB_File.xs is really too old to patch up.
1466     # Skip DB_File, unless we're invoked with an explicit -Unoextensions
1467     if (!exists $defines{noextensions}) {
1468         $defines{noextensions} = 'DB_File';
1469     } elsif (defined $defines{noextensions}) {
1470         $defines{noextensions} .= ' DB_File';
1471     }
1472     ++$unfixable_db_file;
1473 }
1474
1475 patch_Configure();
1476 patch_hints();
1477 if ($options{'all-fixups'}) {
1478     patch_SH();
1479     patch_C();
1480     patch_ext();
1481 }
1482 apply_fixups($options{'early-fixup'});
1483
1484 # if Encode is not needed for the test, you can speed up the bisect by
1485 # excluding it from the runs with -Dnoextensions=Encode
1486 # ccache is an easy win. Remove it if it causes problems.
1487 # Commit 1cfa4ec74d4933da adds ignore_versioned_solibs to Configure, and sets it
1488 # to true in hints/linux.sh
1489 # On dromedary, from that point on, Configure (by default) fails to find any
1490 # libraries, because it scans /usr/local/lib /lib /usr/lib, which only contain
1491 # versioned libraries. Without -lm, the build fails.
1492 # Telling /usr/local/lib64 /lib64 /usr/lib64 works from that commit onwards,
1493 # until commit faae14e6e968e1c0 adds it to the hints.
1494 # However, prior to 1cfa4ec74d4933da telling Configure the truth doesn't work,
1495 # because it will spot versioned libraries, pass them to the compiler, and then
1496 # bail out pretty early on. Configure won't let us override libswanted, but it
1497 # will let us override the entire libs list.
1498
1499 foreach (@{$options{A}}) {
1500     push @paths, $1 if /^libpth=(.*)/s;
1501 }
1502
1503 unless (extract_from_file('Configure', 'ignore_versioned_solibs')) {
1504     # Before 1cfa4ec74d4933da, so force the libs list.
1505
1506     my @libs;
1507     # This is the current libswanted list from Configure, less the libs removed
1508     # by current hints/linux.sh
1509     foreach my $lib (qw(sfio socket inet nsl nm ndbm gdbm dbm db malloc dl
1510                         ld sun m crypt sec util c cposix posix ucb BSD)) {
1511         foreach my $dir (@paths) {
1512             # Note the wonderful consistency of dot-or-not in the config vars:
1513             next unless -f "$dir/lib$lib.$Config{dlext}"
1514                 || -f "$dir/lib$lib$Config{lib_ext}";
1515             push @libs, "-l$lib";
1516             last;
1517         }
1518     }
1519     $defines{libs} = \@libs unless exists $defines{libs};
1520 }
1521
1522 $defines{usenm} = undef
1523     if $major < 2 && !exists $defines{usenm};
1524
1525 my ($missing, $created_dirs);
1526 ($missing, $created_dirs) = force_manifest()
1527     if $options{'force-manifest'};
1528
1529 my @ARGS = '-dEs';
1530 foreach my $key (sort keys %defines) {
1531     my $val = $defines{$key};
1532     if (ref $val) {
1533         push @ARGS, "-D$key=@$val";
1534     } elsif (!defined $val) {
1535         push @ARGS, "-U$key";
1536     } elsif (!length $val) {
1537         push @ARGS, "-D$key";
1538     } else {
1539         $val = "" if $val eq "\0";
1540         push @ARGS, "-D$key=$val";
1541     }
1542 }
1543 push @ARGS, map {"-A$_"} @{$options{A}};
1544
1545 my $prefix;
1546
1547 # Testing a module? We need to install perl/cpan modules to a temp dir
1548 if ($options{module} || $options{'with-module'} || $options{'test-module'})
1549 {
1550   $prefix = tempdir(CLEANUP => 1);
1551
1552   push @ARGS, "-Dprefix=$prefix";
1553   push @ARGS, "-Uversiononly", "-Dinstallusrbinperl=n";
1554 }
1555
1556 # If a file in MANIFEST is missing, Configure asks if you want to
1557 # continue (the default being 'n'). With stdin closed or /dev/null,
1558 # it exits immediately and the check for config.sh below will skip.
1559 # Without redirecting stdin, the commands called will attempt to read from
1560 # stdin (and thus effectively hang)
1561 run_with_options({stdin => '/dev/null', name => 'Configure'},
1562                  './Configure', @ARGS);
1563
1564 patch_SH() unless $options{'all-fixups'};
1565 apply_fixups($options{'late-fixup'});
1566
1567 if (-f 'config.sh') {
1568     # Emulate noextensions if Configure doesn't support it.
1569     fake_noextensions()
1570         if $major < 10 && $defines{noextensions};
1571     if (system './Configure -S') {
1572         # See commit v5.23.5-89-g7a4fcb3.  Configure may try to run
1573         # ./optdef.sh instead of UU/optdef.sh.  Copying the file is
1574         # easier than patching Configure (which mentions optdef.sh multi-
1575         # ple times).
1576         require File::Copy;
1577         File::Copy::copy("UU/optdef.sh", "./optdef.sh");
1578         system_or_die('./Configure -S');
1579     }
1580 }
1581
1582 if ($target =~ /config\.s?h/) {
1583     match_and_exit($target, @ARGV) if $match && -f $target;
1584     report_and_exit(-f $target, 'could build', 'could not build', $target)
1585         if $options{'test-build'};
1586
1587     skip("could not build $target") unless -f $target;
1588
1589     run_report_and_exit(@ARGV);
1590 } elsif (!-f 'config.sh') {
1591     # Skip if something went wrong with Configure
1592
1593     skip('could not build config.sh');
1594 }
1595
1596 force_manifest_cleanup($missing, $created_dirs)
1597         if $missing;
1598
1599 if($options{'force-regen'}
1600    && extract_from_file('Makefile', qr/\bregen_headers\b/)) {
1601     # regen_headers was added in e50aee73b3d4c555, patch.1m for perl5.001
1602     # It's not worth faking it for earlier revisions.
1603     system_or_die('make regen_headers');
1604 }
1605
1606 unless ($options{'all-fixups'}) {
1607     patch_C();
1608     patch_ext();
1609 }
1610
1611 # Parallel build for miniperl is safe
1612 system "$options{make} $j miniperl </dev/null";
1613
1614 # This is the file we expect make to create
1615 my $expected_file = $target =~ /^test/ ? 't/perl'
1616     : $target eq 'Fcntl' ? "lib/auto/Fcntl/Fcntl.$Config{so}"
1617     : $target;
1618 # This is the target we tell make to build in order to get $expected_file
1619 my $real_target = $target eq 'Fcntl' ? $expected_file : $target;
1620
1621 if ($target ne 'miniperl') {
1622     # Nearly all parallel build issues fixed by 5.10.0. Untrustworthy before that.
1623     $j = '' if $major < 10;
1624
1625     if ($real_target eq 'test_prep') {
1626         if ($major < 8) {
1627             # test-prep was added in 5.004_01, 3e3baf6d63945cb6.
1628             # renamed to test_prep in 2001 in 5fe84fd29acaf55c.
1629             # earlier than that, just make test. It will be fast enough.
1630             $real_target = extract_from_file('Makefile.SH',
1631                                              qr/^(test[-_]prep):/,
1632                                              'test');
1633         }
1634     }
1635
1636     system "$options{make} $j $real_target </dev/null";
1637 }
1638
1639 my $expected_file_found = $expected_file =~ /perl$/
1640     ? -x $expected_file : -r $expected_file;
1641
1642 if ($expected_file_found && $expected_file eq 't/perl') {
1643     # Check that it isn't actually pointing to ../miniperl, which will happen
1644     # if the sanity check ./miniperl -Ilib -MExporter -e '<?>' fails, and
1645     # Makefile tries to run minitest.
1646
1647     # Of course, helpfully sometimes it's called ../perl, other times .././perl
1648     # and who knows if that list is exhaustive...
1649     my ($dev0, $ino0) = stat 't/perl';
1650     my ($dev1, $ino1) = stat 'perl';
1651     unless (defined $dev0 && defined $dev1 && $dev0 == $dev1 && $ino0 == $ino1) {
1652         undef $expected_file_found;
1653         my $link = readlink $expected_file;
1654         warn "'t/perl' => '$link', not 'perl'";
1655         die_255("Could not realink t/perl: $!") unless defined $link;
1656     }
1657 }
1658
1659 my $just_testing = 0;
1660
1661 if ($options{'test-build'}) {
1662     report_and_exit($expected_file_found, 'could build', 'could not build',
1663                     $real_target);
1664 } elsif (!$expected_file_found) {
1665     skip("could not build $real_target");
1666 } elsif (my $mod_opt = $options{module} || $options{'with-module'}
1667                || ($just_testing++, $options{'test-module'})) {
1668   # Testing a cpan module? See if it will install
1669   # First we need to install this perl somewhere
1670   system_or_die('./installperl');
1671
1672   my @m = split(',', $mod_opt);
1673
1674   my $bdir = File::Temp::tempdir(
1675     CLEANUP => 1,
1676   ) or die $!;
1677
1678   # Don't ever stop to ask the user for input
1679   $ENV{AUTOMATED_TESTING} = 1;
1680   $ENV{PERL_MM_USE_DEFAULT} = 1;
1681
1682   # Don't let these interfere with our cpan installs
1683   delete $ENV{PERL_MB_OPT};
1684   delete $ENV{PERL_MM_OPT};
1685
1686   # Make sure we load up our CPAN::MyConfig and then
1687   # override the build_dir so we have a fresh one
1688   # every build
1689   my $cdir = $options{'cpan-config-dir'}
1690           || File::Spec->catfile($ENV{HOME},".cpan");
1691
1692   my @cpanshell = (
1693     "$prefix/bin/perl",
1694     "-I", "$cdir",
1695     "-MCPAN::MyConfig",
1696     "-MCPAN",
1697     "-e","\$CPAN::Config->{build_dir}=q{$bdir};",
1698     "-e",
1699   );
1700
1701   for (@m) {
1702     s/-/::/g if /-/ and !m|/|;
1703   }
1704   my $install = join ",", map { "'$_'" } @m;
1705   if ($just_testing) {
1706     $install = "test($install)";
1707   } elsif ($options{'no-module-tests'}) {
1708     $install = "notest('install',$install)";
1709   } else {
1710     $install = "install($install)";
1711   }
1712   my $last = $m[-1];
1713   my $status_method = $just_testing ? 'test' : 'uptodate';
1714   my $shellcmd = "$install; die unless CPAN::Shell->expand(Module => '$last')->$status_method;";
1715
1716   if ($options{module} || $options{'test-module'}) {
1717     run_report_and_exit(@cpanshell, $shellcmd);
1718   } else {
1719     my $ret = run_with_options({setprgp => $options{setpgrp},
1720                                 timeout => $options{timeout},
1721                                }, @cpanshell, $shellcmd);
1722     $ret &= 0xff if $options{crash};
1723
1724     # Failed? Give up
1725     if ($ret) {
1726       report_and_exit(!$ret, 'zero exit from', 'non-zero exit from', "@_");
1727     }
1728   }
1729 }
1730
1731 match_and_exit($real_target, @ARGV) if $match;
1732
1733 if (defined $options{'one-liner'}) {
1734     my $exe = $target =~ /^(?:perl$|test)/ ? 'perl' : 'miniperl';
1735     unshift @ARGV, map {('-e', $_)} @{$options{'one-liner'}};
1736     foreach (qw(c l w)) {
1737         unshift @ARGV, "-$_" if $options{$_};
1738     }
1739     unshift @ARGV, "./$exe", '-Ilib';
1740 }
1741
1742 if (-f $ARGV[0]) {
1743     my $fh = open_or_die($ARGV[0]);
1744     my $line = <$fh>;
1745     unshift @ARGV, $1, '-Ilib'
1746         if $line =~ $run_with_our_perl;
1747 }
1748
1749 if ($options{valgrind}) {
1750     # Turns out to be too confusing to use an optional argument with the path
1751     # of the valgrind binary, as if --valgrind takes an optional argument,
1752     # then specifying it as the last option eats the first part of the testcase.
1753     # ie this: .../bisect.pl --valgrind testcase
1754     # is treated as --valgrind=testcase and as there is no test case given,
1755     # it's an invalid commandline, bailing out with the usage message.
1756
1757     # Currently, the test script can't signal a skip with 125, so anything
1758     # non-zero would do. But to keep that option open in future, use 124
1759     unshift @ARGV, 'valgrind', '--error-exitcode=124';
1760 }
1761
1762 # This is what we came here to run:
1763
1764 if (exists $Config{ldlibpthname}) {
1765     require Cwd;
1766     my $varname = $Config{ldlibpthname};
1767     my $cwd = Cwd::getcwd();
1768     if (defined $ENV{$varname}) {
1769         $ENV{$varname} = $cwd . $Config{path_sep} . $ENV{$varname};
1770     } else {
1771         $ENV{$varname} = $cwd;
1772     }
1773 }
1774
1775 run_report_and_exit(@ARGV);
1776
1777 ############################################################################
1778 #
1779 # Patching, editing and faking routines only below here.
1780 #
1781 ############################################################################
1782
1783 sub fake_noextensions {
1784     edit_file('config.sh', sub {
1785                   my @lines = split /\n/, shift;
1786                   my @ext = split /\s+/, $defines{noextensions};
1787                   foreach (@lines) {
1788                       next unless /^extensions=/ || /^dynamic_ext/;
1789                       foreach my $ext (@ext) {
1790                           s/\b$ext( )?\b/$1/;
1791                       }
1792                   }
1793                   return join "\n", @lines;
1794               });
1795 }
1796
1797 sub force_manifest {
1798     my (@missing, @created_dirs);
1799     my $fh = open_or_die('MANIFEST');
1800     while (<$fh>) {
1801         next unless /^(\S+)/;
1802         # -d is special case needed (at least) between 27332437a2ed1941 and
1803         # bf3d9ec563d25054^ inclusive, as manifest contains ext/Thread/Thread
1804         push @missing, $1
1805             unless -f $1 || -d $1;
1806     }
1807     close_or_die($fh);
1808
1809     foreach my $pathname (@missing) {
1810         my @parts = split '/', $pathname;
1811         my $leaf = pop @parts;
1812         my $path = '.';
1813         while (@parts) {
1814             $path .= '/' . shift @parts;
1815             next if -d $path;
1816             mkdir $path, 0700 or die_255("Can't create $path: $!");
1817             unshift @created_dirs, $path;
1818         }
1819         $fh = open_or_die($pathname, '>');
1820         close_or_die($fh);
1821         chmod 0, $pathname or die_255("Can't chmod 0 $pathname: $!");
1822     }
1823     return \@missing, \@created_dirs;
1824 }
1825
1826 sub force_manifest_cleanup {
1827     my ($missing, $created_dirs) = @_;
1828     # This is probably way too paranoid:
1829     my @errors;
1830     require Fcntl;
1831     foreach my $file (@$missing) {
1832         my (undef, undef, $mode, undef, undef, undef, undef, $size)
1833             = stat $file;
1834         if (!defined $mode) {
1835             push @errors, "Added file $file has been deleted by Configure";
1836             next;
1837         }
1838         if (Fcntl::S_IMODE($mode) != 0) {
1839             push @errors,
1840                 sprintf 'Added file %s had mode changed by Configure to %03o',
1841                     $file, $mode;
1842         }
1843         if ($size != 0) {
1844             push @errors,
1845                 "Added file $file had sized changed by Configure to $size";
1846         }
1847         unlink $file or die_255("Can't unlink $file: $!");
1848     }
1849     foreach my $dir (@$created_dirs) {
1850         rmdir $dir or die_255("Can't rmdir $dir: $!");
1851     }
1852     skip("@errors")
1853         if @errors;
1854 }
1855
1856 sub patch_Configure {
1857     if ($major < 1) {
1858         if (extract_from_file('Configure',
1859                               qr/^\t\t\*=\*\) echo "\$1" >> \$optdef;;$/)) {
1860             # This is "        Spaces now allowed in -D command line options.",
1861             # part of commit ecfc54246c2a6f42
1862             apply_patch(<<'EOPATCH');
1863 diff --git a/Configure b/Configure
1864 index 3d3b38d..78ffe16 100755
1865 --- a/Configure
1866 +++ b/Configure
1867 @@ -652,7 +777,8 @@ while test $# -gt 0; do
1868                         echo "$me: use '-U symbol=', not '-D symbol='." >&2
1869                         echo "$me: ignoring -D $1" >&2
1870                         ;;
1871 -               *=*) echo "$1" >> $optdef;;
1872 +               *=*) echo "$1" | \
1873 +                               sed -e "s/'/'\"'\"'/g" -e "s/=\(.*\)/='\1'/" >> $optdef;;
1874                 *) echo "$1='define'" >> $optdef;;
1875                 esac
1876                 shift
1877 EOPATCH
1878         }
1879
1880         if (extract_from_file('Configure', qr/^if \$contains 'd_namlen' \$xinc\b/)) {
1881             # Configure's original simple "grep" for d_namlen falls foul of the
1882             # approach taken by the glibc headers:
1883             # #ifdef _DIRENT_HAVE_D_NAMLEN
1884             # # define _D_EXACT_NAMLEN(d) ((d)->d_namlen)
1885             #
1886             # where _DIRENT_HAVE_D_NAMLEN is not defined on Linux.
1887             # This is also part of commit ecfc54246c2a6f42
1888             apply_patch(<<'EOPATCH');
1889 diff --git a/Configure b/Configure
1890 index 3d3b38d..78ffe16 100755
1891 --- a/Configure
1892 +++ b/Configure
1893 @@ -3935,7 +4045,8 @@ $rm -f try.c
1894  
1895  : see if the directory entry stores field length
1896  echo " "
1897 -if $contains 'd_namlen' $xinc >/dev/null 2>&1; then
1898 +$cppstdin $cppflags $cppminus < "$xinc" > try.c
1899 +if $contains 'd_namlen' try.c >/dev/null 2>&1; then
1900         echo "Good, your directory entry keeps length information in d_namlen." >&4
1901         val="$define"
1902  else
1903 EOPATCH
1904         }
1905     }
1906
1907     if ($major < 2
1908         && !extract_from_file('Configure',
1909                               qr/Try to guess additional flags to pick up local libraries/)) {
1910         my $mips = extract_from_file('Configure',
1911                                      qr!(''\) if (?:\./)?mips; then)!);
1912         # This is part of perl-5.001n. It's needed, to add -L/usr/local/lib to
1913         # the ld flags if libraries are found there. It shifts the code to set
1914         # up libpth earlier, and then adds the code to add libpth entries to
1915         # ldflags
1916         # mips was changed to ./mips in ecfc54246c2a6f42, perl5.000 patch.0g
1917         apply_patch(sprintf <<'EOPATCH', $mips);
1918 diff --git a/Configure b/Configure
1919 index 53649d5..0635a6e 100755
1920 --- a/Configure
1921 +++ b/Configure
1922 @@ -2749,6 +2749,52 @@ EOM
1923         ;;
1924  esac
1925  
1926 +: Set private lib path
1927 +case "$plibpth" in
1928 +'') if ./mips; then
1929 +               plibpth="$incpath/usr/lib /usr/local/lib /usr/ccs/lib"
1930 +       fi;;
1931 +esac
1932 +case "$libpth" in
1933 +' ') dlist='';;
1934 +'') dlist="$plibpth $glibpth";;
1935 +*) dlist="$libpth";;
1936 +esac
1937 +
1938 +: Now check and see which directories actually exist, avoiding duplicates
1939 +libpth=''
1940 +for xxx in $dlist
1941 +do
1942 +    if $test -d $xxx; then
1943 +               case " $libpth " in
1944 +               *" $xxx "*) ;;
1945 +               *) libpth="$libpth $xxx";;
1946 +               esac
1947 +    fi
1948 +done
1949 +$cat <<'EOM'
1950 +
1951 +Some systems have incompatible or broken versions of libraries.  Among
1952 +the directories listed in the question below, please remove any you
1953 +know not to be holding relevant libraries, and add any that are needed.
1954 +Say "none" for none.
1955 +
1956 +EOM
1957 +case "$libpth" in
1958 +'') dflt='none';;
1959 +*)
1960 +       set X $libpth
1961 +       shift
1962 +       dflt=${1+"$@"}
1963 +       ;;
1964 +esac
1965 +rp="Directories to use for library searches?"
1966 +. ./myread
1967 +case "$ans" in
1968 +none) libpth=' ';;
1969 +*) libpth="$ans";;
1970 +esac
1971 +
1972  : flags used in final linking phase
1973  case "$ldflags" in
1974  '') if ./venix; then
1975 @@ -2765,6 +2811,23 @@ case "$ldflags" in
1976         ;;
1977  *) dflt="$ldflags";;
1978  esac
1979 +
1980 +: Possible local library directories to search.
1981 +loclibpth="/usr/local/lib /opt/local/lib /usr/gnu/lib"
1982 +loclibpth="$loclibpth /opt/gnu/lib /usr/GNU/lib /opt/GNU/lib"
1983 +
1984 +: Try to guess additional flags to pick up local libraries.
1985 +for thislibdir in $libpth; do
1986 +       case " $loclibpth " in
1987 +       *" $thislibdir "*)
1988 +               case "$dflt " in 
1989 +               "-L$thislibdir ") ;;
1990 +               *)  dflt="$dflt -L$thislibdir" ;;
1991 +               esac
1992 +               ;;
1993 +       esac
1994 +done
1995 +
1996  echo " "
1997  rp="Any additional ld flags (NOT including libraries)?"
1998  . ./myread
1999 @@ -2828,52 +2891,6 @@ n) echo "OK, that should do.";;
2000  esac
2001  $rm -f try try.* core
2002  
2003 -: Set private lib path
2004 -case "$plibpth" in
2005 -%s
2006 -               plibpth="$incpath/usr/lib /usr/local/lib /usr/ccs/lib"
2007 -       fi;;
2008 -esac
2009 -case "$libpth" in
2010 -' ') dlist='';;
2011 -'') dlist="$plibpth $glibpth";;
2012 -*) dlist="$libpth";;
2013 -esac
2014 -
2015 -: Now check and see which directories actually exist, avoiding duplicates
2016 -libpth=''
2017 -for xxx in $dlist
2018 -do
2019 -    if $test -d $xxx; then
2020 -               case " $libpth " in
2021 -               *" $xxx "*) ;;
2022 -               *) libpth="$libpth $xxx";;
2023 -               esac
2024 -    fi
2025 -done
2026 -$cat <<'EOM'
2027 -
2028 -Some systems have incompatible or broken versions of libraries.  Among
2029 -the directories listed in the question below, please remove any you
2030 -know not to be holding relevant libraries, and add any that are needed.
2031 -Say "none" for none.
2032 -
2033 -EOM
2034 -case "$libpth" in
2035 -'') dflt='none';;
2036 -*)
2037 -       set X $libpth
2038 -       shift
2039 -       dflt=${1+"$@"}
2040 -       ;;
2041 -esac
2042 -rp="Directories to use for library searches?"
2043 -. ./myread
2044 -case "$ans" in
2045 -none) libpth=' ';;
2046 -*) libpth="$ans";;
2047 -esac
2048 -
2049  : compute shared library extension
2050  case "$so" in
2051  '')
2052 EOPATCH
2053     }
2054
2055     if ($major == 4 && extract_from_file('Configure', qr/^d_gethbynam=/)) {
2056         # Fixes a bug introduced in 4599a1dedd47b916
2057         apply_commit('3cbc818d1d0ac470');
2058     }
2059
2060     if ($major == 4 && extract_from_file('Configure',
2061                                          qr/gethbadd_addr_type=`echo \$gethbadd_addr_type/)) {
2062         # Fixes a bug introduced in 3fd537d4b944bc7a
2063         apply_commit('6ff9219da6cf8cfd');
2064     }
2065
2066     if ($major == 4 && extract_from_file('Configure',
2067                                          qr/^pthreads_created_joinable=/)) {
2068         # Fix for bug introduced in 52e1cb5ebf5e5a8c
2069         # Part of commit ce637636a41b2fef
2070         edit_file('Configure', sub {
2071                       my $code = shift;
2072                       $code =~ s{^pthreads_created_joinable=''}
2073                                 {d_pthreads_created_joinable=''}ms
2074                                     or die_255("Substitution failed");
2075                       $code =~ s{^pthreads_created_joinable='\$pthreads_created_joinable'}
2076                                 {d_pthreads_created_joinable='\$d_pthreads_created_joinable'}ms
2077                            or die_255("Substitution failed");
2078                       return $code;
2079                   });
2080     }
2081
2082     if ($major < 5 && extract_from_file('Configure',
2083                                         qr!if \$cc \$ccflags try\.c -o try >/dev/null 2>&1; then!)) {
2084         # Analogous to the more general fix of dfe9444ca7881e71
2085         # Without this flags such as -m64 may not be passed to this compile,
2086         # which results in a byteorder of '1234' instead of '12345678', which
2087         # can then cause crashes.
2088
2089         if (extract_from_file('Configure', qr/xxx_prompt=y/)) {
2090             # 8e07c86ebc651fe9 or later
2091             # ("This is my patch  patch.1n  for perl5.001.")
2092             apply_patch(<<'EOPATCH');
2093 diff --git a/Configure b/Configure
2094 index 62249dd..c5c384e 100755
2095 --- a/Configure
2096 +++ b/Configure
2097 @@ -8247,7 +8247,7 @@ main()
2098  }
2099  EOCP
2100         xxx_prompt=y
2101 -       if $cc $ccflags try.c -o try >/dev/null 2>&1 && ./try > /dev/null; then
2102 +       if $cc $ccflags $ldflags try.c -o try >/dev/null 2>&1 && ./try > /dev/null; then
2103                 dflt=`./try`
2104                 case "$dflt" in
2105                 [1-4][1-4][1-4][1-4]|12345678|87654321)
2106 EOPATCH
2107         } else {
2108             apply_patch(<<'EOPATCH');
2109 diff --git a/Configure b/Configure
2110 index 53649d5..f1cd64a 100755
2111 --- a/Configure
2112 +++ b/Configure
2113 @@ -6362,7 +6362,7 @@ main()
2114         printf("\n");
2115  }
2116  EOCP
2117 -       if $cc $ccflags try.c -o try >/dev/null 2>&1 ; then
2118 +       if $cc $ccflags $ldflags try.c -o try >/dev/null 2>&1 ; then
2119                 dflt=`./try`
2120                 case "$dflt" in
2121                 ????|????????) echo "(The test program ran ok.)";;
2122 EOPATCH
2123         }
2124     }
2125
2126     if ($major < 6 && !extract_from_file('Configure',
2127                                          qr!^\t-A\)$!)) {
2128         # This adds the -A option to Configure, which is incredibly useful
2129         # Effectively this is commits 02e93a22d20fc9a5, 5f83a3e9d818c3ad,
2130         # bde6b06b2c493fef, f7c3111703e46e0c and 2 lines of trailing whitespace
2131         # removed by 613d6c3e99b9decc, but applied at slightly different
2132         # locations to ensure a clean patch back to 5.000
2133         # Note, if considering patching to the intermediate revisions to fix
2134         # bugs in -A handling, f7c3111703e46e0c is from 2002, and hence
2135         # $major == 8
2136
2137         # To add to the fun, early patches add -K and -O options, and it's not
2138         # trivial to get patch to put the C<. ./posthint.sh> in the right place
2139         edit_file('Configure', sub {
2140                       my $code = shift;
2141                       $code =~ s/(optstr = ")([^"]+";\s*# getopt-style specification)/$1A:$2/
2142                           or die_255("Substitution failed");
2143                       $code =~ s!^(: who configured the system)!
2144 touch posthint.sh
2145 . ./posthint.sh
2146
2147 $1!ms
2148                           or die_255("Substitution failed");
2149                       return $code;
2150                   });
2151         apply_patch(<<'EOPATCH');
2152 diff --git a/Configure b/Configure
2153 index 4b55fa6..60c3c64 100755
2154 --- a/Configure
2155 +++ b/Configure
2156 @@ -1150,6 +1150,7 @@ set X `for arg in "$@"; do echo "X$arg"; done |
2157  eval "set $*"
2158  shift
2159  rm -f options.awk
2160 +rm -f posthint.sh
2161  
2162  : set up default values
2163  fastread=''
2164 @@ -1172,6 +1173,56 @@ while test $# -gt 0; do
2165         case "$1" in
2166         -d) shift; fastread=yes;;
2167         -e) shift; alldone=cont;;
2168 +       -A)
2169 +           shift
2170 +           xxx=''
2171 +           yyy="$1"
2172 +           zzz=''
2173 +           uuu=undef
2174 +           case "$yyy" in
2175 +            *=*) zzz=`echo "$yyy"|sed 's!=.*!!'`
2176 +                 case "$zzz" in
2177 +                 *:*) zzz='' ;;
2178 +                 *)   xxx=append
2179 +                      zzz=" "`echo "$yyy"|sed 's!^[^=]*=!!'`
2180 +                      yyy=`echo "$yyy"|sed 's!=.*!!'` ;;
2181 +                 esac
2182 +                 ;;
2183 +            esac
2184 +            case "$xxx" in
2185 +            '')  case "$yyy" in
2186 +                 *:*) xxx=`echo "$yyy"|sed 's!:.*!!'`
2187 +                      yyy=`echo "$yyy"|sed 's!^[^:]*:!!'`
2188 +                      zzz=`echo "$yyy"|sed 's!^[^=]*=!!'`
2189 +                      yyy=`echo "$yyy"|sed 's!=.*!!'` ;;
2190 +                 *)   xxx=`echo "$yyy"|sed 's!:.*!!'`
2191 +                      yyy=`echo "$yyy"|sed 's!^[^:]*:!!'` ;;
2192 +                 esac
2193 +                 ;;
2194 +            esac
2195 +           case "$xxx" in
2196 +           append)
2197 +               echo "$yyy=\"\${$yyy}$zzz\""    >> posthint.sh ;;
2198 +           clear)
2199 +               echo "$yyy=''"                  >> posthint.sh ;;
2200 +           define)
2201 +               case "$zzz" in
2202 +               '') zzz=define ;;
2203 +               esac
2204 +               echo "$yyy='$zzz'"              >> posthint.sh ;;
2205 +           eval)
2206 +               echo "eval \"$yyy=$zzz\""       >> posthint.sh ;;
2207 +           prepend)
2208 +               echo "$yyy=\"$zzz\${$yyy}\""    >> posthint.sh ;;
2209 +           undef)
2210 +               case "$zzz" in
2211 +               '') zzz="$uuu" ;;
2212 +               esac
2213 +               echo "$yyy=$zzz"                >> posthint.sh ;;
2214 +            *)  echo "$me: unknown -A command '$xxx', ignoring -A $1" >&2 ;;
2215 +           esac
2216 +           shift
2217 +           ;;
2218         -f)
2219                 shift
2220                 cd ..
2221 EOPATCH
2222     }
2223
2224     if ($major < 8 && $^O eq 'aix') {
2225         edit_file('Configure', sub {
2226                       my $code = shift;
2227                       # Replicate commit a8c676c69574838b
2228                       # Whitespace allowed at the ends of /lib/syscalls.exp lines
2229                       # and half of commit c6912327ae30e6de
2230                       # AIX syscalls.exp scan: the syscall might be marked 32, 3264, or 64
2231                       $code =~ s{(\bsed\b.*\bsyscall)(?:\[0-9\]\*)?(\$.*/lib/syscalls\.exp)}
2232                                 {$1 . "[0-9]*[ \t]*" . $2}e;
2233                       return $code;
2234                   });
2235     }
2236
2237     if ($major < 8 && !extract_from_file('Configure',
2238                                          qr/^\t\tif test ! -t 0; then$/)) {
2239         # Before dfe9444ca7881e71, Configure would refuse to run if stdin was
2240         # not a tty. With that commit, the tty requirement was dropped for -de
2241         # and -dE
2242         # Commit aaeb8e512e8e9e14 dropped the tty requirement for -S
2243         # For those older versions, it's probably easiest if we simply remove
2244         # the sanity test.
2245         edit_file('Configure', sub {
2246                       my $code = shift;
2247                       $code =~ s/test ! -t 0/test Perl = rules/;
2248                       return $code;
2249                   });
2250     }
2251
2252     if ($major == 8 || $major == 9) {
2253         # Fix symbol detection to that of commit 373dfab3839ca168 if it's any
2254         # intermediate version 5129fff43c4fe08c or later, as the intermediate
2255         # versions don't work correctly on (at least) Sparc Linux.
2256         # 5129fff43c4fe08c adds the first mention of mistrustnm.
2257         # 373dfab3839ca168 removes the last mention of lc=""
2258         edit_file('Configure', sub {
2259                       my $code = shift;
2260                       return $code
2261                           if $code !~ /\btc="";/; # 373dfab3839ca168 or later
2262                       return $code
2263                           if $code !~ /\bmistrustnm\b/; # before 5129fff43c4fe08c
2264                       my $fixed = <<'EOC';
2265
2266 : is a C symbol defined?
2267 csym='tlook=$1;
2268 case "$3" in
2269 -v) tf=libc.tmp; tdc="";;
2270 -a) tf=libc.tmp; tdc="[]";;
2271 *) tlook="^$1\$"; tf=libc.list; tdc="()";;
2272 esac;
2273 tx=yes;
2274 case "$reuseval-$4" in
2275 true-) ;;
2276 true-*) tx=no; eval "tval=\$$4"; case "$tval" in "") tx=yes;; esac;;
2277 esac;
2278 case "$tx" in
2279 yes)
2280         tval=false;
2281         if $test "$runnm" = true; then
2282                 if $contains $tlook $tf >/dev/null 2>&1; then
2283                         tval=true;
2284                 elif $test "$mistrustnm" = compile -o "$mistrustnm" = run; then
2285                         echo "void *(*(p()))$tdc { extern void *$1$tdc; return &$1; } int main() { if(p()) return(0); else return(1); }"> try.c;
2286                         $cc -o try $optimize $ccflags $ldflags try.c >/dev/null 2>&1 $libs && tval=true;
2287                         $test "$mistrustnm" = run -a -x try && { $run ./try$_exe >/dev/null 2>&1 || tval=false; };
2288                         $rm -f try$_exe try.c core core.* try.core;
2289                 fi;
2290         else
2291                 echo "void *(*(p()))$tdc { extern void *$1$tdc; return &$1; } int main() { if(p()) return(0); else return(1); }"> try.c;
2292                 $cc -o try $optimize $ccflags $ldflags try.c $libs >/dev/null 2>&1 && tval=true;
2293                 $rm -f try$_exe try.c;
2294         fi;
2295         ;;
2296 *)
2297         case "$tval" in
2298         $define) tval=true;;
2299         *) tval=false;;
2300         esac;
2301         ;;
2302 esac;
2303 eval "$2=$tval"'
2304
2305 EOC
2306                       $code =~ s/\n: is a C symbol defined\?\n.*?\neval "\$2=\$tval"'\n\n/$fixed/sm
2307                           or die_255("substitution failed");
2308                       return $code;
2309                   });
2310     }
2311
2312     if ($major < 10
2313         && extract_from_file('Configure', qr/^set malloc\.h i_malloc$/)) {
2314         # This is commit 01d07975f7ef0e7d, trimmed, with $compile inlined as
2315         # prior to bd9b35c97ad661cc Configure had the malloc.h test before the
2316         # definition of $compile.
2317         apply_patch(<<'EOPATCH');
2318 diff --git a/Configure b/Configure
2319 index 3d2e8b9..6ce7766 100755
2320 --- a/Configure
2321 +++ b/Configure
2322 @@ -6743,5 +6743,22 @@ set d_dosuid
2323  
2324  : see if this is a malloc.h system
2325 -set malloc.h i_malloc
2326 -eval $inhdr
2327 +: we want a real compile instead of Inhdr because some systems have a
2328 +: malloc.h that just gives a compile error saying to use stdlib.h instead
2329 +echo " "
2330 +$cat >try.c <<EOCP
2331 +#include <stdlib.h>
2332 +#include <malloc.h>
2333 +int main () { return 0; }
2334 +EOCP
2335 +set try
2336 +if $cc $optimize $ccflags $ldflags -o try $* try.c $libs > /dev/null 2>&1; then
2337 +    echo "<malloc.h> found." >&4
2338 +    val="$define"
2339 +else
2340 +    echo "<malloc.h> NOT found." >&4
2341 +    val="$undef"
2342 +fi
2343 +$rm -f try.c try
2344 +set i_malloc
2345 +eval $setvar
2346  
2347 EOPATCH
2348     }
2349 }
2350
2351 sub patch_hints {
2352     if ($^O eq 'freebsd') {
2353         # There are rather too many version-specific FreeBSD hints fixes to
2354         # patch individually. Also, more than once the FreeBSD hints file has
2355         # been written in what turned out to be a rather non-future-proof style,
2356         # with case statements treating the most recent version as the
2357         # exception, instead of treating previous versions' behaviour explicitly
2358         # and changing the default to cater for the current behaviour. (As
2359         # strangely, future versions inherit the current behaviour.)
2360         checkout_file('hints/freebsd.sh');
2361     } elsif ($^O eq 'darwin') {
2362         if ($major < 8) {
2363             # We can't build on darwin without some of the data in the hints
2364             # file. Probably less surprising to use the earliest version of
2365             # hints/darwin.sh and then edit in place just below, than use
2366             # blead's version, as that would create a discontinuity at
2367             # f556e5b971932902 - before it, hints bugs would be "fixed", after
2368             # it they'd resurface. This way, we should give the illusion of
2369             # monotonic bug fixing.
2370             my $faking_it;
2371             if (!-f 'hints/darwin.sh') {
2372                 checkout_file('hints/darwin.sh', 'f556e5b971932902');
2373                 ++$faking_it;
2374             }
2375
2376             edit_file('hints/darwin.sh', sub {
2377                       my $code = shift;
2378                       # Part of commit 8f4f83badb7d1ba9, which mostly undoes
2379                       # commit 0511a818910f476c.
2380                       $code =~ s/^cppflags='-traditional-cpp';$/cppflags="\${cppflags} -no-cpp-precomp"/m;
2381                       # commit 14c11978e9b52e08/803bb6cc74d36a3f
2382                       # Without this, code in libperl.bundle links against op.o
2383                       # in preference to opmini.o on the linker command line,
2384                       # and hence miniperl tries to use File::Glob instead of
2385                       # csh
2386                       $code =~ s/^(lddlflags=)/ldflags="\${ldflags} -flat_namespace"\n$1/m;
2387                       # f556e5b971932902 also patches Makefile.SH with some
2388                       # special case code to deal with useshrplib for darwin.
2389                       # Given that post 5.8.0 the darwin hints default was
2390                       # changed to false, and it would be very complex to splice
2391                       # in that code in various versions of Makefile.SH back
2392                       # to 5.002, lets just turn it off.
2393                       $code =~ s/^useshrplib='true'/useshrplib='false'/m
2394                           if $faking_it;
2395
2396                       # Part of commit d235852b65d51c44
2397                       # Don't do this on a case sensitive HFS+ partition, as it
2398                       # breaks the build for 5.003 and earlier.
2399                       if ($case_insensitive
2400                           && $code !~ /^firstmakefile=GNUmakefile/) {
2401                           $code .= "\nfirstmakefile=GNUmakefile;\n";
2402                       }
2403
2404                       return $code;
2405                   });
2406         }
2407     } elsif ($^O eq 'netbsd') {
2408         if ($major < 6) {
2409             # These are part of commit 099685bc64c7dbce
2410             edit_file('hints/netbsd.sh', sub {
2411                           my $code = shift;
2412                           my $fixed = <<'EOC';
2413 case "$osvers" in
2414 0.9|0.8*)
2415         usedl="$undef"
2416         ;;
2417 *)
2418         if [ -f /usr/libexec/ld.elf_so ]; then
2419                 d_dlopen=$define
2420                 d_dlerror=$define
2421                 ccdlflags="-Wl,-E -Wl,-R${PREFIX}/lib $ccdlflags"
2422                 cccdlflags="-DPIC -fPIC $cccdlflags"
2423                 lddlflags="--whole-archive -shared $lddlflags"
2424         elif [ "`uname -m`" = "pmax" ]; then
2425 # NetBSD 1.3 and 1.3.1 on pmax shipped an 'old' ld.so, which will not work.
2426                 d_dlopen=$undef
2427         elif [ -f /usr/libexec/ld.so ]; then
2428                 d_dlopen=$define
2429                 d_dlerror=$define
2430                 ccdlflags="-Wl,-R${PREFIX}/lib $ccdlflags"
2431 # we use -fPIC here because -fpic is *NOT* enough for some of the
2432 # extensions like Tk on some netbsd platforms (the sparc is one)
2433                 cccdlflags="-DPIC -fPIC $cccdlflags"
2434                 lddlflags="-Bforcearchive -Bshareable $lddlflags"
2435         else
2436                 d_dlopen=$undef
2437         fi
2438         ;;
2439 esac
2440 EOC
2441                           $code =~ s/^case "\$osvers" in\n0\.9\|0\.8.*?^esac\n/$fixed/ms;
2442                           return $code;
2443                       });
2444         }
2445     } elsif ($^O eq 'openbsd') {
2446         if ($major < 8) {
2447             checkout_file('hints/openbsd.sh', '43051805d53a3e4c')
2448                 unless -f 'hints/openbsd.sh';
2449             my $which = extract_from_file('hints/openbsd.sh',
2450                                           qr/# from (2\.8|3\.1) onwards/,
2451                                           '');
2452             if ($which eq '') {
2453                 my $was = extract_from_file('hints/openbsd.sh',
2454                                             qr/(lddlflags="(?:-Bforcearchive )?-Bshareable)/);
2455                 # This is commit 154d43cbcf57271c and parts of 5c75dbfa77b0949c
2456                 # and 29b5585702e5e025
2457                 apply_patch(sprintf <<'EOPATCH', $was);
2458 diff --git a/hints/openbsd.sh b/hints/openbsd.sh
2459 index a7d8bf2..5b79709 100644
2460 --- a/hints/openbsd.sh
2461 +++ b/hints/openbsd.sh
2462 @@ -37,7 +37,25 @@ OpenBSD.alpha|OpenBSD.mips|OpenBSD.powerpc|OpenBSD.vax)
2463         # we use -fPIC here because -fpic is *NOT* enough for some of the
2464         # extensions like Tk on some OpenBSD platforms (ie: sparc)
2465         cccdlflags="-DPIC -fPIC $cccdlflags"
2466 -       %s $lddlflags"
2467 +       case "$osvers" in
2468 +       [01].*|2.[0-7]|2.[0-7].*)
2469 +               lddlflags="-Bshareable $lddlflags"
2470 +               ;;
2471 +       2.[8-9]|3.0)
2472 +               ld=${cc:-cc}
2473 +               lddlflags="-shared -fPIC $lddlflags"
2474 +               ;;
2475 +       *) # from 3.1 onwards
2476 +               ld=${cc:-cc}
2477 +               lddlflags="-shared -fPIC $lddlflags"
2478 +               libswanted=`echo $libswanted | sed 's/ dl / /'`
2479 +               ;;
2480 +       esac
2481 +
2482 +       # We need to force ld to export symbols on ELF platforms.
2483 +       # Without this, dlopen() is crippled.
2484 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
2485 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
2486         ;;
2487  esac
2488  
2489 EOPATCH
2490             } elsif ($which eq '2.8') {
2491                 # This is parts of 5c75dbfa77b0949c and 29b5585702e5e025, and
2492                 # possibly eb9cd59d45ad2908
2493                 my $was = extract_from_file('hints/openbsd.sh',
2494                                             qr/lddlflags="(-shared(?: -fPIC)?) \$lddlflags"/);
2495
2496                 apply_patch(sprintf <<'EOPATCH', $was);
2497 --- a/hints/openbsd.sh  2011-10-21 17:25:20.000000000 +0200
2498 +++ b/hints/openbsd.sh  2011-10-21 16:58:43.000000000 +0200
2499 @@ -44,11 +44,21 @@
2500         [01].*|2.[0-7]|2.[0-7].*)
2501                 lddlflags="-Bshareable $lddlflags"
2502                 ;;
2503 -       *) # from 2.8 onwards
2504 +       2.[8-9]|3.0)
2505                 ld=${cc:-cc}
2506 -               lddlflags="%s $lddlflags"
2507 +               lddlflags="-shared -fPIC $lddlflags"
2508 +               ;;
2509 +       *) # from 3.1 onwards
2510 +               ld=${cc:-cc}
2511 +               lddlflags="-shared -fPIC $lddlflags"
2512 +               libswanted=`echo $libswanted | sed 's/ dl / /'`
2513                 ;;
2514         esac
2515 +
2516 +       # We need to force ld to export symbols on ELF platforms.
2517 +       # Without this, dlopen() is crippled.
2518 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
2519 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
2520         ;;
2521  esac
2522  
2523 EOPATCH
2524             } elsif ($which eq '3.1'
2525                      && !extract_from_file('hints/openbsd.sh',
2526                                            qr/We need to force ld to export symbols on ELF platforms/)) {
2527                 # This is part of 29b5585702e5e025
2528                 apply_patch(<<'EOPATCH');
2529 diff --git a/hints/openbsd.sh b/hints/openbsd.sh
2530 index c6b6bc9..4839d04 100644
2531 --- a/hints/openbsd.sh
2532 +++ b/hints/openbsd.sh
2533 @@ -54,6 +54,11 @@ alpha-2.[0-8]|mips-*|vax-*|powerpc-2.[0-7]|m88k-*)
2534                 libswanted=`echo $libswanted | sed 's/ dl / /'`
2535                 ;;
2536         esac
2537 +
2538 +       # We need to force ld to export symbols on ELF platforms.
2539 +       # Without this, dlopen() is crippled.
2540 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
2541 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
2542         ;;
2543  esac
2544  
2545 EOPATCH
2546             }
2547         }
2548     } elsif ($^O eq 'linux') {
2549         if ($major < 1) {
2550             # sparc linux seems to need the -Dbool=char -DHAS_BOOL part of
2551             # perl5.000 patch.0n: [address Configure and build issues]
2552             edit_file('hints/linux.sh', sub {
2553                           my $code = shift;
2554                           $code =~ s!-I/usr/include/bsd!-Dbool=char -DHAS_BOOL!g;
2555                           return $code;
2556                       });
2557         }
2558
2559         if ($major <= 9) {
2560             if (`uname -sm` =~ qr/^Linux sparc/) {
2561                 if (extract_from_file('hints/linux.sh', qr/sparc-linux/)) {
2562                     # Be sure to use -fPIC not -fpic on Linux/SPARC
2563                     apply_commit('f6527d0ef0c13ad4');
2564                 } elsif(!extract_from_file('hints/linux.sh',
2565                                            qr/^sparc-linux\)$/)) {
2566                     my $fh = open_or_die('hints/linux.sh', '>>');
2567                     print $fh <<'EOT' or die_255($!);
2568
2569 case "`uname -m`" in
2570 sparc*)
2571         case "$cccdlflags" in
2572         *-fpic*) cccdlflags="`echo $cccdlflags|sed 's/-fpic/-fPIC/'`" ;;
2573         *)       cccdlflags="$cccdlflags -fPIC" ;;
2574         esac
2575         ;;
2576 esac
2577 EOT
2578                     close_or_die($fh);
2579                 }
2580             }
2581         }
2582     } elsif ($^O eq 'solaris') {
2583         if (($major == 13 || $major == 14)
2584             && extract_from_file('hints/solaris_2.sh', qr/getconfldllflags/)) {
2585             apply_commit('c80bde4388070c45');
2586         }
2587     }
2588 }
2589
2590 sub patch_SH {
2591     # Cwd.xs added in commit 0d2079faa739aaa9. Cwd.pm moved to ext/ 8 years
2592     # later in commit 403f501d5b37ebf0
2593     if ($major > 0 && <*/Cwd/Cwd.xs>) {
2594         if ($major < 10
2595             && !extract_from_file('Makefile.SH', qr/^extra_dep=''$/)) {
2596             # The Makefile.PL for Unicode::Normalize needs
2597             # lib/unicore/CombiningClass.pl. Even without a parallel build, we
2598             # need a dependency to ensure that it builds. This is a variant of
2599             # commit 9f3ef600c170f61e. Putting this for earlier versions gives
2600             # us a spot on which to hang the edits below
2601             apply_patch(<<'EOPATCH');
2602 diff --git a/Makefile.SH b/Makefile.SH
2603 index f61d0db..6097954 100644
2604 --- a/Makefile.SH
2605 +++ b/Makefile.SH
2606 @@ -155,10 +155,20 @@ esac
2607  
2608  : Prepare dependency lists for Makefile.
2609  dynamic_list=' '
2610 +extra_dep=''
2611  for f in $dynamic_ext; do
2612      : the dependency named here will never exist
2613        base=`echo "$f" | sed 's/.*\///'`
2614 -    dynamic_list="$dynamic_list lib/auto/$f/$base.$dlext"
2615 +    this_target="lib/auto/$f/$base.$dlext"
2616 +    dynamic_list="$dynamic_list $this_target"
2617 +
2618 +    : Parallel makes reveal that we have some interdependencies
2619 +    case $f in
2620 +       Math/BigInt/FastCalc) extra_dep="$extra_dep
2621 +$this_target: lib/auto/List/Util/Util.$dlext" ;;
2622 +       Unicode/Normalize) extra_dep="$extra_dep
2623 +$this_target: lib/unicore/CombiningClass.pl" ;;
2624 +    esac
2625  done
2626  
2627  static_list=' '
2628 @@ -987,2 +997,9 @@ n_dummy $(nonxs_ext):       miniperl$(EXE_EXT) preplibrary $(DYNALOADER) FORCE
2629         @$(LDLIBPTH) sh ext/util/make_ext nonxs $@ MAKE=$(MAKE) LIBPERL_A=$(LIBPERL)
2630 +!NO!SUBS!
2631 +
2632 +$spitshell >>Makefile <<EOF
2633 +$extra_dep
2634 +EOF
2635 +
2636 +$spitshell >>Makefile <<'!NO!SUBS!'
2637  
2638 EOPATCH
2639         }
2640
2641         if ($major == 15 && $^O !~ /^(linux|darwin|.*bsd)$/
2642             && extract_from_file('Makefile.SH', qr/^V.* \?= /)) {
2643             # Remove the GNU-make-ism (which the BSD makes also support, but
2644             # most other makes choke on)
2645             apply_patch(<<'EOPATCH');
2646 diff --git a/Makefile.SH b/Makefile.SH
2647 index 94952bd..13e9001 100755
2648 --- a/Makefile.SH
2649 +++ b/Makefile.SH
2650 @@ -338,8 +338,8 @@ linux*|darwin)
2651  $spitshell >>$Makefile <<!GROK!THIS!
2652  # If you're going to use valgrind and it can't be invoked as plain valgrind
2653  # then you'll need to change this, or override it on the make command line.
2654 -VALGRIND ?= valgrind
2655 -VG_TEST  ?= ./perl -e 1 2>/dev/null
2656 +VALGRIND = valgrind
2657 +VG_TEST  = ./perl -e 1 2>/dev/null
2658  
2659  !GROK!THIS!
2660         ;;
2661 EOPATCH
2662         }
2663
2664         if ($major == 11) {
2665             if (extract_from_file('patchlevel.h',
2666                                   qr/^#include "unpushed\.h"/)) {
2667                 # I had thought it easier to detect when building one of the 52
2668                 # commits with the original method of incorporating the git
2669                 # revision and drop parallel make flags. Commits shown by
2670                 # git log 46807d8e809cc127^..dcff826f70bf3f64^ ^d4fb0a1f15d1a1c4
2671                 # However, it's not actually possible to make miniperl for that
2672                 # configuration as-is, because the file .patchnum is only made
2673                 # as a side effect of target 'all'
2674                 # I also don't think that it's "safe" to simply run
2675                 # make_patchnum.sh before the build. We need the proper
2676                 # dependency rules in the Makefile to *stop* it being run again
2677                 # at the wrong time.
2678                 # This range is important because contains the commit that
2679                 # merges Schwern's y2038 work.
2680                 apply_patch(<<'EOPATCH');
2681 diff --git a/Makefile.SH b/Makefile.SH
2682 index 9ad8b6f..106e721 100644
2683 --- a/Makefile.SH
2684 +++ b/Makefile.SH
2685 @@ -540,9 +544,14 @@ sperl.i: perl.c $(h)
2686  
2687  .PHONY: all translators utilities make_patchnum
2688  
2689 -make_patchnum:
2690 +make_patchnum: lib/Config_git.pl
2691 +
2692 +lib/Config_git.pl: make_patchnum.sh
2693         sh $(shellflags) make_patchnum.sh
2694  
2695 +# .patchnum, unpushed.h and lib/Config_git.pl are built by make_patchnum.sh
2696 +unpushed.h .patchnum: lib/Config_git.pl
2697 +
2698  # make sure that we recompile perl.c if .patchnum changes
2699  perl$(OBJ_EXT): .patchnum unpushed.h
2700  
2701 EOPATCH
2702             } elsif (-f '.gitignore'
2703                      && extract_from_file('.gitignore', qr/^\.patchnum$/)) {
2704                 # 8565263ab8a47cda to 46807d8e809cc127^ inclusive.
2705                 edit_file('Makefile.SH', sub {
2706                               my $code = shift;
2707                               $code =~ s/^make_patchnum:\n/make_patchnum: .patchnum
2708
2709 .sha1: .patchnum
2710
2711 .patchnum: make_patchnum.sh
2712 /m;
2713                               return $code;
2714                           });
2715             } elsif (-f 'lib/.gitignore'
2716                      && extract_from_file('lib/.gitignore',
2717                                           qr!^/Config_git.pl!)
2718                      && !extract_from_file('Makefile.SH',
2719                                         qr/^uudmap\.h.*:bitcount.h$/)) {
2720                 # Between commits and dcff826f70bf3f64 and 0f13ebd5d71f8177^
2721                 edit_file('Makefile.SH', sub {
2722                               my $code = shift;
2723                               # Bug introduced by 344af494c35a9f0f
2724                               # fixed in 0f13ebd5d71f8177
2725                               $code =~ s{^(pod/perlapi\.pod) (pod/perlintern\.pod): }
2726                                         {$1: $2\n\n$2: }m;
2727                               # Bug introduced by efa50c51e3301a2c
2728                               # fixed in 0f13ebd5d71f8177
2729                               $code =~ s{^(uudmap\.h) (bitcount\.h): }
2730                                         {$1: $2\n\n$2: }m;
2731
2732                               # The rats nest of getting git_version.h correct
2733
2734                               if ($code =~ s{git_version\.h: stock_git_version\.h
2735 \tcp stock_git_version\.h git_version\.h}
2736                                             {}m) {
2737                                   # before 486cd780047ff224
2738
2739                                   # We probably can't build between
2740                                   # 953f6acfa20ec275^ and 8565263ab8a47cda
2741                                   # inclusive, but all commits in that range
2742                                   # relate to getting make_patchnum.sh working,
2743                                   # so it is extremely unlikely to be an
2744                                   # interesting bisect target. They will skip.
2745
2746                                   # No, don't spawn a submake if
2747                                   # make_patchnum.sh or make_patchnum.pl fails
2748                                   $code =~ s{\|\| \$\(MAKE\) miniperl.*}
2749                                             {}m;
2750                                   $code =~ s{^\t(sh.*make_patchnum\.sh.*)}
2751                                             {\t-$1}m;
2752
2753                                   # Use an external perl to run make_patchnum.pl
2754                                   # because miniperl still depends on
2755                                   # git_version.h
2756                                   $code =~ s{^\t.*make_patchnum\.pl}
2757                                             {\t-$^X make_patchnum.pl}m;
2758
2759
2760                                   # "Truth in advertising" - running
2761                                   # make_patchnum generates 2 files.
2762                                   $code =~ s{^make_patchnum:.*}{
2763 make_patchnum: lib/Config_git.pl
2764
2765 git_version.h: lib/Config_git.pl
2766
2767 perlmini\$(OBJ_EXT): git_version.h
2768
2769 lib/Config_git.pl:}m;
2770                               }
2771                               # Right, now we've corrected Makefile.SH to
2772                               # correctly describe how lib/Config_git.pl and
2773                               # git_version.h are made, we need to fix the rest
2774
2775                               # This emulates commit 2b63e250843b907e
2776                               # This might duplicate the rule stating that
2777                               # git_version.h depends on lib/Config_git.pl
2778                               # This is harmless.
2779                               $code =~ s{^(?:lib/Config_git\.pl )?git_version\.h: (.* make_patchnum\.pl.*)}
2780                                         {git_version.h: lib/Config_git.pl
2781
2782 lib/Config_git.pl: $1}m;
2783
2784                               # This emulates commits 0f13ebd5d71f8177 and
2785                               # and a04d4598adc57886. It ensures that
2786                               # lib/Config_git.pl is built before configpm,
2787                               # and that configpm is run exactly once.
2788                               $code =~ s{^(\$\(.*?\) )?(\$\(CONFIGPOD\))(: .*? configpm Porting/Glossary)( lib/Config_git\.pl)?}{
2789                                   # If present, other files depend on $(CONFIGPOD)
2790                                   ($1 ? "$1: $2\n\n" : '')
2791                                       # Then the rule we found
2792                                       . $2 . $3
2793                                           # Add dependency if not there
2794                                           . ($4 ? $4 : ' lib/Config_git.pl')
2795                               }me;
2796
2797                               return $code;
2798                           });
2799             }
2800         }
2801
2802         if ($major < 14) {
2803             # Commits dc0655f797469c47 and d11a62fe01f2ecb2
2804             edit_file('Makefile.SH', sub {
2805                           my $code = shift;
2806                           foreach my $ext (qw(Encode SDBM_File)) {
2807                               next if $code =~ /\b$ext\) extra_dep=/s;
2808                               $code =~ s!(\) extra_dep="\$extra_dep
2809 \$this_target: .*?" ;;)
2810 (    esac
2811 )!$1
2812         $ext) extra_dep="\$extra_dep
2813 \$this_target: lib/auto/Cwd/Cwd.\$dlext" ;;
2814 $2!;
2815                           }
2816                           return $code;
2817                       });
2818         }
2819     }
2820
2821     if ($major == 7) {
2822         # Remove commits 9fec149bb652b6e9 and 5bab1179608f81d8, which add/amend
2823         # rules to automatically run regen scripts that rebuild C headers. These
2824         # cause problems because a git checkout doesn't preserve relative file
2825         # modification times, hence the regen scripts may fire. This will
2826         # obscure whether the repository had the correct generated headers
2827         # checked in.
2828         # Also, the dependency rules for running the scripts were not correct,
2829         # which could cause spurious re-builds on re-running make, and can cause
2830         # complete build failures for a parallel make.
2831         if (extract_from_file('Makefile.SH',
2832                               qr/Writing it this way gives make a big hint to always run opcode\.pl before/)) {
2833             apply_commit('70c6e6715e8fec53');
2834         } elsif (extract_from_file('Makefile.SH',
2835                                    qr/^opcode\.h opnames\.h pp_proto\.h pp\.sym: opcode\.pl$/)) {
2836             revert_commit('9fec149bb652b6e9');
2837         }
2838     }
2839
2840     if ($^O eq 'aix' && $major >= 11 && $major <= 15
2841         && extract_from_file('makedef.pl', qr/^use Config/)) {
2842         edit_file('Makefile.SH', sub {
2843                       # The AIX part of commit e6807d8ab22b761c
2844                       # It's safe to substitute lib/Config.pm for config.sh
2845                       # as lib/Config.pm depends on config.sh
2846                       # If the tree is post e6807d8ab22b761c, the substitution
2847                       # won't match, which is harmless.
2848                       my $code = shift;
2849                       $code =~ s{^(perl\.exp:.* )config\.sh(\b.*)}
2850                                 {$1 . '$(CONFIGPM)' . $2}me;
2851                       return $code;
2852                   });
2853     }
2854
2855     # There was a bug in makedepend.SH which was fixed in version 96a8704c.
2856     # Symptom was './makedepend: 1: Syntax error: Unterminated quoted string'
2857     # Remove this if you're actually bisecting a problem related to
2858     # makedepend.SH
2859     # If you do this, you may need to add in code to correct the output of older
2860     # makedepends, which don't correctly filter newer gcc output such as
2861     # <built-in>
2862     checkout_file('makedepend.SH');
2863
2864     if ($major < 4 && -f 'config.sh'
2865         && !extract_from_file('config.sh', qr/^trnl=/)) {
2866         # This seems to be necessary to avoid makedepend becoming confused,
2867         # and hanging on stdin. Seems that the code after
2868         # make shlist || ...here... is never run.
2869         edit_file('makedepend.SH', sub {
2870                       my $code = shift;
2871                       $code =~ s/^trnl='\$trnl'$/trnl='\\n'/m;
2872                       return $code;
2873                   });
2874     }
2875 }
2876
2877 sub patch_C {
2878     # This is ordered by $major, as it's likely that different platforms may
2879     # well want to share code.
2880
2881     if ($major == 2 && extract_from_file('perl.c', qr/^\tfclose\(e_fp\);$/)) {
2882         # need to patch perl.c to avoid calling fclose() twice on e_fp when
2883         # using -e
2884         # This diff is part of commit ab821d7fdc14a438. The second close was
2885         # introduced with perl-5.002, commit a5f75d667838e8e7
2886         # Might want a6c477ed8d4864e6 too, for the corresponding change to
2887         # pp_ctl.c (likely without this, eval will have "fun")
2888         apply_patch(<<'EOPATCH');
2889 diff --git a/perl.c b/perl.c
2890 index 03c4d48..3c814a2 100644
2891 --- a/perl.c
2892 +++ b/perl.c
2893 @@ -252,6 +252,7 @@ setuid perl scripts securely.\n");
2894  #ifndef VMS  /* VMS doesn't have environ array */
2895      origenviron = environ;
2896  #endif
2897 +    e_tmpname = Nullch;
2898  
2899      if (do_undump) {
2900  
2901 @@ -405,6 +406,7 @@ setuid perl scripts securely.\n");
2902      if (e_fp) {
2903         if (Fflush(e_fp) || ferror(e_fp) || fclose(e_fp))
2904             croak("Can't write to temp file for -e: %s", Strerror(errno));
2905 +       e_fp = Nullfp;
2906         argc++,argv--;
2907         scriptname = e_tmpname;
2908      }
2909 @@ -470,10 +472,10 @@ setuid perl scripts securely.\n");
2910      curcop->cop_line = 0;
2911      curstash = defstash;
2912      preprocess = FALSE;
2913 -    if (e_fp) {
2914 -       fclose(e_fp);
2915 -       e_fp = Nullfp;
2916 +    if (e_tmpname) {
2917         (void)UNLINK(e_tmpname);
2918 +       Safefree(e_tmpname);
2919 +       e_tmpname = Nullch;
2920      }
2921  
2922      /* now that script is parsed, we can modify record separator */
2923 @@ -1369,7 +1371,7 @@ SV *sv;
2924         scriptname = xfound;
2925      }
2926  
2927 -    origfilename = savepv(e_fp ? "-e" : scriptname);
2928 +    origfilename = savepv(e_tmpname ? "-e" : scriptname);
2929      curcop->cop_filegv = gv_fetchfile(origfilename);
2930      if (strEQ(origfilename,"-"))
2931         scriptname = "";
2932
2933 EOPATCH
2934     }
2935
2936     if ($major < 3 && $^O eq 'openbsd'
2937         && !extract_from_file('pp_sys.c', qr/BSD_GETPGRP/)) {
2938         # Part of commit c3293030fd1b7489
2939         apply_patch(<<'EOPATCH');
2940 diff --git a/pp_sys.c b/pp_sys.c
2941 index 4608a2a..f0c9d1d 100644
2942 --- a/pp_sys.c
2943 +++ b/pp_sys.c
2944 @@ -2903,8 +2903,8 @@ PP(pp_getpgrp)
2945         pid = 0;
2946      else
2947         pid = SvIVx(POPs);
2948 -#ifdef USE_BSDPGRP
2949 -    value = (I32)getpgrp(pid);
2950 +#ifdef BSD_GETPGRP
2951 +    value = (I32)BSD_GETPGRP(pid);
2952  #else
2953      if (pid != 0)
2954         DIE("POSIX getpgrp can't take an argument");
2955 @@ -2933,8 +2933,8 @@ PP(pp_setpgrp)
2956      }
2957  
2958      TAINT_PROPER("setpgrp");
2959 -#ifdef USE_BSDPGRP
2960 -    SETi( setpgrp(pid, pgrp) >= 0 );
2961 +#ifdef BSD_SETPGRP
2962 +    SETi( BSD_SETPGRP(pid, pgrp) >= 0 );
2963  #else
2964      if ((pgrp != 0) || (pid != 0)) {
2965         DIE("POSIX setpgrp can't take an argument");
2966 EOPATCH
2967     }
2968
2969     if ($major < 4 && $^O eq 'openbsd') {
2970         my $bad;
2971         # Need changes from commit a6e633defa583ad5.
2972         # Commits c07a80fdfe3926b5 and f82b3d4130164d5f changed the same part
2973         # of perl.h
2974
2975         if (extract_from_file('perl.h',
2976                               qr/^#ifdef HAS_GETPGRP2$/)) {
2977             $bad = <<'EOBAD';
2978 ***************
2979 *** 57,71 ****
2980   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
2981   #define TAINT_ENV()   if (tainting) taint_env()
2982   
2983 ! #ifdef HAS_GETPGRP2
2984 ! #   ifndef HAS_GETPGRP
2985 ! #     define HAS_GETPGRP
2986 ! #   endif
2987 ! #endif
2988
2989 ! #ifdef HAS_SETPGRP2
2990 ! #   ifndef HAS_SETPGRP
2991 ! #     define HAS_SETPGRP
2992 ! #   endif
2993   #endif
2994   
2995 EOBAD
2996         } elsif (extract_from_file('perl.h',
2997                                    qr/Gack, you have one but not both of getpgrp2/)) {
2998             $bad = <<'EOBAD';
2999 ***************
3000 *** 56,76 ****
3001   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
3002   #define TAINT_ENV()   if (tainting) taint_env()
3003   
3004 ! #if defined(HAS_GETPGRP2) && defined(HAS_SETPGRP2)
3005 ! #   define getpgrp getpgrp2
3006 ! #   define setpgrp setpgrp2
3007 ! #   ifndef HAS_GETPGRP
3008 ! #     define HAS_GETPGRP
3009 ! #   endif
3010 ! #   ifndef HAS_SETPGRP
3011 ! #     define HAS_SETPGRP
3012 ! #   endif
3013 ! #   ifndef USE_BSDPGRP
3014 ! #     define USE_BSDPGRP
3015 ! #   endif
3016 ! #else
3017 ! #   if defined(HAS_GETPGRP2) || defined(HAS_SETPGRP2)
3018 !       #include "Gack, you have one but not both of getpgrp2() and setpgrp2()."
3019 ! #   endif
3020   #endif
3021   
3022 EOBAD
3023         } elsif (extract_from_file('perl.h',
3024                                    qr/^#ifdef USE_BSDPGRP$/)) {
3025             $bad = <<'EOBAD'
3026 ***************
3027 *** 91,116 ****
3028   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
3029   #define TAINT_ENV()   if (tainting) taint_env()
3030   
3031 ! #ifdef USE_BSDPGRP
3032 ! #   ifdef HAS_GETPGRP
3033 ! #       define BSD_GETPGRP(pid) getpgrp((pid))
3034 ! #   endif
3035 ! #   ifdef HAS_SETPGRP
3036 ! #       define BSD_SETPGRP(pid, pgrp) setpgrp((pid), (pgrp))
3037 ! #   endif
3038 ! #else
3039 ! #   ifdef HAS_GETPGRP2
3040 ! #       define BSD_GETPGRP(pid) getpgrp2((pid))
3041 ! #       ifndef HAS_GETPGRP
3042 ! #         define HAS_GETPGRP
3043 ! #     endif
3044 ! #   endif
3045 ! #   ifdef HAS_SETPGRP2
3046 ! #       define BSD_SETPGRP(pid, pgrp) setpgrp2((pid), (pgrp))
3047 ! #       ifndef HAS_SETPGRP
3048 ! #         define HAS_SETPGRP
3049 ! #     endif
3050 ! #   endif
3051   #endif
3052   
3053   #ifndef _TYPES_               /* If types.h defines this it's easy. */
3054 EOBAD
3055         }
3056         if ($bad) {
3057             apply_patch(<<"EOPATCH");
3058 *** a/perl.h    2011-10-21 09:46:12.000000000 +0200
3059 --- b/perl.h    2011-10-21 09:46:12.000000000 +0200
3060 $bad--- 91,144 ----
3061   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
3062   #define TAINT_ENV()   if (tainting) taint_env()
3063   
3064 ! /* XXX All process group stuff is handled in pp_sys.c.  Should these 
3065 !    defines move there?  If so, I could simplify this a lot. --AD  9/96.
3066 ! */
3067 ! /* Process group stuff changed from traditional BSD to POSIX.
3068 !    perlfunc.pod documents the traditional BSD-style syntax, so we'll
3069 !    try to preserve that, if possible.
3070 ! */
3071 ! #ifdef HAS_SETPGID
3072 ! #  define BSD_SETPGRP(pid, pgrp)      setpgid((pid), (pgrp))
3073 ! #else
3074 ! #  if defined(HAS_SETPGRP) && defined(USE_BSD_SETPGRP)
3075 ! #    define BSD_SETPGRP(pid, pgrp)    setpgrp((pid), (pgrp))
3076 ! #  else
3077 ! #    ifdef HAS_SETPGRP2  /* DG/UX */
3078 ! #      define BSD_SETPGRP(pid, pgrp)  setpgrp2((pid), (pgrp))
3079 ! #    endif
3080 ! #  endif
3081 ! #endif
3082 ! #if defined(BSD_SETPGRP) && !defined(HAS_SETPGRP)
3083 ! #  define HAS_SETPGRP  /* Well, effectively it does . . . */
3084 ! #endif
3085
3086 ! /* getpgid isn't POSIX, but at least Solaris and Linux have it, and it makes
3087 !     our life easier :-) so we'll try it.
3088 ! */
3089 ! #ifdef HAS_GETPGID
3090 ! #  define BSD_GETPGRP(pid)            getpgid((pid))
3091 ! #else
3092 ! #  if defined(HAS_GETPGRP) && defined(USE_BSD_GETPGRP)
3093 ! #    define BSD_GETPGRP(pid)          getpgrp((pid))
3094 ! #  else
3095 ! #    ifdef HAS_GETPGRP2  /* DG/UX */
3096 ! #      define BSD_GETPGRP(pid)                getpgrp2((pid))
3097 ! #    endif
3098 ! #  endif
3099 ! #endif
3100 ! #if defined(BSD_GETPGRP) && !defined(HAS_GETPGRP)
3101 ! #  define HAS_GETPGRP  /* Well, effectively it does . . . */
3102 ! #endif
3103
3104 ! /* These are not exact synonyms, since setpgrp() and getpgrp() may 
3105 !    have different behaviors, but perl.h used to define USE_BSDPGRP
3106 !    (prior to 5.003_05) so some extension might depend on it.
3107 ! */
3108 ! #if defined(USE_BSD_SETPGRP) || defined(USE_BSD_GETPGRP)
3109 ! #  ifndef USE_BSDPGRP
3110 ! #    define USE_BSDPGRP
3111 ! #  endif
3112   #endif
3113   
3114   #ifndef _TYPES_               /* If types.h defines this it's easy. */
3115 EOPATCH
3116         }
3117     }
3118
3119     if ($major < 4 && $^O eq 'hpux'
3120         && extract_from_file('sv.c', qr/i = _filbuf\(/)) {
3121             apply_patch(<<'EOPATCH');
3122 diff --git a/sv.c b/sv.c
3123 index a1f1d60..0a806f1 100644
3124 --- a/sv.c
3125 +++ b/sv.c
3126 @@ -2641,7 +2641,7 @@ I32 append;
3127  
3128         FILE_cnt(fp) = cnt;             /* deregisterize cnt and ptr */
3129         FILE_ptr(fp) = ptr;
3130 -       i = _filbuf(fp);                /* get more characters */
3131 +       i = __filbuf(fp);               /* get more characters */
3132         cnt = FILE_cnt(fp);
3133         ptr = FILE_ptr(fp);             /* reregisterize cnt and ptr */
3134  
3135
3136 EOPATCH
3137     }
3138
3139     if ($major == 4 && extract_from_file('scope.c', qr/\(SV\*\)SSPOPINT/)) {
3140         # [PATCH] 5.004_04 +MAINT_TRIAL_1 broken when sizeof(int) != sizeof(void)
3141         # Fixes a bug introduced in 161b7d1635bc830b
3142         apply_commit('9002cb76ec83ef7f');
3143     }
3144
3145     if ($major == 4 && extract_from_file('av.c', qr/AvARRAY\(av\) = 0;/)) {
3146         # Fixes a bug introduced in 1393e20655efb4bc
3147         apply_commit('e1c148c28bf3335b', 'av.c');
3148     }
3149
3150     if ($major == 4) {
3151         my $rest = extract_from_file('perl.c', qr/delimcpy(.*)/);
3152         if (defined $rest and $rest !~ /,$/) {
3153             # delimcpy added in fc36a67e8855d031, perl.c refactored to use it.
3154             # bug introduced in 2a92aaa05aa1acbf, fixed in 8490252049bf42d3
3155             # code then moved to util.c in commit 491527d0220de34e
3156             apply_patch(<<'EOPATCH');
3157 diff --git a/perl.c b/perl.c
3158 index 4eb69e3..54bbb00 100644
3159 --- a/perl.c
3160 +++ b/perl.c
3161 @@ -1735,7 +1735,7 @@ SV *sv;
3162             if (len < sizeof tokenbuf)
3163                 tokenbuf[len] = '\0';
3164  #else  /* ! (atarist || DOSISH) */
3165 -           s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend
3166 +           s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
3167                          ':',
3168                          &len);
3169  #endif /* ! (atarist || DOSISH) */
3170 EOPATCH
3171         }
3172     }
3173
3174     if ($major == 4 && $^O eq 'linux') {
3175         # Whilst this is fixed properly in f0784f6a4c3e45e1 which provides the
3176         # Configure probe, it's easier to back out the problematic changes made
3177         # in these previous commits.
3178
3179         # In maint-5.004, the simplest addition is to "correct" the file to
3180         # use the same pre-processor macros as blead had used. Whilst commit
3181         # 9b599b2a63d2324d (reverted below) is described as
3182         # [win32] merge change#887 from maintbranch
3183         # it uses __sun__ and __svr4__ instead of the __sun and __SVR4 of the
3184         # maint branch commit 6cdf74fe31f049dc
3185
3186         edit_file('doio.c', sub {
3187                       my $code = shift;
3188                       $code =~ s{defined\(__sun\) && defined\(__SVR4\)}
3189                                 {defined(__sun__) && defined(__svr4__)}g;
3190                       return $code;
3191                   });
3192
3193         if (extract_from_file('doio.c',
3194                               qr!^/\* XXX REALLY need metaconfig test \*/$!)) {
3195             revert_commit('4682965a1447ea44', 'doio.c');
3196         }
3197         if (my $token = extract_from_file('doio.c',
3198                                           qr!^#if (defined\(__sun(?:__)?\)) && defined\(__svr4__\) /\* XXX Need metaconfig test \*/$!)) {
3199             my $patch = `git show -R 9b599b2a63d2324d doio.c`;
3200             $patch =~ s/defined\(__sun__\)/$token/g;
3201             apply_patch($patch);
3202         }
3203         if (extract_from_file('doio.c',
3204                               qr!^/\* linux \(and Solaris2\?\) uses :$!)) {
3205             revert_commit('8490252049bf42d3', 'doio.c');
3206         }
3207         if (extract_from_file('doio.c',
3208                               qr/^          unsemds.buf = &semds;$/)) {
3209             revert_commit('8e591e46b4c6543e');
3210         }
3211         if (extract_from_file('doio.c',
3212                               qr!^#ifdef __linux__      /\* XXX Need metaconfig test \*/$!)) {
3213             # Reverts part of commit 3e3baf6d63945cb6
3214             apply_patch(<<'EOPATCH');
3215 diff --git b/doio.c a/doio.c
3216 index 62b7de9..0d57425 100644
3217 --- b/doio.c
3218 +++ a/doio.c
3219 @@ -1333,9 +1331,6 @@ SV **sp;
3220      char *a;
3221      I32 id, n, cmd, infosize, getinfo;
3222      I32 ret = -1;
3223 -#ifdef __linux__       /* XXX Need metaconfig test */
3224 -    union semun unsemds;
3225 -#endif
3226  
3227      id = SvIVx(*++mark);
3228      n = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
3229 @@ -1364,29 +1359,11 @@ SV **sp;
3230             infosize = sizeof(struct semid_ds);
3231         else if (cmd == GETALL || cmd == SETALL)
3232         {
3233 -#ifdef __linux__       /* XXX Need metaconfig test */
3234 -/* linux uses :
3235 -   int semctl (int semid, int semnun, int cmd, union semun arg)
3236 -
3237 -       union semun {
3238 -            int val;
3239 -            struct semid_ds *buf;
3240 -            ushort *array;
3241 -       };
3242 -*/
3243 -            union semun semds;
3244 -           if (semctl(id, 0, IPC_STAT, semds) == -1)
3245 -#else
3246             struct semid_ds semds;
3247             if (semctl(id, 0, IPC_STAT, &semds) == -1)
3248 -#endif
3249                 return -1;
3250             getinfo = (cmd == GETALL);
3251 -#ifdef __linux__       /* XXX Need metaconfig test */
3252 -           infosize = semds.buf->sem_nsems * sizeof(short);
3253 -#else
3254             infosize = semds.sem_nsems * sizeof(short);
3255 -#endif
3256                 /* "short" is technically wrong but much more portable
3257                    than guessing about u_?short(_t)? */
3258         }
3259 @@ -1429,12 +1406,7 @@ SV **sp;
3260  #endif
3261  #ifdef HAS_SEM
3262      case OP_SEMCTL:
3263 -#ifdef __linux__       /* XXX Need metaconfig test */
3264 -        unsemds.buf = (struct semid_ds *)a;
3265 -       ret = semctl(id, n, cmd, unsemds);
3266 -#else
3267         ret = semctl(id, n, cmd, (struct semid_ds *)a);
3268 -#endif
3269         break;
3270  #endif
3271  #ifdef HAS_SHM
3272 EOPATCH
3273         }
3274         # Incorrect prototype added as part of 8ac853655d9b7447, fixed as part
3275         # of commit dc45a647708b6c54, with at least one intermediate
3276         # modification. Correct prototype for gethostbyaddr has socklen_t
3277         # second. Linux has uint32_t first for getnetbyaddr.
3278         # Easiest just to remove, instead of attempting more complex patching.
3279         # Something similar may be needed on other platforms.
3280         edit_file('pp_sys.c', sub {
3281                       my $code = shift;
3282                       $code =~ s/^    struct hostent \*(?:PerlSock_)?gethostbyaddr\([^)]+\);$//m;
3283                       $code =~ s/^    struct netent \*getnetbyaddr\([^)]+\);$//m;
3284                       return $code;
3285                   });
3286     }
3287
3288     if ($major < 5 && $^O eq 'aix'
3289         && !extract_from_file('pp_sys.c',
3290                               qr/defined\(HOST_NOT_FOUND\) && !defined\(h_errno\)/)) {
3291         # part of commit dc45a647708b6c54
3292         # Andy Dougherty's configuration patches (Config_63-01 up to 04).
3293         apply_patch(<<'EOPATCH')
3294 diff --git a/pp_sys.c b/pp_sys.c
3295 index c2fcb6f..efa39fb 100644
3296 --- a/pp_sys.c
3297 +++ b/pp_sys.c
3298 @@ -54,7 +54,7 @@ extern "C" int syscall(unsigned long,...);
3299  #endif
3300  #endif
3301  
3302 -#ifdef HOST_NOT_FOUND
3303 +#if defined(HOST_NOT_FOUND) && !defined(h_errno)
3304  extern int h_errno;
3305  #endif
3306  
3307 EOPATCH
3308     }
3309
3310     if ($major == 5
3311         && `git rev-parse HEAD` eq "22c35a8c2392967a5ba6b5370695be464bd7012c\n") {
3312         # Commit 22c35a8c2392967a is significant,
3313         # "phase 1 of somewhat major rearrangement of PERL_OBJECT stuff"
3314         # but doesn't build due to 2 simple errors. blead in this broken state
3315         # was merged to the cfgperl branch, and then these were immediately
3316         # corrected there. cfgperl (with the fixes) was merged back to blead.
3317         # The resultant rather twisty maze of commits looks like this:
3318
3319 =begin comment
3320
3321 * | |   commit 137225782c183172f360c827424b9b9f8adbef0e
3322 |\ \ \  Merge: 22c35a8 2a8ee23
3323 | |/ /  Author: Gurusamy Sarathy <gsar@cpan.org>
3324 | | |   Date:   Fri Oct 30 17:38:36 1998 +0000
3325 | | |
3326 | | |       integrate cfgperl tweaks into mainline
3327 | | |
3328 | | |       p4raw-id: //depot/perl@2144
3329 | | |
3330 | * | commit 2a8ee23279873759693fa83eca279355db2b665c
3331 | | | Author: Jarkko Hietaniemi <jhi@iki.fi>
3332 | | | Date:   Fri Oct 30 13:27:39 1998 +0000
3333 | | |
3334 | | |     There can be multiple yacc/bison errors.
3335 | | |
3336 | | |     p4raw-id: //depot/cfgperl@2143
3337 | | |
3338 | * | commit 93fb2ac393172fc3e2c14edb20b718309198abbc
3339 | | | Author: Jarkko Hietaniemi <jhi@iki.fi>
3340 | | | Date:   Fri Oct 30 13:18:43 1998 +0000
3341 | | |
3342 | | |     README.posix-bc update.
3343 | | |
3344 | | |     p4raw-id: //depot/cfgperl@2142
3345 | | |
3346 | * | commit 4ec43091e8e6657cb260b5e563df30aaa154effe
3347 | | | Author: Jarkko Hietaniemi <jhi@iki.fi>
3348 | | | Date:   Fri Oct 30 09:12:59 1998 +0000
3349 | | |
3350 | | |     #2133 fallout.
3351 | | |
3352 | | |     p4raw-id: //depot/cfgperl@2141
3353 | | |
3354 | * |   commit 134ca994cfefe0f613d43505a885e4fc2100b05c
3355 | |\ \  Merge: 7093112 22c35a8
3356 | |/ /  Author: Jarkko Hietaniemi <jhi@iki.fi>
3357 |/| |   Date:   Fri Oct 30 08:43:18 1998 +0000
3358 | | |
3359 | | |       Integrate from mainperl.
3360 | | |
3361 | | |       p4raw-id: //depot/cfgperl@2140
3362 | | |
3363 * | | commit 22c35a8c2392967a5ba6b5370695be464bd7012c
3364 | | | Author: Gurusamy Sarathy <gsar@cpan.org>
3365 | | | Date:   Fri Oct 30 02:51:39 1998 +0000
3366 | | |
3367 | | |     phase 1 of somewhat major rearrangement of PERL_OBJECT stuff
3368 | | |     (objpp.h is gone, embed.pl now does some of that); objXSUB.h
3369 | | |     should soon be automated also; the global variables that
3370 | | |     escaped the PL_foo conversion are now reined in; renamed
3371 | | |     MAGIC in regcomp.h to REG_MAGIC to avoid collision with the
3372 | | |     type of same name; duplicated lists of pp_things in various
3373 | | |     places is now gone; result has only been tested on win32
3374 | | |
3375 | | |     p4raw-id: //depot/perl@2133
3376
3377 =end comment
3378
3379 =cut
3380
3381         # and completely confuses git bisect (and at least me), causing it to
3382         # the bisect run to confidently return the wrong answer, an unrelated
3383         # commit on the cfgperl branch.
3384
3385         apply_commit('4ec43091e8e6657c');
3386     }
3387
3388     if ($major == 5
3389         && extract_from_file('pp_sys.c', qr/PERL_EFF_ACCESS_R_OK/)
3390         && !extract_from_file('pp_sys.c', qr/XXX Configure test needed for eaccess/)) {
3391         # Between 5ff3f7a4e03a6b10 and c955f1177b2e311d^
3392         # This is the meat of commit c955f1177b2e311d (without the other
3393         # indenting changes that would cause a conflict).
3394         # Without this 538 revisions won't build on (at least) Linux
3395         apply_patch(<<'EOPATCH');
3396 diff --git a/pp_sys.c b/pp_sys.c
3397 index d60c8dc..867dee4 100644
3398 --- a/pp_sys.c
3399 +++ b/pp_sys.c
3400 @@ -198,9 +198,18 @@ static char zero_but_true[ZBTLEN + 1] = "0 but true";
3401  #   if defined(I_SYS_SECURITY)
3402  #       include <sys/security.h>
3403  #   endif
3404 -#   define PERL_EFF_ACCESS_R_OK(p) (eaccess((p), R_OK, ACC_SELF))
3405 -#   define PERL_EFF_ACCESS_W_OK(p) (eaccess((p), W_OK, ACC_SELF))
3406 -#   define PERL_EFF_ACCESS_X_OK(p) (eaccess((p), X_OK, ACC_SELF))
3407 +    /* XXX Configure test needed for eaccess */
3408 +#   ifdef ACC_SELF
3409 +        /* HP SecureWare */
3410 +#       define PERL_EFF_ACCESS_R_OK(p) (eaccess((p), R_OK, ACC_SELF))
3411 +#       define PERL_EFF_ACCESS_W_OK(p) (eaccess((p), W_OK, ACC_SELF))
3412 +#       define PERL_EFF_ACCESS_X_OK(p) (eaccess((p), X_OK, ACC_SELF))
3413 +#   else
3414 +        /* SCO */
3415 +#       define PERL_EFF_ACCESS_R_OK(p) (eaccess((p), R_OK))
3416 +#       define PERL_EFF_ACCESS_W_OK(p) (eaccess((p), W_OK))
3417 +#       define PERL_EFF_ACCESS_X_OK(p) (eaccess((p), X_OK))
3418 +#   endif
3419  #endif
3420  
3421  #if !defined(PERL_EFF_ACCESS_R_OK) && defined(HAS_ACCESSX) && defined(ACC_SELF)
3422 EOPATCH
3423     }
3424
3425     if ($major == 5
3426         && extract_from_file('mg.c', qr/If we're still on top of the stack, pop us off/)
3427         && !extract_from_file('mg.c', qr/PL_savestack_ix -= popval/)) {
3428         # Fix up commit 455ece5e082708b1:
3429         # SSNEW() API for allocating memory on the savestack
3430         # Message-Id: <tqemtae338.fsf@puma.genscan.com>
3431         # Subject: [PATCH 5.005_51] (was: why SAVEDESTRUCTOR()...)
3432         apply_commit('3c8a44569607336e', 'mg.c');
3433     }
3434
3435     if ($major == 5) {
3436         if (extract_from_file('doop.c', qr/croak\(no_modify\);/)
3437             && extract_from_file('doop.c', qr/croak\(PL_no_modify\);/)) {
3438             # Whilst the log suggests that this would only fix 5 commits, in
3439             # practice this area of history is a complete tarpit, and git bisect
3440             # gets very confused by the skips in the middle of the back and
3441             # forth merging between //depot/perl and //depot/cfgperl
3442             apply_commit('6393042b638dafd3');
3443         }
3444
3445         # One error "fixed" with another:
3446         if (extract_from_file('pp_ctl.c',
3447                               qr/\Qstatic void *docatch_body _((void *o));\E/)) {
3448             apply_commit('5b51e982882955fe');
3449         }
3450         # Which is then fixed by this:
3451         if (extract_from_file('pp_ctl.c',
3452                               qr/\Qstatic void *docatch_body _((valist\E/)) {
3453             apply_commit('47aa779ee4c1a50e');
3454         }
3455
3456         if (extract_from_file('thrdvar.h', qr/PERLVARI\(Tprotect/)
3457             && !extract_from_file('embedvar.h', qr/PL_protect/)) {
3458             # Commit 312caa8e97f1c7ee didn't update embedvar.h
3459             apply_commit('e0284a306d2de082', 'embedvar.h');
3460         }
3461     }
3462
3463     if ($major == 5
3464         && extract_from_file('sv.c',
3465                              qr/PerlDir_close\(IoDIRP\((?:\(IO\*\))?sv\)\);/)
3466         && !(extract_from_file('toke.c',
3467                                qr/\QIoDIRP(FILTER_DATA(AvFILLp(PL_rsfp_filters))) = NULL\E/)
3468              || extract_from_file('toke.c',
3469                                   qr/\QIoDIRP(datasv) = (DIR*)NULL;\E/))) {
3470         # Commit 93578b34124e8a3b, //depot/perl@3298
3471         # close directory handles properly when localized,
3472         # tweaked slightly by commit 1236053a2c722e2b,
3473         # add test case for change#3298
3474         #
3475         # The fix is the last part of:
3476         #
3477         # various fixes for clean build and test on win32; configpm broken,
3478         # needed to open myconfig.SH rather than myconfig; sundry adjustments
3479         # to bytecode stuff; tweaks to DYNAMIC_ENV_FETCH code to make it
3480         # work under win32; getenv_sv() changed to getenv_len() since SVs
3481         # aren't visible in the lower echelons; remove bogus exports from
3482         # config.sym; PERL_OBJECT-ness for C++ exception support; null out
3483         # IoDIRP in filter_del() or sv_free() will attempt to close it
3484         #
3485         # The changed code is modified subsequently by commit e0c198038146b7a4
3486         apply_commit('a6c403648ecd5cc7', 'toke.c');
3487     }
3488
3489     if ($major < 6 && $^O eq 'netbsd'
3490         && !extract_from_file('unixish.h',
3491                               qr/defined\(NSIG\).*defined\(__NetBSD__\)/)) {
3492         apply_patch(<<'EOPATCH')
3493 diff --git a/unixish.h b/unixish.h
3494 index 2a6cbcd..eab2de1 100644
3495 --- a/unixish.h
3496 +++ b/unixish.h
3497 @@ -89,7 +89,7 @@
3498   */
3499  /* #define ALTERNATE_SHEBANG "#!" / **/
3500  
3501 -#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
3502 +#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX) || defined(__NetBSD__)
3503  # include <signal.h>
3504  #endif
3505  
3506 EOPATCH
3507     }
3508
3509     if ($major == 7 && $^O eq 'aix' &&
3510         extract_from_file('ext/List/Util/Util.xs', qr/PUSHBLOCK/)
3511         && !extract_from_file('makedef.pl', qr/^Perl_cxinc/)) {
3512         # Need this to get List::Utils 1.03 and later to compile.
3513         # 1.03 also expects to call Perl_pp_rand. Commit d3632a54487acc5f
3514         # fixes this (for the unthreaded case), but it's not until 1.05,
3515         # two days later, that this is fixed properly.
3516         apply_commit('cbb96eed3f175499');
3517     }
3518
3519     if (($major >= 7 || $major <= 9) && $^O eq 'openbsd'
3520         && `uname -m` eq "sparc64\n"
3521         # added in 2000 by commit cb434fcc98ac25f5:
3522         && extract_from_file('regexec.c',
3523                              qr!/\* No need to save/restore up to this paren \*/!)
3524         # re-indented in 2006 by commit 95b2444054382532:
3525         && extract_from_file('regexec.c', qr/^\t\tCURCUR cc;$/)) {
3526         # Need to work around a bug in (at least) OpenBSD's 4.6's sparc64 #
3527         # compiler ["gcc (GCC) 3.3.5 (propolice)"]. Between commits
3528         # 3ec562b0bffb8b8b (2002) and 1a4fad37125bac3e^ (2005) the darling thing
3529         # fails to compile any code for the statement cc.oldcc = PL_regcc;
3530         #
3531         # If you refactor the code to "fix" that, or force the issue using set
3532         # in the debugger, the stack smashing detection code fires on return
3533         # from S_regmatch(). Turns out that the compiler doesn't allocate any
3534         # (or at least enough) space for cc.
3535         #
3536         # Restore the "uninitialised" value for cc before function exit, and the
3537         # stack smashing code is placated.  "Fix" 3ec562b0bffb8b8b (which
3538         # changes the size of auto variables used elsewhere in S_regmatch), and
3539         # the crash is visible back to bc517b45fdfb539b (which also changes
3540         # buffer sizes). "Unfix" 1a4fad37125bac3e and the crash is visible until
3541         # 5b47454deb66294b.  Problem goes away if you compile with -O, or hack
3542         # the code as below.
3543         #
3544         # Hence this turns out to be a bug in (old) gcc. Not a security bug we
3545         # still need to fix.
3546         apply_patch(<<'EOPATCH');
3547 diff --git a/regexec.c b/regexec.c
3548 index 900b491..6251a0b 100644
3549 --- a/regexec.c
3550 +++ b/regexec.c
3551 @@ -2958,7 +2958,11 @@ S_regmatch(pTHX_ regnode *prog)
3552                                 I,I
3553   *******************************************************************/
3554         case CURLYX: {
3555 -               CURCUR cc;
3556 +           union {
3557 +               CURCUR hack_cc;
3558 +               char hack_buff[sizeof(CURCUR) + 1];
3559 +           } hack;
3560 +#define cc hack.hack_cc
3561                 CHECKPOINT cp = PL_savestack_ix;
3562                 /* No need to save/restore up to this paren */
3563                 I32 parenfloor = scan->flags;
3564 @@ -2983,6 +2987,7 @@ S_regmatch(pTHX_ regnode *prog)
3565                 n = regmatch(PREVOPER(next));   /* start on the WHILEM */
3566                 regcpblow(cp);
3567                 PL_regcc = cc.oldcc;
3568 +#undef cc
3569                 saySAME(n);
3570             }
3571             /* NOT REACHED */
3572 EOPATCH
3573 }
3574
3575     if ($major < 8 && $^O eq 'openbsd'
3576         && !extract_from_file('perl.h', qr/include <unistd\.h>/)) {
3577         # This is part of commit 3f270f98f9305540, applied at a slightly
3578         # different location in perl.h, where the context is stable back to
3579         # 5.000
3580         apply_patch(<<'EOPATCH');
3581 diff --git a/perl.h b/perl.h
3582 index 9418b52..b8b1a7c 100644
3583 --- a/perl.h
3584 +++ b/perl.h
3585 @@ -496,6 +496,10 @@ register struct op *Perl_op asm(stringify(OP_IN_REGISTER));
3586  #   include <sys/param.h>
3587  #endif
3588  
3589 +/* If this causes problems, set i_unistd=undef in the hint file.  */
3590 +#ifdef I_UNISTD
3591 +#   include <unistd.h>
3592 +#endif
3593  
3594  /* Use all the "standard" definitions? */
3595  #if defined(STANDARD_C) && defined(I_STDLIB)
3596 EOPATCH
3597     }
3598 }
3599
3600 sub patch_ext {
3601     if (-f 'ext/POSIX/Makefile.PL'
3602         && extract_from_file('ext/POSIX/Makefile.PL',
3603                              qr/Explicitly avoid including/)) {
3604         # commit 6695a346c41138df, which effectively reverts 170888cff5e2ffb7
3605
3606         # PERL5LIB is populated by make_ext.pl with paths to the modules we need
3607         # to run, don't override this with "../../lib" since that may not have
3608         # been populated yet in a parallel build.
3609         apply_commit('6695a346c41138df');
3610     }
3611
3612     if (-f 'ext/Hash/Util/Makefile.PL'
3613         && extract_from_file('ext/Hash/Util/Makefile.PL',
3614                              qr/\bDIR\b.*'FieldHash'/)) {
3615         # ext/Hash/Util/Makefile.PL should not recurse to FieldHash's Makefile.PL
3616         # *nix, VMS and Win32 all know how to (and have to) call the latter directly.
3617         # As is, targets in ext/Hash/Util/FieldHash get called twice, which may result
3618         # in race conditions, and certainly messes up make clean; make distclean;
3619         apply_commit('550428fe486b1888');
3620     }
3621
3622     if ($major < 8 && $^O eq 'darwin' && !-f 'ext/DynaLoader/dl_dyld.xs') {
3623         checkout_file('ext/DynaLoader/dl_dyld.xs', 'f556e5b971932902');
3624         apply_patch(<<'EOPATCH');
3625 diff -u a/ext/DynaLoader/dl_dyld.xs~ a/ext/DynaLoader/dl_dyld.xs
3626 --- a/ext/DynaLoader/dl_dyld.xs~        2011-10-11 21:41:27.000000000 +0100
3627 +++ b/ext/DynaLoader/dl_dyld.xs 2011-10-11 21:42:20.000000000 +0100
3628 @@ -41,6 +41,35 @@
3629  #include "perl.h"
3630  #include "XSUB.h"
3631  
3632 +#ifndef pTHX
3633 +#  define pTHX         void
3634 +#  define pTHX_
3635 +#endif
3636 +#ifndef aTHX
3637 +#  define aTHX
3638 +#  define aTHX_
3639 +#endif
3640 +#ifndef dTHX
3641 +#  define dTHXa(a)     extern int Perl___notused(void)
3642 +#  define dTHX         extern int Perl___notused(void)
3643 +#endif
3644 +
3645 +#ifndef Perl_form_nocontext
3646 +#  define Perl_form_nocontext form
3647 +#endif
3648 +
3649 +#ifndef Perl_warn_nocontext
3650 +#  define Perl_warn_nocontext warn
3651 +#endif
3652 +
3653 +#ifndef PTR2IV
3654 +#  define PTR2IV(p)    (IV)(p)
3655 +#endif
3656 +
3657 +#ifndef get_av
3658 +#  define get_av perl_get_av
3659 +#endif
3660 +
3661  #define DL_LOADONCEONLY
3662  
3663  #include "dlutils.c"   /* SaveError() etc      */
3664 @@ -185,7 +191,7 @@
3665      CODE:
3666      DLDEBUG(1,PerlIO_printf(Perl_debug_log, "dl_load_file(%s,%x):\n", filename,flags));
3667      if (flags & 0x01)
3668 -       Perl_warn(aTHX_ "Can't make loaded symbols global on this platform while loading %s",filename);
3669 +       Perl_warn_nocontext("Can't make loaded symbols global on this platform while loading %s",filename);
3670      RETVAL = dlopen(filename, mode) ;
3671      DLDEBUG(2,PerlIO_printf(Perl_debug_log, " libref=%x\n", RETVAL));
3672      ST(0) = sv_newmortal() ;
3673 EOPATCH
3674         if ($major < 4 && !extract_from_file('util.c', qr/^form/m)) {
3675             apply_patch(<<'EOPATCH');
3676 diff -u a/ext/DynaLoader/dl_dyld.xs~ a/ext/DynaLoader/dl_dyld.xs
3677 --- a/ext/DynaLoader/dl_dyld.xs~        2011-10-11 21:56:25.000000000 +0100
3678 +++ b/ext/DynaLoader/dl_dyld.xs 2011-10-11 22:00:00.000000000 +0100
3679 @@ -60,6 +60,18 @@
3680  #  define get_av perl_get_av
3681  #endif
3682  
3683 +static char *
3684 +form(char *pat, ...)
3685 +{
3686 +    char *retval;
3687 +    va_list args;
3688 +    va_start(args, pat);
3689 +    vasprintf(&retval, pat, &args);
3690 +    va_end(args);
3691 +    SAVEFREEPV(retval);
3692 +    return retval;
3693 +}
3694 +
3695  #define DL_LOADONCEONLY
3696  
3697  #include "dlutils.c"   /* SaveError() etc      */
3698 EOPATCH
3699         }
3700     }
3701
3702     if ($major < 10) {
3703         if ($unfixable_db_file) {
3704             # Nothing we can do.
3705         } elsif (!extract_from_file('ext/DB_File/DB_File.xs',
3706                                     qr/^#ifdef AT_LEAST_DB_4_1$/)) {
3707             # This line is changed by commit 3245f0580c13b3ab
3708             my $line = extract_from_file('ext/DB_File/DB_File.xs',
3709                                          qr/^(        status = \(?RETVAL->dbp->open\)?\(RETVAL->dbp, name, NULL, RETVAL->type, $)/);
3710             apply_patch(<<"EOPATCH");
3711 diff --git a/ext/DB_File/DB_File.xs b/ext/DB_File/DB_File.xs
3712 index 489ba96..fba8ded 100644
3713 --- a/ext/DB_File/DB_File.xs
3714 +++ b/ext/DB_File/DB_File.xs
3715 \@\@ -183,4 +187,8 \@\@
3716  #endif
3717  
3718 +#if DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 1)
3719 +#    define AT_LEAST_DB_4_1
3720 +#endif
3721 +
3722  /* map version 2 features & constants onto their version 1 equivalent */
3723  
3724 \@\@ -1334,7 +1419,12 \@\@ SV *   sv ;
3725  #endif
3726  
3727 +#ifdef AT_LEAST_DB_4_1
3728 +        status = (RETVAL->dbp->open)(RETVAL->dbp, NULL, name, NULL, RETVAL->type, 
3729 +                               Flags, mode) ; 
3730 +#else
3731  $line
3732                                 Flags, mode) ; 
3733 +#endif
3734         /* printf("open returned %d %s\\n", status, db_strerror(status)) ; */
3735  
3736 EOPATCH
3737         }
3738     }
3739
3740     if ($major < 10 and -f 'ext/IPC/SysV/SysV.xs') {
3741         edit_file('ext/IPC/SysV/SysV.xs', sub {
3742                       my $xs = shift;
3743                       my $fixed = <<'EOFIX';
3744
3745 #include <sys/types.h>
3746 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
3747 #ifndef HAS_SEM
3748 #   include <sys/ipc.h>
3749 #endif
3750 #   ifdef HAS_MSG
3751 #       include <sys/msg.h>
3752 #   endif
3753 #   ifdef HAS_SHM
3754 #       if defined(PERL_SCO) || defined(PERL_ISC)
3755 #           include <sys/sysmacros.h>   /* SHMLBA */
3756 #       endif
3757 #      include <sys/shm.h>
3758 #      ifndef HAS_SHMAT_PROTOTYPE
3759            extern Shmat_t shmat (int, char *, int);
3760 #      endif
3761 #      if defined(HAS_SYSCONF) && defined(_SC_PAGESIZE)
3762 #          undef  SHMLBA /* not static: determined at boot time */
3763 #          define SHMLBA sysconf(_SC_PAGESIZE)
3764 #      elif defined(HAS_GETPAGESIZE)
3765 #          undef  SHMLBA /* not static: determined at boot time */
3766 #          define SHMLBA getpagesize()
3767 #      endif
3768 #   endif
3769 #endif
3770 EOFIX
3771                       $xs =~ s!
3772 #include <sys/types\.h>
3773 .*
3774 (#ifdef newCONSTSUB|/\* Required)!$fixed$1!ms;
3775                       return $xs;
3776                   });
3777     }
3778 }
3779
3780 sub apply_fixups {
3781     my $fixups = shift;
3782     return unless $fixups;
3783     foreach my $file (@$fixups) {
3784         my $fh = open_or_die($file);
3785         my $line = <$fh>;
3786         close_or_die($fh);
3787         if ($line =~ /^#!perl\b/) {
3788             system $^X, $file
3789                 and die_255("$^X $file failed: \$!=$!, \$?=$?");
3790         } elsif ($line =~ /^#!(\/\S+)/) {
3791             system $file
3792                 and die_255("$file failed: \$!=$!, \$?=$?");
3793         } else {
3794             if (my ($target, $action, $pattern)
3795                 = $line =~ m#^(\S+) ([=!])~ /(.*)/#) {
3796                 if (length $pattern) {
3797                     next unless -f $target;
3798                     if ($action eq '=') {
3799                         next unless extract_from_file($target, $pattern);
3800                     } else {
3801                         next if extract_from_file($target, $pattern);
3802                     }
3803                 } else {
3804                     # Avoid the special case meaning of the empty pattern,
3805                     # and instead use this to simply test for the file being
3806                     # present or absent
3807                     if ($action eq '=') {
3808                         next unless -f $target;
3809                     } else {
3810                         next if -f $target;
3811                     }
3812                 }
3813             }
3814             system_or_die("patch -p1 <$file");
3815         }
3816     }
3817 }
3818
3819 # ex: set ts=8 sts=4 sw=4 et: