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