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