This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
bisect-runner.pl should avoid ext/Hash/Util/FieldHash being built twice.
[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 Carp;
8
9 my @targets
10     = qw(config.sh config.h miniperl lib/Config.pm Fcntl perl test_prep);
11
12 my $cpus;
13 if (open my $fh, '<', '/proc/cpuinfo') {
14     while (<$fh>) {
15         ++$cpus if /^processor\s+:\s+\d+$/;
16     }
17 } elsif (-x '/sbin/sysctl') {
18     $cpus = 1 + $1 if `/sbin/sysctl hw.ncpu` =~ /^hw\.ncpu: (\d+)$/;
19 } elsif (-x '/usr/bin/getconf') {
20     $cpus = 1 + $1 if `/usr/bin/getconf _NPROCESSORS_ONLN` =~ /^(\d+)$/;
21 }
22
23 my %options =
24     (
25      jobs => defined $cpus ? $cpus + 1 : 2,
26      'expect-pass' => 1,
27      clean => 1, # mostly for debugging this
28     );
29
30 my $linux64 = `uname -sm` eq "Linux x86_64\n" ? '64' : '';
31
32 my @paths;
33
34 if ($^O eq 'linux') {
35     # This is the search logic for a multi-arch library layout
36     # added to linux.sh in commits 40f026236b9959b7 and dcffd848632af2c7.
37     my $gcc = -x '/usr/bin/gcc' ? '/usr/bin/gcc' : 'gcc';
38
39     foreach (`$gcc -print-search-dirs`) {
40         next unless /^libraries: =(.*)/;
41         foreach (split ':', $1) {
42             next if m/gcc/;
43             next unless -d $_;
44             s!/$!!;
45             push @paths, $_;
46         }
47     }
48 }
49
50 push @paths, map {$_ . $linux64} qw(/usr/local/lib /lib /usr/lib);
51
52 my %defines =
53     (
54      usedevel => '',
55      optimize => '-g',
56      cc => (`ccache --version`, $?) ? 'cc' : 'ccache cc',
57      ld => 'cc',
58      ($linux64 ? (libpth => \@paths) : ()),
59     );
60
61 unless(GetOptions(\%options,
62                   'target=s', 'make=s', 'jobs|j=i', 'expect-pass=i',
63                   'expect-fail' => sub { $options{'expect-pass'} = 0; },
64                   'clean!', 'one-liner|e=s', 'match=s', 'force-manifest',
65                   'force-regen', 'test-build', 'A=s@', 'l', 'w',
66                   'check-args', 'check-shebang!', 'usage|help|?', 'validate',
67                   'D=s@' => sub {
68                       my (undef, $val) = @_;
69                       if ($val =~ /\A([^=]+)=(.*)/s) {
70                           $defines{$1} = length $2 ? $2 : "\0";
71                       } else {
72                           $defines{$val} = '';
73                       }
74                   },
75                   'U=s@' => sub {
76                       $defines{$_[1]} = undef;
77                   },
78                  )) {
79     pod2usage(exitval => 255, verbose => 1);
80 }
81
82 my ($target, $j, $match) = @options{qw(target jobs match)};
83
84 @ARGV = ('sh', '-c', 'cd t && ./perl TEST base/*.t')
85     if $options{validate} && !@ARGV;
86
87 pod2usage(exitval => 255, verbose => 1) if $options{usage};
88 pod2usage(exitval => 255, verbose => 1)
89     unless @ARGV || $match || $options{'test-build'} || defined $options{'one-liner'};
90 pod2usage(exitval => 255, verbose => 1)
91     if !$options{'one-liner'} && ($options{l} || $options{w});
92
93 check_shebang($ARGV[0]) if $options{'check-shebang'} && @ARGV;
94
95 exit 0 if $options{'check-args'};
96
97 =head1 NAME
98
99 bisect.pl - use git bisect to pinpoint changes
100
101 =head1 SYNOPSIS
102
103     # When did this become an error?
104     .../Porting/bisect.pl -e 'my $a := 2;'
105     # When did this stop being an error?
106     .../Porting/bisect.pl --expect-fail -e '1 // 2'
107     # When did this stop matching?
108     .../Porting/bisect.pl --match '\b(?:PL_)hash_seed_set\b'
109     # When did this start matching?
110     .../Porting/bisect.pl --expect-fail --match '\buseithreads\b'
111     # When did this test program stop working?
112     .../Porting/bisect.pl -- ./perl -Ilib ../test_prog.pl
113     # When did this first become valid syntax?
114     .../Porting/bisect.pl --target=miniperl --end=v5.10.0 \
115          --expect-fail -e 'my $a := 2;'
116     # What was the last revision to build with these options?
117     .../Porting/bisect.pl --test-build -Dd_dosuid
118
119 =head1 DESCRIPTION
120
121 Together F<bisect.pl> and F<bisect-runner.pl> attempt to automate the use
122 of C<git bisect> as much as possible. With one command (and no other files)
123 it's easy to find out
124
125 =over 4
126
127 =item *
128
129 Which commit caused this example code to break?
130
131 =item *
132
133 Which commit caused this example code to start working?
134
135 =item *
136
137 Which commit added the first to match this regex?
138
139 =item *
140
141 Which commit removed the last to match this regex?
142
143 =back
144
145 usually without needing to know which versions of perl to use as start and
146 end revisions.
147
148 By default F<bisect.pl> will process all options, then use the rest of the
149 command line as arguments to list C<system> to run a test case. By default,
150 the test case should pass (exit with 0) on earlier perls, and fail (exit
151 non-zero) on I<blead>. F<bisect.pl> will use F<bisect-runner.pl> to find the
152 earliest stable perl version on which the test case passes, check that it
153 fails on blead, and then use F<bisect-runner.pl> with C<git bisect run> to
154 find the commit which caused the failure.
155
156 Because the test case is the complete argument to C<system>, it is easy to
157 run something other than the F<perl> built, if necessary. If you need to run
158 the perl built, you'll probably need to invoke it as C<./perl -Ilib ...>
159
160 You need a clean checkout to run a bisect, and you can't use the checkout
161 which contains F<Porting/bisect.pl> (because C<git bisect>) will check out
162 a revision before F<Porting/bisect-runner.pl> was added, which
163 C<git bisect run> needs). If your working checkout is called F<perl>, the
164 simplest solution is to make a local clone, and run from that. I<i.e.>:
165
166     cd ..
167     git clone perl perl2
168     cd perl2
169     ../perl/Porting/bisect.pl ...
170
171 By default, F<bisect-runner.pl> will automatically disable the build of
172 L<DB_File> for commits earlier than ccb44e3bf3be2c30, as it's not practical
173 to patch DB_File 1.70 and earlier to build with current Berkeley DB headers.
174 (ccb44e3bf3be2c30 was in September 1999, between 5.005_62 and 5.005_63.)
175 If your F<db.h> is old enough you can override this with C<-Unoextensions>.
176
177 =head1 OPTIONS
178
179 =over 4
180
181 =item *
182
183 --start I<commit-ish>
184
185 Earliest revision to test, as a I<commit-ish> (a tag, commit or anything
186 else C<git> understands as a revision). If not specified, F<bisect.pl> will
187 search stable perl releases from 5.002 to 5.14.0 until it finds one where
188 the test case passes.
189
190 =item *
191
192 --end I<commit-ish>
193
194 Most recent revision to test, as a I<commit-ish>. If not specified, defaults
195 to I<blead>.
196
197 =item *
198
199 --target I<target>
200
201 F<Makefile> target (or equivalent) needed, to run the test case. If specified,
202 this should be one of
203
204 =over 4
205
206 =item *
207
208 I<config.sh>
209
210 Just run F<./Configure>
211
212 =item *
213
214 I<config.h>
215
216 Run the various F<*.SH> files to generate F<Makefile>, F<config.h>, I<etc>.
217
218 =item *
219
220 I<miniperl>
221
222 Build F<miniperl>.
223
224 =item *
225
226 I<lib/Config.pm>
227
228 Use F<miniperl> to build F<lib/Config.pm>
229
230 =item *
231
232 I<Fcntl>
233
234 Build F<lib/auto/Fcntl/Fnctl.so> (strictly, C<.$Config{so}>). As L<Fcntl>
235 is simple XS module present since 5.000, this provides a fast test of
236 whether XS modules can be built. Note, XS modules are built by F<miniperl>,
237 hence this target will not build F<perl>.
238
239 =item *
240
241 I<perl>
242
243 Build F<perl>. This also builds pure-Perl modules in F<cpan>, F<dist> and
244 F<ext>. XS modules (such as L<Fcntl>) are not built.
245
246 =item *
247
248 I<test_prep>
249
250 Build everything needed to run the tests. This is the default if we're
251 running test code, but is time consuming, as it means building all
252 XS modules. For older F<Makefile>s, the previous name of C<test-prep>
253 is automatically substituted. For very old F<Makefile>s, C<make test> is
254 run, as there is no target provided to just get things ready, and for 5.004
255 and earlier the tests run very quickly.
256
257 =back
258
259 =item *
260
261 --one-liner 'code to run'
262
263 =item *
264
265 -e 'code to run'
266
267 Example code to run, just like you'd use with C<perl -e>.
268
269 This prepends C<./perl -Ilib -e 'code to run'> to the test case given,
270 or F<./miniperl> if I<target> is C<miniperl>.
271
272 (Usually you'll use C<-e> instead of providing a test case in the
273 non-option arguments to F<bisect.pl>)
274
275 C<-E> intentionally isn't supported, as it's an error in 5.8.0 and earlier,
276 which interferes with detecting errors in the example code itself.
277
278 =item *
279
280 -l
281
282 Add C<-l> to the command line with C<-e>
283
284 This will automatically append a newline to every output line of your testcase.
285 Note that you can't specify an argument to F<perl>'s C<-l> with this, as it's
286 not feasible to emulate F<perl>'s somewhat quirky switch parsing with
287 L<Getopt::Long>. If you need the full flexibility of C<-l>, you need to write
288 a full test case, instead of using C<bisect.pl>'s C<-e> shortcut.
289
290 =item *
291
292 -w
293
294 Add C<-w> to the command line with C<-e>
295
296 It's not valid to pass C<-l> or C<-w> to C<bisect.pl> unless you are also
297 using C<-e>
298
299 =item *
300
301 --expect-fail
302
303 The test case should fail for the I<start> revision, and pass for the I<end>
304 revision. The bisect run will find the first commit where it passes.
305
306 =item *
307
308 -Dnoextensions=Encode
309
310 =item *
311
312 -Uusedevel
313
314 =item *
315
316 -Accflags=-DNO_MATHOMS
317
318 Arguments to pass to F<Configure>. Repeated C<-A> arguments are passed
319 through as is. C<-D> and C<-U> are processed in order, and override
320 previous settings for the same parameter. F<bisect-runner.pl> emulates
321 C<-Dnoextensions> when F<Configure> itself does not provide it, as it's
322 often very useful to be able to disable some XS extensions.
323
324 =item *
325
326 --make I<make-prog>
327
328 The C<make> command to use. If this not set, F<make> is used. If this is
329 set, it also adds a C<-Dmake=...> else some recursive make invocations
330 in extensions may fail. Typically one would use this as C<--make gmake>
331 to use F<gmake> in place of the system F<make>.
332
333 =item *
334
335 --jobs I<jobs>
336
337 =item *
338
339 -j I<jobs>
340
341 Number of C<make> jobs to run in parallel. If F</proc/cpuinfo> exists and
342 can be parsed, or F</sbin/sysctl> exists and reports C<hw.ncpu>, or
343 F</usr/bin/getconf> exists and reports C<_NPROCESSORS_ONLN> defaults to 1 +
344 I<number of CPUs>. Otherwise defaults to 2.
345
346 =item *
347
348 --match pattern
349
350 Instead of running a test program to determine I<pass> or I<fail>, pass
351 if the given regex matches, and hence search for the commit that removes
352 the last matching file.
353
354 If no I<target> is specified, the match is against all files in the
355 repository (which is fast). If a I<target> is specified, that target is
356 built, and the match is against only the built files. C<--expect-fail> can
357 be used with C<--match> to search for a commit that adds files that match.
358
359 =item *
360
361 --test-build
362
363 Test that the build completes, without running any test case.
364
365 By default, if the build for the desired I<target> fails to complete,
366 F<bisect-runner.pl> reports a I<skip> back to C<git bisect>, the assumption
367 being that one wants to find a commit which changed state "builds && passes"
368 to "builds && fails". If instead one is interested in which commit broke the
369 build (possibly for particular F<Configure> options), use I<--test-build>
370 to treat a build failure as a failure, not a "skip".
371
372 Often this option isn't as useful as it first seems, because I<any> build
373 failure will be reported to C<git bisect> as a failure, not just the failure
374 that you're interested in. Generally, to debug a particular problem, it's
375 more useful to use a I<target> that builds properly at the point of interest,
376 and then a test case that runs C<make>. For example:
377
378     .../Porting/bisect.pl --start=perl-5.000 --end=perl-5.002 \
379         --expect-fail --force-manifest --target=miniperl make perl
380
381 will find the first revision capable of building L<DynaLoader> and then
382 F<perl>, without becoming confused by revisions where F<miniperl> won't
383 even link.
384
385 =item *
386
387 --force-manifest
388
389 By default, a build will "skip" if any files listed in F<MANIFEST> are not
390 present. Usually this is useful, as it avoids false-failures. However, there
391 are some long ranges of commits where listed files are missing, which can
392 cause a bisect to abort because all that remain are skipped revisions.
393
394 In these cases, particularly if the test case uses F<miniperl> and no modules,
395 it may be more useful to force the build to continue, even if files
396 F<MANIFEST> are missing.
397
398 =item *
399
400 --force-regen
401
402 Run C<make regen_headers> before building F<miniperl>. This may fix a build
403 that otherwise would skip because the generated headers at that revision
404 are stale. It's not the default because it conceals this error in the true
405 state of such revisions.
406
407 =item *
408
409 --expect-pass [0|1]
410
411 C<--expect-pass=0> is equivalent to C<--expect-fail>. I<1> is the default.
412
413 =item *
414
415 --no-clean
416
417 Tell F<bisect-runner.pl> not to clean up after the build. This allows one
418 to use F<bisect-runner.pl> to build the current particular perl revision for
419 interactive testing, or for debugging F<bisect-runner.pl>.
420
421 Passing this to F<bisect.pl> will likely cause the bisect to fail badly.
422
423 =item *
424
425 --validate
426
427 Test that all stable revisions can be built. By default, attempts to build
428 I<blead>, I<v5.14.0> .. I<perl-5.002>. Stops at the first failure, without
429 cleaning the checkout. Use I<--start> to specify the earliest revision to
430 test, I<--end> to specify the most recent. Useful for validating a new
431 OS/CPU/compiler combination. For example
432
433     ../perl/Porting/bisect.pl --validate -le 'print "Hello from $]"'
434
435 If no testcase is specified, the default is to use F<t/TEST> to run
436 F<t/base/*.t>
437
438 =item *
439
440 --check-args
441
442 Validate the options and arguments, and exit silently if they are valid.
443
444 =item *
445
446 --check-shebang
447
448 Validate that the test case isn't an executable file with a
449 C<#!/usr/bin/perl> line (or similar). As F<bisect-runner.pl> does B<not>
450 prepend C<./perl> to the test case, a I<#!> line specifying an external
451 F<perl> binary will cause the test case to always run with I<that> F<perl>,
452 not the F<perl> built by the bisect runner. Likely this is not what you
453 wanted. If your test case is actually a wrapper script to run other
454 commands, you should run it with an explicit interpreter, to be clear. For
455 example, instead of C<../perl/Porting/bisect.pl ~/test/testcase.pl> you'd
456 run C<../perl/Porting/bisect.pl /usr/bin/perl ~/test/testcase.pl>
457
458 =item *
459
460 --usage
461
462 =item *
463
464 --help
465
466 =item *
467
468 -?
469
470 Display the usage information and exit.
471
472 =back
473
474 =cut
475
476 die "$0: Can't build $target" if defined $target && !grep {@targets} $target;
477
478 $j = "-j$j" if $j =~ /\A\d+\z/;
479
480 if (exists $options{make}) {
481     if (!exists $defines{make}) {
482         $defines{make} = $options{make};
483     }
484 } else {
485     $options{make} = 'make';
486 }
487
488 # Sadly, however hard we try, I don't think that it will be possible to build
489 # modules in ext/ on x86_64 Linux before commit e1666bf5602ae794 on 1999/12/29,
490 # which updated to MakeMaker 3.7, which changed from using a hard coded ld
491 # in the Makefile to $(LD). On x86_64 Linux the "linker" is gcc.
492
493 sub open_or_die {
494     my $file = shift;
495     my $mode = @_ ? shift : '<';
496     open my $fh, $mode, $file or croak("Can't open $file: $!");
497     ${*$fh{SCALAR}} = $file;
498     return $fh;
499 }
500
501 sub close_or_die {
502     my $fh = shift;
503     return if close $fh;
504     croak("Can't close: $!") unless ref $fh eq 'GLOB';
505     croak("Can't close ${*$fh{SCALAR}}: $!");
506 }
507
508 sub extract_from_file {
509     my ($file, $rx, $default) = @_;
510     my $fh = open_or_die($file);
511     while (<$fh>) {
512         my @got = $_ =~ $rx;
513         return wantarray ? @got : $got[0]
514             if @got;
515     }
516     return $default if defined $default;
517     return;
518 }
519
520 sub edit_file {
521     my ($file, $munger) = @_;
522     local $/;
523     my $fh = open_or_die($file);
524     my $orig = <$fh>;
525     die "Can't read $file: $!" unless defined $orig && close $fh;
526     my $new = $munger->($orig);
527     return if $new eq $orig;
528     $fh = open_or_die($file, '>');
529     print $fh $new or die "Can't print to $file: $!";
530     close_or_die($fh);
531 }
532
533 # AIX supplies a pre-historic patch program, which certainly predates Linux
534 # and is probably older than NT. It can't cope with unified diffs. Meanwhile,
535 # it's hard enough to get git diff to output context diffs, let alone git show,
536 # and nearly all the patches embedded here are unified. So it seems that the
537 # path of least resistance is to convert unified diffs to context diffs:
538
539 sub process_hunk {
540     my ($from_out, $to_out, $has_from, $has_to, $delete, $add) = @_;
541     ++$$has_from if $delete;
542     ++$$has_to if $add;
543
544     if ($delete && $add) {
545         $$from_out .= "! $_\n" foreach @$delete;
546         $$to_out .= "! $_\n" foreach @$add;
547     } elsif ($delete) {
548         $$from_out .= "- $_\n" foreach @$delete;
549     } elsif ($add) {
550          $$to_out .= "+ $_\n" foreach @$add;
551     }
552 }
553
554 # This isn't quite general purpose, as it can't cope with
555 # '\ No newline at end of file'
556 sub ud2cd {
557     my $diff_in = shift;
558     my $diff_out = '';
559
560     # Stuff before the diff
561     while ($diff_in =~ s/\A(?!\*\*\* )(?!--- )([^\n]*\n?)//ms && length $1) {
562         $diff_out .= $1;
563     }
564
565     if (!length $diff_in) {
566         die "That didn't seem to be a diff";
567     }
568
569     if ($diff_in =~ /\A\*\*\* /ms) {
570         warn "Seems to be a context diff already\n";
571         return $diff_out . $diff_in;
572     }
573
574     # Loop for files
575  FILE: while (1) {
576         if ($diff_in =~ s/\A((?:diff |index )[^\n]+\n)//ms) {
577             $diff_out .= $1;
578             next;
579         }
580         if ($diff_in !~ /\A--- /ms) {
581             # Stuff after the diff;
582             return $diff_out . $diff_in;
583         }
584         $diff_in =~ s/\A([^\n]+\n?)//ms;
585         my $line = $1;
586         die "Can't parse '$line'" unless $line =~ s/\A--- /*** /ms;
587         $diff_out .= $line;
588         $diff_in =~ s/\A([^\n]+\n?)//ms;
589         $line = $1;
590         die "Can't parse '$line'" unless $line =~ s/\A\+\+\+ /--- /ms;
591         $diff_out .= $line;
592
593         # Loop for hunks
594         while (1) {
595             next FILE
596                 unless $diff_in =~ s/\A\@\@ (-([0-9]+),([0-9]+) \+([0-9]+),([0-9]+)) \@\@[^\n]*\n?//;
597             my ($hunk, $from_start, $from_count, $to_start, $to_count)
598                 = ($1, $2, $3, $4, $5);
599             my $from_end = $from_start + $from_count - 1;
600             my $to_end = $to_start + $to_count - 1;
601             my ($from_out, $to_out, $has_from, $has_to, $add, $delete);
602             while (length $diff_in && ($from_count || $to_count)) {
603                 die "Confused in $hunk" unless $diff_in =~ s/\A([^\n]*)\n//ms;
604                 my $line = $1;
605                 $line = ' ' unless length $line;
606                 if ($line =~ /^ .*/) {
607                     process_hunk(\$from_out, \$to_out, \$has_from, \$has_to,
608                                  $delete, $add);
609                     undef $delete;
610                     undef $add;
611                     $from_out .= " $line\n";
612                     $to_out .= " $line\n";
613                     --$from_count;
614                     --$to_count;
615                 } elsif ($line =~ /^-(.*)/) {
616                     push @$delete, $1;
617                     --$from_count;
618                 } elsif ($line =~ /^\+(.*)/) {
619                     push @$add, $1;
620                     --$to_count;
621                 } else {
622                     die "Can't parse '$line' as part of hunk $hunk";
623                 }
624             }
625             process_hunk(\$from_out, \$to_out, \$has_from, \$has_to,
626                          $delete, $add);
627             die "No lines in hunk $hunk"
628                 unless length $from_out || length $to_out;
629             die "No changes in hunk $hunk"
630                 unless $has_from || $has_to;
631             $diff_out .= "***************\n";
632             $diff_out .= "*** $from_start,$from_end ****\n";
633             $diff_out .= $from_out if $has_from;
634             $diff_out .= "--- $to_start,$to_end ----\n";
635             $diff_out .= $to_out if $has_to;
636         }
637     }
638 }
639
640 {
641     my $use_context;
642
643     sub placate_patch_prog {
644         my $patch = shift;
645
646         if (!defined $use_context) {
647             my $version = `patch -v 2>&1`;
648             die "Can't run `patch -v`, \$?=$?, bailing out"
649                 unless defined $version;
650             if ($version =~ /Free Software Foundation/) {
651                 $use_context = 0;
652             } elsif ($version =~ /Header: patch\.c,v.*\blwall\b/) {
653                 # The system patch is older than Linux, and probably older than
654                 # Windows NT.
655                 $use_context = 1;
656             } else {
657                 # Don't know.
658                 $use_context = 0;
659             }
660         }
661
662         return $use_context ? ud2cd($patch) : $patch;
663     }
664 }
665
666 sub apply_patch {
667     my ($patch, $what, $files) = @_;
668     $what = 'patch' unless defined $what;
669     unless (defined $files) {
670         $patch =~ m!^--- a/(\S+)\n\+\+\+ b/\1!sm;
671         $files = " $1";
672     }
673     my $patch_to_use = placate_patch_prog($patch);
674     open my $fh, '|-', 'patch', '-p1' or die "Can't run patch: $!";
675     print $fh $patch_to_use;
676     return if close $fh;
677     print STDERR "Patch is <<'EOPATCH'\n${patch}EOPATCH\n";
678     print STDERR "\nConverted to a context diff <<'EOCONTEXT'\n${patch_to_use}EOCONTEXT\n";
679     die "Can't $what$files: $?, $!";
680 }
681
682 sub apply_commit {
683     my ($commit, @files) = @_;
684     my $patch = `git show $commit @files`;
685     if (!defined $patch) {
686         die "Can't get commit $commit for @files: $?" if @files;
687         die "Can't get commit $commit: $?";
688     }
689     apply_patch($patch, "patch $commit", @files ? " for @files" : '');
690 }
691
692 sub revert_commit {
693     my ($commit, @files) = @_;
694     my $patch = `git show -R $commit @files`;
695     if (!defined $patch) {
696         die "Can't get revert commit $commit for @files: $?" if @files;
697         die "Can't get revert commit $commit: $?";
698     }
699     apply_patch($patch, "revert $commit", @files ? " for @files" : '');
700 }
701
702 sub checkout_file {
703     my ($file, $commit) = @_;
704     $commit ||= 'blead';
705     system "git show $commit:$file > $file </dev/null"
706         and die "Could not extract $file at revision $commit";
707 }
708
709 sub check_shebang {
710     my $file = shift;
711     return unless -e $file;
712     if (!-x $file) {
713         die "$file is not executable.
714 system($file, ...) is always going to fail.
715
716 Bailing out";
717     }
718     my $fh = open_or_die($file);
719     my $line = <$fh>;
720     return unless $line =~ m{\A#!(/\S+/perl\S*)\s};
721     die "$file will always be run by $1
722 It won't be tested by the ./perl we build.
723 If you intended to run it with that perl binary, please change your
724 test case to
725
726     $1 @ARGV
727
728 If you intended to test it with the ./perl we build, please change your
729 test case to
730
731     ./perl -Ilib @ARGV
732
733 [You may also need to add -- before ./perl to prevent that -Ilib as being
734 parsed as an argument to bisect.pl]
735
736 Bailing out";
737 }
738
739 sub clean {
740     if ($options{clean}) {
741         # Needed, because files that are build products in this checked out
742         # version might be in git in the next desired version.
743         system 'git clean -dxf </dev/null';
744         # Needed, because at some revisions the build alters checked out files.
745         # (eg pod/perlapi.pod). Also undoes any changes to makedepend.SH
746         system 'git reset --hard HEAD </dev/null';
747     }
748 }
749
750 sub skip {
751     my $reason = shift;
752     clean();
753     warn "skipping - $reason";
754     exit 125;
755 }
756
757 sub report_and_exit {
758     my ($ret, $pass, $fail, $desc) = @_;
759
760     clean();
761
762     my $got = ($options{'expect-pass'} ? !$ret : $ret) ? 'good' : 'bad';
763     if ($ret) {
764         print "$got - $fail $desc\n";
765     } else {
766         print "$got - $pass $desc\n";
767     }
768
769     exit($got eq 'bad');
770 }
771
772 sub match_and_exit {
773     my $target = shift;
774     my $matches = 0;
775     my $re = qr/$match/;
776     my @files;
777
778     {
779         local $/ = "\0";
780         @files = defined $target ? `git ls-files -o -z`: `git ls-files -z`;
781         chomp @files;
782     }
783
784     foreach my $file (@files) {
785         my $fh = open_or_die($file);
786         while (<$fh>) {
787             if ($_ =~ $re) {
788                 ++$matches;
789                 if (tr/\t\r\n -~\200-\377//c) {
790                     print "Binary file $file matches\n";
791                 } else {
792                     $_ .= "\n" unless /\n\z/;
793                     print "$file: $_";
794                 }
795             }
796         }
797         close_or_die($fh);
798     }
799     report_and_exit(!$matches,
800                     $matches == 1 ? '1 match for' : "$matches matches for",
801                     'no matches for', $match);
802 }
803
804 # Not going to assume that system perl is yet new enough to have autodie
805 system 'git clean -dxf </dev/null' and die;
806
807 if (!defined $target) {
808     match_and_exit() if $match;
809     $target = 'test_prep';
810 }
811
812 skip('no Configure - is this the //depot/perlext/Compiler branch?')
813     unless -f 'Configure';
814
815 # This changes to PERL_VERSION in 4d8076ea25903dcb in 1999
816 my $major
817     = extract_from_file('patchlevel.h',
818                         qr/^#define\s+(?:PERL_VERSION|PATCHLEVEL)\s+(\d+)\s/,
819                         0);
820
821 patch_Configure();
822 patch_hints();
823
824 # if Encode is not needed for the test, you can speed up the bisect by
825 # excluding it from the runs with -Dnoextensions=Encode
826 # ccache is an easy win. Remove it if it causes problems.
827 # Commit 1cfa4ec74d4933da adds ignore_versioned_solibs to Configure, and sets it
828 # to true in hints/linux.sh
829 # On dromedary, from that point on, Configure (by default) fails to find any
830 # libraries, because it scans /usr/local/lib /lib /usr/lib, which only contain
831 # versioned libraries. Without -lm, the build fails.
832 # Telling /usr/local/lib64 /lib64 /usr/lib64 works from that commit onwards,
833 # until commit faae14e6e968e1c0 adds it to the hints.
834 # However, prior to 1cfa4ec74d4933da telling Configure the truth doesn't work,
835 # because it will spot versioned libraries, pass them to the compiler, and then
836 # bail out pretty early on. Configure won't let us override libswanted, but it
837 # will let us override the entire libs list.
838
839 unless (extract_from_file('Configure', 'ignore_versioned_solibs')) {
840     # Before 1cfa4ec74d4933da, so force the libs list.
841
842     my @libs;
843     # This is the current libswanted list from Configure, less the libs removed
844     # by current hints/linux.sh
845     foreach my $lib (qw(sfio socket inet nsl nm ndbm gdbm dbm db malloc dl dld
846                         ld sun m crypt sec util c cposix posix ucb BSD)) {
847         foreach my $dir (@paths) {
848             next unless -f "$dir/lib$lib.so";
849             push @libs, "-l$lib";
850             last;
851         }
852     }
853     $defines{libs} = \@libs unless exists $defines{libs};
854 }
855
856 $defines{usenm} = undef
857     if $major < 2 && !exists $defines{usenm};
858
859 my ($missing, $created_dirs);
860 ($missing, $created_dirs) = force_manifest()
861     if $options{'force-manifest'};
862
863 my @ARGS = '-dEs';
864 foreach my $key (sort keys %defines) {
865     my $val = $defines{$key};
866     if (ref $val) {
867         push @ARGS, "-D$key=@$val";
868     } elsif (!defined $val) {
869         push @ARGS, "-U$key";
870     } elsif (!length $val) {
871         push @ARGS, "-D$key";
872     } else {
873         $val = "" if $val eq "\0";
874         push @ARGS, "-D$key=$val";
875     }
876 }
877 push @ARGS, map {"-A$_"} @{$options{A}};
878
879 # </dev/null because it seems that some earlier versions of Configure can
880 # call commands in a way that now has them reading from stdin (and hanging)
881 my $pid = fork;
882 die "Can't fork: $!" unless defined $pid;
883 if (!$pid) {
884     open STDIN, '<', '/dev/null';
885     # If a file in MANIFEST is missing, Configure asks if you want to
886     # continue (the default being 'n'). With stdin closed or /dev/null,
887     # it exits immediately and the check for config.sh below will skip.
888     exec './Configure', @ARGS;
889     die "Failed to start Configure: $!";
890 }
891 waitpid $pid, 0
892     or die "wait for Configure, pid $pid failed: $!";
893
894 patch_SH();
895
896 if (-f 'config.sh') {
897     # Emulate noextensions if Configure doesn't support it.
898     fake_noextensions()
899         if $major < 10 && $defines{noextensions};
900     system './Configure -S </dev/null' and die;
901 }
902
903 if ($target =~ /config\.s?h/) {
904     match_and_exit($target) if $match && -f $target;
905     report_and_exit(!-f $target, 'could build', 'could not build', $target)
906         if $options{'test-build'};
907
908     my $ret = system @ARGV;
909     report_and_exit($ret, 'zero exit from', 'non-zero exit from', "@ARGV");
910 } elsif (!-f 'config.sh') {
911     # Skip if something went wrong with Configure
912
913     skip('could not build config.sh');
914 }
915
916 force_manifest_cleanup($missing, $created_dirs)
917         if $missing;
918
919 if($options{'force-regen'}
920    && extract_from_file('Makefile', qr/\bregen_headers\b/)) {
921     # regen_headers was added in e50aee73b3d4c555, patch.1m for perl5.001
922     # It's not worth faking it for earlier revisions.
923     system "make regen_headers </dev/null"
924         and die;
925 }
926
927 patch_C();
928 patch_ext();
929
930 # Parallel build for miniperl is safe
931 system "$options{make} $j miniperl </dev/null";
932
933 my $expected = $target =~ /^test/ ? 't/perl'
934     : $target eq 'Fcntl' ? "lib/auto/Fcntl/Fcntl.$Config{so}"
935     : $target;
936 my $real_target = $target eq 'Fcntl' ? $expected : $target;
937
938 if ($target ne 'miniperl') {
939     # Nearly all parallel build issues fixed by 5.10.0. Untrustworthy before that.
940     $j = '' if $major < 10;
941
942     if ($real_target eq 'test_prep') {
943         if ($major < 8) {
944             # test-prep was added in 5.004_01, 3e3baf6d63945cb6.
945             # renamed to test_prep in 2001 in 5fe84fd29acaf55c.
946             # earlier than that, just make test. It will be fast enough.
947             $real_target = extract_from_file('Makefile.SH',
948                                              qr/^(test[-_]prep):/,
949                                              'test');
950         }
951     }
952
953     system "$options{make} $j $real_target </dev/null";
954 }
955
956 my $missing_target = $expected =~ /perl$/ ? !-x $expected : !-r $expected;
957
958 if ($options{'test-build'}) {
959     report_and_exit($missing_target, 'could build', 'could not build',
960                     $real_target);
961 } elsif ($missing_target) {
962     skip("could not build $real_target");
963 }
964
965 match_and_exit($real_target) if $match;
966
967 if (defined $options{'one-liner'}) {
968     my $exe = $target =~ /^(?:perl$|test)/ ? 'perl' : 'miniperl';
969     unshift @ARGV, '-e', $options{'one-liner'};
970     unshift @ARGV, '-l' if $options{l};
971     unshift @ARGV, '-w' if $options{w};
972     unshift @ARGV, "./$exe", '-Ilib';
973 }
974
975 # This is what we came here to run:
976
977 if (exists $Config{ldlibpthname}) {
978     require Cwd;
979     my $varname = $Config{ldlibpthname};
980     my $cwd = Cwd::getcwd();
981     if (defined $ENV{$varname}) {
982         $ENV{$varname} = $cwd . $Config{path_sep} . $ENV{$varname};
983     } else {
984         $ENV{$varname} = $cwd;
985     }
986 }
987
988 my $ret = system @ARGV;
989
990 report_and_exit($ret, 'zero exit from', 'non-zero exit from', "@ARGV");
991
992 ############################################################################
993 #
994 # Patching, editing and faking routines only below here.
995 #
996 ############################################################################
997
998 sub fake_noextensions {
999     edit_file('config.sh', sub {
1000                   my @lines = split /\n/, shift;
1001                   my @ext = split /\s+/, $defines{noextensions};
1002                   foreach (@lines) {
1003                       next unless /^extensions=/ || /^dynamic_ext/;
1004                       foreach my $ext (@ext) {
1005                           s/\b$ext( )?\b/$1/;
1006                       }
1007                   }
1008                   return join "\n", @lines;
1009               });
1010 }
1011
1012 sub force_manifest {
1013     my (@missing, @created_dirs);
1014     my $fh = open_or_die('MANIFEST');
1015     while (<$fh>) {
1016         next unless /^(\S+)/;
1017         # -d is special case needed (at least) between 27332437a2ed1941 and
1018         # bf3d9ec563d25054^ inclusive, as manifest contains ext/Thread/Thread
1019         push @missing, $1
1020             unless -f $1 || -d $1;
1021     }
1022     close_or_die($fh);
1023
1024     foreach my $pathname (@missing) {
1025         my @parts = split '/', $pathname;
1026         my $leaf = pop @parts;
1027         my $path = '.';
1028         while (@parts) {
1029             $path .= '/' . shift @parts;
1030             next if -d $path;
1031             mkdir $path, 0700 or die "Can't create $path: $!";
1032             unshift @created_dirs, $path;
1033         }
1034         $fh = open_or_die($pathname, '>');
1035         close_or_die($fh);
1036         chmod 0, $pathname or die "Can't chmod 0 $pathname: $!";
1037     }
1038     return \@missing, \@created_dirs;
1039 }
1040
1041 sub force_manifest_cleanup {
1042     my ($missing, $created_dirs) = @_;
1043     # This is probably way too paranoid:
1044     my @errors;
1045     require Fcntl;
1046     foreach my $file (@$missing) {
1047         my (undef, undef, $mode, undef, undef, undef, undef, $size)
1048             = stat $file;
1049         if (!defined $mode) {
1050             push @errors, "Added file $file has been deleted by Configure";
1051             next;
1052         }
1053         if (Fcntl::S_IMODE($mode) != 0) {
1054             push @errors,
1055                 sprintf 'Added file %s had mode changed by Configure to %03o',
1056                     $file, $mode;
1057         }
1058         if ($size != 0) {
1059             push @errors,
1060                 "Added file $file had sized changed by Configure to $size";
1061         }
1062         unlink $file or die "Can't unlink $file: $!";
1063     }
1064     foreach my $dir (@$created_dirs) {
1065         rmdir $dir or die "Can't rmdir $dir: $!";
1066     }
1067     skip("@errors")
1068         if @errors;
1069 }
1070
1071 sub patch_Configure {
1072     if ($major < 1) {
1073         if (extract_from_file('Configure',
1074                               qr/^\t\t\*=\*\) echo "\$1" >> \$optdef;;$/)) {
1075             # This is "        Spaces now allowed in -D command line options.",
1076             # part of commit ecfc54246c2a6f42
1077             apply_patch(<<'EOPATCH');
1078 diff --git a/Configure b/Configure
1079 index 3d3b38d..78ffe16 100755
1080 --- a/Configure
1081 +++ b/Configure
1082 @@ -652,7 +777,8 @@ while test $# -gt 0; do
1083                         echo "$me: use '-U symbol=', not '-D symbol='." >&2
1084                         echo "$me: ignoring -D $1" >&2
1085                         ;;
1086 -               *=*) echo "$1" >> $optdef;;
1087 +               *=*) echo "$1" | \
1088 +                               sed -e "s/'/'\"'\"'/g" -e "s/=\(.*\)/='\1'/" >> $optdef;;
1089                 *) echo "$1='define'" >> $optdef;;
1090                 esac
1091                 shift
1092 EOPATCH
1093         }
1094
1095         if (extract_from_file('Configure', qr/^if \$contains 'd_namlen' \$xinc\b/)) {
1096             # Configure's original simple "grep" for d_namlen falls foul of the
1097             # approach taken by the glibc headers:
1098             # #ifdef _DIRENT_HAVE_D_NAMLEN
1099             # # define _D_EXACT_NAMLEN(d) ((d)->d_namlen)
1100             #
1101             # where _DIRENT_HAVE_D_NAMLEN is not defined on Linux.
1102             # This is also part of commit ecfc54246c2a6f42
1103             apply_patch(<<'EOPATCH');
1104 diff --git a/Configure b/Configure
1105 index 3d3b38d..78ffe16 100755
1106 --- a/Configure
1107 +++ b/Configure
1108 @@ -3935,7 +4045,8 @@ $rm -f try.c
1109  
1110  : see if the directory entry stores field length
1111  echo " "
1112 -if $contains 'd_namlen' $xinc >/dev/null 2>&1; then
1113 +$cppstdin $cppflags $cppminus < "$xinc" > try.c
1114 +if $contains 'd_namlen' try.c >/dev/null 2>&1; then
1115         echo "Good, your directory entry keeps length information in d_namlen." >&4
1116         val="$define"
1117  else
1118 EOPATCH
1119         }
1120     }
1121
1122     if ($major < 2
1123         && !extract_from_file('Configure',
1124                               qr/Try to guess additional flags to pick up local libraries/)) {
1125         my $mips = extract_from_file('Configure',
1126                                      qr!(''\) if (?:\./)?mips; then)!);
1127         # This is part of perl-5.001n. It's needed, to add -L/usr/local/lib to
1128         # theld flags if libraries are found there. It shifts the code to set up
1129         # libpth earlier, and then adds the code to add libpth entries to
1130         # ldflags
1131         # mips was changed to ./mips in ecfc54246c2a6f42, perl5.000 patch.0g
1132         apply_patch(sprintf <<'EOPATCH', $mips);
1133 diff --git a/Configure b/Configure
1134 index 53649d5..0635a6e 100755
1135 --- a/Configure
1136 +++ b/Configure
1137 @@ -2749,6 +2749,52 @@ EOM
1138         ;;
1139  esac
1140  
1141 +: Set private lib path
1142 +case "$plibpth" in
1143 +'') if ./mips; then
1144 +               plibpth="$incpath/usr/lib /usr/local/lib /usr/ccs/lib"
1145 +       fi;;
1146 +esac
1147 +case "$libpth" in
1148 +' ') dlist='';;
1149 +'') dlist="$plibpth $glibpth";;
1150 +*) dlist="$libpth";;
1151 +esac
1152 +
1153 +: Now check and see which directories actually exist, avoiding duplicates
1154 +libpth=''
1155 +for xxx in $dlist
1156 +do
1157 +    if $test -d $xxx; then
1158 +               case " $libpth " in
1159 +               *" $xxx "*) ;;
1160 +               *) libpth="$libpth $xxx";;
1161 +               esac
1162 +    fi
1163 +done
1164 +$cat <<'EOM'
1165 +
1166 +Some systems have incompatible or broken versions of libraries.  Among
1167 +the directories listed in the question below, please remove any you
1168 +know not to be holding relevant libraries, and add any that are needed.
1169 +Say "none" for none.
1170 +
1171 +EOM
1172 +case "$libpth" in
1173 +'') dflt='none';;
1174 +*)
1175 +       set X $libpth
1176 +       shift
1177 +       dflt=${1+"$@"}
1178 +       ;;
1179 +esac
1180 +rp="Directories to use for library searches?"
1181 +. ./myread
1182 +case "$ans" in
1183 +none) libpth=' ';;
1184 +*) libpth="$ans";;
1185 +esac
1186 +
1187  : flags used in final linking phase
1188  case "$ldflags" in
1189  '') if ./venix; then
1190 @@ -2765,6 +2811,23 @@ case "$ldflags" in
1191         ;;
1192  *) dflt="$ldflags";;
1193  esac
1194 +
1195 +: Possible local library directories to search.
1196 +loclibpth="/usr/local/lib /opt/local/lib /usr/gnu/lib"
1197 +loclibpth="$loclibpth /opt/gnu/lib /usr/GNU/lib /opt/GNU/lib"
1198 +
1199 +: Try to guess additional flags to pick up local libraries.
1200 +for thislibdir in $libpth; do
1201 +       case " $loclibpth " in
1202 +       *" $thislibdir "*)
1203 +               case "$dflt " in 
1204 +               "-L$thislibdir ") ;;
1205 +               *)  dflt="$dflt -L$thislibdir" ;;
1206 +               esac
1207 +               ;;
1208 +       esac
1209 +done
1210 +
1211  echo " "
1212  rp="Any additional ld flags (NOT including libraries)?"
1213  . ./myread
1214 @@ -2828,52 +2891,6 @@ n) echo "OK, that should do.";;
1215  esac
1216  $rm -f try try.* core
1217  
1218 -: Set private lib path
1219 -case "$plibpth" in
1220 -%s
1221 -               plibpth="$incpath/usr/lib /usr/local/lib /usr/ccs/lib"
1222 -       fi;;
1223 -esac
1224 -case "$libpth" in
1225 -' ') dlist='';;
1226 -'') dlist="$plibpth $glibpth";;
1227 -*) dlist="$libpth";;
1228 -esac
1229 -
1230 -: Now check and see which directories actually exist, avoiding duplicates
1231 -libpth=''
1232 -for xxx in $dlist
1233 -do
1234 -    if $test -d $xxx; then
1235 -               case " $libpth " in
1236 -               *" $xxx "*) ;;
1237 -               *) libpth="$libpth $xxx";;
1238 -               esac
1239 -    fi
1240 -done
1241 -$cat <<'EOM'
1242 -
1243 -Some systems have incompatible or broken versions of libraries.  Among
1244 -the directories listed in the question below, please remove any you
1245 -know not to be holding relevant libraries, and add any that are needed.
1246 -Say "none" for none.
1247 -
1248 -EOM
1249 -case "$libpth" in
1250 -'') dflt='none';;
1251 -*)
1252 -       set X $libpth
1253 -       shift
1254 -       dflt=${1+"$@"}
1255 -       ;;
1256 -esac
1257 -rp="Directories to use for library searches?"
1258 -. ./myread
1259 -case "$ans" in
1260 -none) libpth=' ';;
1261 -*) libpth="$ans";;
1262 -esac
1263 -
1264  : compute shared library extension
1265  case "$so" in
1266  '')
1267 EOPATCH
1268     }
1269
1270     if ($major < 5 && extract_from_file('Configure',
1271                                         qr!if \$cc \$ccflags try\.c -o try >/dev/null 2>&1; then!)) {
1272         # Analogous to the more general fix of dfe9444ca7881e71
1273         # Without this flags such as -m64 may not be passed to this compile,
1274         # which results in a byteorder of '1234' instead of '12345678', which
1275         # can then cause crashes.
1276
1277         if (extract_from_file('Configure', qr/xxx_prompt=y/)) {
1278             # 8e07c86ebc651fe9 or later
1279             # ("This is my patch  patch.1n  for perl5.001.")
1280             apply_patch(<<'EOPATCH');
1281 diff --git a/Configure b/Configure
1282 index 62249dd..c5c384e 100755
1283 --- a/Configure
1284 +++ b/Configure
1285 @@ -8247,7 +8247,7 @@ main()
1286  }
1287  EOCP
1288         xxx_prompt=y
1289 -       if $cc $ccflags try.c -o try >/dev/null 2>&1 && ./try > /dev/null; then
1290 +       if $cc $ccflags $ldflags try.c -o try >/dev/null 2>&1 && ./try > /dev/null; then
1291                 dflt=`./try`
1292                 case "$dflt" in
1293                 [1-4][1-4][1-4][1-4]|12345678|87654321)
1294 EOPATCH
1295         } else {
1296             apply_patch(<<'EOPATCH');
1297 diff --git a/Configure b/Configure
1298 index 53649d5..f1cd64a 100755
1299 --- a/Configure
1300 +++ b/Configure
1301 @@ -6362,7 +6362,7 @@ main()
1302         printf("\n");
1303  }
1304  EOCP
1305 -       if $cc $ccflags try.c -o try >/dev/null 2>&1 ; then
1306 +       if $cc $ccflags $ldflags try.c -o try >/dev/null 2>&1 ; then
1307                 dflt=`./try`
1308                 case "$dflt" in
1309                 ????|????????) echo "(The test program ran ok.)";;
1310 EOPATCH
1311         }
1312     }
1313
1314     if ($major < 6 && !extract_from_file('Configure',
1315                                          qr!^\t-A\)$!)) {
1316         # This adds the -A option to Configure, which is incredibly useful
1317         # Effectively this is commits 02e93a22d20fc9a5, 5f83a3e9d818c3ad,
1318         # bde6b06b2c493fef, f7c3111703e46e0c and 2 lines of trailing whitespace
1319         # removed by 613d6c3e99b9decc, but applied at slightly different
1320         # locations to ensure a clean patch back to 5.000
1321         # Note, if considering patching to the intermediate revisions to fix
1322         # bugs in -A handling, f7c3111703e46e0c is from 2002, and hence
1323         # $major == 8
1324
1325         # To add to the fun, early patches add -K and -O options, and it's not
1326         # trivial to get patch to put the C<. ./posthint.sh> in the right place
1327         edit_file('Configure', sub {
1328                       my $code = shift;
1329                       $code =~ s/(optstr = ")([^"]+";\s*# getopt-style specification)/$1A:$2/
1330                           or die "Substitution failed";
1331                       $code =~ s!^(: who configured the system)!
1332 touch posthint.sh
1333 . ./posthint.sh
1334
1335 $1!ms
1336                           or die "Substitution failed";
1337                       return $code;
1338                   });
1339         apply_patch(<<'EOPATCH');
1340 diff --git a/Configure b/Configure
1341 index 4b55fa6..60c3c64 100755
1342 --- a/Configure
1343 +++ b/Configure
1344 @@ -1150,6 +1150,7 @@ set X `for arg in "$@"; do echo "X$arg"; done |
1345  eval "set $*"
1346  shift
1347  rm -f options.awk
1348 +rm -f posthint.sh
1349  
1350  : set up default values
1351  fastread=''
1352 @@ -1172,6 +1173,56 @@ while test $# -gt 0; do
1353         case "$1" in
1354         -d) shift; fastread=yes;;
1355         -e) shift; alldone=cont;;
1356 +       -A)
1357 +           shift
1358 +           xxx=''
1359 +           yyy="$1"
1360 +           zzz=''
1361 +           uuu=undef
1362 +           case "$yyy" in
1363 +            *=*) zzz=`echo "$yyy"|sed 's!=.*!!'`
1364 +                 case "$zzz" in
1365 +                 *:*) zzz='' ;;
1366 +                 *)   xxx=append
1367 +                      zzz=" "`echo "$yyy"|sed 's!^[^=]*=!!'`
1368 +                      yyy=`echo "$yyy"|sed 's!=.*!!'` ;;
1369 +                 esac
1370 +                 ;;
1371 +            esac
1372 +            case "$xxx" in
1373 +            '')  case "$yyy" in
1374 +                 *:*) xxx=`echo "$yyy"|sed 's!:.*!!'`
1375 +                      yyy=`echo "$yyy"|sed 's!^[^:]*:!!'`
1376 +                      zzz=`echo "$yyy"|sed 's!^[^=]*=!!'`
1377 +                      yyy=`echo "$yyy"|sed 's!=.*!!'` ;;
1378 +                 *)   xxx=`echo "$yyy"|sed 's!:.*!!'`
1379 +                      yyy=`echo "$yyy"|sed 's!^[^:]*:!!'` ;;
1380 +                 esac
1381 +                 ;;
1382 +            esac
1383 +           case "$xxx" in
1384 +           append)
1385 +               echo "$yyy=\"\${$yyy}$zzz\""    >> posthint.sh ;;
1386 +           clear)
1387 +               echo "$yyy=''"                  >> posthint.sh ;;
1388 +           define)
1389 +               case "$zzz" in
1390 +               '') zzz=define ;;
1391 +               esac
1392 +               echo "$yyy='$zzz'"              >> posthint.sh ;;
1393 +           eval)
1394 +               echo "eval \"$yyy=$zzz\""       >> posthint.sh ;;
1395 +           prepend)
1396 +               echo "$yyy=\"$zzz\${$yyy}\""    >> posthint.sh ;;
1397 +           undef)
1398 +               case "$zzz" in
1399 +               '') zzz="$uuu" ;;
1400 +               esac
1401 +               echo "$yyy=$zzz"                >> posthint.sh ;;
1402 +            *)  echo "$me: unknown -A command '$xxx', ignoring -A $1" >&2 ;;
1403 +           esac
1404 +           shift
1405 +           ;;
1406         -f)
1407                 shift
1408                 cd ..
1409 EOPATCH
1410     }
1411
1412     if ($major < 8 && $^O eq 'aix') {
1413         edit_file('Configure', sub {
1414                       my $code = shift;
1415                       # Replicate commit a8c676c69574838b
1416                       # Whitespace allowed at the ends of /lib/syscalls.exp lines
1417                       # and half of commit c6912327ae30e6de
1418                       # AIX syscalls.exp scan: the syscall might be marked 32, 3264, or 64
1419                       $code =~ s{(\bsed\b.*\bsyscall)(?:\[0-9\]\*)?(\$.*/lib/syscalls\.exp)}
1420                                 {$1 . "[0-9]*[ \t]*" . $2}e;
1421                       return $code;
1422                   });
1423     }
1424
1425     if ($major < 8 && !extract_from_file('Configure',
1426                                          qr/^\t\tif test ! -t 0; then$/)) {
1427         # Before dfe9444ca7881e71, Configure would refuse to run if stdin was
1428         # not a tty. With that commit, the tty requirement was dropped for -de
1429         # and -dE
1430         # Commit aaeb8e512e8e9e14 dropped the tty requirement for -S
1431         # For those older versions, it's probably easiest if we simply remove
1432         # the sanity test.
1433         edit_file('Configure', sub {
1434                       my $code = shift;
1435                       $code =~ s/test ! -t 0/test Perl = rules/;
1436                       return $code;
1437                   });
1438     }
1439
1440     if ($major == 8 || $major == 9) {
1441         # Fix symbol detection to that of commit 373dfab3839ca168 if it's any
1442         # intermediate version 5129fff43c4fe08c or later, as the intermediate
1443         # versions don't work correctly on (at least) Sparc Linux.
1444         # 5129fff43c4fe08c adds the first mention of mistrustnm.
1445         # 373dfab3839ca168 removes the last mention of lc=""
1446         edit_file('Configure', sub {
1447                       my $code = shift;
1448                       return $code
1449                           if $code !~ /\btc="";/; # 373dfab3839ca168 or later
1450                       return $code
1451                           if $code !~ /\bmistrustnm\b/; # before 5129fff43c4fe08c
1452                       my $fixed = <<'EOC';
1453
1454 : is a C symbol defined?
1455 csym='tlook=$1;
1456 case "$3" in
1457 -v) tf=libc.tmp; tdc="";;
1458 -a) tf=libc.tmp; tdc="[]";;
1459 *) tlook="^$1\$"; tf=libc.list; tdc="()";;
1460 esac;
1461 tx=yes;
1462 case "$reuseval-$4" in
1463 true-) ;;
1464 true-*) tx=no; eval "tval=\$$4"; case "$tval" in "") tx=yes;; esac;;
1465 esac;
1466 case "$tx" in
1467 yes)
1468         tval=false;
1469         if $test "$runnm" = true; then
1470                 if $contains $tlook $tf >/dev/null 2>&1; then
1471                         tval=true;
1472                 elif $test "$mistrustnm" = compile -o "$mistrustnm" = run; then
1473                         echo "void *(*(p()))$tdc { extern void *$1$tdc; return &$1; } int main() { if(p()) return(0); else return(1); }"> try.c;
1474                         $cc -o try $optimize $ccflags $ldflags try.c >/dev/null 2>&1 $libs && tval=true;
1475                         $test "$mistrustnm" = run -a -x try && { $run ./try$_exe >/dev/null 2>&1 || tval=false; };
1476                         $rm -f try$_exe try.c core core.* try.core;
1477                 fi;
1478         else
1479                 echo "void *(*(p()))$tdc { extern void *$1$tdc; return &$1; } int main() { if(p()) return(0); else return(1); }"> try.c;
1480                 $cc -o try $optimize $ccflags $ldflags try.c $libs >/dev/null 2>&1 && tval=true;
1481                 $rm -f try$_exe try.c;
1482         fi;
1483         ;;
1484 *)
1485         case "$tval" in
1486         $define) tval=true;;
1487         *) tval=false;;
1488         esac;
1489         ;;
1490 esac;
1491 eval "$2=$tval"'
1492
1493 EOC
1494                       $code =~ s/\n: is a C symbol defined\?\n.*?\neval "\$2=\$tval"'\n\n/$fixed/sm
1495                           or die "substitution failed";
1496                       return $code;
1497                   });
1498     }
1499
1500     if ($major < 10
1501         && extract_from_file('Configure', qr/^set malloc\.h i_malloc$/)) {
1502         # This is commit 01d07975f7ef0e7d, trimmed, with $compile inlined as
1503         # prior to bd9b35c97ad661cc Configure had the malloc.h test before the
1504         # definition of $compile.
1505         apply_patch(<<'EOPATCH');
1506 diff --git a/Configure b/Configure
1507 index 3d2e8b9..6ce7766 100755
1508 --- a/Configure
1509 +++ b/Configure
1510 @@ -6743,5 +6743,22 @@ set d_dosuid
1511  
1512  : see if this is a malloc.h system
1513 -set malloc.h i_malloc
1514 -eval $inhdr
1515 +: we want a real compile instead of Inhdr because some systems have a
1516 +: malloc.h that just gives a compile error saying to use stdlib.h instead
1517 +echo " "
1518 +$cat >try.c <<EOCP
1519 +#include <stdlib.h>
1520 +#include <malloc.h>
1521 +int main () { return 0; }
1522 +EOCP
1523 +set try
1524 +if $cc $optimize $ccflags $ldflags -o try $* try.c $libs > /dev/null 2>&1; then
1525 +    echo "<malloc.h> found." >&4
1526 +    val="$define"
1527 +else
1528 +    echo "<malloc.h> NOT found." >&4
1529 +    val="$undef"
1530 +fi
1531 +$rm -f try.c try
1532 +set i_malloc
1533 +eval $setvar
1534  
1535 EOPATCH
1536     }
1537 }
1538
1539 sub patch_hints {
1540     if ($^O eq 'freebsd') {
1541         # There are rather too many version-specific FreeBSD hints fixes to
1542         # patch individually. Also, more than once the FreeBSD hints file has
1543         # been written in what turned out to be a rather non-future-proof style,
1544         # with case statements treating the most recent version as the
1545         # exception, instead of treating previous versions' behaviour explicitly
1546         # and changing the default to cater for the current behaviour. (As
1547         # strangely, future versions inherit the current behaviour.)
1548         checkout_file('hints/freebsd.sh');
1549     } elsif ($^O eq 'darwin') {
1550         if ($major < 8) {
1551             # We can't build on darwin without some of the data in the hints
1552             # file. Probably less surprising to use the earliest version of
1553             # hints/darwin.sh and then edit in place just below, than use
1554             # blead's version, as that would create a discontinuity at
1555             # f556e5b971932902 - before it, hints bugs would be "fixed", after
1556             # it they'd resurface. This way, we should give the illusion of
1557             # monotonic bug fixing.
1558             my $faking_it;
1559             if (!-f 'hints/darwin.sh') {
1560                 checkout_file('hints/darwin.sh', 'f556e5b971932902');
1561                 ++$faking_it;
1562             }
1563
1564             edit_file('hints/darwin.sh', sub {
1565                       my $code = shift;
1566                       # Part of commit 8f4f83badb7d1ba9, which mostly undoes
1567                       # commit 0511a818910f476c.
1568                       $code =~ s/^cppflags='-traditional-cpp';$/cppflags="\${cppflags} -no-cpp-precomp"/m;
1569                       # commit 14c11978e9b52e08/803bb6cc74d36a3f
1570                       # Without this, code in libperl.bundle links against op.o
1571                       # in preference to opmini.o on the linker command line,
1572                       # and hence miniperl tries to use File::Glob instead of
1573                       # csh
1574                       $code =~ s/^(lddlflags=)/ldflags="\${ldflags} -flat_namespace"\n$1/m;
1575                       # f556e5b971932902 also patches Makefile.SH with some
1576                       # special case code to deal with useshrplib for darwin.
1577                       # Given that post 5.8.0 the darwin hints default was
1578                       # changed to false, and it would be very complex to splice
1579                       # in that code in various versions of Makefile.SH back
1580                       # to 5.002, lets just turn it off.
1581                       $code =~ s/^useshrplib='true'/useshrplib='false'/m
1582                           if $faking_it;
1583                       return $code;
1584                   });
1585         }
1586     } elsif ($^O eq 'netbsd') {
1587         if ($major < 6) {
1588             # These are part of commit 099685bc64c7dbce
1589             edit_file('hints/netbsd.sh', sub {
1590                           my $code = shift;
1591                           my $fixed = <<'EOC';
1592 case "$osvers" in
1593 0.9|0.8*)
1594         usedl="$undef"
1595         ;;
1596 *)
1597         if [ -f /usr/libexec/ld.elf_so ]; then
1598                 d_dlopen=$define
1599                 d_dlerror=$define
1600                 ccdlflags="-Wl,-E -Wl,-R${PREFIX}/lib $ccdlflags"
1601                 cccdlflags="-DPIC -fPIC $cccdlflags"
1602                 lddlflags="--whole-archive -shared $lddlflags"
1603         elif [ "`uname -m`" = "pmax" ]; then
1604 # NetBSD 1.3 and 1.3.1 on pmax shipped an 'old' ld.so, which will not work.
1605                 d_dlopen=$undef
1606         elif [ -f /usr/libexec/ld.so ]; then
1607                 d_dlopen=$define
1608                 d_dlerror=$define
1609                 ccdlflags="-Wl,-R${PREFIX}/lib $ccdlflags"
1610 # we use -fPIC here because -fpic is *NOT* enough for some of the
1611 # extensions like Tk on some netbsd platforms (the sparc is one)
1612                 cccdlflags="-DPIC -fPIC $cccdlflags"
1613                 lddlflags="-Bforcearchive -Bshareable $lddlflags"
1614         else
1615                 d_dlopen=$undef
1616         fi
1617         ;;
1618 esac
1619 EOC
1620                           $code =~ s/^case "\$osvers" in\n0\.9\|0\.8.*?^esac\n/$fixed/ms;
1621                           return $code;
1622                       });
1623         }
1624     } elsif ($^O eq 'openbsd') {
1625         if ($major < 8) {
1626             checkout_file('hints/openbsd.sh', '43051805d53a3e4c')
1627                 unless -f 'hints/openbsd.sh';
1628             my $which = extract_from_file('hints/openbsd.sh',
1629                                           qr/# from (2\.8|3\.1) onwards/,
1630                                           '');
1631             if ($which eq '') {
1632                 my $was = extract_from_file('hints/openbsd.sh',
1633                                             qr/(lddlflags="(?:-Bforcearchive )?-Bshareable)/);
1634                 # This is commit 154d43cbcf57271c and parts of 5c75dbfa77b0949c
1635                 # and 29b5585702e5e025
1636                 apply_patch(sprintf <<'EOPATCH', $was);
1637 diff --git a/hints/openbsd.sh b/hints/openbsd.sh
1638 index a7d8bf2..5b79709 100644
1639 --- a/hints/openbsd.sh
1640 +++ b/hints/openbsd.sh
1641 @@ -37,7 +37,25 @@ OpenBSD.alpha|OpenBSD.mips|OpenBSD.powerpc|OpenBSD.vax)
1642         # we use -fPIC here because -fpic is *NOT* enough for some of the
1643         # extensions like Tk on some OpenBSD platforms (ie: sparc)
1644         cccdlflags="-DPIC -fPIC $cccdlflags"
1645 -       %s $lddlflags"
1646 +       case "$osvers" in
1647 +       [01].*|2.[0-7]|2.[0-7].*)
1648 +               lddlflags="-Bshareable $lddlflags"
1649 +               ;;
1650 +       2.[8-9]|3.0)
1651 +               ld=${cc:-cc}
1652 +               lddlflags="-shared -fPIC $lddlflags"
1653 +               ;;
1654 +       *) # from 3.1 onwards
1655 +               ld=${cc:-cc}
1656 +               lddlflags="-shared -fPIC $lddlflags"
1657 +               libswanted=`echo $libswanted | sed 's/ dl / /'`
1658 +               ;;
1659 +       esac
1660 +
1661 +       # We need to force ld to export symbols on ELF platforms.
1662 +       # Without this, dlopen() is crippled.
1663 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
1664 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
1665         ;;
1666  esac
1667  
1668 EOPATCH
1669             } elsif ($which eq '2.8') {
1670                 # This is parts of 5c75dbfa77b0949c and 29b5585702e5e025, and
1671                 # possibly eb9cd59d45ad2908
1672                 my $was = extract_from_file('hints/openbsd.sh',
1673                                             qr/lddlflags="(-shared(?: -fPIC)?) \$lddlflags"/);
1674
1675                 apply_patch(sprintf <<'EOPATCH', $was);
1676 --- a/hints/openbsd.sh  2011-10-21 17:25:20.000000000 +0200
1677 +++ b/hints/openbsd.sh  2011-10-21 16:58:43.000000000 +0200
1678 @@ -44,11 +44,21 @@
1679         [01].*|2.[0-7]|2.[0-7].*)
1680                 lddlflags="-Bshareable $lddlflags"
1681                 ;;
1682 -       *) # from 2.8 onwards
1683 +       2.[8-9]|3.0)
1684                 ld=${cc:-cc}
1685 -               lddlflags="%s $lddlflags"
1686 +               lddlflags="-shared -fPIC $lddlflags"
1687 +               ;;
1688 +       *) # from 3.1 onwards
1689 +               ld=${cc:-cc}
1690 +               lddlflags="-shared -fPIC $lddlflags"
1691 +               libswanted=`echo $libswanted | sed 's/ dl / /'`
1692                 ;;
1693         esac
1694 +
1695 +       # We need to force ld to export symbols on ELF platforms.
1696 +       # Without this, dlopen() is crippled.
1697 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
1698 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
1699         ;;
1700  esac
1701  
1702 EOPATCH
1703             } elsif ($which eq '3.1'
1704                      && !extract_from_file('hints/openbsd.sh',
1705                                            qr/We need to force ld to export symbols on ELF platforms/)) {
1706                 # This is part of 29b5585702e5e025
1707                 apply_patch(<<'EOPATCH');
1708 diff --git a/hints/openbsd.sh b/hints/openbsd.sh
1709 index c6b6bc9..4839d04 100644
1710 --- a/hints/openbsd.sh
1711 +++ b/hints/openbsd.sh
1712 @@ -54,6 +54,11 @@ alpha-2.[0-8]|mips-*|vax-*|powerpc-2.[0-7]|m88k-*)
1713                 libswanted=`echo $libswanted | sed 's/ dl / /'`
1714                 ;;
1715         esac
1716 +
1717 +       # We need to force ld to export symbols on ELF platforms.
1718 +       # Without this, dlopen() is crippled.
1719 +       ELF=`${cc:-cc} -dM -E - </dev/null | grep __ELF__`
1720 +       test -n "$ELF" && ldflags="-Wl,-E $ldflags"
1721         ;;
1722  esac
1723  
1724 EOPATCH
1725             }
1726         }
1727     } elsif ($^O eq 'linux') {
1728         if ($major < 1) {
1729             # sparc linux seems to need the -Dbool=char -DHAS_BOOL part of
1730             # perl5.000 patch.0n: [address Configure and build issues]
1731             edit_file('hints/linux.sh', sub {
1732                           my $code = shift;
1733                           $code =~ s!-I/usr/include/bsd!-Dbool=char -DHAS_BOOL!g;
1734                           return $code;
1735                       });
1736         }
1737
1738         if ($major <= 9) {
1739             if (`uname -sm` =~ qr/^Linux sparc/) {
1740                 if (extract_from_file('hints/linux.sh', qr/sparc-linux/)) {
1741                     # Be sure to use -fPIC not -fpic on Linux/SPARC
1742                     apply_commit('f6527d0ef0c13ad4');
1743                 } elsif(!extract_from_file('hints/linux.sh',
1744                                            qr/^sparc-linux\)$/)) {
1745                     my $fh = open_or_die('hints/linux.sh', '>>');
1746                     print $fh <<'EOT' or die $!;
1747
1748 case "`uname -m`" in
1749 sparc*)
1750         case "$cccdlflags" in
1751         *-fpic*) cccdlflags="`echo $cccdlflags|sed 's/-fpic/-fPIC/'`" ;;
1752         *)       cccdlflags="$cccdlflags -fPIC" ;;
1753         esac
1754         ;;
1755 esac
1756 EOT
1757                     close_or_die($fh);
1758                 }
1759             }
1760         }
1761     }
1762 }
1763
1764 sub patch_SH {
1765     # Cwd.xs added in commit 0d2079faa739aaa9. Cwd.pm moved to ext/ 8 years
1766     # later in commit 403f501d5b37ebf0
1767     if ($major > 0 && <*/Cwd/Cwd.xs>) {
1768         if ($major < 10
1769             && !extract_from_file('Makefile.SH', qr/^extra_dep=''$/)) {
1770             # The Makefile.PL for Unicode::Normalize needs
1771             # lib/unicore/CombiningClass.pl. Even without a parallel build, we
1772             # need a dependency to ensure that it builds. This is a variant of
1773             # commit 9f3ef600c170f61e. Putting this for earlier versions gives
1774             # us a spot on which to hang the edits below
1775             apply_patch(<<'EOPATCH');
1776 diff --git a/Makefile.SH b/Makefile.SH
1777 index f61d0db..6097954 100644
1778 --- a/Makefile.SH
1779 +++ b/Makefile.SH
1780 @@ -155,10 +155,20 @@ esac
1781  
1782  : Prepare dependency lists for Makefile.
1783  dynamic_list=' '
1784 +extra_dep=''
1785  for f in $dynamic_ext; do
1786      : the dependency named here will never exist
1787        base=`echo "$f" | sed 's/.*\///'`
1788 -    dynamic_list="$dynamic_list lib/auto/$f/$base.$dlext"
1789 +    this_target="lib/auto/$f/$base.$dlext"
1790 +    dynamic_list="$dynamic_list $this_target"
1791 +
1792 +    : Parallel makes reveal that we have some interdependencies
1793 +    case $f in
1794 +       Math/BigInt/FastCalc) extra_dep="$extra_dep
1795 +$this_target: lib/auto/List/Util/Util.$dlext" ;;
1796 +       Unicode/Normalize) extra_dep="$extra_dep
1797 +$this_target: lib/unicore/CombiningClass.pl" ;;
1798 +    esac
1799  done
1800  
1801  static_list=' '
1802 @@ -987,2 +997,9 @@ n_dummy $(nonxs_ext):       miniperl$(EXE_EXT) preplibrary $(DYNALOADER) FORCE
1803         @$(LDLIBPTH) sh ext/util/make_ext nonxs $@ MAKE=$(MAKE) LIBPERL_A=$(LIBPERL)
1804 +!NO!SUBS!
1805 +
1806 +$spitshell >>Makefile <<EOF
1807 +$extra_dep
1808 +EOF
1809 +
1810 +$spitshell >>Makefile <<'!NO!SUBS!'
1811  
1812 EOPATCH
1813         }
1814
1815         if ($major == 11) {
1816             if (extract_from_file('patchlevel.h',
1817                                   qr/^#include "unpushed\.h"/)) {
1818                 # I had thought it easier to detect when building one of the 52
1819                 # commits with the original method of incorporating the git
1820                 # revision and drop parallel make flags. Commits shown by
1821                 # git log 46807d8e809cc127^..dcff826f70bf3f64^ ^d4fb0a1f15d1a1c4
1822                 # However, it's not actually possible to make miniperl for that
1823                 # configuration as-is, because the file .patchnum is only made
1824                 # as a side effect of target 'all'
1825                 # I also don't think that it's "safe" to simply run
1826                 # make_patchnum.sh before the build. We need the proper
1827                 # dependency rules in the Makefile to *stop* it being run again
1828                 # at the wrong time.
1829                 # This range is important because contains the commit that
1830                 # merges Schwern's y2038 work.
1831                 apply_patch(<<'EOPATCH');
1832 diff --git a/Makefile.SH b/Makefile.SH
1833 index 9ad8b6f..106e721 100644
1834 --- a/Makefile.SH
1835 +++ b/Makefile.SH
1836 @@ -540,9 +544,14 @@ sperl.i: perl.c $(h)
1837  
1838  .PHONY: all translators utilities make_patchnum
1839  
1840 -make_patchnum:
1841 +make_patchnum: lib/Config_git.pl
1842 +
1843 +lib/Config_git.pl: make_patchnum.sh
1844         sh $(shellflags) make_patchnum.sh
1845  
1846 +# .patchnum, unpushed.h and lib/Config_git.pl are built by make_patchnum.sh
1847 +unpushed.h .patchnum: lib/Config_git.pl
1848 +
1849  # make sure that we recompile perl.c if .patchnum changes
1850  perl$(OBJ_EXT): .patchnum unpushed.h
1851  
1852 EOPATCH
1853             } elsif (-f '.gitignore'
1854                      && extract_from_file('.gitignore', qr/^\.patchnum$/)) {
1855                 # 8565263ab8a47cda to 46807d8e809cc127^ inclusive.
1856                 edit_file('Makefile.SH', sub {
1857                               my $code = shift;
1858                               $code =~ s/^make_patchnum:\n/make_patchnum: .patchnum
1859
1860 .sha1: .patchnum
1861
1862 .patchnum: make_patchnum.sh
1863 /m;
1864                               return $code;
1865                           });
1866             } elsif (-f 'lib/.gitignore'
1867                      && extract_from_file('lib/.gitignore',
1868                                           qr!^/Config_git.pl!)
1869                      && !extract_from_file('Makefile.SH',
1870                                         qr/^uudmap\.h.*:bitcount.h$/)) {
1871                 # Between commits and dcff826f70bf3f64 and 0f13ebd5d71f8177^
1872                 edit_file('Makefile.SH', sub {
1873                               my $code = shift;
1874                               # Bug introduced by 344af494c35a9f0f
1875                               # fixed in 0f13ebd5d71f8177
1876                               $code =~ s{^(pod/perlapi\.pod) (pod/perlintern\.pod): }
1877                                         {$1: $2\n\n$2: }m;
1878                               # Bug introduced by efa50c51e3301a2c
1879                               # fixed in 0f13ebd5d71f8177
1880                               $code =~ s{^(uudmap\.h) (bitcount\.h): }
1881                                         {$1: $2\n\n$2: }m;
1882
1883                               # The rats nest of getting git_version.h correct
1884
1885                               if ($code =~ s{git_version\.h: stock_git_version\.h
1886 \tcp stock_git_version\.h git_version\.h}
1887                                             {}m) {
1888                                   # before 486cd780047ff224
1889
1890                                   # We probably can't build between
1891                                   # 953f6acfa20ec275^ and 8565263ab8a47cda
1892                                   # inclusive, but all commits in that range
1893                                   # relate to getting make_patchnum.sh working,
1894                                   # so it is extremely unlikely to be an
1895                                   # interesting bisect target. They will skip.
1896
1897                                   # No, don't spawn a submake if
1898                                   # make_patchnum.sh or make_patchnum.pl fails
1899                                   $code =~ s{\|\| \$\(MAKE\) miniperl.*}
1900                                             {}m;
1901                                   $code =~ s{^\t(sh.*make_patchnum\.sh.*)}
1902                                             {\t-$1}m;
1903
1904                                   # Use an external perl to run make_patchnum.pl
1905                                   # because miniperl still depends on
1906                                   # git_version.h
1907                                   $code =~ s{^\t.*make_patchnum\.pl}
1908                                             {\t-$^X make_patchnum.pl}m;
1909
1910
1911                                   # "Truth in advertising" - running
1912                                   # make_patchnum generates 2 files.
1913                                   $code =~ s{^make_patchnum:.*}{
1914 make_patchnum: lib/Config_git.pl
1915
1916 git_version.h: lib/Config_git.pl
1917
1918 perlmini\$(OBJ_EXT): git_version.h
1919
1920 lib/Config_git.pl:}m;
1921                               }
1922                               # Right, now we've corrected Makefile.SH to
1923                               # correctly describe how lib/Config_git.pl and
1924                               # git_version.h are made, we need to fix the rest
1925
1926                               # This emulates commit 2b63e250843b907e
1927                               # This might duplicate the rule stating that
1928                               # git_version.h depends on lib/Config_git.pl
1929                               # This is harmless.
1930                               $code =~ s{^(?:lib/Config_git\.pl )?git_version\.h: (.* make_patchnum\.pl.*)}
1931                                         {git_version.h: lib/Config_git.pl
1932
1933 lib/Config_git.pl: $1}m;
1934
1935                               # This emulates commits 0f13ebd5d71f8177 and
1936                               # and a04d4598adc57886. It ensures that
1937                               # lib/Config_git.pl is built before configpm,
1938                               # and that configpm is run exactly once.
1939                               $code =~ s{^(\$\(.*?\) )?(\$\(CONFIGPOD\))(: .*? configpm Porting/Glossary)( lib/Config_git\.pl)?}{
1940                                   # If present, other files depend on $(CONFIGPOD)
1941                                   ($1 ? "$1: $2\n\n" : '')
1942                                       # Then the rule we found
1943                                       . $2 . $3
1944                                           # Add dependency if not there
1945                                           . ($4 ? $4 : ' lib/Config_git.pl')
1946                               }me;
1947
1948                               return $code;
1949                           });
1950             }
1951         }
1952
1953         if ($major < 14) {
1954             # Commits dc0655f797469c47 and d11a62fe01f2ecb2
1955             edit_file('Makefile.SH', sub {
1956                           my $code = shift;
1957                           foreach my $ext (qw(Encode SDBM_File)) {
1958                               next if $code =~ /\b$ext\) extra_dep=/s;
1959                               $code =~ s!(\) extra_dep="\$extra_dep
1960 \$this_target: .*?" ;;)
1961 (    esac
1962 )!$1
1963         $ext) extra_dep="\$extra_dep
1964 \$this_target: lib/auto/Cwd/Cwd.\$dlext" ;;
1965 $2!;
1966                           }
1967                           return $code;
1968                       });
1969         }
1970     }
1971
1972     if ($major == 7) {
1973         # Remove commits 9fec149bb652b6e9 and 5bab1179608f81d8, which add/amend
1974         # rules to automatically run regen scripts that rebuild C headers. These
1975         # cause problems because a git checkout doesn't preserve relative file
1976         # modification times, hence the regen scripts may fire. This will
1977         # obscure whether the repository had the correct generated headers
1978         # checked in.
1979         # Also, the dependency rules for running the scripts were not correct,
1980         # which could cause spurious re-builds on re-running make, and can cause
1981         # complete build failures for a parallel make.
1982         if (extract_from_file('Makefile.SH',
1983                               qr/Writing it this way gives make a big hint to always run opcode\.pl before/)) {
1984             apply_commit('70c6e6715e8fec53');
1985         } elsif (extract_from_file('Makefile.SH',
1986                                    qr/^opcode\.h opnames\.h pp_proto\.h pp\.sym: opcode\.pl$/)) {
1987             revert_commit('9fec149bb652b6e9');
1988         }
1989     }
1990
1991     if ($^O eq 'aix' && $major >= 11 && $major <= 15
1992         && extract_from_file('makedef.pl', qr/^use Config/)) {
1993         edit_file('Makefile.SH', sub {
1994                       # The AIX part of commit e6807d8ab22b761c
1995                       # It's safe to substitute lib/Config.pm for config.sh
1996                       # as lib/Config.pm depends on config.sh
1997                       # If the tree is post e6807d8ab22b761c, the substitution
1998                       # won't match, which is harmless.
1999                       my $code = shift;
2000                       $code =~ s{^(perl\.exp:.* )config\.sh(\b.*)}
2001                                 {$1 . '$(CONFIGPM)' . $2}me;
2002                       return $code;
2003                   });
2004     }
2005
2006     # There was a bug in makedepend.SH which was fixed in version 96a8704c.
2007     # Symptom was './makedepend: 1: Syntax error: Unterminated quoted string'
2008     # Remove this if you're actually bisecting a problem related to
2009     # makedepend.SH
2010     # If you do this, you may need to add in code to correct the output of older
2011     # makedepends, which don't correctly filter newer gcc output such as
2012     # <built-in>
2013     checkout_file('makedepend.SH');
2014
2015     if ($major < 4 && -f 'config.sh'
2016         && !extract_from_file('config.sh', qr/^trnl=/)) {
2017         # This seems to be necessary to avoid makedepend becoming confused,
2018         # and hanging on stdin. Seems that the code after
2019         # make shlist || ...here... is never run.
2020         edit_file('makedepend.SH', sub {
2021                       my $code = shift;
2022                       $code =~ s/^trnl='\$trnl'$/trnl='\\n'/m;
2023                       return $code;
2024                   });
2025     }
2026 }
2027
2028 sub patch_C {
2029     # This is ordered by $major, as it's likely that different platforms may
2030     # well want to share code.
2031
2032     if ($major == 2 && extract_from_file('perl.c', qr/^\tfclose\(e_fp\);$/)) {
2033         # need to patch perl.c to avoid calling fclose() twice on e_fp when
2034         # using -e
2035         # This diff is part of commit ab821d7fdc14a438. The second close was
2036         # introduced with perl-5.002, commit a5f75d667838e8e7
2037         # Might want a6c477ed8d4864e6 too, for the corresponding change to
2038         # pp_ctl.c (likely without this, eval will have "fun")
2039         apply_patch(<<'EOPATCH');
2040 diff --git a/perl.c b/perl.c
2041 index 03c4d48..3c814a2 100644
2042 --- a/perl.c
2043 +++ b/perl.c
2044 @@ -252,6 +252,7 @@ setuid perl scripts securely.\n");
2045  #ifndef VMS  /* VMS doesn't have environ array */
2046      origenviron = environ;
2047  #endif
2048 +    e_tmpname = Nullch;
2049  
2050      if (do_undump) {
2051  
2052 @@ -405,6 +406,7 @@ setuid perl scripts securely.\n");
2053      if (e_fp) {
2054         if (Fflush(e_fp) || ferror(e_fp) || fclose(e_fp))
2055             croak("Can't write to temp file for -e: %s", Strerror(errno));
2056 +       e_fp = Nullfp;
2057         argc++,argv--;
2058         scriptname = e_tmpname;
2059      }
2060 @@ -470,10 +472,10 @@ setuid perl scripts securely.\n");
2061      curcop->cop_line = 0;
2062      curstash = defstash;
2063      preprocess = FALSE;
2064 -    if (e_fp) {
2065 -       fclose(e_fp);
2066 -       e_fp = Nullfp;
2067 +    if (e_tmpname) {
2068         (void)UNLINK(e_tmpname);
2069 +       Safefree(e_tmpname);
2070 +       e_tmpname = Nullch;
2071      }
2072  
2073      /* now that script is parsed, we can modify record separator */
2074 @@ -1369,7 +1371,7 @@ SV *sv;
2075         scriptname = xfound;
2076      }
2077  
2078 -    origfilename = savepv(e_fp ? "-e" : scriptname);
2079 +    origfilename = savepv(e_tmpname ? "-e" : scriptname);
2080      curcop->cop_filegv = gv_fetchfile(origfilename);
2081      if (strEQ(origfilename,"-"))
2082         scriptname = "";
2083
2084 EOPATCH
2085     }
2086
2087     if ($major < 3 && $^O eq 'openbsd'
2088         && !extract_from_file('pp_sys.c', qr/BSD_GETPGRP/)) {
2089         # Part of commit c3293030fd1b7489
2090         apply_patch(<<'EOPATCH');
2091 diff --git a/pp_sys.c b/pp_sys.c
2092 index 4608a2a..f0c9d1d 100644
2093 --- a/pp_sys.c
2094 +++ b/pp_sys.c
2095 @@ -2903,8 +2903,8 @@ PP(pp_getpgrp)
2096         pid = 0;
2097      else
2098         pid = SvIVx(POPs);
2099 -#ifdef USE_BSDPGRP
2100 -    value = (I32)getpgrp(pid);
2101 +#ifdef BSD_GETPGRP
2102 +    value = (I32)BSD_GETPGRP(pid);
2103  #else
2104      if (pid != 0)
2105         DIE("POSIX getpgrp can't take an argument");
2106 @@ -2933,8 +2933,8 @@ PP(pp_setpgrp)
2107      }
2108  
2109      TAINT_PROPER("setpgrp");
2110 -#ifdef USE_BSDPGRP
2111 -    SETi( setpgrp(pid, pgrp) >= 0 );
2112 +#ifdef BSD_SETPGRP
2113 +    SETi( BSD_SETPGRP(pid, pgrp) >= 0 );
2114  #else
2115      if ((pgrp != 0) || (pid != 0)) {
2116         DIE("POSIX setpgrp can't take an argument");
2117 EOPATCH
2118     }
2119
2120     if ($major < 4 && $^O eq 'openbsd') {
2121         my $bad;
2122         # Need changes from commit a6e633defa583ad5.
2123         # Commits c07a80fdfe3926b5 and f82b3d4130164d5f changed the same part
2124         # of perl.h
2125
2126         if (extract_from_file('perl.h',
2127                               qr/^#ifdef HAS_GETPGRP2$/)) {
2128             $bad = <<'EOBAD';
2129 ***************
2130 *** 57,71 ****
2131   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
2132   #define TAINT_ENV()   if (tainting) taint_env()
2133   
2134 ! #ifdef HAS_GETPGRP2
2135 ! #   ifndef HAS_GETPGRP
2136 ! #     define HAS_GETPGRP
2137 ! #   endif
2138 ! #endif
2139
2140 ! #ifdef HAS_SETPGRP2
2141 ! #   ifndef HAS_SETPGRP
2142 ! #     define HAS_SETPGRP
2143 ! #   endif
2144   #endif
2145   
2146 EOBAD
2147         } elsif (extract_from_file('perl.h',
2148                                    qr/Gack, you have one but not both of getpgrp2/)) {
2149             $bad = <<'EOBAD';
2150 ***************
2151 *** 56,76 ****
2152   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
2153   #define TAINT_ENV()   if (tainting) taint_env()
2154   
2155 ! #if defined(HAS_GETPGRP2) && defined(HAS_SETPGRP2)
2156 ! #   define getpgrp getpgrp2
2157 ! #   define setpgrp setpgrp2
2158 ! #   ifndef HAS_GETPGRP
2159 ! #     define HAS_GETPGRP
2160 ! #   endif
2161 ! #   ifndef HAS_SETPGRP
2162 ! #     define HAS_SETPGRP
2163 ! #   endif
2164 ! #   ifndef USE_BSDPGRP
2165 ! #     define USE_BSDPGRP
2166 ! #   endif
2167 ! #else
2168 ! #   if defined(HAS_GETPGRP2) || defined(HAS_SETPGRP2)
2169 !       #include "Gack, you have one but not both of getpgrp2() and setpgrp2()."
2170 ! #   endif
2171   #endif
2172   
2173 EOBAD
2174         } elsif (extract_from_file('perl.h',
2175                                    qr/^#ifdef USE_BSDPGRP$/)) {
2176             $bad = <<'EOBAD'
2177 ***************
2178 *** 91,116 ****
2179   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
2180   #define TAINT_ENV()   if (tainting) taint_env()
2181   
2182 ! #ifdef USE_BSDPGRP
2183 ! #   ifdef HAS_GETPGRP
2184 ! #       define BSD_GETPGRP(pid) getpgrp((pid))
2185 ! #   endif
2186 ! #   ifdef HAS_SETPGRP
2187 ! #       define BSD_SETPGRP(pid, pgrp) setpgrp((pid), (pgrp))
2188 ! #   endif
2189 ! #else
2190 ! #   ifdef HAS_GETPGRP2
2191 ! #       define BSD_GETPGRP(pid) getpgrp2((pid))
2192 ! #       ifndef HAS_GETPGRP
2193 ! #         define HAS_GETPGRP
2194 ! #     endif
2195 ! #   endif
2196 ! #   ifdef HAS_SETPGRP2
2197 ! #       define BSD_SETPGRP(pid, pgrp) setpgrp2((pid), (pgrp))
2198 ! #       ifndef HAS_SETPGRP
2199 ! #         define HAS_SETPGRP
2200 ! #     endif
2201 ! #   endif
2202   #endif
2203   
2204   #ifndef _TYPES_               /* If types.h defines this it's easy. */
2205 EOBAD
2206         }
2207         if ($bad) {
2208             apply_patch(<<"EOPATCH");
2209 *** a/perl.h    2011-10-21 09:46:12.000000000 +0200
2210 --- b/perl.h    2011-10-21 09:46:12.000000000 +0200
2211 $bad--- 91,144 ----
2212   #define TAINT_PROPER(s)       if (tainting) taint_proper(no_security, s)
2213   #define TAINT_ENV()   if (tainting) taint_env()
2214   
2215 ! /* XXX All process group stuff is handled in pp_sys.c.  Should these 
2216 !    defines move there?  If so, I could simplify this a lot. --AD  9/96.
2217 ! */
2218 ! /* Process group stuff changed from traditional BSD to POSIX.
2219 !    perlfunc.pod documents the traditional BSD-style syntax, so we'll
2220 !    try to preserve that, if possible.
2221 ! */
2222 ! #ifdef HAS_SETPGID
2223 ! #  define BSD_SETPGRP(pid, pgrp)      setpgid((pid), (pgrp))
2224 ! #else
2225 ! #  if defined(HAS_SETPGRP) && defined(USE_BSD_SETPGRP)
2226 ! #    define BSD_SETPGRP(pid, pgrp)    setpgrp((pid), (pgrp))
2227 ! #  else
2228 ! #    ifdef HAS_SETPGRP2  /* DG/UX */
2229 ! #      define BSD_SETPGRP(pid, pgrp)  setpgrp2((pid), (pgrp))
2230 ! #    endif
2231 ! #  endif
2232 ! #endif
2233 ! #if defined(BSD_SETPGRP) && !defined(HAS_SETPGRP)
2234 ! #  define HAS_SETPGRP  /* Well, effectively it does . . . */
2235 ! #endif
2236
2237 ! /* getpgid isn't POSIX, but at least Solaris and Linux have it, and it makes
2238 !     our life easier :-) so we'll try it.
2239 ! */
2240 ! #ifdef HAS_GETPGID
2241 ! #  define BSD_GETPGRP(pid)            getpgid((pid))
2242 ! #else
2243 ! #  if defined(HAS_GETPGRP) && defined(USE_BSD_GETPGRP)
2244 ! #    define BSD_GETPGRP(pid)          getpgrp((pid))
2245 ! #  else
2246 ! #    ifdef HAS_GETPGRP2  /* DG/UX */
2247 ! #      define BSD_GETPGRP(pid)                getpgrp2((pid))
2248 ! #    endif
2249 ! #  endif
2250 ! #endif
2251 ! #if defined(BSD_GETPGRP) && !defined(HAS_GETPGRP)
2252 ! #  define HAS_GETPGRP  /* Well, effectively it does . . . */
2253 ! #endif
2254
2255 ! /* These are not exact synonyms, since setpgrp() and getpgrp() may 
2256 !    have different behaviors, but perl.h used to define USE_BSDPGRP
2257 !    (prior to 5.003_05) so some extension might depend on it.
2258 ! */
2259 ! #if defined(USE_BSD_SETPGRP) || defined(USE_BSD_GETPGRP)
2260 ! #  ifndef USE_BSDPGRP
2261 ! #    define USE_BSDPGRP
2262 ! #  endif
2263   #endif
2264   
2265   #ifndef _TYPES_               /* If types.h defines this it's easy. */
2266 EOPATCH
2267         }
2268     }
2269
2270     if ($major == 4 && extract_from_file('scope.c', qr/\(SV\*\)SSPOPINT/)) {
2271         # [PATCH] 5.004_04 +MAINT_TRIAL_1 broken when sizeof(int) != sizeof(void)
2272         # Fixes a bug introduced in 161b7d1635bc830b
2273         apply_commit('9002cb76ec83ef7f');
2274     }
2275
2276     if ($major == 4 && extract_from_file('av.c', qr/AvARRAY\(av\) = 0;/)) {
2277         # Fixes a bug introduced in 1393e20655efb4bc
2278         apply_commit('e1c148c28bf3335b', 'av.c');
2279     }
2280
2281     if ($major == 4) {
2282         my $rest = extract_from_file('perl.c', qr/delimcpy(.*)/);
2283         if (defined $rest and $rest !~ /,$/) {
2284             # delimcpy added in fc36a67e8855d031, perl.c refactored to use it.
2285             # bug introduced in 2a92aaa05aa1acbf, fixed in 8490252049bf42d3
2286             # code then moved to util.c in commit 491527d0220de34e
2287             apply_patch(<<'EOPATCH');
2288 diff --git a/perl.c b/perl.c
2289 index 4eb69e3..54bbb00 100644
2290 --- a/perl.c
2291 +++ b/perl.c
2292 @@ -1735,7 +1735,7 @@ SV *sv;
2293             if (len < sizeof tokenbuf)
2294                 tokenbuf[len] = '\0';
2295  #else  /* ! (atarist || DOSISH) */
2296 -           s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend
2297 +           s = delimcpy(tokenbuf, tokenbuf + sizeof tokenbuf, s, bufend,
2298                          ':',
2299                          &len);
2300  #endif /* ! (atarist || DOSISH) */
2301 EOPATCH
2302         }
2303     }
2304
2305     if ($major == 4 && $^O eq 'linux') {
2306         # Whilst this is fixed properly in f0784f6a4c3e45e1 which provides the
2307         # Configure probe, it's easier to back out the problematic changes made
2308         # in these previous commits:
2309         if (extract_from_file('doio.c',
2310                               qr!^/\* XXX REALLY need metaconfig test \*/$!)) {
2311             revert_commit('4682965a1447ea44', 'doio.c');
2312         }
2313         if (my $token = extract_from_file('doio.c',
2314                                           qr!^#if (defined\(__sun(?:__)?\)) && defined\(__svr4__\) /\* XXX Need metaconfig test \*/$!)) {
2315             my $patch = `git show -R 9b599b2a63d2324d doio.c`;
2316             $patch =~ s/defined\(__sun__\)/$token/g;
2317             apply_patch($patch);
2318         }
2319         if (extract_from_file('doio.c',
2320                               qr!^/\* linux \(and Solaris2\?\) uses :$!)) {
2321             revert_commit('8490252049bf42d3', 'doio.c');
2322         }
2323         if (extract_from_file('doio.c',
2324                               qr/^          unsemds.buf = &semds;$/)) {
2325             revert_commit('8e591e46b4c6543e');
2326         }
2327         if (extract_from_file('doio.c',
2328                               qr!^#ifdef __linux__      /\* XXX Need metaconfig test \*/$!)) {
2329             # Reverts part of commit 3e3baf6d63945cb6
2330             apply_patch(<<'EOPATCH');
2331 diff --git b/doio.c a/doio.c
2332 index 62b7de9..0d57425 100644
2333 --- b/doio.c
2334 +++ a/doio.c
2335 @@ -1333,9 +1331,6 @@ SV **sp;
2336      char *a;
2337      I32 id, n, cmd, infosize, getinfo;
2338      I32 ret = -1;
2339 -#ifdef __linux__       /* XXX Need metaconfig test */
2340 -    union semun unsemds;
2341 -#endif
2342  
2343      id = SvIVx(*++mark);
2344      n = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2345 @@ -1364,29 +1359,11 @@ SV **sp;
2346             infosize = sizeof(struct semid_ds);
2347         else if (cmd == GETALL || cmd == SETALL)
2348         {
2349 -#ifdef __linux__       /* XXX Need metaconfig test */
2350 -/* linux uses :
2351 -   int semctl (int semid, int semnun, int cmd, union semun arg)
2352 -
2353 -       union semun {
2354 -            int val;
2355 -            struct semid_ds *buf;
2356 -            ushort *array;
2357 -       };
2358 -*/
2359 -            union semun semds;
2360 -           if (semctl(id, 0, IPC_STAT, semds) == -1)
2361 -#else
2362             struct semid_ds semds;
2363             if (semctl(id, 0, IPC_STAT, &semds) == -1)
2364 -#endif
2365                 return -1;
2366             getinfo = (cmd == GETALL);
2367 -#ifdef __linux__       /* XXX Need metaconfig test */
2368 -           infosize = semds.buf->sem_nsems * sizeof(short);
2369 -#else
2370             infosize = semds.sem_nsems * sizeof(short);
2371 -#endif
2372                 /* "short" is technically wrong but much more portable
2373                    than guessing about u_?short(_t)? */
2374         }
2375 @@ -1429,12 +1406,7 @@ SV **sp;
2376  #endif
2377  #ifdef HAS_SEM
2378      case OP_SEMCTL:
2379 -#ifdef __linux__       /* XXX Need metaconfig test */
2380 -        unsemds.buf = (struct semid_ds *)a;
2381 -       ret = semctl(id, n, cmd, unsemds);
2382 -#else
2383         ret = semctl(id, n, cmd, (struct semid_ds *)a);
2384 -#endif
2385         break;
2386  #endif
2387  #ifdef HAS_SHM
2388 EOPATCH
2389         }
2390         # Incorrect prototype added as part of 8ac853655d9b7447, fixed as part
2391         # of commit dc45a647708b6c54, with at least one intermediate
2392         # modification. Correct prototype for gethostbyaddr has socklen_t
2393         # second. Linux has uint32_t first for getnetbyaddr.
2394         # Easiest just to remove, instead of attempting more complex patching.
2395         # Something similar may be needed on other platforms.
2396         edit_file('pp_sys.c', sub {
2397                       my $code = shift;
2398                       $code =~ s/^    struct hostent \*(?:PerlSock_)?gethostbyaddr\([^)]+\);$//m;
2399                       $code =~ s/^    struct netent \*getnetbyaddr\([^)]+\);$//m;
2400                       return $code;
2401                   });
2402     }
2403
2404     if ($major < 5 && $^O eq 'aix'
2405         && !extract_from_file('pp_sys.c',
2406                               qr/defined\(HOST_NOT_FOUND\) && !defined\(h_errno\)/)) {
2407         # part of commit dc45a647708b6c54
2408         # Andy Dougherty's configuration patches (Config_63-01 up to 04).
2409         apply_patch(<<'EOPATCH')
2410 diff --git a/pp_sys.c b/pp_sys.c
2411 index c2fcb6f..efa39fb 100644
2412 --- a/pp_sys.c
2413 +++ b/pp_sys.c
2414 @@ -54,7 +54,7 @@ extern "C" int syscall(unsigned long,...);
2415  #endif
2416  #endif
2417  
2418 -#ifdef HOST_NOT_FOUND
2419 +#if defined(HOST_NOT_FOUND) && !defined(h_errno)
2420  extern int h_errno;
2421  #endif
2422  
2423 EOPATCH
2424     }
2425
2426     if ($major < 6 && $^O eq 'netbsd'
2427         && !extract_from_file('unixish.h',
2428                               qr/defined\(NSIG\).*defined\(__NetBSD__\)/)) {
2429         apply_patch(<<'EOPATCH')
2430 diff --git a/unixish.h b/unixish.h
2431 index 2a6cbcd..eab2de1 100644
2432 --- a/unixish.h
2433 +++ b/unixish.h
2434 @@ -89,7 +89,7 @@
2435   */
2436  /* #define ALTERNATE_SHEBANG "#!" / **/
2437  
2438 -#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
2439 +#if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX) || defined(__NetBSD__)
2440  # include <signal.h>
2441  #endif
2442  
2443 EOPATCH
2444     }
2445
2446     if (($major >= 7 || $major <= 9) && $^O eq 'openbsd'
2447         && `uname -m` eq "sparc64\n"
2448         # added in 2000 by commit cb434fcc98ac25f5:
2449         && extract_from_file('regexec.c',
2450                              qr!/\* No need to save/restore up to this paren \*/!)
2451         # re-indented in 2006 by commit 95b2444054382532:
2452         && extract_from_file('regexec.c', qr/^\t\tCURCUR cc;$/)) {
2453         # Need to work around a bug in (at least) OpenBSD's 4.6's sparc64 #
2454         # compiler ["gcc (GCC) 3.3.5 (propolice)"]. Between commits
2455         # 3ec562b0bffb8b8b (2002) and 1a4fad37125bac3e^ (2005) the darling thing
2456         # fails to compile any code for the statement cc.oldcc = PL_regcc;
2457         #
2458         # If you refactor the code to "fix" that, or force the issue using set
2459         # in the debugger, the stack smashing detection code fires on return
2460         # from S_regmatch(). Turns out that the compiler doesn't allocate any
2461         # (or at least enough) space for cc.
2462         #
2463         # Restore the "uninitialised" value for cc before function exit, and the
2464         # stack smashing code is placated.  "Fix" 3ec562b0bffb8b8b (which
2465         # changes the size of auto variables used elsewhere in S_regmatch), and
2466         # the crash is visible back to bc517b45fdfb539b (which also changes
2467         # buffer sizes). "Unfix" 1a4fad37125bac3e and the crash is visible until
2468         # 5b47454deb66294b.  Problem goes away if you compile with -O, or hack
2469         # the code as below.
2470         #
2471         # Hence this turns out to be a bug in (old) gcc. Not a security bug we
2472         # still need to fix.
2473         apply_patch(<<'EOPATCH');
2474 diff --git a/regexec.c b/regexec.c
2475 index 900b491..6251a0b 100644
2476 --- a/regexec.c
2477 +++ b/regexec.c
2478 @@ -2958,7 +2958,11 @@ S_regmatch(pTHX_ regnode *prog)
2479                                 I,I
2480   *******************************************************************/
2481         case CURLYX: {
2482 -               CURCUR cc;
2483 +           union {
2484 +               CURCUR hack_cc;
2485 +               char hack_buff[sizeof(CURCUR) + 1];
2486 +           } hack;
2487 +#define cc hack.hack_cc
2488                 CHECKPOINT cp = PL_savestack_ix;
2489                 /* No need to save/restore up to this paren */
2490                 I32 parenfloor = scan->flags;
2491 @@ -2983,6 +2987,7 @@ S_regmatch(pTHX_ regnode *prog)
2492                 n = regmatch(PREVOPER(next));   /* start on the WHILEM */
2493                 regcpblow(cp);
2494                 PL_regcc = cc.oldcc;
2495 +#undef cc
2496                 saySAME(n);
2497             }
2498             /* NOT REACHED */
2499 EOPATCH
2500 }
2501
2502     if ($major < 8 && $^O eq 'openbsd'
2503         && !extract_from_file('perl.h', qr/include <unistd\.h>/)) {
2504         # This is part of commit 3f270f98f9305540, applied at a slightly
2505         # different location in perl.h, where the context is stable back to
2506         # 5.000
2507         apply_patch(<<'EOPATCH');
2508 diff --git a/perl.h b/perl.h
2509 index 9418b52..b8b1a7c 100644
2510 --- a/perl.h
2511 +++ b/perl.h
2512 @@ -496,6 +496,10 @@ register struct op *Perl_op asm(stringify(OP_IN_REGISTER));
2513  #   include <sys/param.h>
2514  #endif
2515  
2516 +/* If this causes problems, set i_unistd=undef in the hint file.  */
2517 +#ifdef I_UNISTD
2518 +#   include <unistd.h>
2519 +#endif
2520  
2521  /* Use all the "standard" definitions? */
2522  #if defined(STANDARD_C) && defined(I_STDLIB)
2523 EOPATCH
2524     }
2525 }
2526
2527 sub patch_ext {
2528     if (-f 'ext/POSIX/Makefile.PL'
2529         && extract_from_file('ext/POSIX/Makefile.PL',
2530                              qr/Explicitly avoid including/)) {
2531         # commit 6695a346c41138df, which effectively reverts 170888cff5e2ffb7
2532
2533         # PERL5LIB is populated by make_ext.pl with paths to the modules we need
2534         # to run, don't override this with "../../lib" since that may not have
2535         # been populated yet in a parallel build.
2536         apply_commit('6695a346c41138df');
2537     }
2538
2539     if (-f 'ext/Hash/Util/Makefile.PL'
2540         && extract_from_file('ext/Hash/Util/Makefile.PL',
2541                              qr/\bDIR\b.*'FieldHash'/)) {
2542         # ext/Hash/Util/Makefile.PL should not recurse to FieldHash's Makefile.PL
2543         # *nix, VMS and Win32 all know how to (and have to) call the latter directly.
2544         # As is, targets in ext/Hash/Util/FieldHash get called twice, which may result
2545         # in race conditions, and certainly messes up make clean; make distclean;
2546         apply_commit('550428fe486b1888');
2547     }
2548
2549     if ($major < 8 && $^O eq 'darwin' && !-f 'ext/DynaLoader/dl_dyld.xs') {
2550         checkout_file('ext/DynaLoader/dl_dyld.xs', 'f556e5b971932902');
2551         apply_patch(<<'EOPATCH');
2552 diff -u a/ext/DynaLoader/dl_dyld.xs~ a/ext/DynaLoader/dl_dyld.xs
2553 --- a/ext/DynaLoader/dl_dyld.xs~        2011-10-11 21:41:27.000000000 +0100
2554 +++ b/ext/DynaLoader/dl_dyld.xs 2011-10-11 21:42:20.000000000 +0100
2555 @@ -41,6 +41,35 @@
2556  #include "perl.h"
2557  #include "XSUB.h"
2558  
2559 +#ifndef pTHX
2560 +#  define pTHX         void
2561 +#  define pTHX_
2562 +#endif
2563 +#ifndef aTHX
2564 +#  define aTHX
2565 +#  define aTHX_
2566 +#endif
2567 +#ifndef dTHX
2568 +#  define dTHXa(a)     extern int Perl___notused(void)
2569 +#  define dTHX         extern int Perl___notused(void)
2570 +#endif
2571 +
2572 +#ifndef Perl_form_nocontext
2573 +#  define Perl_form_nocontext form
2574 +#endif
2575 +
2576 +#ifndef Perl_warn_nocontext
2577 +#  define Perl_warn_nocontext warn
2578 +#endif
2579 +
2580 +#ifndef PTR2IV
2581 +#  define PTR2IV(p)    (IV)(p)
2582 +#endif
2583 +
2584 +#ifndef get_av
2585 +#  define get_av perl_get_av
2586 +#endif
2587 +
2588  #define DL_LOADONCEONLY
2589  
2590  #include "dlutils.c"   /* SaveError() etc      */
2591 @@ -185,7 +191,7 @@
2592      CODE:
2593      DLDEBUG(1,PerlIO_printf(Perl_debug_log, "dl_load_file(%s,%x):\n", filename,flags));
2594      if (flags & 0x01)
2595 -       Perl_warn(aTHX_ "Can't make loaded symbols global on this platform while loading %s",filename);
2596 +       Perl_warn_nocontext("Can't make loaded symbols global on this platform while loading %s",filename);
2597      RETVAL = dlopen(filename, mode) ;
2598      DLDEBUG(2,PerlIO_printf(Perl_debug_log, " libref=%x\n", RETVAL));
2599      ST(0) = sv_newmortal() ;
2600 EOPATCH
2601         if ($major < 4 && !extract_from_file('util.c', qr/^form/m)) {
2602             apply_patch(<<'EOPATCH');
2603 diff -u a/ext/DynaLoader/dl_dyld.xs~ a/ext/DynaLoader/dl_dyld.xs
2604 --- a/ext/DynaLoader/dl_dyld.xs~        2011-10-11 21:56:25.000000000 +0100
2605 +++ b/ext/DynaLoader/dl_dyld.xs 2011-10-11 22:00:00.000000000 +0100
2606 @@ -60,6 +60,18 @@
2607  #  define get_av perl_get_av
2608  #endif
2609  
2610 +static char *
2611 +form(char *pat, ...)
2612 +{
2613 +    char *retval;
2614 +    va_list args;
2615 +    va_start(args, pat);
2616 +    vasprintf(&retval, pat, &args);
2617 +    va_end(args);
2618 +    SAVEFREEPV(retval);
2619 +    return retval;
2620 +}
2621 +
2622  #define DL_LOADONCEONLY
2623  
2624  #include "dlutils.c"   /* SaveError() etc      */
2625 EOPATCH
2626         }
2627     }
2628
2629     if ($major < 10) {
2630         if (!extract_from_file('ext/DB_File/DB_File.xs',
2631                                qr!^#else /\* Berkeley DB Version > 2 \*/$!)) {
2632             # This DB_File.xs is really too old to patch up.
2633             # Skip DB_File, unless we're invoked with an explicit -Unoextensions
2634             if (!exists $defines{noextensions}) {
2635                 $defines{noextensions} = 'DB_File';
2636             } elsif (defined $defines{noextensions}) {
2637                 $defines{noextensions} .= ' DB_File';
2638             }
2639         } elsif (!extract_from_file('ext/DB_File/DB_File.xs',
2640                                     qr/^#ifdef AT_LEAST_DB_4_1$/)) {
2641             # This line is changed by commit 3245f0580c13b3ab
2642             my $line = extract_from_file('ext/DB_File/DB_File.xs',
2643                                          qr/^(        status = \(?RETVAL->dbp->open\)?\(RETVAL->dbp, name, NULL, RETVAL->type, $)/);
2644             apply_patch(<<"EOPATCH");
2645 diff --git a/ext/DB_File/DB_File.xs b/ext/DB_File/DB_File.xs
2646 index 489ba96..fba8ded 100644
2647 --- a/ext/DB_File/DB_File.xs
2648 +++ b/ext/DB_File/DB_File.xs
2649 \@\@ -183,4 +187,8 \@\@
2650  #endif
2651  
2652 +#if DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 1)
2653 +#    define AT_LEAST_DB_4_1
2654 +#endif
2655 +
2656  /* map version 2 features & constants onto their version 1 equivalent */
2657  
2658 \@\@ -1334,7 +1419,12 \@\@ SV *   sv ;
2659  #endif
2660  
2661 +#ifdef AT_LEAST_DB_4_1
2662 +        status = (RETVAL->dbp->open)(RETVAL->dbp, NULL, name, NULL, RETVAL->type, 
2663 +                               Flags, mode) ; 
2664 +#else
2665  $line
2666                                 Flags, mode) ; 
2667 +#endif
2668         /* printf("open returned %d %s\\n", status, db_strerror(status)) ; */
2669  
2670 EOPATCH
2671         }
2672     }
2673
2674     if ($major < 10 and -f 'ext/IPC/SysV/SysV.xs') {
2675         edit_file('ext/IPC/SysV/SysV.xs', sub {
2676                       my $xs = shift;
2677                       my $fixed = <<'EOFIX';
2678
2679 #include <sys/types.h>
2680 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
2681 #ifndef HAS_SEM
2682 #   include <sys/ipc.h>
2683 #endif
2684 #   ifdef HAS_MSG
2685 #       include <sys/msg.h>
2686 #   endif
2687 #   ifdef HAS_SHM
2688 #       if defined(PERL_SCO) || defined(PERL_ISC)
2689 #           include <sys/sysmacros.h>   /* SHMLBA */
2690 #       endif
2691 #      include <sys/shm.h>
2692 #      ifndef HAS_SHMAT_PROTOTYPE
2693            extern Shmat_t shmat (int, char *, int);
2694 #      endif
2695 #      if defined(HAS_SYSCONF) && defined(_SC_PAGESIZE)
2696 #          undef  SHMLBA /* not static: determined at boot time */
2697 #          define SHMLBA sysconf(_SC_PAGESIZE)
2698 #      elif defined(HAS_GETPAGESIZE)
2699 #          undef  SHMLBA /* not static: determined at boot time */
2700 #          define SHMLBA getpagesize()
2701 #      endif
2702 #   endif
2703 #endif
2704 EOFIX
2705                       $xs =~ s!
2706 #include <sys/types\.h>
2707 .*
2708 (#ifdef newCONSTSUB|/\* Required)!$fixed$1!ms;
2709                       return $xs;
2710                   });
2711     }
2712 }
2713
2714 # Local variables:
2715 # cperl-indent-level: 4
2716 # indent-tabs-mode: nil
2717 # End:
2718 #
2719 # ex: set ts=8 sts=4 sw=4 et: